text
stringlengths
2
1.04M
meta
dict
import os import re import uuid from distutils.core import setup from setuptools import find_packages from pip.req import parse_requirements PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) # parse_requirements() returns generator of pip.req.InstallRequirement objects install_requirements = parse_requirements( os.path.join(PROJECT_ROOT, 'requirements.txt'), session=uuid.uuid1()) # e.g. ['django', 'google-api-python-client'] requirements = [str(ir.req) for ir in install_requirements] setup( name='dj-translate', version='1.0.4', packages=find_packages(exclude=['tests']), install_requires=requirements, include_package_data=True, package_data={ 'autotranslate': ['templates/autotranslate/*.html', 'templates/autotranslate/css/*.css', 'templates/autotranslate/js/*.js', 'static/admin/img/*.png' ], }, zip_safe=False, license='MIT License', description='A simple Django app to automatically translate the pot (`.po`) files generated by django\'s ' 'makemessages command using google translate.', long_description=README, url='https://github.com/dadasoz/dj-translate/', author='Dadaso Zanzane', author_email='dada.z888@gmail.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
{ "content_hash": "58c58b7a2e76ba7229f480669946785f", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 110, "avg_line_length": 34.868852459016395, "alnum_prop": 0.6356370474847203, "repo_name": "dadasoz/dj-translate", "id": "04a46fd02d3e412a3fdebd277f6df9098f1cce59", "size": "2127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1850" }, { "name": "HTML", "bytes": "15669" }, { "name": "JavaScript", "bytes": "4614" }, { "name": "Python", "bytes": "69514" } ], "symlink_target": "" }
[Traefik](http://traefik.io/) is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease. ## Introduction This chart bootstraps Traefik as a Kubernetes ingress controller with optional support for SSL and Let's Encrypt. __NOTE:__ Operators will typically wish to install this component into the `kube-system` namespace where that namespace's default service account will ensure adequate privileges to watch `Ingress` resources _cluster-wide_. ## Prerequisites - Kubernetes 1.4+ with Beta APIs enabled - Kubernetes 1.6+ if you want to enable RBAC - You are deploying the chart to a cluster with a cloud provider capable of provisioning an external load balancer (e.g. AWS or GKE) - You control DNS for the domain(s) you intend to route through Traefik - __Suggested:__ PV provisioner support in the underlying infrastructure ## A Quick Note on Versioning Up until version 1.2.1-b of this chart, the semantic version of the chart was kept in-sync with the semantic version of the (default) version of Traefik installed by the chart. A dash and a letter were appended to Traefik's semantic version to indicate incrementally improved versions of the chart itself. For example, chart version 1.2.1-a and 1.2.1-b _both_ provide Traefik 1.2.1, but 1.2.1-b is a chart that is incrementally improved in some way from its immediate predecessor-- 1.2.1-a. This convention, in practice, suffered from a few problems, not the least of which was that it defied what was permitted by [semver 2.0.0](http://semver.org/spec/v2.0.0.html). This, in turn, lead to some difficulty in Helm understanding the versions of this chart. Beginning with version 1.3.0 of this chart, the version references _only_ the revision of the chart itself. The `appVersion` field in `chart.yaml` now conveys information regarding the revision of Traefik that the chart provides. ## Installing the Chart To install the chart with the release name `my-release`: ```bash $ helm install stable/traefik --name my-release --namespace kube-system ``` After installing the chart, create DNS records for applicable domains to direct inbound traffic to the load balancer. You can use the commands below to find the load balancer's IP/hostname: __NOTE:__ It may take a few minutes for this to become available. You can watch the status by running: ```bash $ kubectl get svc my-release-traefik --namespace kube-system -w ``` Once `EXTERNAL-IP` is no longer `<pending>`: ```bash $ kubectl describe service my-release-traefik -n kube-system | grep Ingress | awk '{print $3}' ``` __NOTE:__ If ACME support is enabled, it is only _after_ this step is complete that Traefik will be able to successfully use the ACME protocol to obtain certificates from Let's Encrypt. ## Uninstalling the Chart To uninstall/delete the `my-release` deployment: ```bash $ helm delete my-release ``` The command removes all the Kubernetes components associated with the chart and deletes the release. ## Configuration The following tables lists the configurable parameters of the Traefik chart and their default values. | Parameter | Description | Default | | ------------------------------- | -------------------------------------------------------------------- | ----------------------------------------- | | `image` | Traefik image name | `traefik` | | `imageTag` | The version of the official Traefik image to use | `1.4.5` | | `serviceType` | A valid Kubernetes service type | `LoadBalancer` | | `loadBalancerIP` | An available static IP you have reserved on your cloud platform | None | | `loadBalancerSourceRanges` | list of IP CIDRs allowed access to load balancer (if supported) | None | | `replicas` | The number of replicas to run; __NOTE:__ Full Traefik clustering with leader election is not yet supported, which can affect any configured Let's Encrypt setup; see Clustering section | `1` | | `cpuRequest` | Initial share of CPU requested per Traefik pod | `100m` | | `memoryRequest` | Initial share of memory requested per Traefik pod | `20Mi` | | `cpuLimit` | CPU limit per Traefik pod | `200m` | | `memoryLimit` | Memory limit per Traefik pod | `30Mi` | | `rbac.enabled` | Whether to enable RBAC with a specific cluster role and binding for Traefik | `false` | | `nodeSelector` | Node labels for pod assignment | `{}` | | `tolerations` | List of node taints to tolerate | `[]` | | `debug.enabled` | Turn on/off Traefik's debug mode. Enabling it will override the logLevel to `DEBUG` and provide `/debug/vars` endpoint that allows Go runtime stats to be inspected, such as number of Goroutines and memory stats | `false` | | `ssl.enabled` | Whether to enable HTTPS | `false` | | `ssl.enforced` | Whether to redirect HTTP requests to HTTPS | `false` | | `ssl.defaultCert` | Base64 encoded default certficate | A self-signed certificate | | `ssl.defaultKey` | Base64 encoded private key for the certificate above | The private key for the certificate above | | `acme.enabled` | Whether to use Let's Encrypt to obtain certificates | `false` | | `acme.email` | Email address to be used in certificates obtained from Let's Encrypt | `admin@example.com` | | `acme.staging` | Whether to get certs from Let's Encrypt's staging environment | `true` | | `acme.logging` | display debug log messages from the acme client library | `false` | | `acme.persistence.enabled` | Create a volume to store ACME certs (if ACME is enabled) | `true` | | `acme.persistence.storageClass` | Type of `StorageClass` to request-- will be cluster-specific | `nil` (uses alpha storage class annotation) | | `acme.persistence.accessMode` | `ReadWriteOnce` or `ReadOnly` | `ReadWriteOnce` | | `acme.persistence.size` | Minimum size of the volume requested | `1Gi` | | `dashboard.enabled` | Whether to enable the Traefik dashboard | `false` | | `dashboard.domain` | Domain for the Traefik dashboard | `traefik.example.com` | | `dashboard.ingress.annotations` | Annotations for the Traefik dashboard Ingress definition, specified as a map | None | | `dashboard.ingress.labels` | Labels for the Traefik dashboard Ingress definition, specified as a map | None | | `dashboard.auth.basic` | Basic auth for the Traefik dashboard specified as a map, see Authentication section | unset by default; this means basic auth is disabled | | `dashboard.statistics.recentErrors` | Number of recent errors to show in the ‘Health’ tab | None | | `service.annotations` | Annotations for the Traefik Service definition, specified as a map | None | | `service.labels` | Additional labels for the Traefik Service definition, specified as a map | None | | `service.nodePorts.http` | Desired nodePort for service of type NodePort used for http requests | blank ('') - will assign a dynamic node port | | `service.nodePorts.https` | Desired nodePort for service of type NodePort used for https requests | blank ('') - will assign a dynamic node port | | `gzip.enabled` | Whether to use gzip compression | `true` | | `kubernetes.namespaces` | List of Kubernetes namespaces to watch | All namespaces | | `kubernetes.labelSelector` | Valid Kubernetes ingress label selector to watch (e.g `realm=public`)| No label filter | | `accessLogs.enabled` | Whether to enable Traefik's access logs | `false` | | `accessLogs.filePath` | The path to the log file. Logs to stdout if omitted | None | | `accessLogs.format` | What format the log entries should be in. Either `common` or `json` | `common` | | `metrics.prometheus.enabled` | Whether to enable the `/metrics` endpoint for metric collection by Prometheus. | `false` | | `metrics.prometheus.buckets` | A list of response times (in seconds) - for each list element, Traefik will report all response times less than the element. | `[0.1,0.3,1.2,5]` | | `metrics.datadog.enabled` | Whether to enable pushing metrics to Datadog. | `false` | | `metrics.datadog.address` | Datadog host in the format <hostname>:<port> | `localhost:8125` | | `metrics.datadog.pushInterval` | How often to push metrics to Datadog. | `10s` | | `metrics.statsd.enabled` | Whether to enable pushing metrics to Statsd. | `false` | | `metrics.statsd.address` | Statsd host in the format <hostname>:<port> | `localhost:8125` | | `metrics.statsd.pushInterval` | How often to push metrics to Statsd. | `10s` | | `deployment.hostPort.httpEnabled` | Whether to enable hostPort binding to host for http. | `false` | | `deployment.hostPort.httpsEnabled` | Whether to enable hostPort binding to host for https. | `false` | | `deployment.hostPort.dashboardEnabled` | Whether to enable hostPort binding to host for dashboard. | `false` | Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example: ```bash $ helm install --name my-release --namespace kube-system \ --set dashboard.enabled=true,dashboard.domain=traefik.example.com stable/traefik ``` The above command enables the Traefik dashboard on the domain `traefik.example.com`. Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example: ```bash $ helm install --name my-release --namespace kube-system --values values.yaml stable/traefik ``` ### Clustering / High Availability Currently it is possible to specify the number of `replicas` but the implementation is naive. **Full Traefik clustering with leader election is not yet supported.** It is heavily advised to not set a value for `replicas` if you also have Let's Encrypt configured. While setting `replicas` will work for many cases, since no leader is elected it has the consequence that each node will end up requesting Let's Encrypt certificates if this is also configured. This will quickly cut into the very modest rate limit that Let's Encrypt enforces. [Basic auth](https://docs.traefik.io/toml/#api-backend) can be specified via `dashboard.auth.basic` as a map of usernames to passwords as below. See the linked Traefik documentation for accepted passwords encodings. It is advised to single quote passwords to avoid issues with special characters: ```bash $ helm install --name my-release --namespace kube-system \ --set dashboard.enabled=true,dashboard.auth.basic.test='$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/' \ stable/traefik ``` Alternatively in YAML form: ```yaml dashboard: enabled: true domain: traefik.example.com auth: basic: test: $apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/ ```
{ "content_hash": "14848c9c763e6be420933d7b4b13f73d", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 375, "avg_line_length": 74.2896174863388, "alnum_prop": 0.5653549098933431, "repo_name": "ledor473/charts", "id": "cf949f3123cc68d6a2c1f0dbadb395ff3d9e6187", "size": "13610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stable/traefik/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "8523" }, { "name": "Makefile", "bytes": "1684" }, { "name": "Python", "bytes": "244" }, { "name": "Shell", "bytes": "49582" }, { "name": "Smarty", "bytes": "136379" } ], "symlink_target": "" }
#region Copyright (c) 2020 Filip Fodemski // // Copyright (c) 2020 Filip Fodemski // // 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 // #endregion using SmartGraph.Dag.Interfaces; using SmartGraph.Xml; using System; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace SmartGraph.RandomGraphGenerator.Formats { internal class EngineXmlFormatWriter : IGraphFormatWriter { static void WriteInputs(XmlWriter xmlWriter, IVertex vertex) { xmlWriter.WriteStartElement("e", "inputs", XmlEngineBuilder.EngineNamespace); int inputId = 0; foreach (var ie in vertex.InEdges) { xmlWriter.WriteStartElement("e", "input", XmlEngineBuilder.EngineNamespace); xmlWriter.WriteAttributeString("name", string.Format("input-{0}", ++inputId)); xmlWriter.WriteAttributeString("ref", string.Format("node-{0}", ie.Source.Name)); xmlWriter.WriteEndElement(); // input } xmlWriter.WriteEndElement(); // inputs } public void Write(IGraph graph, TextWriter writer) { var random = new Random(); var ens = XmlEngineBuilder.EngineNamespace; var nns = XmlEngineBuilder.NodesNamespace; var xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = new UTF8Encoding(false); xmlSettings.Indent = true; var memoryStream = new MemoryStream(); using (var xmlWriter = XmlWriter.Create(memoryStream, xmlSettings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("e", "engine", ens); xmlWriter.WriteAttributeString("name", "RandomTester"); xmlWriter.WriteAttributeString("xmlns", ""); xmlWriter.WriteAttributeString("xmlns", "e", null, ens); xmlWriter.WriteAttributeString("xmlns", "n", null, nns); var sortedVertices = graph.Vertices.ToList(); sortedVertices.Sort(new VertexNameComparer()); foreach (var v in sortedVertices) { xmlWriter.WriteStartElement("e", "node", ens); if (v.InEdges.Any() && v.OutEdges.Any()) // calculated node { xmlWriter.WriteAttributeString("name", string.Format("node-{0}", v.Name)); WriteInputs(xmlWriter, v); xmlWriter.WriteStartElement("e", "obj", ens); xmlWriter.WriteAttributeString( "type", "SmartGraph.Engine.Nodes.Core.SumOfInputs, SmartGraph.Engine.Nodes"); xmlWriter.WriteStartElement("n", "SumOfInputs", nns); xmlWriter.WriteEndElement(); // SumOfInputs xmlWriter.WriteEndElement(); // obj } else if (v.OutEdges.None()) // publisher { xmlWriter.WriteAttributeString("name", string.Format("node-{0}-publisher", v.Name)); WriteInputs(xmlWriter, v); xmlWriter.WriteStartElement("e", "obj", ens); xmlWriter.WriteAttributeString( "type", "SmartGraph.Engine.Nodes.Core.SleepJob, SmartGraph.Engine.Nodes"); xmlWriter.WriteStartElement("n", "SleepJob", nns); xmlWriter.WriteEndElement(); // SleepJob xmlWriter.WriteEndElement(); // obj } else if (v.InEdges.None()) // active node { xmlWriter.WriteAttributeString("name", string.Format("node-{0}", v.Name)); xmlWriter.WriteStartElement("e", "obj", ens); xmlWriter.WriteAttributeString( "type", "SmartGraph.Engine.Nodes.Core.Ticker, SmartGraph.Engine.Nodes"); xmlWriter.WriteStartElement("n", "Ticker", nns); xmlWriter.WriteAttributeString("random", "true"); xmlWriter.WriteAttributeString("minValue", "100"); xmlWriter.WriteAttributeString("maxValue", "1000"); xmlWriter.WriteEndElement(); // Ticker xmlWriter.WriteEndElement(); // obj } else { throw new InvalidOperationException( string.Format("Vertex '{0}' is of unknown type.", v.Name)); } xmlWriter.WriteEndElement(); // node } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); } writer.Write(Encoding.UTF8.GetString(memoryStream.ToArray())); writer.Flush(); } } }
{ "content_hash": "5507bda7a4f3bcb8bc5e2a3713410582", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 138, "avg_line_length": 44.23021582733813, "alnum_prop": 0.5653871177618738, "repo_name": "filipek/SmartGraph", "id": "00634773230dbfe01a4382def259a8f2df06ff3f", "size": "6150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SmartGraph.RandomGraphGenerator/Formats/EngineXmlFormatWriter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "175056" }, { "name": "HTML", "bytes": "6386" } ], "symlink_target": "" }
/* *@file:GeoFilter.h *@brief: implement nearby searching filter *@author:wangbaobao@b5m.com *@date:2014-07-09. */ #ifndef GEO_FILTER_H_ #define GEO_FILTER_H_ #include "RTypeStringPropTableBuilder.h" #include "GeoHashEncoder.h" #include <common/RTypeStringPropTable.h> #include <stdint.h> #include <vector> #include <assert.h> namespace sf1r { class GeoFilter { public: typedef uint32_t doc_id_t; typedef std::vector<doc_id_t> DocIdVector; typedef std::pair<double, double> CoordinatePair; public: GeoFilter(double scope, const CoordinatePair& coordinate, RTypeStringPropTableBuilder *rtype_builder) :scope_(scope), rtype_builder_(rtype_builder), coordinate_(coordinate) { } ~GeoFilter() { } void Filter(DocIdVector &doc_ids) { GeoHashEncoder encoder; GeoHashNeighbors neighbor_grids = encoder.GetNeighborsGridsByScope(coordinate_.first, coordinate_.second, scope_); //get rtype property "GeoHash" instance assert(rtype_builder_); boost::shared_ptr<RTypeStringPropTable> &rtype_table = rtype_builder_->createPropertyTable("GeoHash"); DocIdVector::iterator doc_id_iter = doc_ids.begin(); for(; doc_id_iter != doc_ids.end(); ++doc_id_iter) { bool is_matched = false; std::string rtype_value; rtype_table->getRTypeString((unsigned int)(*doc_id_iter), rtype_value); if(rtype_value.empty()) { //need remove ??? continue; } for(size_t i = 0; i < 9; i++) { if(neighbor_grids.grids[i].empty()) continue; //match neighbor grids //rtype_value stores 12bytes geohash string //so we check whether rtype_value start with grids[j] size_t pos = rtype_value.find(neighbor_grids.grids[i]); if(pos == 0) { is_matched = true; break; } } if(is_matched == false){ doc_ids.erase(doc_id_iter); } } } private: double scope_; RTypeStringPropTableBuilder *rtype_builder_; const CoordinatePair &coordinate_; }; } #endif
{ "content_hash": "d928f9b46fd36f0ff104ee316756458b", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 88, "avg_line_length": 23.155555555555555, "alnum_prop": 0.6401151631477927, "repo_name": "izenecloud/sf1r-lite", "id": "7fbe7961d42fc16e33dcbf40e0331ffcd09af1d2", "size": "2084", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/core/search-manager/GeoFilter.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1785" }, { "name": "C", "bytes": "246141" }, { "name": "C++", "bytes": "3916418" }, { "name": "Makefile", "bytes": "260" }, { "name": "Python", "bytes": "25450" }, { "name": "Ruby", "bytes": "5785" }, { "name": "Shell", "bytes": "6684" } ], "symlink_target": "" }
Famous old school game (https://en.wikipedia.org/wiki/Gruntz). ![Gruntz in Docker container](https://raw.githubusercontent.com/whaleapps/gruntz/master/docs/gruntz.png) ## Usage ``` docker run \ --rm \ -it \ -v /tmp/.X11-unix:/tmp/.X11-unix:ro \ -e DISPLAY=$DISPLAY \ --device /dev/snd \ -v /dev/shm:/dev/shm \ whaleapps/gruntz ``` Don't forget to allow xhost. ``` xhost +x ``` ## Troubleshooting Gruntz works only at resolution 640x480.
{ "content_hash": "f9a68bb1ddca158fb335fb6ff26ebf36", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 104, "avg_line_length": 18.846153846153847, "alnum_prop": 0.6244897959183674, "repo_name": "whaleapps/gruntz", "id": "10e9dca414ada3a3705773f8ae3c193aea87fb1a", "size": "500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "67" } ], "symlink_target": "" }
package net.mingsoft; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(scanBasePackages={"net.mingsoft"}) public class MSServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MSApplication.class); } }
{ "content_hash": "ed5eaf59883fe9901cb1127718ee8747", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 81, "avg_line_length": 32.5, "alnum_prop": 0.8557692307692307, "repo_name": "ming-soft/MCMS", "id": "13e6d1f2b3e5bde15fb3f2bdf63082350d3904a3", "size": "1671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/mingsoft/MSServletInitializer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "351" }, { "name": "CSS", "bytes": "428513" }, { "name": "FreeMarker", "bytes": "177771" }, { "name": "HTML", "bytes": "1112712" }, { "name": "Java", "bytes": "162567" }, { "name": "JavaScript", "bytes": "8684053" }, { "name": "Less", "bytes": "22670" }, { "name": "Shell", "bytes": "321" } ], "symlink_target": "" }
<section id="editor-bookmarks"> <title>Working with bookmarks</title> <section id="define-bookmark"> <title>Defining bookmarks</title> <para> A bookmark inside the editor is defined by adding the keyword <literal>@WbTag</literal> followed by the name of the bookmark into a SQL comment: </para> <programlisting>-- @WbTag delete everything truncate table orders,order_line,customers; commit; </programlisting> <para> The keyword is not case sensitive, <literal>@wbtag</literal> will work just as wel as <literal>@WBTAG</literal>, or <literal>@WbTag</literal>. A multiline comment can be used as well as a single line comment. </para> <para> The annotations for <link linkend="result-names">naming a result</link> can additionally be included in the bookmark list. This is enabled in the <link linkend="option-result-name">options panel for the editor</link>. </para> <para> The names of procedures and functions can also be used as bookmarks if enabled in the <link linkend="">bookmark options</link> </para> </section> <section id="jump-bookmark"> <title>Jumping to a bookmark</title> <para> To jump to a bookmark select <menuchoice><guimenu>Tools</guimenu><guimenuitem>Bookmarks</guimenuitem></menuchoice>. A dialog box with all defined bookmarks will be displayed. You can filter the list of displayed bookmarks by entering a value in the input field. Depending on the option <guimenu>Filter on name only</guimenu> the value will either be compared only against the bookmark name. If that option is disabled then the bookmark name and the name of the SQL tab will be checked for the entered value. </para> <note><para> The selection in the bookmark list can be moved with the <keycap>UP/DOWN</keycap> keys even when the cursor is located in the filter input field. </para></note> <para> If the option <guimenu>Only for current tab</guimenu> is enabled, then the dialog will open showing only bookmarks for the current tab. </para> </section> <section id="bookmark-config"> <title>Configuring the display of the bookmark list</title> <para> There are two options to influence how the list of bookmarks is displayed. Both options are available when displaying the context menu for the list header (usually through a click with the right mouse button): <itemizedlist> <listitem> <simpara> Remember column widths - if this is enabled, the columns are not automatically adjusted to the width of the content. Instead the list remembers whatever width was adjusted. </simpara> </listitem> <listitem> <simpara> Remember sort order - by default the list is sorted by the name of the bookmark. When this option is selected, whatever sort order is selected (by clicking on the column headers) will be saved and restored the next time the dialog is opened. </simpara> </listitem> </itemizedlist> </para> </section> </section>
{ "content_hash": "b2341868e0d5babb41eac0275eeac51f", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 132, "avg_line_length": 44.74647887323944, "alnum_prop": 0.6858671702864337, "repo_name": "Taller/sqlworkbench-plus", "id": "ad4da57a06ad03bec5e9e91eff837eace5db4bf3", "size": "3177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/xml/bookmarks.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4060" }, { "name": "CSS", "bytes": "4714" }, { "name": "HTML", "bytes": "103882" }, { "name": "Java", "bytes": "12464050" }, { "name": "Lex", "bytes": "53858" }, { "name": "Shell", "bytes": "2206" }, { "name": "Visual Basic", "bytes": "1211" }, { "name": "XSLT", "bytes": "231405" } ], "symlink_target": "" }
Recurrent Neural Network Examples =========== For more current implementations of NLP and RNN models with MXNet, please visit [gluon-nlp](http://gluon-nlp.mxnet.io/index.html) ------ This directory contains functions for creating recurrent neural networks models using high level mxnet.rnn interface. Here is a short overview of what is in this directory. Directory | What's in it? --- | --- `word_lm/` | Language model trained on the Sherlock Holmes dataset achieving state of the art performance `bucketing/` | Language model with bucketing API with python `bucket_R/` | Language model with bucketing API with R `old/` | Language model trained with low level symbol interface (deprecated)
{ "content_hash": "3571a64430c3b21d9d3027c4a6e4381d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 129, "avg_line_length": 36.68421052631579, "alnum_prop": 0.757532281205165, "repo_name": "ptrendx/mxnet", "id": "1d1df6ed768794d4fe477a01cbcc48d0ad4c4961", "size": "697", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "example/rnn/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "174781" }, { "name": "C++", "bytes": "6495727" }, { "name": "CMake", "bytes": "90332" }, { "name": "Clojure", "bytes": "503982" }, { "name": "Cuda", "bytes": "838222" }, { "name": "Dockerfile", "bytes": "61391" }, { "name": "Groovy", "bytes": "97961" }, { "name": "HTML", "bytes": "40277" }, { "name": "Java", "bytes": "181373" }, { "name": "Julia", "bytes": "427299" }, { "name": "Jupyter Notebook", "bytes": "3613882" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "178070" }, { "name": "Perl", "bytes": "1535873" }, { "name": "Perl 6", "bytes": "7280" }, { "name": "PowerShell", "bytes": "11478" }, { "name": "Python", "bytes": "6375321" }, { "name": "R", "bytes": "357740" }, { "name": "Scala", "bytes": "1256104" }, { "name": "Shell", "bytes": "397784" }, { "name": "Smalltalk", "bytes": "3497" } ], "symlink_target": "" }
<?php namespace WPChecksum; class ThemeCheckerTest extends \PHPUnit_Framework_TestCase { public function __construct() { setHttpMode('real'); } public function testLocal() { require_once __DIR__ . '/../TestsProvider.php'; $app = Checksum::getApplication(new \TestsProvider(array())); $checker = new ThemeChecker(null, true); $theme = new \MockTheme(array( 'Name' => 'TwentyTwelve', 'Version' => '2.2', 'stylesheet' => 'twentytwelve', 'theme_root' => __DIR__ . '/fixtures/themes', 'template' => 'twentytwelve', )); $out = $checker->check('twentytwelve', $theme); $this->assertTrue(isset($out['type'])); $this->assertTrue(isset($out['slug'])); $this->assertTrue(isset($out['name'])); $this->assertTrue(isset($out['version'])); $this->assertTrue(isset($out['status'])); $this->assertTrue(isset($out['changeset'])); $this->assertEquals($out['type'], 'theme'); $this->assertEquals($out['slug'], 'twentytwelve'); $this->assertEquals($out['name'], 'TwentyTwelve'); $this->assertEquals($out['version'], '2.2'); $this->assertEquals(count($out['changeset']), 2); $this->assertTrue(isset($out['changeset']['readme.txt'])); $this->assertEquals($out['changeset']['readme.txt']->isDir, 0); $this->assertEquals($out['changeset']['readme.txt']->isSoft, true); $this->assertTrue(isset($out['changeset']['archive.php'])); $this->assertEquals($out['changeset']['archive.php']->isDir, 0); $this->assertEquals($out['changeset']['archive.php']->isSoft, false); $theme = new \MockTheme(array( 'Name' => 'Premium', 'Version' => '2.2', 'stylesheet' => 'premium', 'theme_root' => __DIR__ . '/fixtures/themes', 'template' => 'premium', )); $out = $checker->check('premium', $theme); } }
{ "content_hash": "ce1946d6e4a7d3dc4ce2e31e23eac936", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 77, "avg_line_length": 34.98275862068966, "alnum_prop": 0.5446032528339083, "repo_name": "eriktorsner/wp-checksum", "id": "d464a933aa27c8ab5437af217eb749ada6d3d720", "size": "2029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/ThemeCheckerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "92896" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- POM file. --> <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.apache.ignite</groupId> <artifactId>ignite-cassandra</artifactId> <version>2.9.0-SNAPSHOT</version> <relativePath>..</relativePath> </parent> <artifactId>ignite-cassandra-store</artifactId> <version>2.9.0-SNAPSHOT</version> <url>http://ignite.apache.org</url> <properties> <commons-beanutils.version>1.9.2</commons-beanutils.version> <cassandra-driver.version>3.2.0</cassandra-driver.version> <cassandra-all.version>3.11.3</cassandra-all.version> <netty.version>4.1.27.Final</netty.version> <metrics-core.version>3.0.2</metrics-core.version> </properties> <dependencies> <!-- Apache commons --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> </dependency> <!-- Ignite --> <dependency> <groupId>org.apache.ignite</groupId> <artifactId>ignite-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.ignite</groupId> <artifactId>ignite-spring</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.ignite</groupId> <artifactId>ignite-log4j</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <!-- Cassandra and required dependencies --> <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>${cassandra-driver.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-handler</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-buffer</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-common</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-transport</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-codec</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-resolver</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <dependency> <groupId>com.codahale.metrics</groupId> <artifactId>metrics-core</artifactId> <version>${metrics-core.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.apache.cassandra</groupId> <artifactId>cassandra-all</artifactId> <version>${cassandra-all.version}</version> <scope>test</scope> <exclusions> <exclusion> <artifactId>log4j-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion> </exclusions> </dependency> <!-- Apache log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <encoding>UTF-8</encoding> <fork>true</fork> <debug>false</debug> <debuglevel>lines,vars,source</debuglevel> <meminitial>256</meminitial> <maxmem>512</maxmem> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.10</version> <executions> <execution> <id>copy-all-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/tests-package/lib</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> <excludeArtifactIds> netty-all,cassandra-all,snappy-java,lz4,compress-lzf,commons-codec,commons-lang3,commons-math3, concurrentlinkedhashmap-lru,antlr,ST4,antlr-runtime,jcl-over-slf4j,jackson-core-asl, jackson-mapper-asl,json-simple,high-scale-lib,snakeyaml,jbcrypt,reporter-config3, reporter-config-base,hibernate-validator,validation-api,jboss-logging,thrift-server, disruptor,stream,fastutil,logback-core,logback-classic,libthrift,httpclient,httpcore, cassandra-thrift,jna,jamm,joda-time,sigar,ecj,tools </excludeArtifactIds> </configuration> </execution> <!-- --> <execution> <id>copy-main-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/libs</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> <excludeTransitive>true</excludeTransitive> <excludeGroupIds> org.apache.ignite,org.springframework,org.gridgain </excludeGroupIds> <excludeArtifactIds> commons-logging,slf4j-api,cache-api,slf4j-api,aopalliance </excludeArtifactIds> <includeScope>runtime</includeScope> </configuration> </execution> <!-- --> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <dependencies> <dependency> <groupId>ant-contrib</groupId> <artifactId>ant-contrib</artifactId> <version>1.0b3</version> <exclusions> <exclusion> <groupId>ant</groupId> <artifactId>ant</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <executions> <execution> <id>package-tests</id> <phase>package</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <taskdef resource="net/sf/antcontrib/antlib.xml" /> <if> <available file="${project.build.directory}/test-classes" type="dir" /> <then> <copy todir="${project.build.directory}/tests-package/lib"> <fileset dir="${project.build.directory}"> <include name="*.jar" /> </fileset> </copy> <jar destfile="${project.build.directory}/tests-package/lib/${project.artifactId}-${project.version}-tests.jar"> <fileset dir="${project.build.directory}/test-classes"> <include name="**/*.class" /> </fileset> </jar> <copy todir="${project.build.directory}/tests-package/settings"> <fileset dir="${project.build.directory}/test-classes"> <include name="**/*.properties" /> <include name="**/*.xml" /> </fileset> </copy> <copy todir="${project.build.directory}/tests-package"> <fileset dir="${project.build.testSourceDirectory}/../scripts"> <include name="**/*" /> </fileset> </copy> <fixcrlf srcdir="${project.build.directory}/tests-package" eol="lf" eof="remove"> <include name="*.sh" /> </fixcrlf> <copy todir="${project.build.directory}/tests-package"> <fileset dir="${project.build.testSourceDirectory}/.."> <include name="bootstrap/**" /> </fileset> </copy> <fixcrlf srcdir="${project.build.directory}/tests-package/bootstrap" eol="lf" eof="remove"> <include name="**" /> </fixcrlf> <zip destfile="${project.build.directory}/ignite-cassandra-tests-${project.version}.zip" compress="true" whenempty="create" level="9" encoding="UTF-8" useLanguageEncodingFlag="true" createUnicodeExtraFields="not-encodeable"> <zipfileset dir="${project.build.directory}/tests-package" prefix="ignite-cassandra-tests"> <exclude name="**/*.sh" /> </zipfileset> <zipfileset dir="${project.build.directory}/tests-package" prefix="ignite-cassandra-tests" filemode="555"> <include name="**/*.sh" /> </zipfileset> </zip> </then> </if> </target> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "dcfdf898b8525bb5c191ed018714ec86", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 264, "avg_line_length": 44.00310559006211, "alnum_prop": 0.47095772461006424, "repo_name": "andrey-kuznetsov/ignite", "id": "2696e4354ef433aa66f0feae09d7322d5a24be76", "size": "14169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/cassandra/store/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "61105" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "6413910" }, { "name": "C++", "bytes": "3684419" }, { "name": "CSS", "bytes": "281251" }, { "name": "Dockerfile", "bytes": "16105" }, { "name": "Groovy", "bytes": "15081" }, { "name": "HTML", "bytes": "821135" }, { "name": "Java", "bytes": "42474774" }, { "name": "JavaScript", "bytes": "1785625" }, { "name": "M4", "bytes": "21724" }, { "name": "Makefile", "bytes": "121296" }, { "name": "PHP", "bytes": "486991" }, { "name": "PLpgSQL", "bytes": "623" }, { "name": "PowerShell", "bytes": "11987" }, { "name": "Python", "bytes": "342274" }, { "name": "Scala", "bytes": "1386030" }, { "name": "Shell", "bytes": "615962" }, { "name": "TSQL", "bytes": "6130" }, { "name": "TypeScript", "bytes": "476855" } ], "symlink_target": "" }
package net.automatalib.commons.smartcollections; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.Test; @Test public class BinaryHeapTest { private final BinaryHeap<Integer> heap = BinaryHeap.create(Arrays.asList(42, 37)); @Test public void testHeapOps() { Assert.assertEquals(heap.size(), 2); Assert.assertFalse(heap.isEmpty()); Assert.assertFalse(heap.contains(13)); Assert.assertEquals(heap.peekMin().intValue(), 37); Assert.assertTrue(heap.add(13)); Assert.assertEquals(heap.size(), 3); Assert.assertEquals(heap.peekMin().intValue(), 13); Assert.assertEquals(heap.extractMin().intValue(), 13); Assert.assertEquals(heap.size(), 2); Assert.assertEquals(heap.peekMin().intValue(), 37); heap.add(40); Assert.assertEquals(heap.size(), 3); Assert.assertEquals(heap.peekMin().intValue(), 37); Assert.assertEquals(heap.extractMin().intValue(), 37); Assert.assertEquals(heap.size(), 2); Assert.assertEquals(heap.peekMin().intValue(), 40); Assert.assertEquals(heap.extractMin().intValue(), 40); Assert.assertEquals(heap.size(), 1); Assert.assertEquals(heap.peekMin().intValue(), 42); Assert.assertEquals(heap.extractMin().intValue(), 42); Assert.assertEquals(heap.size(), 0); Assert.assertTrue(heap.isEmpty()); } }
{ "content_hash": "1f74435a59d33d211918939c62249c46", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 83, "avg_line_length": 27.5625, "alnum_prop": 0.7142857142857143, "repo_name": "bencaldwell/automatalib", "id": "6be1e8cc3a03f98a2c945f2d27ef6a9613821b76", "size": "1987", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "commons/smartcollections/src/test/java/net/automatalib/commons/smartcollections/BinaryHeapTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1443830" }, { "name": "Shell", "bytes": "6794" } ], "symlink_target": "" }
require "rubygems" require "json" rightscale_marker :begin node[:web_app] = JSON.parse(node[:web_app_config]) RightScale::Repo::GitSshKey.new.create(node[:repo][:default][:credential], node[:repo][:default][:credential] ) execute "composer_install" do cwd "/home/webapps/#{node[:web_app][:application]}#{node[:web_app][:symfony_dir]}" command "pwd" command "php composer.phar update #{node[:composer][:arguments]}" only_if { ::File.exists?("/home/webapps/#{node[:web_app][:application]}#{node[:web_app][:symfony_dir]}composer.phar") } action :run end rightscale_marker :end
{ "content_hash": "e963c63d779746ebc49b4fc86350da18", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 121, "avg_line_length": 32.72222222222222, "alnum_prop": 0.7011884550084889, "repo_name": "SchoolSpring/cookbooks_internal", "id": "7b1c6c395331a5050acf38a80484b80019067e06", "size": "589", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cookbooks/symfony/recipes/update_vendors.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "20437" }, { "name": "Perl", "bytes": "6503" }, { "name": "Python", "bytes": "750" }, { "name": "Ruby", "bytes": "102848" }, { "name": "Shell", "bytes": "6511" } ], "symlink_target": "" }
package com.sun.mirror.declaration; /** * Represents an element of an annotation type. * * @deprecated All components of this API have been superseded by the * standardized annotation processing API. The replacement for the * functionality of this interface is included in {@link * javax.lang.model.element.ExecutableElement}. * * @author Joe Darcy * @author Scott Seligman * @since 1.5 */ @Deprecated @SuppressWarnings("deprecation") public interface AnnotationTypeElementDeclaration extends MethodDeclaration { /** * Returns the default value of this element. * * @return the default value of this element, or null if this element * has no default. */ AnnotationValue getDefaultValue(); /** * {@inheritDoc} */ AnnotationTypeDeclaration getDeclaringType(); }
{ "content_hash": "ea9968b49bbab2e983eeaedc4b21db50", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 77, "avg_line_length": 24.38235294117647, "alnum_prop": 0.7092882991556092, "repo_name": "haikuowuya/android_system_code", "id": "a101dc673dc9f6c9502d97afdf2a0a1770027acb", "size": "1038", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/sun/mirror/declaration/AnnotationTypeElementDeclaration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "182432" }, { "name": "Java", "bytes": "124952631" } ], "symlink_target": "" }
// // CMTextFieldView.m // I_NScreen // // Created by 조백근 on 2015. 10. 12.. // Copyright © 2015년 STVN. All rights reserved. // #import "CMTextFieldView.h" #import "CMCustomNumberPadView.h" static int tag_button_delete = 21001;//삭제버튼 태그 static int tag_button_done = 849404; @interface CMTextFieldView () <UITextFieldDelegate> @property (nonatomic, strong) UIImageView* backgroundImageView; @property (nonatomic, strong) UIButton* doneButton; @end @implementation CMTextFieldView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { //1. data self.placeHolder = @""; //2. subviews self.backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds]; [self addSubview:self.backgroundImageView]; self.inputField = [[UITextField alloc] initWithFrame:self.bounds]; self.inputField.delegate = self; self.inputField.font = [UIFont systemFontOfSize:15]; self.inputField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; [self addSubview:self.inputField]; self.fieldLeftView = [[UIView alloc] initWithFrame:CGRectZero]; self.fieldRightView = [[UIView alloc] initWithFrame:CGRectZero]; self.inputField.leftView = self.fieldLeftView; self.inputField.rightView = self.fieldRightView; //3. default setting self.fieldState = CMTextFieldControlStateNormal; self.fieldType = CMTextFieldTypeDefault; self.fieldKeypad = CMTextFieldKeypadDefault; self.limitType = CMTextFieldLimitTypeNone; self.isCheckMaxInput = NO; _maxInput = 0; self.inputDelegate = nil; //4. 초성검색을 위한 이벤트 등록 [self.inputField addTarget:self action:@selector(textMessageChanged:) forControlEvents:UIControlEventEditingChanged]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; } return self; } - (void)setFrame:(CGRect)frame{ if (CGRectEqualToRect(self.frame, frame)) { return; } [super setFrame:frame]; [self clearSubLayers]; self.backgroundImageView.frame = self.bounds; self.inputField.frame = self.bounds; self.fieldState = CMTextFieldControlStateNormal; } - (void)clearSubLayers { CALayer* layer = self.layer; NSArray* subLayers = layer.sublayers; for (NSInteger i = subLayers.count - 1; i >= 0 ; i--) { CALayer* subLayer = subLayers[i]; if ([subLayer.name isEqualToString:@"outerLine"]) { [subLayer removeFromSuperlayer]; } } } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } - (void)setMaxInput:(NSInteger)maxInput { _maxInput = maxInput; if (_maxInput > 0) { self.isCheckMaxInput = YES; } } - (UIImage*)createBackgrroundImageWithFieldState:(CMTextFieldControlState)fieldState { NSString* imageName; switch ((NSInteger)_fieldState) { case CMTextFieldControlStateNormal: { imageName = @"pwbox.png"; } break; case CMTextFieldControlStateActive: { imageName = @"pwbox.png"; } break; case CMTextFieldControlStateDisable: { imageName = @"pwbox.png"; } break; case CMTextFieldControlStateError: { imageName = @"pwbox_error.png"; } break; } UIImage* image = [[UIImage imageNamed:@"pwbox.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 50, 10, 50)]; return image; } - (void)setFieldState:(CMTextFieldControlState)fieldState { _fieldState = fieldState; [self clearSubLayers]; self.inputField.enabled = YES; switch ((NSInteger)_fieldState) { case CMTextFieldControlStateNormal : {//정상 if (self.deleteButton != nil) { self.deleteButton.hidden = YES; } break; } case CMTextFieldControlStateActive : {//활성화(포커스) break; } case CMTextFieldControlStateDisable : {//비활성화(입력받지 않음) self.inputField.enabled = NO; break; } case CMTextFieldControlStateError : {//입력값 에러 break; } } [self.backgroundImageView setImage:[self createBackgrroundImageWithFieldState:fieldState]]; } - (void)setFieldType:(CMTextFieldType)fieldType { _fieldType = fieldType; switch ((NSInteger)_fieldState) { case CMTextFieldTypeDefault : {//기본필드 break; } case CMTextFieldTypePassword : {//암호필드 self.inputField.secureTextEntry = YES; break; } case CMTextFieldTypeButton : {//버튼 break; } }//end switch } - (void)setFieldKeypad:(CMTextFieldKeypad)fieldKeypad { _fieldKeypad = fieldKeypad; switch ((NSInteger)_fieldKeypad) { case CMTextFieldKeypadDefault : { self.inputField.keyboardType = UIKeyboardTypeDefault; self.inputField.returnKeyType = UIReturnKeyDone; break; } case CMTextFieldKeypadNum : { self.inputField.keyboardType = UIKeyboardTypeNumberPad; self.inputField.returnKeyType = UIReturnKeyDone; break; } }//end switch } #pragma mark - UI - (void)layoutSubviews { [super layoutSubviews]; self.inputField.frame = self.bounds; self.fieldState = _fieldState; } #pragma mark - inputField setting - (void)settingLeftMargin:(CGFloat)margin { CGRect frame = CGRectMake(0, 0, margin, self.bounds.size.height); self.inputField.leftView.frame = frame; [self.inputField setLeftViewMode:UITextFieldViewModeAlways]; } - (void)settingTextAlignment:(NSTextAlignment)textAlignment { self.inputField.textAlignment = textAlignment; if (textAlignment == NSTextAlignmentCenter) { self.inputField.leftView.frame = CGRectZero; self.inputField.rightView.frame = CGRectZero; } } - (void)settingInputFieldHolder:(NSString*)holder { // self.inputField.placeholder = holder; UIFont *font = [UIFont systemFontOfSize:13]; CGSize inputSize = [holder sizeWithAttributes: @{NSFontAttributeName: self.inputField.font}]; CGSize holderSize = [holder sizeWithAttributes: @{NSFontAttributeName: font}]; CGFloat multiple = (inputSize.height/holderSize.height) - 0.15;//수직정렬 NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; [style setAlignment:NSTextAlignmentLeft]; [style setLineBreakMode:NSLineBreakByWordWrapping]; [style setLineHeightMultiple:multiple]; NSDictionary *attribute = @{ NSFontAttributeName:font, NSForegroundColorAttributeName:[CMColor colorPlaceHolderColor], NSParagraphStyleAttributeName:style }; // Added line NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] initWithString:holder attributes:attribute]; self.inputField.attributedPlaceholder = attributeText; } #pragma mark - Private - (void)clearTextField { self.inputField.text = @"";//텍스트 필드 초기화 [self textMessageChanged:self.inputField];//텍스트 필드 변경사항 전파 if (_fieldState != CMTextFieldControlStateNormal) { self.fieldState = CMTextFieldControlStateNormal;//상태값 변경 } else { self.deleteButton.hidden = YES;//삭제버튼 숨김 } } - (void)addDoneButton { if (self.inputField.keyboardType == UIKeyboardTypeNumberPad) { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) { NSArray *listViews = [[NSBundle mainBundle] loadNibNamed:@"CMCustomNumberPadView" owner:nil options:nil]; CMCustomNumberPadView *textFieldView = listViews[0]; self.inputField.inputView = textFieldView; textFieldView.textField = self.inputField; textFieldView.doneBlock = ^void(UITextField* textField) { [self textFieldShouldReturn:textField]; }; } else { UIWindow* tempWindow; UIView* keyboard; if([[UIApplication sharedApplication] windows].count > 1){ tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; }else{ return; } for(int i=0; i<[tempWindow.subviews count]; i++) { keyboard = [tempWindow.subviews objectAtIndex:i]; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES) { self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; self.doneButton.tag = tag_button_done; self.doneButton.frame = CGRectMake(0, 163, 106, 53); self.doneButton.adjustsImageWhenHighlighted = NO; [self.doneButton setTitle:@"DONE" forState:UIControlStateNormal]; [self.doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.doneButton addTarget:self action:@selector(buttonWasTouchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside]; [keyboard addSubview:self.doneButton]; } else if([[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES){ self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; self.doneButton.tag = tag_button_done; self.doneButton.frame = CGRectMake(0,[[ UIScreen mainScreen] bounds ].size.height-53, 106, 53); self.doneButton.adjustsImageWhenHighlighted = NO; [self.doneButton setTitle:@"DONE" forState:UIControlStateNormal]; [self.doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.doneButton addTarget:self action:@selector(buttonWasTouchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside]; [keyboard addSubview:self.doneButton]; } } else { if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) { self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; self.doneButton.tag = tag_button_done; self.doneButton.frame = CGRectMake(0, 163, 106, 53); self.doneButton.adjustsImageWhenHighlighted = NO; [self.doneButton setTitle:@"DONE" forState:UIControlStateNormal]; [self.doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.doneButton addTarget:self action:@selector(buttonWasTouchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside]; [keyboard addSubview:self.doneButton]; } } } } } } #pragma mark - EVENT - (void)buttonWasTouchUpInside:(id)sender withEvent:(UIEvent*)event { if (![sender isKindOfClass:[UIView class]]) { return; } //switch 문에서 에러가 발생해서 if로 바꿈.. NSInteger tag = [(UIButton*)sender tag]; if (tag == tag_button_delete) { [self clearTextField]; } else if (tag == tag_button_done) { [self textFieldShouldReturn:self.inputField]; } } #pragma mark - DELEGATE #pragma mark - UITextField Event - (void)textMessageChanged:(UITextField* )textField { /** * ios8 이하 버전에서 한글 입력시 초성 자음 입력 후 모음을 입력할 때 * 초성 자음과 모음을 조합하는 과정에서 조합시 ""으로 변경되면서 * 이벤트가 동작하는 문제가 발생하여 이 경우 대처하기 위한 조건 추가함. * * _fieldState == HMInputFieldControlStateActivate 는 해당 이벤트가 동작하기 전 * shouldChangeCharactersInRange: 딜리게이트 메소드를 타는데 이때는 입력된 정보가 정확히 있기 때문에 * 이때 입력값에 따라 _fieldState를 재설정 하는 로직을 기술하였고, 이를 신뢰하여서 해당 정보로 한번더 체크해서 이슈 처리 */ float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if(version < 8.0){ if (_fieldState == CMTextFieldControlStateActive && textField.text.length == 0 ) { return; } } if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textMessageChanged:)]) { return [self.inputDelegate textMessageChanged:textField]; } } - (void)resignFirstResponder { if (_fieldState != CMTextFieldControlStateNormal) { self.fieldState = CMTextFieldControlStateNormal; } [self.inputField resignFirstResponder]; } #pragma mark - UITextFieldDelegate - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { //버튼 유형이면 패스 if (self.fieldType == CMTextFieldTypeButton) { if (self.inputTouchBlock != nil) { self.inputTouchBlock(); } return NO; } //버튼 유형이 아니고, 상태가 액티브가 아니면 액티브로 변경 if (_fieldState != CMTextFieldControlStateActive) { self.fieldState = CMTextFieldControlStateActive; } //입력된 값이 있고 딜리트 버튼을 세팅하면 딜리트 버튼 표시 NSString* input = [textField.text trim]; if (input.length > 0 && self.deleteButton != nil) { self.deleteButton.hidden = NO; } if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) { return [self.inputDelegate textFieldShouldBeginEditing:textField]; } return YES; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) { return [self.inputDelegate textFieldShouldEndEditing:textField]; } return YES; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { //버튼 유형이 아니고, 상태가 디폴트가 아니면 디폴트로 if (_fieldState != CMTextFieldControlStateNormal) { self.fieldState = CMTextFieldControlStateNormal; } if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldShouldReturn:)]) { return [self.inputDelegate textFieldShouldReturn:textField]; } return [textField resignFirstResponder]; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *inputText = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (inputText.length == 0) { self.deleteButton.hidden = YES; if (_fieldState != CMTextFieldControlStateNormal) { self.fieldState = CMTextFieldControlStateNormal; } } else { self.deleteButton.hidden = NO; if (_fieldState != CMTextFieldControlStateActive) { self.fieldState = CMTextFieldControlStateActive; } } if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) { return [self.inputDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string]; } //제한조건 1. 길이체크 if (self.isCheckMaxInput && range.location >= self.maxInput) { return NO; } //제한조건 2. 입력값 유효성 체크 if (self.limitType != CMTextFieldLimitTypeNone) { inputText = [inputText trim]; switch ((NSInteger)self.limitType) { case CMTextFieldLimitTypeNotHangul : { if ([NSString isContainKorean:inputText] == YES) { return NO; } break; } case CMTextFieldLimitTypeOnlyNum : { if ([NSString isDigitOnly:inputText] == NO) { return NO; } break; } }//end switch } return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField { [self addDoneButton]; if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) { [self.inputDelegate textFieldShouldEndEditing:textField]; } } - (void)textFieldDidEndEditing:(UITextField *)textField { [_doneButton removeFromSuperview]; _doneButton = nil; if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) { [self.inputDelegate textFieldDidEndEditing:textField]; return; } [textField resignFirstResponder]; } - (BOOL)textFieldShouldClear:(UITextField *)textField { if (self.inputDelegate != nil && [self.inputDelegate respondsToSelector:@selector(textFieldShouldClear:)]) { return [self.inputDelegate textFieldShouldClear:textField];; } return YES; } - (void)keyboardWillShow:(NSNotification*)notification { /*if ([self isFirstResponder] == false) { return; } UINavigationController* navigationController = (UINavigationController*)[[[[UIApplication sharedApplication] delegate] window] rootViewController]; CGRect rootViewFrame = navigationController.view.frame; NSDictionary* keyboardInfo = [notification userInfo]; CGRect keyboardFrame = [[keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGRect frame = [self.window convertRect:self.frame fromView:self.superview]; CGFloat bottomPadding = 3; if (keyboardFrame.origin.y < frame.origin.y + bottomPadding) { CGFloat calcY; if ((CGRectGetMaxY(frame) <= keyboardFrame.origin.y) && (keyboardFrame.origin.y - CGRectGetMaxY(frame) < bottomPadding)) { calcY = bottomPadding - (keyboardFrame.origin.y - CGRectGetMaxY(frame)); } else { calcY = CGRectGetMaxY(frame) - keyboardFrame.origin.y + bottomPadding; } rootViewFrame.origin.y -= calcY; [UIView animateWithDuration:.4 animations:^{ navigationController.view.frame = rootViewFrame; }]; }*/ } - (void)keyboardWillHide:(NSNotification*)noti { /*UINavigationController* navigationController = (UINavigationController*)[[[[UIApplication sharedApplication] delegate] window] rootViewController]; CGRect rootViewFrame = navigationController.view.frame; rootViewFrame.origin.y = 0; [UIView animateWithDuration:.4 animations:^{ navigationController.view.frame = rootViewFrame; }];*/ } @end
{ "content_hash": "5f4204e7f854e07ada748649b7706ed5", "timestamp": "", "source": "github", "line_count": 533, "max_line_length": 154, "avg_line_length": 36.26454033771107, "alnum_prop": 0.6351596047389932, "repo_name": "LambertPark/I_NScreen", "id": "b2d01c0cefb734cd9f76bb358236424814409279", "size": "20062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "I_NScreen/I_NScreen/Classes/_CMCommon/_view/CMTextFieldView.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "201147" }, { "name": "C++", "bytes": "1666268" }, { "name": "Objective-C", "bytes": "2694626" }, { "name": "Objective-C++", "bytes": "341449" }, { "name": "Ruby", "bytes": "448" }, { "name": "Shell", "bytes": "38663" }, { "name": "Swift", "bytes": "5163" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _firebaseConnect = require('./firebaseConnect'); var _firebaseConnect2 = _interopRequireDefault(_firebaseConnect); var _compose = require('./compose'); var _compose2 = _interopRequireDefault(_compose); var _reducer = require('./reducer'); var _reducer2 = _interopRequireDefault(_reducer); var _constants = require('./constants'); var _constants2 = _interopRequireDefault(_constants); var _helpers = require('./helpers'); var helpers = _interopRequireWildcard(_helpers); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _extends({ firebase: _firebaseConnect2.default, firebaseConnect: _firebaseConnect2.default, createFirebaseConnect: _firebaseConnect.createFirebaseConnect, firebaseStateReducer: _reducer2.default, reduxReactFirebase: _compose2.default, reactReduxFirebase: _compose2.default, reduxFirebase: _compose2.default, constants: _constants2.default, actionTypes: _constants.actionTypes, getFirebase: _compose.getFirebase, helpers: helpers }, helpers); module.exports = exports['default'];
{ "content_hash": "48a9c4bf2925012212bf187ad70470b2", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 269, "avg_line_length": 37.17391304347826, "alnum_prop": 0.7204678362573099, "repo_name": "taforyou/testtesttest-yo", "id": "b051ef5cac86472ab32953260c459336ad1da00e", "size": "1710", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/react-redux-firebase/lib/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12154" }, { "name": "HTML", "bytes": "245" }, { "name": "JavaScript", "bytes": "103350" } ], "symlink_target": "" }
using namespace std; vector<string> ListAssembliesInDirectory(const char* dirPath); struct ClrTokenImp { unsigned int domainId; void* pCLRRuntimeHost; coreclr_initialize_ptr coreclr_initialize; coreclr_create_delegate_ptr coreclr_create_delegate; coreclr_shutdown_2_ptr coreclr_shutdown_2; }; ClrToken LoadClr(wstring wCoreClrFolderPath, wstring wAppBase, wstring wAppPaths, wstring wAppDomainName) { // The bulk of the plugin is written assuming Unicode strings, stored as 16-bit-char wstring. // The hosting API is all 8-bit-char strings. To make things simple, we work entirely in // 8-bit in this method, so start off narrowing our input. // string coreClrFolderPath = narrow(wCoreClrFolderPath); string appPaths = narrow(wAppPaths); string appDomainName = narrow(wAppDomainName); string appBase = narrow(wAppBase); #if APL string coreClrFilePath = coreClrFolderPath + "libcoreclr.dylib"; #else string coreClrFilePath = coreClrFolderPath + "coreclr.dll"; #endif XPLMDebugString(("XPNet: Will load CLR from: " + coreClrFilePath + "\n").c_str()); if (appPaths.length() > 0) appPaths += PATH_ENTRY_SEP; appPaths += appBase + PATH_ENTRY_SEP + coreClrFolderPath; // For simplicity we add here all assemblies of the core clr to the list of fully trusted assemblies vector<string> files = ListAssembliesInDirectory(coreClrFolderPath.c_str()); // Append the path to the assemblies to the full path to all full trusted assemblies string fullTrustedAssemblies; for (unsigned int i = 0; i < files.size(); i++) { fullTrustedAssemblies.append(coreClrFolderPath); fullTrustedAssemblies.append(files[i]); fullTrustedAssemblies.append(PATH_ENTRY_SEP); } // Load the CoreCLR dll into the process HMODULE hCoreCLRModule = SysLoadLibrary(coreClrFilePath); if (!hCoreCLRModule) { string msg = "XPNet: Could not load CoreCLR from path (" + coreClrFilePath + ").\n"; XPLMDebugString(msg.c_str()); return nullptr; } coreclr_initialize_ptr coreclr_initialize = (coreclr_initialize_ptr)SysGetProcAddress(hCoreCLRModule, "coreclr_initialize"); coreclr_create_delegate_ptr coreclr_create_delegate = (coreclr_create_delegate_ptr)SysGetProcAddress(hCoreCLRModule, "coreclr_create_delegate"); coreclr_shutdown_2_ptr coreclr_shutdown_2 = (coreclr_shutdown_2_ptr)SysGetProcAddress(hCoreCLRModule, "coreclr_shutdown_2"); if (!coreclr_initialize) { XPLMDebugString("XPNet: Failed to find coreclr export: coreclr_initialize.\n"); return nullptr; } if (!coreclr_create_delegate) { XPLMDebugString("XPNet: Failed to find coreclr export: coreclr_create_delegate.\n"); return nullptr; } if (!coreclr_shutdown_2) { XPLMDebugString("XPNet: Failed to find coreclr export: coreclr_shutdown_2.\n"); return nullptr; } const char* property_keys[] = { "APPBASE", "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", }; const char* property_values[] = { // APPBASE appBase.c_str(), // TRUSTED_PLATFORM_ASSEMBLIES fullTrustedAssemblies.c_str(), // APP_PATHS appPaths.c_str() }; string entrypointExePath = narrow(GetEntrypointExecutablePath()); unsigned int domainId; void* pCLRRuntimeHost; int st = coreclr_initialize( entrypointExePath.c_str(), appDomainName.c_str(), sizeof(property_keys) / sizeof(property_keys[0]), property_keys, property_values, &pCLRRuntimeHost, &domainId ); if (FAILED(st)) { //wprintf_s(L"Full trusted assemblies: %S\n", pCoreClrStartupParams->FullTrustedAssembliePaths.c_str()); //wprintf_s(L"AppPaths: %S\n", pCoreClrStartupParams->AppPaths.c_str()); string msg = "XPNet: coreclr_initialize failed - status: (" + to_string(st) + ").\n"; XPLMDebugString(msg.c_str()); return nullptr; } return new ClrTokenImp { domainId, pCLRRuntimeHost, coreclr_initialize, coreclr_create_delegate, coreclr_shutdown_2 }; } void UnloadClr(ClrToken clrToken) { ClrTokenImp* clr = static_cast<ClrTokenImp*>(clrToken); int latchedExitCode; int st = clr->coreclr_shutdown_2(clr->pCLRRuntimeHost, clr->domainId, &latchedExitCode); if (FAILED(st)) { string msg = "XPNet: coreclr_shutdown_2 failed - status: (" + to_string(st) + ").\n"; XPLMDebugString(msg.c_str()); } delete clr; } void* GetClrMethod(ClrToken clrToken, std::wstring assemblyName, std::wstring typeName, std::wstring methodName) { ClrTokenImp* clr = static_cast<ClrTokenImp*>(clrToken); void *pMethod; int st = clr->coreclr_create_delegate( clr->pCLRRuntimeHost, clr->domainId, narrow(assemblyName).c_str(), narrow(typeName).c_str(), narrow(methodName).c_str(), &pMethod ); if (FAILED(st)) { string msg = "XPNet: coreclr_create_delegate - failed to create a delegate to managed method (" + narrow(methodName) + "): (" + to_string(st) + ").\n"; XPLMDebugString(msg.c_str()); return 0; } return pMethod; } // Function to list all files in a specific directory with a specified pattern vector<string> ListAssembliesInDirectory(const char* dirPath) { vector<string> result; for (auto& dirEntry : fs::recursive_directory_iterator(dirPath)) { const auto& filename = dirEntry.path().filename(); if (filename.extension() == ".dll") result.push_back(filename.string()); } return result; }
{ "content_hash": "735c56145dedb1dbe15dd23d61b43969", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 153, "avg_line_length": 30.658823529411766, "alnum_prop": 0.7285111281657713, "repo_name": "jaurenq/XPNet", "id": "b02f13ff255684f4f9ccd29062e4739febff2da9", "size": "5765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XPNet.Native/xpnetclrhost.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6105" }, { "name": "C#", "bytes": "104613" }, { "name": "C++", "bytes": "52254" }, { "name": "Makefile", "bytes": "6628" } ], "symlink_target": "" }
package org.keycloak.testsuite.ldap; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import javax.security.auth.kerberos.KerberosPrincipal; import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor; import org.apache.directory.server.kerberos.KerberosConfig; import org.apache.directory.server.kerberos.kdc.KdcServer; import org.apache.directory.server.kerberos.shared.replay.ReplayCache; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler; import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler; import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler; import org.apache.directory.server.ldap.handlers.sasl.ntlm.NtlmMechanismHandler; import org.apache.directory.server.ldap.handlers.sasl.plain.PlainMechanismHandler; import org.apache.directory.server.protocol.shared.transport.UdpTransport; import org.apache.directory.shared.kerberos.KerberosTime; import org.apache.directory.shared.kerberos.KerberosUtils; import org.apache.directory.shared.kerberos.codec.types.EncryptionType; import org.jboss.logging.Logger; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class KerberosEmbeddedServer extends LDAPEmbeddedServer { private static final Logger log = Logger.getLogger(KerberosEmbeddedServer.class); private final String kerberosRealm; private final int kdcPort; private final String kdcEncryptionTypes; private KdcServer kdcServer; public static void main(String[] args) throws Exception { EmbeddedServersFactory factory = EmbeddedServersFactory.readConfiguration(); KerberosEmbeddedServer kerberosEmbeddedServer = factory.createKerberosServer(); kerberosEmbeddedServer.init(); kerberosEmbeddedServer.start(); } protected KerberosEmbeddedServer(String baseDN, String bindHost, int bindPort, String ldifFile, String ldapSaslPrincipal, String kerberosRealm, int kdcPort, String kdcEncryptionTypes) { super(baseDN, bindHost, bindPort, ldifFile, ldapSaslPrincipal); this.kdcEncryptionTypes = kdcEncryptionTypes; this.kerberosRealm = kerberosRealm; this.kdcPort = kdcPort; } @Override public void init() throws Exception { super.init(); log.info("Creating KDC server. kerberosRealm: " + kerberosRealm + ", kdcPort: " + kdcPort + ", kdcEncryptionTypes: " + kdcEncryptionTypes); createAndStartKdcServer(); } @Override protected DirectoryService createDirectoryService() throws Exception { DirectoryService directoryService = super.createDirectoryService(); directoryService.addLast(new KeyDerivationInterceptor()); return directoryService; } @Override protected LdapServer createLdapServer() { LdapServer ldapServer = super.createLdapServer(); ldapServer.setSaslHost( this.bindHost ); ldapServer.setSaslPrincipal( this.ldapSaslPrincipal); ldapServer.setSaslRealms(new ArrayList<String>()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.PLAIN, new PlainMechanismHandler()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.CRAM_MD5, new CramMd5MechanismHandler()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.DIGEST_MD5, new DigestMd5MechanismHandler()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.GSSAPI, new GssapiMechanismHandler()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.NTLM, new NtlmMechanismHandler()); ldapServer.addSaslMechanismHandler(SupportedSaslMechanisms.GSS_SPNEGO, new NtlmMechanismHandler()); return ldapServer; } protected KdcServer createAndStartKdcServer() throws Exception { KerberosConfig kdcConfig = new KerberosConfig(); kdcConfig.setServicePrincipal("krbtgt/" + this.kerberosRealm + "@" + this.kerberosRealm); kdcConfig.setPrimaryRealm(this.kerberosRealm); kdcConfig.setMaximumTicketLifetime(60000 * 1440); kdcConfig.setMaximumRenewableLifetime(60000 * 10080); kdcConfig.setPaEncTimestampRequired(false); Set<EncryptionType> encryptionTypes = convertEncryptionTypes(); kdcConfig.setEncryptionTypes(encryptionTypes); kdcServer = new NoReplayKdcServer(kdcConfig); kdcServer.setSearchBaseDn(this.baseDN); UdpTransport udp = new UdpTransport(this.bindHost, this.kdcPort); kdcServer.addTransports(udp); kdcServer.setDirectoryService(directoryService); // Launch the server kdcServer.start(); return kdcServer; } public void stop() throws Exception { stopLdapServer(); stopKerberosServer(); shutdownDirectoryService(); } protected void stopKerberosServer() { log.info("Stopping Kerberos server."); kdcServer.stop(); } private Set<EncryptionType> convertEncryptionTypes() { Set<EncryptionType> encryptionTypes = new HashSet<EncryptionType>(); String[] configEncTypes = kdcEncryptionTypes.split(","); for ( String enc : configEncTypes ) { enc = enc.trim(); for ( EncryptionType type : EncryptionType.getEncryptionTypes() ) { if ( type.getName().equalsIgnoreCase( enc ) ) { encryptionTypes.add( type ); } } } encryptionTypes = KerberosUtils.orderEtypesByStrength(encryptionTypes); return encryptionTypes; } /** * Replacement of apacheDS KdcServer class with disabled ticket replay cache. * * @author Dominik Pospisil <dpospisi@redhat.com> */ class NoReplayKdcServer extends KdcServer { NoReplayKdcServer(KerberosConfig kdcConfig) { super(kdcConfig); } /** * * Dummy implementation of the ApacheDS kerberos replay cache. Essentially disables kerbores ticket replay checks. * https://issues.jboss.org/browse/JBPAPP-10974 * * @author Dominik Pospisil <dpospisi@redhat.com> */ private class DummyReplayCache implements ReplayCache { @Override public boolean isReplay(KerberosPrincipal serverPrincipal, KerberosPrincipal clientPrincipal, KerberosTime clientTime, int clientMicroSeconds) { return false; } @Override public void save(KerberosPrincipal serverPrincipal, KerberosPrincipal clientPrincipal, KerberosTime clientTime, int clientMicroSeconds) { } @Override public void clear() { } } /** * @throws java.io.IOException if we cannot bind to the sockets */ @Override public void start() throws IOException, LdapInvalidDnException { super.start(); try { // override initialized replay cache with a dummy implementation Field replayCacheField = KdcServer.class.getDeclaredField("replayCache"); replayCacheField.setAccessible(true); replayCacheField.set(this, new DummyReplayCache()); } catch (Exception e) { throw new RuntimeException(e); } } } }
{ "content_hash": "e36c39b770805d4c3abfcf650de5bfb3", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 189, "avg_line_length": 37.30622009569378, "alnum_prop": 0.7028344234962165, "repo_name": "matzew/keycloak", "id": "325f19b4ec6f5f46e8b52e4fa8048eeab098ad74", "size": "7797", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testsuite/integration/src/test/java/org/keycloak/testsuite/ldap/KerberosEmbeddedServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "22819" }, { "name": "CSS", "bytes": "549903" }, { "name": "HTML", "bytes": "343236" }, { "name": "Java", "bytes": "7147725" }, { "name": "JavaScript", "bytes": "1259846" }, { "name": "Shell", "bytes": "10703" }, { "name": "XSLT", "bytes": "2870" } ], "symlink_target": "" }
<?php namespace Guzzle\Service\Command; use Guzzle\Http\Message\Response; use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight; use Guzzle\Service\Command\LocationVisitor\Response\ResponseVisitorInterface; use Guzzle\Service\Description\Parameter; use Guzzle\Service\Description\OperationInterface; use Guzzle\Service\Description\Operation; use Guzzle\Service\Exception\ResponseClassException; use Guzzle\Service\Resource\Model; /** * Response parser that attempts to marshal responses into an associative array based on models in a service description */ class OperationResponseParser extends DefaultResponseParser { /** @var VisitorFlyweight $factory Visitor factory */ protected $factory; /** @var self */ protected static $instance; /** @var bool */ private $schemaInModels; /** * @return self * @codeCoverageIgnore */ public static function getInstance() { if (!static::$instance) { static::$instance = new static(VisitorFlyweight::getInstance()); } return static::$instance; } /** * @param VisitorFlyweight $factory Factory to use when creating visitors * @param bool $schemaInModels Set to true to inject schemas into models */ public function __construct(VisitorFlyweight $factory, $schemaInModels = false) { $this->factory = $factory; $this->schemaInModels = $schemaInModels; } /** * Add a location visitor to the command * * @param string $location Location to associate with the visitor * @param ResponseVisitorInterface $visitor Visitor to attach * * @return self */ public function addVisitor($location, ResponseVisitorInterface $visitor) { $this->factory->addResponseVisitor($location, $visitor); return $this; } protected function handleParsing(CommandInterface $command, Response $response, $contentType) { $operation = $command->getOperation(); $type = $operation->getResponseType(); $model = null; if ($type == OperationInterface::TYPE_MODEL) { $model = $operation->getServiceDescription()->getModel($operation->getResponseClass()); } elseif ($type == OperationInterface::TYPE_CLASS) { return $this->parseClass($command); } if (!$model) { // Return basic processing if the responseType is not model or the model cannot be found return parent::handleParsing($command, $response, $contentType); } elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) { // Returns a model with no visiting if the command response processing is not model return new Model(parent::handleParsing($command, $response, $contentType)); } else { // Only inject the schema into the model if "schemaInModel" is true return new Model($this->visitResult($model, $command, $response), $this->schemaInModels ? $model : null); } } /** * Parse a class object * * @param CommandInterface $command Command to parse into an object * * @return mixed * @throws ResponseClassException */ protected function parseClass(CommandInterface $command) { // Emit the operation.parse_class event. If a listener injects a 'result' property, then that will be the result $event = new CreateResponseClassEvent(array('command' => $command)); $command->getClient()->getEventDispatcher()->dispatch('command.parse_response', $event); if ($result = $event->getResult()) { return $result; } $className = $command->getOperation()->getResponseClass(); if (!method_exists($className, 'fromCommand')) { throw new ResponseClassException("{$className} must exist and implement a static fromCommand() method"); } return $className::fromCommand($command); } /** * Perform transformations on the result array * * @param Parameter $model Model that defines the structure * @param CommandInterface $command Command that performed the operation * @param Response $response Response received * * @return array Returns the array of result data */ protected function visitResult(Parameter $model, CommandInterface $command, Response $response) { $foundVisitors = $result = $knownProps = array(); $props = $model->getProperties(); foreach ($props as $schema) { if ($location = $schema->getLocation()) { // Trigger the before method on the first found visitor of this type if (!isset($foundVisitors[$location])) { $foundVisitors[$location] = $this->factory->getResponseVisitor($location); $foundVisitors[$location]->before($command, $result); } } } // Visit additional properties when it is an actual schema if (($additional = $model->getAdditionalProperties()) instanceof Parameter) { $this->visitAdditionalProperties($model, $command, $response, $additional, $result, $foundVisitors); } // Apply the parameter value with the location visitor foreach ($props as $schema) { $knownProps[$schema->getName()] = 1; if ($location = $schema->getLocation()) { $foundVisitors[$location]->visit($command, $response, $schema, $result); } } // Remove any unknown and potentially unsafe top-level properties if ($additional === false) { $result = array_intersect_key($result, $knownProps); } // Call the after() method of each found visitor foreach ($foundVisitors as $visitor) { $visitor->after($command); } return $result; } protected function visitAdditionalProperties( Parameter $model, CommandInterface $command, Response $response, Parameter $additional, &$result, array &$foundVisitors ) { // Only visit when a location is specified if ($location = $additional->getLocation()) { if (!isset($foundVisitors[$location])) { $foundVisitors[$location] = $this->factory->getResponseVisitor($location); $foundVisitors[$location]->before($command, $result); } // Only traverse if an array was parsed from the before() visitors if (is_array($result)) { // Find each additional property foreach (array_keys($result) as $key) { // Check if the model actually knows this property. If so, then it is not additional if (!$model->getProperty($key)) { // Set the name to the key so that we can parse it with each visitor $additional->setName($key); $foundVisitors[$location]->visit($command, $response, $additional, $result); } } // Reset the additionalProperties name to null $additional->setName(null); } } } }
{ "content_hash": "8e1eb3f07eb3e75a63d963f6459937f4", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 120, "avg_line_length": 38.83076923076923, "alnum_prop": 0.5954833597464342, "repo_name": "Condors/TunisiaMall", "id": "711fa6e156e259e33db6765774933f4d8c7f781e", "size": "7572", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php", "mode": "33261", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "16927" }, { "name": "ApacheConf", "bytes": "3688" }, { "name": "Batchfile", "bytes": "690" }, { "name": "CSS", "bytes": "836798" }, { "name": "HTML", "bytes": "917753" }, { "name": "JavaScript", "bytes": "1079135" }, { "name": "PHP", "bytes": "196744" }, { "name": "Shell", "bytes": "4247" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Gallery with Vertical Thumbnail Navigater Theme - Jssor Slider, Carousel, Slideshow with Javascript Source Code</title> </head> <body style="margin: 0px; padding: 0px; font-family:Arial, Verdana;background-color:#fff;"> <!-- it works the same with all jquery version from 1.x to 2.x --> <script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="../js/jssor.slider.mini.js"></script> <!-- use jssor.slider.debug.js instead for debug --> <script> jQuery(document).ready(function ($) { var _SlideshowTransitions = [ //Zoom- in {$Duration: 1200, $Zoom: 1, $Easing: { $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseOutQuad }, $Opacity: 2 }, //Zoom+ out {$Duration: 1000, $Zoom: 11, $SlideOut: true, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 }, //Rotate Zoom- in {$Duration: 1200, $Zoom: 1, $Rotate: 1, $During: { $Zoom: [0.2, 0.8], $Rotate: [0.2, 0.8] }, $Easing: { $Zoom: $JssorEasing$.$EaseSwing, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseSwing }, $Opacity: 2, $Round: { $Rotate: 0.5} }, //Rotate Zoom+ out {$Duration: 1000, $Zoom: 11, $Rotate: 1, $SlideOut: true, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} }, //Zoom HDouble- in {$Duration: 1200, x: 0.5, $Cols: 2, $Zoom: 1, $Assembly: 2049, $ChessMode: { $Column: 15 }, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 }, //Zoom HDouble+ out {$Duration: 1200, x: 4, $Cols: 2, $Zoom: 11, $SlideOut: true, $Assembly: 2049, $ChessMode: { $Column: 15 }, $Easing: { $Left: $JssorEasing$.$EaseInExpo, $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 }, //Rotate Zoom- in L {$Duration: 1200, x: 0.6, $Zoom: 1, $Rotate: 1, $During: { $Left: [0.2, 0.8], $Zoom: [0.2, 0.8], $Rotate: [0.2, 0.8] }, $Easing: { $Left: $JssorEasing$.$EaseSwing, $Zoom: $JssorEasing$.$EaseSwing, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseSwing }, $Opacity: 2, $Round: { $Rotate: 0.5} }, //Rotate Zoom+ out R {$Duration: 1000, x: -4, $Zoom: 11, $Rotate: 1, $SlideOut: true, $Easing: { $Left: $JssorEasing$.$EaseInExpo, $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} }, //Rotate Zoom- in R {$Duration: 1200, x: -0.6, $Zoom: 1, $Rotate: 1, $During: { $Left: [0.2, 0.8], $Zoom: [0.2, 0.8], $Rotate: [0.2, 0.8] }, $Easing: { $Left: $JssorEasing$.$EaseSwing, $Zoom: $JssorEasing$.$EaseSwing, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseSwing }, $Opacity: 2, $Round: { $Rotate: 0.5} }, //Rotate Zoom+ out L {$Duration: 1000, x: 4, $Zoom: 11, $Rotate: 1, $SlideOut: true, $Easing: { $Left: $JssorEasing$.$EaseInExpo, $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} }, //Rotate HDouble- in {$Duration: 1200, x: 0.5, y: 0.3, $Cols: 2, $Zoom: 1, $Rotate: 1, $Assembly: 2049, $ChessMode: { $Column: 15 }, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseOutQuad, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.7} }, //Rotate HDouble- out {$Duration: 1000, x: 0.5, y: 0.3, $Cols: 2, $Zoom: 1, $Rotate: 1, $SlideOut: true, $Assembly: 2049, $ChessMode: { $Column: 15 }, $Easing: { $Left: $JssorEasing$.$EaseInExpo, $Top: $JssorEasing$.$EaseInExpo, $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.7} }, //Rotate VFork in {$Duration: 1200, x: -4, y: 2, $Rows: 2, $Zoom: 11, $Rotate: 1, $Assembly: 2049, $ChessMode: { $Row: 28 }, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseOutQuad, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.7} }, //Rotate HFork in {$Duration: 1200, x: 1, y: 2, $Cols: 2, $Zoom: 11, $Rotate: 1, $Assembly: 2049, $ChessMode: { $Column: 19 }, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseOutQuad, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.8} } ]; var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlayInterval: 1500, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideDuration: 600, //Specifies default duration (swipe) for slide in milliseconds $SlideshowOptions: { //[Optional] Options to specify and enable slideshow or not $Class: $JssorSlideshowRunner$, //[Required] Class to create instance of slideshow $Transitions: _SlideshowTransitions, //[Required] An array of slideshow transitions to play slideshow $TransitionsOrder: 1, //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random $ShowLink: true //[Optional] Whether to bring slide link on top of the slider when slideshow is running, default value is false }, $ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance $ChanceToShow: 1, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 2, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1 //[Optional] Steps to go for each navigation request, default value is 1 }, $ThumbnailNavigatorOptions: { //[Optional] Options to specify and enable thumbnail navigator or not $Class: $JssorThumbnailNavigator$, //[Required] Class to create thumbnail navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $ActionMode: 1, //[Optional] 0 None, 1 act by click, 2 act by mouse hover, 3 both, default value is 1 $Lanes: 2, //[Optional] Specify lanes to arrange thumbnails, default value is 1 $SpacingX: 14, //[Optional] Horizontal space between each thumbnail in pixel, default value is 0 $SpacingY: 12, //[Optional] Vertical space between each thumbnail in pixel, default value is 0 $DisplayPieces: 6, //[Optional] Number of pieces to display, default value is 1 $ParkingPosition: 156, //[Optional] The offset position to park thumbnail $Orientation: 2 //[Optional] Orientation to arrange thumbnails, 1 horizental, 2 vertical, default value is 1 } }; var jssor_slider1 = new $JssorSlider$("slider1_container", options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth; if (parentWidth) jssor_slider1.$ScaleWidth(Math.max(Math.min(parentWidth, 960), 300)); else window.setTimeout(ScaleSlider, 30); } ScaleSlider(); $(window).bind("load", ScaleSlider); $(window).bind("resize", ScaleSlider); $(window).bind("orientationchange", ScaleSlider); //responsive code end }); </script> <!-- Jssor Slider Begin --> <!-- To move inline styles to css file/block, please specify a class name for each element. --> <div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 960px; height: 480px; background: #191919; overflow: hidden;"> <!-- Loading Screen --> <div u="loading" style="position: absolute; top: 0px; left: 0px;"> <div style="filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block; background-color: #000000; top: 0px; left: 0px;width: 100%;height:100%;"> </div> <div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center; top: 0px; left: 0px;width: 100%;height:100%;"> </div> </div> <!-- Slides Container --> <div u="slides" style="cursor: move; position: absolute; left: 240px; top: 0px; width: 720px; height: 480px; overflow: hidden;"> <div> <img u="image" src="../img/travel/01.jpg" /> <img u="thumb" src="../img/travel/thumb-01.jpg" /> </div> <div> <img u="image" src="../img/travel/02.jpg" /> <img u="thumb" src="../img/travel/thumb-02.jpg" /> </div> <div> <img u="image" src="../img/travel/03.jpg" /> <img u="thumb" src="../img/travel/thumb-03.jpg" /> </div> <div> <img u="image" src="../img/travel/04.jpg" /> <img u="thumb" src="../img/travel/thumb-04.jpg" /> </div> <div> <img u="image" src="../img/travel/05.jpg" /> <img u="thumb" src="../img/travel/thumb-05.jpg" /> </div> <div> <img u="image" src="../img/travel/06.jpg" /> <img u="thumb" src="../img/travel/thumb-06.jpg" /> </div> <div> <img u="image" src="../img/travel/07.jpg" /> <img u="thumb" src="../img/travel/thumb-07.jpg" /> </div> <div> <img u="image" src="../img/travel/08.jpg" /> <img u="thumb" src="../img/travel/thumb-08.jpg" /> </div> <div> <img u="image" src="../img/travel/09.jpg" /> <img u="thumb" src="../img/travel/thumb-09.jpg" /> </div> <div> <img u="image" src="../img/travel/10.jpg" /> <img u="thumb" src="../img/travel/thumb-10.jpg" /> </div> <div> <img u="image" src="../img/travel/11.jpg" /> <img u="thumb" src="../img/travel/thumb-11.jpg" /> </div> <div> <img u="image" src="../img/travel/12.jpg" /> <img u="thumb" src="../img/travel/thumb-12.jpg" /> </div> <div> <img u="image" src="../img/travel/13.jpg" /> <img u="thumb" src="../img/travel/thumb-13.jpg" /> </div> <div> <img u="image" src="../img/travel/14.jpg" /> <img u="thumb" src="../img/travel/thumb-14.jpg" /> </div> </div> <!--#region Arrow Navigator Skin Begin --> <style> /* jssor slider arrow navigator skin 05 css */ /* .jssora05l (normal) .jssora05r (normal) .jssora05l:hover (normal mouseover) .jssora05r:hover (normal mouseover) .jssora05l.jssora05ldn (mousedown) .jssora05r.jssora05rdn (mousedown) */ .jssora05l, .jssora05r { display: block; position: absolute; /* size of arrow element */ width: 40px; height: 40px; cursor: pointer; background: url(../img/a17.png) no-repeat; overflow: hidden; } .jssora05l { background-position: -10px -40px; } .jssora05r { background-position: -70px -40px; } .jssora05l:hover { background-position: -130px -40px; } .jssora05r:hover { background-position: -190px -40px; } .jssora05l.jssora05ldn { background-position: -250px -40px; } .jssora05r.jssora05rdn { background-position: -310px -40px; } </style> <!-- Arrow Left --> <span u="arrowleft" class="jssora05l" style="top: 158px; left: 248px;"> </span> <!-- Arrow Right --> <span u="arrowright" class="jssora05r" style="top: 158px; right: 8px"> </span> <!--#endregion Arrow Navigator Skin End --> <!--#region Thumbnail Navigator Skin Begin --> <!-- Help: http://www.jssor.com/development/slider-with-thumbnail-navigator-jquery.html --> <style> /* jssor slider thumbnail navigator skin 02 css */ /* .jssort02 .p (normal) .jssort02 .p:hover (normal mouseover) .jssort02 .p.pav (active) .jssort02 .p.pdn (mousedown) */ .jssort02 { position: absolute; /* size of thumbnail navigator container */ width: 240px; height: 480px; } .jssort02 .p { position: absolute; top: 0; left: 0; width: 99px; height: 66px; } .jssort02 .t { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; } .jssort02 .w { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; } .jssort02 .c { position: absolute; top: 0px; left: 0px; width: 95px; height: 62px; border: #000 2px solid; box-sizing: content-box; background: url(../img/t01.png) -800px -800px no-repeat; _background: none; } .jssort02 .pav .c { top: 2px; _top: 0px; left: 2px; _left: 0px; width: 95px; height: 62px; border: #000 0px solid; _border: #fff 2px solid; background-position: 50% 50%; } .jssort02 .p:hover .c { top: 0px; left: 0px; width: 97px; height: 64px; border: #fff 1px solid; background-position: 50% 50%; } .jssort02 .p.pdn .c { background-position: 50% 50%; width: 95px; height: 62px; border: #000 2px solid; } * html .jssort02 .c, * html .jssort02 .pdn .c, * html .jssort02 .pav .c { /* ie quirks mode adjust */ width /**/: 99px; height /**/: 66px; } </style> <!-- thumbnail navigator container --> <div u="thumbnavigator" class="jssort02" style="left: 0px; bottom: 0px;"> <!-- Thumbnail Item Skin Begin --> <div u="slides" style="cursor: default;"> <div u="prototype" class="p"> <div class=w><div u="thumbnailtemplate" class="t"></div></div> <div class=c></div> </div> </div> <!-- Thumbnail Item Skin End --> </div> <!--#endregion Thumbnail Navigator Skin End --> <a style="display: none" href="http://www.jssor.com">Image Slider</a> </div> <!-- Jssor Slider End --> </body> </html>
{ "content_hash": "ced90559d0ded699411cb5c4b111e6f0", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 367, "avg_line_length": 57.67391304347826, "alnum_prop": 0.5019115825749825, "repo_name": "alucard263096/NCMI", "id": "0fa2995b470b04a5fe57559ebf8adffa200df3f9", "size": "18573", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Website/vendors/Jssor.Slider.FullPack/demos-jquery/image-gallery-with-vertical-thumbnail.source.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26" }, { "name": "C#", "bytes": "19245" }, { "name": "CSS", "bytes": "120997" }, { "name": "HTML", "bytes": "399160" }, { "name": "JavaScript", "bytes": "64086" }, { "name": "PHP", "bytes": "6030013" }, { "name": "Shell", "bytes": "4440" }, { "name": "Smarty", "bytes": "7124" } ], "symlink_target": "" }
package org.apache.camel.itest.jetty; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.AvailablePortFinder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class JettyConstantSetHeaderTest extends CamelTestSupport { private int port; @Test public void testJettyConstantSetHeader() throws Exception { getMockEndpoint("mock:before").message(0).header("beer").isNull(); MockEndpoint result = getMockEndpoint("mock:result"); result.expectedBodiesReceived("Hello World"); result.message(0).header("beer").isEqualTo("Carlsberg"); String reply = template.requestBody("http://localhost:" + port + "/beer", "Hello World", String.class); assertEquals("Bye World", reply); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { port = AvailablePortFinder.getNextAvailable(8000); return new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:http://localhost:" + port + "/beer") .convertBodyTo(String.class) .to("mock:before") .setHeader("beer", constant("Carlsberg")) .to("mock:result") .transform(constant("Bye World")); } }; } }
{ "content_hash": "60f913b829c0afd7ffcc244f1c924b8f", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 111, "avg_line_length": 34.25, "alnum_prop": 0.6297279362972794, "repo_name": "Fabryprog/camel", "id": "716d3c7244df1201ec278ecbc8798db9116d4823", "size": "2309", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/camel-itest/src/test/java/org/apache/camel/itest/jetty/JettyConstantSetHeaderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "17204" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "14479" }, { "name": "HTML", "bytes": "909437" }, { "name": "Java", "bytes": "82182194" }, { "name": "JavaScript", "bytes": "102432" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17240" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "271473" } ], "symlink_target": "" }
// ----------------------------------------------------------------------- // Copyright (c) David Kean. // ----------------------------------------------------------------------- using System; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; using AudioSwitcher.ComponentModel; using AudioSwitcher.Presentation.CommandModel; namespace AudioSwitcher.Presentation.UI { // Responsible for sync'ing between a Command and a ToolStripMenuItem internal class MenuItemCommandBinding { private readonly ToolStripMenuItem _item; private readonly ToolStripDropDown _dropDown; private readonly Lifetime<ICommand> _lifetime; private readonly ICommand _command; private readonly object _argument; public MenuItemCommandBinding(ToolStripDropDown dropDown, ToolStripMenuItem item, Lifetime<ICommand> command) : this(dropDown, item, command, (Func<object>)null) { } public MenuItemCommandBinding(ToolStripDropDown dropDown, ToolStripMenuItem item, Lifetime<ICommand> command, object argument) { if (dropDown == null) throw new ArgumentNullException("dropDown"); if (item == null) throw new ArgumentNullException("item"); if (command == null) throw new ArgumentNullException("command"); _dropDown = dropDown; _item = item; _command = command.Instance; _lifetime = command; _argument = argument; RegisterEvents(); Refresh(); } private void RegisterEvents(bool register = true) { if (register) { _dropDown.Opening += OnContextMenuStripOpening; _dropDown.ItemRemoved += OnItemRemoved; _dropDown.ItemClicked += OnItemClicked; _command.PropertyChanged += OnCommandPropertyChanged; } else { _dropDown.Opening -= OnContextMenuStripOpening; _dropDown.ItemRemoved -= OnItemRemoved; _dropDown.ItemClicked -= OnItemClicked; _command.PropertyChanged -= OnCommandPropertyChanged; } } private void OnItemRemoved(object sender, ToolStripItemEventArgs e) { if (e.Item == _item) RegisterEvents(register: false); _lifetime.Dispose(); } private void OnItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem == _item) _command.Run(_argument); } public void Refresh() { _command.Refresh(_argument); SyncProperty(_command, CommandProperty.IsVisible); SyncProperty(_command, CommandProperty.IsEnabled); SyncProperty(_command, CommandProperty.IsChecked); SyncProperty(_command, CommandProperty.Text); SyncProperty(_command, CommandProperty.Image); SyncProperty(_command, CommandProperty.TooltipText); } private void OnContextMenuStripOpening(object sender, CancelEventArgs e) { Refresh(); } private void OnCommandPropertyChanged(object sender, PropertyChangedEventArgs e) { Command command = (Command)sender; SyncProperty(command, e.PropertyName); } private void SyncProperty(ICommand command, string propertyName) { switch (propertyName) { case CommandProperty.IsVisible: _item.Visible = command.IsVisible; break; case CommandProperty.IsEnabled: _item.Enabled = command.IsEnabled; break; case CommandProperty.IsChecked: _item.Checked = command.IsChecked; break; case CommandProperty.Text: _item.Text = command.Text; break; case CommandProperty.TooltipText: _item.ToolTipText = command.TooltipText; break; case CommandProperty.Image: default: Debug.Assert(propertyName == CommandProperty.Image); _item.Image = command.Image; break; } } } }
{ "content_hash": "50460942a2f5bb8fa7096a111a159e1c", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 134, "avg_line_length": 33.46268656716418, "alnum_prop": 0.5557537912578056, "repo_name": "paulcbetts/audio-switcher", "id": "9f4a9e3561775c34b922cb785ef61ddf6d0741fb", "size": "4486", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AudioSwitcher/Presentation/UI/MenuItemCommandBinding.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "200968" }, { "name": "Smalltalk", "bytes": "15830" } ], "symlink_target": "" }
package com.example.just.businesinfo.fragments; import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.example.just.businesinfo.ISuccess; import com.example.just.businesinfo.R; import com.example.just.businesinfo.connect.DatabaseHandler; import com.example.just.businesinfo.Entity.ParsedDataSet; import com.example.just.businesinfo.connect.XmlContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class CurrencyFragment extends Fragment implements View.OnClickListener { private ListView lv; DatabaseHandler db; ProgressDialog dialog; SwipeRefreshLayout mySwipeRefreshLayout; ParseXmlAsync parseXmlAsyn; LoadDBCurrency loadDBCurrency; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_currency, container, false); lv = (ListView) view.findViewById(R.id.list); mySwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); mySwipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { try { if (!hasConnection(getActivity())) { Toast.makeText(getActivity(), R.string.Network_is_not_conn, Toast.LENGTH_LONG).show(); mySwipeRefreshLayout.setRefreshing(false); } else { parseXmlAsyn = new ParseXmlAsync(); parseXmlAsyn.execute(); } } catch (Exception e) { e.printStackTrace(); } } } ); db = new DatabaseHandler(getActivity()); obtainCurrency(new Handler(Looper.getMainLooper()), new ISuccess<Integer>() { @Override public void onSuccess(Integer createTableCurrency) { try { if (createTableCurrency < 1) { if (createTableCurrency <= 1) { dialog = ProgressDialog.show(getActivity(), "", getString(R.string.Loading), true); parseXmlAsyn = new ParseXmlAsync(); parseXmlAsyn.execute(); } } dialog = ProgressDialog.show(getActivity(), "", getString(R.string.Loading), true); loadDBCurrency = new LoadDBCurrency(); loadDBCurrency.execute(); } catch (Exception e) { e.printStackTrace(); } } }); return view; } private void obtainCurrency(final Handler handler, final ISuccess<Integer> success) { new Thread(new Runnable() { @Override public void run() { final int createTableCurrency = db.getCreateTableCurrency(); handler.post(new Runnable() { @Override public void run() { success.onSuccess(createTableCurrency); } }); } }).start(); } public void onResume() { super.onResume(); loadDBCurrency = new LoadDBCurrency(); loadDBCurrency.execute(); } public static boolean hasConnection(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = cm.getActiveNetworkInfo(); return wifiInfo != null && wifiInfo.isConnectedOrConnecting(); } @Override public void onClick(View v) { } public class ParseXmlAsync extends AsyncTask<Void, Void, List<HashMap<String, String>>> { @Override protected List<HashMap<String, String>> doInBackground(Void... argo0) { List<HashMap<String, String>> currencyDataSetResult = new ArrayList<>(); try { Calendar mcurrentDate = Calendar.getInstance(); int mYear = mcurrentDate.get(Calendar.YEAR); int mMonth = mcurrentDate.get(Calendar.MONTH) + 1; int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); InputSource inputSource; URL url = new URL(getString(R.string.CurrencyURL) + mMonth + "/" + mDay + "/" + mYear); inputSource = new InputSource(url.openStream()); SAXParserFactory saxParserFactory = SAXParserFactory .newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); XmlContentHandler xmlContentHandler = new XmlContentHandler(); xmlReader.setContentHandler(xmlContentHandler); xmlReader.parse(inputSource); List<ParsedDataSet> parsedDataSet = xmlContentHandler .getParsedData(); Iterator<ParsedDataSet> i = parsedDataSet.iterator(); ParsedDataSet dataItem; while (i.hasNext()) { dataItem = i.next(); ParsedDataSet parsedDataSets = db.getParsedDataSetByName(dataItem.getNumCode()); if (parsedDataSets != null) { db.updateDataSet(dataItem.getRate(), dataItem.getNumCode()); } else { db.addContact(new ParsedDataSet(dataItem.getCurrency(), dataItem.getNumCode(), dataItem.getCharCode(), dataItem.getScale(), dataItem.getName(), dataItem.getRate(), "true")); } } currencyDataSetResult = db.getAllContactsHash(); } catch (Exception e) { e.printStackTrace(); } return currencyDataSetResult; } @Override protected void onPostExecute(List<HashMap<String, String>> result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter( getActivity(), result, R.layout.list_item, new String[]{"CharCode", "Scale", "Name", "Rate"}, new int[]{R.id.nameEng, R.id.Scale, R.id.nominal, R.id.Rate}); lv.setAdapter(adapter); dialog.dismiss(); mySwipeRefreshLayout.setRefreshing(false); } } public class LoadDBCurrency extends AsyncTask<Void, Void, List<HashMap<String, String>>> { @Override protected List<HashMap<String, String>> doInBackground(Void... argo0) { List<HashMap<String, String>> parsedDataSets = new ArrayList<>(); try { parsedDataSets = db.getAllContactsHash(); } catch (Exception e) { e.printStackTrace(); } return parsedDataSets; } @Override protected void onPostExecute(List<HashMap<String, String>> result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter( getActivity(), result, R.layout.list_item, new String[]{"CharCode", "Scale", "Name", "Rate"}, new int[]{R.id.nameEng, R.id.Scale, R.id.nominal, R.id.Rate}); lv.setAdapter(adapter); dialog.dismiss(); mySwipeRefreshLayout.setRefreshing(false); } } }
{ "content_hash": "3ee0559482b07887e5f62c48bb0965da", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 197, "avg_line_length": 38.09417040358744, "alnum_prop": 0.5841082989994114, "repo_name": "Garasjuk/EPAMtraning2016", "id": "f574a4a27a46de001bd9494a1392196ad44cc134", "size": "8495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BusinesInfo/app/src/main/java/com/example/just/businesinfo/fragments/CurrencyFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2547" }, { "name": "Java", "bytes": "202261" } ], "symlink_target": "" }
function [theta] = calcTheta(lambda, X, Y,Xtest,Ytest) err = @(theta)sum((X*theta - Y).^2) + lambda*sum(abs(theta)); options = optimoptions(@fminunc,'Display','iter','Algorithm','quasi-newton','MaxFunEvals',280000); theta = fminunc(err, zeros(280,1), options); end
{ "content_hash": "5ceb8cbb8b3af2be2fd96568d30196fe", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 98, "avg_line_length": 33.375, "alnum_prop": 0.6891385767790262, "repo_name": "lycarter/6.867-proj1", "id": "a67e4c5d78d779ff99f7c99a6683f45cf7f124d8", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "matlab/doLAD_blog.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "9505" }, { "name": "Python", "bytes": "2012" }, { "name": "TeX", "bytes": "18221" } ], "symlink_target": "" }
/** * @file * @author Microsoft Corporation * @version Unknown * * @section DESCRIPTION * This is the standard D3D view provider implementation that comes with a new Windows 8 immersive application */ #include "pch.h" #include "ViewProvider.h" #include "D3DView.h" using namespace Windows::ApplicationModel::Core; using namespace Windows::UI::Core; using namespace Windows::ApplicationModel::Activation; ViewProvider::ViewProvider() { m_activationEntryPoint = ActivationEntryPoint::Unknown; } void ViewProvider::Initialize(Windows::UI::Core::CoreWindow^ window, Windows::ApplicationModel::Core::CoreApplicationView^ applicationView) { m_window = window; m_applicationView = applicationView; } // this method is called after Initialize void ViewProvider::Load(Platform::String^ entryPoint ) { if (entryPoint == "P8Ball.App") { m_activationEntryPoint = ActivationEntryPoint::P8Ball; } } // this method is called after Load void ViewProvider::Run() { if (m_activationEntryPoint == ActivationEntryPoint::P8Ball) { auto view = ref new D3DView(m_window, m_applicationView); view->Run(); // Must delete the view explicitly in order to break a circular dependency // between View and CoreWindow. View holds on to a CoreWindow reference most // typically for window activation, while CoreWindow refers back to View when // event handlers are hooked up. Without breaking this circular dependency, // neither View nor CoreWindow object gets to clean up. It's also important // to note that a 'delete' call on a ref class instance simply means calling // into a class destructor in order to explicitly break a cycle. It doesn't // actually deallocate any memory. delete view; } } void ViewProvider::Uninitialize() { }
{ "content_hash": "eb915dfde60c3e00166b8bc39dd78d4c", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 139, "avg_line_length": 30.42622950819672, "alnum_prop": 0.7122844827586207, "repo_name": "thaddeusdiamond/P8Ball", "id": "677e127abd422d8edc66ac8c2b350e1040e6e0ce", "size": "1856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/P8Ball/ViewProvider.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9695" }, { "name": "C++", "bytes": "18591" } ], "symlink_target": "" }
IPC_MESSAGE_CONTROL0(TestMsg_QuitRunLoop) // ----------------------------------------------------------------------------- // These tests leak memory, this macro disables the test when under the // LeakSanitizer. #ifdef LEAK_SANITIZER #define WILL_LEAK(NAME) DISABLED_##NAME #else #define WILL_LEAK(NAME) NAME #endif namespace content { namespace { // FIXME: It would be great if there was a reusable mock SingleThreadTaskRunner class TestTaskCounter : public base::SingleThreadTaskRunner { public: TestTaskCounter() : count_(0) {} // SingleThreadTaskRunner implementation. bool PostDelayedTask(const tracked_objects::Location&, const base::Closure&, base::TimeDelta) override { base::AutoLock auto_lock(lock_); count_++; return true; } bool PostNonNestableDelayedTask(const tracked_objects::Location&, const base::Closure&, base::TimeDelta) override { base::AutoLock auto_lock(lock_); count_++; return true; } bool RunsTasksOnCurrentThread() const override { return true; } int NumTasksPosted() const { base::AutoLock auto_lock(lock_); return count_; } private: ~TestTaskCounter() override {} mutable base::Lock lock_; int count_; }; #if defined(COMPILER_MSVC) // See explanation for other RenderViewHostImpl which is the same issue. #pragma warning(push) #pragma warning(disable: 4250) #endif class RenderThreadImplForTest : public RenderThreadImpl { public: RenderThreadImplForTest( const InProcessChildThreadParams& params, std::unique_ptr<blink::scheduler::RendererScheduler> scheduler, scoped_refptr<base::SingleThreadTaskRunner>& test_task_counter) : RenderThreadImpl(params, std::move(scheduler), test_task_counter) {} ~RenderThreadImplForTest() override {} }; #if defined(COMPILER_MSVC) #pragma warning(pop) #endif void QuitTask(base::MessageLoop* message_loop) { message_loop->QuitWhenIdle(); } class QuitOnTestMsgFilter : public IPC::MessageFilter { public: explicit QuitOnTestMsgFilter(base::MessageLoop* message_loop) : message_loop_(message_loop) {} // IPC::MessageFilter overrides: bool OnMessageReceived(const IPC::Message& message) override { message_loop_->task_runner()->PostTask( FROM_HERE, base::Bind(&QuitTask, message_loop_)); return true; } bool GetSupportedMessageClasses( std::vector<uint32_t>* supported_message_classes) const override { supported_message_classes->push_back(TestMsgStart); return true; } private: ~QuitOnTestMsgFilter() override {} base::MessageLoop* message_loop_; }; class RenderThreadImplBrowserTest : public testing::Test { public: void SetUp() override { // SequencedWorkerPool is enabled by default in tests. Disable it for this // test to avoid a DCHECK failure when RenderThreadImpl::Init enables it. // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler // redirection experiment concludes https://crbug.com/622400. base::SequencedWorkerPool::DisableForProcessForTesting(); content_renderer_client_.reset(new ContentRendererClient()); SetRendererClientForTesting(content_renderer_client_.get()); browser_threads_.reset( new TestBrowserThreadBundle(TestBrowserThreadBundle::IO_MAINLOOP)); scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = base::ThreadTaskRunnerHandle::Get(); InitializeMojo(); shell_context_.reset(new TestServiceManagerContext); child_connection_.reset(new ChildConnection( mojom::kRendererServiceName, "test", mojo::edk::GenerateRandomToken(), ServiceManagerConnection::GetForProcess()->GetConnector(), io_task_runner)); mojo::MessagePipe pipe; IPC::mojom::ChannelBootstrapPtr channel_bootstrap; child_connection_->GetRemoteInterfaces()->GetInterface(&channel_bootstrap); channel_ = IPC::ChannelProxy::Create( IPC::ChannelMojo::CreateServerFactory( channel_bootstrap.PassInterface().PassHandle(), io_task_runner), nullptr, io_task_runner); mock_process_.reset(new MockRenderProcess); test_task_counter_ = make_scoped_refptr(new TestTaskCounter()); // RenderThreadImpl expects the browser to pass these flags. base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); base::CommandLine::StringVector old_argv = cmd->argv(); cmd->AppendSwitchASCII(switches::kNumRasterThreads, "1"); cmd->AppendSwitchASCII( switches::kContentImageTextureTarget, cc::BufferToTextureTargetMapToString( cc::DefaultBufferToTextureTargetMapForTesting())); std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler = blink::scheduler::RendererScheduler::Create(); scoped_refptr<base::SingleThreadTaskRunner> test_task_counter( test_task_counter_.get()); thread_ = new RenderThreadImplForTest( InProcessChildThreadParams(io_task_runner, child_connection_->service_token()), std::move(renderer_scheduler), test_task_counter); cmd->InitFromArgv(old_argv); test_msg_filter_ = make_scoped_refptr( new QuitOnTestMsgFilter(base::MessageLoop::current())); thread_->AddFilter(test_msg_filter_.get()); } void TearDown() override { if (base::CommandLine::ForCurrentProcess()->HasSwitch( kSingleProcessTestsFlag)) { // In a single-process mode, we need to avoid destructing mock_process_ // because it will call _exit(0) and kill the process before the browser // side is ready to exit. ANNOTATE_LEAKING_OBJECT_PTR(mock_process_.get()); mock_process_.release(); } } IPC::Sender* sender() { return channel_.get(); } scoped_refptr<TestTaskCounter> test_task_counter_; TestContentClientInitializer content_client_initializer_; std::unique_ptr<ContentRendererClient> content_renderer_client_; std::unique_ptr<TestBrowserThreadBundle> browser_threads_; std::unique_ptr<TestServiceManagerContext> shell_context_; std::unique_ptr<ChildConnection> child_connection_; std::unique_ptr<IPC::ChannelProxy> channel_; std::unique_ptr<MockRenderProcess> mock_process_; scoped_refptr<QuitOnTestMsgFilter> test_msg_filter_; RenderThreadImplForTest* thread_; // Owned by mock_process_. }; void CheckRenderThreadInputHandlerManager(RenderThreadImpl* thread) { ASSERT_TRUE(thread->input_handler_manager()); } // Check that InputHandlerManager outlives compositor thread because it uses // raw pointers to post tasks. // Disabled under LeakSanitizer due to memory leaks. http://crbug.com/348994 TEST_F(RenderThreadImplBrowserTest, WILL_LEAK(InputHandlerManagerDestroyedAfterCompositorThread)) { ASSERT_TRUE(thread_->input_handler_manager()); thread_->compositor_task_runner()->PostTask( FROM_HERE, base::Bind(&CheckRenderThreadInputHandlerManager, thread_)); } // Disabled under LeakSanitizer due to memory leaks. TEST_F(RenderThreadImplBrowserTest, WILL_LEAK(ResourceDispatchIPCTasksGoThroughScheduler)) { sender()->Send(new ResourceHostMsg_FollowRedirect(0)); sender()->Send(new TestMsg_QuitRunLoop()); base::RunLoop().Run(); EXPECT_EQ(1, test_task_counter_->NumTasksPosted()); } // Disabled under LeakSanitizer due to memory leaks. TEST_F(RenderThreadImplBrowserTest, WILL_LEAK(NonResourceDispatchIPCTasksDontGoThroughScheduler)) { // NOTE other than not being a resource message, the actual message is // unimportant. sender()->Send(new TestMsg_QuitRunLoop()); base::RunLoop().Run(); EXPECT_EQ(0, test_task_counter_->NumTasksPosted()); } enum NativeBufferFlag { kDisableNativeBuffers, kEnableNativeBuffers }; class RenderThreadImplGpuMemoryBufferBrowserTest : public ContentBrowserTest, public testing::WithParamInterface< ::testing::tuple<NativeBufferFlag, gfx::BufferFormat>> { public: RenderThreadImplGpuMemoryBufferBrowserTest() {} ~RenderThreadImplGpuMemoryBufferBrowserTest() override {} gpu::GpuMemoryBufferManager* memory_buffer_manager() { return memory_buffer_manager_; } private: void SetUpOnRenderThread() { memory_buffer_manager_ = RenderThreadImpl::current()->GetGpuMemoryBufferManager(); } // Overridden from BrowserTestBase: void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kSingleProcess); NativeBufferFlag native_buffer_flag = ::testing::get<0>(GetParam()); switch (native_buffer_flag) { case kEnableNativeBuffers: command_line->AppendSwitch(switches::kEnableNativeGpuMemoryBuffers); break; case kDisableNativeBuffers: command_line->AppendSwitch(switches::kDisableNativeGpuMemoryBuffers); break; } } void SetUpOnMainThread() override { NavigateToURL(shell(), GURL(url::kAboutBlankURL)); PostTaskToInProcessRendererAndWait(base::Bind( &RenderThreadImplGpuMemoryBufferBrowserTest::SetUpOnRenderThread, base::Unretained(this))); } gpu::GpuMemoryBufferManager* memory_buffer_manager_ = nullptr; DISALLOW_COPY_AND_ASSIGN(RenderThreadImplGpuMemoryBufferBrowserTest); }; // https://crbug.com/652531 IN_PROC_BROWSER_TEST_P(RenderThreadImplGpuMemoryBufferBrowserTest, DISABLED_Map) { gfx::BufferFormat format = ::testing::get<1>(GetParam()); gfx::Size buffer_size(4, 4); std::unique_ptr<gfx::GpuMemoryBuffer> buffer = memory_buffer_manager()->CreateGpuMemoryBuffer( buffer_size, format, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, gpu::kNullSurfaceHandle); ASSERT_TRUE(buffer); EXPECT_EQ(format, buffer->GetFormat()); // Map buffer planes. ASSERT_TRUE(buffer->Map()); // Write to buffer and check result. size_t num_planes = gfx::NumberOfPlanesForBufferFormat(format); for (size_t plane = 0; plane < num_planes; ++plane) { ASSERT_TRUE(buffer->memory(plane)); ASSERT_TRUE(buffer->stride(plane)); size_t row_size_in_bytes = gfx::RowSizeForBufferFormat(buffer_size.width(), format, plane); EXPECT_GT(row_size_in_bytes, 0u); std::unique_ptr<char[]> data(new char[row_size_in_bytes]); memset(data.get(), 0x2a + plane, row_size_in_bytes); size_t height = buffer_size.height() / gfx::SubsamplingFactorForBufferFormat(format, plane); for (size_t y = 0; y < height; ++y) { // Copy |data| to row |y| of |plane| and verify result. memcpy( static_cast<char*>(buffer->memory(plane)) + y * buffer->stride(plane), data.get(), row_size_in_bytes); EXPECT_EQ(0, memcmp(static_cast<char*>(buffer->memory(plane)) + y * buffer->stride(plane), data.get(), row_size_in_bytes)); } } buffer->Unmap(); } INSTANTIATE_TEST_CASE_P( RenderThreadImplGpuMemoryBufferBrowserTests, RenderThreadImplGpuMemoryBufferBrowserTest, ::testing::Combine(::testing::Values(kDisableNativeBuffers, kEnableNativeBuffers), // These formats are guaranteed to work on all platforms. ::testing::Values(gfx::BufferFormat::R_8, gfx::BufferFormat::BGR_565, gfx::BufferFormat::RGBA_4444, gfx::BufferFormat::RGBA_8888, gfx::BufferFormat::BGRA_8888, gfx::BufferFormat::YVU_420))); } // namespace } // namespace content
{ "content_hash": "1fb169e642c0cf87aa4827be062180e6", "timestamp": "", "source": "github", "line_count": 330, "max_line_length": 80, "avg_line_length": 35.50606060606061, "alnum_prop": 0.6838781258001195, "repo_name": "google-ar/WebARonARCore", "id": "af28029cb823213f3492c6c02e6d38ba98f8ae11", "size": "14308", "binary": false, "copies": "1", "ref": "refs/heads/webarcore_57.0.2987.5", "path": "content/renderer/render_thread_impl_browsertest.cc", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
```bash pip install PyBluez PySerial ``` PyBluez PySerial
{ "content_hash": "2bc03451c85894cc77ecd7d59eb5aa77", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 28, "avg_line_length": 12, "alnum_prop": 0.7333333333333333, "repo_name": "idf/Robot-In-Maze", "id": "ce6de08e6779d7f19013eb0a7a8a4af4eb7fd5bb", "size": "84", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raspberry/readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "93195" }, { "name": "C", "bytes": "6566" }, { "name": "C++", "bytes": "708086" }, { "name": "Objective-C", "bytes": "860" }, { "name": "Processing", "bytes": "29315" }, { "name": "Python", "bytes": "107862" } ], "symlink_target": "" }
package com.amazonaws.services.lambda.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.lambda.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * ListProvisionedConcurrencyConfigsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListProvisionedConcurrencyConfigsRequestProtocolMarshaller implements Marshaller<Request<ListProvisionedConcurrencyConfigsRequest>, ListProvisionedConcurrencyConfigsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/2019-09-30/functions/{FunctionName}/provisioned-concurrency?List=ALL").httpMethodName(HttpMethodName.GET) .hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSLambda").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ListProvisionedConcurrencyConfigsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ListProvisionedConcurrencyConfigsRequest> marshall(ListProvisionedConcurrencyConfigsRequest listProvisionedConcurrencyConfigsRequest) { if (listProvisionedConcurrencyConfigsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ListProvisionedConcurrencyConfigsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, listProvisionedConcurrencyConfigsRequest); protocolMarshaller.startMarshalling(); ListProvisionedConcurrencyConfigsRequestMarshaller.getInstance().marshall(listProvisionedConcurrencyConfigsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "023ecc3938c113ef77d3be17ff62ebe2", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 154, "avg_line_length": 43.45454545454545, "alnum_prop": 0.7824267782426778, "repo_name": "aws/aws-sdk-java", "id": "ed816249361c5c48296347ea1458d9d10ec37909", "size": "2970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/transform/ListProvisionedConcurrencyConfigsRequestProtocolMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package fi.lbd.mobile.adapters.test; import android.app.Activity; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.shadows.ShadowLog; import org.robolectric.Robolectric; import java.util.HashMap; import java.util.Map; import fi.lbd.mobile.CustomRobolectricTestRunner; import fi.lbd.mobile.R; import fi.lbd.mobile.adapters.ListDetailsAdapter; import fi.lbd.mobile.location.ImmutablePointLocation; import fi.lbd.mobile.mapobjects.ImmutableMapObject; import fi.lbd.mobile.mapobjects.MapObject; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Created by Ossi. */ @RunWith(CustomRobolectricTestRunner.class) public class ListDetailsAdapterTest { @Mock ImmutablePointLocation location; @Mock Activity mockActivity = mock(Activity.class); Activity activity; LayoutInflater inflater; Map<String, String> propertiesTest1; Map<String, String> metadataTest1; MapObject mapObjectTest1; ListDetailsAdapter adapterTest1; ListDetailsAdapter adapterTest2; ListDetailsAdapter adapterTest3; ListDetailsAdapter adapterTest4; @Before public void setUp() throws Exception { ShadowLog.stream = System.out; MockitoAnnotations.initMocks(this); propertiesTest1 = new HashMap<>(); propertiesTest1.put("propertyp0", "valuep0"); propertiesTest1.put("propertyp1", "valuep1"); metadataTest1 = new HashMap<>(); metadataTest1.put("propertym0", "valuem0"); metadataTest1.put("propertym1", "valuem1"); activity = Robolectric.buildActivity(Activity.class).create().get(); mapObjectTest1 = new ImmutableMapObject(false, "1", location, propertiesTest1, metadataTest1); adapterTest1 = new ListDetailsAdapter(mockActivity, mapObjectTest1, propertiesTest1.size(), 1,metadataTest1.size()); adapterTest2 = new ListDetailsAdapter(mockActivity, mapObjectTest1, propertiesTest1.size()+1, 1,metadataTest1.size()+1); adapterTest3 = new ListDetailsAdapter(mockActivity, mapObjectTest1, propertiesTest1.size(), 0,metadataTest1.size()-1); adapterTest4 = new ListDetailsAdapter(mockActivity, mapObjectTest1, 0,0,0); } @Test public void testConstructor() { final String testName = "testConstructor"; System.out.println("_____________________________________________________________________"); System.out.println("TESTING: "+testName); System.out.println("---------------------------------------------------------------------"); assertThat(adapterTest1.getCount() == 5); assertThat(adapterTest2.getCount() == 5); assertThat(adapterTest3.getCount() == 3); assertThat(adapterTest4.getCount() == 0); ListDetailsAdapter adapterTest5 = new ListDetailsAdapter(mockActivity, mapObjectTest1, 0,100,metadataTest1.size()-1); ListDetailsAdapter adapterTest6 = new ListDetailsAdapter(mockActivity, mapObjectTest1, propertiesTest1.size()-1,-100,metadataTest1.size()-2); assertThat(adapterTest5.getCount() == 2); assertThat(adapterTest6.getCount() == 1); } @Test public void testGetView(){ final String testName = "testGetView"; System.out.println("_____________________________________________________________________"); System.out.println("TESTING: "+testName); System.out.println("---------------------------------------------------------------------"); LayoutInflater layoutInflater = Robolectric.buildActivity(Activity.class).create().get().getLayoutInflater(); LayoutInflater mockLayoutInflater = mock(LayoutInflater.class); ViewGroup mockViewGroup = mock(ViewGroup.class); LinearLayout parent = new LinearLayout(Robolectric.application); LinearLayout linearLayout = (LinearLayout)layoutInflater.inflate(R.layout.listview_single_row, parent); TextView titleText = (TextView)linearLayout.findViewById(R.id.textViewObjectId); TextView dataText = (TextView)linearLayout.findViewById(R.id.textViewDistance); when(mockActivity.getLayoutInflater()).thenReturn(mockLayoutInflater); when(mockLayoutInflater.inflate(R.layout.listview_double_row, mockViewGroup, false)).thenReturn(mockViewGroup); when(mockViewGroup.findViewById(R.id.textViewObjectId)).thenReturn(titleText); when(mockViewGroup.findViewById(R.id.textViewObjectLocation)).thenReturn(dataText); titleText.setText("Text"); dataText.setText("Text"); for(int i = -1; i < 7; ++i){ // Test an illegal index in each adapter if(i == -1){ adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Text")); assertThat(dataText.getText().equals("Text")); titleText.setText("Text"); dataText.setText("Text"); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Text")); assertThat(dataText.getText().equals("Text")); titleText.setText("Text"); dataText.setText("Text"); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Text")); assertThat(dataText.getText().equals("Text")); titleText.setText("Text"); dataText.setText("Text"); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Text")); assertThat(dataText.getText().equals("Text")); titleText.setText("Text"); dataText.setText("Text"); } // Test the first two elements in each adapter else if(i < 2) { adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals(String.format("propertyp%d", i))); assertThat(dataText.getText().equals(String.format("valuep%d", i))); titleText.setText("Should change"); dataText.setText("Should change"); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals(String.format("propertyp%d", i))); assertThat(dataText.getText().equals(String.format("valuep%d", i))); titleText.setText("Should change"); dataText.setText("Should change"); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals(String.format("propertyp%d", i))); assertThat(dataText.getText().equals(String.format("valuep%d", i))); titleText.setText("Should not change"); dataText.setText("Should not change"); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); titleText.setText("Should change"); dataText.setText("Should change"); } // Test the third element in each adapter. AdapterTest3 doesn't contain location, so // third element should be a metadata element. else if (i == 2){ adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("LOCATION")); titleText.setText("Should change"); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("LOCATION")); titleText.setText("Should change"); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("propertym0")); assertThat(dataText.getText().equals("valuem0")); titleText.setText("Should not change"); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); titleText.setText("Should change"); dataText.setText("Should change"); } // Test the fourth element in each adapter else if (i == 3){ adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("propertym0")); assertThat(dataText.getText().equals("valuem0")); titleText.setText("Should change"); dataText.setText("Should change"); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("propertym0")); assertThat(dataText.getText().equals("valuem0")); titleText.setText("Should not change"); dataText.setText("Should not change"); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); titleText.setText("Should not change"); dataText.setText("Should not change"); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); titleText.setText("Should change"); dataText.setText("Should change"); } // Test fifth elements else if (i == 4){ adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("propertym1")); assertThat(dataText.getText().equals("valuem1")); titleText.setText("Should change"); dataText.setText("Should change"); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("propertym1")); assertThat(dataText.getText().equals("valuem1")); titleText.setText("Should not change"); dataText.setText("Should not change"); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); titleText.setText("Should not change"); dataText.setText("Should not change"); } else { adapterTest1.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); adapterTest2.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); adapterTest3.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); adapterTest4.getView(i, null, mockViewGroup); assertThat(titleText.getText().equals("Should not change")); assertThat(dataText.getText().equals("Should not change")); } } } }
{ "content_hash": "700953fdfe5c55ebeccd896bb6f2c39a", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 119, "avg_line_length": 46.06060606060606, "alnum_prop": 0.6085526315789473, "repo_name": "tttro/projektityokurssi", "id": "736cecaff1c7520d844025cd9881f1a7ac0f8110", "size": "12160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mobile/LBDMobileClient/app/src/test/java/fi/lbd/mobile/adapters/test/ListDetailsAdapterTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "41078" }, { "name": "Java", "bytes": "441369" }, { "name": "JavaScript", "bytes": "153125" }, { "name": "Makefile", "bytes": "5589" }, { "name": "Python", "bytes": "91897" }, { "name": "Shell", "bytes": "5113" } ], "symlink_target": "" }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateReferencesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('references', function (Blueprint $table) { $table->increments('id'); $table->string('first_name'); $table->string('last_name'); $table->string('company_name'); $table->string('position'); $table->integer('candidate_id', false, true)->unsigned(); $table->string('phone_number'); $table->string('email'); $table->timestamps(); $table->foreign('candidate_id')->references('id')->on('candidates'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('references'); } }
{ "content_hash": "0fc82fd2a5f372e5babd45113e51db7b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 80, "avg_line_length": 24.825, "alnum_prop": 0.5488418932527693, "repo_name": "Chantouch/www.jcolabs.com", "id": "7ebc714e7e74d2e34607bf1086259128c5888296", "size": "993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/migrations/2016_11_23_205430_create_references_table.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "CSS", "bytes": "496089" }, { "name": "HTML", "bytes": "2731852" }, { "name": "JavaScript", "bytes": "3153434" }, { "name": "PHP", "bytes": "558961" }, { "name": "Vue", "bytes": "559" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; c60c9c02-7ed0-4998-a7b8-86846b6e4521 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#ExtendedMap.Forms.Plugin.iOS">ExtendedMap.Forms.Plugin.iOS</a></strong></td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> </tr> </tbody> </table> </div> <div id="details"> </div> </div> </body> </html>
{ "content_hash": "8358762d0669f20cc3bcbcf4ed944aa7", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 562, "avg_line_length": 40.295833333333334, "alnum_prop": 0.5741908799503671, "repo_name": "kuhlenh/port-to-core", "id": "d9fdf135e6fc54882810c518d33f2324fa87cad8", "size": "9671", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/xa/xam.plugins.forms.extendedmap.1.0.0.11/ExtendedMap.Forms.Plugin.iOS-MonoTouch10.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta httpEquiv="Content-Type" content="text/html; charset=utf-8"/> <title>Test results - Class carlosgsouza.vinylshop.functional.v2.ArtistFunctionalSpec</title> <link href="base-style.css" rel="stylesheet" type="text/css"/> <link href="style.css" rel="stylesheet" type="text/css"/> <script src="report.js" type="text/javascript"></script> </head> <body> <div id="content"> <h1>Class carlosgsouza.vinylshop.functional.v2.ArtistFunctionalSpec</h1> <div class="breadcrumbs"> <a href="index.html">all</a> &gt; <a href="carlosgsouza.vinylshop.functional.v2.html">carlosgsouza.vinylshop.functional.v2</a> &gt; ArtistFunctionalSpec</div> <div id="summary"> <table> <tr> <td> <div class="summaryGroup"> <table> <tr> <td> <div class="infoBox" id="tests"> <div class="counter">6</div> <p>tests</p> </div> </td> <td> <div class="infoBox" id="failures"> <div class="counter">0</div> <p>failures</p> </div> </td> <td> <div class="infoBox" id="duration"> <div class="counter">0.057s</div> <p>duration</p> </div> </td> </tr> </table> </div> </td> <td> <div class="infoBox success" id="successRate"> <div class="percent">100%</div> <p>successful</p> </div> </td> </tr> </table> </div> <div id="tabs"> <ul class="tabLinks"> <li> <a href="#tab0">Tests</a> </li> </ul> <div id="tab0" class="tab"> <h2>Tests</h2> <table> <thead> <tr> <th>Test</th> <th>Duration</th> <th>Result</th> </tr> </thead> <tr> <td class="success">should ignore the case when searching for vinyls given the artist</td> <td>0.005s</td> <td class="success">passed</td> </tr> <tr> <td class="success">should list all artists</td> <td>0.010s</td> <td class="success">passed</td> </tr> <tr> <td class="success">should match partially when searching for vinyls given the artist</td> <td>0.005s</td> <td class="success">passed</td> </tr> <tr> <td class="success">should search for vinyls given the artist</td> <td>0.014s</td> <td class="success">passed</td> </tr> <tr> <td class="success">should show no results if the artist is not provided for the artist search</td> <td>0.008s</td> <td class="success">passed</td> </tr> <tr> <td class="success">should show no results if there are no vinyls with the given artist</td> <td>0.015s</td> <td class="success">passed</td> </tr> </table> </div> </div> <div id="footer"> <p>Generated by <a href="http://www.gradle.org">Gradle 1.8</a> at Dec 14, 2013 2:31:35 PM</p> </div> </div> </body>
{ "content_hash": "d61c33686b264e6804ba8b67bd2f2193", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 124, "avg_line_length": 23.01851851851852, "alnum_prop": 0.672164119066774, "repo_name": "carlosgsouza/types-and-quality", "id": "f92c384171e1c74434c74ea91e045ff2b00b5025", "size": "2486", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "experiments/1_vinyl_collection/a0/analysis/data/mateus/snapshots/1386958167226/build/reports/tests/carlosgsouza.vinylshop.functional.v2.ArtistFunctionalSpec.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "163714" }, { "name": "Groovy", "bytes": "4181201" }, { "name": "Java", "bytes": "3017224" }, { "name": "JavaScript", "bytes": "134918" }, { "name": "Shell", "bytes": "175054" } ], "symlink_target": "" }
local io = require "io" local os = require "os" local table = require "table" local nixio = require "nixio" local fs = require "nixio.fs" local uci = require "luci.model.uci" local ntm = require "luci.model.network" local luci = {} luci.util = require "luci.util" luci.ip = require "luci.ip" local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select, unpack = tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select, unpack module "luci.sys" function call(...) return os.execute(...) / 256 end exec = luci.util.exec -- containing the whole environment is returned otherwise this function returns -- the corresponding string value for the given name or nil if no such variable -- exists. getenv = nixio.getenv function hostname(newname) if type(newname) == "string" and #newname > 0 then fs.writefile( "/proc/sys/kernel/hostname", newname ) return newname else return nixio.uname().nodename end end function httpget(url, stream, target) if not target then local source = stream and io.popen or luci.util.exec return source("wget -qO- %s" % luci.util.shellquote(url)) else return os.execute("wget -qO %s %s" % {luci.util.shellquote(target), luci.util.shellquote(url)}) end end function reboot() return os.execute("reboot >/dev/null 2>&1") end --- Returns the system type, cpu name and installed physical memory. -- @return String containing the system or platform identifier -- @return String containing hardware model information -- @return String containing the total memory amount in kB -- @return String containing the memory used for caching in kB -- @return String containing the memory used for buffering in kB -- @return String containing the free memory amount in kB -- @return String containing the cpu bogomips (number) function sysinfo() local cpuinfo = fs.readfile("/proc/cpuinfo") local meminfo = fs.readfile("/proc/meminfo") local memtotal = tonumber(meminfo:match("MemTotal:%s*(%d+)")) local memcached = tonumber(meminfo:match("\nCached:%s*(%d+)")) local memfree = tonumber(meminfo:match("MemFree:%s*(%d+)")) local membuffers = tonumber(meminfo:match("Buffers:%s*(%d+)")) local bogomips = tonumber(cpuinfo:match("[Bb]ogo[Mm][Ii][Pp][Ss].-: ([^\n]+)")) or 0 local swaptotal = tonumber(meminfo:match("SwapTotal:%s*(%d+)")) local swapcached = tonumber(meminfo:match("SwapCached:%s*(%d+)")) local swapfree = tonumber(meminfo:match("SwapFree:%s*(%d+)")) local system = cpuinfo:match("system type\t+: ([^\n]+)") or cpuinfo:match("Processor\t+: ([^\n]+)") or cpuinfo:match("model name\t+: ([^\n]+)") local model = luci.util.pcdata(fs.readfile("/tmp/sysinfo/model")) or cpuinfo:match("machine\t+: ([^\n]+)") or cpuinfo:match("Hardware\t+: ([^\n]+)") or luci.util.pcdata(fs.readfile("/proc/diag/model")) or nixio.uname().machine or system return system, model, memtotal, memcached, membuffers, memfree, bogomips, swaptotal, swapcached, swapfree end --- Returns the system load average values. -- @return String containing the average load value 1 minute ago -- @return String containing the average load value 5 minutes ago -- @return String containing the average load value 15 minutes ago function loadavg() local info = nixio.sysinfo() return info.loads[1], info.loads[2], info.loads[3] end function syslog() return luci.util.exec("logread") end function dmesg() return luci.util.exec("dmesg") end function uniqueid(bytes) local rand = fs.readfile("/dev/urandom", bytes) return rand and nixio.bin.hexlify(rand) end function uptime() return nixio.sysinfo().uptime end net = {} local function _nethints(what, callback) local _, k, e, mac, ip, name, duid, iaid local cur = uci.cursor() local ifn = { } local hosts = { } local lookup = { } local function _add(i, ...) local k = select(i, ...) if k then if not hosts[k] then hosts[k] = { } end hosts[k][1] = select(1, ...) or hosts[k][1] hosts[k][2] = select(2, ...) or hosts[k][2] hosts[k][3] = select(3, ...) or hosts[k][3] hosts[k][4] = select(4, ...) or hosts[k][4] end end luci.ip.neighbors(nil, function(neigh) if neigh.mac and neigh.family == 4 then _add(what, neigh.mac:string(), neigh.dest:string(), nil, nil) elseif neigh.mac and neigh.family == 6 then _add(what, neigh.mac:string(), nil, neigh.dest:string(), nil) end end) if fs.access("/etc/ethers") then for e in io.lines("/etc/ethers") do mac, name = e:match("^([a-fA-F0-9:-]+)%s+(%S+)") mac = luci.ip.checkmac(mac) if mac and name then if luci.ip.checkip4(name) then _add(what, mac, name, nil, nil) else _add(what, mac, nil, nil, name) end end end end cur:foreach("dhcp", "dnsmasq", function(s) if s.leasefile and fs.access(s.leasefile) then for e in io.lines(s.leasefile) do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") mac = luci.ip.checkmac(mac) if mac and ip then _add(what, mac, ip, nil, name ~= "*" and name) end end end end ) cur:foreach("dhcp", "odhcpd", function(s) if type(s.leasefile) == "string" and fs.access(s.leasefile) then for e in io.lines(s.leasefile) do duid, iaid, name, _, ip = e:match("^# %S+ (%S+) (%S+) (%S+) (-?%d+) %S+ %S+ ([0-9a-f:.]+)/[0-9]+") mac = net.duid_to_mac(duid) if mac then if ip and iaid == "ipv4" then _add(what, mac, ip, nil, name ~= "*" and name) elseif ip then _add(what, mac, nil, ip, name ~= "*" and name) end end end end end ) cur:foreach("dhcp", "host", function(s) for mac in luci.util.imatch(s.mac) do mac = luci.ip.checkmac(mac) if mac then _add(what, mac, s.ip, nil, s.name) end end end) for _, e in ipairs(nixio.getifaddrs()) do if e.name ~= "lo" then ifn[e.name] = ifn[e.name] or { } if e.family == "packet" and e.addr and #e.addr == 17 then ifn[e.name][1] = e.addr:upper() elseif e.family == "inet" then ifn[e.name][2] = e.addr elseif e.family == "inet6" then ifn[e.name][3] = e.addr end end end for _, e in pairs(ifn) do if e[what] and (e[2] or e[3]) then _add(what, e[1], e[2], e[3], e[4]) end end for _, e in pairs(hosts) do lookup[#lookup+1] = (what > 1) and e[what] or (e[2] or e[3]) end if #lookup > 0 then lookup = luci.util.ubus("network.rrdns", "lookup", { addrs = lookup, timeout = 250, limit = 1000 }) or { } end for _, e in luci.util.kspairs(hosts) do callback(e[1], e[2], e[3], lookup[e[2]] or lookup[e[3]] or e[4]) end end -- Each entry contains the values in the following order: -- [ "mac", "name" ] function net.mac_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) name = name or v4 if name and name ~= mac then callback(mac, name or v4) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) name = name or v4 if name and name ~= mac then rv[#rv+1] = { mac, name or v4 } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv4_hints(callback) if callback then _nethints(2, function(mac, v4, v6, name) name = name or mac if name and name ~= v4 then callback(v4, name) end end) else local rv = { } _nethints(2, function(mac, v4, v6, name) name = name or mac if name and name ~= v4 then rv[#rv+1] = { v4, name } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv6_hints(callback) if callback then _nethints(3, function(mac, v4, v6, name) name = name or mac if name and name ~= v6 then callback(v6, name) end end) else local rv = { } _nethints(3, function(mac, v4, v6, name) name = name or mac if name and name ~= v6 then rv[#rv+1] = { v6, name } end end) return rv end end function net.host_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) if mac and mac ~= "00:00:00:00:00:00" and (v4 or v6 or name) then callback(mac, v4, v6, name) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) if mac and mac ~= "00:00:00:00:00:00" and (v4 or v6 or name) then local e = { } if v4 then e.ipv4 = v4 end if v6 then e.ipv6 = v6 end if name then e.name = name end rv[mac] = e end end) return rv end end function net.conntrack(callback) local ok, nfct = pcall(io.lines, "/proc/net/nf_conntrack") if not ok or not nfct then return nil end local line, connt = nil, (not callback) and { } for line in nfct do local fam, l3, l4, timeout, tuples = line:match("^(ipv[46]) +(%d+) +%S+ +(%d+) +(%d+) +(.+)$") if fam and l3 and l4 and timeout and not tuples:match("^TIME_WAIT ") then l4 = nixio.getprotobynumber(l4) local entry = { bytes = 0, packets = 0, layer3 = fam, layer4 = l4 and l4.name or "unknown", timeout = tonumber(timeout, 10) } local key, val for key, val in tuples:gmatch("(%w+)=(%S+)") do if key == "bytes" or key == "packets" then entry[key] = entry[key] + tonumber(val, 10) elseif key == "src" or key == "dst" then if entry[key] == nil then entry[key] = luci.ip.new(val):string() end elseif key == "sport" or key == "dport" then if entry[key] == nil then entry[key] = val end elseif val then entry[key] = val end end if callback then callback(entry) else connt[#connt+1] = entry end end end return callback and true or connt end function net.devices() local devs = {} local seen = {} for k, v in ipairs(nixio.getifaddrs()) do if v.name and not seen[v.name] then seen[v.name] = true devs[#devs+1] = v.name end end return devs end function net.duid_to_mac(duid) local b1, b2, b3, b4, b5, b6 if type(duid) == "string" then -- DUID-LLT / Ethernet if #duid == 28 then b1, b2, b3, b4, b5, b6 = duid:match("^00010001(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)%x%x%x%x%x%x%x%x$") -- DUID-LL / Ethernet elseif #duid == 20 then b1, b2, b3, b4, b5, b6 = duid:match("^00030001(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)$") -- DUID-LL / Ethernet (Without Header) elseif #duid == 12 then b1, b2, b3, b4, b5, b6 = duid:match("^(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)$") end end return b1 and luci.ip.checkmac(table.concat({ b1, b2, b3, b4, b5, b6 }, ":")) end process = {} function process.info(key) local s = {uid = nixio.getuid(), gid = nixio.getgid()} return not key and s or s[key] end function process.list() local data = {} local k local ps = luci.util.execi("/bin/busybox top -bn1") if not ps then return end for line in ps do local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match( "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][<NW ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)" ) local idx = tonumber(pid) if idx and not cmd:match("top %-bn1") then data[idx] = { ['PID'] = pid, ['PPID'] = ppid, ['USER'] = user, ['STAT'] = stat, ['VSZ'] = vsz, ['%MEM'] = mem, ['%CPU'] = cpu, ['COMMAND'] = cmd } end end return data end function process.setgroup(gid) return nixio.setgid(gid) end function process.setuser(uid) return nixio.setuid(uid) end process.signal = nixio.kill local function xclose(fd) if fd and fd:fileno() > 2 then fd:close() end end function process.exec(command, stdout, stderr, nowait) local out_r, out_w, err_r, err_w if stdout then out_r, out_w = nixio.pipe() end if stderr then err_r, err_w = nixio.pipe() end local pid = nixio.fork() if pid == 0 then nixio.chdir("/") local null = nixio.open("/dev/null", "w+") if null then nixio.dup(out_w or null, nixio.stdout) nixio.dup(err_w or null, nixio.stderr) nixio.dup(null, nixio.stdin) xclose(out_w) xclose(out_r) xclose(err_w) xclose(err_r) xclose(null) end nixio.exec(unpack(command)) os.exit(-1) end local _, pfds, rv = nil, {}, { code = -1, pid = pid } xclose(out_w) xclose(err_w) if out_r then pfds[#pfds+1] = { fd = out_r, cb = type(stdout) == "function" and stdout, name = "stdout", events = nixio.poll_flags("in", "err", "hup") } end if err_r then pfds[#pfds+1] = { fd = err_r, cb = type(stderr) == "function" and stderr, name = "stderr", events = nixio.poll_flags("in", "err", "hup") } end while #pfds > 0 do local nfds, err = nixio.poll(pfds, -1) if not nfds and err ~= nixio.const.EINTR then break end local i for i = #pfds, 1, -1 do local rfd = pfds[i] if rfd.revents > 0 then local chunk, err = rfd.fd:read(4096) if chunk and #chunk > 0 then if rfd.cb then rfd.cb(chunk) else rfd.buf = rfd.buf or {} rfd.buf[#rfd.buf + 1] = chunk end else table.remove(pfds, i) if rfd.buf then rv[rfd.name] = table.concat(rfd.buf, "") end rfd.fd:close() end end end end if not nowait then _, _, rv.code = nixio.waitpid(pid) end return rv end user = {} -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" } user.getuser = nixio.getpw function user.getpasswd(username) local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username) local pwh = pwe and (pwe.pwdp or pwe.passwd) if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then return nil, pwe else return pwh, pwe end end function user.checkpasswd(username, pass) local pwh, pwe = user.getpasswd(username) if pwe then return (pwh == nil or nixio.crypt(pass, pwh) == pwh) end return false end function user.setpasswd(username, password) return os.execute("(echo %s; sleep 1; echo %s) | passwd %s >/dev/null 2>&1" %{ luci.util.shellquote(password), luci.util.shellquote(password), luci.util.shellquote(username) }) end wifi = {} function wifi.getiwinfo(ifname) ntm.init() local wnet = ntm:get_wifinet(ifname) if wnet and wnet.iwinfo then return wnet.iwinfo end local wdev = ntm:get_wifidev(ifname) if wdev and wdev.iwinfo then return wdev.iwinfo end return { ifname = ifname } end init = {} init.dir = "/etc/init.d/" function init.names() local names = { } for name in fs.glob(init.dir.."*") do names[#names+1] = fs.basename(name) end return names end function init.index(name) if fs.access(init.dir..name) then return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null" %{ init.dir, name }) end end local function init_action(action, name) if fs.access(init.dir..name) then return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action }) end end function init.enabled(name) return (init_action("enabled", name) == 0) end function init.enable(name) return (init_action("enable", name) == 0) end function init.disable(name) return (init_action("disable", name) == 0) end function init.start(name) return (init_action("start", name) == 0) end function init.stop(name) return (init_action("stop", name) == 0) end function init.restart(name) return (init_action("restart", name) == 0) end function init.reload(name) return (init_action("reload", name) == 0) end
{ "content_hash": "b06ee4b33de5802e318e736ba53fc75c", "timestamp": "", "source": "github", "line_count": 649, "max_line_length": 106, "avg_line_length": 23.627118644067796, "alnum_prop": 0.6186904917177514, "repo_name": "artynet/luci", "id": "9faf52ef3d6f7e4f5969b55b5f3e2527755ea9ae", "size": "15443", "binary": false, "copies": "1", "ref": "refs/heads/lininonightly", "path": "modules/luci-base/luasrc/sys.lua", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1147997" }, { "name": "C#", "bytes": "42820" }, { "name": "C++", "bytes": "6412" }, { "name": "CMake", "bytes": "609" }, { "name": "CSS", "bytes": "149256" }, { "name": "Dockerfile", "bytes": "1196" }, { "name": "HTML", "bytes": "667363" }, { "name": "Java", "bytes": "49574" }, { "name": "JavaScript", "bytes": "909916" }, { "name": "Lex", "bytes": "7173" }, { "name": "Lua", "bytes": "1538629" }, { "name": "Makefile", "bytes": "124093" }, { "name": "Perl", "bytes": "49472" }, { "name": "Python", "bytes": "1165" }, { "name": "Shell", "bytes": "55576" }, { "name": "Visual Basic", "bytes": "33030" }, { "name": "Yacc", "bytes": "14699" } ], "symlink_target": "" }
using static STULib.Types.Generic.Common; namespace STULib.Types.Dump { [STU(0xF34FD3D6)] public class STU_F34FD3D6 : STU_DD856C32 { [STUField(0x5659BA67, EmbeddedInstance = true)] public STULib.Types.STUConfigVar m_5659BA67; [STUField(0x59E99793, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_59E99793; [STUField(0xB21A0AA8, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_B21A0AA8; [STUField(0xF7948A78, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_F7948A78; [STUField(0x65C81D9A, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_65C81D9A; [STUField(0xF0762954, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_F0762954; [STUField(0x7319BFFF, EmbeddedInstance = true)] public STULib.Types.Dump.STUConfigVarDynamic m_7319BFFF; } }
{ "content_hash": "7968caaa3b06c640e0d2439b7cfef1b2", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 64, "avg_line_length": 36.7037037037037, "alnum_prop": 0.7093844601412714, "repo_name": "kerzyte/OWLib", "id": "b496bd5848c38b9eaafdf00b6928a78cf1c30ef9", "size": "1029", "binary": false, "copies": "1", "ref": "refs/heads/overwatch/1.14", "path": "STULib/Types/Dump/STU_F34FD3D6.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3136047" } ], "symlink_target": "" }
module Basement.BlockN (module X) where import Basement.Sized.Block as X
{ "content_hash": "7914dd96113856cf7aa2096884989ed2", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 39, "avg_line_length": 24.666666666666668, "alnum_prop": 0.7972972972972973, "repo_name": "vincenthz/hs-foundation", "id": "7f3bd638c4f4a0eb2ee12f7d42fa00abcdf09994", "size": "210", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "basement/Basement/BlockN.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "238197" } ], "symlink_target": "" }
namespace :whassup do task :setup do require 'whassup' end desc "Run all defined uptime checks" task :check => :setup do Whassup.check_all end desc "List all uptime checks" task :list => :setup do puts Whassup.locations.join("\n") end desc "Run whassup process" task :run => :setup do while true do Rake::Task["whassup:list"].execute Rake::Task["whassup:check"].execute sleep 60 end end end
{ "content_hash": "6c917301da883504dbe923acb77a1596", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 41, "avg_line_length": 18.32, "alnum_prop": 0.6331877729257642, "repo_name": "rossta/whassup", "id": "0de9580c383dae2e269d9046d41814dbe9bc9bd0", "size": "458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/whassup/tasks.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "13302" } ], "symlink_target": "" }
/* $Id: VBoxNetIntIf.cpp $ */ /** @file * VBoxNetIntIf - IntNet Interface Client Routines. */ /* * Copyright (C) 2009-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_DEFAULT #include "VBoxNetLib.h" #include <VBox/intnet.h> #include <VBox/intnetinline.h> #include <VBox/sup.h> #include <VBox/vmm/vmm.h> #include <VBox/err.h> #include <VBox/log.h> #include <iprt/string.h> /** * Flushes the send buffer. * * @returns VBox status code. * @param pSession The support driver session. * @param hIf The interface handle to flush. */ int VBoxNetIntIfFlush(PSUPDRVSESSION pSession, INTNETIFHANDLE hIf) { INTNETIFSENDREQ SendReq; SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; SendReq.Hdr.cbReq = sizeof(SendReq); SendReq.pSession = pSession; SendReq.hIf = hIf; return SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_SEND, 0, &SendReq.Hdr); } /** * Copys the SG segments into the specified fram. * * @param pvFrame The frame buffer. * @param cSegs The number of segments. * @param paSegs The segments. */ static void vboxnetIntIfCopySG(void *pvFrame, size_t cSegs, PCINTNETSEG paSegs) { uint8_t *pbDst = (uint8_t *)pvFrame; for (size_t iSeg = 0; iSeg < cSegs; iSeg++) { memcpy(pbDst, paSegs[iSeg].pv, paSegs[iSeg].cb); pbDst += paSegs[iSeg].cb; } } /** * Writes a frame packet to the buffer. * * @returns VBox status code. * @param pBuf The buffer. * @param pRingBuf The ring buffer to read from. * @param cSegs The number of segments. * @param paSegs The segments. */ int VBoxNetIntIfRingWriteFrame(PINTNETBUF pBuf, PINTNETRINGBUF pRingBuf, size_t cSegs, PCINTNETSEG paSegs) { /* * Validate input. */ AssertPtr(pBuf); AssertPtr(pRingBuf); AssertPtr(paSegs); Assert(cSegs > 0); /* * Calc frame size. */ uint32_t cbFrame = 0; for (size_t iSeg = 0; iSeg < cSegs; iSeg++) cbFrame += paSegs[iSeg].cb; Assert(cbFrame >= sizeof(RTMAC) * 2); /* * Allocate a frame, copy the data and commit it. */ PINTNETHDR pHdr = NULL; void *pvFrame = NULL; int rc = IntNetRingAllocateFrame(pRingBuf, cbFrame, &pHdr, &pvFrame); if (RT_SUCCESS(rc)) { vboxnetIntIfCopySG(pvFrame, cSegs, paSegs); IntNetRingCommitFrame(pRingBuf, pHdr); return VINF_SUCCESS; } return rc; } /** * Sends a frame * * @returns VBox status code. * @param pSession The support driver session. * @param hIf The interface handle. * @param pBuf The interface buffer. * @param cSegs The number of segments. * @param paSegs The segments. * @param fFlush Whether to flush the write. */ int VBoxNetIntIfSend(PSUPDRVSESSION pSession, INTNETIFHANDLE hIf, PINTNETBUF pBuf, size_t cSegs, PCINTNETSEG paSegs, bool fFlush) { int rc = VBoxNetIntIfRingWriteFrame(pBuf, &pBuf->Send, cSegs, paSegs); if (rc == VERR_BUFFER_OVERFLOW) { VBoxNetIntIfFlush(pSession, hIf); rc = VBoxNetIntIfRingWriteFrame(pBuf, &pBuf->Send, cSegs, paSegs); } if (RT_SUCCESS(rc) && fFlush) rc = VBoxNetIntIfFlush(pSession, hIf); return rc; }
{ "content_hash": "b43b88ffb000a43b4936e59ac82bd9d2", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 106, "avg_line_length": 29.416058394160583, "alnum_prop": 0.6109181141439206, "repo_name": "egraba/vbox_openbsd", "id": "2a85cfa6a2a149edc1008a59a2a4610735b150b1", "size": "4030", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "VirtualBox-5.0.0/src/VBox/NetworkServices/NetLib/VBoxNetIntIf.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "88714" }, { "name": "Assembly", "bytes": "4303680" }, { "name": "AutoIt", "bytes": "2187" }, { "name": "Batchfile", "bytes": "95534" }, { "name": "C", "bytes": "192632221" }, { "name": "C#", "bytes": "64255" }, { "name": "C++", "bytes": "83842667" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "6041" }, { "name": "CSS", "bytes": "26756" }, { "name": "D", "bytes": "41844" }, { "name": "DIGITAL Command Language", "bytes": "56579" }, { "name": "DTrace", "bytes": "1466646" }, { "name": "GAP", "bytes": "350327" }, { "name": "Groff", "bytes": "298540" }, { "name": "HTML", "bytes": "467691" }, { "name": "IDL", "bytes": "106734" }, { "name": "Java", "bytes": "261605" }, { "name": "JavaScript", "bytes": "80927" }, { "name": "Lex", "bytes": "25122" }, { "name": "Logos", "bytes": "4941" }, { "name": "Makefile", "bytes": "426902" }, { "name": "Module Management System", "bytes": "2707" }, { "name": "NSIS", "bytes": "177212" }, { "name": "Objective-C", "bytes": "5619792" }, { "name": "Objective-C++", "bytes": "81554" }, { "name": "PHP", "bytes": "58585" }, { "name": "Pascal", "bytes": "69941" }, { "name": "Perl", "bytes": "240063" }, { "name": "PowerShell", "bytes": "10664" }, { "name": "Python", "bytes": "9094160" }, { "name": "QMake", "bytes": "3055" }, { "name": "R", "bytes": "21094" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1460572" }, { "name": "SourcePawn", "bytes": "4139" }, { "name": "TypeScript", "bytes": "142342" }, { "name": "Visual Basic", "bytes": "7161" }, { "name": "XSLT", "bytes": "1034475" }, { "name": "Yacc", "bytes": "22312" } ], "symlink_target": "" }
package com.google.testing.threadtester; /** * Runs a set of multithreaded tests. To create a multithreaded test, define a * class with a public no-arg constructor, and a set of public no-arg instance * methods annotated with the {@link ThreadedTest} annotation. The * ThreadedTestRunner will create a new instance of the test class, and invoke * each of the annotated methods in turn. For example, using JUnit 4 syntax: * <pre> * public class MyClassTest { * public MyClassTest() {} * * &064;Test * public void runThreadedTests { * new ThreadedTestRunner().runTests(MyClassTest.class, MyClass.class); * } * * &064;ThreadedTest * public void testThreading { * MyTest subject = new MyTest(); * ClassInstrumentationImpl instr = * Instrumentation.getClassInstrumentation(MyClass.class); * ... * } * </pre> * <p> * Before invoking each method, the runner will invoke the method with the * {@link ThreadedBefore} annotation (if any). Setup code common the all of the tests * can be added here. After invoking each method, the @{link ThreadedAfter} * method will be invoked. This can be used to verify results, and to free * resources. * <p> * Note that this class is normally used with standalone tests that use an * {@link InterleavedRunner} or define their own {@link Breakpoint}s and manage * their own Threads. For simpler test cases, consider using the {@link * AnnotatedTestRunner}. * * @see BaseThreadedTestRunner * @see Instrumentation * * @author alasdair.mackintosh@gmail.com (Alasdair Mackintosh) */ public class ThreadedTestRunner extends BaseThreadedTestRunner { @Override protected String getWrapperName() { return ThreadedTestWrapper.class.getName(); } }
{ "content_hash": "c4a00cf32d59dbf34277f4703445a553", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 85, "avg_line_length": 34.431372549019606, "alnum_prop": 0.7220956719817767, "repo_name": "google/thread-weaver", "id": "d1001642ba6780de5ef66f2a601df3b9a223cf9c", "size": "2354", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "main/com/google/testing/threadtester/ThreadedTestRunner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "473293" } ], "symlink_target": "" }
- [Instalasi Python 3](#instalasi-python-3) - [Instalasi editor teks (opsional)](#instalasi-editor-teks-opsional) - [Visual Studio Code](#visual-studio-code) - [Sublime Text](#sublime-text) <br> ## Instalasi Python 3 Di mata kuliah ini, kalian memerlukan **Python 3**. Silakan ikuti petunjuk instalasi berikut jika kalian belum menginstalnya di komputer kalian. 1. [Unduh][python3 downloads] Python 3 sesuai sistem operasi yang kalian gunakan. Jika menggunakan sistem operasi berbasis Linux, silakan unduh dan instal via Terminal. 2. Buka berkas yang telah diunduh. Ketika dialog instalasi muncul, pastikan untuk mencentang `Add Python 3.x to PATH` untuk memudahkan kalian nantinya. ![Add Python 3.x to PATH](images/lab00_01.jpg) 3. Klik `Install Now`, tunggu hingga selesai, kemudian tutup dialog instalasi. <br> ## Instalasi editor teks (opsional) **Editor teks** bawaan Python (IDLE) sebenarnya sudah cukup untuk membantu kalian selama mempelajari mata kuliah ini. Namun, ketika sudah mencapai materi yang lebih lanjut, disarankan untuk menggunakan editor teks lainnya, misalnya [**Visual Studio Code**][vs code] atau [**Sublime Text**][sublime text]. <br> ### Visual Studio Code Apabila kalian ingin menggunakan **Visual Studio Code** sebagai editor teks kalian, silakan ikuti petunjuk instalasi berikut. 1. [Unduh][vs code download] Visual Studio Code sesuai sistem operasi yang kalian gunakan. 2. Buka berkas yang telah diunduh, kemudian lanjutkan proses instalasi. 3. Disarankan untuk mencentang `Add "Open with Code" action` pada tahap `Select Additional Tasks`. Ini akan menambahkan opsi `Open with Code` ketika kalian melakukan klik kanan pada suatu berkas atau direktori (tergantung pilihan yang kalian centang), sehingga kalian bisa mengedit berkas kode di Visual Studio Code lebih mudah nantinya. ![Add "Open with Code" action](images/lab00_02.jpg) 4. Tunggu hingga instalasi selesai, kemudian buka Visual Studio Code. 5. Di bagian kiri, klik ikon untuk `Extensions`, ketikkan `Python` pada *search field*, kemudian instal ekstensi Python. ![Python extension](images/lab00_03.jpg) 6. Jika muncul pesan `Select Python Environment` di bagian bawah, klik dan arahkan pada instalasi Python 3 kalian. ![Python environment](images/lab00_04.jpg) 7. Nantinya, jika muncul notifikasi untuk menginstal `pylint` ketika kalian membuka berkas kode Python, silakan instal jika diinginkan. Alat `pylint` akan membantu kalian menjaga penulisan kode kalian tetap rapi dan sesuai dengan konvensi yang telah ditetapkan. 8. Untuk menjalankan kode Python, klik **`Debug` -> `Start Debugging`** atau tekan <kbd>F5</kbd>. <br> ### Sublime Text Apabila kalian ingin menggunakan **Sublime Text** sebagai editor teks kalian, silakan ikuti petunjuk instalasi berikut. 1. [Unduh][st3 download] Sublime Text sesuai sistem operasi yang kalian gunakan. 2. Buka berkas yang telah diunduh, kemudian lanjutkan proses instalasi. 3. Disarankan untuk mencentang `Add to explorer context menu` pada tahap `Select Additional Tasks`. Ini akan menambahkan opsi `Open with Sublime Text` ketika kalian melakukan klik kanan pada suatu berkas, sehingga kalian bisa mengedit berkas kode di Sublime Text lebih mudah nantinya. ![Add to explorer context menu](images/lab00_05.jpg) 4. Tunggu hingga instalasi selesai, kemudian buka Sublime Text. 5. Klik **`Preferences` -> `Browse Packages...`**, kemudian buka direktori `User`. 6. Buka berkas [**`Python (shell).sublime-build`**][sublime build], klik kanan pada tombol `Raw`, klik `Save link as...` (bisa juga dengan klik tombol `Raw`, kemudian klik kanan dan klik `Save as...`), arahkan ke direktori `User` tadi, kemudian klik `Save`. Bisa juga dengan menyimpannya di direktori sementara, kemudian menyalinnya ke direktori `User` tadi. **Pastikan berkas yang disimpan memiliki ekstensi `.sublime-build`, bukan `.sublime-build.txt` atau yang lainnya.** 7. Untuk menjalankan kode Python, tekan <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd>, pilih `Python (shell)`. Untuk selanjutnya, cukup tekan <kbd>Ctrl</kbd>+<kbd>B</kbd> saja. 8. Kalian bisa menambahkan beberapa *package* yang berguna melalui [**Package Control**][package control], seperti *package* **Anaconda**, **SublimeLinter**, **SublimeREPL**, dan lain-lain. <br> [python3 downloads]: https://python.org/downloads [vs code]: https://code.visualstudio.com [sublime text]: https://sublimetext.com [vs code download]: https://code.visualstudio.com/Download [st3 download]: https://sublimetext.com/3 [sublime build]: misc/Python%20(shell).sublime-build [package control]: https://packagecontrol.io
{ "content_hash": "8ffebde56eaeda7b7f43f655a2d86a1d", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 79, "avg_line_length": 37.476190476190474, "alnum_prop": 0.7498941126641254, "repo_name": "laymonage/TarungLab", "id": "a15c710578f387c9608c25b8db4f58ae8dadfb20", "size": "4763", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lab_instructions/lab00.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "30286" } ], "symlink_target": "" }
from __future__ import absolute_import, division, unicode_literals import copy import functools import logging from flexget.plugin import PluginError from flexget.utils.template import render_from_entry log = logging.getLogger('entry') class EntryUnicodeError(Exception): """This exception is thrown when trying to set non-unicode compatible field value to entry.""" def __init__(self, key, value): self.key = key self.value = value def __str__(self): return 'Field %s is not unicode-compatible (%r)' % (self.key, self.value) class LazyField(object): """ LazyField is a type of :class:`Entry` field which is evaluated only when it's value is requested. This way FlexGet can avoid doing heavy lookups from the internet or database for details that may not be needed ever. Stores callback function(s) to which populates :class:`Entry` fields. Callback is ran when it's called or to get a string representation.""" def __init__(self, entry, field, func): self.entry = entry self.field = field self.funcs = [func] def __call__(self): # Return a result from the first lookup function which succeeds for func in self.funcs[:]: result = func(self.entry, self.field) if result is not None: return result def __str__(self): return str(self()) def __repr__(self): return '<LazyField(field=%s)>' % self.field def __unicode__(self): return unicode(self()) class Entry(dict): """ Represents one item in task. Must have `url` and *title* fields. Stores automatically *original_url* key, which is necessary because plugins (eg. urlrewriters) may change *url* into something else and otherwise that information would be lost. Entry will also transparently convert all ascii strings into unicode and raises :class:`EntryUnicodeError` if conversion fails on any value being set. Such failures are caught by :class:`~flexget.task.Task` and trigger :meth:`~flexget.task.Task.abort`. """ def __init__(self, *args, **kwargs): self.traces = [] self.snapshots = {} self._state = 'undecided' self._hooks = {'accept': [], 'reject': [], 'fail': [], 'complete': []} self.task = None if len(args) == 2: kwargs['title'] = args[0] kwargs['url'] = args[1] args = [] # Make sure constructor does not escape our __setitem__ enforcement self.update(*args, **kwargs) def trace(self, message, operation=None, plugin=None): """ Adds trace message to the entry which should contain useful information about why plugin did not operate on entry. Accept and Reject messages are added to trace automatically. :param string message: Message to add into entry trace. :param string operation: None, reject, accept or fail :param plugin: Uses task.current_plugin by default, pass value to override """ if operation not in (None, 'accept', 'reject', 'fail'): raise ValueError('Unknown operation %s' % operation) item = (plugin, operation, message) if item not in self.traces: self.traces.append(item) def run_hooks(self, action, **kwargs): """ Run hooks that have been registered for given ``action``. :param action: Name of action to run hooks for :param kwargs: Keyword arguments that should be passed to the registered functions """ for func in self._hooks[action]: func(self, **kwargs) def add_hook(self, action, func, **kwargs): """ Add a hook for ``action`` to this entry. :param string action: One of: 'accept', 'reject', 'fail', 'complete' :param func: Function to execute when event occurs :param kwargs: Keyword arguments that should be passed to ``func`` :raises: ValueError when given an invalid ``action`` """ try: self._hooks[action].append(functools.partial(func, **kwargs)) except KeyError: raise ValueError('`%s` is not a valid entry action' % action) def on_accept(self, func, **kwargs): """ Register a function to be called when this entry is accepted. :param func: The function to call :param kwargs: Keyword arguments that should be passed to the registered function """ self.add_hook('accept', func, **kwargs) def on_reject(self, func, **kwargs): """ Register a function to be called when this entry is rejected. :param func: The function to call :param kwargs: Keyword arguments that should be passed to the registered function """ self.add_hook('reject', func, **kwargs) def on_fail(self, func, **kwargs): """ Register a function to be called when this entry is failed. :param func: The function to call :param kwargs: Keyword arguments that should be passed to the registered function """ self.add_hook('fail', func, **kwargs) def on_complete(self, func, **kwargs): """ Register a function to be called when a :class:`Task` has finished processing this entry. :param func: The function to call :param kwargs: Keyword arguments that should be passed to the registered function """ self.add_hook('complete', func, **kwargs) def accept(self, reason=None, **kwargs): if self.rejected: log.debug('tried to accept rejected %r' % self) elif not self.accepted: self._state = 'accepted' self.trace(reason, operation='accept') # Run entry on_accept hooks self.run_hooks('accept', reason=reason, **kwargs) def reject(self, reason=None, **kwargs): # ignore rejections on immortal entries if self.get('immortal'): reason_str = '(%s)' % reason if reason else '' log.info('Tried to reject immortal %s %s' % (self['title'], reason_str)) self.trace('Tried to reject immortal %s' % reason_str) return if not self.rejected: self._state = 'rejected' self.trace(reason, operation='reject') # Run entry on_reject hooks self.run_hooks('reject', reason=reason, **kwargs) def fail(self, reason=None, **kwargs): log.debug('Marking entry \'%s\' as failed' % self['title']) if not self.failed: self._state = 'failed' self.trace(reason, operation='fail') log.error('Failed %s (%s)' % (self['title'], reason)) # Run entry on_fail hooks self.run_hooks('fail', reason=reason, **kwargs) def complete(self, **kwargs): # Run entry on_complete hooks self.run_hooks('complete', **kwargs) @property def accepted(self): return self._state == 'accepted' @property def rejected(self): return self._state == 'rejected' @property def failed(self): return self._state == 'failed' @property def undecided(self): return self._state == 'undecided' def __setitem__(self, key, value): # Enforce unicode compatibility. Check for all subclasses of basestring, so that NavigableStrings are also cast if isinstance(value, basestring) and not type(value) == unicode: try: value = unicode(value) except UnicodeDecodeError: raise EntryUnicodeError(key, value) # url and original_url handling if key == 'url': if not isinstance(value, basestring): raise PluginError('Tried to set %r url to %r' % (self.get('title'), value)) self.setdefault('original_url', value) # title handling if key == 'title': if not isinstance(value, basestring): raise PluginError('Tried to set title to %r' % value) try: log.trace('ENTRY SET: %s = %r' % (key, value)) except Exception as e: log.debug('trying to debug key `%s` value threw exception: %s' % (key, e)) dict.__setitem__(self, key, value) def update(self, *args, **kwargs): """Overridden so our __setitem__ is not avoided.""" if args: if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) other = dict(args[0]) for key in other: self[key] = other[key] for key in kwargs: self[key] = kwargs[key] def setdefault(self, key, value=None): """Overridden so our __setitem__ is not avoided.""" if key not in self: self[key] = value return self[key] def __getitem__(self, key): """Supports lazy loading of fields. If a stored value is a :class:`LazyField`, call it, return the result.""" result = dict.__getitem__(self, key) if isinstance(result, LazyField): log.trace('evaluating lazy field %s' % key) return result() else: return result def get(self, key, default=None, eval_lazy=True, lazy=None): """ Overridden so that our __getitem__ gets used for :class:`LazyFields` :param string key: Name of the key :param object default: Value to be returned if key does not exists :param bool eval_lazy: Allow evaluating LazyFields or not :param bool lazy: Provided for backwards compatibility :return: Value or given *default* """ if lazy is not None: log.warning('deprecated lazy kwarg used') eval_lazy = lazy if not eval_lazy and self.is_lazy(key): return default try: return self[key] except KeyError: return default def __contains__(self, key): """Will cause lazy field lookup to occur and will return false if a field exists but is None.""" return self.get(key) is not None def register_lazy_fields(self, fields, func): """Register a list of fields to be lazily loaded by callback func. :param list fields: List of field names that are registered as lazy fields :param func: Callback function which is called when lazy field needs to be evaluated. Function call will get params (entry, field). See :class:`LazyField` class for more details. """ for field in fields: if self.is_lazy(field): # If the field is already a lazy field, append this function to it's list of functions dict.get(self, field).funcs.append(func) elif not self.get(field, eval_lazy=False): # If it is not a lazy field, and isn't already populated, make it a lazy field self[field] = LazyField(self, field, func) def unregister_lazy_fields(self, fields, func): """ :param list fields: List of field names to unregister. If given field is not lazy loading, value is set to None :param function func: Function to be removed from registered. :return: Number of removed functions :rtype: int """ removed = 0 for field in fields: if self.is_lazy(field): lazy_funcs = dict.get(self, field).funcs if func in lazy_funcs: removed += 1 lazy_funcs.remove(func) if not lazy_funcs: self[field] = None return removed def is_lazy(self, field): """ :param string field: Name of the field to check :return: True if field is lazy loading. :rtype: bool """ return isinstance(dict.get(self, field), LazyField) def safe_str(self): return '%s | %s' % (self['title'], self['url']) # TODO: this is too manual, maybe we should somehow check this internally and throw some exception if # application is trying to operate on invalid entry def isvalid(self): """ :return: True if entry is valid. Return False if this cannot be used. :rtype: bool """ if not 'title' in self: return False if not 'url' in self: return False if not isinstance(self['url'], basestring): return False if not isinstance(self['title'], basestring): return False return True def take_snapshot(self, name): """ Takes a snapshot of the entry under *name*. Snapshots can be accessed via :attr:`.snapshots`. :param string name: Snapshot name """ snapshot = {} for field, value in self.iteritems(): try: snapshot[field] = copy.deepcopy(value) except TypeError: log.warning('Unable to take `%s` snapshot for field `%s` in `%s`' % (name, field, self['title'])) if snapshot: if name in self.snapshots: log.warning('Snapshot `%s` is being overwritten for `%s`' % (name, self['title'])) self.snapshots[name] = snapshot def update_using_map(self, field_map, source_item, ignore_none=False): """ Populates entry fields from a source object using a dictionary that maps from entry field names to attributes (or keys) in the source object. :param dict field_map: A dictionary mapping entry field names to the attribute in source_item (or keys, if source_item is a dict)(nested attributes/dicts are also supported, separated by a dot,) or a function that takes source_item as an argument :param source_item: Source of information to be used by the map :param ignore_none: Ignore any None values, do not record it to the Entry """ func = dict.get if isinstance(source_item, dict) else getattr for field, value in field_map.iteritems(): if isinstance(value, basestring): v = functools.reduce(func, value.split('.'), source_item) else: v = value(source_item) if ignore_none and v is None: continue self[field] = v def render(self, template): """ Renders a template string based on fields in the entry. :param string template: A template string that uses jinja2 or python string replacement format. :return: The result of the rendering. :rtype: string :raises RenderError: If there is a problem. """ if not isinstance(template, basestring): raise ValueError('Trying to render non string template, got %s' % repr(template)) log.trace('rendering: %s' % template) return render_from_entry(template, self) def __eq__(self, other): return self.get('title') == other.get('title') and self.get('original_url') == other.get('original_url') def __hash__(self): return hash(self.get('title', '') + self.get('original_url', '')) def __repr__(self): return '<Entry(title=%s,state=%s)>' % (self['title'], self._state)
{ "content_hash": "882b65b9f99b1f5e690d32bfef293fc6", "timestamp": "", "source": "github", "line_count": 413, "max_line_length": 119, "avg_line_length": 37.40193704600484, "alnum_prop": 0.5922832912539652, "repo_name": "camon/Flexget", "id": "7ce38db366a403db1e3735b0a5e4375063ea2dc6", "size": "15447", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "flexget/entry.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56725" }, { "name": "JavaScript", "bytes": "455222" }, { "name": "Python", "bytes": "1957167" } ], "symlink_target": "" }
package com.facebook; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import java.util.InputMismatchException; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; @PrepareForTest( { ProfileCache.class }) public class ProfileManagerTest extends FacebookPowerMockTestCase { @Before public void before() { FacebookSdk.sdkInitialize(RuntimeEnvironment.application); } @Test public void testLoadCurrentProfileEmptyCache() { ProfileCache profileCache = mock(ProfileCache.class); LocalBroadcastManager localBroadcastManager = mock(LocalBroadcastManager.class); ProfileManager profileManager = new ProfileManager( localBroadcastManager, profileCache ); assertFalse(profileManager.loadCurrentProfile()); verify(profileCache, times(1)).load(); } @Test public void testLoadCurrentProfileWithCache() { ProfileCache profileCache = mock(ProfileCache.class); Profile profile = ProfileTest.createDefaultProfile(); when(profileCache.load()).thenReturn(profile); LocalBroadcastManager localBroadcastManager = mock(LocalBroadcastManager.class); ProfileManager profileManager = new ProfileManager( localBroadcastManager, profileCache ); assertTrue(profileManager.loadCurrentProfile()); verify(profileCache, times(1)).load(); // Verify that we don't save it back verify(profileCache, never()).save(any(Profile.class)); // Verify that we broadcast verify(localBroadcastManager).sendBroadcast(any(Intent.class)); // Verify that if we set the same (semantically) profile there is no additional broadcast. profileManager.setCurrentProfile(ProfileTest.createDefaultProfile()); verify(localBroadcastManager, times(1)).sendBroadcast(any(Intent.class)); // Verify that if we unset the profile there is a broadcast profileManager.setCurrentProfile(null); verify(localBroadcastManager, times(2)).sendBroadcast(any(Intent.class)); } }
{ "content_hash": "46a3168ec15f9d9864d67757e34a609d", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 98, "avg_line_length": 36.388888888888886, "alnum_prop": 0.7282442748091603, "repo_name": "CristianOliveiraDaRosa/facebook-android-sdk", "id": "1747f5af46fa523b1f422f6d3b5fa442936d6775", "size": "3720", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "facebook/junitTests/src/test/java/com/facebook/ProfileManagerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1950154" }, { "name": "Shell", "bytes": "2407" } ], "symlink_target": "" }
FROM golang ADD . /go/src/github.com/havr/docksy RUN go get github.com/fsouza/go-dockerclient RUN go get github.com/coreos/go-etcd/etcd RUN go install github.com/havr/docksy/main CMD /go/bin/main EXPOSE 80 443
{ "content_hash": "0da534426a078b1c58df2ab2cfd6d7ee", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 21.3, "alnum_prop": 0.7746478873239436, "repo_name": "havr/docksy", "id": "34fb757f869e1e7807ca5c368ba04391a5205867", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "9601" }, { "name": "Shell", "bytes": "498" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.batch.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** An error that occurred when resizing a pool. */ @Fluent public final class ResizeError { /* * An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ @JsonProperty(value = "code", required = true) private String code; /* * A message describing the error, intended to be suitable for display in a user interface. */ @JsonProperty(value = "message", required = true) private String message; /* * Additional details about the error. */ @JsonProperty(value = "details") private List<ResizeError> details; /** Creates an instance of ResizeError class. */ public ResizeError() { } /** * Get the code property: An identifier for the error. Codes are invariant and are intended to be consumed * programmatically. * * @return the code value. */ public String code() { return this.code; } /** * Set the code property: An identifier for the error. Codes are invariant and are intended to be consumed * programmatically. * * @param code the code value to set. * @return the ResizeError object itself. */ public ResizeError withCode(String code) { this.code = code; return this; } /** * Get the message property: A message describing the error, intended to be suitable for display in a user * interface. * * @return the message value. */ public String message() { return this.message; } /** * Set the message property: A message describing the error, intended to be suitable for display in a user * interface. * * @param message the message value to set. * @return the ResizeError object itself. */ public ResizeError withMessage(String message) { this.message = message; return this; } /** * Get the details property: Additional details about the error. * * @return the details value. */ public List<ResizeError> details() { return this.details; } /** * Set the details property: Additional details about the error. * * @param details the details value to set. * @return the ResizeError object itself. */ public ResizeError withDetails(List<ResizeError> details) { this.details = details; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (code() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException("Missing required property code in model ResizeError")); } if (message() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException("Missing required property message in model ResizeError")); } if (details() != null) { details().forEach(e -> e.validate()); } } private static final ClientLogger LOGGER = new ClientLogger(ResizeError.class); }
{ "content_hash": "601e13504dac3133f3167b785888d388", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 110, "avg_line_length": 29.048780487804876, "alnum_prop": 0.6280436607892528, "repo_name": "Azure/azure-sdk-for-java", "id": "efb96e52f347b6c95e4d923121ee555384403b45", "size": "3573", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/batch/azure-resourcemanager-batch/src/main/java/com/azure/resourcemanager/batch/models/ResizeError.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
package org.apache.tomcat.jni; /** Time * * @author Mladen Turk */ public class Time { /** number of microseconds per second */ public static final long APR_USEC_PER_SEC = 1000000L; /** number of milliseconds per microsecond */ public static final long APR_MSEC_PER_USEC = 1000L; /** * @param t The time * @return apr_time_t as a second */ public static long sec(long t) { return t / APR_USEC_PER_SEC; } /** * @param t The time * @return apr_time_t as a msec */ public static long msec(long t) { return t / APR_MSEC_PER_USEC; } /** * number of microseconds since 00:00:00 January 1, 1970 UTC * @return the current time */ public static native long now(); /** * Formats dates in the RFC822 * format in an efficient manner. * @param t the time to convert * @return the formatted date */ public static native String rfc822(long t); /** * Formats dates in the ctime() format * in an efficient manner. * Unlike ANSI/ISO C ctime(), apr_ctime() does not include * a \n at the end of the string. * @param t the time to convert * @return the formatted date */ public static native String ctime(long t); /** * Sleep for the specified number of micro-seconds. * <br><b>Warning :</b> May sleep for longer than the specified time. * @param t desired amount of time to sleep. */ public static native void sleep(long t); }
{ "content_hash": "2837711d9bba6afba48eaa3d4e94d783", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 73, "avg_line_length": 23.753846153846155, "alnum_prop": 0.5971502590673575, "repo_name": "Nickname0806/Test_Q4", "id": "22aeb25fa918578647bcb25c6544b75c925342ed", "size": "2357", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "java/org/apache/tomcat/jni/Time.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "37067" }, { "name": "CSS", "bytes": "13304" }, { "name": "HTML", "bytes": "324818" }, { "name": "Java", "bytes": "18705370" }, { "name": "NSIS", "bytes": "40764" }, { "name": "Perl", "bytes": "13860" }, { "name": "Shell", "bytes": "47014" }, { "name": "XSLT", "bytes": "31592" } ], "symlink_target": "" }
require 'test/unit' class RubyamfQuicklyTest < Test::Unit::TestCase # Replace this with your real tests. def test_this_plugin flunk end end
{ "content_hash": "e0f372390dcad24c65a14b1596865cfc", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 18.875, "alnum_prop": 0.7284768211920529, "repo_name": "pillowfactory/rubyamf_quickly", "id": "4ad69a81d1e7d84251494b34a8d38a669abeafb4", "size": "151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/rubyamf_quickly_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "16759" } ], "symlink_target": "" }
import { combineReducers, createStore as reduxCreateStore } from 'redux' import userState from './user' const rootReducer = combineReducers({ userState }); const createStore = () => reduxCreateStore(rootReducer, {}) export default createStore
{ "content_hash": "5b5e0adcc047f94d51c28131e4980395", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 72, "avg_line_length": 24.8, "alnum_prop": 0.7620967741935484, "repo_name": "emero/gatsby-redux-styled-starter", "id": "4820357b03e8d72549931e2a1aa4881ceff0f556", "size": "248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/stores/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4970" } ], "symlink_target": "" }
bigacme ===== [![Build Status](https://travis-ci.org/magnuswatn/bigacme.svg?branch=master)](https://travis-ci.org/magnuswatn/bigacme) [![codecov](https://codecov.io/gh/magnuswatn/bigacme/branch/master/graph/badge.svg)](https://codecov.io/gh/magnuswatn/bigacme) An ACME client for F5 Big-IP. It can be used to get certificates from a ACME compatible CA, and auto-renew them before they expire. This can reduce the administrative burden of SSL. <p align="center"> <img src="https://static.watn.no/bigacme.svg"> </p> ## Prerequisites * F5 Big-IP, version 11 or higher * A server with access to both the Big-IP and the CA ## How it works You manually create a CSR on the Big-IP and then tells bigacme to turn it into a certificate. Bigacme does so by configuring the Big-IP to answer the challenges from the CA. When it's time to renew the certficiate, bigacme repeats the process. See more detailed information in the docs folder.
{ "content_hash": "5a1181a6a3ce7f5d76aff38dcd857bc7", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 243, "avg_line_length": 44.666666666666664, "alnum_prop": 0.7547974413646056, "repo_name": "magnuswatn/bigacme", "id": "4af4f12609c8bcf3007857a63f356fa8cc0b2238", "size": "938", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "132417" }, { "name": "Tcl", "bytes": "1223" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FezDecrypter.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FezDecrypter.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> internal static System.Drawing.Icon decrypter { get { object obj = ResourceManager.GetObject("decrypter", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap FEZ_Alphabet_Big { get { object obj = ResourceManager.GetObject("FEZ_Alphabet_Big", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap FEZ_Alphabet_Medium { get { object obj = ResourceManager.GetObject("FEZ_Alphabet_Medium", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
{ "content_hash": "f1a15d9a8fe1b43a0479644c73875880", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 178, "avg_line_length": 43.39784946236559, "alnum_prop": 0.5760654112983151, "repo_name": "JakyCode/FezDecrypter", "id": "e6d89df09150c3aedf1af29a21ff9781a9d66fef", "size": "4038", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/FezDecrypter/Properties/Resources.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "10669" }, { "name": "Shell", "bytes": "1164" } ], "symlink_target": "" }
 /* File generated by NetTiers templates [www.nettiers.com] Important: Do not modify this file. Edit the file Document.cs instead. */ #region Using Directives using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Security; using System.Data; using Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Entities.Validation; //using Entities = Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Data; using Nettiers.AdventureWorks.Data.Bases; using Microsoft.Practices.EnterpriseLibrary.Logging; #endregion namespace Nettiers.AdventureWorks.Services { ///<summary> /// An object representation of the 'Document' table. ///</summary> /// <remarks> /// IMPORTANT!!! You should not modify this partial class, modify the Document.cs file instead. /// All custom implementations should be done in the <see cref="Document"/> class. /// </remarks> [DataObject] [CLSCompliant(true)] public partial class DocumentServiceBase : ServiceBase<Document, DocumentKey> { #region Constructors ///<summary> /// Creates a new <see cref="Document"/> instance . ///</summary> public DocumentServiceBase() : base() { } ///<summary> /// A simple factory method to create a new <see cref="Document"/> instance. ///</summary> ///<param name="_title">Title of the document.</param> ///<param name="_fileName">Directory path and file name of the document</param> ///<param name="_fileExtension">File extension indicating the document type. For example, .doc or .txt.</param> ///<param name="_revision">Revision number of the document. </param> ///<param name="_changeNumber">Engineering change approval number.</param> ///<param name="_status">1 = Pending approval, 2 = Approved, 3 = Obsolete</param> ///<param name="_documentSummary">Document abstract.</param> ///<param name="_document">Complete document.</param> ///<param name="_modifiedDate">Date and time the record was last updated.</param> public static Document CreateDocument(System.String _title, System.String _fileName, System.String _fileExtension, System.String _revision, System.Int32 _changeNumber, System.Byte _status, System.String _documentSummary, System.Byte[] _document, System.DateTime _modifiedDate) { Document newEntityDocument = new Document(); newEntityDocument.Title = _title; newEntityDocument.FileName = _fileName; newEntityDocument.FileExtension = _fileExtension; newEntityDocument.Revision = _revision; newEntityDocument.ChangeNumber = _changeNumber; newEntityDocument.Status = _status; newEntityDocument.DocumentSummary = _documentSummary; newEntityDocument.Document = _document; newEntityDocument.ModifiedDate = _modifiedDate; return newEntityDocument; } #endregion Constructors #region Fields private static SecurityContext<Document> securityContext = new SecurityContext<Document>(); private static readonly string layerExceptionPolicy = "ServiceLayerExceptionPolicy"; private static readonly bool noTranByDefault = false; #endregion #region SecurityContext ///<summary> /// Contains all necessary information to validate and authorize the /// call of the method with the Principal and Roles of the current user. ///</summary> public static SecurityContext<Document> SecurityContext { get { return securityContext; } } #endregion #region Data Access Methods #region GetByForeignKey Methods #endregion GetByForeignKey Methods #region GetByIndexes /// <summary> /// Gets a row from the DataSource based on its primary key. /// </summary> /// <param name="key">The unique identifier of the row to retrieve.</param> /// <returns>Returns an instance of the Entity class.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public override Document Get(DocumentKey key) { return GetByDocumentId(key.DocumentId); } /// <summary> /// method that Gets rows in a <see cref="TList{Document}" /> from the datasource based on the primary key AK_Document_FileName_Revision index. /// </summary> /// <param name="_fileName">Directory path and file name of the document</param> /// <param name="_revision">Revision number of the document. </param> /// <returns>Returns an instance of the <see cref="Document"/> class.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document GetByFileNameRevision(System.String _fileName, System.String _revision) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByFileNameRevision"); #endregion Security check #region Initialisation Document entity = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; entity = dataProvider.DocumentProvider.GetByFileNameRevision(transactionManager, _fileName, _revision) as Document; } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entity; } /// <summary> /// Method that Gets rows in a <see cref="TList{Document}" /> from the datasource based on the primary key AK_Document_FileName_Revision index. /// </summary> /// <param name="_fileName">Directory path and file name of the document</param> /// <param name="_revision">Revision number of the document. </param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Page length of records you would like to retrieve</param> /// <param name="totalCount">out parameter, number of total rows in given query.</param> /// <returns>Returns an instance of the <see cref="Document"/> class.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document GetByFileNameRevision(System.String _fileName, System.String _revision, int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByFileNameRevision"); #endregion Security check #region Initialisation totalCount = -1; Document entity = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; entity = dataProvider.DocumentProvider.GetByFileNameRevision(transactionManager, _fileName, _revision, start, pageLength, out totalCount) as Document; } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entity; } /// <summary> /// method that Gets rows in a <see cref="TList{Document}" /> from the datasource based on the primary key PK_Document_DocumentID index. /// </summary> /// <param name="_documentId">Primary key for Document records.</param> /// <returns>Returns an instance of the <see cref="Document"/> class.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document GetByDocumentId(System.Int32 _documentId) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByDocumentId"); #endregion Security check #region Initialisation Document entity = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; entity = dataProvider.DocumentProvider.GetByDocumentId(transactionManager, _documentId) as Document; } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entity; } /// <summary> /// Method that Gets rows in a <see cref="TList{Document}" /> from the datasource based on the primary key PK_Document_DocumentID index. /// </summary> /// <param name="_documentId">Primary key for Document records.</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Page length of records you would like to retrieve</param> /// <param name="totalCount">out parameter, number of total rows in given query.</param> /// <returns>Returns an instance of the <see cref="Document"/> class.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document GetByDocumentId(System.Int32 _documentId, int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByDocumentId"); #endregion Security check #region Initialisation totalCount = -1; Document entity = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; entity = dataProvider.DocumentProvider.GetByDocumentId(transactionManager, _documentId, start, pageLength, out totalCount) as Document; } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entity; } #endregion GetByIndexes #region GetAll /// <summary> /// Get a complete collection of <see cref="Document" /> entities. /// </summary> /// <returns></returns> public override TList<Document> GetAll() { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetAll"); #endregion Security check #region Initialisation TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.GetAll(transactionManager); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } /// <summary> /// Get a set portion of a complete list of <see cref="Document" /> entities /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="totalCount">out parameter, number of total rows in given query.</param> /// <returns>a <see cref="TList{Document}"/> </returns> public virtual TList<Document> GetAll(int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetAll"); #endregion Security check #region Initialisation totalCount = -1; TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.GetAll(transactionManager, start, pageLength, out totalCount); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } #endregion GetAll #region GetPaged /// <summary> /// Gets a page of <see cref="TList{Document}" /> rows from the DataSource. /// </summary> /// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param> /// <remarks></remarks> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> GetPaged(out int totalCount) { return GetPaged(null, null, 0, int.MaxValue, out totalCount); } /// <summary> /// Gets a page of <see cref="TList{Document}" /> rows from the DataSource. /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="totalCount">Number of rows in the DataSource.</param> /// <remarks></remarks> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> GetPaged(int start, int pageLength, out int totalCount) { return GetPaged(null, null, start, pageLength, out totalCount); } /// <summary> /// Gets a page of entity rows with a <see cref="TList{Document}" /> from the DataSource with a where clause and order by clause. /// </summary> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC).</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param> /// <remarks></remarks> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public override TList<Document> GetPaged(string whereClause,string orderBy, int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetPaged"); #endregion Security check #region Initialisation totalCount = -1; TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.GetPaged(transactionManager, whereClause, orderBy, start, pageLength, out totalCount); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } /// <summary> /// Gets the number of rows in the DataSource that match the specified whereClause. /// This method is only provided as a workaround for the ObjectDataSource's need to /// execute another method to discover the total count instead of using another param, like our out param. /// This method should be avoided if using the ObjectDataSource or another method. /// </summary> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="totalCount">Number of rows in the DataSource.</param> /// <returns>Returns the number of rows.</returns> public int GetTotalItems(string whereClause, out int totalCount) { GetPaged(whereClause, null, 0, int.MaxValue, out totalCount); return totalCount; } #endregion GetPaged #region Find #region Parsed Find Methods /// <summary> /// Attempts to do a parameterized version of a simple whereclause. /// Returns rows meeting the whereClause condition from the DataSource. /// </summary> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks> /// <returns>Returns a typed collection of Entity objects.</returns> public virtual TList<Document> Find(string whereClause) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("Find"); #endregion Security check #region Initialisation TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.Find(transactionManager, whereClause); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } /// <summary> /// Returns rows meeting the whereClause condition from the DataSource. /// </summary> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="totalCount">out parameter to get total records for query</param> /// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks> /// <returns>Returns a typed collection TList{Document} of <c>Document</c> objects.</returns> public override TList<Document> Find(string whereClause, int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("Find"); #endregion Security check #region Initialisation totalCount = -1; TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.Find(transactionManager, whereClause, start, pageLength, out totalCount); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } #endregion Parsed Find Methods #region Parameterized Find Methods /// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> Find(IFilterParameterCollection parameters) { return Find(parameters, (string) null); } /// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <param name="sortColumns">A collection of <see cref="SqlSortColumn"/> objects.</param> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> Find(IFilterParameterCollection parameters, ISortColumnCollection sortColumns) { return Find(parameters, sortColumns.ToString()); } /// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> Find(IFilterParameterCollection parameters, string orderBy) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("Find"); #endregion Security check #region Initialisation TransactionManager transactionManager = null; TList<Document> list = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.Find(transactionManager, parameters, orderBy); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } /// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <param name="sortColumns">A collection of <see cref="SqlSortColumn"/> objects.</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out. The number of rows that match this query.</param> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> Find(IFilterParameterCollection parameters, ISortColumnCollection sortColumns, int start, int pageLength, out int count) { return Find(parameters, sortColumns.ToString(), start, pageLength, out count); } /// <summary> /// Returns rows from the DataSource that meet the parameter conditions. /// </summary> /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out. The number of rows that match this query.</param> /// <returns>Returns a typed collection of <c>Document</c> objects.</returns> public virtual TList<Document> Find(IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("Find"); #endregion Security check #region Initialisation count = -1; TransactionManager transactionManager = null; TList<Document> list = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.Find(transactionManager, parameters, orderBy, start, pageLength, out count); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } #endregion Parameterized Find Methods #endregion #region Insert #region Insert Entity /// <summary> /// public virtual method that Inserts a Document object into the datasource using a transaction. /// </summary> /// <param name="entity">Document object to Insert.</param> /// <remarks>After Inserting into the datasource, the Document object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns bool that the operation is successful.</returns> /// <example> /// The following code shows the usage of the Insert Method with an already open transaction. /// <code> /// Document entity = new Document(); /// entity.StringProperty = "foo"; /// entity.IntProperty = 12; /// entity.ChildObjectSource.StringProperty = "bar"; /// TransactionManager tm = null; /// try /// { /// tm = ConnectionContext.CreateTransaction(); /// //Insert Child entity, Then Parent Entity /// ChildObjectTypeService.Insert(entity.ChildObjectSource); /// DocumentService.Insert(entity); /// } /// catch (Exception e) /// { /// if (tm != null &amp;&amp; tm.IsOpen) tm.Rollback(); /// if (DomainUtil.HandleException(e, name)) throw; /// } /// </code> /// </example> [DataObjectMethod(DataObjectMethodType.Insert)] public override bool Insert(Document entity) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Insert"); if (!entity.IsValid) throw new EntityNotValidException(entity, "Insert", entity.Error); #endregion Security and validation check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.Insert(transactionManager, entity); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion Insert Entity #region Insert Collection /// <summary> /// public virtual method that Inserts rows in <see cref="TList{Document}" /> to the datasource. /// </summary> /// <param name="entityCollection"><c>Document</c> objects in a <see cref="TList{Document}" /> object to Insert.</param> /// <remarks> /// This function will only Insert entity objects marked as dirty /// and have an identity field equal to zero. /// Upon Inserting the objects, each dirty object will have the public /// method <c>Object.AcceptChanges()</c> called to make it clean. /// After Inserting into the datasource, the <c>Document</c> objects will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) ///</remarks> /// <returns>Returns the number of successful Insert.</returns> /// <example> /// The following code shows the usage of the Insert Method with a collection of Document. /// <code><![CDATA[ /// TList<Document> list = new TList<Document>(); /// Document entity = new Document(); /// entity.StringProperty = "foo"; /// Document entity2 = new Document(); /// entity.StringProperty = "bar"; /// list.Add(entity); /// list.Add(entity2); /// DocumentService.Insert(list); /// } /// catch (Exception e) /// { /// if (DomainUtil.HandleException(e, name)) throw; /// } /// ]]></code> /// </example> [DataObjectMethod(DataObjectMethodType.Insert)] public virtual TList<Document> Insert(TList<Document> entityCollection) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Insert"); if (!entityCollection.IsValid) { throw new EntityNotValidException(entityCollection, "Insert", DomainUtil.GetErrorsFromList<Document>(entityCollection)); } #endregion Security and validation check #region Initialisation bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.Insert(transactionManager, entityCollection); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entityCollection; } #endregion Insert Collection #endregion Insert #region Update #region Update Entity /// <summary> /// public virtual method that Updates a Document object into the datasource using a transaction. /// </summary> /// <param name="entity">Document object to Update.</param> /// <remarks>After Updateing into the datasource, the Document object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns bool that the operation is successful.</returns> /// <example> /// The following code shows the usage of the Update Method with an already open transaction. /// <code> /// Document entity = DocumentService.GetByPrimaryKeyColumn(1234); /// entity.StringProperty = "foo"; /// entity.IntProperty = 12; /// entity.ChildObjectSource.StringProperty = "bar"; /// TransactionManager tm = null; /// try /// { /// tm = ConnectionContext.CreateTransaction(); /// //Update Child entity, Then Parent Entity /// ChildObjectTypeService.Update(entity.ChildObjectSource); /// DocumentService.Update(entity); /// } /// catch (Exception e) /// { /// if (tm != null &amp;&amp; tm.IsOpen) tm.Rollback(); /// if (DomainUtil.HandleException(e, name)) throw; /// } /// </code> /// </example> [DataObjectMethod(DataObjectMethodType.Update)] public override bool Update(Document entity) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Update"); if (!entity.IsValid) throw new EntityNotValidException(entity, "Update", entity.Error); #endregion Security and validation check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.Update(transactionManager, entity); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion Update Entity #region Update Collection /// <summary> /// public virtual method that Updates rows in <see cref="TList{Document}" /> to the datasource. /// </summary> /// <param name="entityCollection"><c>Document</c> objects in a <see cref="TList{Document}" /> object to Update.</param> /// <remarks> /// This function will only Update entity objects marked as dirty /// and have an identity field equal to zero. /// Upon Updateing the objects, each dirty object will have the public /// method <c>Object.AcceptChanges()</c> called to make it clean. /// After Updateing into the datasource, the <c>Document</c> objects will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) ///</remarks> /// <returns>Returns the number of successful Update.</returns> /// <example> /// The following code shows the usage of the Update Method with a collection of Document. /// <code><![CDATA[ /// TList<Document> list = new TList<Document>(); /// Document entity = new Document(); /// entity.StringProperty = "foo"; /// Document entity2 = new Document(); /// entity.StringProperty = "bar"; /// list.Add(entity); /// list.Add(entity2); /// DocumentService.Update(list); /// } /// catch (Exception e) /// { /// if (DomainUtil.HandleException(e, name)) throw; /// } /// ]]></code> /// </example> [DataObjectMethod(DataObjectMethodType.Update)] public virtual TList<Document> Update(TList<Document> entityCollection) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Update"); if (!entityCollection.IsValid) { throw new EntityNotValidException(entityCollection, "Update", DomainUtil.GetErrorsFromList<Document>(entityCollection)); } #endregion Security and validation check #region Initialisation bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.Update(transactionManager, entityCollection); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entityCollection; } #endregion Update Collection #endregion Update #region Save #region Save Entity /// <summary> /// public virtual method that Saves a Document object into the datasource using a transaction. /// </summary> /// <param name="entity">Document object to Save.</param> /// <remarks>After Saveing into the datasource, the Document object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns bool that the operation is successful.</returns> /// <example> /// The following code shows the usage of the Save Method with an already open transaction. /// <code> /// Document entity = DocumentService.GetByPrimaryKeyColumn(1234); /// entity.StringProperty = "foo"; /// entity.IntProperty = 12; /// entity.ChildObjectSource.StringProperty = "bar"; /// TransactionManager tm = null; /// try /// { /// tm = ConnectionContext.CreateTransaction(); /// //Save Child entity, Then Parent Entity /// ChildObjectTypeService.Save(entity.ChildObjectSource); /// DocumentService.Save(entity); /// } /// catch (Exception e) /// { /// if (tm != null &amp;&amp; tm.IsOpen) tm.Rollback(); /// if (DomainUtil.HandleException(e, name)) throw; /// } /// </code> /// </example> [DataObjectMethod(DataObjectMethodType.Update)] public override Document Save(Document entity) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Save"); if (!entity.IsValid) throw new EntityNotValidException(entity, "Save", entity.Error); #endregion Security and validation check #region Initialisation bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.Save(transactionManager, entity); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entity; } #endregion Save Entity #region Save Collection /// <summary> /// public virtual method that Saves rows in <see cref="TList{Document}" /> to the datasource. /// </summary> /// <param name="entityCollection"><c>Document</c> objects in a <see cref="TList{Document}" /> object to Save.</param> /// <remarks> /// This function will only Save entity objects marked as dirty /// and have an identity field equal to zero. /// Upon Saveing the objects, each dirty object will have the public /// method <c>Object.AcceptChanges()</c> called to make it clean. /// After Saveing into the datasource, the <c>Document</c> objects will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) ///</remarks> /// <returns>Returns the number of successful Save.</returns> /// <example> /// The following code shows the usage of the Save Method with a collection of Document. /// <code><![CDATA[ /// TList<Document> list = new TList<Document>(); /// Document entity = new Document(); /// entity.StringProperty = "foo"; /// Document entity2 = new Document(); /// entity.StringProperty = "bar"; /// list.Add(entity); /// list.Add(entity2); /// DocumentService.Save(list); /// } /// catch (Exception e) /// { /// if (DomainUtil.HandleException(e, name)) throw; /// } /// ]]></code> /// </example> [DataObjectMethod(DataObjectMethodType.Update)] public virtual TList<Document> Save(TList<Document> entityCollection) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Save"); if (!entityCollection.IsValid) { throw new EntityNotValidException(entityCollection, "Save", DomainUtil.GetErrorsFromList<Document>(entityCollection)); } #endregion Security and validation check #region Initialisation bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.Save(transactionManager, entityCollection); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entityCollection; } #endregion Save Collection #endregion Save #region Delete #region Delete Entity /// <summary> /// public virtual method that Deletes a Document object into the datasource using a transaction. /// </summary> /// <param name="entity">Document object to Delete.</param> /// <remarks>After Deleteing into the datasource, the Document object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> /// <returns>Returns bool that the operation is successful.</returns> /// <example> /// The following code shows the usage of the Delete Method with an already open transaction. /// <code> /// Document entity = DocumentService.GetByPrimaryKeyColumn(1234); /// entity.StringProperty = "foo"; /// entity.IntProperty = 12; /// entity.ChildObjectSource.StringProperty = "bar"; /// TransactionManager tm = null; /// try /// { /// tm = ConnectionContext.CreateTransaction(); /// //Delete Child entity, Then Parent Entity /// ChildObjectTypeService.Delete(entity.ChildObjectSource); /// DocumentService.Delete(entity); /// } /// catch (Exception e) /// { /// if (tm != null &amp;&amp; tm.IsOpen) tm.Rollback(); /// if (DomainUtil.HandleException(e, name)) throw; /// } /// </code> /// </example> [DataObjectMethod(DataObjectMethodType.Delete)] public override bool Delete(Document entity) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Delete"); if (!entity.IsValid) throw new EntityNotValidException(entity, "Delete", entity.Error); #endregion Security and validation check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.Delete(transactionManager, entity); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion Delete Entity #region Delete Collection /// <summary> /// public virtual method that Deletes rows in <see cref="TList{Document}" /> to the datasource. /// </summary> /// <param name="entityCollection"><c>Document</c> objects in a <see cref="TList{Document}" /> object to Delete.</param> /// <remarks> /// This function will only Delete entity objects marked as dirty /// and have an identity field equal to zero. /// Upon Deleteing the objects, each dirty object will have the public /// method <c>Object.AcceptChanges()</c> called to make it clean. /// After Deleteing into the datasource, the <c>Document</c> objects will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) ///</remarks> /// <returns>Returns the number of successful Delete.</returns> /// <example> /// The following code shows the usage of the Delete Method with a collection of Document. /// <code><![CDATA[ /// TList<Document> list = new TList<Document>(); /// Document entity = new Document(); /// entity.StringProperty = "foo"; /// Document entity2 = new Document(); /// entity.StringProperty = "bar"; /// list.Add(entity); /// list.Add(entity2); /// DocumentService.Delete(list); /// } /// catch (Exception e) /// { /// if (DomainUtil.HandleException(e, name)) throw; /// } /// ]]></code> /// </example> [DataObjectMethod(DataObjectMethodType.Delete)] public virtual TList<Document> Delete(TList<Document> entityCollection) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("Delete"); if (!entityCollection.IsValid) { throw new EntityNotValidException(entityCollection, "Delete", DomainUtil.GetErrorsFromList<Document>(entityCollection)); } #endregion Security and validation check #region Initialisation bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.Delete(transactionManager, entityCollection); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return entityCollection; } #endregion Delete Collection #endregion Delete #region Delete /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="key">The unique identifier of the row to delete.</param> /// <returns>Returns true if operation suceeded.</returns> public bool Delete(DocumentKey key) { return Delete(key.DocumentId ); } /// <summary> /// Deletes a row from the DataSource based on the PK'S System.Int32 _documentId /// </summary> /// <param name="_documentId">Document pk id.</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> [DataObjectMethod(DataObjectMethodType.Delete)] public virtual bool Delete(System.Int32 _documentId) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("Delete"); #endregion Security check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level transactionManager = ConnectionScope.ValidateOrCreateTransaction(); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.Delete(transactionManager, _documentId); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion #region GetBy m:m Aggregate Relationships #region GetByProductIdFromProductDocument /// <summary> /// Gets Document objects from the datasource by ProductID in the /// ProductDocument table. Table Document is related to table Product /// through the (M:N) relationship defined in the ProductDocument table. /// </summary> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <returns>Returns a typed collection of Document objects.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual TList<Document> GetByProductIdFromProductDocument(System.Int32 _productId) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByProductIdFromProductDocument"); #endregion Security check #region Initialisation TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.GetByProductIdFromProductDocument(transactionManager, _productId); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } /// <summary> /// Gets Document objects from the datasource by ProductID in the /// ProductDocument table. Table Document is related to table Product /// through the (M:N) relationship defined in the ProductDocument table. /// </summary> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="totalCount">Out param: Total Number of results returned.</param> /// <remarks></remarks> /// <returns>Returns a typed collection of Document objects.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual TList<Document> GetByProductIdFromProductDocument(System.Int32 _productId, int start, int pageLength, out int totalCount) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("GetByProductIdFromProductDocument"); #endregion Security check #region Initialisation totalCount = -1; TList<Document> list = null; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; list = dataProvider.DocumentProvider.GetByProductIdFromProductDocument(transactionManager, _productId, start, pageLength, out totalCount); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return list; } #endregion GetByProductIdFromProductDocument #endregion N2N Relationships #region Custom Methods #endregion #region DeepLoad #region Deep Load By Entity Keys /// <summary> /// public virtualDeep Loads the requested <see cref="Document"/> by the entity keys. The criteria of the child /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>. /// </summary> /// <param name="_fileName">Directory path and file name of the document</param> /// <param name="_revision">Revision number of the document. </param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param> /// <param name="childTypes">Document Property Collection Type Array To Include or Exclude from Load</param> /// <returns>Returns an instance of the <see cref="Document"/> class and DeepLoaded.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document DeepLoadByFileNameRevision(System.String _fileName, System.String _revision, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes) { // throws security exception if not authorized SecurityContext.IsAuthorized("DeepLoadByFileNameRevision"); bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction; Document entity = GetByFileNameRevision(_fileName, _revision); //Check to see if entity is not null, before attempting to Deep Load if (entity != null) DeepLoad(entity, deep, deepLoadType, childTypes); return entity; } /// <summary> /// public virtualDeep Loads the requested <see cref="Document"/> by the entity keys. The criteria of the child /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>. /// </summary> /// <param name="_documentId">Primary key for Document records.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param> /// <param name="childTypes">Document Property Collection Type Array To Include or Exclude from Load</param> /// <returns>Returns an instance of the <see cref="Document"/> class and DeepLoaded.</returns> [DataObjectMethod(DataObjectMethodType.Select)] public virtual Document DeepLoadByDocumentId(System.Int32 _documentId, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes) { // throws security exception if not authorized SecurityContext.IsAuthorized("DeepLoadByDocumentId"); bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction; Document entity = GetByDocumentId(_documentId); //Check to see if entity is not null, before attempting to Deep Load if (entity != null) DeepLoad(entity, deep, deepLoadType, childTypes); return entity; } #endregion #region DeepLoad By Entity /// <summary> /// public virtualDeep Load the IEntity object with all of the child /// property collections only 1 Level Deep. /// </summary> /// <param name="entity">Document Object</param> /// <remarks> /// <seealso cref="DeepLoad(Document)"/> overloaded methods for a recursive N Level deep loading method. /// </remarks> [DataObjectMethod(DataObjectMethodType.Select)] public virtual void DeepLoad(Document entity) { DeepLoad(entity, false, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// public virtualDeep Load the IEntity object with all of the child /// property collections only 1 Level Deep. /// </summary> /// <remarks> /// <seealso cref="DeepLoad(Document)"/> overloaded methods for a recursive N Level deep loading method. /// </remarks> /// <param name="entity">Document Object</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> [DataObjectMethod(DataObjectMethodType.Select)] public virtual void DeepLoad(Document entity, bool deep) { DeepLoad(entity, deep, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// public virtualDeep Loads the <see cref="IEntity"/> object with criteria based of the child /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>. /// </summary> /// <remarks> /// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph. /// </remarks> /// <param name="entity">The <see cref="Document"/> object to load.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively load all Property Collections that are descendants of this instance. /// If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param> /// <param name="childTypes">Document Property Collection Type Array To Include or Exclude from Load</param> [DataObjectMethod(DataObjectMethodType.Select)] public virtual void DeepLoad(Document entity, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("DeepLoad"); #endregion Security check #region Initialisation TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.DeepLoad(transactionManager, entity, deep, deepLoadType, childTypes); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return; } #endregion #region DeepLoad By Entity Collection /// <summary> /// Deep Loads the <see cref="TList{Document}" /> object with all of the child /// property collections only 1 Level Deep. /// </summary> /// <remarks> /// <seealso cref="DeepLoad(Document)"/> overloaded methods for a recursive N Level deep loading method. /// </remarks> /// <param name="entityCollection">the <see cref="TList{Document}" /> Object to deep loads.</param> [DataObjectMethod(DataObjectMethodType.Select)] public virtual void DeepLoad(TList<Document> entityCollection) { DeepLoad(entityCollection, false, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// Deep Loads the <see cref="TList{Document}" /> object. /// </summary> /// <remarks> /// <seealso cref="DeepLoad(Document)"/> overloaded methods for a recursive N Level deep loading method. /// </remarks> /// <param name="entityCollection">the <see cref="TList{Document}" /> Object to deep loads.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> [DataObjectMethod(DataObjectMethodType.Select)] public virtual void DeepLoad(TList<Document> entityCollection, bool deep) { DeepLoad(entityCollection, deep, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// Deep Loads the entire <see cref="TList{Document}" /> object with criteria based of the child /// property collections only N Levels Deep based on the DeepLoadType. /// </summary> /// <remarks> /// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire collection's object graph. /// </remarks> /// <param name="entityCollection">The <see cref="TList{Document}" /> instance to load.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType"><see cref="DeepLoadType"/> Enumeration to Include/Exclude object property collections from Load. /// Use DeepLoadType.IncludeChildren, ExcludeChildren to traverse the entire object graph. /// </param> /// <param name="childTypes"><see cref="Document"/> Property Collection Type Array To Include or Exclude from Load</param> [DataObjectMethod(DataObjectMethodType.Select, false)] public override void DeepLoad(TList<Document> entityCollection, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes) { #region Security check // throws security exception if not authorized SecurityContext.IsAuthorized("DeepLoad"); #endregion Security check #region Initialisation TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault); dataProvider = ConnectionScope.Current.DataProvider; dataProvider.DocumentProvider.DeepLoad(transactionManager, entityCollection, deep, deepLoadType, childTypes); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return; } #endregion #endregion #region DeepSave #region DeepSave By Entity /// <summary> /// public virtualDeep Saves the <see cref="Document"/> object with all of the child /// property collections N Levels Deep. /// </summary> /// <param name="entity">Document Object</param> [DataObjectMethod(DataObjectMethodType.Update)] public override bool DeepSave(Document entity) { return DeepSave(entity, DeepSaveType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// public virtualDeep Saves the entire object graph of the Document object with criteria based of the child /// Type property array and DeepSaveType. /// </summary> /// <param name="entity">Document Object</param> /// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param> /// <param name="childTypes"><c>Document</c> property Type Array To Include or Exclude from Save</param> [DataObjectMethod(DataObjectMethodType.Update)] public override bool DeepSave(Document entity, DeepSaveType deepSaveType, params System.Type[] childTypes) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("DeepSave"); if (!entity.IsValid) { throw new EntityNotValidException(entity, "DeepSave"); } #endregion Security and validation check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level transactionManager = ConnectionScope.ValidateOrCreateTransaction(); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.DeepSave(transactionManager, entity, deepSaveType, childTypes); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion #region DeepSave By Entity Collection /// <summary> /// Deep Save the entire <see cref="TList{Document}" /> object with all of the child /// property collections. /// </summary> /// <param name="entityCollection">TList{Document} Object</param> [DataObjectMethod(DataObjectMethodType.Update)] public virtual bool DeepSave(TList<Document> entityCollection) { return DeepSave(entityCollection, DeepSaveType.ExcludeChildren, System.Type.EmptyTypes); } /// <summary> /// Deep Save the entire object graph of the <see cref="TList{Document}" /> object with criteria based of the child /// property collections. /// </summary> /// <param name="entityCollection"><see cref="TList{Document}" /> Object</param> /// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param> /// <param name="childTypes">Document Property Collection Type Array To Include or Exclude from Save</param> [DataObjectMethod(DataObjectMethodType.Update)] public override bool DeepSave(TList<Document> entityCollection, DeepSaveType deepSaveType, params System.Type[] childTypes) { #region Security and validation check // throws security exception if not authorized SecurityContext.IsAuthorized("DeepSave"); if (!entityCollection.IsValid) { throw new EntityNotValidException(entityCollection, "DeepSave"); } #endregion Security and validation check #region Initialisation bool result = false; bool isBorrowedTransaction = false; TransactionManager transactionManager = null; NetTiersProvider dataProvider = null; #endregion Initialisation try { isBorrowedTransaction = ConnectionScope.Current.HasTransaction; //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level transactionManager = ConnectionScope.ValidateOrCreateTransaction(); dataProvider = ConnectionScope.Current.DataProvider; result = dataProvider.DocumentProvider.DeepSave(transactionManager, entityCollection, deepSaveType, childTypes); if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen) transactionManager.Commit(); } catch (Exception exc) { #region Handle transaction rollback and exception if (transactionManager != null && transactionManager.IsOpen) transactionManager.Rollback(); //Handle exception based on policy if (DomainUtil.HandleException(exc, layerExceptionPolicy)) throw; #endregion Handle transaction rollback and exception } return result; } #endregion #endregion #endregion Data Access Methods }//End Class } // end namespace
{ "content_hash": "8ca714b0bb4a93ff4d2f09a0faab5c5d", "timestamp": "", "source": "github", "line_count": 1834, "max_line_length": 278, "avg_line_length": 40.471101417666304, "alnum_prop": 0.6833234533304592, "repo_name": "Giten2004/netTiers", "id": "74442af211f69facb29f8e2ac9c4522378a7d851", "size": "74226", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Services/DocumentServiceBase.generated.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "620" }, { "name": "C#", "bytes": "331739" }, { "name": "CSS", "bytes": "9299" }, { "name": "JavaScript", "bytes": "18312" }, { "name": "XSLT", "bytes": "25193" } ], "symlink_target": "" }
namespace zxing { namespace qrcode { class MatrixUtil { private: MatrixUtil() {} static const int POSITION_DETECTION_PATTERN[7][7]; static const int POSITION_ADJUSTMENT_PATTERN[5][5]; static const int POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[40][7]; static const int TYPE_INFO_COORDINATES[16][2]; static const int VERSION_INFO_POLY; static const int TYPE_INFO_POLY; static const int TYPE_INFO_MASK_PATTERN; private: // Check if "value" is empty. static bool isEmpty(int value) { return value == 255; } //static bool isEmpty(int value) { return value == -1; } static void embedTimingPatterns(ByteMatrix& matrix); // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) static void embedDarkDotAtLeftBottomCorner(ByteMatrix& matrix); static void embedHorizontalSeparationPattern(size_t xStart, size_t yStart, ByteMatrix& matrix); static void embedVerticalSeparationPattern(size_t xStart, size_t yStart, ByteMatrix& matrix); // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are // almost identical, since we cannot write a function that takes 2D arrays in different sizes in // C/C++. We should live with the fact. static void embedPositionAdjustmentPattern(size_t xStart, size_t yStart, ByteMatrix& matrix); static void embedPositionDetectionPattern(size_t xStart, size_t yStart, ByteMatrix& matrix); // Embed position detection patterns and surrounding vertical/horizontal separators. static void embedPositionDetectionPatternsAndSeparators(ByteMatrix& matrix); // Embed position adjustment patterns if need be. static void maybeEmbedPositionAdjustmentPatterns(const Version& version, ByteMatrix& matrix); public: // Set all cells to -1. -1 means that the cell is empty (not set yet). static void clearMatrix(ByteMatrix& matrix) { matrix.clear((zxing::byte) -1); } // Embed basic patterns. On success, modify the matrix and return true. // The basic patterns are: // - Position detection patterns // - Timing patterns // - Dark dot at the left bottom corner // - Position adjustment patterns, if need be static void embedBasicPatterns(const Version& version, ByteMatrix& matrix); // Embed type information. On success, modify the matrix. static void embedTypeInfo(const ErrorCorrectionLevel& ecLevel, int maskPattern, ByteMatrix& matrix); // Embed version information if need be. On success, modify the matrix and return true. // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. static void maybeEmbedVersionInfo(const Version& version, ByteMatrix& matrix); // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. // For debugging purposes, it skips masking process if "getMaskPattern" is -1. // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. static void embedDataBits(const BitArray& dataBits, int maskPattern, ByteMatrix& matrix); // Return the position of the most significant bit set (to one) in the "value". The most // significant bit is position 32. If there is no bit set, return 0. Examples: // - findMSBSet(0) => 0 // - findMSBSet(1) => 1 // - findMSBSet(255) => 8 static int findMSBSet(int value); // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH // code is used for encoding type information and version information. // Example: Calculation of version information of 7. // f(x) is created from 7. // - 7 = 000111 in 6 bits // - f(x) = x^2 + x^1 + x^0 // g(x) is given by the standard (p. 67) // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 // Multiply f(x) by x^(18 - 6) // - f'(x) = f(x) * x^(18 - 6) // - f'(x) = x^14 + x^13 + x^12 // Calculate the remainder of f'(x) / g(x) // x^2 // __________________________________________________ // g(x) )x^14 + x^13 + x^12 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 // -------------------------------------------------- // x^11 + x^10 + x^7 + x^4 + x^2 // // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 // Encode it in binary: 110010010100 // The return value is 0xc94 (1100 1001 0100) // // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit // operations. We don't care if cofficients are positive or negative. static int calculateBCHCode(int value, int poly); // Make bit vector of version information. On success, store the result in "bits" and return true. // See 8.10 of JISX0510:2004 (p.45) for details. static void makeVersionInfoBits(const Version& version, BitArray& bits); // Make bit vector of type information. On success, store the result in "bits" and return true. // Encode error correction level and mask pattern. See 8.9 of // JISX0510:2004 (p.45) for details. static void makeTypeInfoBits(const ErrorCorrectionLevel& ecLevel, int maskPattern, BitArray& bits); // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On // success, store the result in "matrix" and return true. static void buildMatrix(const BitArray& dataBits, const ErrorCorrectionLevel &ecLevel, Version& version, int maskPattern, ByteMatrix& matrix); }; } } #endif //MATRIXUTIL_H
{ "content_hash": "d6d9e8d0823eeb2eec1e3dd3338290c5", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 104, "avg_line_length": 45.395348837209305, "alnum_prop": 0.6299521857923497, "repo_name": "ftylitak/qzxing", "id": "79ce8c498383aa3683278485d3545b98fdcc52cb", "size": "6283", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/zxing/zxing/qrcode/encoder/MatrixUtil.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "69570" }, { "name": "C++", "bytes": "1361979" }, { "name": "CMake", "bytes": "17672" }, { "name": "QMake", "bytes": "23280" }, { "name": "Shell", "bytes": "12188" } ], "symlink_target": "" }
<?php // Start of memcached v.2.0.1 /** * Represents a connection to a set of memcached servers. * @link http://php.net/manual/en/class.memcached.php */ class Memcached { /** * <p>Enables or disables payload compression. When enabled, * item values longer than a certain threshold (currently 100 bytes) will be * compressed during storage and decompressed during retrieval * transparently.</p> * <p>Type: boolean, default: <b>TRUE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_COMPRESSION = -1001; const OPT_COMPRESSION_TYPE = -1004; /** * <p>This can be used to create a "domain" for your item keys. The value * specified here will be prefixed to each of the keys. It cannot be * longer than 128 characters and will reduce the * maximum available key size. The prefix is applied only to the item keys, * not to the server keys.</p> * <p>Type: string, default: "".</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_PREFIX_KEY = -1002; /** * <p> * Specifies the serializer to use for serializing non-scalar values. * The valid serializers are <b>Memcached::SERIALIZER_PHP</b> * or <b>Memcached::SERIALIZER_IGBINARY</b>. The latter is * supported only when memcached is configured with * --enable-memcached-igbinary option and the * igbinary extension is loaded. * </p> * <p>Type: integer, default: <b>Memcached::SERIALIZER_PHP</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_SERIALIZER = -1003; /** * <p>Indicates whether igbinary serializer support is available.</p> * <p>Type: boolean.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HAVE_IGBINARY = 0; /** * <p>Indicates whether JSON serializer support is available.</p> * <p>Type: boolean.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HAVE_JSON = 0; const HAVE_SESSION = 1; const HAVE_SASL = 0; /** * <p>Specifies the hashing algorithm used for the item keys. The valid * values are supplied via <b>Memcached::HASH_*</b> constants. * Each hash algorithm has its advantages and its disadvantages. Go with the * default if you don't know or don't care.</p> * <p>Type: integer, default: <b>Memcached::HASH_DEFAULT</b></p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_HASH = 2; /** * <p>The default (Jenkins one-at-a-time) item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_DEFAULT = 0; /** * <p>MD5 item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_MD5 = 1; /** * <p>CRC item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_CRC = 2; /** * <p>FNV1_64 item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_FNV1_64 = 3; /** * <p>FNV1_64A item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_FNV1A_64 = 4; /** * <p>FNV1_32 item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_FNV1_32 = 5; /** * <p>FNV1_32A item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_FNV1A_32 = 6; /** * <p>Hsieh item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_HSIEH = 7; /** * <p>Murmur item key hashing algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const HASH_MURMUR = 8; /** * <p>Specifies the method of distributing item keys to the servers. * Currently supported methods are modulo and consistent hashing. Consistent * hashing delivers better distribution and allows servers to be added to * the cluster with minimal cache losses.</p> * <p>Type: integer, default: <b>Memcached::DISTRIBUTION_MODULA.</b></p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_DISTRIBUTION = 9; /** * <p>Modulo-based key distribution algorithm.</p> * @link http://php.net/manual/en/memcached.constants.php */ const DISTRIBUTION_MODULA = 0; /** * <p>Consistent hashing key distribution algorithm (based on libketama).</p> * @link http://php.net/manual/en/memcached.constants.php */ const DISTRIBUTION_CONSISTENT = 1; /** * <p>Enables or disables compatibility with libketama-like behavior. When * enabled, the item key hashing algorithm is set to MD5 and distribution is * set to be weighted consistent hashing distribution. This is useful * because other libketama-based clients (Python, Ruby, etc.) with the same * server configuration will be able to access the keys transparently. * </p> * <p> * It is highly recommended to enable this option if you want to use * consistent hashing, and it may be enabled by default in future * releases. * </p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_LIBKETAMA_COMPATIBLE = 16; const OPT_LIBKETAMA_HASH = 17; const OPT_TCP_KEEPALIVE = 32; /** * <p>Enables or disables buffered I/O. Enabling buffered I/O causes * storage commands to "buffer" instead of being sent. Any action that * retrieves data causes this buffer to be sent to the remote connection. * Quitting the connection or closing down the connection will also cause * the buffered data to be pushed to the remote connection.</p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_BUFFER_WRITES = 10; /** * <p>Enable the use of the binary protocol. Please note that you cannot * toggle this option on an open connection.</p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_BINARY_PROTOCOL = 18; /** * <p>Enables or disables asynchronous I/O. This is the fastest transport * available for storage functions.</p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_NO_BLOCK = 0; /** * <p>Enables or disables the no-delay feature for connecting sockets (may * be faster in some environments).</p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_TCP_NODELAY = 1; /** * <p>The maximum socket send buffer in bytes.</p> * <p>Type: integer, default: varies by platform/kernel * configuration.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_SOCKET_SEND_SIZE = 4; /** * <p>The maximum socket receive buffer in bytes.</p> * <p>Type: integer, default: varies by platform/kernel * configuration.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_SOCKET_RECV_SIZE = 5; /** * <p>In non-blocking mode this set the value of the timeout during socket * connection, in milliseconds.</p> * <p>Type: integer, default: 1000.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_CONNECT_TIMEOUT = 14; /** * <p>The amount of time, in seconds, to wait until retrying a failed * connection attempt.</p> * <p>Type: integer, default: 0.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_RETRY_TIMEOUT = 15; /** * <p>Socket sending timeout, in microseconds. In cases where you cannot * use non-blocking I/O this will allow you to still have timeouts on the * sending of data.</p> * <p>Type: integer, default: 0.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_SEND_TIMEOUT = 19; /** * <p>Socket reading timeout, in microseconds. In cases where you cannot * use non-blocking I/O this will allow you to still have timeouts on the * reading of data.</p> * <p>Type: integer, default: 0.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_RECV_TIMEOUT = 20; /** * <p>Timeout for connection polling, in milliseconds.</p> * <p>Type: integer, default: 1000.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_POLL_TIMEOUT = 8; /** * <p>Enables or disables caching of DNS lookups.</p> * <p>Type: boolean, default: <b>FALSE</b>.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_CACHE_LOOKUPS = 6; /** * <p>Specifies the failure limit for server connection attempts. The * server will be removed after this many continuous connection * failures.</p> * <p>Type: integer, default: 0.</p> * @link http://php.net/manual/en/memcached.constants.php */ const OPT_SERVER_FAILURE_LIMIT = 21; const OPT_AUTO_EJECT_HOSTS = 28; const OPT_HASH_WITH_PREFIX_KEY = 25; const OPT_NOREPLY = 26; const OPT_SORT_HOSTS = 12; const OPT_VERIFY_KEY = 13; const OPT_USE_UDP = 27; const OPT_NUMBER_OF_REPLICAS = 29; const OPT_RANDOMIZE_REPLICA_READ = 30; const OPT_REMOVE_FAILED_SERVERS = 35; /** * <p>The operation was successful.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_SUCCESS = 0; /** * <p>The operation failed in some fashion.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_FAILURE = 1; /** * <p>DNS lookup failed.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_HOST_LOOKUP_FAILURE = 2; /** * <p>Failed to read network data.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_UNKNOWN_READ_FAILURE = 7; /** * <p>Bad command in memcached protocol.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_PROTOCOL_ERROR = 8; /** * <p>Error on the client side.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_CLIENT_ERROR = 9; /** * <p>Error on the server side.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_SERVER_ERROR = 10; /** * <p>Failed to write network data.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_WRITE_FAILURE = 5; /** * <p>Failed to do compare-and-swap: item you are trying to store has been * modified since you last fetched it.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_DATA_EXISTS = 12; /** * <p>Item was not stored: but not because of an error. This normally * means that either the condition for an "add" or a "replace" command * wasn't met, or that the item is in a delete queue.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_NOTSTORED = 14; /** * <p>Item with this key was not found (with "get" operation or "cas" * operations).</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_NOTFOUND = 16; /** * <p>Partial network data read error.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_PARTIAL_READ = 18; /** * <p>Some errors occurred during multi-get.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_SOME_ERRORS = 19; /** * <p>Server list is empty.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_NO_SERVERS = 20; /** * <p>End of result set.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_END = 21; /** * <p>System error.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_ERRNO = 26; /** * <p>The operation was buffered.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_BUFFERED = 32; /** * <p>The operation timed out.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_TIMEOUT = 31; /** * <p>Bad key.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_BAD_KEY_PROVIDED = 33; const RES_STORED = 15; const RES_DELETED = 22; const RES_STAT = 24; const RES_ITEM = 25; const RES_NOT_SUPPORTED = 28; const RES_FETCH_NOTFINISHED = 30; const RES_SERVER_MARKED_DEAD = 35; const RES_UNKNOWN_STAT_KEY = 36; const RES_INVALID_HOST_PROTOCOL = 34; const RES_MEMORY_ALLOCATION_FAILURE = 17; /** * <p>Failed to create network socket.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_CONNECTION_SOCKET_CREATE_FAILURE = 11; /** * <p>Payload failure: could not compress/decompress or serialize/unserialize the value.</p> * @link http://php.net/manual/en/memcached.constants.php */ const RES_PAYLOAD_FAILURE = -1001; /** * <p>The default PHP serializer.</p> * @link http://php.net/manual/en/memcached.constants.php */ const SERIALIZER_PHP = 1; /** * <p>The igbinary serializer. * Instead of textual representation it stores PHP data structures in a * compact binary form, resulting in space and time gains.</p> * @link http://php.net/manual/en/memcached.constants.php */ const SERIALIZER_IGBINARY = 2; /** * <p>The JSON serializer. Requires PHP 5.2.10+.</p> * @link http://php.net/manual/en/memcached.constants.php */ const SERIALIZER_JSON = 3; const SERIALIZER_JSON_ARRAY = 4; const COMPRESSION_FASTLZ = 2; const COMPRESSION_ZLIB = 1; /** * <p>A flag for <b>Memcached::getMulti</b> and * <b>Memcached::getMultiByKey</b> to ensure that the keys are * returned in the same order as they were requested in. Non-existing keys * get a default value of NULL.</p> * @link http://php.net/manual/en/memcached.constants.php */ const GET_PRESERVE_ORDER = 1; const GET_ERROR_RETURN_VALUE = false; /** * (PECL memcached &gt;= 0.1.0)<br/> * Create a Memcached instance * @link http://php.net/manual/en/memcached.construct.php * @param $persistent_id [optional] * @param $callback [optional] */ public function __construct ($persistent_id, $callback) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Return the result code of the last operation * @link http://php.net/manual/en/memcached.getresultcode.php * @return int Result code of the last Memcached operation. */ public function getResultCode () {} /** * (PECL memcached &gt;= 1.0.0)<br/> * Return the message describing the result of the last operation * @link http://php.net/manual/en/memcached.getresultmessage.php * @return string Message describing the result of the last Memcached operation. */ public function getResultMessage () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Retrieve an item * @link http://php.net/manual/en/memcached.get.php * @param string $key <p> * The key of the item to retrieve. * </p> * @param callable $cache_cb [optional] <p> * Read-through caching callback or <b>NULL</b>. * </p> * @param float $cas_token [optional] <p> * The variable to store the CAS token in. * </p> * @return mixed the value stored in the cache or <b>FALSE</b> otherwise. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function get ($key, callable $cache_cb = null, &$cas_token = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Retrieve an item from a specific server * @link http://php.net/manual/en/memcached.getbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key of the item to fetch. * </p> * @param callable $cache_cb [optional] <p> * Read-through caching callback or <b>NULL</b> * </p> * @param float $cas_token [optional] <p> * The variable to store the CAS token in. * </p> * @return mixed the value stored in the cache or <b>FALSE</b> otherwise. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function getByKey ($server_key, $key, callable $cache_cb = null, &$cas_token = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Retrieve multiple items * @link http://php.net/manual/en/memcached.getmulti.php * @param array $keys <p> * Array of keys to retrieve. * </p> * @param array $cas_tokens [optional] <p> * The variable to store the CAS tokens for the found items. * </p> * @param int $flags [optional] <p> * The flags for the get operation. * </p> * @return mixed the array of found items or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function getMulti (array $keys, array &$cas_tokens = null, $flags = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Retrieve multiple items from a specific server * @link http://php.net/manual/en/memcached.getmultibykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param array $keys <p> * Array of keys to retrieve. * </p> * @param string $cas_tokens [optional] <p> * The variable to store the CAS tokens for the found items. * </p> * @param int $flags [optional] <p> * The flags for the get operation. * </p> * @return array the array of found items or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function getMultiByKey ($server_key, array $keys, &$cas_tokens = null, $flags = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Request multiple items * @link http://php.net/manual/en/memcached.getdelayed.php * @param array $keys <p> * Array of keys to request. * </p> * @param bool $with_cas [optional] <p> * Whether to request CAS token values also. * </p> * @param callable $value_cb [optional] <p> * The result callback or <b>NULL</b>. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function getDelayed (array $keys, $with_cas = null, callable $value_cb = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Request multiple items from a specific server * @link http://php.net/manual/en/memcached.getdelayedbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param array $keys <p> * Array of keys to request. * </p> * @param bool $with_cas [optional] <p> * Whether to request CAS token values also. * </p> * @param callable $value_cb [optional] <p> * The result callback or <b>NULL</b>. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function getDelayedByKey ($server_key, array $keys, $with_cas = null, callable $value_cb = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Fetch the next result * @link http://php.net/manual/en/memcached.fetch.php * @return array the next result or <b>FALSE</b> otherwise. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_END</b> if result set is exhausted. */ public function fetch () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Fetch all the remaining results * @link http://php.net/manual/en/memcached.fetchall.php * @return array the results or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function fetchAll () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Store an item * @link http://php.net/manual/en/memcached.set.php * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function set ($key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Store an item on a specific server * @link http://php.net/manual/en/memcached.setbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function setByKey ($server_key, $key, $value, $expiration = null) {} /** * @param $key * @param $expiration */ public function touch ($key, $expiration) {} /** * @param $server_key * @param $key * @param $expiration */ public function touchByKey ($server_key, $key, $expiration) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Store multiple items * @link http://php.net/manual/en/memcached.setmulti.php * @param array $items <p> * An array of key/value pairs to store on the server. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function setMulti (array $items, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Store multiple items on a specific server * @link http://php.net/manual/en/memcached.setmultibykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param array $items <p> * An array of key/value pairs to store on the server. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function setMultiByKey ($server_key, array $items, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Compare and swap an item * @link http://php.net/manual/en/memcached.cas.php * @param float $cas_token <p> * Unique value associated with the existing item. Generated by memcache. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_DATA_EXISTS</b> if the item you are trying * to store has been modified since you last fetched it. */ public function cas ($cas_token, $key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Compare and swap an item on a specific server * @link http://php.net/manual/en/memcached.casbykey.php * @param float $cas_token <p> * Unique value associated with the existing item. Generated by memcache. * </p> * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_DATA_EXISTS</b> if the item you are trying * to store has been modified since you last fetched it. */ public function casByKey ($cas_token, $server_key, $key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Add an item under a new key * @link http://php.net/manual/en/memcached.add.php * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key already exists. */ public function add ($key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Add an item under a new key on a specific server * @link http://php.net/manual/en/memcached.addbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key already exists. */ public function addByKey ($server_key, $key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Append data to an existing item * @link http://php.net/manual/en/memcached.append.php * @param string $key <p> * The key under which to store the value. * </p> * @param string $value <p> * The string to append. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function append ($key, $value) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Append data to an existing item on a specific server * @link http://php.net/manual/en/memcached.appendbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param string $value <p> * The string to append. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function appendByKey ($server_key, $key, $value) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Prepend data to an existing item * @link http://php.net/manual/en/memcached.prepend.php * @param string $key <p> * The key of the item to prepend the data to. * </p> * @param string $value <p> * The string to prepend. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function prepend ($key, $value) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Prepend data to an existing item on a specific server * @link http://php.net/manual/en/memcached.prependbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key of the item to prepend the data to. * </p> * @param string $value <p> * The string to prepend. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function prependByKey ($server_key, $key, $value) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Replace the item under an existing key * @link http://php.net/manual/en/memcached.replace.php * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function replace ($key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Replace the item under an existing key on a specific server * @link http://php.net/manual/en/memcached.replacebykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key under which to store the value. * </p> * @param mixed $value <p> * The value to store. * </p> * @param int $expiration [optional] <p> * The expiration time, defaults to 0. See Expiration Times for more info. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTSTORED</b> if the key does not exist. */ public function replaceByKey ($server_key, $key, $value, $expiration = null) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Delete an item * @link http://php.net/manual/en/memcached.delete.php * @param string $key <p> * The key to be deleted. * </p> * @param int $time [optional] <p> * The amount of time the server will wait to delete the item. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function delete ($key, $time = 0) {} /** * @param $keys * @param $time [optional] */ public function deleteMulti ($keys, $time) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Delete an item from a specific server * @link http://php.net/manual/en/memcached.deletebykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @param string $key <p> * The key to be deleted. * </p> * @param int $time [optional] <p> * The amount of time the server will wait to delete the item. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function deleteByKey ($server_key, $key, $time = 0) {} /** * @param $server_key * @param $keys * @param $time [optional] */ public function deleteMultiByKey ($server_key, $keys, $time) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Increment numeric item's value * @link http://php.net/manual/en/memcached.increment.php * @param string $key <p> * The key of the item to increment. * </p> * @param int $offset [optional] <p> * The amount by which to increment the item's value. * </p> * @return int new item's value on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function increment ($key, $offset = 1) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Decrement numeric item's value * @link http://php.net/manual/en/memcached.decrement.php * @param string $key <p> * The key of the item to decrement. * </p> * @param int $offset [optional] <p> * The amount by which to decrement the item's value. * </p> * @return int item's new value on success or <b>FALSE</b> on failure. * The <b>Memcached::getResultCode</b> will return * <b>Memcached::RES_NOTFOUND</b> if the key does not exist. */ public function decrement ($key, $offset = 1) {} /** * @param $server_key * @param $key * @param $offset [optional] * @param $initial_value [optional] * @param $expiry [optional] */ public function incrementByKey ($server_key, $key, $offset, $initial_value, $expiry) {} /** * @param $server_key * @param $key * @param $offset [optional] * @param $initial_value [optional] * @param $expiry [optional] */ public function decrementByKey ($server_key, $key, $offset, $initial_value, $expiry) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Add a server to the server pool * @link http://php.net/manual/en/memcached.addserver.php * @param string $host <p> * The hostname of the memcache server. If the hostname is invalid, data-related * operations will set * <b>Memcached::RES_HOST_LOOKUP_FAILURE</b> result code. * </p> * @param int $port <p> * The port on which memcache is running. Usually, this is * 11211. * </p> * @param int $weight [optional] <p> * The weight of the server relative to the total weight of all the * servers in the pool. This controls the probability of the server being * selected for operations. This is used only with consistent distribution * option and usually corresponds to the amount of memory available to * memcache on that server. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. */ public function addServer ($host, $port, $weight = 0) {} /** * (PECL memcached &gt;= 0.1.1)<br/> * Add multiple servers to the server pool * @link http://php.net/manual/en/memcached.addservers.php * @param array $servers * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. */ public function addServers (array $servers) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Get the list of the servers in the pool * @link http://php.net/manual/en/memcached.getserverlist.php * @return array The list of all servers in the server pool. */ public function getServerList () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Map a key to a server * @link http://php.net/manual/en/memcached.getserverbykey.php * @param string $server_key <p> * The key identifying the server to store the value on. * </p> * @return array <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function getServerByKey ($server_key) {} public function resetServerList () {} public function quit () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Get server pool statistics * @link http://php.net/manual/en/memcached.getstats.php * @return array Array of server statistics, one entry per server. */ public function getStats () {} /** * (PECL memcached &gt;= 0.1.5)<br/> * Get server pool version info * @link http://php.net/manual/en/memcached.getversion.php * @return array Array of server versions, one entry per server. */ public function getVersion () {} public function getAllKeys () {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Invalidate all items in the cache * @link http://php.net/manual/en/memcached.flush.php * @param int $delay [optional] <p> * Numer of seconds to wait before invalidating the items. * </p> * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. * Use <b>Memcached::getResultCode</b> if necessary. */ public function flush ($delay = 0) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Retrieve a Memcached option value * @link http://php.net/manual/en/memcached.getoption.php * @param int $option <p> * One of the Memcached::OPT_* constants. * </p> * @return mixed the value of the requested option, or <b>FALSE</b> on * error. */ public function getOption ($option) {} /** * (PECL memcached &gt;= 0.1.0)<br/> * Set a Memcached option * @link http://php.net/manual/en/memcached.setoption.php * @param int $option * @param mixed $value * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. */ public function setOption ($option, $value) {} /** * @param $options */ public function setOptions ($options) {} public function isPersistent () {} public function isPristine () {} } /** * @link http://php.net/manual/en/class.memcachedexception.php */ class MemcachedException extends RuntimeException { protected $message; protected $code; protected $file; protected $line; /** * (PHP 5 &gt;= 5.1.0)<br/> * Clone the exception * @link http://php.net/manual/en/exception.clone.php * @return void No value is returned. */ final private function __clone () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Construct the exception * @link http://php.net/manual/en/exception.construct.php * @param $message [optional] * @param $code [optional] * @param $previous [optional] */ public function __construct ($message, $code, $previous) {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the Exception message * @link http://php.net/manual/en/exception.getmessage.php * @return string the Exception message as a string. */ final public function getMessage () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the Exception code * @link http://php.net/manual/en/exception.getcode.php * @return mixed the exception code as integer in * <b>Exception</b> but possibly as other type in * <b>Exception</b> descendants (for example as * string in <b>PDOException</b>). */ final public function getCode () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the file in which the exception occurred * @link http://php.net/manual/en/exception.getfile.php * @return string the filename in which the exception was created. */ final public function getFile () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the line in which the exception occurred * @link http://php.net/manual/en/exception.getline.php * @return int the line number where the exception was created. */ final public function getLine () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the stack trace * @link http://php.net/manual/en/exception.gettrace.php * @return array the Exception stack trace as an array. */ final public function getTrace () {} /** * (PHP 5 &gt;= 5.3.0)<br/> * Returns previous Exception * @link http://php.net/manual/en/exception.getprevious.php * @return Exception the previous <b>Exception</b> if available * or <b>NULL</b> otherwise. */ final public function getPrevious () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * Gets the stack trace as a string * @link http://php.net/manual/en/exception.gettraceasstring.php * @return string the Exception stack trace as a string. */ final public function getTraceAsString () {} /** * (PHP 5 &gt;= 5.1.0)<br/> * String representation of the exception * @link http://php.net/manual/en/exception.tostring.php * @return string the string representation of the exception. */ public function __toString () {} } // End of memcached v.2.0.1 ?>
{ "content_hash": "45c7ebd3262fc30fee1c9fe3b25876a3", "timestamp": "", "source": "github", "line_count": 1224, "max_line_length": 107, "avg_line_length": 32.540849673202615, "alnum_prop": 0.6342957569671103, "repo_name": "evolution411/symfonyfos", "id": "0d5b72097f93a7626826267d54ae637313f019d1", "size": "39830", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Acme/HelloBundle/Resources/public/images/NetBeans 7.3/php/phpstubs/phpruntime/memcached.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2647" }, { "name": "Batchfile", "bytes": "68313" }, { "name": "CSS", "bytes": "115896" }, { "name": "HTML", "bytes": "9995101" }, { "name": "Java", "bytes": "163040" }, { "name": "JavaScript", "bytes": "25142" }, { "name": "PHP", "bytes": "3222652" }, { "name": "Perl", "bytes": "10177" }, { "name": "Python", "bytes": "3401" }, { "name": "Shell", "bytes": "129432" }, { "name": "XSLT", "bytes": "221100" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Cars.Models; using Cars.Web.Infrastructure.Peek.Web.Infrastructure.Mapping; namespace Cars.Web.Models { public class IndexViewModel : IMapFrom<Car> { [Required] [Display(Name = "Описание")] [StringLength(20, MinimumLength = 3, ErrorMessage = "Моля въведете валидна марка между {2} и {1} символа!")] public string Description { get; set; } [Display(Name = "Вносители")] public ICollection<Shipper> Shippers { get; set; } } }
{ "content_hash": "0cee1266c860c6e0f234f9080f4f0e87", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 116, "avg_line_length": 30.55, "alnum_prop": 0.679214402618658, "repo_name": "didimitrov/Cars", "id": "d6678e7fe40e4a697a06c299abfb4e3938998541", "size": "667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cars/Cars.Web/Models/IndexViewModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "99" }, { "name": "C#", "bytes": "66751" }, { "name": "CSS", "bytes": "1551" }, { "name": "HTML", "bytes": "5125" }, { "name": "JavaScript", "bytes": "11024" } ], "symlink_target": "" }
This document describes `DiagnosticSource`, a simple module that allows code to be instrumented for production-time logging of **rich data payloads** for consumption **within the process** that was instrumented. At runtime consumers can **dynamically discover** data sources and subscribe to the ones of interest. In addition to background on how the class works, this document also covers [naming conventions](#naming-conventions) and [best practices](#best-practices) when instrumenting code. ------------------------------------------- ## Relationship to Other Logging Facilities In addition to `DiagnosticSource`, there are two other logging systems provided by Microsoft: 1. `EventSource` [docs](https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource(v=vs.110).aspx) and [src](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs). `EventSource` has been available since V4.5 of the .NET Runtime and is what is used to instrument the runtime itself. It is designed to be fast and to be strongly typed (payloads are typed, named properties), and to interface with OS logging infrastructure like Event Tracing for Windows [(ETW)](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363668(v=vs.85).aspx) or [LTTng](http://lttng.org/) on Linux. 2. `ILogger` [src](https://github.com/aspnet/logging). A number of popular third party formatted string logging systems for .NET have been built including NLog, SeriLog, and Log4Net. The `ILogger` NuGet package is designed to 'wrap' any of these and hide from the instrumentation code which exact logging system is being used. Using this wrapper makes the most sense if your goal is to 'plug into' a logging pipeline that assumes one of these logging systems. `DiagnosticSource` has more architectural similarity to `EventSource`. The main difference is that `EventSource` assumes that the data being logged will **leave the process** and thus requires that **only serializable data** be logged. However, `DiagnosticSource` was designed to allow in-process tools to get at very rich data. Because the consumer is assumed to be within the same process, non-serializable types (e.g. `HttpResponseMessage` or `HttpContext`) can be passed, which gives the consumer a lot of potential data to work with. As explained in [DiagnosticSourceEventSource.cs](System/Diagnostics/DiagnosticSourceEventSource.cs), there is a bridge that pipes information from `DiagnosticSources` to an `EventSource`. Thus `EventSource` consumers can get at all `DiagnosticSource` events. While the data payloads from `DiagnosticSource` can't in general be passed through to the `EventSource` (because they are not serializable), there is a mechanism in the bridge that enables consumers to specify which fields to pass along to the `EventSource`. What this means is that in general it is not necessary to instrument a code site multiple times. By instrumenting with Diagnostic source, both clients that need the rich data (and thus use `DiagnosticListener`) as well as any consumers using `EventListeners` (or OS facilities like ETW) can get at the data. ---------------------------------------- ## Instrumenting with DiagnosticSource/DiagnosticListener Perhaps surprisingly, the heart of the `DiagnosticSource` logging architecture is not the `DiagnosticSource` class but rather the `DiagnosticListener` class which 'receives' the events. This is because the `DiagnosticSource` type is just an abstract base class that defines the methods needed to actually log events. It is the `DiagnosticListener` which holds the actual implementation. Thus the first step in instrumenting code with `DiagnosticSource` is to create a `DiagnosticListener`. For example: ```C# private static DiagnosticSource httpLogger = new DiagnosticListener("System.Net.Http"); ``` Notice that httpLogger is typed as a `DiagnosticSource`. This is because this code only cares about writing events and thus only cares about the `DiagnosticSource` methods that the `DiagnosticListener` implements. `DiagnosticListeners` are given names when they are created and this name should be the name of logical grouping of related events (typically the component). Later this name is used to find the Listener and subscribe to any of its events. Once you have an instance of a `DiagnosticSource`, logging is very straightforward. The interface consists of only two methods: ```C# bool IsEnabled(string name) void Write(string name, object value); ``` A typical call site will look like: ```C# if (httpLogger.IsEnabled("RequestStart")) httpLogger.Write("RequestStart", new { Url="http://clr", Request=aRequest }); ``` Already some of the architectural elements are being exposed, namely: 1. Every event has a `string` name (e.g. `RequestStart`), and exactly one `object` as a payload. 2. If you need to send more than one item, you can do so by creating an `object` with all information in it as properties. C#'s [anonymous type](https://msdn.microsoft.com/en-us/library/bb397696.aspx) feature is typically used to create a type to pass 'on the fly', and makes this scheme very convenient. 3. At the instrumentation site, you must guard the call to `Write()` with an `IsEnabled()` check on the same event name. Without this check, even when the instrumentation is inactive, the rules of the C# language require all the work of creating the payload `object` and calling `Write()` to be done, even though nothing is actually listening for the data. By guarding the `Write()` call, we make it efficient when the source is not enabled. ### Creating DiagnosticSources (Actually DiagnosticListeners) Perhaps confusingly you make a `DiagnosticSource` by creating a `DiagnosticListener`: ```C# static DiagnosticSource mySource = new DiagnosticListener("System.Net.Http"); ``` Basically a `DiagnosticListener` is a named place where a source sends its information (events). From an implementation point of view, `DiagnosticSource` is an abstract class that has the two instrumentation methods, and `DiagnosticListener` is something that implements that abstract class. Thus every `DiagnosticListener` is a `DiagnosticSource`, and by making a `DiagnosticListener` you implicitly make a `DiagnosticSource` as well. `DiagnosticListeners` have a name, which is used to represent the component associated with the event. Thus the event names only need to be unique within a component. ---------------------------------------- ## Best Practices ### Naming Conventions #### DiagnosticListener Names * CONSIDER - the likely scenarios for USING information when deciding how many `DiagnosticListener` to have and the events in each. Keep in mind that it is **very easy and efficient** to filter all the events in a particular listener so ideally the most important scenarios involve turning on whole listeners and not needing to filter for particular events. You may need to split a source into multiple smaller ones to achieve this, and this is OK. For example there are both incoming HTTP requests and outgoing HTTP requests and you may only need one or the other, so having a System.Net.Http.Incoming and System.Net.Http.Outgoing for each sub-case is good. * CONSIDER - the likely volume of events. High volume events may deserve their own `DiagnosticListener`. You don't really want to mix high volume and low volume events in the same listener unless they both support the same scenario. It is OK however to put several **low volume** events in a 'miscellaneous' listener, even if they support different scenarios if it simplifies things enough. * DO - Consider the scenario when picking the name for the `DiagnosticListener`. Often, this name is the component in which the `DiagnosticListener` lives, but **usage scenarios trump component naming**. You want it to be the case that users can correctly guess which listeners to activate knowing just their scenario. * DO - Make the name for the `DiagnosticListeners` **globally unique**. This is typically done by making the first part of the name the component (e.g. System.Net.Http) * DO - Use dots '.' to create multi-part names. This works well if the name is a Name of a component (which uses dots). * DO NOT - name the listener after the Listener (thus something like System.Net.HttpDiagnosticListener is bad). #### Event Names * DO - keep the names reasonably short (< 16 characters). Keep in mind that event names are already qualified by the Listener so the name only needs to be unique within a listener. Short names make `IsEnabled()` faster. * DO - use activities (see [Activity Users Guide](ActivityUserGuide.md)) for events that are marking the begining and end of an interval of time. The key value of Activities is that they indicate that they represent a DURATION, and they also track what 'caused' them (and thus logging systems can stitch together a 'causality graph'). * DO - If for some reason you can't use Activities, and your events mark the start and stop of an interval of time, use the 'Start' and 'Stop' suffixes on the events. ### Payloads * DO use the anonymous type syntax 'new { property1 = value1 ...}' as the default way to pass a payload *even if there is only one data element*. This makes adding more data later easy and compatible. * CONSIDER creating an explicit type for the payload. The main value for doing this is that the receiver can cast the received object to that type and immediately fetch fields (with anonymous types reflection must be used to fetch fields). This is both easier to program and more efficient. Thus in scenarios where there is likely high-volume filtering to be done by the logging listener, having this type available to do the cast is valuable. Note that this type needs to be made public (since the listener needs to see it), and should be under the namespace System.Diagnostics.DiagnosticSource.PayloadTypes. Note that if there is doubt about the value DO NOT create an explicit type, as you CAN convert from an anonymous type to a explicit type compatibly in the future, but once you expose the payload type you must keep it forever. The payload type should simply have C# 'TYPE NAME {get; set; }' properties (you can't use fields). You may add new properties as needed in the future. * CONSIDER in high volume cases (e.g. > 1K/sec) consider reusing the payload object instead of creating a new one each time the event is fired. This only works well if you already have locking or exclusive objects where you can remember the payload for the 'next' event to send easily and correctly (you are only saving an object allocation, which is not large). * CONSIDER - if you have an event that is so frequent that the performance of the logging is an important consideration, **and** you have only one data item **and** it is unlikely that you will ever have more data to pass to the event, **and** the data item is a normal class (not a value type) **then** you save some cost by simply by passing the data `object` directly without using an anonymous type wrapper. * DO - use standard names for particular payload items. (TODO: Put the list here as we define standard payload names). ### Filtering * DO - always enclose the `Write()` call in a call to `IsEnabled()` for the same event name. Otherwise a lot of setup logic will be called even if there is nothing listening for the event. * CONSIDER - enclosing `IsEnabled(string, object, object)` calls with pure `IsEnabled(string)` calls to avoid the extra cost of creating a context in case a consumer is not interested in such events at all. * CONSIDER - passing public named types instances to `IsEnabled()` overloads with `object` parameters to keep `IsEnabled()` as efficient as possible. * DO - when subscribing to `DiagnosticSource` with an advanced filter for event name and extended context, make sure the filter returns `true` for `null` context properties if the consumer is interested in at least some events with context. ### Other Conventions * DO NOT - make the `DiagnosticListener` public. There is no need to as subscribers will use the `AllListener` property to hook up. ---------------------------------------- ## Consuming Data with DiagnosticListener Up until now, this guide has focused on how to instrument code to generate logging information. In this section we focus on subscribing and decoding of that information. ### Discovery of DiagnosticListeners The first step in receiving events is to discover which `DiagnosticListeners` you are interested in. While it is possible to discover `DiagnosticListeners` at compile time by referencing static variables (e.g. like the `httpLogger` in the previous example), this is typically not flexible enough. Instead `DiagnosticListener` supports a way of discovering `DiagnosticListeners` that are active in the system at runtime. The API to accomplish this is the `AllListeners` `IObservable<DiagnosticListener>`. The `IObservable` interface is the 'callback' version of the `IEnumerable` interface. You can learn more about it at the [Reactive Extensions](https://msdn.microsoft.com/en-us/data/gg577609.aspx) site. In a nutshell, you have an object called an `IObserver` which has three callbacks, `OnNext`, `OnComplete` and `OnError`, and an `IObservable` has single method called `Subscribe` which gets passed one of these Observers. Once connected, the Observer gets callbacks (mostly `OnNext` callbacks) when things happen. By including the `System.Reactive.Core` NuGet package, you can get a bunch of useful extensions that make using `IObservable` nice. A typical use of the `AllListeners` static property looks like this: ```C# // We are using AllListeners to turn an Action<DiagnosticListener> into an IObserver<DiagnosticListener> static IDisposable listenerSubscription = DiagnosticListener.AllListeners.Subscribe(delegate (DiagnosticListener listener) { // We get a callback of every Diagnostics Listener that is active in the system (past present or future) if (listener.Name == "System.Net.Http") { // Here is where we put code to subscribe to the Listener. } }); // Typically you leave the listenerSubscription subscription active forever. // However when you no longer want your callback to be called, you can // call listenerSubscription.Dispose() to cancel your subscription to the IObservable. ``` This code basically creates a callback delegate and using the `AllListeners.Subscribe` method requests that that delegate be called for every active `DiagnosticListener` in the system. Typically you inspect the name of the listener and based on that, decide whether to subscribe to the listener or not. The code above is looking for our 'System.Net.Http' listener that we created previously. Like all calls to `Subscribe()`, this one returns an `IDisposable` that represents the subscription itself. Callbacks will continue to happen as long as nothing calls `Dispose()` on this subscription object. The above code never calls it, so it will receive callbacks forever. It is important to note that when you subscribe to `AllListeners`, you get a callback for ALL ACTIVE `DiagnosticListeners`. Thus, upon subscribing, you get a flurry of callbacks for all existing `DiagnosticListeners`, but as new ones are created, you get a callback for those as well. Thus you get a complete list of everything it is possible to subscribe to. Finally, note that the code above is taking advantage of convenience functionality in the `System.Reactive.Core` library. The `DiagnosticListener.AllListeners.Subscribe` method actually requires that it be passed an `IObserver<DiagnosticListener>`, which is a class that has three callbacks (`OnNext`, `OnError`, `OnComplete`), but we passed it an `Action<DiagnosticListener>`. The magic that makes this work is an extension method in `System.Reactive.Core` that takes the `Action` and from it makes an `IObserver` (called `AnonymousObserver`) which calls the `Action` in its `OnNext` callback. This glue is what makes the code concise. #### Subscribing to DiagnosticListeners A `DiagnosticListener` implements the `IObservable<KeyValuePair<string, object>>` interface, so you can call `Subscribe()` on it as well. Thus we can fill out the previous example a bit: ```C# static IDisposable networkSubscription = null; static IDisposable listenerSubscription = DiagnosticListener.AllListeners.Subscribe(delegate (DiagnosticListener listener) { if (listener.Name == "System.Net.Http") { lock(allListeners) { if (networkSubscription != null) networkSubscription.Dispose(); networkSubscription = listener.Subscribe((KeyValuePair<string, object> evnt) => Console.WriteLine("From Listener {0} Received Event {1} with payload {2}", networkListener.Name, evnt.Key, evnt.Value.ToString())); } } }); // At some point you may wish to dispose the networkSubscription. ``` In this example, after finding the 'System.Net.Http' `DiagnosticListener`, we create an action that prints out the name of the listener, event, and `payload.ToString()`. Notice a few things: 1. `DiagnosticListener` implements `IObservable<KeyValuePair<string, object>>`. This means on each callback we get a `KeyValuePair`. The key of this pair is the name of the event and the value is the payload `object`. In the code above we simply log this information to the console. 2. We keep track of our subscriptions to the `DiagnosticListener`. In this case we have a networkSubscription variable that remembers this, and if we get another 'creation' we unsubscribe the previous listener and subscribe to the new one. 3. We use locks. The `DiagnosticSource`/`DiagnosticListener` code is thread safe, but the callback code also needs to be thread safe. It is possible that two `DiagnosticListeners` with the same name are created at the same time (although that is a bit unexpected), so to avoid races we do updates of our shared variables under the protection of a lock. Once the above code is run, the next time a `Write()` is done on 'System.Net.Http' `DiagnosticListener` the information will be logged to the console. It is also important to note that subscriptions are independent of one another. Thus other code can do exactly the same thing as the code above, and thus generate two 'pipes' of the logging information. #### Decoding Payloads The `KeyvaluePair` that is passed to the callback has the event name and payload, but the payload is typed simply as an `object`. Odds are that you want to get at more specific data. There are two ways of doing this: 1. If the payload is a well known type (e.g. a `string`, or an `HttpMessageRequest`) then you can simply cast the `object` to the expected type (using the `as` operator so as not to cause an exception if you are wrong) and then access the fields. This is very efficient. 2. Use reflection API. For example, if we assume we have the method: ```C# /// Define a shortcut method that fetches a field of a particular name. static class PropertyExtensions { static object GetProperty(this object _this, string propertyName) { return _this.GetType().GetTypeInfo().GetDeclaredProperty(propertyName)?.GetValue(_this); } } ``` Then we could replace the `listener.Subscribe()` call above with the following code, to decode the payload more fully: ```C# networkSubscription = listener.Subscribe(delegate(KeyValuePair<string, object> evnt) { var eventName = evnt.Key; var payload = evnt.Value; if (eventName == "RequestStart") { var url = payload.GetProperty("Url") as string; var request = payload.GetProperty("Request"); Console.WriteLine("Got RequestStart with URL {0} and Request {1}", url, request); } }); ``` Note that using reflection is relatively expensive. However, using reflection is your only option if the payloads were generated using anonymous types. You can reduce this overhead by making fast, specialized property fetchers either using `PropertyInfo.CreateDelegate` or `ReflectEmit`, but that is beyond the scope of this document. (See the [PropertySpec](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs#L784) class used in the `DiagnosticSourceEventSource` for an example of a fast, delegate-based property fetcher.) #### Filtering In the example above the code uses the `IObservable.Subscribe()` method to hook up the callback, which causes all events to be given to the callback. However `DiagnosticListener` has overloads of `Subscribe()` that allow the controller to control which events get through. Thus we could replace the `listener.Subscribe()` call in the previous example with the following code: ```C# // Create the callback delegate Action<KeyValuePair<string, object>> callback = (KeyValuePair<string, object> evnt) => Console.WriteLine("From Listener {0} Received Event {1} with payload {2}", networkListener.Name, evnt.Key, evnt.Value.ToString()); // Turn it into an observer (using System.Reactive.Core's AnonymousObserver) Observer<KeyValuePair<string, object>> observer = new AnonymousObserver<KeyValuePair<string, object>>(callback); // Create a predicate (asks only for one kind of event) Predicate<string> predicate = (string eventName) => eventName == "RequestStart"; // Subscribe with a filter predicate IDisposable subscription = listener.Subscribe(observer, predicate); // subscription.Dispose() to stop the callbacks. ``` This very efficiently subscribes to only the 'RequestStart' events. All other events will cause the `DiagnosticSource.IsEnabled()` method to return `false`, and thus be efficiently filtered out. ##### Context-based Filtering Some scenarios require advanced filtering based on extended context. Producers may call `DiagnosticSource.IsEnabled()` overloads and supply additional event properties: ```C# if (httpLogger.IsEnabled("RequestStart", aRequest, anActivity)) httpLogger.Write("RequestStart", new { Url="http://clr", Request=aRequest }); ``` And consumers may use such properties to filter events more precisely: ```C# // Create a predicate (asks only for Requests for certains URIs) Func<string, object, object, bool> predicate = (string eventName, object context, object activity) => { if (eventName == "RequestStart") { HttpRequestMessage request = context as HttpRequestMessage; if (request != null) { return IsUriEnabled(request.RequestUri); } } return false; } // Subscribe with a filter predicate IDisposable subscription = listener.Subscribe(observer, predicate); ``` Note that producers are not aware of the filter a consumer has provided. `DiagnosticListener` will invoke the provided filter, omitting additional arguments if necessary, thus the filter should expect to receive a `null` context. Producers should enclose `IsEnabled()` calls with event name and context with pure `IsEnabled()` calls for event name, so consumers must ensure that their filter allows events without context to pass through. ---------------------------------------- ## Consuming DiagnosticSource Data with EventListeners and ETW The `System.Diagnostic.DiagnosticSource` NuGet package comes with a built in `EventSource` called Microsoft-Diagnostics-DiagnosticSource. This `EventSource` has the ability to subscribe to any `DiagnosticListener` as well as pluck off particular data items from `DiagnosticSource` payloads. Thus code that is using `System.Diagnostics.Tracing.EventListener` or ETW can get at any information logged with `DiagnosticSource`. See [DiagnosticSourceEventSource](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs) for more information on how to use it.
{ "content_hash": "c2de5971407363e462688ab18ba1f5c6", "timestamp": "", "source": "github", "line_count": 455, "max_line_length": 173, "avg_line_length": 53.85274725274725, "alnum_prop": 0.7520303636289434, "repo_name": "mmitche/corefx", "id": "eebc041a079f5ab7d105c627550559e4fa2373d9", "size": "24536", "binary": false, "copies": "28", "ref": "refs/heads/master", "path": "src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "280724" }, { "name": "ASP", "bytes": "1687" }, { "name": "Batchfile", "bytes": "20096" }, { "name": "C", "bytes": "3730054" }, { "name": "C#", "bytes": "166928159" }, { "name": "C++", "bytes": "117360" }, { "name": "CMake", "bytes": "77718" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groovy", "bytes": "50984" }, { "name": "HTML", "bytes": "653" }, { "name": "Makefile", "bytes": "13780" }, { "name": "OpenEdge ABL", "bytes": "137969" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "95072" }, { "name": "Python", "bytes": "1535" }, { "name": "Roff", "bytes": "9387" }, { "name": "Shell", "bytes": "119395" }, { "name": "Visual Basic", "bytes": "1001421" }, { "name": "XSLT", "bytes": "513537" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; /// <exclude /> public class OTEaseSineInOut : OTEase { /// <exclude /> public override float ease(float t, float b, float c, float d) { return -c / 2 * (Mathf.Cos(Mathf.PI * t / d) - 1) + b; } }
{ "content_hash": "8c3dad5c3863d14483b4b513d9b5096a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 20.53846153846154, "alnum_prop": 0.5917602996254682, "repo_name": "Vaskivo/CloneAndConquerRemake", "id": "d4c00cceaee71b00717a354e730d27f44e0d34ca", "size": "1930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Orthello/Standard Assets/OT/Tweening/OTEaseSineInOut.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2413" }, { "name": "C#", "bytes": "486864" }, { "name": "JavaScript", "bytes": "3273" } ], "symlink_target": "" }
/* globals process */ import fs from 'fs' import path from 'path' import globAll from 'glob-all' import chokidar from 'chokidar' import Promise, { promisify } from 'bluebird' import resolveTarget from './lib/resolve-target' import sourcesBases from './lib/sources-bases' import isGlob from './lib/is-glob' import trimQuotes from './lib/trim-quotes' import { copyDir, copyFile, remove, stat } from './lib/fs' Promise.config({ cancellation: true }) const defaults = { watch: false, delete: true, depth: Infinity, } /** * Synchronise files, directories and/or glob patterns, optionally watching for changes. * * @param {string|Array.<string>} sources - A list of files, directories and/or glob patterns. * @param {string} target - The destination directory. * @param {Object} [options] - An optional configuration object. * @param {bool} [options.watch=false] - Enable or disable watch mode. * @param {bool} [options.delete=true] - Whether to delete the `target`'s content initially. * @param {bool} [options.depth=Infinity] - Chokidars `depth` (If set, limits how many levels of subdirectories will be traversed). * @param {string} [options.transform=false] - A module path resolved by node's `require`. * @param {NotifyCallback} [notify] - An optional notification callback. * @returns {CloseFunc} - Returns a close function which cancels active promises and watch mode. */ // eslint-disable-next-line consistent-return const syncGlob = (sources, target, options = {}, notify = () => {}) => { if (!Array.isArray(sources)) { // eslint-disable-next-line no-param-reassign sources = [sources] } // eslint-disable-next-line no-param-reassign sources = sources.map(trimQuotes) if (typeof options === 'function') { // eslint-disable-next-line no-param-reassign notify = options // eslint-disable-next-line no-param-reassign options = {} } // eslint-disable-next-line no-param-reassign options = { ...defaults, ...options, } const notifyError = (err) => { notify('error', err) } const bases = sourcesBases(sources) const resolveTargetFromBases = resolveTarget(bases) const { depth, watch } = options let { transform } = options if (typeof depth !== 'number' || isNaN(depth)) { notifyError('Expected valid number for option "depth"') return false } if (transform) { let transformPath = transform try { require.resolve(transformPath) } catch (err) { transformPath = path.join(process.cwd(), transformPath) try { require.resolve(transformPath) } catch (err2) { notifyError(err2) } } // eslint-disable-next-line transform = require(transformPath) } // Initial mirror const mirrorInit = [ promisify(globAll)(sources.map(source => (isGlob(source) === -1 && fs.statSync(source).isDirectory() ? `${source}/**` : source))) .then(files => files.map(file => path.normalize(file))), ] if (options.delete) { mirrorInit.push(remove(target) .then(() => { notify('remove', [target]) }) .catch(notifyError) ) } else { notify('no-delete', target) } let mirrorPromiseAll = Promise.all(mirrorInit) .then(([files]) => Promise.all(files.map((source) => { const resolvedTarget = resolveTargetFromBases(source, target) return stat(source) .then((stats) => { let result if (stats.isFile()) { result = copyFile(source, resolvedTarget, transform) } else if (stats.isDirectory()) { result = copyDir(source, resolvedTarget) } if (result) { result = result.then(() => { notify('copy', [source, resolvedTarget]) }) } return result }) .catch(notifyError) }))) .then(() => { notify('mirror', [sources, target]) }) .catch(notifyError) .finally(() => { mirrorPromiseAll = null }) let watcher let activePromises = [] const close = () => { if (watcher) { watcher.close() watcher = null } if (mirrorPromiseAll) { mirrorPromiseAll.cancel() mirrorPromiseAll = null } if (activePromises) { activePromises.forEach((promise) => { promise.cancel() }) activePromises = null } } // Watcher to keep in sync from that if (watch) { watcher = chokidar.watch(sources, { persistent: true, depth, ignoreInitial: true, awaitWriteFinish: true, }) watcher.on('ready', notify.bind(undefined, 'watch', sources)) .on('all', (event, source) => { const resolvedTarget = resolveTargetFromBases(source, target) let promise switch (event) { case 'add': case 'change': promise = copyFile(source, resolvedTarget, transform) break case 'addDir': promise = copyDir(source, resolvedTarget) break case 'unlink': case 'unlinkDir': promise = remove(resolvedTarget) break default: return } activePromises.push(promise .then(() => { const eventMap = { add: 'copy', addDir: 'copy', change: 'copy', unlink: 'remove', unlinkDir: 'remove', } notify(eventMap[event] || event, [source, resolvedTarget]) }) .catch(notifyError) .finally(() => { if (activePromises) { const index = activePromises.indexOf(promise) if (index !== -1) { activePromises.slice(index, 1) } } promise = null }) ) }) .on('error', notifyError) process.on('SIGINT', close) process.on('SIGQUIT', close) process.on('SIGTERM', close) } return close } export default syncGlob /** * This callback notifies you about various steps, like: * - **copy:** File or directory has been copied to `target`. * - **remove:** File or directory has been removed from `target`. * - **no-delete:** No initial deletion of `target`s contents. * - **mirror:** Initial copy of all `sources` to `target` done. * - **watch:** Watch mode has started. * - **error:** Any error which may occurred during program execution. * * @callback NotifyCallback * @param {string} type - The type of notification. * @param {...any} args - Event specific variadic arguments. */ /** * A cleanup function which cancels all active promises and closes watch mode if enabled. * * @typedef {function} CloseFunc */
{ "content_hash": "f7cdc468bf8f7a109698d039112e2af6", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 131, "avg_line_length": 27.076305220883533, "alnum_prop": 0.5971521803619104, "repo_name": "AndyOGo/node-sync-glob", "id": "3013ed0739665cd4b244ff032b6fbf320772a66a", "size": "6742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "36533" } ], "symlink_target": "" }
# include <boost/type_traits/add_reference.hpp> # include <boost/type_traits/add_const.hpp> # include <boost/mpl/int.hpp> # include <boost/static_assert.hpp> # include <boost/python/refcount.hpp> # include <cstddef> namespace boost { namespace python { namespace detail { template <std::size_t> struct return_arg_pos_argument_must_be_positive # if defined(__GNUC__) && __GNUC__ >= 3 || defined(__EDG__) {} # endif ; struct return_none { template <class T> struct apply { struct type { static bool convertible() { return true; } PyObject *operator()( typename value_arg<T>::type ) const { return none(); } }; }; }; } template < std::size_t arg_pos=1 , class Base = default_call_policies > struct return_arg : Base { private: BOOST_STATIC_CONSTANT(bool, legal = arg_pos > 0); public: typedef typename mpl::if_c< legal , detail::return_none , detail::return_arg_pos_argument_must_be_positive<arg_pos> // we could default to the base result_converter in case or // arg_pos==0 since return arg 0 means return result, but I // think it is better to issue an error instead, cause it can // lead to confusions >::type result_converter; template <class ArgumentPackage> static PyObject* postcall(ArgumentPackage const& args, PyObject* result) { // In case of arg_pos == 0 we could simply return Base::postcall, // but this is redundant BOOST_STATIC_ASSERT(arg_pos > 0); result = Base::postcall(args,result); if (!result) return 0; Py_DECREF(result); return incref( detail::get(mpl::int_<arg_pos-1>(),args) ); } }; template < class Base = default_call_policies > struct return_self : return_arg<1,Base> {}; }} // namespace boost::python #endif // RETURN_ARG_DWA2003719_HPP
{ "content_hash": "4599b17154e906ee8d27da30b5bd11ea", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 76, "avg_line_length": 24.57471264367816, "alnum_prop": 0.5556594948550047, "repo_name": "darwin/upgradr", "id": "76be50ae5fe548bdb1facba71607bff7f56447f7", "size": "2565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ieaddon/Upgradr/boost/python/return_arg.hpp", "mode": "33261", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Page { /// <summary> /// Brings page to front (activates tab). /// </summary> [CommandResponse(ProtocolName.Page.BringToFront)] [SupportedBy("Chrome")] public class BringToFrontCommandResponse { } }
{ "content_hash": "85a957404ff043614dafd76e1e43c3c0", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 56, "avg_line_length": 22.75, "alnum_prop": 0.7692307692307693, "repo_name": "MasterDevs/ChromeDevTools", "id": "37d0bcd2c19c3740377334b63c465604c09811ab", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/ChromeDevTools/Protocol/Chrome/Page/BringToFrontCommandResponse.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1135040" } ], "symlink_target": "" }
export Root from './containers/Root'; export BodyAttributes from './components/BodyAttributes'; export createStore from './lib/createStore'; export prepareRoutesWithTransitionHooks from './lib/prepareRoutesWithTransitionHooks'; export * from './lib/route-helper'; export * from './lib/constants'; export getHttpClient from './lib/getHttpClient'; export { set404StatusCode, setStatusCode } from './lib/actions'; export * from './lib/errorUtils';
{ "content_hash": "2736fe145a692fe9f29afeffcdf5546d", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 86, "avg_line_length": 49.44444444444444, "alnum_prop": 0.7752808988764045, "repo_name": "TrueCar/gluestick", "id": "3574ddcc2a515f2e30ddeb9060f65e1131380c4a", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "packages/gluestick/shared/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1334" }, { "name": "HTML", "bytes": "2763" }, { "name": "JavaScript", "bytes": "536659" }, { "name": "Shell", "bytes": "2793" } ], "symlink_target": "" }
namespace WebFrontend.Models { public class CloseModel { public int Id { get; set; } public decimal AmountPaid { get; set; } } }
{ "content_hash": "6ef3d3c3baffbebacfe9951d8a781a9c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 19.625, "alnum_prop": 0.5923566878980892, "repo_name": "edumentab/cqrs-starter-kit", "id": "d146b134368e0ee3529d658fa6c4cd596d37d5a6", "size": "159", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sample-app/WebFrontend/Models/CloseModel.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP.NET", "bytes": "102" }, { "name": "C#", "bytes": "110703" }, { "name": "CSS", "bytes": "963" }, { "name": "HTML", "bytes": "8290" }, { "name": "JavaScript", "bytes": "281" }, { "name": "TSQL", "bytes": "1585" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b4d28e6001552d0531e0cfd2da94fbe4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "fb854cdb2cd8f580171f249cd942f1d921036be0", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Ocotea/Ocotea valerioides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// TODO: this is special because it gets imported during build. // // TODO: 17.0.3 has not been released to NPM; // It exists as a placeholder so that DevTools can support work tag changes between releases. // When we next publish a release (either 17.0.3 or 17.1.0), update the matching TODO in backend/renderer.js export default '17.0.3';
{ "content_hash": "f68787bee0b578e2f7e7622cebad42c4", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 108, "avg_line_length": 42.875, "alnum_prop": 0.7376093294460642, "repo_name": "acdlite/react", "id": "69b37a19f037981efec20516715e57edd3828881", "size": "531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/shared/ReactVersion.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5225" }, { "name": "C++", "bytes": "44278" }, { "name": "CSS", "bytes": "70235" }, { "name": "CoffeeScript", "bytes": "16554" }, { "name": "HTML", "bytes": "115342" }, { "name": "JavaScript", "bytes": "5541727" }, { "name": "Makefile", "bytes": "189" }, { "name": "Python", "bytes": "259" }, { "name": "Shell", "bytes": "3829" }, { "name": "TypeScript", "bytes": "19904" } ], "symlink_target": "" }
#pragma once #include <fstream> #include <list> #include <string> #include <memory> using namespace std; #include "wator/layer.hpp" #include <opencv2/core/core.hpp> namespace Wator { /** * NeuralNetParam. **/ struct ImageLayerParam { string root_ = "data/retina/"; }; class CoulombLayer; class EinsteinLayer; class ImageLayer :public LayerInput { public: /** * Constructor **/ explicit ImageLayer(); /** * load * @return None. **/ virtual void load(bool train); private: void pump(void); void dump(const std::vector<cv::Mat> &planes); private: cv::Mat mat_; ImageLayerParam param_; const list<string> extension_; }; }
{ "content_hash": "76c9c81ae4eb82d67e361e2dd54775ba", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 54, "avg_line_length": 21.1, "alnum_prop": 0.523696682464455, "repo_name": "WatorVapor/wator", "id": "6752d43511c16990c8f3a9b4a42a5d673fe2ef41", "size": "2351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/wator/layer_image.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "64282" }, { "name": "CMake", "bytes": "757" }, { "name": "Makefile", "bytes": "318" } ], "symlink_target": "" }
package edu.clemson.rsrg.prover.absyn.iterators; import edu.clemson.rsrg.prover.absyn.PExp; import java.util.NoSuchElementException; /** * <p> * A {@code PExpSubexpressionIterator} defines the interface for classes that iterate over the sub-expressions of a * {@link PExp}, with the ability to get a version of the original {@code PExp} in which any given sub-expression has * been replaced with another. * </p> * * @author Hampton Smith * * @version 2.0 */ public interface PExpSubexpressionIterator { /** * <p> * This method returns {@code true} <strong>iff</strong> there are additional sub-expressions. I.e., returns * {@code true} <strong>iff</strong> {@link #next()} would return an element rather than throwing an exception. * </p> * * @return {@code true} if the iterator has more elements, {@code false} otherwise. */ boolean hasNext(); /** * <p> * This method returns the next sub-expression./p> * * @return The next element in the iteration. * * @throws NoSuchElementException * If there are no further subexpressions. */ PExp next(); /** * <p> * This method returns a version of the original {@link PExp} (i.e., the {@code PExp} over whose sub-expressions we * are iterating) with the sub-expression most recently returned by {@link #next()} replaced with * {@code newExpression}. * </p> * * @param newExpression * The argument to replace the most recently returned one with. * * @return The new version. */ PExp replaceLast(PExp newExpression); }
{ "content_hash": "281c1b1b2f95714b47cefbd403652603", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 119, "avg_line_length": 30.072727272727274, "alnum_prop": 0.6408706166868199, "repo_name": "yushan87/RESOLVE", "id": "c68bfde5a419ec689e4ff79d6d8e99a93241394f", "size": "2023", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/java/edu/clemson/rsrg/prover/absyn/iterators/PExpSubexpressionIterator.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "29622" }, { "name": "Java", "bytes": "3971554" }, { "name": "Mathematica", "bytes": "6449" }, { "name": "Ruby", "bytes": "1558" }, { "name": "Shell", "bytes": "3815" } ], "symlink_target": "" }
import { combineReducers } from 'redux'; import BodyReducer from './body.reducer'; import UiReducer from './ui/ui.reducer'; export default combineReducers({ ui: UiReducer, body: BodyReducer });
{ "content_hash": "1c5da22d1d16b6046c4653d0221c82f3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 41, "avg_line_length": 22.555555555555557, "alnum_prop": 0.7192118226600985, "repo_name": "ryanjamesmcgill/yourtime", "id": "d0e220cf48e3427ade60970579ee4d1feb5f09c1", "size": "203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/redux/reducers/product/serviceform/serviceform.reducer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "148182" }, { "name": "JavaScript", "bytes": "386371" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Category: main | Maria.Recipes &mdash; Keto Enthusiast, Indian Food Lover </title> <meta property="og:title" content="Category: main | Maria .Recipes &mdash; Keto Enthusiast, Indian Food Lover " /> <meta name="twitter:title" content="Category: main | Maria .Recipes &mdash; Keto Enthusiast, Indian Food Lover " /> <meta name="description" content="Category: main"> <meta name="description" property="og:description" content="Category: main" /> <meta name="twitter:description" content="Category: main" /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@your_handler" /> <meta property="og:url" content="/categories/main/" /> <!--<meta property="og:image" content="https://farm1.staticflickr.com/313/31662446346_b9070c8fa2_o_d.jpg" />--> <meta name="twitter:image" content="" /> <meta name="author" content="Maria .Recipes" /> <meta name="copyright" content="Copyright by Maria .Recipes. All Rights Reserved." /> <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="stylesheet" href="/assets/css/Dropdown.css"> <link rel="stylesheet" href="/assets/css/demonstration.css"> <link rel="canonical" href="/categories/main/"> <link rel="alternate" type="application/rss+xml" title="" href="/feed.xml"> <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js"></script> <script> WebFont.load({ google: { families: ['Oswald:400,700', 'Patrick Hand:400', 'Abel:400', 'Droid Serif:400,700', 'Yellowtail:400'] } }); </script> </head> <body> <section class="delicious"> <header class="header clear"> <div class="blog-info clear"> <a href="" class="blog-logo" onclick="return false;"> <img src="/assets/svg/dummy-logo.svg" alt="Maria .Recipes" /> </a> <div class="blog-titles"> <strong><a href="/">Maria .Recipes</a></strong> <span>Keto Enthusiast, Indian Food Lover</span> </div> </div> <div class="clr"></div> <div class="search" role="search"> <div class="search-holder clear"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0px" y="0px" viewBox="0 0 80 80" xml:space="preserve"><path fill="#ddd" d="M55.4 33.8c0-5.9-2.1-11-6.3-15.2s-9.3-6.3-15.2-6.3 -11 2.1-15.2 6.3 -6.3 9.3-6.3 15.2 2.1 11 6.3 15.2 9.3 6.3 15.2 6.3 11-2.1 15.2-6.3S55.4 39.8 55.4 33.8zM80 73.8c0 1.7-0.6 3.1-1.8 4.3C77 79.4 75.5 80 73.8 80c-1.7 0-3.2-0.6-4.3-1.8L53 61.7c-5.7 4-12.1 6-19.2 6 -4.6 0-9-0.9-13.1-2.7s-7.8-4.2-10.8-7.2S4.4 51.2 2.7 47 0 38.4 0 33.8s0.9-9 2.7-13.1 4.2-7.8 7.2-10.8 6.6-5.4 10.8-7.2S29.3 0 33.8 0s9 0.9 13.1 2.7 7.8 4.2 10.8 7.2 5.4 6.6 7.2 10.8 2.7 8.6 2.7 13.1c0 7.1-2 13.4-6 19.2l16.5 16.5C79.4 70.7 80 72.1 80 73.8z"/></svg> <input type="text" id="search-input" placeholder="search..."> </div> <ul id="results-container" class="results-container"></ul> </div> <nav role="navigation" class="mainmenu"> <ul class="dropdown clear"> <li><a href="/" >Home</a></li> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <li><a href="" onclick="return false;" ><span>Español&nbsp;<img style="float:right;" class="crazyimage" src="https://farm2.staticflickr.com/2069/1757117582_126ceab48f_o_d.gif"></span></a> <ul> <li> <a href="/espanol/recetas"><span>Recetas</span></a> </li><li> <a href="/espanol/infodieta"><span>Info Dieta<span></a> </li><li> <a href="/espanol/libro"><span>Libro<span></a> </li> </li> </ul> </li> <!-- --> <!-- --> <!-- --> <!-- --> <li> <a href="/products/" onclick="return false;" ><span>Keto Products</span></a> <ul> <li> <a href="/products/indianVegMenu"><span>Indian Veg Menu</span></a> </li><li> <a href="/products/indianNonVegMenu"><span>Indian NonVeg Menu<span></a> </li><li> <a href="/products/customizedMealPlan"><span>Customized Meal Plan<span></a> </li><li> <a href="/products/recommendedBooks"><span>Recommended Books<span></a> </li><li> <a href="/products/ketoShoppingList"><span>Keto Shopping List<span></a> </li><li> </li> </ul> </li> <li><a href="/blog/" >Blog</a></li> <!-- --> <li><a href="/about/" >About</a></li> <!-- --> <li><a href="/subscribe/" color="red">Subscribe</a></li> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> </ul> </nav> <div class="clr"></div> </header> <main role="main"> <section class="index"> <section class="posts clear" itemscope itemtype="http://schema.org/Blog"> <div class="section-title"><span>Posts From Category: main</span></div> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2018-02-05T00:00:00+01:00" itemprop="datePublished">5 Feb, 2018</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/stirFry">Low Carb Stir Fry</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4606/40087628312_b37a117202_o_d.jpg" /> I made this stir fry the other day and it came out truly delicious. For an even lower carb version, you can use regular tofu and substitute the cashews for peanuts. If you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 1 cup of broccoli florets (90 g) * 2 servings of <a href="http://maria.recipes/tofu">Soy-free Tofu</a> * 3 tbsp coconut oil * 1 tbsp sesame oil (or more coconut oil) * 1/2 brown onion, chopped (50-60 g) * 1 dried red chilli * 1 medium red bell pepper, chopped (120 g) * 1 tsp ginger paste * 2 tbsp soy sauce (or coconut aminos) * 1 oz cashew nuts (raw or roasted) * Optional: one star anise * Salt to taste (about 1/4 tsp) * Black pepper to taste * Optional: pinch of stevia (equivalent to 1/2 tsp sugar) * 1/2 tbsp lemon juice * Coriander to garnish <!-- --> * **Process** 1. Cook the broccoli until just fork tender. I cooked it in the microwave with a little water and salt for about 6-7 minutes, stirring a little in between. 2. Warm up two tablespoons of coconut oil in a pan over medium-high heat. Once hot, sautée the [tofu](http://maria.recipes/tofu) until golden (about 5 minutes). Take out and reserve. 3. Add the rest of the oil in the pan. Once hot, add the onions, red chili and star anise and a little salt. Cook for about 5 minutes until brown, stirring frequently. 4. Add the ginger paste and cook, stirring, for one minute. 5. Add the red bell pepper with a little salt, reduce the heat to medium and cook for 2-3 minutes until it gets a bit softer. 6. Add the broccoli, stevia and soy sauce. Mix, cover and cook for about two minutes. 7. Add the cooked tofu. Cook for 2-3 minutes everything together. 8. Turn off the stove, add the lemon juice, check the salt and serve with coriander. * **Nutritional information**, _for half the recipe_ * 485 kCal * 23 g total carbs * **15 g net carbs** * 8 g fiber * **18 g protein** * 76 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-12-11T00:00:00+01:00" itemprop="datePublished">11 Dec, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/salmonSalad">Smoked Salmon Salad</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4525/38998872582_e3774018f2_o_d.jpg" /> I love smoked salmon. It makes for some of the best salads ever. This is one of my favorite and easier combinations. Just a few ingredients and you get something simple and delicious! And if you want, you can fry the onion first, which will make it even yummier. If you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 3 cups (90 g) mixed lettuce, chopped * 1/8 small red onion, finely chopped * 75 g smoked salmon, chopped * 1/4 cup (40 g) feta cheese, crumbled * 1/2 avocado, sliced * 1 tbsp capers * 1 tbsp extra virgin coconut oil * 3 large eggs * 1/2 tsp lemon juice * Salt and pepper <!-- --> * **Process** 1. Get a big bowl. 2. Mix everything. 3. Eat it! * **Nutritional information**, _for the whole recipe_ * 488 kCal * 14.1 g total carbs * **5.9 g net carbs** * 8.2 g fiber * **22.6 g protein** * 40 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-09-03T00:00:00+02:00" itemprop="datePublished">3 Sep, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/escabecheEng">Tuna/Chicken &quot;Escabeche&quot;</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4390/36812027506_f94bbdef5c_o_d.jpg" /> My favorite meal as a kid was, hands down, "Pollo en escabeche": Chicken cooked in an oil and vinegar sauce, left to sit in the fridge for a few days for the flavors to be even better. It is very easy to make and only requires a few ingredients. In this occasion I made it with tuna, but you can use the same amount of chicken breast, add one chicken stock cube and cook for a little longer. And if you aren't a big fan of vinegar, you can substitute some (or all) of it for lemon juice (although it will have more carbs!). If you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 4 Tuna pieces, raw (500 g) * 2 medium onions, sliced (200 g) * 3 garlic cloves, chopped (optional) * Optional: zest of one lemon * 1/3 tsp salt * 1 tsp dried thyme * 2 tbsp chopped fresh parsley (optional) * 1 bayleaf * 1/2 tsp whole black pepper * 100 mL extra virgin olive oil * 100 (or 125 in my case!) of apple cider vinegar <!-- --> * **Process** 1. Mix all the ingredients in a saucepan and let it marinate for at least 3 hours, preferably overnight. Try to use a small saucepan so that the tuna is covered in the onion and sauce (if it doesn't cover it all the way it is ok, it will release liquid as it cooks). 2. Scoop out the tuna and leave on the side. Then, put the saucepan over medium low heat, cover and, when it starts to boil, reduce to very low heat and cook for about 30 minutes, for the onions to soften. 3. Add the tuna back into the pan, move everything around to ensure the tuna is covered, and let it cook for about 15 minutes or until no longer raw. Be careful, it overcooks very fast and you might end up with very tough tuna! 4. Take it off the stove and leave it covered. Once cooled down, put in the fridge and let it sit there for at least 24 hours, and upto 1-2 weeks. 5. Serve cold or at room temperature with salad and/or with cauliflower rice. * **Nutritional information**, _per serving (serves 4)_ * 415 kCal * 6.4 g total carbs * **5.2 g net carbs** * 1.2 g fiber * **30 g protein** * 29.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-07-30T00:00:00+02:00" itemprop="datePublished">30 Jul, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenMirch">Chicken Mirchwala</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4308/35872816070_61f413b491_o_d.jpg" /> This one is my boyfriend's creation: a roasted spicy chicken with spices and melt-in-the-mouth red bell peppers. Perfect for serving for guests - just add some fatty side dish and you will have the perfect keto meal! If you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 7 pieces of chicken thighs (1000 g, with skin and bone) * 2 tbsp olive oil * 1 medium red bell pepper (120g), sliced * 1 medium brown onion (110), sliced * 1/3 tsp salt * 1/2 tsp garam masala * 1/2 tsp turmeric * 1 tsp ground coriander * 1/4 tsp black pepper * 1/2 tsp or red chili powder (or more to taste) * 1/3 tsp chaat masala (optional) * 1/3 tsp chana masala (optional) * Fresh coriander for garnishing <!-- --> * **Process** 1. First, preheat your oven at 200ºC. Meanwhile mix the pepper and onion with the chaat masala. Alternately you can add a good pinch of salt, pepper and cayenne. 2. In a separate plate, rub the chicken with the oil, then add the spices and salt. Mix well. 3. In your baking dish, put a bed of the vegetables, then the chicken on top. 4. Cook in the oven for 45 minutes, turn the chicken pieces around, and cook for another 45 minutes. Optional: about 15 minutes before you take it out, add some chana masala. 5. Let it sit for 5 minutes, garnish with fresh coriander and serve. * **Nutritional information**, _per piece of chicken and sauce_ * 220 kCal * 3.3 g total carbs * **2.3 g net carbs** * 1.1 g fiber * **28 g protein** * 10 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-06-11T00:00:00+02:00" itemprop="datePublished">11 Jun, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/roastedTomatoSalad">Roasted Tomato Salad</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4206/35081777392_d0f3ee9eb5_o_d.jpg" /> This salad using roasted tomatoes is delicious and perfect for a lunchbox or as a sidedish if you have guests. And you can add some seeds or some bacon for extra flavor and crunch! And if you like my recipes, don’t forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the Keto Recipe Recommender. * 1 serving of <a href="http://maria.recipes/roastedTomato">Roasted tomatoes</a>, including its sauce * 3 cups (90g) of mixed lettuce * 30 g goat cheese (or other type) * 2 eggs, boiled * 1/3 small red onion, thinly sliced <!-- --> * **Process** 1. Mix everything. 2. Use the roasted tomato sauce as dressing. * **Nutritional information**, _for the whole recipe_ * 456 kCal * 10.6 g total carbs * **7.6 g net carbs** * 3 g fiber * **21.1 g protein** * 36.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-30T00:00:00+02:00" itemprop="datePublished">30 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenSalad">Chicken Salad</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4246/34605649540_f7f99b75f0_o_d.jpg" /> Making keto lunch boxes can be a real struggle. Keto food can be delicious, but not everything is easily packed, so I often have to resort to salads. I am a simple salad gal, but my bae considers spinach to be "rabbit food", so I have to up my game when I make a salad for him... and that is how this beauty was born! With chicken, bacon, avocado and mayo, as keto as it can get! And if you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 3 cups of lettuce (90g) * 60 g chicken breast, cooked (half a breast) * 30 g bacon, cooked * 1 boiled egg * 1/2 avocado * 2 tbsp mayonnaise * 1/2 tsp tomato purée * 1/3 tsp Dijon mustard * 1 tsp lemon juice * Stevia to taste (equivalent to 1/2 tsp sugar) * Optional: chipotle chili * Freshly ground black pepper <!-- --> * **Process** 1. Mix the mayo, tomato purée, mustard, lemon, stevia, chili and black pepper with a generous pinch of salt until you have a smooth dressing. 2. Put all the ingredients into a plate. Top with your dressing. Eat. * **Nutritional information**, _for the whole recipe_ * 592 kCal * 11.5 g total carbs * **3.7 g net carbs** * 7.9 g fiber * **25.9 g protein** * 50.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-24T00:00:00+02:00" itemprop="datePublished">24 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/eggfreeOmelet">Egg free Spinach Omelet</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4249/34801212716_b76e0a433a_o_d.jpg" /> Not eating eggs when on a ketogenic diet can be very taxing, since most breakfast involve eggs. But now, you can make low carb and egg free omelets, customising the filling to your taste. And if you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 1/6 cup (2 tbsp + 2 tsp) chickpea flour (20 g) * 1/6 cup protein powder, flavor free (18 g) (I use <a href="http://amzn.to/2nAykTb">unflavored whey</a>) * 1/9 cup (1 tbsp + 2 tsp) flax seeds, ground (18g) * 1/8 tsp turmeric * 1/2 cup water * 3 oz (90 g) of goat cheese * 3 cups (90g) of fresh spinach * 3 tbsp oil * Pinch of salt and pepper <!-- --> * **Process** 1. Put half of the oil in a non stick pan on medium heat. Add the spinach with salt and pepper and cook for two minutes until wilted, then transfer to a plate and divide into three. 2. Whisk the chickpea flour, flax meal, protein powder and water with salt and pepper (add the water slowly to avoid overdoing it, and add more if necessary); you should end up with a thick batter. Put the other half of the oil in the pan and add one third of the mixture. 3. Move the pan to ensure it covers the whole pan, then in one half put the spinach and the cheese. 4. Cook on medium-low until the egg is almost set, then fold on itself. 5. Take out of the pan, proceed in the same manner for the other two omelets and serve. * **Nutritional information**, _for one omelet (one third of the recipe)_ * 342 kCal * 9.8 g total carbs * **5.1 g net carbs** * 4.6 g fiber * **18.3 g protein** * 26.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-16T00:00:00+02:00" itemprop="datePublished">16 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/blueCheeseSalad">Blue Cheese Salad</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4161/33851704074_3047be692a_o_d.jpg" /> A low carb salad perfect for your lunchbox, or for one of those lazy days when you dont feel like cooking. Don't forget to [subscribe](http://maria.recipes/subscribe) to get access to the **Keto Recipe Recommender**. * 3 cups of lettuce, chopped (90g) * 40 g roquefort or blue cheese, cubed * A handful of walnuts, chopped (30g) * 2 tbsp of flax seeds or hemp hearts (20g) * 1/3 tsp Dijon mustard * 1 tbsp extra virgin olive oil * 1/2 tbsp apple cider vinegar or lemon juice * Stevia to taste * Salt and black pepper to taste <!-- --> * **Process** 1. Mix the oil, vinegar, mustard, salt, pepper and a bit of stevia. You should end up with a bittersweet dressing. 2. Mix all the ingredients. 3. Dress the salad and serve. * **Nutritional information**, _for the whole recipe_ * 572 kCal * 12.5 g total carbs * **4.1 g net carbs** * 8.4 g fiber * **17.8 g protein** * 52.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-09T00:00:00+02:00" itemprop="datePublished">9 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/garlicShrimp">Fried Garlic Shrimp</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4184/34433776712_7792ef03a3_o_d.jpg" /> A very popular way of making shrimp in Spain is "al ajillo", meaning sauteed in olive oil with garlic and some cayenne pepper. A 10 minute meal perfect for those who don't like cooking or don't have much time for it! And if you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 3/4 cup (135g) of raw, peeled shrimp * 2 tbsp olive oil * 2 cloves of garlic, thinly sliced * 1-2 whole dried cayenne pepper * Optional: fresh parsley to garnish * Salt to taste <!-- --> * **Process** 1. Put the oil in a small pan over medium-high heat. Add the garlic and cayenne. 2. When the garlic is brown (not burnt!), add the shrimp. Cook for about 2-3 minutes until they are no longer raw. 3. Turn off the stove, add the salt and serve. * **Nutritional information**, _for the whole recipe_ * 337 kCal * 2.5 g total carbs * **2.4 g net carbs** * 0.1 g fiber * **19.8 g protein** * 28.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-05T00:00:00+02:00" itemprop="datePublished">5 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/seekhKebab">Lazy Seekh Kebab</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4180/34339135961_bc655fa89c_o_d.jpg" /> This is what I call my Lazy Seekh Kebab: just mix up some spices with meat, then cook it in the pan with veggies. No tandoori, no long cooking process, but still incredible flavor! And if you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 300 g minced lamb or beef (20% fat) * 1 small onion (70g) * 100 g red bell pepper (or mixed red-green-yellow) * 2 tbsp chopped coriander * 1/2 tsp garam masala * 1/2 tsp turmeric powder * 1/2 tsp cumin powder * 1/2 tsp coriander powder * 1/2 tsp red chili powder (or to taste) * 1/2 tsp salt * 1/4 tsp garlic powder * 1/4 tsp ginger powder * 1/2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a> <!-- --> * **Process** 1. Chop half the onion into very small pieces. Then mix it with the meat, coriander and spices. 2. Mix the meat with your hands, then form them into sausage shaped kebabs. 3. Chop the rest of the vegetables. 4. Put 1/2 tbsp oil in a pan on high heat, then add the vegetables and cook for 2 minutes. 5. Now lower the heat to medium, add in the kebabs and cover with a lid. 6. Cook for about 2 minutes, then turn the kebabs 90 degrees and move the veggies so they don't burn. Proceed until you have done all four sides. 7. Serve with some mint chutney. * **Nutritional information**, _for half the recipe_ * 631 kCal * 27.8 g total carbs * **4.9 g net carbs** * 22.9 g fiber * **25.3 g protein** * 51.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-05T00:00:00+02:00" itemprop="datePublished">5 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/eggKathiRoll">Keto Egg Kathi Roll</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4155/33603992043_2f7e487f62_o_d.jpg" /> Another Indian Streetfood, keto-fied: Egg Kathi Roll, made with flax roti. Delicious! For more Indian Streetfood, check out my <a href="http://maria.recipes/ketoMomo">Keto Momo recipe</a> and my <a href="http://maria.recipes/kathiRoll">Paneer Kathi Roll</a>! And if you like my recipes, don't forget to [subscribe](http://maria.recipes/subscribe), which will also give you access to the **Keto Recipe Recommender**. * 2 eggs * Two <a href="http://maria.recipes/flaxRoti">Flax Roti</a> * 4 tsp <a href="http://amzn.to/2nRguh4">coconut oil</a>, one for each flax roti * 1 tbsp yogurt (10% fat) * 1/2 cup of fresh coriander * 1/2 clove of garlic * 1/4 tsp ginger paste * 1/16 tsp cumin powder * 1/8 tsp chaat masala (can sub with a good pinch of salt) * 1/4 cup of mixed shredded cabbage (10g), green pepper (10g), green chili (to taste) and red onion (5g) * 1/4 tsp lemon juice * Pinch of red chili powder or to taste * 1/4 tsp chaat masala (can sub with 1/4 tsp salt) * 1/2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a> <!-- --> * **Process** 1. Grind the yogurt, coriander, garlic and ginger with the 1/8 tsp cumin and the 1/4 tsp chaat masala to make the Green chutney. 2. Make the flax roti, adding 1 tsp of oil to the pan when you cook them. 3. Mix the vegetables with the rest of the spices and the lemon juice. 4. Put 1/2 tbsp oil in a pan on high heat, then add the vegetable mixture and cook for about 2-3 minutes. Meanwhile, mix the eggs with a pinch of salt. 5. Add the egg mixture into the cooked veggies and scramble them until they are no longer raw. 5. Make your rolls: take one flax roti, spread a good amount of chutney, add 1/2 of the scramble-veggie mixture and close it. Done! * **Nutritional information**, _for two rolls (the whole recipe)_ * 631 kCal * 27.8 g total carbs * **4.9 g net carbs** * 22.9 g fiber * **25.3 g protein** * 51.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-02T12:00:00+02:00" itemprop="datePublished">2 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/kathiRoll">Keto Paneer Kathi Roll</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4155/33568674003_607384294b_o_d.jpg" /> If you like Indian Streetfood like I do, you are in for a real treat. This Kathi Roll will not disappoint you one bit. And for a vegan version, simply substitute the Paneer for Tofu or Tempeh (and add a bit more oil when cooking it). For more Indian Streetfood, check out my <a href="http://maria.recipes/ketoMomo">Keto Momo recipe</a>! * Four servings of <a href="http://maria.recipes/paneerTikka">Paneer Tikka</a> * 2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a>, for cooking the paneer * Four <a href="http://maria.recipes/flaxRoti">Flax Roti</a> * 4 tsp <a href="http://amzn.to/2nRguh4">coconut oil</a>, one for each flax roti * 2 tbsp yogurt (10% fat) * 1 cup of fresh coriander * 1 clove of garlic * 1/2 tsp ginger paste * 1/8 tsp cumin powder * 1/4 tsp chaat masala (can sub with a good pinch of salt) * 1/3 cup shredded cabbage (35g) * 1/4 small red onion, sliced thinly (15g) * 1/3 green pepper, sliced thinly (40g) * 1 green chili, deseeded, thinly sliced (chili to taste) * 1 tsp lemon juice * 1/4 tsp red chili powder or to taste * 3/4 tsp chaat masala (can sub with 1/4 tsp salt) <!-- --> * **Process** 1. Make the paneer tikka in a pan, using 2 tbsp coconut oil in total; it is best to cook it in two batches. 2. Grind the yogurt, coriander, garlic and ginger with the 1/8 tsp cumin and the 1/4 tsp chaat masala to make the Green chutney. 3. Make the flax roti, adding 1 tsp of oil to the pan when you cook them. 4. Mix the vegetables with the rest of the spices and the lemon juice. 5. Make your rolls: take one flax roti, spread a good amount of chutney, add 1/4 of the Paneer Tikka, top with 1/4 of the vegetable mix and close it. Done! * **Nutritional information**, _per Kathi roll_ * 519 kCal * 18.1 g total carbs * **6 g net carbs** * 12.1 g fiber * **17.6 g protein** * 44.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-02T10:00:00+02:00" itemprop="datePublished">2 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/veganmacncheese">Keto Vegan, Paleo Mac &#39;N Cheese</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4183/34021920910_370c665b19_o_d.jpg" /> If you don't eat cheese for ethical reasons or because you have a sensitivity, give a go at my Vegan Mac And Cheese, Ketofied with cauliflower. Although different to the original, its creaminess will surprise you! * 1/2 medium cauliflower head, bite-sized pieces (300g) * 2 tbsp nutritional yeast (24g) * 1/3 cup of hemp hearts (or use raw almonds) * 1/3 cup raw sunflower seeds * 1/3 cup unsweetened almond milk * 1 tsp lemon juice * 1/4 tsp Dijon mustard * Salt and black pepper * Optional: chives or other herbs <!-- --> * **Process** 1. Optional step: soak the seeds for a couple of hours. 2. Boil or steam the cauliflower until just fork tender. Do not overcook it! 3. Preheat the oven to 180C. 4. Mix all the ingredients except the cauliflower to form a paste. It will be quite thick. Then mix in the cauliflower. 5. Put into a greased baking tray. 5. Bake for about 30 minutes until the top is nice and golden. * **Nutritional information**, _per serving (serves 3)_ * 243 kCal * 13.1 g total carbs * **6.7 g net carbs** * 6.4 g fiber * **14.7 g protein** * 16.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-01T12:00:00+02:00" itemprop="datePublished">1 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/kathiRollSpa">Paneer Kathi Roll, Ceto</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4155/33568674003_607384294b_o_d.jpg" /> Si te gusta la comida rápida (streetfood) de india, esta te va a encantar. Este Kathi Roll (rollito picante de queso y verdura) está tan rico como el original. Y para hacerlo vegano, simplemente sustituye el Paneer por tofu o Tempeh (y agrega un poco más de aceite al cocinarlo). Para más recetas indias de este tipo, échale un vistazo a mis <a href="http://maria.recipes/momoCeto">Momos Cetogénicos</a>! * Cuatro raciones de <a href="http://maria.recipes/paneerTikkaSpa">Paneer Tikka</a> * 2 cdas de <a href="http://amzn.to/2nK2mEP">aceite de coco</a>, para cocinar el paneer * Four <a href="http://maria.recipes/rotiLino">Roti de lino</a> * 4 cditas <a href="http://amzn.to/2nK2mEP">aceite de coco</a>, una para cada roti de lino * 2 cdas yogur (10% grasa) * 1 taza de cilantro fresco * 1 diente de ajo * 1/2 cdita de pasta de jengibre * 1/8 cdita comino en polvo * 1/4 cdita de Chaat masala (lo puedes sustituir por un buen pellizco de sal) * 1/3 taza de repollo picado fino (35g) * 1/4 cebolla roja pequeña, picada fina (15g) * 1/3 pimiento verde, en tiras finas (40g) * 1 chili verde fresco, sin semillas, picado fino (o cantidad al gusto) * 1 cdita de zumo de limón * 1/4 cdita de chili seco o al gusto * 3/4 cdita de chaat masala (la puedes sustituir por 1/4 cdita de sal) <!-- --> * **Elaboración** 1. Prepara el Paneer Tikka en una sartén, empleando 2 cucharadas de aceite de coco; lo mejor es hacerlo en dos tandas. 2. Bate el yogur, cilantro, ajo, jengibre, comino y 1/4 tsp chaat masala para hacer el Chutney (salsa). 3. Prepara los Rotis poniendo una cucharadita de aceite en la sartén al cocinarlos. 4. Mezcla las verduras con el resto de especias y el zumo de limón. 5. Prepara tus rollitos: toma un roti de lino, extiende chutney por encima, pon 1/4 del paneer y después agrégale 1/4 de las verduras, ciérralo y ya está listo! * **Información Nutricional**, _por Kathi roll_ * 519 kCal * 18.1 g H de C totales * **6 g H de C netos** * 12.1 g fibra * **17.6 g proteina** * 44.9 g grasa </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-01T11:00:00+02:00" itemprop="datePublished">1 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenAlfredo">Chicken Alfredo</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2840/34378943725_c659445fca_o_d.jpg" /> Alfredo is a classic Pasta dish that people often avoid because it is full of cream and cheese... Which is good news for us, keto-ers! Simply use zoodles instead of pasta and you will end up with a delicious, 15 minute meal. * 2 medium zucchini (400g), spiralized to form zoodles * 150 g chicken breast, in strips * 3/4 cup heavy whipping cream (180g) * 2/3 cup Parmesan cheese, grated (60g) * 2 tbsp butter * 3/4 tsp onion powder * 3/4 tsp garlic powder * 1/4 chicken bouillon cube * Black pepper to taste <!-- --> * **Process** 1. Put the butter in the pan and use it to brown the chicken, which should take about 5 minutes. 2. Add the zoodles and cook another 2 minutes until they get a bit soft (do not overcook or they will release water). 3. Optional: take out the chicken and zoodles from the pan, then add the cream and cook about 5 minutes to reduce it. 4. Add all the ingredients into the pan and cook it together for 1 minute or so. 5. Enjoy the creamy goodness. * **Nutritional information**, _for 1/3 of the recipe_ * 451 kCal * 7.4 g total carbs * **5.9 g net carbs** * 1.5 g fiber * **20.8 g protein** * 37.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-01T10:00:00+02:00" itemprop="datePublished">1 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/macncheese">Keto Mac &#39;N Cheese</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2825/33568674093_fb60b7e0dc_o_d.jpg" /> My take at Mac And Cheese, Ketofied with cauliflower. Even the vegetable haters will give in to this cheesiness delight! * 1 medium head of cauliflower, cut into bite-sized pieces (600g) * 2,5 heaping tbsp of cream cheese (75g) * 1,5 cups of shredded cheddar (170g) * 3/4 cup heavy whipping cream (180g) * 1/4 tsp Dijon mustard * Salt and black pepper * Optional: chives or other herbs <!-- --> * **Process** 1. Boil or steam the cauliflower until just fork tender. Do not overcook it! 2. Preheat the oven to 180C. 3. Mix all the ingredients except the cauliflower to form a paste. It will be quite thick. Then mix in the cauliflower. It will seem a bit too thick to mix in but don't worry - when the cheese melts, it will all be good. 4. Put into a greased baking tray. 5. Bake for about 30 minutes until the top is nice and golden. * **Nutritional information**, _per serving (serves 4)_ * 418 kCal * 9.7 g total carbs * **6.7 g net carbs** * 3 g fiber * **15.5 g protein** * 36.8 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-01T09:00:00+02:00" itemprop="datePublished">1 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenRoquefort">Chicken with Roquefort (Blue cheese)</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2814/34407070285_b2edafeaf3_o_d.jpg" /> A very simple meal. My mother used to make this for us for dinner in the weekdays, since it barely took any time but was delicious. Enjoy it with some [salad](http://maria.recipes/simpleSalad) or with [cauliflower rice](http://maria.recipes/cauliflowerRice) on the side. * 2 skinless chicken breasts, cubed (240g) * 20-25 g roquefort or blue cheese * 60 g heavy whipping cream * 2 tbsp olive oil * 1 cup of canned and drained mushrooms (160g) * Salt, pepper <!-- --> * **Process** 1. Warm up the oil, then add the chicken to brown with some salt and pepper for about 2-3 minutes. 2. Add the mushrooms and cook everything on low until the chicken is no longer raw. 3. Meanwhile, mix or blend the cheese with the cream. Add 1-2 tbsp of water if necessary (but no more as it thins out when you add it to the pan later). 4. Now, add the sauce to the pan, let it all cook together for a minute, and serve. * **Nutritional information**, _for half the recipe_ * 422 kCal * 5 g total carbs * **3.1 g net carbs** * 1.9 g fiber * **29.4 g protein** * 31.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-05-01T09:00:00+02:00" itemprop="datePublished">1 May, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/mushroomAlfredo">Mushroom Alfredo</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4168/34254392242_bb4d069f61_o_d.jpg" /> Alfredo is a classic Pasta dish that people often avoid because it is full of cream and cheese... Which is good news for us, keto-ers! Simply use zoodles instead of pasta and you will end up with a delicious, 15 minute meal. * 2 medium zucchini (400g), spiralized to form zoodles * 2 cups of whole white mushrooms (200g), cut into bite sized pieces * 2/3 cup heavy whipping cream (180g) * 3/4 cup Parmesan cheese, grated (60g) * 2 tbsp butter * 3/4 tsp onion powder * 3/4 tsp garlic powder * 1/4 vegetable bouillon cube * 1/2 Scoop of neutral flavor Whey Powder * Black pepper to taste <!-- --> * **Process** 1. Put the butter in the pan and use it to cook the mushrooms until tender (about 5 minutes). 2. Add the zoodles and cook another 2 minutes until they get a bit soft (do not overcook or they will release water). 3. Optional: take out the mushrooms and zoodles from the pan, then add the cream and cook about 5 minutes to reduce it. 4. Add all the ingredients into the pan and cook it together for 1 minute or so. 5. Enjoy the creamy goodness. * **Nutritional information**, _for 1/3 of the recipe_ * 437 kCal * 19.4 g total carbs * **7.5 g net carbs** * 2.1 g fiber * **19.4 g protein** * 36.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-29T09:00:00+02:00" itemprop="datePublished">29 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/greekSalad">Greek Salad (3 ways)</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2831/33493809574_b43abab688_o_d.jpg" /> A simple summery salad that you can customize to fit into your nutritional restrictions. I am suggesting a version with eggs and another one egg-free, but you could use chicken instead of eggs, and if you are a vegan, you could substitute the Feta cheese for Tofu feta (tofu cubed and marinated in apple cider vinegar, lemon, salt and oregano), adding some extra oil. * 1 small cucumber, chopped (160g) * 1 small tomato, chopped (100g) * 1/4 small red onion, chopped (15g) * 10 black olives, preferably kalamata (30g) * 50 g feta cheese, cubed * 2 tbsp <a href="amzn.to/2otU1I8">hemp hearts</a> (30g) OR 2 boiled eggs * Dried or fresh oregano * 1 tbsp extra virgin olive oil * 1/2 tbsp apple cider vinegar * Salt and pepper to taste <!-- --> * **Process** 1. Mix the ingredients and eat. * **Nutritional information**, _for the whole recipe_ * If using hemp seeds: * 521 kCal * 13.8 g total carbs * **8.5 g net carbs** * 5.2 g fiber * **19.8 g protein** * 44 g fat * If using eggs: * 482 kCal * 11.4 g total carbs * **8.2 g net carbs** * 3.2 g fiber * **21.8 g protein** * 38.5 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-26T10:00:00+02:00" itemprop="datePublished">26 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/pizzaBbq">Pizza Pollo BBQ (ceto)</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4166/33894618680_b6c9dc00a3_o_d.jpg" /> This is seriously the best pizza. You have to try! * 1 base de pizza, como mi <a href="http://maria.recipes/ketoPizzaSpa">Masa de Pizza</a> * 4 cdas de <a href="http://maria.recipes/bbqSpa">salsa barbacoa ceto</a> (1/8 de la salsa de la receta) * 2/3 taza de mozzarella rallada (80g) * 80 g pollo crudo, en trocitos * 20 g cebolla roja, en trozos finos * Cilantro fresco <!-- --> * **Elaboración** 1. Prepara la base de la pizza según tu receta. 2. Saca la masa del horno, cúbrela con salsa BBQ, agrega la mozzarella, después pon el pollo y la cebolla y mételo al horno. 3. Cocínala hasta que el pollo ya no esté crudo (unos 5-10 minutos). 4. Sácala, agrega el cilantro fresco y disfruta. * **Información nutricional**, * _por media pizza_ * 434 kCal * **7.4 g H de C netos** * 24.1 g fibra * 31.5 g H de C totales * **27.4 g proteina** * 28.5 g grasa * _mitad de toppings_ * 192 kCal * 4.3 g H de C netos * 0.8 g fibra * 5 g H de C totales * **19 g proteina** * 10.4 g grasa </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-26T10:00:00+02:00" itemprop="datePublished">26 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/bbqPizza">BBQ-chicken pizza</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4166/33894618680_b6c9dc00a3_o_d.jpg" /> This is seriously the best pizza. You have to try! * 1 pizza base, such as my <a href="http://maria.recipes/ketoPizza">Flax Pizza</a> * 4 tbsp of <a href="http://maria.recipes/bbq">keto BBQ sauce</a> (1/8 of the sauce recipe) * 2/3 cup shredded mozzarella (80g) * 80 g raw chicken, chopped * 20 g red onion, thinly sliced * Fresh coriander <!-- --> * **Process** 1. Make the pizza base as per your recipe. 2. Take out the cooked pizza base, top with the BBQ sauce, then the mozzarella, then the chicken and onion. Put it back in the oven. 3. Cook until the chicken is no longer raw (about 5-10 minutes). 4. Take it out, top with fresh coriander and enjoy. * **Nutritional information**, * _half a pizza_ * 434 kCal * **7.4 g net carbs** * 31.5 g total carbs * 24.1 g fiber * **27.4 g protein** * 28.5 g fat * _toppings only_ * 192 kCal * **4.2 g net carbs** * 5 g total carbs * 0.8 g fiber * **19 g protein** * 10.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-26T09:00:00+02:00" itemprop="datePublished">26 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tunaSalad">Keto Tuna Salad</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2875/33468271463_0ff5c26126_o_d.jpg" /> A very simple tuna salad for when you don´t feel like cooking (which happens to me more often then I would like to admit!). * 1/3 can of tuna in brine, solids only (55g) * 1 boiled egg * 2 cups of shredded lettuce (90-100g) * 30 g (1 oz) cheddar, edam or similar cheese * 1 small tomato, chopped (100g) * 1/4 small onion, chopped (18g) * 1.5 tbsp olive oil * 1 tbsp apple cider vinegar * Optional add-ins for the dressing: Dijon mustard, Stevia, basil leaves * Salt and pepper to taste <!-- --> * **Process** 1. Mix the ingredients for the dressing. 2. Chop all the veggies, top with the tuna, egg and cheese, dress and serve. * **Nutritional information**, _for the whole recipe_ * 453 kCal * **5.1 g net carbs** * 8.4 g total carbs * 3.3 g fiber * **26 g protein** * 35.5 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-25T09:00:00+02:00" itemprop="datePublished">25 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenRice">Keto Chicken Fried Rice</a></h2> <div class="post-content"> <img src="https://farm5.staticflickr.com/4194/34278802555_bf15dfe80f_o_d.jpg" /> I am all about fast recipes lately. This one takes 15-20 minutes, including the chopping time! If you like fried rice, try my <a href="http://maria.recipes/mushroomRice">Mushroom fried rice</a>! * 1 and 1/2 cups of <a href="maria.recipes/cauliflowerRice">cauli-rice</a> * 1 egg * 1 medium spring onion, chopped (15g) * 2 tbsp chopped green or red bell pepper (20g) * 1 deseeded chili chopped, or to taste * 1/2 tsp ginger paste * 1.5 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a> * 0.5 tbsp sesame oil * 2/3 tbsp soy sauce * 90 g chicken breast, chopped * 1/2 star anise, whole (optional, but gives very nice chinese flavor) * Salt, black pepper to taste <!-- --> * **Process** 1. Warm up the oil and use it to fry the white part of the spring onions, the chili, star anise and the bell pepper. 2. After about 5 minutes, when the spring onion is golden, add ginger and cook for 1 minute. 3. Then, add the chicken and brown it for about 2-3 minutes. 4. Now add the cauli-rice with some black pepper and salt (or you can sprinkle about 1/8 of a chicken bouillon cube). Cook for about 2 minutes. 5. Add the soy sauce and cook another 2-3 minutes or until the cauli-rice is tender. 6. Turn off the stove, add the green parts of the onions and serve. * **Nutritional information**, _whole recipe_ * 473 kCal * **7.7 g net carbs** * 12.1 g total carbs * 4.4 g fiber * **30.3 g protein** * 34.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-20T00:00:00+02:00" itemprop="datePublished">20 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/vegChili">Fast Veg Chili</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2912/34027770331_47fcc61d56_o_d.jpg" /> In 15 minutes you can make this easy and tasty vegetarian chili. Have a salad on the side and you have the perfect weeknight dinner. * 20 g soy granules * 30 g red bell pepper, chopped (about 2 tbsp) * 1 small green onion (scallion), finely chopped (5 g) * 2/3 tbsp tomato paste * 35 g cheddar, shredded * 1/8 tsp ground cumin * 1/4 tsp smoked paprika * Chili to taste * 1,5 tbsp oil * Salt, black pepper, fresh coriander to garnish <!-- --> * **Process** 1. Warm up the oil on medium-high, then add the white part of the scallions along with the bell pepper and a pinch of salt. Cook for about 10 minutes until very soft. 2. Meanwhile, mix the tomato paste with 1/3 cup of hot water and a pinch of salt, then add the soy granules to rehydrate. 3. When the veggies are soft, add the spices and cook for another minute. 4. Add the hydrated soy with the liquid. Let it all cook for a couple of minutes until the sauce is as thick as you like it. 5. Put in your bowl, add the cheddar so it melts, then top with the green part of the scallions and some coriander. * **Nutritional information**, _whole recipe_ * 407 kCal * **10.1 g net carbs** * 11.9 g total carbs * 1.8 g fiber * **20.6 g protein** * 32.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-20T00:00:00+02:00" itemprop="datePublished">20 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/frittata">Asparagus Frittata</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2868/34027766091_cc96d5e3d5_o_d.jpg" /> Asparagus are a great low-carb vegetable, and make for the most delicious frittata. In 20 minutes you will have a delicious breakfast or lunch! For another cheesy recipe, I suggest you try my amazing <a href="http://maria.recipes/broccoliMuffins">Broccoli muffins</a>! * 6 eggs, whisked * 60 g cheddar, shredded * 1 clove of garlic, finely minced * 1/2 small onion, chopped (35 g) * 200 g asparagus, chopped * 1 tbsp oil * Salt, black pepper to taste <!-- --> * **Process** 1. Warm up the oil on medium-high, then add the garlic and brown it for about 2 minutes. 2. Add the onions with a pinch of salt, and cook for about 5 minutes until it starts to soften. 3. Add the asparagus with some salt and pepper. Cook covered for another 5 minutes until they get soft. 4. Add the eggs and cook on low for 5 minutes, covered, until it is almost set. Meanwhile, preheat your broiler. 5. Sprinkle the cheese on top, then put under the broiler for about 5 minutes or until the eggs are set. * **Nutritional information**, _for half the recipe_ * 417 kCal * **4.8 g net carbs** * 2.4 g fiber * 7.2 g total carbs * **28.4 g protein** * 30.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-18T00:00:00+02:00" itemprop="datePublished">18 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/lambSpinach">Saag Gosht (Lamb Spinach curry)</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2905/33978034402_918c68046e_o_d.jpg" /> With very few ingredientes and spices you can make this creamy and spicy lamb curry, full of nutrients and flavor! * 225 g lamb, cubed * 100 g fresh or frozen and thawed spinach, coarsely chopped * 1/2 small onion, chopped (35 g) * 1,5 cloves of garlic, chopped * 2/3 tsp ginger paste * 1 green chili, chopped (or to taste) * 2 tbsp olive oil * 1/4 tsp cinnamon * 1/2 tsp garam masala * 1 tsp coriander powder * Salt to taste * Coriander to garnish <!-- --> * **Process** 1. Warm up the oil on medium heat, then add the onions and fry for about 5 minutes until soft and slightly brown. 2. Add the garlic, ginger and chili and cook for about 2 minutes. 3. Put the heat on high, add the meat with some salt and sear the meat for 5 minutes. 4. Add 1/2 cup of water, lower the heat to low, partially cover and let it simmer for about 45 minutes or until the meat is tender. Add water if it gets too dry. 5. When the meat is tender, add the spinach with some salt. Cook for 10 minutes. You should end up with a thick gravy. 6. Taste to check the salt, sprinkle with coriander and serve. * **Nutritional information**, _half recipe_ * 391 kCal * **3.5 g net carbs** * 1.9 g fiber * 5.4 g total carbs * **22.7 g protein** * 31.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-17T11:00:00+02:00" itemprop="datePublished">17 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/zucchiniQuiche">Zucchini Blue Cheese Quiche</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2948/33728039440_8397ffcf5a_o_d.jpg" /> Cheesy quiche was one of my favorite meals before going low carb. So being able to make my own low carb version of them is just amazing. And believe me, this is just as bit as good as the real deal. Give it a try! * 1 <a href="http://maria.recipes/ketoCrust">keto crust</a>, cooked * 3 eggs * 1/3 cup heavy cream (80 g) * 200 g zucchini, cubed * 3/4 small onion, chopped (50 g) * 1 tbsp olive oil * 75 g blue cheese, cubed * Salt, black pepper to taste <!-- --> * **Process** 1. Preheat the oven to 180C. 2. Warm up the oil over medium heat. Add the onion and zucchini with salt and pepper and cook for about 15 minutes until tender. 3. Blend the eggs with the cream. 4. Put the zucchini mixture and the cheese over the crust, evenly distributed. Then pour the egg mixture over the top. 5. Bake for about 30 minutes or until the center is set. * **Nutritional information**, _for 1/5 of the recipe_ * 484 kCal * **4.9 g net carbs**, 11.7 g fiber, 16.7 g total carbs * **16.3 g protein** * 40.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-14T00:00:00+02:00" itemprop="datePublished">14 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/friedEggCurry">Fried Egg Curry</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2821/33195158693_ceedc880ca_o_d.jpg" /> Another take at Egg Curry. This is my mother-in-law's style, frying the boiled eggs to get a hard, crunchy coating. Perfect for keto-ers! * 3 eggs, hard-boiled and peeled * 1/2 tsp ginger paste * 1/4 tsp turmeric * 1 tsp garam masala * 2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a> * Salt, chili to taste * Fresh coriander for garnishing <!-- --> * **Process** 1. Put half the oil in a small saucepan and fry the boiled, peeled eggs for about 10-15 min until they are golden and crunchy all around. Then set aside. 2. Meanwhile, warm up the other half of the oil. Fry the onion and ginger for about 15 minutes on medium-low and covered, until they break down. 3. Add the garam masala and some water if it is dry. Let it cook for another 3-4 minutes. 4. Add the eggs and let it all cook together for 3-5 minutes. 5. Garnish with coriander. * **Nutritional information** * 477 kCal * **5.1 g net carbs**, 1.3 g fiber, 6.4 g total carbs * **19.5 g protein** * 41.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-14T00:00:00+02:00" itemprop="datePublished">14 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/dryChicken">Dry Spicy Chicken</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2828/33647911490_cd9a7bff5c_o_d.jpg" /> An easy to make and very low carb chicken meal. Get all the indian flavors in your keto journey! * 300 g chicken thighs, boneless, with skin, chopped * 1/2 tsp ginger paste * 1.5 garlic cloves, minced * 1/2 tsp turmeric * A bunch of curry leaves (about 14) * 1/2 tsp mustard seeds * 1 tbsp coconut oil * 1/2 tbsp ghee * Salt, chili to taste * Fresh coriander for garnishing <!-- --> * **Process** 1. Marinate the chicken with the ginger, garlic, turmeric, salt and chili for at least an hour, preferably overnight. 2. Fry the chicken in two batches. In each one, put 1/2 tbsp coconut oil, then fry 6-7 curry leaves and 1/4 tsp mustard seeds, then add half the chicken and cook on high heat for about 5 minutes to seal, then on low heat for another 10 minutes until cooked through and tender. 3. Repeat with the second batch. 4. Garnish with coriander and ghee. * **Nutritional information**, _per serving (serves 2)_ * 572 kCal * **1 g net carbs**, 0.2 g fiber, 1.2 g total carbs * **21.1 g protein** * 53.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-13T00:00:00+02:00" itemprop="datePublished">13 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/eggBhurji">Egg Bhurji (indian scramble)</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2813/33966365416_0b513d6e0a_o_d.jpg" /> A simple meal full of flavor: scrambled eggs with veggies and spices, indian style! * 3 eggs * 1/2 small onion, chopped (35 g) * 1/2 tomato, chopped (50 g) * Fresh Green Chili to taste * 1/8 tsp whole cumin seeds * 1/4 tsp turmeric * 1/8-1/4 tsp garam masala * Salt to taste * Fresh coriander to taste (3 tbsp) * 1 tbsp oil <!-- --> * **Process** 1. Mix all three eggs with 1/4 tsp salt, the turmeric and the garam masala. Set aside for later. 2. Warm up the oil over medium heat. Add the cumin and fry it for a minute (don't burn it). 3. Add the onion and the chili, along with a pinch of salt. Cook for 5 minutes until very soft and translucent. 4. Add the tomatoes and a pinch of salt. Cook for 2 minutes until they start to break down. 5. Lower the flame to low and add the egg mixture. 6. Cook stirring constantly until it is as cooked as desired. 7. Turn off the stove, add the fresh coriander and serve. * **Nutritional information**, _for the whole recipe_ * 92 kCal * **4.5 g net carbs**, 1.2 g fiber, 5.8 g total carbs * **19.5 g protein** * 28 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-07T00:00:00+02:00" itemprop="datePublished">7 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/mushroomRice">Mushroom Fried Rice</a></h2> <div class="post-content"> <img src="https://farm3.staticflickr.com/2844/33077383743_3db10f0472_o_d.jpg" /> Fried rice is such a delicious main or side dish to have, but completely out of the question in a keto diet. But today I bring you a keto fried rice, with a special ingredient that will boost your protein and fat intake and make this a great option for vegan ketoers! <ul> <li>1/3 cup <a href="http://amzn.to/2nKbesg">hemp hearts</a> (47 g)</li> <li>1 cup of <a href="http://maria.recipes/cauliflowerRice">cauliflower rice</a> (120 g)</li> <li>1 cup of sliced mushrooms (70 g)</li> <li>2 tbsp or 1 medium green onion (scallions), separating white and green part (15 g)</li> <li>1,5 tbsp finely chopped green pepper</li> <li>Green or red chili to taste (I used about 1 red chili, without seeds, sliced)</li> <li>1/3 garlic clove, very finely chopped or into paste</li> <li>1/3 tsp ginger paste</li> <li>1/3 tbsp soy sauce</li> <li>Salt to taste (about 1/4 tsp)</li> <li>1 tbsp oil</li> </ul> * **Process** 1. Warm up the oil over medium heat. Add the white part of the green onions, the chili, garlic and ginger. Cook for about 3 minutes until soft. 2. Add the pepper and mushrooms, as well as half the salt. Cook for another 3 minutes until the mushrooms are soft. 3. Add the hemp and cauliflower rice, as well as the rest of the salt. Cook for a couple of minutes. 4. Add the soy sauce, cook for another minute. Then add the green part of the green onions and serve. * **Nutritional information**, for one serving (the whole recipe) * 458 kCal * **8.5 g net carbs**, 6.9 g fiber, 15.4 g total carbs * 21.9 g protein * 37.5 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-04-05T00:00:00+02:00" itemprop="datePublished">5 Apr, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/roastLamb">Roast Lamb</a></h2> <div class="post-content"> <img src= "https://farm4.staticflickr.com/3949/33017081784_1aef62652f_o_d.jpg" /> Ever since I was a kid, my mom would make lamb or fish "en cuajadera": roasted with white wine, potatos and vegetables. By omitting the potatoes, this is a delicious and complete meal, perfect for a ketogenic diet. <ul> <li>One Leg of lamb (if boneless should be 450 g meat)</li> <li>1 medium zucchini, sliced (180g)</li> <li>1 medium onion, sliced (110g)</li> <li>1 cup of chopped tomato (150 g)</li> <li>3 garlic cloves, chopped</li> <li>150 mL of dry white wine</li> <li>2 tbsp olive oil</li> <li>A handful of parsley</li> <li>Salt, ground black pepper, dry thyme</li> </ul> * **Process** 1. Preheat the oven to 200C. 2. Chop the vegetables. Place on a greased baking tray. Then put the lamb on top and add the rest of the ingredients. 3. Bake for about 90 minutes (depending on the size of the lamb piece), turning it around after half the time, until the meat is tender. * **Nutritional information**, for 1/3 of the recipe: * 483 kCal * **6.7 g net carbs**, 1.8 g fiber, 8.5 g total carbs * 29.2 g protein * 32.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-03-29T00:00:00+02:00" itemprop="datePublished">29 Mar, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tunaWrap">Tuna Collard Wraps</a></h2> <div class="post-content"> <img src="https://farm4.staticflickr.com/3940/33715823785_8d4cb9823b_o_d.jpg" /> This is such an easy recipe I wasn't even sure if I should upload it! These wraps take about 5 minutes to put together and are incredibly tasty. You can add other ingredients to taste, such as chopped pickles, or you could add 50 g of cooked chopped prawns to have a serving of 30 g of protein. <ul> <li>3 collard greens, stem removed (50g)</li> <li>55 g tinned tuna (in brine) (solids only)</li> <li>One boiled egg</li> <li>2 tbsp mayonnaise (30g)</li> <li>1/4 avocado (50 g)</li> <li>7 green olives, chopped</li> <li>Optional: black pepper, ground chili</li> </ul> * **Process** 1. Prepare the collard greens by removing the stem. You can chop it off altogether, or you can put the leaf on a chopping board and then trim the stem horizontally like you would when making [cabbage rolls](http://maria.recipes/ketoCabbageRolls). 2. Mash the avocado with a fork, then mix all the ingredients for the filling. Divide into three. 3. Put one part of the filling into the edge of the collard leaf, then wrap as if you were making [cabbage rolls](http://maria.recipes/ketoCabbageRolls). You can secure the wraps with toothpicks if you want to have them on the go. * **Nutritional information**, for 3 wraps (the whole recipe): * 466 kCal * **2.3 g net carbs**, 6.2 g fiber, 8.5 g total carbs * 20.1 g protein * 40.8 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-02-27T00:00:00+01:00" itemprop="datePublished">27 Feb, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/stuffedPeppers">Stuffed Green Peppers</a></h2> <div class="post-content"> <img src= "https://farm3.staticflickr.com/2838/32973931784_066e14d701_o_d.jpg" > A simple recipe for meat stuffed green peppers, that you can adapt to your taste by using different spices. <ul> <li>3 green bell peppers, big, or 6 small green peppers (500g)</li> <li>400 g minced beef (20% fat)</li> <li>50 g onion (1/2 medium)</li> <li>1-2 garlic cloves very finely chopped</li> <li>Salt, black pepper, nutmeg</li> <li>2 tbsp extra virgin olive oil</li> <li>1 egg</li> <li>Fresh parsley</li> <li>1 cup of tomato puree or one big tomato (180g)</li> <li>60 mL white wine, or half white wine and half cherry or similar wine</li> </ul> * **Process** 1. Mix all the ingredients for the filling and keep in the fridge for at least 30 min: meat, egg, salt, pepper, nutmeg, parsley, garlic and white or cherry wine. 2. Preheat the oven to 200C. 3. Open the peppers on the top (creating a lid) and throw away the seeds inside. 4. Use the meat mixture to fill the peppers. 5. Blend (or finely chop) the tomato and onion (you can use half the oil in the recipe to fry the onion) and pour over the peppers. Then add the remaining oil and white wine. 6. Bake for about 40 minutes or until the pepper is tender and the meat is cooked through. * **Nutritional information**, per serving (serves 3) * 508 kCal * **8.6 g net carbs**, 3.8 g fiber, 12.4 g total carbs * 27 g protein * 37.5 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-02-21T00:00:00+01:00" itemprop="datePublished">21 Feb, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/paneerMakhani">Paneer Makhani</a></h2> <div class="post-content"> <img src= "https://d30b2uadky41tr.cloudfront.net/Blog/image.axd?picture=/2017/02/PaneerMakhani1.JPG" /> This is one of my all-time favorite Paneer recipes, and I am so happy to have used it as my guest post at [the KetoDietApp website](http://www.ketodietapp.com)! If you want to check out the ingredients, instructions and nutritional information for this wonder of indian cuisine, just [click here](https://ketodietapp.com/Blog/post/2017/02/21/low-carb-paneer-makhani). </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-02-16T00:00:00+01:00" itemprop="datePublished">16 Feb, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tahiniSalad">Tofu Tahini Salad</a></h2> <div class="post-content"> <img src= "https://farm4.staticflickr.com/3766/32813937571_b33fcbc674_o_d.jpg" > Raw cabbage is delicious for salads. And when combined with sauteed tofu and a tahini dressing, it makes an amazing meal. Even my mom, who is a bit skeptical about cabbage, kept saying it was amazing! <ul> <li>1 cup shredded cabbage (70 g)</li> <li>1/2 cup shredded purple cabbage (35 g)</li> <li>125 g firm tofu</li> <li>1/8 tsp salt (or more to taste)</li> <li>1/8 tsp black salt (kala namak) (sub for regular salt if not available)</li> <li>1 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1 tbsp olive oil</li> <li>1 tbsp lemon juice</li> <li>1/4 garlic clove (or less, to taste)</li> <li>1 tbsp tahini</li> <li>Stevia or other sweetener to taste</li> <li>2-3 tbsp water</li> <li>Spicy Paprika, Black pepper</li> </ul> * **Process** 1. In a pan over medium-high heat, melt the coconut oil. Add the cubed tofu with the black salt and some black pepper, and fry for 10-15 minutes until it is golden and slightly crunchy. 2. Meanwhile, chop the cabbabe. 3. Mix all the other ingredients except the paprika to make the dressing. If you aren’t a big garlic fan, leave it in a big chunk and let it infuse, then take out before eating. 4. Add half of the dressing to the cabbage and mix well to cover it. 5. Once the tofu is done, serve on top of the cabbage, add the rest of the dressing and some paprika, and serve while it is still warm. * **Nutritional information**, for the whole recipe * 556 kCal * **9.4 g net carbs**, 7.3 g fiber, 16.7 g total carbs * 46.9 g fat * 25.2 g protein </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-02-05T00:00:00+01:00" itemprop="datePublished">5 Feb, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tofu">Soy-free Tofu</a></h2> <div class="post-content"> <img src= "https://farm1.staticflickr.com/665/32351747630_5bf5f3066a_o_d.jpg" /> Soy is almost unavoidable in a vegetarian diet, especially for lowcarbers. But a lot of people are alergic, others are intolerant, and other people like me don't want to base all their nourishment on a single ingredient... But here comes Chickpea Tofu to the rescue! The original recipe is from Birmania: a tofu made from chickpea flour that is served as is in salads. I modified it a bit, reducing the amount of chickpea flour and incorporating some flax and protein powder to make it lower carb and higher protein. The result are tofu cubes with a very delicate flavor and texture, that can be sauteed in oil, which makes them slightly crunchy on the outside but still pillowy in the inside. A real delicacy! My favorite way of having them is sauteed with coconut oil and spices, served warm over salad with some fresh coriander. Yum. <ul> <li>1/2 cup (60g) chickpea flour</li> <li>50g flavor free protein powder (like <a href="http://amzn.to/2nAykTb">unflavored whey</a> or <a href="http://amzn.to/2ossGXa">pea protein powder</a>)</li> <li>1/3 cup (50g) <a href="http://amzn.to/2oA16Uv">flax seeds</a>, ground</li> <li>1/2-2/3 tsp salt</li> <li>1/4-1/3 tsp turmeric</li> <li>2 cups of water</li> </ul> * **Process** 1. Mix the dry ingredients. Then add one cup of the water and mix until you have a batter/paste. 2. Take the rest of the water to a boil. When it starts boiling, gently add in the batter while whisking. 3. Keep simmering while whisking for about 8 minutes, until it is as thick as clay. You can whisk in the beginning, then switch to a spatula when it gets thicker. 4. Pour in a lightly greased mold and let it cool down in the fridge for at least one hour. * **Nutritional Information**, for 1/6 of the recipe * 112 kCal * **4.7 g net carbs**, 4 g fiber, 8.6 g total carbs * 11.3 g protein * 4.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-02-03T00:00:00+01:00" itemprop="datePublished">3 Feb, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/fishCurry">Fish Curry</a></h2> <div class="post-content"> <img src= "https://farm1.staticflickr.com/294/32568848351_1c33a25e85_o_d.jpg" /> When people think of indian food, they very rarely think of fish dishes, but in certain parts of the country like Bengal or Mumbai, fish curries are a staple in every household. This one in particular is my favorite, as the coconut milk makes for a super creamy sauce. <ul> <li>500 g cod or other similar fish, cut in chunks</li> <li>3 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1 dried red chili (or one green chili chopped to be added with the garlic and ginger)</li> <li>1 tsp mustard seeds</li> <li>1/2 medium onion (50 g)</li> <li>1 small tomato (150 g)</li> <li>1 tsp ginger paste</li> <li>2 tsp garlic paste or 4 cloves, minced</li> <li>1/2 tsp turmeric</li> <li>1 tsp powdered cumin</li> <li>1 tsp powdered coriander</li> <li>1/2 tsp garam masala</li> <li>Ground black pepper</li> <li>Salt (about 1/2 tsp in total)</li> <li>3/4 cups coconut milk</li> <li>Optional: 1-2 tbsp apple cider vinegar or lemon juice</li> <li>Fresh coriander to garnish</li> </ul> * **Process** 1. Warm up the oil in a pan over medium high heat. Fry the mustard seeds and dried red chili. 2. When the seeds start to pop, wait about one minute, then add the garlic, ginger and onions with a bit of salt. Cook on medium heat for 5-10 minutes until they are translucent. 3. Add the chopped tomatoes with salt. Cook for 5 minutes until they break down. 4. Add the fish with the rest of the salt. 5. Turn up the stove to high heat to cook the fish for about 2 minutes. Add the spices. Mix and cook for 30 seconds, then add the coconut milk. 6. Let it simmer for about 5 minutes. Turn off the stove, add vinegar or lemon juice, garnish with coriander and serve. * **Nutritional information**, for 1/3 of the recipe * 392 kCal * **5.8 g net carbs**, 1.4 g fiber, 7.2 g total carbs * 31.8 g protein * 26.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-24T00:00:00+01:00" itemprop="datePublished">24 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/ketoPizza">Keto Pizza (vegan)</a></h2> <div class="post-content"> <img src= "https://farm1.staticflickr.com/572/31684977893_6a35594472_o_d.jpg" > This pizza base is seriously awesome. I used [this recipe](http://www.meatfreeketo.com/vegan-fathead-pizza-crust/) but omitted the vegan cheese and used some nutritional yeast instead to get some cheesy flavor. Seriously: this pizza holds its shape perfectly, is chewy and salty and delicious, vegan, and only 3.1 g net carbs for half a pizza crust! <ul> <li>85 g of <a href="http://amzn.to/2oA16Uv">flax seeds</a>, ground (1/2 cup + 1.5 tbsp)</li> <li>4 tbsp <a href="http://amzn.to/2otIMQ1">psyllium husk powder</a>(32 g)</li> <li>1 tsp of baking powder</li> <li>1/2 tsp salt</li> <li>1/2 tsp garlic powder</li> <li>1/4 tsp dried oregano</li> <li>2-3 tbsp (6 g) nutritional yeast (optional)</li> <li>1 cup of water</li> <li>For Margharita Pizzaa: 1 tbsp olive oil, 1 cup (110 g) shredded mozzarella (you can use vegan mozzarella, but it will change the macros), 1/2 cup tomato passata, some dried oregano, fresh basil</li> </ul> * **Process** 1. Preheat the oven to 180C. 2. In a bowl, mix everything except the water. Then add the water little by little until you form a dough. 3. Put the dough on a parchment paper, put another paper on top and then spread it out with a rolling pin until it is 2-3 mm thick. Once it is even, cut it out to whichever shape you want (I used a big lid to make it round). If it cracks, use your finger with a little bit of water to smooth it out. 4. Bake for 20-25 minutes until it's slightly dry and golden. 5. Put whichever toppings you want and then bake for another 5-10 minutes. * **Nutritional information**, for half the base / for half a margharita pizza * 241 kCal / 487 kCal * **3.1 g net carbs**, 26.4 g total carbs, 23.3 g fiber / **7.7 g net carbs**, 24.3 g fiber * 8.4 g protein / 24.1 g protein * 18.1 g fat / 36.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-22T00:00:00+01:00" itemprop="datePublished">22 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/eggfreeHash">Egg-free LCHF Hash Browns</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/595/32029061850_955f97973d_o_d.jpg" > A simple recipe for a low-carb, lactovegetarian breakfast, for a good boost of fiber in the morning. <ul> <li>100 g paneer, crumbled</li> <li>1 flax egg: 1 tbsp <a href="http://amzn.to/2oA16Uv">flax seeds</a>, ground + 3 tbsp warm water</li> <li>1 cup (70g) shredded cabbage</li> <li>2 tbsp chopped green onions</li> <li>Salt and pepper to taste</li> <li>1 tbsp coconut oil</li> </ul> * **Process** 1. First, prepare your flax egg and let it sit for a couple of minutes. 2. Add the paneer to the flax egg and mix until you have a sticky paste. You can add a bit of water if needed. 3. Add salt, pepper and the vegetables and mix. Then divide into three. 4. Put 1/3 tbsp coconut oil in a pan and use it to fry one of the patties, about 3 minutes on the first side and 2 minutes after flipping. 5. Proceed with the other two parts of the mixture and serve. * **Nutritional information**, _for the whole recipe_ * 478 kCal * **6.3 g net carbs**, 4 g fiber, 10.3 g total carbs * **22.4 g protein** * 40 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-21T00:00:00+01:00" itemprop="datePublished">21 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/bhurji">Paneer Bhurji</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/671/31566913314_9a07089685_o_d.jpg" > This is the indian version of scrambled tofu: crumbled paneer with vegetables and spices. A very filling meal full of protein that takes 10 minutes from start to finish. A must try! <ul> <li>250 g paneer, crumbled</li> <li>50 g onion (1/2 medium), chopped</li> <li>1 small tomato (100g), chopped</li> <li>Other vegetables to taste (like green peas), optional</li> <li>1 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1/4 tsp whole cumin</li> <li>Red chili powder to taste</li> <li>1/2 tsp turmeric</li> <li>1/8 tsp garam masala or more to taste</li> <li>Optional: 1/4 tsp kasuri methi (dried fenugreek leaves)</li> <li>Fresh coriander</li> <li>1/2 tbsp lemon juice</li> </ul> * **Process** 1. First, if the crumbled paneer is too dry, add a little bit of warm water to rehydrate it. 2. Melt the coconut oil over medium-high heat. Add the cumin seeds until they start popping. Then, add the onion with some salt and cook for 5 minutes until they are brown. 3. Once the onion is cooked, add the ginger and garlic. Cook for a minute. 4. Add the tomatoes and salt. Cook for two minutes until they the tomatoes are soft, then add the other spices. Mix well. 5. Add the paneer (drained if you were soaking it). Cook for 30-60 seconds. Add the kasuri methi if you are using it. 6. Garnish with lemon juice and coriander. * **Nutritional information**, _for a serving (recipe serves 2)_ * 466 kCal * **8.3 g net carbs**, 2 g fiber, 10.2 g total carbs * **26 g protein** * 36.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-17T00:00:00+01:00" itemprop="datePublished">17 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/sauteedTofu">Sautéed Tofu Salad</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/302/31539521834_6d64390935_o_d.jpg" > I love sautéed tofu; it gets very chewy and crunchy, and when mixed with spices it can be delicious. <ul> <li>2 cups (250 g) firm tofu, cubed OR 200 g paneer (if using paneer, omit mayonnaise)</li> <li>3/4 tsp turmeric</li> <li>1/4 tsp salt</li> <li>Red chili powder to taste</li> <li>1/8 tsp salt</li> <li>1/8 tsp black pepper</li> <li>1 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1/2 tbsp lemon juice</li> <li>4 cups of fresh spinach (120g) OR 4 cups shredded lettuce (180g)</li> <li>1 cup of fresh cucumber (130g) <i>(Optional; omit for fewer carbs)</i></li> <li>1/2 cup of fresh red bell pepper (75g) <i>(Optional; omit for fewer carbs)</i></li> <li>1/2 cup pumpkin seeds</li> <li>2 tbsp mayonnaise OR 3/4 extra tbsp coconut oil and 3/4 extra tbsp olive oil</li> <li>1 tbsp extra virgin olive oil</li> <li>1 tbsp lemon juice</li> <li>Fresh coriander</li> <li>Optional: Chaat masala, to taste</li> </ul> * **Process** 1. In a non-stick pan, melt the coconut oil over medium-high heat. Then add the tofu and all the spices along with 1/2 tbsp lemon juice. Sautée for 15-20 minutes until it is very golden and firm. 2. Mix all the other ingredients and serve while the tofu is still warm. If you are making this ahead of time, keep the tofu in a separate container and warm up before eating. * **Nutritional information**, _for a serving (recipe serves 2)_ * 572 kCal * **7.9 g net carbs**, 7.7 g fiber, 15.6 g total carbs * **28.6 g protein** * 48.2 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-16T00:00:00+01:00" itemprop="datePublished">16 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/paneer">How to make Paneer</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/301/32231928512_a405f5a901_o_d.jpg" > Paneer is indian cottage cheese, one of the basic protein sources for vegetarian curries. You can use it in blocks in tikka or gravies, or you can crumble it for egg-free hash browns or bhurji. The nutritional info may not be 100% accurate as I estimated using packaged paneer. The more it is drained, the lower carb it will be. <ul> <li>2 L (8 cups) whole fat milk</li> <li>1/4 cup lemon juice or apple cider vinegar</li> <li>1/8 tsp salt</li> </ul> * **Process** 1. Bring the milk to a boil in a heavy bottom saucepan. 2. Reduce the heat to low and add the lemon juice, stirring constantly until it curdles and the whey has separated completely. 3. Using a very fine sieve or a cheese cloth, separate the curds from the whey. You can keep the whey for something different (it has some protein, but also carbs, so not keto-friendly!). 4. Drain the curd well and use it fresh, or put it with some weight on top to form a firm block. * **Nutritional information**, _for 100g_ * 300 kCal * **3.3 g net carbs**, 0 g fiber, 3.3 g total carbs * **20 g protein** * 23.5 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2017-01-14T00:00:00+01:00" itemprop="datePublished">14 Jan, 2017</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenCurry">Easy Chicken Curry</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/489/32244700206_81ecbdf106_o_d.jpg" /> Easiest recipe for a delicious Chicken Curry. It won't be as good as the recipes that use real indian spices and blends... but it is pretty darn good anyway :) <ul> <li>8 chicken drumsticks, with skin and bone (1 kg)</li> <li>4 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1/2 big onion or one medium (110g)</li> <li>1 tsp ginger paste or 1 inch ginger</li> <li>1 tsp garlic paste or one big clove of garlic</li> <li>2 tsp curry powder</li> <li>1 cup of coconut milk</li> <li>1/4-1 cup of water depending on desired sauce</li> <li><i>Optional:coriander to garnish</i></li> </ul> * **Process** 1. In a pot or a pressure cooker, in two batches, sear the meat (with some salt) for about 3 minutes, using 1 tbsp oil per batch. Set the seared drumsticks aside. 2. Purée the onion, ginger and garlic. 3. Heat up the other 2 tbsp oil and fry the onion paste, with salt and pepper, over medium heat for about 10 minutes until it smells sweet. 4. Add the curry powder. Cook for 60 seconds, then add the coconut milk and water (add water depending on how thick you want your sauce; add more water if you will be cooking on an open pot). Mix well until the sauce is even. 5. When it comes to a boil, add the chicken back in. Now cook on an open flame on low heat for about 45-60 minutes or in a pressure cooker for 20 minutes until the meat is tender. 6. Garnish with coriander and serve. * **Nutritional information**, _for one drumstick with 1/8 of the sauce_ - 333 kCal - **2.1 g net carbs**, 0.4 g fiber, 2.5 g total carbs - 24.2 g protein - 25.3 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-12-27T00:00:00+01:00" itemprop="datePublished">27 Dec, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/mungBurgers">Mung Burgers</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/283/31773130252_35eb530678_o_d.jpg" /> This recipe for burger patties using mung beans is a great way to get some legumes in your diet. Mung beans (green soy) have a very nice flavor, and if you let them sprout, the carb count will be lower and they will have more protein. On top of that, you can add any spices you want to get different styles. It is hard to know the exact nutritional information for this recipe as it depends on how long the beans sprout for; I estimated the data sprouting them for 3 or 4 days. <ul> <li>1/2 cup (100g) mung beans (green soy)</li> <li>Optional: 30 g unflavored protein powder (such as <a href="http://amzn.to/2nAykTb">whey</a> or <a href="http://amzn.to/2ossGXa">pea protein powder</a>)</li> <li>Salt</li> <li>Black pepper</li> <li>2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a> or butter or ghee</li> <li>Other spices to taste</li> </ul> * **Process** 1. Let the beans sprout for 3 or 4 days until they have roots of 1-2 cm. 2. Blend all the ingredients until you have a thick paste. 3. Divide into four and form patties using your hands. 4. Fry each patty with 1/2 tbsp oil until it is golden on both sides (about 2 minutes per side). * **Nutritional information**, per pattie - 149 kCal - **7 g net carbs**, 3.1 g fiber, 10.1 g total carbs - **11 g de protein** - 7.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-12-12T10:10:00+01:00" itemprop="datePublished">12 Dec, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/veganQuiche">Vegan Quiche</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/313/31662446346_b9070c8fa2_o_d.jpg" /> A great recipe for all those vegan ketoers, or anyone who cannot eat eggs but still wants to eat some french amazingness. You can adapt this basic recipe to your taste, changing the vegetables and/or adding other ingredients, such as cheese or meat! <ul> <li> 1 <a href="http://maria.recipes/ketoCrust">low-carb crust</a> </li> <li> 1.5 cups of chopped zucchini (180-200 g, one medium) </li> <li> One leek (80g) </li> <li> 2 tbsp olive oil</li> <li> 1/2 tsp salt</li> <li> 400 g firm tofu</li> <li> 3-4 tbsp water</li> <li> 1/4 tsp turmeric</li> <li> Black pepper to taste</li> <li> <i>Optional: 3 tbsp nutritional yeast</i> </li> </ul> * **Process** 1. Preheat the oven to 180C. 2. Use the oil to fry your vegetables. - _I added 1 tbsp of soy sauce to my vegetables to get some umami, as I didn't have nutritional yeast!_ 3. Blend the tofu with the water, turmeric, salt and pepper. You should get a dense batter. 4. Add the cooked vegetables to the tofu mixture, then spoon over your crust. 5. Bake for about 30 minutes or until the center is set. Let it cool for 5 minutes before cutting into it. * **Nutritional info**, _per slice (serves 5)_ * 505 kCal * **8.6 g net carbs**, 15.6 g fiber, 24.2 g total carbs * **25.5 g protein** * 37.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-12-10T00:00:00+01:00" itemprop="datePublished">10 Dec, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/ketoCrust">Keto Vegan Crust</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/591/31553200562_c11ef9c964_o_d.jpg" /> This crust, based on the recipe from [healthfulpursuit](http://www.healthfulpursuit.com), takes a while to make, but is gluten-free, egg-free, vegan, low carb, and has a great flavor! <ul> <li>1 + 1/4 cups ground <a href="http://amzn.to/2oA16Uv">flax seeds</a></li> <li>1/4 sunflower seeds, ground</li> <li>80-100 g onion (one small)</li> <li>1/3 tsp salt</li> <li>2 tbsp olive oil</li> <li>1/2 tbsp apple cider vinegar</li> <li>1/2 tsp baking powder</li> <li>Other ingredients to taste, for example one clove of garlic (minced)</li> </ul> * **Process** 1. Warm up the oven to 110C. 2. Blend the onion with the oil and vinegar. 3. In a separate bowl mix the other ingredients, then add the onion mixture. You should get a thick paste, dry but not crumbly. If it crumbles, add some water. 4. Grease your quiche mold very well (or even better, put a circle of parchment paper in the bottom) and put the mixture inside. Then use a spoon or your hands to form the crust. Water your hands to smooth it out. 5. Bake for 90 minutes until it is dry and crunchy. Then, take it out and add the filling of choice, * **Nutritional info**, _for 1/5 crust_ * 294 kCal * **2.4 g net carbs**, 11.1 g fiber, 13.5 g total carbs * **8.5 g protein** * 24.8 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-12-08T00:00:00+01:00" itemprop="datePublished">8 Dec, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/salmon">Salmon in soy sauce</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/769/31584141351_883e3468d6_o_d.jpg"/> A great, easy, tasty, keto recipe. My family adores it, it literally takes 10-15 minutes to make, and is super filling. You have to try it! Add more oil if you want it to be more filling, or accompany with a fatty vegetable side dish. <ul> <li> 2 salmon fillets, about 1 inch thick (14 oz in total)</li> <li> 1 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li> The green part of 3 leeks (cut out the ends) OR one whole leek (90g)</li> <li> 1 tsp fresh ginger paste</li> <li> 1/4 tsp salt</li> <li> 1/4 tsp black pepper</li> <li> 1 tbsp soy sauce</li> <li> 3 tbsp water</li> <li> 2 tbsp lemon juice</li> <li> Stevia or sweetener to taste (equals 1-2 tsp sugar)</li> <li> 1/2 tbsp sesame oil</li> <li> Optional: coriander for garnishing</li> </ul> * **Process** 1. Melt the coconut oil over high heat. Then fry the ginger for 2 minutes. 2. Add the leeks, salt and pepper. Cook stirring frequently for about 5 minutes, until soft. 3. Add the salmon and cook on high for 2 minutes on each side. 4. Add the soy sauce and water, cook for 30 seconds, then cover and reduce to low heat until the salmon is cooked through. 5. Once cooked, add the lemon juice, stevia and sesame oil, mix well and serve. * **Nutritional info**, _per serving_ * 207 kCal * **3.4 g net carbs**, 0.5 g fiber, 3.9 g total carbs * **22.3 g protein** * 11.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-12-08T00:00:00+01:00" itemprop="datePublished">8 Dec, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/pumpkinCurry">Pumpkin Curry</a></h2> <div class="post-content"> <img src="https://farm6.staticflickr.com/5564/31662699386_64cef758be_o_d.jpg" /> It had been so long since I published any indian food! This is one of my favorite veg curries. It is sweet with a slightly acid touch thanks to the mango powder (that can be substituted for lemon), and is awesome with some dal and rice or roti. <ul> <li>500 g pumpkin or butternut squash</li> <li>Dried red chili (1-2)</li> <li>100 g onion</li> <li>1 tsp ginger paste</li> <li>1/4 tsp asafoetida (can be subbed for 1/2 tsp garlic paste, that would be used with the ginger)</li> <li>1/4 tsp fenugreek seeds (methi)</li> <li>1/4 tsp garam masala</li> <li>1/4 tsp turmeric</li> <li>Fresh coriander, to serve</li> <li>1 tbsp oil (mustard or <a href="http://amzn.to/2nRguh4">coconut oil</a>)</li> <li>1/2 tsp mango powder (amchoor) or 1 tbsp lemon juice</li> <li>Stevia or sweetener to taste (equivalent to 1 tsp sugar)</li> </ul> * **Process** 1. Heat up the oil. Fry the fenugreek seeds, chili and asafoetida for 2 minutes (don't burn them!!!). 2. Add the ginger. Cook for 1 minute, then add the onion and salt. Cook on slow heat for about 10 minutes, until it is brown and soft. 3. Add the pumpkin and spices (except amchoor) and some more salt. Cook for 2 minutes, stirring. Then, pour 1/4 cup water and cover. 4. Cook on low heat. Once the pumpkin is soft, add the rest of the ingredients, mix and serve. * **Nutritional info**, _per serving, using butternut squash (serves 4)_ * 100 kCal * **14 g net carbs**, 3.2 g fiber, 17.2 g total carbs * **1.6 g protein** * 3.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-11-04T00:00:00+01:00" itemprop="datePublished">4 Nov, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/seitanSausage">Seitan Sausage</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/268/31553354842_96c90f3f12_o_d.jpg" /> This is one of these recipes that I make in bulk and then freeze for an easy lunch or dinner for another day. These sausages are fenomenal, very high protein and quite low-carb, so they make for a great dinner when combined with some cauli-rice, keto bbq sauce and salad. Hope you enjoy them! <ul> <li>250 g <a href="http://amzn.to/2n4ufue">vital wheat gluten</a></li> <li>300 g tofu (best to use silken, but you can use firm if you want)</li> <li>Optional: 1/2 cup nutritional yeast</li> <li>2 tbsp onion powder</li> <li>1/2 tsp black pepper</li> <li>2 tsp sweet paprika</li> <li>1 tsp smoked paprika</li> <li>chili to taste</li> <li>1 tbsp ground mustard seeds</li> <li>1 tsp salt</li> <li>Sweetener to taste (equals 1 tsp sugar)</li> <li>3 garlic cloves</li> <li>2 tbsp soy sauce</li> <li>3 tsp liquid smoke</li> <li>1 cup of water</li> <li>2 tbsp olive oil</li> </ul> * **Process** 1. Blend the tofu, garlic, soy sauce, oliquid smoke, water and oil until smooth. 2. Mix all the dry ingredients. 3. Add the wet mixture into the dry and mix well. 4. Knead the dough for about 5-10 minutes. 5. Divide into 12 equal pieces and roll each piece in a sausage shape with some aluminum foil. 6. Steam for 30 minutes. 7. Let them cool down and keep in the fridge or freezer. When you want to eat them, just stir-fry them with some oil and enjoy! * **Nutritional info**, _per serving_ * 139 kCal * **5 g net carbs**, 1.5 g fiber, 6.5 g total carbs * **20.1 g protein** * 4.2 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-10-17T11:12:00+02:00" itemprop="datePublished">17 Oct, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/ketoLasagna">Keto Veggie Lasagna</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/629/31639726906_1fce7b772e_o_d.jpg" /> I am so happy about this lasagna! It is vegetarian (and can be vegan if you use a vegan milk and omit the mozzarella) and low-carb, and it is as good as the traditional one! For the sauce, you can combine milk and heavy cream as you want, and/or use vegetarian milks to lower the carb count. In my case, i used soy milk mixed with single cream. <ul> <li>2 medium zucchini (400 g)</li> <li>2/3 chopped onion (75 g)</li> <li>1/2 tsp garlic powder</li> <li>1/4 tsp dried oregano</li> <li>2 tbsp tomato purée</li> <li>2 tbsp olive oil</li> <li>50 g soy granules</li> <li>1 tbsp <a href="http://amzn.to/2oA16Uv">flax seeds</a> ground</li> <li>1/2 cup of milk + 1/2 cup of heavy cream</li> <li>A pinch of nutmeg</li> <li>1/2 tbsp <a href="http://amzn.to/2otIMQ1">psyllium husk powder</a></li> <li>1/2 cup shredded mozzarella</li> <li>Salt</li> <li>Black pepper</li> </ul> * **Process** 1. Cut the zucchini in thin strips of about 2 mm thick. Then cook with a little bit of olive oil on a non-stick pan, in the microwave or steam them, until they are slightly softer but not completely mushy! 2. Hydrate the soy in salty water or in stock. 3. Fry the onion on medium heat about 10 minutes until it is soft. After, add the rest of ingredients and 1/2 cup of water and let everything boil until you have a nice thick sauce. 4. For the white sauce: warm up the water and cream with the nutmeg and some salt. Then add the psyllium and mix very well (you might need a hand mixer). Adjust the texture bu adding more psyllium or more milk. 5. Make the lasagna alternating layers of zucchini and soy mixture, and use the bechamel to cover everything. Then add the mozzarella on top. 6. Bake at 180-200C for 30 minutes, putting it under the broiler in the last 5 min. * **Nutritional info**, _for 1/4th recipe_ - 310 kCal - 14.6 g total carbs, 3.1 g fiber, **11.5 g net carbs** - **14 g protein** - 23.2 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-09-27T09:00:00+02:00" itemprop="datePublished">27 Sep, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/ketoCabbageRolls">Keto Cabbage rolls</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/701/30866637123_f211993d27_o_d.jpg" /> This is not really a new recipe; I just adapted my [previous cabbage roll recipe](http://maria.recipes/cabbageRollso) to decrease the carbs, filling them with soy granules and seeds. They are as good as the original recipe, and this time I made a video on how to make the wraps. I hope you like them. <ul> <li>One whole cabbage head (we will use the 8 outer leaves, about 260 g)</li> <li>70 g soy granules</li> <li>1/2 cup of pumpkin seeds (65g), chopped</li> <li>1 tbsp tomato paste (concentrate)</li> <li>1/2 onion (80g)</li> <li>2 tablespoons olive oil</li> <li>2 garlic cloves</li> <li>Spices: 1 tsp spicy paprika,</li> <li>1 tsp cumin</li> <li>2 tsp cinnamon</li> <li>2 bay leaves</li> <li>1/4 tsp chili powder</li> <li>1 tbsp tomato paste (concentrate)</li> <li>1.5 cups of tomato purée (passata)</li> <li>6 cloves</li> <li>1 tbsp olive oil</li> <li>A pinch of salt</li> <li>Some sugar or stevia (optional)</li> </ul> * **Process** 1. First, boil the whole cabbage. I made it in the pressure cooker for 10 minutes. Then, cool with water to stop any further cooking. 2. Hydrate the soy granules. Meanwhile, gently fry the onion with 2 cloves of garlic, chopped, and bay leaf. * If you want the onion to be extra soft and sweet, you can make it like I did [in my other recipe](http://maria.recipes/cabbageRolls) 3. Once the onion is soft, add the spices and cook for a minute. Then, add the soy, seeds and tomato paste. Cook for 5 more minutes and then let it cool. You can add fresh parsley or coriander if you like it. 4. Take the 8 outer cabbage leaves. Put them flat over a surface and, with a knife, trim the stem without cutting all the way through. 5. Divide the soy mixture into eight, and put a portion onto each cabbage leaf. Then, wrap like I show in the video. 6. Put the rolls in a big pot in one or two layers, leaving little space between them. Mix the ingredients for the sauce (all the other ingredients) and pour over the rolls. 7. Let them boil for about 30 minutes. 8. Serve with flax bread, rice, salad... * **Nutritional info**, _per serving (4 servings in total)_ * 295 kCal * 21.5 g total carbs, 5.9 g fiber, **15.6 g net carbs** * **17.1 g protein** * 18.8 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-09-26T08:58:00+02:00" itemprop="datePublished">26 Sep, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tunaEggplant">Tuna-stuffed Eggplant</a></h2> <div class="post-content"> <img src="https://farm6.staticflickr.com/5589/31639725306_05b7b546eb_o_d.jpg" /> This is an easy week-night dinner that my mom would make quite often when I was a kid. It was one of the few vegetable dishes that I actually enjoyed! I tweaked it a little bit to make it lower carb and higher in fat, and the result is delicious :D <ul> <li>One big eggplant (550-600g)</li> <li>50 g of tuna (canned in brine)</li> <li>2 eggs</li> <li>2 tbsp olive oil</li> <li>1 tbsp tomato paste</li> <li>2/3 cup (40 g) parmesan</li> <li>1/2 tsp oregano</li> <li>Pinch of chili to taste</li> <li>Salt to taste</li> </ul> * **Process** 1. First, cut the eggplant lenthgwise and cook it until it is tender: you can cook it in the microwave, in the oven or in a pan. 2. Once cooked through, use a spoon to scoop out the flesh of the eggplant, leaving the skin and part of the flesh to stuff later. 3. In a bowl, chop the eggplant flesh finely, and then add all the other ingredients (leave some of the parmesan to use as topping) and mix. 4. Use the mixture to fill in the eggplant skins. Top with more cheese. 5. Warm up for the filling to set, either in the microwave or in the oven. * **Nutritional info**, _per serving (serves 2)_ * 408 kCal * 18.6 g total carbs, 8.6 g fiber, **10 g net carbs** * **31 g protein** * 24.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-09-25T00:00:00+02:00" itemprop="datePublished">25 Sep, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/korma">Chicken korma</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/683/30866633873_0e3e5dd382_o_d.jpg"/> I love this curry and its aromatic, thick sauce. It's a real crowd-pleaser. The traditional way of making it takes forever, but I used [this one](https://www.youtube.com/watch?v=We1qXKTbqOM) as reference, since it is easier and takes "only" one hour to make. For the sauce you can use cashews, which make it creamier, but I used almonds to lower the carbs in the recipe. Eat it with rice, naan or, in my case, salad and cauli-rice :D <ul> <li>325 g white onion</li> <li>3 garlic cloves</li> <li>2 cm ginger or 1 tsp ginger paste</li> <li>3 tbsp oil (I used mustard oil)</li> <li>420 g chicken breast (you could use drumsticks instead; it will be even better!)</li> <li>30 whole, peeled almonds (40-45g), soaked in water for 24h</li> <li>3 tbsp of coconut milk</li> <li>3/4 cup coconut milk</li> <li>5 cm cinnamon stick</li> <li>10 cloves</li> <li>10 green cardamom</li> <li>3 tsp powdered coriander</li> <li>1/2 tsp turmeric</li> <li>1/4 tsp chili powder</li> <li>3/4 tsp garam masala</li> <li>1-1.5 tsp salt</li> <li>Optional: some sugar or stevia, if you want the sauce to be sweet.</li> </ul> * **Process** 1. First, blend the ingredients for the onion purée until smooth: onions, garlic, ginger. Separately, form the almond paste, blending the almonds, 3 tbsp coconut milk and 3 tbsp water. 2. In a pan, heat up the oil and fry the whole spices (cardamom, cloves, cinnamon stick) 2 minutes, without burning them. 3. Add the onion purée and a bit of salt and cook, stirring often, for about 15 minutes on medium-high. Be careful not to let it stick to the bottom of the pan. 4. Meanwhile, cube the chicken (if using drumsticks, leave them whole) and blend the ingredients for the almond paste. 5. Once the onion has formed a pretty dry paste, take off the stove and add the ground spices. Cook for about a minute. Then, add in the chicken with some salt and brown for 5 minutes. 6. Pour the coconut milk and 3/4 cup of water and mix well to form a thick sauce. Lower the heat and let it simmer for 15-20 minutes, or until the chicken is tender. Add more water if it starts to get dry. 7. Finally, add the almond paste and the garam masala and mix. Add more water if you want a thinner sauce. Let everything boil for a couple of minutes and serve. * Nutritional info, _per serving (serves 4)_ * 412 kCal * 12.4 g total carbs, 3 g fiber, 9.4 g net carbs * 26.3 g protein * 30.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-09-15T00:00:00+02:00" itemprop="datePublished">15 Sep, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/piccata">Chicken Piccata</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/473/31699796545_d6c637b8e0_o_d.jpg" /> This is an italian dish perfect for carnivores, but it also works wonderfully using seitan instead of chicken (_but if you are using seitan, the final carb count will be higher_. The final result is a slightly thick sauce, acidic from the lemon and capers, and with smooth buttery texture... Perfect with salad, rice or cauli-rice! If you follow a ketogenic diet, do not hesitate on adding more butter - the more, the better :D <ul> <li>750 g chicken breast fillets, or 6 seitan steaks</li> <li>1/3 medium onion (60g), sliced finely</li> <li>2 garlic cloves, thinly sliced</li> <li>2 tbsp capers</li> <li>3 tbsp butter</li> <li>2 tbsp olive oil</li> <li>Salt, black pepper</li> <li>One chicken stock cube (optional)</li> <li>1/2 cup (125 mL) white wine</li> <li>1/4 cup (60 mL) lemon juice</li> <li>The zest of half a lemon</li> <li>About 1/4 cup of chopped parsley</li> <li>1 tbsp flax meal</li> </ul> * **Process** 1. In a pan, brown the chicken (with some salt) using a bit of the butter over medium-high. Leave the browned pieces on the side for later. 2. Add the rest of butter and oil in the pan and fry the onion and garlic over medium-low for 10-15 minutes, until it's brown and soft. 3. Add the meat back in and pour the wine. Let it simmer about 5 minutes for the alcohol to evaporate. Mix well. 4. After, add the capers, some black pepper and half the parsley. Mix well. 5. Finally, add the flax (to thicken the sauce) and the lemon juice. Turn off the stove and garnish with the rest of the parsley and some lemon slices. * Nutritional info, _per serving (serves 6)_ * 286 kCal * 3.1 g total carbs, 0.66 g fiber, 2.5 g net carbs * 27.3 g protein * 16 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-08-24T00:00:00+02:00" itemprop="datePublished">24 Aug, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tacoFilling">Veg Taco Filling</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/494/30866630673_40f1925baf_o_d.jpg"/> This is super tasty for taco night, but will work for any recipe in which you want to substitute minced meat - just adapt the spices to the recipe you are using! If you are using it for mexican food - I would recommend adding some minced vegan chorizo for a more intense flavor. A recipe will be coming up soon! <ul> <li> 50 g small soy granules</li> <li> 1/2 cup pumpkin seeds (pepitas)</li> <li> 1/2 tsp cumin powder</li> <li> 1/2 tsp paprika</li> <li> 2 tbsp tomato purée</li> <li> 1 cup vegetable stock</li> <li> 1/2 small red onion (30 g)</li> <li> 1 tbsp soy sauce (optional)</li> <li> 1 tbsp lemon juice, fresh</li> <li> 2 tbsp olive oil</li> <li> Optional: fresh coriander, to garnish</li> </ul> * **Process** 1. Chop the pumpkin seeds roughly. Put the soy and the seeds in a bowl with the soy sauce and the stock for at least 10-15 minutes to hidrate. 2. Heat up the oil in a pan and add the chopped onion and garlic. Fry on medium-low heat for about 10 minutes until it looks soft. 3. Add the spices and the tomato purée. Mix and cook for about 1 minute. 4. Add the soy-seed mixture with its liquid and cook for a few minutes until it warms up. You can add more liquid if you want, or dry it out more to your liking. 5. Turn off the stove, add the lemon juice and coriander and eat! * Nutritional info, _per serving (recipe makes 4)_ * 231 kCal * 9.6 g total carbs, 1.9 g fiber, 7.7 g net carbs * 13 g protein * 17.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-08-07T00:00:00+02:00" itemprop="datePublished">7 Aug, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/ketoCabbage">Chinese Cabbage</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/558/31698882625_da6456f08b_o_d.jpg" /> This is a very easy dish with few ingredients, full of fiber, very healthy, and keto-friendly. I don't eat meat so I'm using seitan that I minced, but for omnivores, you could use ground meat (preferably a very fatty one, which would make this higher in fat). <ul> <li>1/2 medium cabbage, thinly sliced (400g)</li> <li>1/6 red onion (30 g), thinly sliced</li> <li>80 g seitan minced, OR minced meat</li> <li>2 tbsp <a href="http://amzn.to/2nRguh4">coconut oil</a></li> <li>1/2 or 1 whole garlic clove, minced</li> <li>1 tsp ginger paste</li> <li>3 tbsp soy sauce + 1/4 tsp kelp powder (optional) OR 1 tbsp soy sauce + 2 tbsp fish sauce</li> <li>1/2 tbsp tahini paste or peanut butter</li> <li>1/4 tsp pepper</li> <li>1/4 tsp of red chili paste (or to taste)</li> <li>2 eggs</li> <li>Sweetener of choice - I used stevia</li> <li>To serve: lemon juice</li> </ul> * **Process** 1. In a pan, fry the ginger and garlic on the oil for 30 seconds. 2. Add the cabbage and onion. Cook covered on medium heat for 5-10 minutes. Meanwhile, mix the soy sauce, kelp, tahini, black pepper and chili powder. 3. When it starts to soften, add the seitan (or meat)and mix. Cook for another 2 minutes. 4. Then,add the sauce, mix and cook for a couple of minutes. 5. When the cabbage is soft, add the eggs as shown in the video: add them raw and mix fast, so they cook covering the cabbage to make it moist. * Nutritional info, _per serving (1/3 recipe)_ * 223 kCal * 12.1 g total Carbs, 3.9 g fiber, 8.2 g net carbs * 14.6 g protein * 14 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-07-26T00:00:00+02:00" itemprop="datePublished">26 Jul, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/thaiCurry">Thai-inspired Curry</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/500/31552406632_0b455a3b31_o_d.jpg" /> Super easy and incredibly delicious recipe. Can be vegan and gluten-free, and is full of fiber, flavor, healthy fats – and great for keto-ers! Just add some more fat to fit your macros, and use whatever vegetables you prefer. And if you wish to avoid tofu, you can use paneer (although this will increase the fat content of the recipe). I like to at it with a big green salad and some keto bread. Makes for an awesome meal to pack for work! <ul> <li>1 tbsp sesame oil</li> <li>1 tbsp olive oil</li> <li>600 g tofu OR 450 g paneer</li> <li>1/3 of a purple onion, thinly sliced (35 g)</li> <li>1 tsp ginger paste</li> <li>100 g spinach, cooked (I use frozen spinach that I then cook in the microwave!)</li> <li>1/3 cup of coconut milk (75 g)</li> <li>1/4 tsp powdered cumin</li> <li>1 tsp powdered coriander</li> <li>1/4 tsp red chili powder (or more to taste)</li> <li>1/4 tsp black pepper</li> <li>2 basil leaves optional</li> <li>Sugar to taste (I used stevia)</li> <li>2 tbsp soy sauce (or 1 tbsp soy sauce + 1 tbsp fish sauce)</li> <li>Half a bunch of broccoli (250 g) (previously steamed, or use it raw and let it cook longer)</li> <li>Optional: 60 g of carrot (omit if keto)</li> <li>Optional: some fresh coriander</li> <li>To garnish: 40 g roasted or fried almonds or peanuts, chopped</li> <li>To garnish: lemon or lime</li> </ul> * **Process** 1. Start by frying the onion, ginger and carrots over medium heat 2. In a blender, blend the ingredients for the sauce: spinach, coconut milk, cumin, coriander, chili, black pepper, basil, stevia, soy sauce. Set aside for later. 3. Once the onions are very soft, add the tofu and cook over medium-high until it gets golden. 4. Add the rest of the vegetables and cook until they are tender (I used steamed broccoli so I only cooked it for 2 minutes so it would warm up). 5. Add the sauce and cook for 2 minutes. 6. Turn of the heat, sprinkle with the chopped nuts and serve with some lemon or lime. * Nutritional info, _per serving (serves 4)_ - 416 kCal - 16.6 g total Carbs, 7.6 g fiber, **9 g net carbs** - 30.1 g protein - 29.6 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-07-18T00:00:00+02:00" itemprop="datePublished">18 Jul, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/eggCurry">Egg curry</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/551/31661912786_fa6fbfefca_o_d.jpg" /> Since going keto two weeks ago I have been craving good indian food. Unfortunately, dal chawal (lentil curry with rice) is not really keto-friendly, so an egg curry with some salad and/or cauli-rice seemed like a good enough substitute! This is more of a pattern to make a very easy egg curry. I usually just add more or less spices depending on how I am feeling that day, so feel free to change the amounts and/or add other spices or ingredients - maybe amchoor, some chunks of red bell pepper... Experiment! <ul> <li>18 boiled eggs, peeled</li> <li>400 g tomatoes, chopped</li> <li>1 tbsp tomato paste</li> <li>300 g onions, chopped</li> <li>4 garlic cloves, chopped</li> <li>An inch of ginger, chopped (or 1 tsp ginger paste)</li> <li>2 tsp garam masala</li> <li>1 tsp turmeric powder</li> <li>1/2 tsp salt</li> <li>3 tbsp oil (I am using mustard oil)</li> <li>Optional: sugar or sweetener of choice</li> <li>1/4 cup of heavy whipping cream (6-g) (you can sub for greek yogurt or coconut milk)</li> </ul> * **Process** 1. Heat the oil in a saucepan, then add the onions. Cook for 10 minutes on medium heat until they are quite soft. 2. Add the garlic and ginger and cook for 2 minutes for the raw smell to go away. 3. Add the spices and cook for 1 minute. If it's too dry and you are scared they will burn, add some water. 4. Add the tomatoes, salt and tomato paste. Cover and cook on low for about 10-15 minutes, until the tomatoes are very soft. 5. _Optional step: you can fry the peeled eggs for a couple of minutes with some oil; this gets them slightly crunchy outside._ 6. Once the tomatoes are soft, blend the sauce and add the yogurt and sugar. Add some water if the sauce is too thick. 7. Put it back into the stove, add the eggs (whole or cut in half), let them boil together for a couple of minutes and serve with some fresh coriander. * **Nutritional info**, _per serving (serves 6)_ - 326 kCal - 9.4 g total carbs, 1.8 g fiber, **7.6 g net carbs** - 18 g protein - 23.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-06-24T00:00:00+02:00" itemprop="datePublished">24 Jun, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/pulao">Veg Pulao</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/316/31326178640_1525979703_o_d.jpg" /> This is one of my hostess' specialty, vegetable pulao, for 4-5 people. An easy one-dish meal that can be slightly changed and always comes out equally delicious. You can use chatever vegetables you ike, such as green peas, broccoli cauliflower, potatoes, red capsisum... <ul> <li>Vegetables, chopped: 1 onion, 1 carrot, 1/2 green capsicum pepper, handful of green beans, green chili to taste.</li> <li>_Optional, to add more protein: textured soy protein, soaked_</li> <li>Whole masala: 4 bay leaves, 4 green cardamoms crushed, 2 black cardamom, 4-5 cm stick of cinnamon, 10 cloves, 12 black peppercorns + 10 small whole garlic cloves</li> <li>Rice: about a cup (roughly the same volume as the vegetables), rinsed</li> <li>1 tsp cumin</li> <li>1 tsp coriander</li> <li>1/4 tsp black pepper</li> <li>Red chili to taste</li> <li>1/4 tsp fenugreek leaves (optional)</li> <li>Sugar to taste</li> <li>1/2 tsp turmeric</li> <li>1-2 tsp salt, in total</li> <li>Optional: yoghurt or curd (especially good for leftovers!)</li> <li> To garnish: coriander (about 1/2 cup), lemon juice, mint (usually saved for meat pulaos)</li> </ul> * **Process** 1. In a pan with 3-4 tbsp oil (or less, if you are fat-conscious), add the whole masala and brown them on low heat. 2. Add the onions and cook them for 15-20 minutes, until they are super brown and caramelised and delicious. 3. Add the carrots and cook them for a couple of minutes to avoid them being raw in the end. Then, add all the other veggies. Cook and cover until slightly soft, on low heat. 4. Add the soy meat, salt and spices and mix thoroughly. After a couple of minutes, add the rice, mix, add the turmeric, and mix again. 5. Now, you can either add some water and fresh coriander and cook it without a lid, or pressure cook it for 2 whistles on high flame. 6. Once the rice is cooked through, fluff up with a fork, garnish with some more coriander, and enjoy. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-06-10T00:00:00+02:00" itemprop="datePublished">10 Jun, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/bisibelebath">Bisi Bele Bath</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/609/31552398312_4d6638dcdd_o_d.jpg" /> While in India I visited Bangalore. In indian restaurants in Europe the food that is mostly served is North Indian. However, south indian cuisine has so much variety and uses such different flavours when compared to North Indian! In this case, I was taught how to make Bisi Bele Bath, a wonderful south indian dish for the rainy season. It is usually a one-pot meal, the perfect comfort food to have in a cozy evening, enough to serve 6 people. The friend that taught this to me tweaks the recipe a little bit, mixing different dals and using two pots instead of one. However, if you want to go for the most traditional version, use only toor dal and rice (it can be cooked in the same pot and at the same time as the rice), and skip the tadka; this will make for an easier one-pot meal. <ul> <li>2 cup of mixed dal</li> <li>3 fistfuls of rice and 2 of broken wheat (you can use all rice for the traditional version, about 1.5 cups)</li> <li>2 carrots, chopped</li> <li>_Optional: 2 tomatoes, chopped_</li> <li>4-5 small shallots, peeled and whole, or a few pieces of green capsicum</li> <li>_Optional: a few green beans, chopped_</li> <li>1/4 tsp asafoetida</li> <li>1/2 tsp turmeric</li> <li>Salt to taste</li> <li>1/2-1 tbsp tamarind paste (if you dont have any, you can use lemon juice instead)</li> <li>5-6 tbsp of bisibelebath masala mixture OR: 1.5 tbsp coriander powder, 1 tbsp black gram dal powder, 2-3 tsp chili powder, 1-1.5 tsp cumin powder, 1/2 tsp cinnamon powder, 1/4-1/2 tsp fenugreek powder, 3-4 cloves and a few curry leaves</li> <li>For the tadka (optional): pinch of asafoetida, dried red chilies to taste, a bunch of curry leaves, 1 tsp black mustard seeds, 1-2 tbsp roasted bengal gram (optional) or cashews, vegetable oil</li> <li>_Optional: jaggery or sugar to taste, cashew nuts (if not used in tadka)_</li> <li>_Optional: fresh coriander to garnish_</li> </ul> * **Process** 1. Wash and rinse the dal a couple of times. Tren, soak for at least 4 hours. 2. In a fast cooker,pour the dal with its soaking water, then add some salt, asafoetida, turmeric, shallots and carrots. Close the lid and let it whistle about 3 times or until it smells like the dal is cooked. 3. Meanwhile, rinse the rice and broken wheat properly. Then, put it in a pot with salted water and boil until cooked. 4. Now, mix the cooked dal and rice in the pot where you cooked the rice in and add the tomatoes. 5. Once the tomatoes are soft, add the bisibelebath masala. Mix well and cook together for a couple of minutes. Add water if it is too thick. 6. Add the tamarind into the mixture. Then, taste for salt and sweetness. 7. Finally (optionally), make the tadka. Heat up 2-3 tbsp of oil in a small pan and fry the whole spices until brown in this order: asafoetida, mustard seeds, chillies, bengal gram and curry leaves. Once it is done, add it into the pot and put a lid on it for the aromas to infuse. 8. Mix everything and serve. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-05-31T00:00:00+02:00" itemprop="datePublished">31 May, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chili">Vegan Chili</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/551/31326382390_388b0acfaa_o_d.jpg" /> There are many vegetarian people in India, so traditional spanish cuisine (very often pork-based) is not very appropriate here, and on top of that, anything european is considered bland (because no chili, no taste, apparently!). So finding something to cook that they would like (that wasnt indian food!) seemed difficult. So... chili to the rescue! I make my chili meatless and with loooooads of veggies (way more than the usual chili con carne have), and I like to add some cacao for a deeper, earthier flavor. I had to omit some spices, but I will transcribe the recipe I usually make so you can enjoy it to the fullest! For those who watch the videos: im so sorry about the terrible picture quality. But cooking in a new kitchen with limited resources and at 40 degrees temperature, being a good photographer was the least of my worries :) <ul> <li>400 g cooked kidney beans (rajma), about 3 cups</li> <li>2 cloves of garlic, very finely chopped</li> <li>2 medium onions, finely chopped</li> <li>3 red bell peppers, finely chopped (you can sub one for a different color pepper)</li> <li>2 tomatoes, chopped</li> <li>300-400 g tomato puree</li> <li>1 tbsp tomato paste</li> <li>Spices (adjust to your taste): 1/2-1 tsp cumin, _1/2 tsp oregano optional_, 1/4 tsp black pepper, _1/4 tsp cinnamon powder optional_, 1 tbsp cacao powder, 1-2 tbsp sugar, _10 g of dark cooking chocolate optional_, 1 tsp of chipotle paste _(you can substitute it for 1 tsp of red chili powder and, if you want, cook the peppers on an open flame for a couple of minutes to get that smoky flavor one gets from the chipotle.)_</li> <li>_Optional: 1/2 cup of corn grains, raw_</li> <li>Salt</li> </ul> * **Process** 1. In a large pot or pan with 2-3 tbsp olive oil, add the onions and garlic with 1/4 tsp of salt. Cook on medium-low heat for about 20 minutes until nice and soft. 2. Add the peppers and corn with 1/4 tsp of salt and cook, covered, for about 10 minutes until the peppers start to soften. 3. Add the spices (except for the chocolate) and cook 1-2 minutes. Then, add the tomato paste, puree and the tomatoes chopped, along with 1/4 tsp salt and 1/2 cup of water and cook on a low heat, uncovered. 4. After 15-20 minutes it should start to be nice and thick. It should cook for at least 20-30 minutes, so add a bit of water if it is becoming too dry. 5. When there are only a couple of minutes left for it to finish, add the chocolate and mix it well so it melts. Then, taste and add salt, chili or even chocolate if you need it. 6. Serve nice and warm. It can stay in the fridge for 3-4 days, and it even gets better flavor! It is also freezer-friendly, so I usually make a huge batch and freeze some for another week. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-05-14T00:00:00+02:00" itemprop="datePublished">14 May, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/sausage">Vegan Sausage</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/738/31326152400_e4b9f7eb3a_o_d.jpg" /> My boyfriend (who so lovingly codes everything for my website, and is the one responsible for the gorgeous look it has!) loves sausages for breakfast. It is one of the few things that I don't like him eating, since it is very fatty, processed, unhealthy meat. The only other things he would like for breakfast usually involve a long time of cooking, so I have been trying to come up with a savory breakfast for him that does not include chicken and can be cooked fast in the morning. So, these sausages came to be: meaty, spicy sausages, that take a little bit of prepping time but that can last in the fridge (or freezer) for a while, making for an easy breakfast, but also awesome in pizzas or sandwiches. You will be gladly surprised when you try it! In fact, I like these better than traditional sausages :) <ul> <li>1/2 cup cooked chickpeas or white beans, mashed with a fork</li> <li>Spices: 1 tsp garlic powder, 1.5 tsp crushed fennel seeds (the recipe I used in the beginning suggested 1 tsp of ground fennel seed instead, but I rather prefer the crushed seed version), 1 tsp spicy paprika, 1 tsp oregano, 1/2 tsp thyme, 1/4 tsp black pepper</li> <li>1/4 cup nutritional yeast (optional)</li> <li>1 tbsp tomato paste</li> <li>1 cup of vegetable broth</li> <li>1+1/4 cups of vital wheat gluten</li> <li>2 tbsp soy sauce</li> </ul> * **Process** 1. Firstly, prepare your water in the steamer. 2. Mix in a bowl the nutritional yeast and the wheat gluten. In a different bowl, mix all the other ingredients. 3. Pour the wet ingredients into the dry and mix thoroughly. You will end up with an elastic ball that forms "threads" (those are your proteins!). 4. Make the shape you want: either form small sausages or one big loaf. Cover each sausage/loaf with cheese cloth. - _If you don't have any cheese cloth, I recommend using sterile gauze pads (If you have a doctor in the family, you will probably have some around the house!)_ 5. Place on your steamer and steam about 35 minutes if making small sausages, or about 50 min if making one big loaf. The cooking time depends a lot on the size of your sausages, so it can vary a lot. If in doubt, just cut it in half and check that the center has changed its texture, losing that "thready" property it had when raw. 6. Eat immediately or save for later. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-05-02T00:00:00+02:00" itemprop="datePublished">2 May, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chewmeinEng">Spiralized chowmein</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/608/31698792525_4c207670e9_o_d.jpg" /> Chowmein is an indo-chinese dish, very typical from Nepal: streetfood served often in doubtious places, but delicious! Normally this would use whole-wheat noodles, but I decided to substitute them for spiralized vegetables. I am using turnips, but you could use other white vegetables. It also usually has carrot but I am avoiding it to keep it low-carb. The most popular ones are Veg Chowmein (vegetarian) and Chicken Chowmein (chicken), although other types of meat can be used, or shrimp or egg. I sometimes make it using tofu (to have some protein but keep it vegan), but whoever wants to can add the meat or shrimp along with the vegetables so they fry together. And of course, quantities are just to orientate you, and can be adapted! This is a strong and tasty dish, spicy and slightly sweet, perfect for 3-4 people. I hope you like it. <ul> <li>3 spiralized turnips, 360g (or you can substitute for whole-wheat noodles)</li> <li>1/4 cabbage (300g), thinly sliced (you can use the spiralizer for this!)</li> <li>1/2 red bell pepper (60g), cut in trips</li> <li>1 medium red onion (100g)</li> <li>Other optional vegetables, such as a handful of boiled green beans</li> <li>250 g firm tofu (optional)</li> <li>2 garlic cloves very finely chopped or 1 tsp garlic paste</li> <li>Strips of fresh ginger (that should be added with the other vegetables) or 2 tsp ginger paste (that would be added with the garlic)</li> <li>3 eggs (optional)</li> <li>Optional: spring onions, for garnishing</li> <li>4 tsp soy sauce (half could be substituted for oyster sauce, for non-vegetarian people)</li> <li>1/2 tsp cumin</li> <li>1 tsp red chili paste or red chili powder (this should be adapted to taste; 1 tsp is very spicy)</li> <li>Salt. </li> <li>Optional: 2 tsp rice vinager, lime juice, or something similar</li> <li>3 tbsp of coconut oil</li> <li>To serve: ketchup and chili sauce (such as Sriracha)</li> </ul> * **Process** 1. In a big enough pan, over medium-high heat, put a tablespoon of oil and then fry the cubed tofu until golden, for about 5 minutes. Later, take it out and put aside for later. 2. Pour the rest of the oil in the pan and add the onion. Let them cook for 5 minutes. When they start to turn translucent, add the rest of the vegetables and cook until tender. 3. Add the garlic and ginger and cook for 2-3 minutes so it loses the raw flavor. 4. Add the vegetable "noodles", mix well and then pour the sauce over everything. 5. Cook for about 5 minutes or until the "noodles" are tender. Check for salt. 6. Serve with some kétchup and chili sauce on top. * **Nutritional information**, per 1/3 recipe - 334 kCal - **15.5 g net carbs**, 6.2 g fiber, 21.7 g total carbs** - 16.4 g protein - 22.2 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-04-11T00:00:00+02:00" itemprop="datePublished">11 Apr, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tikkaMasalaEng">Tikka masala</a></h2> <div class="post-content"> <img src="https://farm6.staticflickr.com/5583/31552267092_2b780b9375_o_d.jpg "/> Chicken Tikka Masala (that can also be made with paneer or tofu to keep it vegetarian) is one of the most typical dishes in indian restaurants. It has a thick onion and tomato sauce, spicy with a sweet touch, that is always a hit. On top of that, it is easier to make than it seems. It doesn't require many ingredients, and it always comes out great. Try it! <ul> <li>700 g chicken or paneer tikka</li> <li>4 peeled tomatoes (450 g or 3 cups)</li> <li>1 chopped medium onion (110g)</li> <li>3 garlic cloves, chopped, or 1 tsp garlic paste</li> <li>2'5 cm minced ginger or 1.5 tsp ginger paste <i>(use 2/3 of the amount if making paneer or tofu tikka masala)</i></li> <li>Stevia to taste (equivalent to 2 tbsp brown sugar)</li> <li>1 tbsp tomato paste</li> <li>2 tsp garam masala</li> <li>1/4 tsp chili or to taste</li> <li>2 tbsp oil or ghee</li> <li>Optional: 4 tbsp heavy cream (or yoghurt). <i>(You can substitute it for coconut milk if you want a vegan Tikka Masala.)</i></li> </ul> * **Process** 1. Heat up the oil and fry the onions for 5 min. 2. Add the garlic and ginger and cook for 2 min. 3. Add the spices and mix around, cooking it for 30 seg. 4. Add the rest of the ingredients, cover and cook on low heat for 20 min. 5. Take off the heat and process the sauce until smooth. Add the cream or yoghurt, and then the chicken or paneer tikka. 6. Let everything boil together for a few minutes and serve with pilao rice. * **Nutritional info**, for 1/5 of the sauce (for information on the chicken/paneer/tofu tikka, visit the [tikka recipe](http://maria.recipes/tikkaEng): - 148 kCal - **5.1 g net carbs**, 1.6 g fiber, 6.7 g total carbs** - 1.4 g protein - 13 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-04-03T00:00:00+02:00" itemprop="datePublished">3 Apr, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/cauliPizza">Cauliflower pizza crust</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/491/31326268320_3a52cb5ffb_b_d.jpg" /> A good way of sneaking some vegetables inside of the pizza... It's very hard to tell the crust is made of cauliflower! And it's a great way of having a low-carb, high-fiber dinner. Don't be skeptical and give it a try. It is delicious! <ul> <li>1 big cauliflower or 5 cups (600g) of <a href="http://maria.recipes/cauliflowerRice">cauliflower rice</a></li> <li>2 eggs</li> <li>1/4-1/2 tsp salt</li> <li>1 tsp oregano</li> <li>3/4 cup grated parmesan (70g)</li> </ul> * **Process** 1. Put the cauliflower rice in two batches in the microwave for 5 minutes. Afterwards, put all the cooked cauliflower into a clean teatowel, fold it and squeeze as much water as you can. If your arms are starting to hurt, you are doing it right. You should spend 5 or 10 minutes doing this, so the final result has good consistency. 2. Once squeezed properly, mix all the ingredients and preheat your oven to 180C 3. Poner la masa sobre un papel de horno en una bandeja de horno y darle forma con las manos. - _The thickness depends on your taste, but it should be even. For pizza I make it 0.3 cm thick, but you can also make tortillas making it very thin, and later on use them for wraps._ 4. Bake until golden. It is a good idea to put it on the lower part of the oven for the last couple of minutes so that the base doesn't end up soggy. 5. Take out of the oven, put the toppings you like, bake it for a couple more minutes so the cheese melts, and... _voilà!_ * **Nutritional information**, for half a pizza (recipe makes two pizzas) - 137 kCal - **5.2 g net carbs**, 3 g fiber, 8.2 g total carbs - 11.9 g protein - 7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-03-27T00:00:00+01:00" itemprop="datePublished">27 Mar, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/zoodles">Zoodles with Tuna</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/720/31583110831_9b91938b81_o_d.jpg" /> This is, hands down, my favorite spiralized recipe. It literally takes 5 minutes to put together, it's healthy, flavourful, balanced... I could eat it every day! <ul> <li>1 medium sized zucchini, spiralized (200g)</li> <li>1/4 tsp garlic powder</li> <li>3 tbsp cream cheese (45g)</li> <li>100g canned tuna, drained</li> <li>1 and 1/2 tablespoon extra virgin olive oil</li> <li>1tbsp Balsamic vinegar</li> <li>Salt, pepper</li> </ul> * **Process** 1. In a pan, put a teaspoon of oil over medium heat. Once it's hot, add the zoodles and cook with the garlic powder, salt and pepper for about 2 minutes, just enough time for them to start getting soft. - _If overcooked, the zoodles will release water._ 2. Add the cheese and then mix everything, so the cheese melts and forms a sauce. 3. Serve with tuna, olive oil and vinager. * **Nutritional information**, for the whole recipe - 423 kCal - **8.4 g net carbs**, 2.1 g fiber, 10.5 g total carbs - 25.1 g protein - 34.4 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-03-13T00:00:00+01:00" itemprop="datePublished">13 Mar, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/steamedEggplant">Steamed eggplant</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/692/31698867005_cb7441a179_k_d.jpg" /> A very easy to make, healthy and tasty recipe. The different flavours combine perfectly, and I often omit the ham for a vegan version. Steaming the eggplant makes the flavour stand out a lot, which I find lovely, but if you are not an eggplant fan, this is not for you! <ul> <li>2 eggplants</li> <li>100 g cubed tofu</li> <li>50-100 g cubed or sliced and chopped ham (optional; can be omitted for a vegan version)</li> <li>For the sauce: 2 tbsp soy sauce, 2 tbsp white whine (or 1 tbsp vinager and a bit of honey, to taste), optional: 1-2 cloves of garlic finely chopped, optional: 1/2 tsp ginger paste, ground black pepper, salt (depending on how salty the soy sauce is), 1 tbsp corn starch</li> <li>Fresh coriander, or fresh parsley for those who don't like coriander</li> </ul> * **Process** 1. Prepare a pan in which you will steam the eggplant. 2. Cut the eggplants lenghtwise and make some cuts into the flesh without going all the way through. 3. Put the eggplants on the recipient where you will steam them later.. 4. Put the ham and tofu on top, and then pour the sauce over everything for it to impregnate the eggplant. Garnish with a little bit of coriander or parsley. - _Don't spill the sauce; if there is too much, keep it and add it a couple of minutes before it is done cooking._ 5. Steam for about 25 minutes until the eggplants are tender. Add some more coriander or parsley, then serve. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-02-14T00:00:00+01:00" itemprop="datePublished">14 Feb, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/friedRice">Fried &quot;Rice&quot;</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/311/31569030800_c6342f7872_o_d.png" /> Another great way to use the cauliflower "rice": make chinese fried rice! It was a huge hit with my guests :) <ul> <li>1/2 cup processed cauliflower or 3 cups (360g) of <a href="http://maria.recipes/cauliflowerRice">cauliflower rice</a></li> <li>180g g shrimp (I buy frozen raw shrimp and thaw)</li> <li>40 g boiled green peas (mine were canned)</li> <li>1/2 carrot, cubed (30g)</li> <li>3 eggs</li> <li>3 tbsp coconut oil (or 2 of coconut oil and 1 of sesame oil)</li> <li>2-3 tbsp soy sauce</li> <li>1/2 tsp ginger paste</li> <li>1/2 tsp garlic paste (1-2 cloves)</li> <li>Salt, black pepper</li> <li>3 tbsp (20g) Spring onion to garnish</li> </ul> * **Process** 1. In a pan with a tablespoon of oil, add the garlic and ginger. After cooking for a minute, add the carrots with a bit of salt and pepper. 2. Cook on medium heat for about 5 minutes until the carrot is slightly soft. Turn up the heat and add the shrimp. 3. Cook the shrimp for a couple of minutes and then add the green peas. Cook for one minute. 4. Add the processed cauliflower, soy sauce, stir very well and cook for a couple of minutes until the cauliflower is soft. 5. Make a small space in the pan and crack the eggs on it; cook them mixing constantly, then incorporating them onto the rice. Check salt and pepper. 6. Garnish with spring onion. * **Nutritional information** - For half the recipe - 403 kCal - **10.2 g net carbs**, 4.2 g fiber, 12.5 g total carbs - 26.3 g protein - 28.8 g fat - For half the recipe, without carrots and peas - 327 kCal - **7.4 g net carbs**, 3.9 g fiber, 11.3 g total carbs - 26.1 g protein - 28.8 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-01-20T00:00:00+01:00" itemprop="datePublished">20 Jan, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/palakPaneerEng">Easy Palak Paneer</a></h2> <div class="post-content"> <img src= "https://farm1.staticflickr.com/273/31698838425_d6a909cc53_o_d.jpg" /> One of my favourite vegetarian foods is palak paneer, a spinach and cheese curry. There is only one minor problem with it, and it is precisely one of its key ingredients: Paneer. Don't get me wrong. I love it. But I cannot seem to be able to find it in stores, trying to replace it with other cheeses just leads to weird-looking attempts at the recipe, and making the paneer myself... well. has anyone tried to make paneer from scratch on a busy week? Um... not very practical. So, the ultimate way to make palak paneer is to not make palak paneer at all, but to make palak TOFU. Yup, you read that right. Tofu actually has quite a neutral flavour that works very well with the spices of the dish, it holds its shape properly, gives nice texture and colour, and from a nutritional point of view, I quite prefer it to the paneer. I know this may sound strange, but seriously: my lovely indian boyfriend enjoyed it a lot, and he was so impressed that I had actually taken the time to make the paneer from scratch... it was only after several times of making it that I told him it was tofu! <ul> <li>300 g paneer or tofu (if using tofu: freeze and defreeze so it firms up)</li> <li>450 g frozen chopped spinach</li> <li>2 tbsp coconut oil (3 if using tofu)</li> <li>1/2 big onion, finely chopped (75 g)</li> <li>1 tsp garlic paste or 2 garlic cloves</li> <li>1 tsp ginger paste or 1 inch ginger</li> <li>Optional: 1 green chili, desseded and sliced</li> <li>1/2 tsp whole cumin seeds</li> <li>2 bay leafs or 1 big indian bay leaf</li> <li>1/4 tsp turmeric</li> <li>1/2 tsp garam masala</li> <li>1/2 tsp ground black pepper</li> <li>Optional: 1/4 tsp red chili powder</li> <li>2 tbsp heavy whipping cream (4 tbsp if using tofu)</li> <li>Optional: 1 tsp dry fenugreek leaves (you can leave it out and maybe add 1&2 tsp cinnamon and garnish with coriander, but the flavor will be very different)</li> <li>Salt</li> </ul> * **Process** 1. Cook the spinach according to the package instructions (I cook mine in the microwave). 2. In a pan, put some oil (1/2-1 tbsp) with the whole spices and the chili. Once they start warming up, add the garlic, ginger and onion, with a pinch of salt. 3. Brown in the pan for about 10 minutes until the onion is tender. Then, add the powdered spices and cook for one minute. 4. Add the spinach with some water and salt. Let cook for 5 minutes. 5. Add the tofu and let cook together for a couple of minutes. 6. Let it cook until the water has evaporated to the consistency of the gravy you like. 7. Turn off the stove, add the yoghurt and the fenugreek leaves and serve. **Nutritional information**, per serving (serves 3) - 488 kCal - **8.5 g net carbs**, 5.2 g fiber, 13.7 g total carbs - 26.1 g protein - 38.7 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-01-10T00:00:00+01:00" itemprop="datePublished">10 Jan, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tandooriChicken2">Easy Tandoori Chicken</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/299/31552272542_31a838d294_o_d.jpg" /> Tandoori chicken with easily available spices - you have no excuse not to make it now, Marta ! <ul> <li>4 chicken thighs, with bone (if boneless, should be around 800 g)</li> <li>1 cup yoghurt (10% fat)</li> <li>Ginger paste - 2 tbsp</li> <li>Garlic paste - 2 tbsp</li> <li>4 tsp paprika </li> <li>1/2 tsp chili</li> <li>3 tsp coriander powder</li> <li>1.5 tsp cumin</li> <li>1 tsp cinnamon</li> <li>1 tsp garlic powder</li> <li>1/2 tsp ginger powder</li> <li>2 tsp onion powder</li> <li>3/4 tsp salt (start with less and add to taste)</li> <li>2 tbsp lemon juice</li> </ul> * **Process** 1. Make slits in the chicken. 2. Mix the yoghurt, lemon and spices. Try the mix to adjust salt. 3. Marinate the chicken and let sit in the fridge at least 4 hours. **_Very important to marinate properly in this case since we are using less spices; otherwise the chicken might be bland._** 4. Preheat the oven to 250 degrees. 5. Put the chicken on the griddle and a baking sheet underneath to collect any juices. 6. Cook until dry and crunchy, at least 30 minutes. 7. Let rest a couple of minutes before serving. * **Nutritional information**, for 1 piece of chicken (200 g, boneless) - 291 kcal - **3.3 g net carbs**, 0.6 g fiber, 3.9 g total carbs - 39.7 g protein - 12.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2016-01-02T00:00:00+01:00" itemprop="datePublished">2 Jan, 2016</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/asianSalad">Vietnamese salad</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/554/31583197911_a3e952bc5c_o_d.jpg" /> This simplified version of Goi Ga, a vietnamese salad, is a unique combination of flavours. Don´t miss it! You can change the ingredients slightly to fit your macros (for example, using more chicken). If you are doing keto, you might want to add some more oil to the recipe. <ul> <li>1/2 a head of cabbage (600g) <i>(Can be subbed for salad, but it won´t be the same)</i></li> <li>Optional: 1/2 cup Bean sprouts</li> <li>1/2 red onion (50g)</li> <li>Fresh mint (aprox. 1/2 cup) (essential!)</li> <li>Cubed cooked boneless chicken thighs (2 chicken thighs, 300 g when raw)</li> <li><i>Optional: 1/4 cup fresh coriander</i></li> <li>Optional: One carrot (if using, carb count will increase)</li> <li>3/4 cup peanuts (100g) or almonds, fried or toasted, chopped</li> <li>3 tbsp rice vinegar (or apple vinager if not available)</li> <li>Stevia to taste</li> <li>3 tbsp olive or coconut oil</li> <li>1 tbsp fish sauce (optional)</li> <li>4 tbsp lime or lemon juice</li> <li>1-2 clove of garlic very finely chopped (or coarsely chopped, letting it infuse and then fishing it out)</li> <li>Optional: 3-4 chopped spring onion (45 g)</li> <li>Salt, black pepper, pinch of powdered chilli</li> </ul> * **Process** 1. Chop everything. It´s very important to slice the cabbage very finely. 2. Make the dressing with the olive, vinegar, lemon juice, fish sauce, garlic, salt, pepper and chili. Then add enough stevia to have a mostly sweet dressing but that still has some acidic hints to it. 3. Put everything in a salad bowl, dress it, mix and serve. * **Nutritional facts**, per serving (serves 4): - 392 kCal - **10.3 g net carbs**, 7.1 g fiber, 17.4 g total carbs - 24.4 g protein - 26.9 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-12-20T00:00:00+01:00" itemprop="datePublished">20 Dec, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/tandooriChicken">Tandoori Chicken</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/292/31698817095_ca8f8c24ec_o_d.jpg" /> </br> This is a very typical indian entrée, that can be made with chicken, paneer, or even vegetables like mushrooms. I like to have it as a main course with a big green salad with lots of olive oil, as well as some fresh tomato, red onions and coriander. If you cannot find tandoori masala, you can use [this recipe instead](http://maria.recipes/chickenTandoori2) <ul> <li>4 chicken thighs, with bone (if boneless, should be around 800 g)</li> <li>1 cup yoghurt (10% fat)</li> <li>2 tbsp tandoori masala</li> <li>Ginger paste - 2 tbsp</li> <li>Garlic paste - 2 tbsp</li> <li>1 tsp paprika</li> <li>1/2 tsp chili</li> <li>3/4 tsp salt (start with less and add to taste)</li> <li>2 tsp coriander powder</li> <li>2 tbsp lemon juice</li> </ul> * **Process** 1. Make slits in the chicken. 2. Mix the yoghurt, lemon and spices. Try the mix to adjust salt. 3. Marinate the chicken and let sit in the fridge at least 4 hours. 4. Preheat the oven to 250 degrees. 5. Put the chicken on the griddle and a baking sheet underneath to collect any juices. 6. Cook until dry and crunchy, at least 30 minutes. 7. Let rest a couple of minutes before serving. * **Nutritional information**, for 1 piece of chicken (200 g, boneless) - 291 kcal - **3.3 g net carbs**, 0.6 g fiber, 3.9 g total carbs - 39.7 g protein - 12.1 g fat </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-11-27T00:00:00+01:00" itemprop="datePublished">27 Nov, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/wraps">Vegan Wraps</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/730/31326293290_586f0622c3_o_d.jpg" /> This is a great filling for a wrap. You can use a crepe-type wrap like I did, or other things like tortillas, chapati or dosa to keep it vegan. <ul> <li>1 cup flour (whole wheat or all-purpose flour)</li> <li>1/2 cup oats</li> <li>1/4-1/2 tsp salt</li> <li>1 egg</li> <li>Three tomatos</li> <li>Half an onion or one shalot, fresh parsley or coriander, salt</li> <li>One avocado</li> <li>400 g of cooked red kidney beans.</li> <li>1-2 tbsp tomato paste, to taste. If not available, can be substituted for fresh tomato (but will require longer cooking time).</li> <li>Salt, to taste (1/2 tsp)</li> <li>Spices, to taste: 1 tsp coriander, 1 tsp cumin</li> <li>Optional: 1/2 onion.</li> <li>Chili, to taste. I use 3-4 fresh chilies, taking the seeds out.</li> </ul> * **Process** 1. To form the crepe mixture, mix the dry ingredients, add the egg, mix and then add the water (1-1.5 cups), a little bit at a time, until you get a thin consistency. Let it sit for 10-15 min. Then cook in a very lightly greased nonstick pan on medium-high heat. 2. For the tomato mixture, chop the tomatoes, half an onion, parsley or coriander and salt and mix; do not add the salt until the very end to prevent the tomato from releasing water. - _If the raw onion flavour is too much, put the chopped onion in cold water for 10-15 min before using._ 3. To prepare the avocado: slice it, add some lemon juice, salt and pepper and mix. 4. To prepare the filling: - Fry the onion, if using; then, add all the ingredients at the same time. - _I use the red kidney beans with the liquid from the jar too, but if you want to, you can substitute it for water._ - Cook on medium heat, stirring, until the mixture is quite thick. 6. Fill the crepes with the tomato, avocado and beans, wrap it up and eat! A perfect recipe for meatless days! </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-11-25T00:00:00+01:00" itemprop="datePublished">25 Nov, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/dalEng">Dal</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/758/31661918516_311af00836_o_d.jpg" /> <ul> <li>1 cup dal (dry lentils); I like using red lentils, which cook fast</li> <li>3 onions</li> <li>Optional: tomato, peppers or any veggies lying around the kitchen</li> <li>Optional: fresh green chillies to taste (I use 3)</li> <li>1 tsp whole cumin seeds</li> <li>1 tsp garlic paste (about 2 garlic cloves)</li> <li>1 tsp ginger paste</li> <li>1/2 tsp turmeric</li> <li>1.5-2 tsp garam masala (to taste)</li> <li>Salt, to taste</li> <li>Oil</li> <li>Optional, to garnish: lemon, fresh coriander.</li> </ul> * **Process** 1. En a casserole, put water with a pinch of turmeric and the dal; once boiling, cover and simmer on low heat, stirring occasionally. 2. Meanwhile, in a pan, add some oil and the cumin seeds. 3. Once the cumin is golden, add the chili and onions (and any other vegetable you might use that takes long to cook). 4. Cook on medium heat until the onion is tender. 5. Add the garlic and the ginger paste and cook stirring for a minute. 6. Add the other spices. * _At this point you could add soft vegetables such as tomatoes and let them cook for a couple of minutes._ 7. Cook about 30 sec-1 min, then turn off the heat. 8. During this time, the dal should've been cooking; the simmering time depends on the type of lentil and your taste (30-60min) * _I don't mind if my dal stil has some texture to it, but if you leave it long enough, it will form a puree like in the video_ * _If the dal is too liquid, turn up the heat and cook uncovered a couple of minutes; if it's too dense, add a splash of water._ 9. Mix in the vegetables with the dal and cook together for 5-10 minutes. Serve with a splash of lemon juice and some fresh coriander. </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-11-20T00:00:00+01:00" itemprop="datePublished">20 Nov, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chanaMasalaEng">Chana Masala</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/715/31698795205_21f826a6a2_b_d.jpg" /> <ul> <li>1 tbsp grated ginger</li> <li>2-3 green chillies / dried red chillies</li> <li>1/2 a lemon, squeezed (1 tbsp lemon juice)</li> <li>2 tsp black pepper</li> <li>1 tsp cumin seeds</li> <li>2 inch piece cinnamon</li> <li>Optional: 1 black cardamom</li> <li>2 tsp roasted cumin powder (dry roast in a pan for about 5 minutes, then powder)</li> <li>2-3 bay leaves</li> <li>2-3 cloves garlic</li> <li>1/4 cup coriander leaves, finely chopped</li> <li>1 1/4 cup black tea (let the tea bag in the hot water for 3 minutes)</li> <li>2 roma tomatoes, finely chopped</li> <li>1/4 cup onion, chopped (plus extra for garnishing)</li> <li>2 cans canned chickpeas/ garbanzo beans, drained and washed - about 500-600 grams</li> <li>2-3 tbsp vegetable oil</li> <li>1 tsp garam masala</li> </ul> * **Process** 1. In a big enough saucepan, heat the oil. Add in the cinnamon, bay leaves, black cardamom and cumin seeds (and dried red chillies if using any). 2. Cook for 30 seconds until the aroma develops. 3. Add the ginger, garlic and green chillies. Cook stirring for 30 seconds. 4. Add the onions and cook on medium heat, covered, until soft. 5. Add the chopped tomatoes and cook for 5-10 minutes. 6. Pour the tea and the chickpeas into the pan. Add salt to taste and the rest of spices. 7. Cook uncovered, stirring occasionally, for 10 minutes. 8. Add the lemon juice, test to adjust seasoning. 9. Mix the coriander leaves, garnish with raw onion and serve with lemon slices. _The best to use is red onion for the garnishing; if non available, I recommend leaving them in cold water for 10 minutes so their taste gets milder._ </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-11-10T00:00:00+01:00" itemprop="datePublished">10 Nov, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/chickenBiryaniEng">Chicken Biryani</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/377/30857157024_5b0b64f26e_o_d.jpg" /> <ul> <li>1 kg chicken, better with bones. <li>For marinating: 1/2 cup yoghurt (125g), 1/2 tsp cumin, 1/2 tsp coriander, 1/4 turmeric, 1/4 chili, salt, 1/4 cup fresh coriander and 1/4 fresh mint</li> <li>2 cups of basmati rice - to be cooked in salty water</li> <li>Yoghurt: 1/2 cup (125 g)</li> <li>2 medium onions, caramelized</li> <li>Vegetables to taste: red pepper, cooked green peas</li> <li>Garlic paste: 2 tsp</li> <li>Ginger paste: 2 tsp</li> <li>Optional: Green chili to taste.</li> <li>Whole spices: cinnamon, bayleaf, 4 green cardamoms, 4 cloves. Others, optional: 5-6 black peppercorns, 1 black cardamom, 3 pieces of mace (can be subbed for a bit of nutmeg)</li> <li>1 tsp black cumin _(or regular cumin)</li> <li>Ground spices: 1 tsp cumin, 1 tsp coriander, 1/4 turmeric, 1/4 chili, 1/2 salt (to taste). </li> <li>Optional: 1/2 tsp garam masala.</li> <li>Fresh mint: 1/4 cup</li> <li>Fresh coriander: 1/4 cup</li> </ul> * **Process** 1. Fry the onion on very slow heat with a pinch of salt until caramelized. 2. Boil the rice about 6 min, until 80% cooked through. 3. In vegetable oil, fry the whole spices for a few secons. 4. Add the black cumin and let crackle, being careful not to burn it. 5. Add the garlic, ginger and green chili. Fry for 1 minute. 6. Add the chicken, vegetables and the rest of the spices. 7. Cook for 15-20 minutes; the chicken must be slightly undercooked. 8. In a greased casserole, form the biryani layers: rice - chicken - rice - onion. 9. Cover and let everything cook slowly for about 20 minutes. 10. Check that the rice and chicken are properly cooked before serving. _Serve with yoghurt-mint sauce or with coriander-mint Raita._ </div> </article> <article class="post" role="article" itemscope itemtype="http://schema.org/BlogPosting"> <div class="post-meta clear"> <time datetime="2015-11-08T00:00:00+01:00" itemprop="datePublished">8 Nov, 2015</time> <span class="category"> <a href="/categories/main/">main</a> </span> </div> <h2 class="post-title" itemprop="name headline"><a itemprop="url" href="/beanBurgers">Bean Burgers</a></h2> <div class="post-content"> <img src="https://farm1.staticflickr.com/718/30888718073_89e0605629_o_d.jpg" /> <ul> <li>500 g cooked red kidney beans</li> <li>2 tbsp besan (chickpea flour) - can be subbed for oat flour or breadcrumbs</li> <li>2 tsp cumin</li> <li>2 tsp paprika</li> <li>1 tsp oregano</li> <li>2 tsp onion powder</li> <li>1/2 tsp garlic powder</li> <li>1/4-1/2 tsp salt (start with less and adjust to taste)</li> <li>1/2 tsp black pepper</li> <li>1/4-1/2 tsp chili</li> <li>Optional: a bit of Worcestershire sauce</li> <li>2 tbsp chopped fresh coriander </li> <li>Optional: breadcrumbs with salt to coat the burguers</li> </ul> * **Process** 1. With a fork, mash the beans to get a paste that still has some texture. 2. Add the rest of ingredients. 3. Form the “burguers” using your wet hands. - _Optional: coat with breadcrubs, which makes the forming easier._ 4. Cook in an oiled pan over medium-high heat, not moving it in the first few minutes. Serve with **avocado**, chipotle sauce, or whatever you like! </div> </article> </section> </section> </main> <footer class="footer"> <div class="social clear"> <a href="https://www.facebook.com/maria.silva.5851"><svg title="facebook" width="16" height="16"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/social-icons.svg#facebook-icon"></use></svg></a> <a href="https://www.instagram.com/maria.recipes/"><svg title="instagram" width="16" height="16"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/social-icons.svg#instagram-icon"></use></svg></a> <a href="mailto:msilvaf.x@gmail.com"><svg title="Email" width="16" height="16"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/social-icons.svg#email-icon"></use></svg></a> </div> <p>Maria.Recipes &copy; 2019 &middot; All Rights Reserved.</p> </footer> </section> <script src="/assets/js/jquery-1.12.2.min.js"></script> <script src="/assets/js/jquery.mCustomScrollbar.min.js"></script> <script src="/assets/js/lunr.min.js"></script> <script src="/assets/js/lunr-feed.js"></script> <script src="/assets/js/backtotop.js"></script> <script src="/assets/js/jquery.fitvids.js"></script> <script src="/assets/js/svg4everybody.min.js"></script> <script src="/assets/js/Dropdown.js"></script> <script src="/assets/js/embed.js"></script> <script src="/assets/js/scripts.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-89576148-1', 'auto'); ga('send', 'pageview'); </script> <!-- Start of StatCounter Code for Default Guide --> <script type="text/javascript"> var sc_project=11165314; var sc_invisible=1; var sc_security="c5d3b5de"; var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www."); document.write("<sc"+"ript type='text/javascript' src='" + scJsHost+ "statcounter.com/counter/counter.js'></"+"script>"); </script> <noscript><div class="statcounter"><a title="website statistics" href="http://statcounter.com/" target="_blank"><img class="statcounter" src="//c.statcounter.com/11165314/0/c5d3b5de/1/" alt="website statistics"></a></div></noscript> <!-- End of StatCounter Code for Default Guide --> <script type="text/javascript"> // Automatically sets the first post image as a featured image on Facebook and Twitter. var firstImg = jQuery('.post.single .post-content').find('img:first-of-type'); var firstImgSrc = firstImg.attr('src'); if (typeof firstImgSrc !== 'undefined') { jQuery('meta[property="og:image"]').attr('content', firstImgSrc); jQuery('meta[name="twitter:image"]').attr('content', firstImgSrc); } firstImg.addClass('post-img'); console.log(firstImgSrc); </script> </body> </html>
{ "content_hash": "a8699082a88e3732e7ff94a611b0f1b5", "timestamp": "", "source": "github", "line_count": 5907, "max_line_length": 666, "avg_line_length": 36.636532927035724, "alnum_prop": 0.5457599393748961, "repo_name": "shashwatx/shashwatx.github.io", "id": "184258a0969710f7bef8e8c6559da2a5d7fbdceb", "size": "216470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "categories/main/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3663" }, { "name": "HTML", "bytes": "21894201" }, { "name": "JavaScript", "bytes": "10130" }, { "name": "Ruby", "bytes": "702" } ], "symlink_target": "" }
<?php $vo_result = $this->getVar('result'); $vn_items_per_page = $this->getVar('current_items_per_page'); $vn_page = $this->getVar('page'); if($vo_result) { $vn_num_results = $this->getVar('num_hits'); $vn_start_result = (($vn_page - 1) * $vn_items_per_page) + 1; $vn_end_result = ($vn_page * $vn_items_per_page); if($vn_end_result > $vn_num_results){ $vn_end_result = $vn_num_results; } print "<div id='searchCount'>"._t("Showing %1 - %2 of %3:", $vn_start_result, $vn_end_result, $vn_num_results)."</div>"; print '<div id="itemResults">'; $vn_item_count = 0; $vn_item_num_label = $vn_start_result; $va_tooltips = array(); $t_list = new ca_lists(); while($vo_result->nextHit() && $vn_item_count < $vn_items_per_page) { $vs_idno = $vo_result->get('ca_objects.idno'); $vn_object_id = $vo_result->get('ca_objects.object_id'); $vs_description = $vo_result->get('ca_objects.pbcoreAnnotation'); if(strlen($vs_description) > 185){ $vs_description = trim(substr($vs_description, 0, 185))."..."; } $va_labels = $vo_result->getDisplayLabels($this->request); print "<div class='result'>".$vn_item_num_label.") "; print caNavLink($this->request, join($va_labels, "; "), '', 'Detail', 'Object', 'Show', array('object_id' => $vn_object_id)); print "<div class='resultDescription'>".$vs_description; print "<img src='".$this->request->getThemeUrlPath()."/graphics/nhf/cross.gif' width='8' height='8' border='0' style='margin: 0px 3px 0px 15px;'>"; print caNavLink($this->request, _t("more"), '', 'Detail', 'Object', 'Show', array('object_id' => $vn_object_id)); print "</div><!-- end description -->"; print "</div>\n"; $vn_item_count++; $vn_item_num_label++; } print "</div><!-- end ItemResults -->\n"; } ?>
{ "content_hash": "beeedea408d4e0576445c9a77e717023", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 149, "avg_line_length": 38.45652173913044, "alnum_prop": 0.607687959299039, "repo_name": "PreserveLafayette/PreserveLafayette", "id": "fc2949b5a89874b281dfc6c48d6b42f91c43fc33", "size": "2988", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "themes/nhf/views/Results/ca_objects_results_full_html.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "28850" } ], "symlink_target": "" }
#ifndef __XML_RELAX_NG__ #define __XML_RELAX_NG__ #include <libxml/xmlversion.h> #include <libxml/hash.h> #include <libxml/xmlstring.h> #ifdef LIBXML_SCHEMAS_ENABLED #ifdef __cplusplus extern "C" { #endif typedef struct _xmlRelaxNG xmlRelaxNG; typedef xmlRelaxNG *xmlRelaxNGPtr; /** * A schemas validation context */ typedef void (XMLCDECL *xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...); typedef void (XMLCDECL *xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...); typedef struct _xmlRelaxNGParserCtxt xmlRelaxNGParserCtxt; typedef xmlRelaxNGParserCtxt *xmlRelaxNGParserCtxtPtr; typedef struct _xmlRelaxNGValidCtxt xmlRelaxNGValidCtxt; typedef xmlRelaxNGValidCtxt *xmlRelaxNGValidCtxtPtr; /* * xmlRelaxNGValidErr: * * List of possible Relax NG validation errors */ typedef enum { XML_RELAXNG_OK = 0, XML_RELAXNG_ERR_MEMORY, XML_RELAXNG_ERR_TYPE, XML_RELAXNG_ERR_TYPEVAL, XML_RELAXNG_ERR_DUPID, XML_RELAXNG_ERR_TYPECMP, XML_RELAXNG_ERR_NOSTATE, XML_RELAXNG_ERR_NODEFINE, XML_RELAXNG_ERR_LISTEXTRA, XML_RELAXNG_ERR_LISTEMPTY, XML_RELAXNG_ERR_INTERNODATA, XML_RELAXNG_ERR_INTERSEQ, XML_RELAXNG_ERR_INTEREXTRA, XML_RELAXNG_ERR_ELEMNAME, XML_RELAXNG_ERR_ATTRNAME, XML_RELAXNG_ERR_ELEMNONS, XML_RELAXNG_ERR_ATTRNONS, XML_RELAXNG_ERR_ELEMWRONGNS, XML_RELAXNG_ERR_ATTRWRONGNS, XML_RELAXNG_ERR_ELEMEXTRANS, XML_RELAXNG_ERR_ATTREXTRANS, XML_RELAXNG_ERR_ELEMNOTEMPTY, XML_RELAXNG_ERR_NOELEM, XML_RELAXNG_ERR_NOTELEM, XML_RELAXNG_ERR_ATTRVALID, XML_RELAXNG_ERR_CONTENTVALID, XML_RELAXNG_ERR_EXTRACONTENT, XML_RELAXNG_ERR_INVALIDATTR, XML_RELAXNG_ERR_DATAELEM, XML_RELAXNG_ERR_VALELEM, XML_RELAXNG_ERR_LISTELEM, XML_RELAXNG_ERR_DATATYPE, XML_RELAXNG_ERR_VALUE, XML_RELAXNG_ERR_LIST, XML_RELAXNG_ERR_NOGRAMMAR, XML_RELAXNG_ERR_EXTRADATA, XML_RELAXNG_ERR_LACKDATA, XML_RELAXNG_ERR_INTERNAL, XML_RELAXNG_ERR_ELEMWRONG, XML_RELAXNG_ERR_TEXTWRONG } xmlRelaxNGValidErr; /* * xmlRelaxNGParserFlags: * * List of possible Relax NG Parser flags */ typedef enum { XML_RELAXNGP_NONE = 0, XML_RELAXNGP_FREE_DOC = 1, XML_RELAXNGP_CRNG = 2 } xmlRelaxNGParserFlag; XMLPUBFUN int XMLCALL xmlRelaxNGInitTypes (void); XMLPUBFUN void XMLCALL xmlRelaxNGCleanupTypes (void); /* * Interfaces for parsing. */ XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL xmlRelaxNGNewParserCtxt (const char *URL); XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL xmlRelaxNGNewMemParserCtxt (const char *buffer, int size); XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL xmlRelaxNGNewDocParserCtxt (xmlDocPtr doc); XMLPUBFUN int XMLCALL xmlRelaxParserSetFlag (xmlRelaxNGParserCtxtPtr ctxt, int flag); XMLPUBFUN void XMLCALL xmlRelaxNGFreeParserCtxt (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void XMLCALL xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int XMLCALL xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN xmlRelaxNGPtr XMLCALL xmlRelaxNGParse (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void XMLCALL xmlRelaxNGFree (xmlRelaxNGPtr schema); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void XMLCALL xmlRelaxNGDump (FILE *output, xmlRelaxNGPtr schema); XMLPUBFUN void XMLCALL xmlRelaxNGDumpTree (FILE * output, xmlRelaxNGPtr schema); #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for validating */ XMLPUBFUN void XMLCALL xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int XMLCALL xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN void XMLCALL xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN xmlRelaxNGValidCtxtPtr XMLCALL xmlRelaxNGNewValidCtxt (xmlRelaxNGPtr schema); XMLPUBFUN void XMLCALL xmlRelaxNGFreeValidCtxt (xmlRelaxNGValidCtxtPtr ctxt); XMLPUBFUN int XMLCALL xmlRelaxNGValidateDoc (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc); /* * Interfaces for progressive validation when possible */ XMLPUBFUN int XMLCALL xmlRelaxNGValidatePushElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int XMLCALL xmlRelaxNGValidatePushCData (xmlRelaxNGValidCtxtPtr ctxt, const xmlChar *data, int len); XMLPUBFUN int XMLCALL xmlRelaxNGValidatePopElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int XMLCALL xmlRelaxNGValidateFullElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_RELAX_NG__ */
{ "content_hash": "b0151e2c54e087a6e3d8e27194855cca", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 89, "avg_line_length": 29.342391304347824, "alnum_prop": 0.7138358955362104, "repo_name": "aestesis/elektronika", "id": "48ffec975387689268284c1ad4e4131997b1e33e", "size": "5613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdk/inc/libxml/relaxng.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "48549" }, { "name": "Batchfile", "bytes": "750" }, { "name": "C", "bytes": "5488357" }, { "name": "C#", "bytes": "5819" }, { "name": "C++", "bytes": "15324761" }, { "name": "CSS", "bytes": "15506" }, { "name": "Clarion", "bytes": "901" }, { "name": "DIGITAL Command Language", "bytes": "7554" }, { "name": "Groff", "bytes": "139567" }, { "name": "HLSL", "bytes": "68082" }, { "name": "HTML", "bytes": "4976882" }, { "name": "Inno Setup", "bytes": "125726" }, { "name": "Logos", "bytes": "323950" }, { "name": "M4", "bytes": "46562" }, { "name": "Makefile", "bytes": "853211" }, { "name": "Module Management System", "bytes": "2810" }, { "name": "Objective-C", "bytes": "98314" }, { "name": "Pascal", "bytes": "52540" }, { "name": "Perl", "bytes": "11707" }, { "name": "PostScript", "bytes": "846478" }, { "name": "SAS", "bytes": "1881" }, { "name": "Shell", "bytes": "461461" }, { "name": "Smalltalk", "bytes": "1253" }, { "name": "Verilog", "bytes": "24576" }, { "name": "Visual Basic", "bytes": "4503" }, { "name": "XSLT", "bytes": "36221" }, { "name": "Yacc", "bytes": "98304" } ], "symlink_target": "" }
// **************************************************************************** // <copyright file="AssemblyInfo.cs" company="GalaSoft Laurent Bugnion"> // Copyright © GalaSoft Laurent Bugnion 2009-2012 // </copyright> // **************************************************************************** // <author>Laurent Bugnion</author> // <email>laurent@galasoft.ch</email> // <date>3.6.2009</date> // <project>GalaSoft.MvvmLight</project> // <web>http://www.galasoft.ch</web> // <license> // See license.txt in this project or http://www.galasoft.ch/license_MIT.txt // </license> // **************************************************************************** using System.Runtime.InteropServices; [assembly: Guid("1e6fd8d3-c424-4beb-b146-a6a78fef2580")]
{ "content_hash": "e934f5351a83cc01b4b3245408435bcf", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 80, "avg_line_length": 43, "alnum_prop": 0.48320413436692505, "repo_name": "wiyonoaten/MvvmLight2Mvx", "id": "e52d2ae7ed3adfc9561dbdbe7207175aa9e4cc20", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/portable-MvvmLight2Mvx", "path": "GalaSoft.MvvmLight/GalaSoft.MvvmLight (SL4)/Properties/AssemblyInfo.SL4.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "94695" }, { "name": "C#", "bytes": "1771794" }, { "name": "CSS", "bytes": "7196" }, { "name": "HTML", "bytes": "9252" }, { "name": "Pascal", "bytes": "5538" }, { "name": "PowerShell", "bytes": "11394" }, { "name": "Smalltalk", "bytes": "7644" } ], "symlink_target": "" }
document.addEventListener('trix-attachment-add', function(ev) { var data = {}; var request = new XMLHttpRequest(); request.open('POST', '/trix/attachment/', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data); });
{ "content_hash": "fc15e61fb51e6639bf1518d701f30e89", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 95, "avg_line_length": 26.90909090909091, "alnum_prop": 0.6993243243243243, "repo_name": "istrategylabs/django-trix", "id": "0ed487a325baf24b8566b9164112a79de565783e", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trix/static/trix/trix-django.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15769" }, { "name": "HTML", "bytes": "265" }, { "name": "JavaScript", "bytes": "395" }, { "name": "Python", "bytes": "6060" } ], "symlink_target": "" }
<?php get_header(); ?> <!-- Row for main content area --> <div class="small-12 large-8 columns" id="content" role="main"> <h1 class="entry-title"><?php echo 'UTHSC Spotlight' ?></h1> <p>Stories from the UTHSC Alumni Magazine</p><hr /> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_type() ); ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; // end have_posts() check ?> <?php /* Display navigation to next/previous pages when applicable */ ?> <?php if ( function_exists('reverie_pagination') ) { reverie_pagination(); } else if ( is_paged() ) { ?> <nav id="post-nav"> <div class="post-previous"><?php next_posts_link( __( '&larr; Older posts', 'reverie' ) ); ?></div> <div class="post-next"><?php previous_posts_link( __( 'Newer posts &rarr;', 'reverie' ) ); ?></div> </nav> <?php } ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
{ "content_hash": "dc50f07b0faf5d137edde4be6a4d9b3c", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 115, "avg_line_length": 39.93333333333333, "alnum_prop": 0.501669449081803, "repo_name": "uthsc/uthscblogs-child-news", "id": "d994123f717b0912d5a4b172c2a75aee82e3a79b", "size": "1198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "archive-spotlight.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "47743" }, { "name": "PHP", "bytes": "24210" }, { "name": "Ruby", "bytes": "997" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <title>Endeavour client</title> <!-- stylesheets --> <link href="assets/css/default.css" rel="stylesheet" /> <!-- third-party libs --> <script src="assets/js/vendor/jquery-2.1.1.js"></script> <script src="assets/js/vendor/underscore-1.6.0.js"></script> <script src="assets/js/vendor/backbone-1.1.1.js"></script> <script src="assets/js/vendor/marionette-1.6.2.js"></script> <!-- app setup --> <script src="assets/js/endeavour.js"></script> <!-- app router --> <script src="assets/js/router.js"></script> <!-- app models --> <script src="assets/js/models/abstract.js"></script> <script src="assets/js/models/state.js"></script> <script src="assets/js/models/session.js"></script> <script src="assets/js/models/user.js"></script> <script src="assets/js/models/list.js"></script> <script src="assets/js/models/list-item.js"></script> <script src="assets/js/models/list-item-details.js"></script> <script src="assets/js/models/internal-timer.js"></script> <!-- app views --> <script src="assets/js/views/stage.js"></script> <script src="assets/js/views/header.js"></script> <script src="assets/js/views/login.js"></script> <script src="assets/js/views/sidebar.js"></script> <script src="assets/js/views/dashboard.js"></script> <script src="assets/js/views/today.js"></script> <script src="assets/js/views/all-lists.js"></script> <script src="assets/js/views/single-list.js"></script> <script src="assets/js/views/single-list-item.js"></script> <script src="assets/js/views/list-items-section.js"></script> <script src="assets/js/views/list-item-details.js"></script> <script src="assets/js/views/calendar.js"></script> <script src="assets/js/views/calendar/week.js"></script> <script src="assets/js/views/calendar/week-day.js"></script> <script src="assets/js/views/calendar/month.js"></script> <script src="assets/js/views/calendar/month-day.js"></script> <script src="assets/js/views/flexi/cell.js"></script> <script src="assets/js/views/flexi/container.js"></script> <script src="assets/js/views/flexi/content.js"></script> <script src="assets/js/views/dialog.js"></script> <script src="assets/js/views/dialog-container.js"></script> <script src="assets/js/views/form-dialog.js"></script> <script src="assets/js/views/dialogs/alert.js"></script> <script src="assets/js/views/dialogs/confirm.js"></script> <script src="assets/js/views/dialogs/feedback.js"></script> <script src="assets/js/views/dialogs/add-new-list-item.js"></script> <script src="assets/js/views/dialogs/add-new-list.js"></script> <script src="assets/js/views/helpers/drag-view.js"></script> <script src="assets/js/views/helpers/date-picker.js"></script> <!-- app init --> <script src="assets/js/start.js"></script> </head> <body> </body> </html>
{ "content_hash": "ef5dd802beec4bcec28fd46ce45362c3", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 96, "avg_line_length": 41.917647058823526, "alnum_prop": 0.6112826269997194, "repo_name": "mycetophorae/endeavour-ui", "id": "9bc37962ddabb517e46b5530d772f8772cba07a6", "size": "3563", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "index.old.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46828" }, { "name": "HTML", "bytes": "4176" }, { "name": "JavaScript", "bytes": "226399" }, { "name": "Ruby", "bytes": "305" }, { "name": "Shell", "bytes": "23" } ], "symlink_target": "" }
import pygame from pygame.locals import * #helper that draws an array arr on screen in steps of step pixels def drawGraph(screen, arr, step=5): maxy = screen.get_height() for i in range(len(arr)-1): x = i*step p1 = (i*step, maxy-arr[i]) p2 = ((i+1)*step, maxy-arr[i+1]) pygame.draw.line(screen, (0,0,0), p1, p2) class PygameHelper: def __init__(self, size=(640,480), fill=(255,255,255)): pygame.init() self.screen = pygame.display.set_mode(size) self.screen.fill(fill) pygame.display.flip() self.running = False self.clock = pygame.time.Clock() #to track FPS self.size = size def handleEvents(self): for event in pygame.event.get(): if event.type == QUIT: self.running = False elif event.type == KEYDOWN: self.keyDown(event.key) elif event.type == KEYUP: if event.key == K_ESCAPE: self.running = False self.keyUp(event.key) elif event.type == MOUSEBUTTONUP: if event.button == 1: self.mouseUp(event.pos) else: self.mouseUp2(event.pos) #wait until a key is pressed, then return def waitForKey(self): press=False while not press: for event in pygame.event.get(): if event.type == KEYUP: press = True #enter the main loop, possibly setting max FPS def mainLoop(self, fps=0): self.running = True while self.running: pygame.display.set_caption("FPS: %i" % self.clock.get_fps()) self.handleEvents() self.update() self.draw() self.clock.tick(fps) #methods to be over-ridden def update(self): pass def draw(self): pass def keyDown(self, key): pass def keyUp(self, key): pass def mouseUp(self, pos): pass def mouseUp2(self, pos): pass
{ "content_hash": "bbca7a8fa0a26a68e5ee53d27889cee1", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 72, "avg_line_length": 27.513157894736842, "alnum_prop": 0.5289335246293639, "repo_name": "AjayMT/game-of-life", "id": "430850c4e9426c520b090864452a976ffa631b59", "size": "2141", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "pygamehelper.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "15910" } ], "symlink_target": "" }
using namespace llvm; // If backtrace support is not enabled, compile out support for pretty stack // traces. This has the secondary effect of not requiring thread local storage // when backtrace support is disabled. #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) // We need a thread local pointer to manage the stack of our stack trace // objects, but we *really* cannot tolerate destructors running and do not want // to pay any overhead of synchronizing. As a consequence, we use a raw // thread-local variable. static LLVM_THREAD_LOCAL const PrettyStackTraceEntry *PrettyStackTraceHead = nullptr; static unsigned PrintStack(const PrettyStackTraceEntry *Entry, raw_ostream &OS){ unsigned NextID = 0; if (Entry->getNextEntry()) NextID = PrintStack(Entry->getNextEntry(), OS); OS << NextID << ".\t"; { sys::Watchdog W(5); Entry->print(OS); } return NextID+1; } /// PrintCurStackTrace - Print the current stack trace to the specified stream. static void PrintCurStackTrace(raw_ostream &OS) { // Don't print an empty trace. if (!PrettyStackTraceHead) return; // If there are pretty stack frames registered, walk and emit them. OS << "Stack dump:\n"; PrintStack(PrettyStackTraceHead, OS); OS.flush(); } // Integrate with crash reporter libraries. #if defined (__APPLE__) && HAVE_CRASHREPORTERCLIENT_H // If any clients of llvm try to link to libCrashReporterClient.a themselves, // only one crash info struct will be used. extern "C" { CRASH_REPORTER_CLIENT_HIDDEN struct crashreporter_annotations_t gCRAnnotations __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 }; } #elif defined (__APPLE__) && HAVE_CRASHREPORTER_INFO static const char *__crashreporter_info__ = 0; asm(".desc ___crashreporter_info__, 0x10"); #endif /// CrashHandler - This callback is run if a fatal signal is delivered to the /// process, it prints the pretty stack trace. static void CrashHandler(void *) { #ifndef __APPLE__ // On non-apple systems, just emit the crash stack trace to stderr. PrintCurStackTrace(errs()); #else // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also // put it into __crashreporter_info__. SmallString<2048> TmpStr; { raw_svector_ostream Stream(TmpStr); PrintCurStackTrace(Stream); } if (!TmpStr.empty()) { #ifdef HAVE_CRASHREPORTERCLIENT_H // Cast to void to avoid warning. (void)CRSetCrashLogMessage(std::string(TmpStr.str()).c_str()); #elif HAVE_CRASHREPORTER_INFO __crashreporter_info__ = strdup(std::string(TmpStr.str()).c_str()); #endif errs() << TmpStr.str(); } #endif } // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) #endif PrettyStackTraceEntry::PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) // Link ourselves. NextEntry = PrettyStackTraceHead; PrettyStackTraceHead = this; #endif } PrettyStackTraceEntry::~PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) assert(PrettyStackTraceHead == this && "Pretty stack trace entry destruction is out of order"); PrettyStackTraceHead = getNextEntry(); #endif } void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; } void PrettyStackTraceProgram::print(raw_ostream &OS) const { OS << "Program arguments: "; // Print the argument list. for (unsigned i = 0, e = ArgC; i != e; ++i) OS << ArgV[i] << ' '; OS << '\n'; } #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) static bool RegisterCrashPrinter() { sys::AddSignalHandler(CrashHandler, nullptr); return false; } #endif void llvm::EnablePrettyStackTrace() { #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) // The first time this is called, we register the crash printer. static bool HandlerRegistered = RegisterCrashPrinter(); (void)HandlerRegistered; #endif } const void* llvm::SavePrettyStackState() { #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) return PrettyStackTraceHead; #else return nullptr; #endif } void llvm::RestorePrettyStackState(const void* Top) { #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) PrettyStackTraceHead = (const PrettyStackTraceEntry*)Top; #endif } void LLVMEnablePrettyStackTrace() { EnablePrettyStackTrace(); }
{ "content_hash": "761aadd40f0c878f1e47045735687b0d", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 80, "avg_line_length": 30.075342465753426, "alnum_prop": 0.7164654976087451, "repo_name": "henfredemars/Fork-Lang", "id": "d6782a70e1a4906877151d34767e3a113b07931f", "size": "5354", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "llvm/lib/Support/PrettyStackTrace.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "10354229" }, { "name": "Batchfile", "bytes": "13322" }, { "name": "C", "bytes": "2489216" }, { "name": "C++", "bytes": "48814710" }, { "name": "CMake", "bytes": "296748" }, { "name": "CSS", "bytes": "3339" }, { "name": "Emacs Lisp", "bytes": "9440" }, { "name": "Go", "bytes": "133302" }, { "name": "Groff", "bytes": "24328" }, { "name": "HTML", "bytes": "145927" }, { "name": "LLVM", "bytes": "38718831" }, { "name": "Lex", "bytes": "3095" }, { "name": "Makefile", "bytes": "352750" }, { "name": "Mirah", "bytes": "202593" }, { "name": "OCaml", "bytes": "401694" }, { "name": "Objective-C", "bytes": "392655" }, { "name": "Perl", "bytes": "27878" }, { "name": "Python", "bytes": "503521" }, { "name": "Shell", "bytes": "827560" }, { "name": "SourcePawn", "bytes": "2461" }, { "name": "Standard ML", "bytes": "2841" }, { "name": "VimL", "bytes": "16468" }, { "name": "Yacc", "bytes": "12546" } ], "symlink_target": "" }
var loc = window.location; chrome.extension.sendRequest(loc);
{ "content_hash": "d7bbea3dfdfab26c19d62c826d5f13ac", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 20.666666666666668, "alnum_prop": 0.7903225806451613, "repo_name": "feross/CMSploit", "id": "4c0dbe9a5cb5643b9eb820f1f6d8ac9de28ff618", "size": "62", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ChromeExtension/contentscript.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "7742" }, { "name": "JavaScript", "bytes": "5984" }, { "name": "Shell", "bytes": "65" } ], "symlink_target": "" }
import json import requests import urllib3 from decimal import Decimal from bs4 import BeautifulSoup from datetime import datetime urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def decimal_default(obj): if isinstance(obj, Decimal): return float(obj) raise TypeError def format_decimal(number): return str(number).replace(".", "").replace(",", ".") def vision(): soup = None try: soup = BeautifulSoup( requests.get('https://www.visionbanco.com', timeout=10, headers={'user-agent': 'Mozilla/5.0'}, verify=False).text, "html.parser") efectivo = soup.select('#efectivo')[0] compra = efectivo.select( 'table > tr > td:nth-of-type(2) > p:nth-of-type(1)')[0].get_text().replace('.', '') venta = efectivo.select( 'table > tr > td:nth-of-type(3) > p:nth-of-type(1)')[0].get_text().replace('.', '') except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def chaco(): try: soup = json.loads( requests.get( "http://www.cambioschaco.com.py/api/branch_office/1/exchange", timeout=10, ).text ) compra = soup["items"][0]["purchasePrice"] venta = soup["items"][0]["salePrice"] except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def maxi(): today = datetime.today().strftime("%d%m%Y") url = "https://www.maxicambios.com.py/" try: soup = BeautifulSoup( requests.get( url, timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) tr_dolar = soup.find( class_="fixed-plugin").find("table").find("tbody").find("tr") compra = tr_dolar.find_all('td')[1].text venta = tr_dolar.find_all('td')[2].text except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def alberdi(): try: soup = BeautifulSoup( requests.get( "http://www.cambiosalberdi.com/index.php", timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) casamatriz = soup.select("#operaciones section.cd-gallery li.villamorra-ico")[0] array = casamatriz.find( class_="recent-received-goals" ).select("h6:nth-of-type(1)")[0].get_text().split() compra = array[0].replace('.', '') venta = array[1].replace('.', '') except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 try: return Decimal(compra), Decimal(venta) except: return 0, 0 def bcp(): try: soup = BeautifulSoup( requests.get( "https://www.bcp.gov.py/webapps/web/cotizacion/monedas", timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) ref = soup.select("#cotizacion-interbancaria > tbody > tr > td:nth-of-type(4)")[ 0 ].get_text() ref = ref.replace(".", "").replace(",", ".") soup = BeautifulSoup( requests.get( "https://www.bcp.gov.py/webapps/web/cotizacion/referencial-fluctuante", timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) compra_array = soup.find( class_="table table-striped table-bordered table-condensed" ).select("tr > td:nth-of-type(4)") venta_array = soup.find( class_="table table-striped table-bordered table-condensed" ).select("tr > td:nth-of-type(5)") posicion = len(compra_array) - 1 compra = compra_array[posicion].get_text().replace( ".", "").replace(",", ".") venta = venta_array[posicion].get_text().replace( ".", "").replace(",", ".") except requests.ConnectionError: compra, venta, ref = 0, 0, 0 except: compra, venta, ref = 0, 0, 0 return Decimal(compra), Decimal(venta), Decimal(ref) def setgov(): try: soup = BeautifulSoup( requests.get( "http://www.set.gov.py/portal/PARAGUAY-SET", timeout=10).text, "html.parser", ) compra = ( soup.select("td.UICotizacion")[0].text.replace( "G. ", "").replace(".", "") ) venta = ( soup.select("td.UICotizacion")[1].text.replace( "G. ", "").replace(".", "") ) except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) # def interfisa(): # try: # jsonResult = requests.get( # "https://seguro.interfisa.com.py/rest/cotizaciones", timeout=10 # ).json() # cotizaciones = jsonResult["operacionResponse"]["cotizaciones"]["monedaCot"] # for coti in cotizaciones: # for k, v in coti.items(): # if v == "DOLARES AMERICANOS": # estamos en el dict de Dolares # compra = coti["compra"] # venta = coti["venta"] # except requests.ConnectionError: # compra, venta = 0, 0 # except: # compra, venta = 0, 0 # return Decimal(compra), Decimal(venta) # def amambay(): # try: # soup = BeautifulSoup( # requests.get( # "https://www.bancobasa.com.py/", timeout=10).text, # "html.parser", # ) # compra = soup.select(".trendscontent > li:nth-of-type(1) > a > .compra")[0].text.replace(".", "") # venta = soup.select(".trendscontent > li:nth-of-type(1) > a > .venta")[0].text.replace(".", "") # except requests.ConnectionError: # compra, venta = 0, 0 # except: # compra, venta = 0, 0 # return Decimal(compra), Decimal(venta) def eurocambio(): try: url = "https://eurocambios.com.py/v2/sgi/utilsDto.php" data = {"param": "getCotizacionesbySucursal", "sucursal": "1"} result = requests.post(url, data, timeout=10).json() compra = result[0]["compra"] venta = result[0]["venta"] except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def myd(): try: soup = BeautifulSoup( requests.get("https://www.mydcambios.com.py/", timeout=10).text, "html.parser", ) compra = soup.select( "div.cambios-banner-text.scrollbox > ul:nth-of-type(2) > li:nth-of-type(2) " )[0].text venta = soup.select( "div.cambios-banner-text.scrollbox > ul:nth-of-type(2) > li:nth-of-type(3) " )[0].text except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def bonanza(): url = "https://bonanzacambios.com.py/" try: soup = BeautifulSoup( requests.get( url, timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) tr_dolar = soup.select(".table-pricing.style1 table tbody tr td.moneda") compra = tr_dolar[0].get_text().replace('.', '') venta = tr_dolar[1].get_text().replace('.', '') except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) # def familiar(): # Comentado porque el servidor bloquea las peticiones # try: # soup = BeautifulSoup( # requests.get('https://www.familiar.com.py/', timeout=10).text, "html.parser") # compra = soup.select( # 'hgroup:nth-of-type(1) > div:nth-of-type(2) > p:nth-of-type(2)')[0].get_text().replace('.', '') # venta = soup.select( # 'hgroup:nth-of-type(1) > div:nth-of-type(3) > p:nth-of-type(2)')[0].get_text().replace('.', '') # except requests.ConnectionError: # compra, venta = 0, 0 # except: # compra, venta = 0, 0 # return Decimal(compra), Decimal(venta) def lamoneda(): try: # soup = BeautifulSoup( # requests.get( # "http://www.lamoneda.com.py/", timeout=10).text, # "html.parser", # ) # casacentral = soup.select("#cotizaciones table tr:nth-of-type(2)")[0] # compra = ( # casacentral.select("td:nth-of-type(3) > div")[0].text.replace(".", "") # ) # venta = ( # casacentral.select("td:nth-of-type(4) > div")[0].text.replace(".", "") # ) today = datetime.today().strftime("%d%m%Y") url = "http://www.lamoneda.com.py/" soup = BeautifulSoup( requests.get( url, timeout=10, headers={"user-agent": "Mozilla/5.0"}, verify=False, ).text, "html.parser", ) tr_dolar = soup.find("table").find("tbody").find("tr") compra = tr_dolar.find_all('td')[2].text.replace(".", "") venta = tr_dolar.find_all('td')[3].text.replace(".", "") except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def bbva(): try: soup = requests.get( "https://www.bancognbcaminamosjuntos.com.py/Yaguarete/public/quotations", timeout=10 ).json() compra = soup[0]["cashBuyPrice"] venta = soup[0]["cashSellPrice"] except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def mundial(): soup = None try: soup = BeautifulSoup( requests.get('http://www.mundialcambios.com.py/?branch=6', timeout=20, headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'}).text, "html.parser") compra = soup.select( 'h3.divisa')[0].get_text().replace('.', '') venta = soup.select( 'h3.divisa')[1].get_text().replace('.', '') except requests.ConnectionError: compra, venta = 0, 0 except: compra, venta = 0, 0 return Decimal(compra), Decimal(venta) def create_json(): mcompra, mventa = maxi() ccompra, cventa = chaco() acompra, aventa = alberdi() bcpcompra, bcpventa, bcpref = bcp() setcompra, setventa = setgov() # intcompra, intventa = interfisa() # ambcompra, ambventa = amambay() eccompra, ecventa = eurocambio() mydcompra, mydventa = myd() bbvacompra, bbvaventa = bbva() # famicompra, famiventa = familiar() wcompra, wventa = mundial() visioncompra, visionventa = vision() bonanzacompra, bonanzaventa = bonanza() lamonedacompra, lamonedaventa = lamoneda() respjson = { "dolarpy": { "cambiosalberdi": {"compra": acompra, "venta": aventa}, "cambioschaco": {"compra": ccompra, "venta": cventa}, "maxicambios": {"compra": mcompra, "venta": mventa}, "bcp": { "compra": bcpcompra, "venta": bcpventa, "referencial_diario": bcpref, }, "set": {"compra": setcompra, "venta": setventa}, # "interfisa": {"compra": intcompra, "venta": intventa}, # "amambay": {"compra": ambcompra, "venta": ambventa}, "mydcambios": {"compra": mydcompra, "venta": mydventa}, "eurocambios": {"compra": eccompra, "venta": ecventa}, # 'familiar': { # 'compra': famicompra, # 'venta': famiventa # } "gnbfusion": {"compra": bbvacompra, "venta": bbvaventa}, "mundialcambios": {"compra": wcompra, "venta": wventa}, 'vision': { 'compra': visioncompra, 'venta': visionventa, }, 'bonanza': { 'compra': bonanzacompra, 'venta': bonanzaventa, }, 'lamoneda': { 'compra': lamonedacompra, 'venta': lamonedaventa, } }, "updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } return json.dumps( respjson, indent=4, sort_keys=True, separators=(",", ": "), default=decimal_default, ) def get_output(): with open("dolar.json", "r") as f: response = f.read() return response def write_output(): response = create_json() with open("dolar.json", "w") as f: f.write(response) write_output()
{ "content_hash": "94ce62eb2a72479d4b4da5a66a306f2f", "timestamp": "", "source": "github", "line_count": 443, "max_line_length": 173, "avg_line_length": 30.54176072234763, "alnum_prop": 0.5226164079822616, "repo_name": "melizeche/dolarPy", "id": "645dc3a882c12426909725152c10979f6319e2a9", "size": "13578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coti.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "23551" }, { "name": "Python", "bytes": "16676" } ], "symlink_target": "" }
package com.amazonaws.services.apigatewayv2.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateAuthorizerResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM * role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on * the Lambda function, specify null. * </p> */ private String authorizerCredentialsArn; /** * <p> * The authorizer identifier. * </p> */ private String authorizerId; /** * <p> * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, the * default value is 300. The maximum value is 3600, or 1 hour. * </p> */ private Integer authorizerResultTtlInSeconds; /** * <p> * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming request * parameters. * </p> */ private String authorizerType; /** * <p> * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed Lambda * function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2: * {account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting the * Lambda function, path indicates that the remaining substring in the URI should be treated as the path to the * resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. * </p> */ private String authorizerUri; /** * <p> * The identity source for which authorization is requested. * </p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For example, if an * Auth header and a Name query string parameters are defined as identity sources, this value is * method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive the * authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all of the * identity-related request parameters are present, not null, and non-empty. Only when this is true does the * authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized response without * calling the Lambda function. The valid value is a string of comma-separated mapping expressions of the specified * request parameters. When the authorization caching is not enabled, this property is optional. * </p> */ private java.util.List<String> identitySource; /** * <p> * The validation expression does not apply to the REQUEST authorizer. * </p> */ private String identityValidationExpression; /** * <p> * The name of the authorizer. * </p> */ private String name; /** * <p> * For REQUEST authorizer, this is not defined. * </p> */ private java.util.List<String> providerArns; /** * <p> * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM * role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on * the Lambda function, specify null. * </p> * * @param authorizerCredentialsArn * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an * IAM role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based * permissions on the Lambda function, specify null. */ public void setAuthorizerCredentialsArn(String authorizerCredentialsArn) { this.authorizerCredentialsArn = authorizerCredentialsArn; } /** * <p> * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM * role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on * the Lambda function, specify null. * </p> * * @return Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an * IAM role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based * permissions on the Lambda function, specify null. */ public String getAuthorizerCredentialsArn() { return this.authorizerCredentialsArn; } /** * <p> * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM * role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on * the Lambda function, specify null. * </p> * * @param authorizerCredentialsArn * Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an * IAM role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based * permissions on the Lambda function, specify null. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withAuthorizerCredentialsArn(String authorizerCredentialsArn) { setAuthorizerCredentialsArn(authorizerCredentialsArn); return this; } /** * <p> * The authorizer identifier. * </p> * * @param authorizerId * The authorizer identifier. */ public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; } /** * <p> * The authorizer identifier. * </p> * * @return The authorizer identifier. */ public String getAuthorizerId() { return this.authorizerId; } /** * <p> * The authorizer identifier. * </p> * * @param authorizerId * The authorizer identifier. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withAuthorizerId(String authorizerId) { setAuthorizerId(authorizerId); return this; } /** * <p> * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, the * default value is 300. The maximum value is 3600, or 1 hour. * </p> * * @param authorizerResultTtlInSeconds * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, * the default value is 300. The maximum value is 3600, or 1 hour. */ public void setAuthorizerResultTtlInSeconds(Integer authorizerResultTtlInSeconds) { this.authorizerResultTtlInSeconds = authorizerResultTtlInSeconds; } /** * <p> * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, the * default value is 300. The maximum value is 3600, or 1 hour. * </p> * * @return The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching * is disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not * set, the default value is 300. The maximum value is 3600, or 1 hour. */ public Integer getAuthorizerResultTtlInSeconds() { return this.authorizerResultTtlInSeconds; } /** * <p> * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, the * default value is 300. The maximum value is 3600, or 1 hour. * </p> * * @param authorizerResultTtlInSeconds * The time to live (TTL), in seconds, of cached authorizer results. If it equals 0, authorization caching is * disabled. If it is greater than 0, API Gateway will cache authorizer responses. If this field is not set, * the default value is 300. The maximum value is 3600, or 1 hour. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withAuthorizerResultTtlInSeconds(Integer authorizerResultTtlInSeconds) { setAuthorizerResultTtlInSeconds(authorizerResultTtlInSeconds); return this; } /** * <p> * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming request * parameters. * </p> * * @param authorizerType * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming * request parameters. * @see AuthorizerType */ public void setAuthorizerType(String authorizerType) { this.authorizerType = authorizerType; } /** * <p> * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming request * parameters. * </p> * * @return The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming * request parameters. * @see AuthorizerType */ public String getAuthorizerType() { return this.authorizerType; } /** * <p> * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming request * parameters. * </p> * * @param authorizerType * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming * request parameters. * @return Returns a reference to this object so that method calls can be chained together. * @see AuthorizerType */ public UpdateAuthorizerResult withAuthorizerType(String authorizerType) { setAuthorizerType(authorizerType); return this; } /** * <p> * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming request * parameters. * </p> * * @param authorizerType * The authorizer type. Currently the only valid value is REQUEST, for a Lambda function using incoming * request parameters. * @return Returns a reference to this object so that method calls can be chained together. * @see AuthorizerType */ public UpdateAuthorizerResult withAuthorizerType(AuthorizerType authorizerType) { this.authorizerType = authorizerType.toString(); return this; } /** * <p> * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed Lambda * function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2: * {account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting the * Lambda function, path indicates that the remaining substring in the URI should be treated as the path to the * resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. * </p> * * @param authorizerUri * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed * Lambda function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda * :us-west-2:{account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting * the Lambda function, path indicates that the remaining substring in the URI should be treated as the path * to the resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. */ public void setAuthorizerUri(String authorizerUri) { this.authorizerUri = authorizerUri; } /** * <p> * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed Lambda * function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2: * {account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting the * Lambda function, path indicates that the remaining substring in the URI should be treated as the path to the * resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. * </p> * * @return The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed * Lambda function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda * :us-west-2:{account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting * the Lambda function, path indicates that the remaining substring in the URI should be treated as the path * to the resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. */ public String getAuthorizerUri() { return this.authorizerUri; } /** * <p> * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed Lambda * function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2: * {account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting the * Lambda function, path indicates that the remaining substring in the URI should be treated as the path to the * resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. * </p> * * @param authorizerUri * The authorizer's Uniform Resource Identifier (URI). ForREQUEST authorizers, this must be a well-formed * Lambda function URI, for example, * arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda * :us-west-2:{account_id}:function:{lambda_function_name}/invocations. In general, the URI has this form: * arn:aws:apigateway:{region}:lambda:path/{service_api} , where {region} is the same as the region hosting * the Lambda function, path indicates that the remaining substring in the URI should be treated as the path * to the resource, including the initial /. For Lambda functions, this is usually of the form * /2015-03-31/functions/[FunctionARN]/invocations. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withAuthorizerUri(String authorizerUri) { setAuthorizerUri(authorizerUri); return this; } /** * <p> * The identity source for which authorization is requested. * </p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For example, if an * Auth header and a Name query string parameters are defined as identity sources, this value is * method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive the * authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all of the * identity-related request parameters are present, not null, and non-empty. Only when this is true does the * authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized response without * calling the Lambda function. The valid value is a string of comma-separated mapping expressions of the specified * request parameters. When the authorization caching is not enabled, this property is optional. * </p> * * @return The identity source for which authorization is requested.</p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For * example, if an Auth header and a Name query string parameters are defined as identity sources, this value * is method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive * the authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying * all of the identity-related request parameters are present, not null, and non-empty. Only when this is * true does the authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized * response without calling the Lambda function. The valid value is a string of comma-separated mapping * expressions of the specified request parameters. When the authorization caching is not enabled, this * property is optional. */ public java.util.List<String> getIdentitySource() { return identitySource; } /** * <p> * The identity source for which authorization is requested. * </p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For example, if an * Auth header and a Name query string parameters are defined as identity sources, this value is * method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive the * authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all of the * identity-related request parameters are present, not null, and non-empty. Only when this is true does the * authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized response without * calling the Lambda function. The valid value is a string of comma-separated mapping expressions of the specified * request parameters. When the authorization caching is not enabled, this property is optional. * </p> * * @param identitySource * The identity source for which authorization is requested.</p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For * example, if an Auth header and a Name query string parameters are defined as identity sources, this value * is method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive * the authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all * of the identity-related request parameters are present, not null, and non-empty. Only when this is true * does the authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized * response without calling the Lambda function. The valid value is a string of comma-separated mapping * expressions of the specified request parameters. When the authorization caching is not enabled, this * property is optional. */ public void setIdentitySource(java.util.Collection<String> identitySource) { if (identitySource == null) { this.identitySource = null; return; } this.identitySource = new java.util.ArrayList<String>(identitySource); } /** * <p> * The identity source for which authorization is requested. * </p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For example, if an * Auth header and a Name query string parameters are defined as identity sources, this value is * method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive the * authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all of the * identity-related request parameters are present, not null, and non-empty. Only when this is true does the * authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized response without * calling the Lambda function. The valid value is a string of comma-separated mapping expressions of the specified * request parameters. When the authorization caching is not enabled, this property is optional. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setIdentitySource(java.util.Collection)} or {@link #withIdentitySource(java.util.Collection)} if you want * to override the existing values. * </p> * * @param identitySource * The identity source for which authorization is requested.</p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For * example, if an Auth header and a Name query string parameters are defined as identity sources, this value * is method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive * the authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all * of the identity-related request parameters are present, not null, and non-empty. Only when this is true * does the authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized * response without calling the Lambda function. The valid value is a string of comma-separated mapping * expressions of the specified request parameters. When the authorization caching is not enabled, this * property is optional. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withIdentitySource(String... identitySource) { if (this.identitySource == null) { setIdentitySource(new java.util.ArrayList<String>(identitySource.length)); } for (String ele : identitySource) { this.identitySource.add(ele); } return this; } /** * <p> * The identity source for which authorization is requested. * </p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For example, if an * Auth header and a Name query string parameters are defined as identity sources, this value is * method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive the * authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all of the * identity-related request parameters are present, not null, and non-empty. Only when this is true does the * authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized response without * calling the Lambda function. The valid value is a string of comma-separated mapping expressions of the specified * request parameters. When the authorization caching is not enabled, this property is optional. * </p> * * @param identitySource * The identity source for which authorization is requested.</p> * <p> * For the REQUEST authorizer, this is required when authorization caching is enabled. The value is a * comma-separated string of one or more mapping expressions of the specified request parameters. For * example, if an Auth header and a Name query string parameters are defined as identity sources, this value * is method.request.header.Auth, method.request.querystring.Name. These parameters will be used to derive * the authorization caching key and to perform runtime validation of the REQUEST authorizer by verifying all * of the identity-related request parameters are present, not null, and non-empty. Only when this is true * does the authorizer invoke the authorizer Lambda function, otherwise, it returns a 401 Unauthorized * response without calling the Lambda function. The valid value is a string of comma-separated mapping * expressions of the specified request parameters. When the authorization caching is not enabled, this * property is optional. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withIdentitySource(java.util.Collection<String> identitySource) { setIdentitySource(identitySource); return this; } /** * <p> * The validation expression does not apply to the REQUEST authorizer. * </p> * * @param identityValidationExpression * The validation expression does not apply to the REQUEST authorizer. */ public void setIdentityValidationExpression(String identityValidationExpression) { this.identityValidationExpression = identityValidationExpression; } /** * <p> * The validation expression does not apply to the REQUEST authorizer. * </p> * * @return The validation expression does not apply to the REQUEST authorizer. */ public String getIdentityValidationExpression() { return this.identityValidationExpression; } /** * <p> * The validation expression does not apply to the REQUEST authorizer. * </p> * * @param identityValidationExpression * The validation expression does not apply to the REQUEST authorizer. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withIdentityValidationExpression(String identityValidationExpression) { setIdentityValidationExpression(identityValidationExpression); return this; } /** * <p> * The name of the authorizer. * </p> * * @param name * The name of the authorizer. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the authorizer. * </p> * * @return The name of the authorizer. */ public String getName() { return this.name; } /** * <p> * The name of the authorizer. * </p> * * @param name * The name of the authorizer. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withName(String name) { setName(name); return this; } /** * <p> * For REQUEST authorizer, this is not defined. * </p> * * @return For REQUEST authorizer, this is not defined. */ public java.util.List<String> getProviderArns() { return providerArns; } /** * <p> * For REQUEST authorizer, this is not defined. * </p> * * @param providerArns * For REQUEST authorizer, this is not defined. */ public void setProviderArns(java.util.Collection<String> providerArns) { if (providerArns == null) { this.providerArns = null; return; } this.providerArns = new java.util.ArrayList<String>(providerArns); } /** * <p> * For REQUEST authorizer, this is not defined. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setProviderArns(java.util.Collection)} or {@link #withProviderArns(java.util.Collection)} if you want to * override the existing values. * </p> * * @param providerArns * For REQUEST authorizer, this is not defined. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withProviderArns(String... providerArns) { if (this.providerArns == null) { setProviderArns(new java.util.ArrayList<String>(providerArns.length)); } for (String ele : providerArns) { this.providerArns.add(ele); } return this; } /** * <p> * For REQUEST authorizer, this is not defined. * </p> * * @param providerArns * For REQUEST authorizer, this is not defined. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAuthorizerResult withProviderArns(java.util.Collection<String> providerArns) { setProviderArns(providerArns); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAuthorizerCredentialsArn() != null) sb.append("AuthorizerCredentialsArn: ").append(getAuthorizerCredentialsArn()).append(","); if (getAuthorizerId() != null) sb.append("AuthorizerId: ").append(getAuthorizerId()).append(","); if (getAuthorizerResultTtlInSeconds() != null) sb.append("AuthorizerResultTtlInSeconds: ").append(getAuthorizerResultTtlInSeconds()).append(","); if (getAuthorizerType() != null) sb.append("AuthorizerType: ").append(getAuthorizerType()).append(","); if (getAuthorizerUri() != null) sb.append("AuthorizerUri: ").append(getAuthorizerUri()).append(","); if (getIdentitySource() != null) sb.append("IdentitySource: ").append(getIdentitySource()).append(","); if (getIdentityValidationExpression() != null) sb.append("IdentityValidationExpression: ").append(getIdentityValidationExpression()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getProviderArns() != null) sb.append("ProviderArns: ").append(getProviderArns()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateAuthorizerResult == false) return false; UpdateAuthorizerResult other = (UpdateAuthorizerResult) obj; if (other.getAuthorizerCredentialsArn() == null ^ this.getAuthorizerCredentialsArn() == null) return false; if (other.getAuthorizerCredentialsArn() != null && other.getAuthorizerCredentialsArn().equals(this.getAuthorizerCredentialsArn()) == false) return false; if (other.getAuthorizerId() == null ^ this.getAuthorizerId() == null) return false; if (other.getAuthorizerId() != null && other.getAuthorizerId().equals(this.getAuthorizerId()) == false) return false; if (other.getAuthorizerResultTtlInSeconds() == null ^ this.getAuthorizerResultTtlInSeconds() == null) return false; if (other.getAuthorizerResultTtlInSeconds() != null && other.getAuthorizerResultTtlInSeconds().equals(this.getAuthorizerResultTtlInSeconds()) == false) return false; if (other.getAuthorizerType() == null ^ this.getAuthorizerType() == null) return false; if (other.getAuthorizerType() != null && other.getAuthorizerType().equals(this.getAuthorizerType()) == false) return false; if (other.getAuthorizerUri() == null ^ this.getAuthorizerUri() == null) return false; if (other.getAuthorizerUri() != null && other.getAuthorizerUri().equals(this.getAuthorizerUri()) == false) return false; if (other.getIdentitySource() == null ^ this.getIdentitySource() == null) return false; if (other.getIdentitySource() != null && other.getIdentitySource().equals(this.getIdentitySource()) == false) return false; if (other.getIdentityValidationExpression() == null ^ this.getIdentityValidationExpression() == null) return false; if (other.getIdentityValidationExpression() != null && other.getIdentityValidationExpression().equals(this.getIdentityValidationExpression()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getProviderArns() == null ^ this.getProviderArns() == null) return false; if (other.getProviderArns() != null && other.getProviderArns().equals(this.getProviderArns()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAuthorizerCredentialsArn() == null) ? 0 : getAuthorizerCredentialsArn().hashCode()); hashCode = prime * hashCode + ((getAuthorizerId() == null) ? 0 : getAuthorizerId().hashCode()); hashCode = prime * hashCode + ((getAuthorizerResultTtlInSeconds() == null) ? 0 : getAuthorizerResultTtlInSeconds().hashCode()); hashCode = prime * hashCode + ((getAuthorizerType() == null) ? 0 : getAuthorizerType().hashCode()); hashCode = prime * hashCode + ((getAuthorizerUri() == null) ? 0 : getAuthorizerUri().hashCode()); hashCode = prime * hashCode + ((getIdentitySource() == null) ? 0 : getIdentitySource().hashCode()); hashCode = prime * hashCode + ((getIdentityValidationExpression() == null) ? 0 : getIdentityValidationExpression().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getProviderArns() == null) ? 0 : getProviderArns().hashCode()); return hashCode; } @Override public UpdateAuthorizerResult clone() { try { return (UpdateAuthorizerResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "39c5e15ce2211c85d4b2dd65d4766260", "timestamp": "", "source": "github", "line_count": 798, "max_line_length": 159, "avg_line_length": 47.39724310776943, "alnum_prop": 0.6695396980673135, "repo_name": "jentfoo/aws-sdk-java", "id": "ee6c7f870322e3e2b10bc85da39d1514542629f9", "size": "38403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateAuthorizerResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
#define BUILDING_NODE_EXTENSION #include "EmiNodeUtil.h" #include "EmiError.h" #include "slab_allocator.h" #include "../core/EmiNetUtil.h" #include <netinet/in.h> #include <cstring> #include <cstdio> #include <cstdlib> #include <node_buffer.h> using namespace v8; static const int SLAB_SIZE = 1024 * 1024; static node::SlabAllocator slab_allocator(SLAB_SIZE); static void close_cb(uv_handle_t* handle) { free(handle); } static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { char *buf = slab_allocator.Allocate(Context::GetCurrent()->Global(), suggested_size); return uv_buf_init(buf, suggested_size); } static void send_cb(uv_udp_send_t* req, int status) { uv_buf_t *buf = (uv_buf_t *)&req[1]; free(buf->base); free(req); } static void recv_cb(uv_udp_t *handle, ssize_t nread, uv_buf_t buf, struct sockaddr *addr, unsigned flags) { HandleScope scope; Local<Object> slab = slab_allocator.Shrink(Context::GetCurrent()->Global(), buf.base, nread < 0 ? 0 : nread); if (nread == 0) return; EmiNodeUtil::EmiNodeUtilRecvCb *recvCb = *(reinterpret_cast<EmiNodeUtil::EmiNodeUtilRecvCb**>(handle+1)); // Invoke recvCb if there is an error (nread < 0) or (if // we did receive data AND the data we received was complete) if (nread < 0 || (nread > 0 && !(flags & UV_UDP_PARTIAL))) { recvCb(handle, *((struct sockaddr_storage *)addr), nread, slab, buf.base - node::Buffer::Data(slab)); } } void EmiNodeUtil::parseIp(const char* host, uint16_t port, int family, sockaddr_storage *out) { if (AF_INET == family) { struct sockaddr_in address4(uv_ip4_addr(host, port)); memcpy(out, &address4, sizeof(struct sockaddr_in)); } else if (AF_INET6 == family) { struct sockaddr_in6 address6(uv_ip6_addr(host, port)); memcpy(out, &address6, sizeof(struct sockaddr_in)); } else { ASSERT(0 && "unexpected address family"); abort(); } } void EmiNodeUtil::ipName(char *buf, size_t bufLen, const sockaddr_storage& addr) { if (AF_INET == addr.ss_family) { uv_ip4_name((struct sockaddr_in *)&addr, buf, bufLen); } else if (AF_INET6 == addr.ss_family) { uv_ip6_name((struct sockaddr_in6 *)&addr, buf, bufLen); } else { ASSERT(0 && "unexpected address family"); } } bool EmiNodeUtil::parseAddressFamily(const char* typeStr, int *family) { if (0 == strcmp(typeStr, "udp4")) { *family = AF_INET; return true; } else if (0 == strcmp(typeStr, "udp6")) { *family = AF_INET6; return true; } else { return false; } } Handle<String> EmiNodeUtil::errStr(uv_err_t err) { HandleScope scope; Local<String> errStr; if (err.code == UV_UNKNOWN) { char errno_buf[100]; snprintf(errno_buf, 100, "Unknown system errno %d", err.sys_errno_); errStr = String::New(errno_buf); } else { errStr = String::NewSymbol(uv_err_name(err)); } return scope.Close(errStr); } void EmiNodeUtil::closeSocket(uv_udp_t *socket) { uv_close((uv_handle_t *)socket, close_cb); } uv_udp_t *EmiNodeUtil::openSocket(const sockaddr_storage& address, EmiNodeUtilRecvCb *recvCb, void *data, EmiError& error) { int err; uv_udp_t *socket = (uv_udp_t *)malloc(sizeof(uv_udp_t)+sizeof(EmiNodeUtilRecvCb*)); *(reinterpret_cast<EmiNodeUtilRecvCb**>(socket+1)) = recvCb; err = uv_udp_init(uv_default_loop(), socket); if (0 != err) { goto error; } if (AF_INET == address.ss_family) { struct sockaddr_in& addr(*((struct sockaddr_in *)&address)); char buf[100]; uv_ip4_name(&addr, buf, sizeof(buf)); err = uv_udp_bind(socket, addr, /*flags:*/0); if (0 != err) { goto error; } } else if (AF_INET6 == address.ss_family) { struct sockaddr_in6& addr6(*((struct sockaddr_in6 *)&address)); err = uv_udp_bind6(socket, addr6, /*flags:*/0); if (0 != err) { goto error; } } else { ASSERT(0 && "unexpected address family"); abort(); } err = uv_udp_recv_start(socket, alloc_cb, recv_cb); if (0 != err) { goto error; } socket->data = data; return socket; error: free(socket); return NULL; } void EmiNodeUtil::sendData(uv_udp_t *socket, const sockaddr_storage& address, const uint8_t *data, size_t size) { uv_udp_send_t *req = (uv_udp_send_t *)malloc(sizeof(uv_udp_send_t)+ sizeof(uv_buf_t)+ sizeof(size_t)); uv_buf_t *buf = (uv_buf_t *)&req[1]; size_t *sizePtr = (size_t *)&buf[1]; // TODO This copies the packet data. We might want to redesign // this part of the code so that this is not required. // // TODO It would probably be better and faster to use the slab // allocator here. char *bufData = (char *)malloc(size); memcpy(bufData, data, size); *buf = uv_buf_init((char *)bufData, size); *sizePtr = size; if (AF_INET == address.ss_family) { if (0 != uv_udp_send(req, socket, buf, /*bufcnt:*/1, *((struct sockaddr_in *)&address), send_cb)) { free(req); } } else if (AF_INET6 == address.ss_family) { if (0 != uv_udp_send6(req, socket, buf, /*bufcnt:*/1, *((struct sockaddr_in6 *)&address), send_cb)) { free(req); } } else { ASSERT(0 && "unexpected address family"); } } EmiTimeInterval EmiNodeUtil::now() { return ((double)uv_hrtime())/NSECS_PER_SEC; }
{ "content_hash": "9268d9a21bafa3c1e51f556eed84c755", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 109, "avg_line_length": 28.929515418502202, "alnum_prop": 0.5095172833866302, "repo_name": "pereckerdal/eminet", "id": "d345034adc71ab5e563a1a3ef455f54134416096", "size": "6567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node/EmiNodeUtil.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6616" }, { "name": "C++", "bytes": "376093" }, { "name": "JavaScript", "bytes": "13276" }, { "name": "Objective-C", "bytes": "30267" }, { "name": "Objective-C++", "bytes": "38470" }, { "name": "Python", "bytes": "1314" } ], "symlink_target": "" }
// // FontUtils.h // docClient // // Created by USER on 15-3-16. // Copyright (c) 2015年 luo. All rights reserved. // #import <Foundation/Foundation.h> static CGFloat adaptiveHeight(CGFloat i6_h,CGFloat i6p_h,CGFloat h) { CGFloat height; static CGFloat screenHeight; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ screenHeight = [UIScreen mainScreen].bounds.size.height; }); if (screenHeight == 667) { height = i6_h; }else if (screenHeight == 736) { height = i6p_h; }else { height = h; } return height; }; #define AdaptiveHeight(i6,i6p,i) adaptiveHeight(i6,i6p,i) #define AttributedStrHIG AdaptiveHeight(118,121,111) #define AttributedStrSize AdaptiveHeight(15,15.5,14) @interface FontUtils : NSObject /** * 特定空间内,文字所占空间大小 * * @param text * @param size * @param font * * @return */ + (CGSize)stringSize:(NSString *)text withSize:(CGSize)size font:(UIFont*) font; /** * 特定空间内,文字所占空间大小 * @param text * @param size * @param attrs * @return */ +(CGSize) stringSize:(NSString *)text withSize:(CGSize)size withAttrsDic:(NSDictionary *) attrs; /** 根据一段文字返回一个类似于微信学术圈样式的文本 */ + (NSAttributedString *)stringWithWeChatFriendCircleStyleString:(NSString *)string; /** 根据一段文字返回一个类似于微信学术圈样式的文本 显示省略号时调用 类似患教内容 @param isGetHig 计算高度时传YES 设置attributed时传NO */ + (NSAttributedString *)stringWithWeChatFriendCircleStyleString:(NSString *)string isGetHig:(BOOL)isGetHig; @end
{ "content_hash": "2c5357a8686a52403d837960ff83549c", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 107, "avg_line_length": 22.253731343283583, "alnum_prop": 0.6854460093896714, "repo_name": "lizhuangzi/WifeButler", "id": "eb91a5ffa742dcadacc69c717451d400b1c0296d", "size": "1689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WifeButler_8_10 2/WifeButler/Classes/Main/Tools/FontUtils.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "825" }, { "name": "Objective-C", "bytes": "2929049" }, { "name": "Objective-C++", "bytes": "11688" }, { "name": "Ruby", "bytes": "467" }, { "name": "Shell", "bytes": "9515" } ], "symlink_target": "" }
package li.strolch.execution; import static li.strolch.model.ModelGenerator.*; import static org.junit.Assert.assertEquals; import java.util.SortedSet; import li.strolch.execution.command.PlanActionCommand; import li.strolch.model.ModelGenerator; import li.strolch.model.ParameterBag; import li.strolch.model.Resource; import li.strolch.model.State; import li.strolch.model.activity.Action; import li.strolch.model.activity.Activity; import li.strolch.model.activity.TimeOrdering; import li.strolch.model.parameter.IntegerParameter; import li.strolch.model.timedstate.IntegerTimedState; import li.strolch.model.timedstate.StrolchTimedState; import li.strolch.model.timevalue.ITimeValue; import li.strolch.model.timevalue.ITimeVariable; import li.strolch.model.timevalue.IValue; import li.strolch.model.timevalue.IValueChange; import li.strolch.model.timevalue.impl.IntegerValue; import li.strolch.model.timevalue.impl.ValueChange; import li.strolch.persistence.api.StrolchTransaction; import li.strolch.testbase.runtime.RuntimeMock; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * @author Martin Smock <martin.smock@bluewin.ch> */ public class PlanActionTest { private static final String RUNTIME_PATH = "target/" + PlanActionTest.class.getSimpleName(); private static final String CONFIG_SRC = "src/test/resources/executiontest"; //$NON-NLS-1$ private static RuntimeMock runtimeMock; private static StrolchTransaction tx; @BeforeClass public static void beforeClass() { runtimeMock = new RuntimeMock(); runtimeMock.mockRuntime(RUNTIME_PATH, CONFIG_SRC); runtimeMock.startContainer(); tx = runtimeMock.openUserTx(runtimeMock.loginTest(), false); } @AfterClass public static void afterClass() { if (runtimeMock != null) runtimeMock.destroyRuntime(); } private Resource resource; private Action action; @Before public void init() { // add a resource with integer state variable this.resource = ModelGenerator.createResource("@1", "Test With States", "Stated"); IntegerTimedState timedState = this.resource.getTimedState(STATE_INTEGER_ID); timedState.getTimeEvolution().clear(); timedState.applyChange(new ValueChange<>(STATE_TIME_0, new IntegerValue(STATE_INTEGER_TIME_0)), true); Activity activity = new Activity("activity", "Test", "Test", TimeOrdering.SERIES); this.action = new Action("action", "Action", "Use"); activity.addElement(this.action); assertEquals(State.CREATED, this.action.getState()); IntegerParameter iP = new IntegerParameter("quantity", "Occupation", 1); this.action.addParameterBag(new ParameterBag("objectives", "Objectives", "Objectives")); this.action.addParameter("objectives", iP); createChanges(this.action); this.action.setResourceId(this.resource.getId()); this.action.setResourceType(this.resource.getType()); tx.add(this.resource); tx.add(activity); } @Test public void test() { PlanActionCommand cmd = new PlanActionCommand(tx); cmd.setAction(this.action); cmd.doCommand(); // check the state assertEquals(State.PLANNED, this.action.getState()); // check the resource Id assertEquals(this.resource.getId(), this.action.getResourceId()); // check if we get the expected result StrolchTimedState<IValue<Integer>> timedState = this.resource.getTimedState(STATE_INTEGER_ID); ITimeVariable<IValue<Integer>> timeEvolution = timedState.getTimeEvolution(); SortedSet<ITimeValue<IValue<Integer>>> values = timeEvolution.getValues(); assertEquals(3, values.size()); ITimeValue<IValue<Integer>> valueAt = timeEvolution.getValueAt(STATE_TIME_0); assertEquals(new IntegerValue(0), valueAt.getValue()); valueAt = timeEvolution.getValueAt(STATE_TIME_10); assertEquals(new IntegerValue(1), valueAt.getValue()); valueAt = timeEvolution.getValueAt(STATE_TIME_20); assertEquals(new IntegerValue(0), valueAt.getValue()); } /** * <p> * add changes to action start and end time with a value defined in the action objective and set the stateId of the * state variable to apply the change to * </p> * * @param action * the action to create changes for */ protected static void createChanges(Action action) { IntegerParameter parameter = action.getParameter("objectives", "quantity"); Integer quantity = parameter.getValue(); IValueChange<IntegerValue> startChange = new ValueChange<>(STATE_TIME_10, new IntegerValue(quantity)); startChange.setStateId(STATE_INTEGER_ID); action.addChange(startChange); IValueChange<IntegerValue> endChange = new ValueChange<>(STATE_TIME_20, new IntegerValue(-quantity)); endChange.setStateId(STATE_INTEGER_ID); action.addChange(endChange); } }
{ "content_hash": "c0d8a8f65849ebb4016edad09854676a", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 116, "avg_line_length": 33.47517730496454, "alnum_prop": 0.7669491525423728, "repo_name": "4treesCH/strolch", "id": "938b4668f16d63db0a5f8edc1e887779de5afbfe", "size": "5341", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "li.strolch.service/src/test/java/li/strolch/execution/PlanActionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "2003" }, { "name": "CSS", "bytes": "2486" }, { "name": "HTML", "bytes": "383752" }, { "name": "Java", "bytes": "4122045" }, { "name": "JavaScript", "bytes": "2831" }, { "name": "PLSQL", "bytes": "3323" }, { "name": "Shell", "bytes": "14167" }, { "name": "Smarty", "bytes": "878" }, { "name": "TSQL", "bytes": "29111" } ], "symlink_target": "" }
> A slush generator for create a React component in isolation The idea of creating this generator components was based on the design structure them in isolation. Where **we believe** the web should be built this way. It is customized based on some current needs and preferences of Personare but you can easily change. Feel free to suggest improvements =] ## How we made To define the structure we use an internal process called **DSS** (Design Structure Sprint) that through a short sprint it allows us to stay focused and aligned with the solution. #### Environment [React Storybook](https://github.com/kadirahq/react-storybook) - *to tell stories with different behaviors of the component and provide an example page.* #### Style Guide - [EditorConfig](http://editorconfig.org/) - *standardize some general settings among multiple editors* - [ESLint](http://eslint.org/) - *for reporting the patterns of code* - **Plugins** - [React](https://github.com/yannickcr/eslint-plugin-react) - [Snazzy](https://github.com/feross/snazzy) - [Standard](https://github.com/feross/standard) - [Standard Loader](https://github.com/timoxley/standard-loader) #### Tests - [Jest](https://facebook.github.io/jest/) - *test framework* #### Compiler - [babel](https://babeljs.io/) - **Plugins** - [ES2015](https://www.npmjs.com/package/babel-preset-es2015) - [stage-0](https://www.npmjs.com/package/babel-preset-stage-0) - [babel-jest](https://www.npmjs.com/package/babel-jest) - [React](https://www.npmjs.com/package/babel-preset-react) ### The structure ```bash ├── .babelrc ├── .editorconfig ├── .eslintrc.json ├── .github │   ├── ISSUE_TEMPLATE.md │   └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .scrutinizer.yml | .travis.yml | circle.yml ├── .storybook │   ├── config.js │   ├── webpack.config.js │   └── webpack.dist.config.js ├── README.md ├── contributing.md ├── package.json ├── src │   ├── MyFirstComponent.css │   ├── MyFirstComponent.js │   └── MyFirstComponent.story.js └── tests ├── MyFirstComponent.test.js └── mock-browser.js ``` ## Installation - Requirements 1. [Node >= 6.0](https://nodejs.org/en/) 2. [Slush](http://slushjs.github.io/#/) After install the requirements, run the following command: ```bash [sudo] npm i -g @personare/slush-react-component-generator ``` ## Usage Create a new folder for your project: ```bash mkdir my-first-component && cd my-first-component ``` Run the generator: ```bash slush react-component-generator ``` ## Team This generator was made with love by [contributors](https://github.com/Personare/react-component-generator/graphs/contributors). ## License [MIT © Personare](./LICENSE)
{ "content_hash": "04c86919db386001a63f6254e448187d", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 256, "avg_line_length": 28.72340425531915, "alnum_prop": 0.6985185185185185, "repo_name": "Personare/react-component-generator", "id": "3182823ac9b364e3c7de3849dddd63d2b6445354", "size": "3048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "273" }, { "name": "JavaScript", "bytes": "10688" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- (1) Optimize for mobile versions: http://goo.gl/EOpFl --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- (1) force latest IE rendering engine: bit.ly/1c8EiC9 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Welcome to Jekyll!</title> <meta name="description" content="The musings of a digital jack of all trades" /> <meta name="HandheldFriendly" content="True" /> <meta name="MobileOptimized" content="320" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <link rel="canonical" href="http://myblog.***.***/jekyll/update/2014/08/29/welcome-to-jekyll.html"> <link rel="shortcut icon" href="/assets/images/favicon.ico"> <!-- <link rel="stylesheet" href=""> --> <link rel="stylesheet" href="http://brick.a.ssl.fastly.net/Linux+Libertine:400,400i,700,700i/Open+Sans:400,400i,700,700i"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" media="screen" href="/css/main.css" /> <link rel="stylesheet" type="text/css" media="print" href="/css/print.css" /> </head> <body itemscope itemtype="http://schema.org/Article"> <!-- header start --> <a href="http://myblog.***.***" class="logo-readium"><span class="logo" style="background-image: url(/assets/images/df_logo.jpg)"></span></a> <!-- header end --> <main class="content" role="main"> <article class="post"> <div class="article-image"> <div class="post-image-image" style="background-image: url(/assets/article_images/2014-08-29-welcome-to-jekyll/desktop.jpg)"> Article Image </div> <div class="post-meta"> <h1 class="post-title">Welcome to Jekyll!</h1> <div class="cf post-meta-text"> <div class="author-image" style="background-image: url(/assets/images/author.jpg)">Blog Logo</div> <h4 class="author-name" itemprop="author" itemscope itemtype="http://schema.org/Person">Mark Smith</h4> on <time datetime="2014-08-29 16:34">29 Aug 2014</time> <!-- , tagged on <span class="post-tag-">, <a href="/tag/"></a></span> --> </div> <div style="text-align:center"> <a href="#topofpage" class="topofpage"><i class="fa fa-angle-down"></i></a> </div> </div> </div> <section class="post-content"> <div class="post-reading"> <span class="post-reading-time"></span> read </div> <a name="topofpage"></a> <p>You’ll find this post in your <code>_posts</code> directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run <code>jekyll serve --watch</code>, which launches a web server and auto-regenerates your site when a file is updated.</p> <p>To add new posts, simply add a file in the <code>_posts</code> directory that follows the convention <code>YYYY-MM-DD-name-of-post.ext</code> and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.</p> <p>Jekyll also offers powerful support for code snippets:</p> <div class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">print_hi</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="nb">puts</span> <span class="s2">&quot;Hi, </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">&quot;</span> <span class="k">end</span> <span class="n">print_hi</span><span class="p">(</span><span class="s1">&#39;Tom&#39;</span><span class="p">)</span> <span class="c1">#=&gt; prints &#39;Hi, Tom&#39; to STDOUT.</span></code></pre></div> <p>Check out the <a href="http://jekyllrb.com">Jekyll docs</a> for more info on how to get the most out of Jekyll. File all bugs/feature requests at <a href="https://github.com/jekyll/jekyll">Jekyll’s GitHub repo</a>. If you have questions, you can ask them on <a href="https://github.com/jekyll/jekyll-help">Jekyll’s dedicated Help repository</a>.</p> <div class="highlight"><pre><code class="language-js" data-lang="js"><span class="o">&lt;</span><span class="nx">footer</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;site-footer&quot;</span><span class="o">&gt;</span> <span class="o">&lt;</span><span class="nx">a</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;subscribe&quot;</span> <span class="nx">href</span><span class="o">=</span><span class="s2">&quot;/feed.xml&quot;</span><span class="o">&gt;</span> <span class="o">&lt;</span><span class="nx">span</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;tooltip&quot;</span><span class="o">&gt;</span> <span class="o">&lt;</span><span class="nx">i</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;fa fa-rss&quot;</span><span class="o">&gt;&lt;</span><span class="err">/i&gt; Subscribe!&lt;/span&gt;&lt;/a&gt;</span> <span class="o">&lt;</span><span class="nx">div</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;inner&quot;</span><span class="o">&gt;</span><span class="nx">a</span> <span class="o">&lt;</span><span class="nx">section</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;copyright&quot;</span><span class="o">&gt;</span><span class="nx">All</span> <span class="nx">content</span> <span class="nx">copyright</span> <span class="o">&lt;</span><span class="nx">a</span> <span class="nx">href</span><span class="o">=</span><span class="s2">&quot;mailto:mark@appmatters.io&quot;</span><span class="o">&gt;</span><span class="nx">Mark</span> <span class="nx">Smith</span><span class="o">&lt;</span><span class="err">/a&gt; &amp;copy; 2015 &amp;bull; All rights reserved.&lt;/section&gt;</span> <span class="o">&lt;</span><span class="nx">section</span> <span class="kr">class</span><span class="o">=</span><span class="s2">&quot;poweredby&quot;</span><span class="o">&gt;</span><span class="nx">Made</span> <span class="kd">with</span> <span class="o">&lt;</span><span class="nx">a</span> <span class="nx">href</span><span class="o">=</span><span class="s2">&quot;http://jekyllrb.com&quot;</span><span class="o">&gt;</span> <span class="nx">Jekyll</span><span class="o">&lt;</span><span class="err">/a&gt;&lt;/section&gt;</span> <span class="o">&lt;</span><span class="err">/div&gt;</span> <span class="o">&lt;</span><span class="err">/footer&gt;</span></code></pre></div> </section> <footer class="post-footer"> <section class="share"> <a class="icon-twitter" href="http://twitter.com/share?text=Welcome+to+Jekyll%21&amp;url=http://myblog.***.***/jekyll/update/2014/08/29/welcome-to-jekyll" onclick="window.open(this.href, 'twitter-share', 'width=550,height=255');return false;"> <i class="fa fa-twitter"></i><span class="hidden">twitter</span> </a> </section> </footer> <div class="bottom-teaser cf"> <div class="isLeft"> <h5 class="index-headline featured"><span>Written by</span></h5> <section class="author"> <div class="author-image" style="background-image: url(/assets/images/author.jpg)">Blog Logo</div> <h4>Mark Smith</h4> <p class="bio"></p> <hr> <p class="published">Published <time datetime="2014-08-29 16:34">29 Aug 2014</time></p> </section> </div> <div class="isRight"> <h5 class="index-headline featured"><span>Supported by</span></h5> <footer class="site-footer"> <section class="poweredby">Proudly published with <a href="http://jekyllrb.com"> Jekyll</a></section> <a class="subscribe" href="/feed.xml"> <span class="tooltip"> <i class="fa fa-rss"></i> You should subscribe to my feed.</span></a> <div class="inner"> <section class="copyright">All content copyright <a href="/">Mark Smith</a> &copy; 2015<br>All rights reserved.</section> </div> </footer> </div> </div> </article> </main> <div class="bottom-closer"> <div class="background-closer-image" style="background-image: url(/assets/images/blogcover.jpg)"> Image </div> <div class="inner"> <h1 class="blog-title">I'M SMITH</h1> <h2 class="blog-description">The musings of a digital jack of all trades</h2> <a href="/" class="btn">Back to Overview</a> </div> </div> <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="/assets/js/jquery.fitvids.js"></script> <script type="text/javascript" src="/assets/js/index.js"></script> <script type="text/javascript" src="/assets/js/readingTime.min.js"></script> <script> (function ($) { "use strict"; $(document).ready(function(){ var $window = $(window), $image = $('.post-image-image, .teaserimage-image'); $window.on('scroll', function() { var top = $window.scrollTop(); if (top < 0 || top > 1500) { return; } $image .css('transform', 'translate3d(0px, '+top/3+'px, 0px)') .css('opacity', 1-Math.max(top/700, 0)); }); $window.trigger('scroll'); var height = $('.article-image').height(); $('.post-content').css('padding-top', height + 'px'); $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 500); return false; } } }); }); }(jQuery)); </script> </body> </html>
{ "content_hash": "446ba0caac03144b104a4897850909f6", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 705, "avg_line_length": 59.61931818181818, "alnum_prop": 0.6044029352901935, "repo_name": "imsmithza/imsmithza.github.io", "id": "587abc1c058c2f4b395a478c0fdfad8e5c7e0830", "size": "10499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/jekyll/update/2014/08/29/welcome-to-jekyll.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35247" }, { "name": "HTML", "bytes": "45232" }, { "name": "JavaScript", "bytes": "7120" } ], "symlink_target": "" }
package elastic_test import ( "context" "encoding/json" "fmt" "log" "os" "reflect" "time" elastic "github.com/venicegeo/pz-gocommon/elasticsearch/elastic-5-api" ) type Tweet struct { User string `json:"user"` Message string `json:"message"` Retweets int `json:"retweets"` Image string `json:"image,omitempty"` Created time.Time `json:"created,omitempty"` Tags []string `json:"tags,omitempty"` Location string `json:"location,omitempty"` } func Example() { errorlog := log.New(os.Stdout, "APP ", log.LstdFlags) // Obtain a client. You can also provide your own HTTP client here. client, err := elastic.NewClient(elastic.SetErrorLog(errorlog)) if err != nil { // Handle error panic(err) } // Trace request and response details like this //client.SetTracer(log.New(os.Stdout, "", 0)) // Ping the Elasticsearch server to get e.g. the version number info, code, err := client.Ping("http://127.0.0.1:9200").Do(context.Background()) if err != nil { // Handle error panic(err) } fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number) // Getting the ES version number is quite common, so there's a shortcut esversion, err := client.ElasticsearchVersion("http://127.0.0.1:9200") if err != nil { // Handle error panic(err) } fmt.Printf("Elasticsearch version %s\n", esversion) // Use the IndexExists service to check if a specified index exists. exists, err := client.IndexExists("twitter").Do(context.Background()) if err != nil { // Handle error panic(err) } if !exists { // Create a new index. mapping := ` { "settings":{ "number_of_shards":1, "number_of_replicas":0 }, "mappings":{ "_default_": { "_all": { "enabled": true } }, "tweet":{ "properties":{ "user":{ "type":"keyword" }, "message":{ "type":"text", "store": true, "fielddata": true }, "retweets":{ "type":"long" }, "tags":{ "type":"keyword" }, "location":{ "type":"geo_point" }, "suggest_field":{ "type":"completion" } } } } } ` createIndex, err := client.CreateIndex("twitter").Body(mapping).Do(context.Background()) if err != nil { // Handle error panic(err) } if !createIndex.Acknowledged { // Not acknowledged } } // Index a tweet (using JSON serialization) tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0} put1, err := client.Index(). Index("twitter"). Type("tweet"). Id("1"). BodyJson(tweet1). Do(context.Background()) if err != nil { // Handle error panic(err) } fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type) // Index a second tweet (by string) tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}` put2, err := client.Index(). Index("twitter"). Type("tweet"). Id("2"). BodyString(tweet2). Do(context.Background()) if err != nil { // Handle error panic(err) } fmt.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type) // Get tweet with specified ID get1, err := client.Get(). Index("twitter"). Type("tweet"). Id("1"). Do(context.Background()) if err != nil { // Handle error panic(err) } if get1.Found { fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type) } // Flush to make sure the documents got written. _, err = client.Flush().Index("twitter").Do(context.Background()) if err != nil { panic(err) } // Search with a term query termQuery := elastic.NewTermQuery("user", "olivere") searchResult, err := client.Search(). Index("twitter"). // search in index "twitter" Query(termQuery). // specify the query Sort("user", true). // sort by "user" field, ascending From(0).Size(10). // take documents 0-9 Pretty(true). // pretty print request and response JSON Do(context.Background()) // execute if err != nil { // Handle error panic(err) } // searchResult is of type SearchResult and returns hits, suggestions, // and all kinds of other information from Elasticsearch. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis) // Each is a convenience function that iterates over hits in a search result. // It makes sure you don't need to check for nil values in the response. // However, it ignores errors in serialization. If you want full control // over iterating the hits, see below. var ttyp Tweet for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) { t := item.(Tweet) fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } // TotalHits is another convenience function that works even when something goes wrong. fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits()) // Here's how you iterate through results with full control over each step. if searchResult.Hits.TotalHits > 0 { fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits) // Iterate through results for _, hit := range searchResult.Hits.Hits { // hit.Index contains the name of the index // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}). var t Tweet err := json.Unmarshal(*hit.Source, &t) if err != nil { // Deserialization failed } // Work with tweet fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } } else { // No hits fmt.Print("Found no tweets\n") } // ... // Delete an index. deleteIndex, err := client.DeleteIndex("twitter").Do(context.Background()) if err != nil { // Handle error panic(err) } if !deleteIndex.Acknowledged { // Not acknowledged } } func ExampleClient_NewClient_default() { // Obtain a client to the Elasticsearch instance on http://127.0.0.1:9200. client, err := elastic.NewClient() if err != nil { // Handle error fmt.Printf("connection failed: %v\n", err) } else { fmt.Println("connected") } _ = client // Output: // connected } func ExampleClient_NewClient_cluster() { // Obtain a client for an Elasticsearch cluster of two nodes, // running on 10.0.1.1 and 10.0.1.2. client, err := elastic.NewClient(elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200")) if err != nil { // Handle error panic(err) } _ = client } func ExampleClient_NewClient_manyOptions() { // Obtain a client for an Elasticsearch cluster of two nodes, // running on 10.0.1.1 and 10.0.1.2. Do not run the sniffer. // Set the healthcheck interval to 10s. When requests fail, // retry 5 times. Print error messages to os.Stderr and informational // messages to os.Stdout. client, err := elastic.NewClient( elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200"), elastic.SetSniff(false), elastic.SetHealthcheckInterval(10*time.Second), elastic.SetMaxRetries(5), elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)), elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags))) if err != nil { // Handle error panic(err) } _ = client } func ExampleIndexExistsService() { // Get a client to the local Elasticsearch instance. client, err := elastic.NewClient() if err != nil { // Handle error panic(err) } // Use the IndexExists service to check if the index "twitter" exists. exists, err := client.IndexExists("twitter").Do(context.Background()) if err != nil { // Handle error panic(err) } if exists { // ... } } func ExampleCreateIndexService() { // Get a client to the local Elasticsearch instance. client, err := elastic.NewClient() if err != nil { // Handle error panic(err) } // Create a new index. createIndex, err := client.CreateIndex("twitter").Do(context.Background()) if err != nil { // Handle error panic(err) } if !createIndex.Acknowledged { // Not acknowledged } } func ExampleDeleteIndexService() { // Get a client to the local Elasticsearch instance. client, err := elastic.NewClient() if err != nil { // Handle error panic(err) } // Delete an index. deleteIndex, err := client.DeleteIndex("twitter").Do(context.Background()) if err != nil { // Handle error panic(err) } if !deleteIndex.Acknowledged { // Not acknowledged } } func ExampleSearchService() { // Get a client to the local Elasticsearch instance. client, err := elastic.NewClient() if err != nil { // Handle error panic(err) } // Search with a term query termQuery := elastic.NewTermQuery("user", "olivere") searchResult, err := client.Search(). Index("twitter"). // search in index "twitter" Query(termQuery). // specify the query Sort("user", true). // sort by "user" field, ascending From(0).Size(10). // take documents 0-9 Pretty(true). // pretty print request and response JSON Do(context.Background()) // execute if err != nil { // Handle error panic(err) } // searchResult is of type SearchResult and returns hits, suggestions, // and all kinds of other information from Elasticsearch. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis) // Number of hits if searchResult.Hits.TotalHits > 0 { fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits) // Iterate through results for _, hit := range searchResult.Hits.Hits { // hit.Index contains the name of the index // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}). var t Tweet err := json.Unmarshal(*hit.Source, &t) if err != nil { // Deserialization failed } // Work with tweet fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } } else { // No hits fmt.Print("Found no tweets\n") } } func ExampleSearchResult() { client, err := elastic.NewClient() if err != nil { panic(err) } // Do a search searchResult, err := client.Search().Index("twitter").Query(elastic.NewMatchAllQuery()).Do(context.Background()) if err != nil { panic(err) } // searchResult is of type SearchResult and returns hits, suggestions, // and all kinds of other information from Elasticsearch. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis) // Each is a utility function that iterates over hits in a search result. // It makes sure you don't need to check for nil values in the response. // However, it ignores errors in serialization. If you want full control // over iterating the hits, see below. var ttyp Tweet for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) { t := item.(Tweet) fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits()) // Here's how you iterate hits with full control. if searchResult.Hits.TotalHits > 0 { fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits) // Iterate through results for _, hit := range searchResult.Hits.Hits { // hit.Index contains the name of the index // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}). var t Tweet err := json.Unmarshal(*hit.Source, &t) if err != nil { // Deserialization failed } // Work with tweet fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } } else { // No hits fmt.Print("Found no tweets\n") } } func ExampleClusterHealthService() { client, err := elastic.NewClient() if err != nil { panic(err) } // Get cluster health res, err := elastic.NewClusterHealthService(client).Index("twitter").Do(context.Background()) if err != nil { panic(err) } if res == nil { panic(err) } fmt.Printf("Cluster status is %q\n", res.Status) } func ExampleClusterHealthService_WaitForGreen() { client, err := elastic.NewClient() if err != nil { panic(err) } // Wait for status green res, err := elastic.NewClusterHealthService(client).WaitForStatus("green").Timeout("15s").Do(context.Background()) if err != nil { panic(err) } if res.TimedOut { fmt.Printf("time out waiting for cluster status %q\n", "green") } else { fmt.Printf("cluster status is %q\n", res.Status) } }
{ "content_hash": "2dbf55d56cc2fad0c8a8782b72a5989a", "timestamp": "", "source": "github", "line_count": 458, "max_line_length": 116, "avg_line_length": 26.49344978165939, "alnum_prop": 0.6571616944123949, "repo_name": "venicegeo/pz-gocommon", "id": "6050e071bbb8b750d62d1b970d9dc4f8212072f5", "size": "12318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elasticsearch/elastic-5-api/example_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "706642" }, { "name": "Groovy", "bytes": "2691" }, { "name": "Shell", "bytes": "6521" } ], "symlink_target": "" }
Use `showHeader: false` to hide the header of bootstrap table. _by [@wenzhixin](https://github.com/wenzhixin)_ <iframe width="100%" height="300" src="http://jsfiddle.net/wenyi/e3nk137y/22/embedded/html,result" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
{ "content_hash": "c484f6d8e3a075a994992c47e5fd3bb5", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 158, "avg_line_length": 90, "alnum_prop": 0.7592592592592593, "repo_name": "mikepenz/bootstrap-table", "id": "612350bf7ab7f057044042be0b30848757f1be0e", "size": "368", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/_i18n/zh-cn/examples/hide-header.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2726" }, { "name": "JavaScript", "bytes": "10828" }, { "name": "Ruby", "bytes": "5086" } ], "symlink_target": "" }
'use strict'; angular.module('pie', ['ngResource', 'ui.bootstrap']) .config(function ($routeProvider) { $routeProvider .when('/', { redirectTo: '/login' }) .when('/discuss/:discussionId', { templateUrl: 'views/discuss.html' }) .when('/edit/:documentId', { templateUrl: 'views/edit.html' }) .when('/editAndDiscuss/:documentId/:sectionIndex/:discussionIndex', { templateUrl: 'views/editAndDiscuss.html' }) .when('/editAndDiscuss/:documentId', { templateUrl: 'views/editAndDiscuss.html' }) .when('/architecture/:documentId', { templateUrl: 'views/architecture.html' }) .when('/profile', { templateUrl: 'views/profile.html' }) .when('/login', { templateUrl: 'views/login.html' }) .otherwise({ templateUrl: 'views/404.html' }); }) .constant('apiBaseUrl', 'http://' + document.domain + ':8080');
{ "content_hash": "abba38b2188662f93a7c50748168f2da", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 72, "avg_line_length": 26.058823529411764, "alnum_prop": 0.6207674943566591, "repo_name": "PieEditor/PIE", "id": "9566d9ff87f8c5de6e318632c34d6cff6d2c7ab0", "size": "886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/front/app/scripts/app.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "9116" }, { "name": "CSS", "bytes": "177982" }, { "name": "JavaScript", "bytes": "70866" }, { "name": "Objective-C++", "bytes": "883" }, { "name": "Python", "bytes": "5796" }, { "name": "Shell", "bytes": "581" }, { "name": "XSLT", "bytes": "1207" } ], "symlink_target": "" }
/** @file Exporter.cpp Assimp export interface. While it's public interface bears many similarities to the import interface (in fact, it is largely symmetric), the internal implementations differs a lot. Exporters are considered stateless and are simple callbacks which we maintain in a global list along with their description strings. Here we implement only the C++ interface (Assimp::Exporter). */ #ifndef ASSIMP_BUILD_NO_EXPORT #include "DefaultIOSystem.h" #include "BlobIOSystem.h" #include "SceneCombiner.h" #include "BaseProcess.h" #include "Importer.h" // need this for GetPostProcessingStepInstanceList() #include "JoinVerticesProcess.h" #include "MakeVerboseFormat.h" #include "ConvertToLHProcess.h" #include "Exceptional.h" #include "ScenePrivate.h" #include <boost/shared_ptr.hpp> #include "../include/assimp/Exporter.hpp" #include "../include/assimp/mesh.h" #include "../include/assimp/postprocess.h" #include "../include/assimp/scene.h" #include <memory> namespace Assimp { // PostStepRegistry.cpp void GetPostProcessingStepInstanceList(std::vector< BaseProcess* >& out); // ------------------------------------------------------------------------------------------------ // Exporter worker function prototypes. Should not be necessary to #ifndef them, it's just a prototype // do not use const, because some exporter need to convert the scene temporary void ExportSceneCollada(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneXFile(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneObj(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneSTL(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneSTLBinary(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportScenePly(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportScenePlyBinary(const char*, IOSystem*, const aiScene*, const ExportProperties*); void ExportScene3DS(const char*, IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneAssbin(const char*, IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneAssxml(const char*, IOSystem*, const aiScene*, const ExportProperties*); // ------------------------------------------------------------------------------------------------ // global array of all export formats which Assimp supports in its current build Exporter::ExportFormatEntry gExporters[] = { #ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER Exporter::ExportFormatEntry( "collada", "COLLADA - Digital Asset Exchange Schema", "dae", &ExportSceneCollada), #endif #ifndef ASSIMP_BUILD_NO_XFILE_EXPORTER Exporter::ExportFormatEntry( "x", "X Files", "x", &ExportSceneXFile, aiProcess_MakeLeftHanded | aiProcess_FlipWindingOrder | aiProcess_FlipUVs), #endif #ifndef ASSIMP_BUILD_NO_OBJ_EXPORTER Exporter::ExportFormatEntry( "obj", "Wavefront OBJ format", "obj", &ExportSceneObj, aiProcess_GenSmoothNormals /*| aiProcess_PreTransformVertices */), #endif #ifndef ASSIMP_BUILD_NO_STL_EXPORTER Exporter::ExportFormatEntry( "stl", "Stereolithography", "stl" , &ExportSceneSTL, aiProcess_Triangulate | aiProcess_GenNormals | aiProcess_PreTransformVertices ), Exporter::ExportFormatEntry( "stlb", "Stereolithography (binary)", "stl" , &ExportSceneSTLBinary, aiProcess_Triangulate | aiProcess_GenNormals | aiProcess_PreTransformVertices ), #endif #ifndef ASSIMP_BUILD_NO_PLY_EXPORTER Exporter::ExportFormatEntry( "ply", "Stanford Polygon Library", "ply" , &ExportScenePly, aiProcess_PreTransformVertices ), Exporter::ExportFormatEntry( "plyb", "Stanford Polygon Library (binary)", "ply", &ExportScenePlyBinary, aiProcess_PreTransformVertices ), #endif #ifndef ASSIMP_BUILD_NO_3DS_EXPORTER Exporter::ExportFormatEntry( "3ds", "Autodesk 3DS (legacy)", "3ds" , &ExportScene3DS, aiProcess_Triangulate | aiProcess_SortByPType | aiProcess_JoinIdenticalVertices), #endif #ifndef ASSIMP_BUILD_NO_ASSBIN_EXPORTER Exporter::ExportFormatEntry( "assbin", "Assimp Binary", "assbin" , &ExportSceneAssbin, 0), #endif #ifndef ASSIMP_BUILD_NO_ASSXML_EXPORTER Exporter::ExportFormatEntry( "assxml", "Assxml Document", "assxml" , &ExportSceneAssxml, 0), #endif }; #define ASSIMP_NUM_EXPORTERS (sizeof(gExporters)/sizeof(gExporters[0])) class ExporterPimpl { public: ExporterPimpl() : blob() , mIOSystem(new Assimp::DefaultIOSystem()) , mIsDefaultIOHandler(true) { GetPostProcessingStepInstanceList(mPostProcessingSteps); // grab all builtin exporters mExporters.resize(ASSIMP_NUM_EXPORTERS); std::copy(gExporters,gExporters+ASSIMP_NUM_EXPORTERS,mExporters.begin()); } ~ExporterPimpl() { delete blob; // Delete all post-processing plug-ins for( unsigned int a = 0; a < mPostProcessingSteps.size(); a++) { delete mPostProcessingSteps[a]; } } public: aiExportDataBlob* blob; boost::shared_ptr< Assimp::IOSystem > mIOSystem; bool mIsDefaultIOHandler; /** Post processing steps we can apply at the imported data. */ std::vector< BaseProcess* > mPostProcessingSteps; /** Last fatal export error */ std::string mError; /** Exporters, this includes those registered using #Assimp::Exporter::RegisterExporter */ std::vector<Exporter::ExportFormatEntry> mExporters; }; } // end of namespace Assimp using namespace Assimp; // ------------------------------------------------------------------------------------------------ Exporter :: Exporter() : pimpl(new ExporterPimpl()) { } // ------------------------------------------------------------------------------------------------ Exporter :: ~Exporter() { FreeBlob(); delete pimpl; } // ------------------------------------------------------------------------------------------------ void Exporter :: SetIOHandler( IOSystem* pIOHandler) { pimpl->mIsDefaultIOHandler = !pIOHandler; pimpl->mIOSystem.reset(pIOHandler); } // ------------------------------------------------------------------------------------------------ IOSystem* Exporter :: GetIOHandler() const { return pimpl->mIOSystem.get(); } // ------------------------------------------------------------------------------------------------ bool Exporter :: IsDefaultIOHandler() const { return pimpl->mIsDefaultIOHandler; } // ------------------------------------------------------------------------------------------------ const aiExportDataBlob* Exporter :: ExportToBlob( const aiScene* pScene, const char* pFormatId, unsigned int, const ExportProperties* pProperties) { if (pimpl->blob) { delete pimpl->blob; pimpl->blob = NULL; } boost::shared_ptr<IOSystem> old = pimpl->mIOSystem; BlobIOSystem* blobio = new BlobIOSystem(); pimpl->mIOSystem = boost::shared_ptr<IOSystem>( blobio ); if (AI_SUCCESS != Export(pScene,pFormatId,blobio->GetMagicFileName())) { pimpl->mIOSystem = old; return NULL; } pimpl->blob = blobio->GetBlobChain(); pimpl->mIOSystem = old; return pimpl->blob; } // ------------------------------------------------------------------------------------------------ bool IsVerboseFormat(const aiMesh* mesh) { // avoid slow vector<bool> specialization std::vector<unsigned int> seen(mesh->mNumVertices,0); for(unsigned int i = 0; i < mesh->mNumFaces; ++i) { const aiFace& f = mesh->mFaces[i]; for(unsigned int j = 0; j < f.mNumIndices; ++j) { if(++seen[f.mIndices[j]] == 2) { // found a duplicate index return false; } } } return true; } // ------------------------------------------------------------------------------------------------ bool IsVerboseFormat(const aiScene* pScene) { for(unsigned int i = 0; i < pScene->mNumMeshes; ++i) { if(!IsVerboseFormat(pScene->mMeshes[i])) { return false; } } return true; } // ------------------------------------------------------------------------------------------------ aiReturn Exporter :: Export( const aiScene* pScene, const char* pFormatId, const char* pPath, unsigned int pPreprocessing, const ExportProperties* pProperties) { ASSIMP_BEGIN_EXCEPTION_REGION(); // when they create scenes from scratch, users will likely create them not in verbose // format. They will likely not be aware that there is a flag in the scene to indicate // this, however. To avoid surprises and bug reports, we check for duplicates in // meshes upfront. const bool is_verbose_format = !(pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) || IsVerboseFormat(pScene); pimpl->mError = ""; for (size_t i = 0; i < pimpl->mExporters.size(); ++i) { const Exporter::ExportFormatEntry& exp = pimpl->mExporters[i]; if (!strcmp(exp.mDescription.id,pFormatId)) { try { // Always create a full copy of the scene. We might optimize this one day, // but for now it is the most pragmatic way. aiScene* scenecopy_tmp; SceneCombiner::CopyScene(&scenecopy_tmp,pScene); std::auto_ptr<aiScene> scenecopy(scenecopy_tmp); const ScenePrivateData* const priv = ScenePriv(pScene); // steps that are not idempotent, i.e. we might need to run them again, usually to get back to the // original state before the step was applied first. When checking which steps we don't need // to run, those are excluded. const unsigned int nonIdempotentSteps = aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_MakeLeftHanded; // Erase all pp steps that were already applied to this scene const unsigned int pp = (exp.mEnforcePP | pPreprocessing) & ~(priv && !priv->mIsCopy ? (priv->mPPStepsApplied & ~nonIdempotentSteps) : 0u); // If no extra postprocessing was specified, and we obtained this scene from an // Assimp importer, apply the reverse steps automatically. // TODO: either drop this, or document it. Otherwise it is just a bad surprise. //if (!pPreprocessing && priv) { // pp |= (nonIdempotentSteps & priv->mPPStepsApplied); //} // If the input scene is not in verbose format, but there is at least postprocessing step that relies on it, // we need to run the MakeVerboseFormat step first. bool must_join_again = false; if (!is_verbose_format) { bool verbosify = false; for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && p->RequireVerboseFormat()) { verbosify = true; break; } } if (verbosify || (exp.mEnforcePP & aiProcess_JoinIdenticalVertices)) { DefaultLogger::get()->debug("export: Scene data not in verbose format, applying MakeVerboseFormat step first"); MakeVerboseFormatProcess proc; proc.Execute(scenecopy.get()); if(!(exp.mEnforcePP & aiProcess_JoinIdenticalVertices)) { must_join_again = true; } } } if (pp) { // the three 'conversion' steps need to be executed first because all other steps rely on the standard data layout { FlipWindingOrderProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { FlipUVsProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { MakeLeftHandedProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } // dispatch other processes for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && !dynamic_cast<FlipUVsProcess*>(p) && !dynamic_cast<FlipWindingOrderProcess*>(p) && !dynamic_cast<MakeLeftHandedProcess*>(p)) { p->Execute(scenecopy.get()); } } ScenePrivateData* const privOut = ScenePriv(scenecopy.get()); ai_assert(privOut); privOut->mPPStepsApplied |= pp; } if(must_join_again) { JoinVerticesProcess proc; proc.Execute(scenecopy.get()); } ExportProperties emptyProperties; // Never pass NULL ExportProperties so Exporters don't have to worry. exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get(), pProperties ? pProperties : &emptyProperties); } catch (DeadlyExportError& err) { pimpl->mError = err.what(); return AI_FAILURE; } return AI_SUCCESS; } } pimpl->mError = std::string("Found no exporter to handle this file format: ") + pFormatId; ASSIMP_END_EXCEPTION_REGION(aiReturn); return AI_FAILURE; } // ------------------------------------------------------------------------------------------------ const char* Exporter :: GetErrorString() const { return pimpl->mError.c_str(); } // ------------------------------------------------------------------------------------------------ void Exporter :: FreeBlob( ) { delete pimpl->blob; pimpl->blob = NULL; pimpl->mError = ""; } // ------------------------------------------------------------------------------------------------ const aiExportDataBlob* Exporter :: GetBlob() const { return pimpl->blob; } // ------------------------------------------------------------------------------------------------ const aiExportDataBlob* Exporter :: GetOrphanedBlob() const { const aiExportDataBlob* tmp = pimpl->blob; pimpl->blob = NULL; return tmp; } // ------------------------------------------------------------------------------------------------ size_t Exporter :: GetExportFormatCount() const { return pimpl->mExporters.size(); } // ------------------------------------------------------------------------------------------------ const aiExportFormatDesc* Exporter :: GetExportFormatDescription( size_t pIndex ) const { if (pIndex >= GetExportFormatCount()) { return NULL; } // Return from static storage if the requested index is built-in. if (pIndex < sizeof(gExporters) / sizeof(gExporters[0])) { return &gExporters[pIndex].mDescription; } return &pimpl->mExporters[pIndex].mDescription; } // ------------------------------------------------------------------------------------------------ aiReturn Exporter :: RegisterExporter(const ExportFormatEntry& desc) { BOOST_FOREACH(const ExportFormatEntry& e, pimpl->mExporters) { if (!strcmp(e.mDescription.id,desc.mDescription.id)) { return aiReturn_FAILURE; } } pimpl->mExporters.push_back(desc); return aiReturn_SUCCESS; } // ------------------------------------------------------------------------------------------------ void Exporter :: UnregisterExporter(const char* id) { for(std::vector<ExportFormatEntry>::iterator it = pimpl->mExporters.begin(); it != pimpl->mExporters.end(); ++it) { if (!strcmp((*it).mDescription.id,id)) { pimpl->mExporters.erase(it); break; } } } ExportProperties :: ExportProperties() {} ExportProperties::ExportProperties(const ExportProperties &other) : mIntProperties(other.mIntProperties), mFloatProperties(other.mFloatProperties), mStringProperties(other.mStringProperties), mMatrixProperties(other.mMatrixProperties) { } // ------------------------------------------------------------------------------------------------ // Set a configuration property void ExportProperties :: SetPropertyInteger(const char* szName, int iValue, bool* bWasExisting /*= NULL*/) { SetGenericProperty<int>(mIntProperties, szName,iValue,bWasExisting); } // ------------------------------------------------------------------------------------------------ // Set a configuration property void ExportProperties :: SetPropertyFloat(const char* szName, float iValue, bool* bWasExisting /*= NULL*/) { SetGenericProperty<float>(mFloatProperties, szName,iValue,bWasExisting); } // ------------------------------------------------------------------------------------------------ // Set a configuration property void ExportProperties :: SetPropertyString(const char* szName, const std::string& value, bool* bWasExisting /*= NULL*/) { SetGenericProperty<std::string>(mStringProperties, szName,value,bWasExisting); } // ------------------------------------------------------------------------------------------------ // Set a configuration property void ExportProperties :: SetPropertyMatrix(const char* szName, const aiMatrix4x4& value, bool* bWasExisting /*= NULL*/) { SetGenericProperty<aiMatrix4x4>(mMatrixProperties, szName,value,bWasExisting); } // ------------------------------------------------------------------------------------------------ // Get a configuration property int ExportProperties :: GetPropertyInteger(const char* szName, int iErrorReturn /*= 0xffffffff*/) const { return GetGenericProperty<int>(mIntProperties,szName,iErrorReturn); } // ------------------------------------------------------------------------------------------------ // Get a configuration property float ExportProperties :: GetPropertyFloat(const char* szName, float iErrorReturn /*= 10e10*/) const { return GetGenericProperty<float>(mFloatProperties,szName,iErrorReturn); } // ------------------------------------------------------------------------------------------------ // Get a configuration property const std::string ExportProperties :: GetPropertyString(const char* szName, const std::string& iErrorReturn /*= ""*/) const { return GetGenericProperty<std::string>(mStringProperties,szName,iErrorReturn); } // ------------------------------------------------------------------------------------------------ // Has a configuration property const aiMatrix4x4 ExportProperties :: GetPropertyMatrix(const char* szName, const aiMatrix4x4& iErrorReturn /*= aiMatrix4x4()*/) const { return GetGenericProperty<aiMatrix4x4>(mMatrixProperties,szName,iErrorReturn); } // ------------------------------------------------------------------------------------------------ // Has a configuration property bool ExportProperties :: HasPropertyInteger(const char* szName) const { return HasGenericProperty<int>(mIntProperties, szName); } // ------------------------------------------------------------------------------------------------ // Has a configuration property bool ExportProperties :: HasPropertyBool(const char* szName) const { return HasGenericProperty<int>(mIntProperties, szName); }; // ------------------------------------------------------------------------------------------------ // Has a configuration property bool ExportProperties :: HasPropertyFloat(const char* szName) const { return HasGenericProperty<float>(mFloatProperties, szName); }; // ------------------------------------------------------------------------------------------------ // Has a configuration property bool ExportProperties :: HasPropertyString(const char* szName) const { return HasGenericProperty<std::string>(mStringProperties, szName); }; // ------------------------------------------------------------------------------------------------ // Has a configuration property bool ExportProperties :: HasPropertyMatrix(const char* szName) const { return HasGenericProperty<aiMatrix4x4>(mMatrixProperties, szName); }; #endif // !ASSIMP_BUILD_NO_EXPORT
{ "content_hash": "02da6b5271e071868928e602cbb2d953", "timestamp": "", "source": "github", "line_count": 575, "max_line_length": 159, "avg_line_length": 34.05391304347826, "alnum_prop": 0.5855165721873244, "repo_name": "spetz911/almaty3d", "id": "f8744503dcd98e430c3ccbe3585ef8d14ab63162", "size": "21430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ThirdParty/assimp/src/Exporter.cpp", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "1464184" }, { "name": "C++", "bytes": "10479967" }, { "name": "CMake", "bytes": "79756" }, { "name": "GLSL", "bytes": "292672" }, { "name": "Logos", "bytes": "577807" }, { "name": "Objective-C", "bytes": "4462" }, { "name": "Perl", "bytes": "145" } ], "symlink_target": "" }
.config-menu { vertical-align: top; display: inline-block; width: 300px; } .config-editor { margin-left: 20px; display: inline-block; } .config-editor .message { font-size: 140%; font-weight: bold; margin: 10px; position: relative; display: none; } .nameList span { display: inline-block; width: 200px; } .nameList form { display: inline; } .newDelegationSettingButton { text-align: right; } .validation-summary-errors { max-width: 800px; } .nestedForm form { display: inline; } .nestedForm label { width: 100px; }
{ "content_hash": "371df8d38545ca1070f9ceeee30a0d7d", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 29, "avg_line_length": 15.685714285714285, "alnum_prop": 0.6775956284153005, "repo_name": "OBHITA/PROCenter", "id": "ffd95076328f3987eeebf35533b67faa4d557e3b", "size": "549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IdentityServer/src/OnPremise/WebSite/Areas/Admin/Content/Admin.css", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "5171" }, { "name": "Batchfile", "bytes": "8423" }, { "name": "C#", "bytes": "5709857" }, { "name": "CSS", "bytes": "6068607" }, { "name": "CoffeeScript", "bytes": "808" }, { "name": "HTML", "bytes": "2093418" }, { "name": "JavaScript", "bytes": "4650209" }, { "name": "PHP", "bytes": "611" }, { "name": "PowerShell", "bytes": "188034" }, { "name": "Ruby", "bytes": "25242" } ], "symlink_target": "" }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.hechikasoft.common.demo.activity.ActLogin"> <!-- Login progress --> <ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:visibility="gone"/> <ScrollView android:id="@+id/login_form" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <AutoCompleteTextView android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_email" android:inputType="textEmailAddress" android:maxLines="1" android:singleLine="true"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_password" android:imeActionId="@+id/login" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true"/> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/email_sign_in_button" style="?android:textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="@string/action_sign_in" android:textStyle="bold"/> </LinearLayout> </ScrollView> </LinearLayout>
{ "content_hash": "d47921b39acaa20fe0d0e929d060c67e", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 76, "avg_line_length": 41.714285714285715, "alnum_prop": 0.573785803237858, "repo_name": "smashdown/android-common", "id": "8bd5ffcdad9dffa3cfb6b163dd5878955754384a", "size": "3212", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/src/main/res/layout/act_login.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "117158" } ], "symlink_target": "" }
from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import IntegrityError from django.test import TestCase from lists.models import Item, List User = get_user_model() class ItemModelTest(TestCase): def test_default_text(self): item = Item() self.assertEqual(item.text, '') def test_item_is_related_to_list(self): list_ = List.objects.create() item = Item() item.list = list_ item.save() self.assertIn(item, list_.item_set.all()) def test_cannot_save_empty_list_items(self): list_ = List.objects.create() item = Item(list=list_, text='') with self.assertRaises(ValidationError): item.save() item.full_clean() def test_duplicate_items_are_invalid(self): list_ = List.objects.create() Item.objects.create(list=list_, text='bla') with self.assertRaises(IntegrityError): item = Item(list=list_, text='bla') item.save() def test_CAN_save_same_item_to_different_lists(self): list1 = List.objects.create() list2 = List.objects.create() Item.objects.create(list=list1, text='bla') item = Item(list=list2, text='bla') item.full_clean() # should not raise def test_list_ordering(self): list1 = List.objects.create() item1 = Item.objects.create(list=list1, text='i1') item2 = Item.objects.create(list=list1, text='item 2') item3 = Item.objects.create(list=list1, text='3') self.assertEqual( list(Item.objects.all()), [item1, item2, item3] ) def test_string_representation(self): item = Item(text='some text') self.assertEqual(str(item), 'some text') class ListModelTest(TestCase): def test_get_absolute_url(self): list_ = List.objects.create() self.assertEqual(list_.get_absolute_url(), '/lists/%d/' % list_.id) def test_create_new_creates_list_and_first_item(self): List.create_new(first_item_text='new item text') new_item = Item.objects.first() self.assertEqual(new_item.text, 'new item text') new_list = List.objects.first() self.assertEqual(new_item.list, new_list) def test_create_new_optionally_saves_owner(self): user = User.objects.create() List.create_new(first_item_text='new item text', owner=user) new_list = List.objects.first() self.assertEqual(new_list.owner, user) def test_lists_can_have_owners(self): List(owner=User()) # should not raise def test_list_owner_is_optional(self): List().full_clean() # should not raise def test_create_returns_new_list_object(self): returned = List.create_new(first_item_text='new item text') new_list = List.objects.first() self.assertEqual(returned, new_list) def test_list_name_is_first_item_text(self): list_ = List.objects.create() Item.objects.create(list=list_, text='first item') Item.objects.create(list=list_, text='second item') self.assertEqual(list_.name, 'first item')
{ "content_hash": "d1201617f62313aa0ee9cd223aed3c81", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 75, "avg_line_length": 35.142857142857146, "alnum_prop": 0.6269543464665416, "repo_name": "PeterHo/mysite", "id": "a32edd5b837f812f0324cc5250b69919d936f0f7", "size": "3198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lists/tests/test_models.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53762" }, { "name": "HTML", "bytes": "35270" }, { "name": "JavaScript", "bytes": "411445" }, { "name": "Python", "bytes": "138911" } ], "symlink_target": "" }
package org.jtheque.core; /* * Copyright JTheque (Baptiste Wicht) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.jtheque.utils.SystemProperty; import org.jtheque.utils.annotations.ThreadSafe; import org.jtheque.utils.io.FileUtils; import java.io.File; /** * Give access to the folders of the application. * * @author Baptiste Wicht */ @ThreadSafe public final class Folders { private static final File CORE_FOLDER; private static final File APPLICATION_FOLDER; private static final File MODULES_FOLDER; static { File userDir = new File(SystemProperty.USER_DIR.get()); CORE_FOLDER = new File(userDir, "core"); FileUtils.createIfNotExists(CORE_FOLDER); APPLICATION_FOLDER = new File(userDir, "application"); FileUtils.createIfNotExists(APPLICATION_FOLDER); MODULES_FOLDER = new File(userDir, "modules"); FileUtils.createIfNotExists(MODULES_FOLDER); } /** * Utility class, not instantiable. */ private Folders() { throw new AssertionError(); } /** * Return the core folder. It seems the folder where the files of the core are located. * * @return The File object who denotes the core folder. */ public static File getCoreFolder() { return CORE_FOLDER; } /** * Return the application folder. * * @return The File object who denotes the application folder. */ public static File getApplicationFolder() { return APPLICATION_FOLDER; } /** * Return the modules folder. It seems the folder where the modules are located. * * @return The File object who denotes the modules folder. */ public static File getModulesFolder() { return MODULES_FOLDER; } }
{ "content_hash": "d180d58e419417db76f4335efdba7a6c", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 91, "avg_line_length": 28.476190476190474, "alnum_prop": 0.6551003344481605, "repo_name": "wichtounet/jtheque-core", "id": "c2c14365a75a30b29bc5910ac111177d2d2ebd76", "size": "3004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jtheque-core/src/main/java/org/jtheque/core/Folders.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1113117" } ], "symlink_target": "" }
import {Firestore} from '@google-cloud/firestore'; class FakeBatch<T> { private docsToDelete: Array<FakeDoc<T>>; constructor() { this.docsToDelete = []; } delete(doc: FakeDoc<T>) { this.docsToDelete.push(doc); } async commit() { for (const doc of this.docsToDelete) { await doc.delete(); } } } class FakeQuery<T> { private collection: FakeCollection<T>; private key: string; private test: string; private value: T; constructor( collection: FakeCollection<T>, key: string, test: string, value: T) { if (test !== '<') { throw new Error('Mock does not support this query test. ' + test); } this.collection = collection; this.key = key; this.test = test; this.value = value; } async get(): Promise<Array<FakeDocSnapshot<T|null>>> { const snapshot = await this.collection.get(); const docs = snapshot.docs; return docs.filter((doc) => { const data = doc.data(); if (!data) { return false; } if (this.test === '<') { // tslint:disable-next-line no-any return (data as any)[this.key] < this.value; } throw new Error('Unsupported query test.'); }); } } class FakeDocSnapshot<T> { private innerData: T; private parent: FakeDoc<T>; constructor(doc: FakeDoc<T>, data: T) { this.innerData = data; this.parent = doc; } get exists() { if (!this.innerData) { return false; } return true; } data() { return this.innerData; } get ref() { return this.parent; } } class FakeCollectionSnapshot<T> { private innerDocs: Array<FakeDocSnapshot<T>>; constructor(docs: Array<FakeDocSnapshot<T>>) { this.innerDocs = docs; } get docs() { return this.innerDocs; } } class FakeDoc<T> { private data: T|null; private parent: FakeCollection<T>; private name: string; private collections: {[key: string]: FakeCollection<T>}; constructor(parent: FakeCollection<T>, name: string) { this.data = null; this.parent = parent; this.name = name; this.collections = {}; } collection(name: string) { if (this.collections[name]) { return this.collections[name]; } this.collections[name] = new FakeCollection(); return this.collections[name]; } async get(): Promise<FakeDocSnapshot<T|null>> { return new FakeDocSnapshot(this, this.data); } async create(data: T) { if (this.data) { throw new Error('Doc already exists.'); } this.data = data; } async update(data: T) { if (!this.data) { throw new Error('You can only update an existing doc'); } this.data = Object.assign(this.data, data); } async set(data: T) { this.data = data; } async delete() { return this.parent._deleteDoc(this.name); } } class FakeCollection<T> { private docs: {[key: string]: FakeDoc<T>}; constructor() { this.docs = {}; } doc(name: string) { if (this.docs[name]) { return this.docs[name]; } this.docs[name] = new FakeDoc(this, name); return this.docs[name]; } where(key: string, test: '<', value: T): FakeQuery<T> { return new FakeQuery(this, key, test, value); } async get(): Promise<FakeCollectionSnapshot<T|null>> { const docs = await Promise.all( Object.keys(this.docs).map((name) => this.docs[name].get())); return new FakeCollectionSnapshot(docs); } async _deleteDoc(name: string) { if (this.docs[name]) { delete this.docs[name]; } } } export function getFirestoreMock<T>(): Firestore { const mockFirstoreData: {[key: string]: FakeCollection<T>} = {}; // tslint:disable-next-line no-any const firestoreMock: any = { runTransaction: (cb: Function) => { return cb({ get: (docRef: FakeDoc<T>) => { return docRef.get(); }, set: (docRef: FakeDoc<T>, data: T) => { docRef.set(data); return cb; }, delete: (docRef: FakeDoc<T>) => { docRef.delete(); return cb; }, }); }, batch: () => { return new FakeBatch(); }, collection: (collectionName: string) => { if (mockFirstoreData[collectionName]) { return mockFirstoreData[collectionName]; } mockFirstoreData[collectionName] = new FakeCollection(); return mockFirstoreData[collectionName]; }, }; firestoreMock._data = mockFirstoreData; return firestoreMock; }
{ "content_hash": "d0b365f50744432a5ce8c678064d7f3a", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 72, "avg_line_length": 21.08411214953271, "alnum_prop": 0.5939716312056738, "repo_name": "PolymerLabs/project-health", "id": "7af5aaac94cba5595cef496a51c329ac41335094", "size": "4512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/fake-firestore.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13749" }, { "name": "HTML", "bytes": "2234" }, { "name": "JavaScript", "bytes": "10459" }, { "name": "TypeScript", "bytes": "535933" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <title>sap.m.GenericTile</title> <script src="shared-config.js"></script> <script src="../../../resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme='sap_belize' data-sap-ui-libs="sap.m, sap.ui.layout, sap.suite.ui.microchart"> </script> <script> jQuery.sap.initMobile(); var oGenericTileData = { mode: sap.m.GenericTileMode.ContentMode, subheader: "Expenses By Region", header: "Comparative Annual Totals", tooltip: "", footerNum: "Actual and Target", footerComp: "Compare across regions", scale: "MM", unit: "EUR", value: "1700", width: 174, padding: true, frameType: sap.m.FrameType.OneByOne, state: sap.m.LoadState.Loaded, valueColor: sap.m.ValueColor.Error, indicator: sap.m.DeviationIndicator.Up, title: "US Profit Margin", footer: "Current Quarter", description: "Maximum deviation", imageDescription: "", backgroundImage: "images/NewsImage1.png", newsTileContent: [{ footer: "August 21, 2013", contentText: "SAP Unveils Powerful New Player Comparison Tool Exclusively on NFL.com", subheader: "SAP News" }], feedTileContent: [{ footer: "New Notifications", contentText: "@@notify Great outcome of the Presentation today. New functionality well received.", subheader: "About 1 minute ago in Computer Market" }], frameTypes: [sap.m.FrameType.OneByOne, sap.m.FrameType.TwoByOne], indicators: Object.keys(sap.m.DeviationIndicator), modes: Object.keys(sap.m.GenericTileMode), states: Object.keys(sap.m.LoadState) }; var fnPress = function (oEvent) { if (oEvent.getParameter("action") === "Press") { var oActionSheet = new sap.m.ActionSheet({ title: "Choose Your Action", showCancelButton: true, placement: "Bottom", buttons: [ new sap.m.Button({ text: "Move" }), new sap.m.Button({ text: "Whatever" }) ], afterClose: function () { oActionSheet.destroy(); } }); oActionSheet.openBy(oEvent.getParameter("domRef")); } else { sap.m.MessageToast.show("Action " + oEvent.getParameter("action") + " on " + oEvent.getSource().getId() + " pressed."); } }; function setDefaultParameters(oData) { var sName; var oUriParameters = jQuery.sap.getUriParameters(); for (sName in oData) { if (oData.hasOwnProperty(sName) && typeof oData[sName] === 'string') { if (oUriParameters.get(sName) !== null) { oData[sName] = oUriParameters.get(sName); } } } } setDefaultParameters(oGenericTileData); var oGenericTileModel = new sap.ui.model.json.JSONModel(oGenericTileData); var oNVConfContS = new sap.m.NumericContent("numeric-cont-l", { value: "{/value}", scale: "{/scale}", indicator: "{/indicator}", formatterValue: "{/isFormatterValue}", truncateValueTo: "{/truncateValueTo}", valueColor: "{/valueColor}", icon: "sap-icon://line-charts", withMargin: true, width: "100%" }); var oNVConfS = new sap.m.TileContent("numeric-tile-cont-l", { unit: "{/unit}", footer: "{/footerNum}", content: oNVConfContS }); var oGenericTile1 = new sap.m.GenericTile({ mode: "{/mode}", subheader: "{/subheader}", frameType: "{/frameType}", header: "{/header}", tooltip: "{/tooltip}", state: "{/state}", headerImage: "{/headerImage}", imageDescription: "{/imageDescription}", press: fnPress, failedText: "{/failedText}", tileContent: [oNVConfS] }); oGenericTile1.addStyleClass("sapUiSmallMargin"); oGenericTile1.bindProperty("width", "/width", function (sValue) { return sValue + "px"; }); var oNumCnt2x1 = new sap.m.NumericContent("numeric-cont-2x1", { value: "{/value}", scale: "{/scale}", indicator: "{/indicator}", // truncateValueTo : 14, valueColor: "{/valueColor}", icon: "sap-icon://line-charts", withMargin: false, width: "100%" }); var oTc2x1 = new sap.m.TileContent("comp-tile-cont-2x1", { unit: "{/unit}", footer: "{/footerComp}", frameType: sap.m.FrameType.TwoByOne, content: oNumCnt2x1 }); var oGenericTile2 = new sap.m.GenericTile({ mode: "{/mode}", tooltip: "{/tooltip}", subheader: "{/subheader}", frameType: sap.m.FrameType.TwoByOne, header: "{/header}", state: "{/state}", headerImage: "{/headerImage}", imageDescription: "{/imageDescription}", press: fnPress, failedText: "{/failedText}", tileContent: [oTc2x1] }); oGenericTile2.addStyleClass("sapUiSmallMargin"); oGenericTile2.bindProperty("width", "/width", function (sValue) { return sValue + "px"; }); var oNewsTileContent = new sap.m.TileContent("news-tile-cont-2x1", { footer: "{footer}", frameType: sap.m.FrameType.TwoByOne, content: new sap.m.NewsContent({ contentText: "{contentText}", subheader: "{subheader}" }) }); var oGenericTile3 = new sap.m.GenericTile({ mode: "{/mode}", tooltip: "{/tooltip}", frameType: sap.m.FrameType.TwoByOne, state: "{/state}", headerImage: "{/headerImage}", imageDescription: "{/imageDescription}", backgroundImage: "{/backgroundImage}", press: fnPress, failedText: "{/failedText}", tileContent: { template: oNewsTileContent, path: "/newsTileContent" } }); oGenericTile3.addStyleClass("sapUiSmallMargin"); oGenericTile3.bindProperty("width", "/width", function (sValue) { return sValue + "px"; }); var oFeedTileContent = new sap.m.TileContent("feed-tile-cont-2x1", { footer: "{footer}", frameType: sap.m.FrameType.TwoByOne, content: new sap.m.FeedContent({ contentText: "{contentText}", subheader: "{subheader}" }) }); var oGenericTile4 = new sap.m.GenericTile({ mode: "{/mode}", tooltip: "{/tooltip}", header: "{/header}", subheader: "{/subheader}", frameType: sap.m.FrameType.TwoByOne, state: "{/state}", headerImage: "{/headerImage}", imageDescription: "{/imageDescription}", press: fnPress, failedText: "{/failedText}", tileContent: { template: oFeedTileContent, path: "/feedTileContent" } }); var oGenericTile5 = new sap.m.GenericTile({ mode: "{/mode}", tooltip: "{/tooltip}", header: "{/header}", subheader: "{/subheader}", frameType: sap.m.FrameType.TwoByOne, state: "{/state}", headerImage: "{/headerImage}", imageDescription: "{/imageDescription}", press: fnPress, failedText: "{/failedText}", tileContent: new sap.m.TileContent({ content: new sap.suite.ui.microchart.ColumnMicroChart({ size: "Responsive", columns: [ new sap.suite.ui.microchart.ColumnMicroChartData({ value: 65, color: "Error" }), new sap.suite.ui.microchart.ColumnMicroChartData({ value: 30, color: "Neutral" }), new sap.suite.ui.microchart.ColumnMicroChartData({ value: 120, color: "Neutral" }), new sap.suite.ui.microchart.ColumnMicroChartData({ value: 5, color: "Error" }), new sap.suite.ui.microchart.ColumnMicroChartData({ value: 85, color: "Error" }) ] }) }) }); oGenericTile5.bindProperty("width", "/width", function (sValue) { return sValue + "px"; }); oGenericTile4.addStyleClass("sapUiSmallMargin"); oGenericTile4.bindProperty("width", "/width", function (sValue) { return sValue + "px"; }); var oModeLabel = new sap.m.Label({ id: "mode-label", text: "Mode" }); var oModeSelect = new sap.m.Select({ items: { path: "/modes", template: new sap.ui.core.Item({ key: "{}", text: "{}" }) }, selectedKey: "{/mode}" }); var oTitleLbl = new sap.m.Label({ text: "Header", labelFor: "title-value" }); var oTitleInput = new sap.m.Input("title-value", { type: sap.m.InputType.Text, placeholder: 'Enter header ...' }); oTitleInput.bindValue("/header"); var oTitleDscr = new sap.m.Label({ text: "Subheader", labelFor: "desc-value" }); var oTooltipLbl = new sap.m.Label({ text: "Tooltip", labelFor: "tooltip-value" }); var oTooltipInput = new sap.m.Input("tooltip-value", { type: sap.m.InputType.Text, placeholder: 'Enter tooltip ...' }); oTooltipInput.bindValue("/tooltip"); // LANGUAGE var oWidthLabel = new sap.m.Label({ text: "Change width", labelFor: "width-change" }); var oWidthSlider = new sap.m.Slider({ width: "100%", min: 174, step: 5, max: 600 }); oWidthSlider.bindProperty("value", "/width"); // oWidthSlider.bindProperty("value", "/width", function(sValue) { // return sValue + "px"; // }); // oWidthSlider.bindProperty("value", { // parts: [ // {path: "/width", type: "sap.ui.model.type.String"}, // ] // }); // { // parts: [ // {path: "/firstName", type: "sap.ui.model.type.String"}, // {path: "myModel2>/lastName"} // ] // } var oLanguageLabel = new sap.m.Label({ text: "Change language", labelFor: "language-change" }); var oUpdateLanguageSelect = new sap.m.Select("language-change", { items: [ new sap.ui.core.Item({key: "en-US", text: "en-US"}), new sap.ui.core.Item({key: "de_CH", text: "de_CH"}), new sap.ui.core.Item({key: "es", text: "es"}), new sap.ui.core.Item({key: "it_CH", text: "it_CH"}), new sap.ui.core.Item({key: "zh_CN", text: "zh_CN"}), new sap.ui.core.Item({key: "es", text: "es"}), ], change: function (oEvent) { var sKey = oEvent.getParameter("selectedItem").getKey(); sap.ui.getCore().getConfiguration().setLanguage(sKey); } }); var oUpdateValueLbl = new sap.m.Label({ text: "Update Value", labelFor: "update-value" }); var oUpdateValueInput = new sap.m.Input("update-value", { type: sap.m.InputType.Text, placeholder: 'Enter value for update ...' }); oUpdateValueInput.bindValue("/value"); var oUpdateScaleLbl = new sap.m.Label({ text: "Update Scale", labelFor: "update-scale" }); var oUpdateScaleInput = new sap.m.Input("update-scale", { type: sap.m.InputType.Text, placeholder: 'Enter value for scale ...' }); oUpdateScaleInput.bindValue("/scale"); var oUpdatePaddingLbl = new sap.m.Label({ text: "Create padding", labelFor: "update-padding" }); var oUpdatePaddingCheckbox = new sap.m.CheckBox("update-padding", { select: function (oEvent) { jQuery("body").toggleClass("sapTilePaddingTest"); } }); var oDescInput = new sap.m.Input("desc-value", { type: sap.m.InputType.Text, placeholder: 'Enter description ...' }); oDescInput.bindValue("/subheader"); var oTitleFoot = new sap.m.Label({ text: "Footers", labelFor: "footer-value" }); var oFooterInputNum = new sap.m.Input("footer-num-value", { type: sap.m.InputType.Text, placeholder: 'Enter Numeric Footer ...' }); oFooterInputNum.bindValue("/footerNum"); var oFooterInputComp = new sap.m.Input("footer-cmp-value", { type: sap.m.InputType.Text, placeholder: 'Enter Comp Footer ...' }); oFooterInputComp.bindValue("/footerComp"); var oTitleUnit = new sap.m.Label({ text: "Units", labelFor: "unit-value" }); var oUnitInput = new sap.m.Input("unit-value", { type: sap.m.InputType.Text, placeholder: 'Enter Units ...' }); oUnitInput.bindValue("/unit"); var oFrameTypeLabel = new sap.m.Label({ text: "Frame Type", labelFor: "ft-value" }); var oFrameTypeSelect = new sap.m.Select("ft-value", { items: { path: "/frameTypes", template: new sap.ui.core.Item({ key: "{}", text: "{}" }) }, selectedKey: "{/frameType}" }); var oPictureLbl = new sap.m.Label({ text: "Header Image", labelFor: "picture-change" }); var oPictureSlct = new sap.m.Select("picture-value", { change: function (oEvent) { var oSelectedItem = oEvent.getParameter("selectedItem"); oGenericTileData.headerImage = oSelectedItem.getKey(); oGenericTileModel.checkUpdate(); }, items: [new sap.ui.core.Item("picture-item-1", { key: "", text: "No picture" }), new sap.ui.core.Item("picture-item-2", { key: "images/grass.jpg", text: "Image1" }), new sap.ui.core.Item("picture-item-3", { key: "images/headerImg1.png", text: "Image2" }), new sap.ui.core.Item("picture-item-4", { key: "images/headerImg2.jpg", text: "Image3" }), new sap.ui.core.Item("picture-item-5", { key: "sap-icon://world", text: "Icon1" }), new sap.ui.core.Item("picture-item-6", { key: "sap-icon://customer-financial-fact-sheet", text: "Icon2" })], selectedItem: "picture-item-1" }); var oImageDescLbl = new sap.m.Label({ text: "Image Description", labelFor: "imageDesc" }); var oImageDescInput = new sap.m.TextArea("imageDesc", { rows: 1, placeholder: '', value: "{/imageDescription}" }); var oStateLabel = new sap.m.Label({ text: "State", labelFor: "loading-state" }); var oStateSelect = new sap.m.Select("loading-state", { items: { path: "/states", template: new sap.ui.core.Item({ key: "{}", text: "{}" }) }, selectedKey: "{/state}" }); var oScopeLabel = new sap.m.Label({ text: "Scope", labelFor: "scope" }); var oScopeSelect = new sap.m.Select({ items: { path: "/scopes", template: new sap.ui.core.Item({ key: "{}", text: "{}" }) }, selectedKey: "{/scope}" }); var oPressLbl = new sap.m.Label({ text: "Press Action", labelFor: "press-action" }); var oPressSwtch = new sap.m.Switch({ id: "press-action", state: true, change: function (oEvent) { var bState = oEvent.getParameter("state"); if (bState) { oGenericTile1.attachPress(fnPress); oGenericTile2.attachPress(fnPress); // oGenericTile3.attachPress(fnPress); } else { oGenericTile1.detachPress(fnPress); oGenericTile2.detachPress(fnPress); // oGenericTile3.detachPress(fnPress); } } }); var oIndicatorLabel = new sap.m.Label({ id: "indicator-label", text: "Indicator" }); var oIndicatorSelect = new sap.m.Select({ items: { path: "/indicators", template: new sap.ui.core.Item({ key: "{}", text: "{}" }) }, selectedKey: "{/indicator}" }); var oFailedLabel = new sap.m.Label({ text: "Failed Text", labelFor: "failed-text" }); var oFailedInput = new sap.m.Input("failed-text", { type: sap.m.InputType.Text, placeholder: 'Enter failed message...' }); oFailedInput.bindValue("/failedText"); var oSizeLbl = new sap.m.Label({ text: "Size", labelFor: "size-button" }); var bBtnEnabled = (window.innerWidth < 375) ? false : true; var oSizeBtn = new sap.m.Button("size-button", { press: function (oEvent) { var sTheme = sap.ui.getCore().getConfiguration().getTheme(); sap.ui.getCore().applyTheme(sTheme); var url = window.location.href; window.open(url, "", "height=900,width=370,top=0,left=0,toolbar=no,menubar=no"); }, enabled: bBtnEnabled, text: "Open new page with small screen size", width: "300px" }); var oControlForm = new sap.ui.layout.Grid("numeric-content-form", { defaultSpan: "XL4 L4 M6 S12", content: [oGenericTile1, oGenericTile2, oGenericTile3, oGenericTile4, oGenericTile5] }); var editableSimpleForm = new sap.ui.layout.form.SimpleForm("controls", { maxContainerCols: 2, editable: true, content: [new sap.ui.core.Title({ // this starts a new group text: "Modify Tile" // }), oModeLabel, oModeSelect, oTitleLbl, oTitleInput, oTitleDscr, oDescInput, oTitleFoot, oFooterInputNum, oFooterInputComp, oTooltipLbl, oTooltipInput, oUpdateValueLbl, oUpdateValueInput, oTitleUnit, // oUnitInput, oFailedLabel, oFailedInput, oFrameTypeLabel, oFrameTypeSelect, oPictureLbl, oPictureSlct,oImageDescLbl, oImageDescInput, oStateLabel, oStateSelect, oScopeLabel, oScopeSelect, oPressLbl, // oPressSwtch, oIndicatorLabel, oIndicatorSelect, oSizeLbl, oSizeBtn] }), oWidthLabel, oWidthSlider, oLanguageLabel, oUpdateLanguageSelect, oUpdateValueLbl, oUpdateValueInput, oUpdateScaleLbl, oUpdateScaleInput, oUpdatePaddingLbl, oUpdatePaddingCheckbox] }); var oPage = new sap.m.Page("initial-page", { showHeader: false, content: [oControlForm, editableSimpleForm] }); oPage.setModel(oGenericTileModel); //create a mobile App embedding the page and place the App into the HTML document var app = new sap.m.App("myApp", { pages: [oPage] }).placeAt("content"); </script> </head> <body id="body" class="sapUiBody"> <div id="content"></div> </body> </html>
{ "content_hash": "8dc4622b733d74f068f52a7f883d061b", "timestamp": "", "source": "github", "line_count": 631, "max_line_length": 220, "avg_line_length": 34.59904912836767, "alnum_prop": 0.4844723341883474, "repo_name": "openui5/packaged-sap.m", "id": "8a1b4b5ede577fbe0a782e91d5693eb5e64794d2", "size": "21832", "binary": false, "copies": "1", "ref": "refs/heads/rel-1.44", "path": "test-resources/sap/m/GenericTileContentLanguage.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2610355" }, { "name": "Gherkin", "bytes": "1908" }, { "name": "HTML", "bytes": "6081296" }, { "name": "JavaScript", "bytes": "7202501" } ], "symlink_target": "" }
from datetime import datetime from channels.message import Message from ..models import Room def user_join(message, **kwargs): # type: (Message, dict) """ Handles a user joining a room :param message: The websocket message :param kwargs: Route kwargs :return: """ room = Room.objects.get(slug=message.content.pop('slug')) username = message.content.pop('username') room.add_member( username=username, reply_channel_name=message.content.pop('reply_channel_name') ) room.emit( event='user-join', data={ 'members': room.members(), 'username': username, } ) def user_leave(message, **kwargs): # type: (Message, dict) """ Handles when a user leaves the room """ room = Room.objects.get(slug=message.content.pop('slug')) left_member = room.remove_member(reply_channel_name=message.reply_channel.name) # Send the user_leave message to the members in the room room.emit( event='user-leave', data={ 'members': room.members(), 'username': left_member.username }) def client_send(message, **kwargs): # type: (Message, dict) """ Handles when the client sends a message """ room = Room.objects.get(slug=message.content.pop('slug')) # Send the new message to the room room.emit( event='message-new', data={ 'msg': message.content['msg'], 'username': message.content['username'], 'time': datetime.now().strftime('%I:%M:%S %p') })
{ "content_hash": "8f6dc2334af9c50c5c20419f9386255f", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 83, "avg_line_length": 27.11864406779661, "alnum_prop": 0.594375, "repo_name": "k-pramod/channel.js", "id": "e2a3ff87da7cb3977afa79f102a668b09da9abbf", "size": "1600", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/chatter/chat/consumers/events.py", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "15910" } ], "symlink_target": "" }
#ifndef XCAM_AIQ_UTILS_H #define XCAM_AIQ_UTILS_H #include "xcam_utils.h" #include "x3a_result.h" #include <base/xcam_3a_stats.h> #include <linux/atomisp.h> namespace XCam { bool translate_3a_stats (XCam3AStats *from, struct atomisp_3a_statistics *to); uint32_t translate_3a_results_to_xcam (XCam::X3aResultList &list, XCam3aResultHead *results[], uint32_t max_count); void free_3a_result (XCam3aResultHead *result); } #endif //XCAM_AIQ_UTILS_H
{ "content_hash": "7eb2807637dfd4805721c9392dd24315", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 88, "avg_line_length": 23.428571428571427, "alnum_prop": 0.6829268292682927, "repo_name": "dspmeng/libxcam", "id": "21d23a2af1380781e507c8b449eea75c45b2df44", "size": "1225", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcore/aiq3a_utils.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "208183" }, { "name": "C++", "bytes": "940344" }, { "name": "Shell", "bytes": "600" } ], "symlink_target": "" }
```js { type: Phrase | String, props: Object<Any>, children: Array<Element> } ``` ## `Phrase` ```js { defaultProps?: Object<Any>, filterResult?: (result: Any, element: Element) => Boolean, mapResult?: (result: Any, element: Element) => Any, describe?: (element: Element) => Element, visit?: (option: Option, element: Element) => Iterable<Option> } ``` `Phrase`s must have either a `describe` or a `visit` function. ## `Option` An object representing the current state of parse tree traversal. Each phrase in the tree will create a new `Option` based upon the `Option` passed to it. Phrases may add properties when traversing the tree. They should remove them when their traverse is outbound, so as not to pollute the object. Ensure that these properties are unique to avoid name conflicts. You must not mutate this object. ```js { text: String, words: Array<Word>, result: Any, score: Number, qualifiers: Array<String> } ``` ## `Word` ```js { text: String, input: Boolean, argument?: String, placeholder?: Boolean, category?: String } ```
{ "content_hash": "2622aa46683a3f8c7d885f48caf02a83", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 71, "avg_line_length": 19.727272727272727, "alnum_prop": 0.6847926267281106, "repo_name": "lacona/lacona", "id": "74b14f5808204db477d840c1d11f8c95795056c4", "size": "1108", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/apireference/types.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "114324" } ], "symlink_target": "" }
<?php namespace selective\ORM\Tests\Mocks; class PDO extends \PDO { public $lastInsertId = 0; public function __construct() { } public function prepare($statement, $options = null) { return new PDOStatement($statement, $this); } public function lastInsertId($seqname = null) { return $this->lastInsertId; } }
{ "content_hash": "51cd7b30f65aa6b731cfefb4c4587fc3", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 56, "avg_line_length": 17.523809523809526, "alnum_prop": 0.6195652173913043, "repo_name": "jamend/selective-orm", "id": "77d55cbd633be44a0ba0a5eeae8c9b2526f8edb9", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/selective/ORM/Tests/Mocks/PDO.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "150456" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ramsey: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.0 / ramsey - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ramsey <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-02-22 04:40:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-22 04:40:42 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.11 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.8.0 Formal proof management system. num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/ramsey&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Ramsey&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: dimension one Ramsey theorem&quot; &quot;keyword: constructive mathematics&quot; &quot;keyword: almost full sets&quot; &quot;category: Mathematics/Logic/See also&quot; &quot;category: Mathematics/Combinatorics and Graph Theory&quot; &quot;category: Miscellaneous/Extracted Programs/Combinatorics&quot; ] authors: [ &quot;Marc Bezem&quot; ] bug-reports: &quot;https://github.com/coq-contribs/ramsey/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/ramsey.git&quot; synopsis: &quot;Ramsey Theory&quot; description: &quot;&quot;&quot; For dimension one, the Infinite Ramsey Theorem states that, for any subset A of the natural numbers nat, either A or nat\\A is infinite. This special case of the Pigeon Hole Principle is classically equivalent to: if A and B are both co-finite, then so is their intersection. None of these principles is constructively valid. In [VB] the notion of an almost full set is introduced, classically equivalent to co-finiteness, for which closure under finite intersection can be proved constructively. A is almost full if for every (strictly) increasing sequence f: nat -&gt; nat there exists an x in nat such that f(x) in A. The notion of almost full and its closure under finite intersection are generalized to all finite dimensions, yielding constructive Ramsey Theorems. The proofs for dimension two and higher essentially use Brouwer&#39;s Bar Theorem. In the proof development below we strengthen the notion of almost full for dimension one in the following sense. A: nat -&gt; Prop is called Y-full if for every (strictly) increasing sequence f: nat -&gt; nat we have (A (f (Y f))). Here of course Y : (nat -&gt; nat) -&gt; nat. Given YA-full A and YB-full B we construct X from YA and YB such that the intersection of A and B is X-full. This is essentially [VB, Th. 5.4], but now it can be done without using axioms, using only inductive types. The generalization to higher dimensions will be much more difficult and is not pursued here.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/ramsey/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=40f729767b3187f93b74a90aac4da5b4&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ramsey.8.9.0 coq.8.8.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0). The following dependencies couldn&#39;t be met: - coq-ramsey -&gt; coq &gt;= 8.9 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ramsey.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "aca909675ac23e547fc81d60909ee107", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 157, "avg_line_length": 42.8041237113402, "alnum_prop": 0.581888246628131, "repo_name": "coq-bench/coq-bench.github.io", "id": "5d094cd1c1895b085401b94db6365ecb5f781c7f", "size": "8306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.0-2.0.5/released/8.8.0/ramsey/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php /* * esta clase es el validador del custom fiel type que reemplaza a los campos booleanos */ namespace Fd\EstablecimientoBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; /** * @Annotation */ class Sinosd extends Constraint { public $message = 'El valor "%string%" seleccionado es inválido'; public function validatedBy() { return 'si_no_sd_validator'; } }
{ "content_hash": "4cfc4b889d33cc951a28dbd7bf68d930", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 19, "alnum_prop": 0.7057416267942583, "repo_name": "mprizmic/fd_c", "id": "4951aa380a83cc6053b6bd1bd38320322db238e4", "size": "419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Fd/EstablecimientoBundle/Validator/Constraints/Sinosd.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16963" }, { "name": "HTML", "bytes": "416754" }, { "name": "JavaScript", "bytes": "4817" }, { "name": "PHP", "bytes": "1671335" }, { "name": "Shell", "bytes": "2414" } ], "symlink_target": "" }
import sbt._ import com.twitter.sbt._ import sbt.Keys._ import sbtassembly.Plugin._ import AssemblyKeys._ import java.io.File object Zipkin extends Build { val CASSIE_VERSION = "0.23.0" val FINAGLE_VERSION = "5.3.5" val OSTRICH_VERSION = "8.2.3" val UTIL_VERSION = "5.3.6" val proxyRepo = Option(System.getenv("SBT_PROXY_REPO")) val travisCi = Option(System.getenv("SBT_TRAVIS_CI")) // for adding travis ci maven repos before others lazy val testDependencies = Seq( "org.scala-tools.testing" % "specs_2.9.1" % "1.6.9" % "test", "org.jmock" % "jmock" % "2.4.0" % "test", "org.hamcrest" % "hamcrest-all" % "1.1" % "test", "cglib" % "cglib" % "2.2.2" % "test", "asm" % "asm" % "1.5.3" % "test", "org.objenesis" % "objenesis" % "1.1" % "test" ) lazy val zipkin = Project( id = "zipkin", base = file(".") ) aggregate(hadoop, hadoopjobrunner, test, thrift, queryCore, queryService, common, scrooge, collectorScribe, web, cassandra, collectorCore, collectorService, kafka) lazy val hadoop = Project( id = "zipkin-hadoop", base = file("zipkin-hadoop"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ assemblySettings ++ TravisCiRepos.newSettings).settings( name := "zipkin-hadoop", version := "0.3.0-SNAPSHOT", parallelExecution in Test := false, libraryDependencies ++= Seq( "com.twitter" % "scalding_2.9.1" % "0.5.3", /* FIXME ElephantBird 3.0.0 picks up libthrift 0.7.0, which is currently incompatible with sbt-thrift so made these intransitive */ "com.twitter.elephantbird" % "elephant-bird-cascading2" % "3.0.0" intransitive(), "com.twitter.elephantbird" % "elephant-bird-core" % "3.0.0" intransitive(), "org.slf4j" % "slf4j-log4j12" % "1.6.4" % "runtime", "com.google.protobuf" % "protobuf-java" % "2.3.0", "org.apache.thrift" % "libthrift" % "0.5.0", "cascading" % "cascading-hadoop" % "2.0.0-wip-288", /* Test dependencies */ "org.scala-tools.testing" % "specs_2.9.1" % "1.6.9" % "test" ), resolvers ++= (proxyRepo match { case None => Seq( "elephant-bird repo" at "http://oss.sonatype.org/content/repositories/comtwitter-286", "Concurrent Maven Repo" at "http://conjars.org/repo") case Some(pr) => Seq() // if proxy is set we assume that it has the artifacts we would get from the above repo }), mainClass in assembly := Some("com.twitter.scalding.Tool"), ivyXML := // slim down the jar <dependencies> <exclude module="jms"/> <exclude module="jmxri"/> <exclude module="jmxtools"/> <exclude org="com.sun.jdmk"/> <exclude org="com.sun.jmx"/> <exclude org="javax.jms"/> <exclude org="org.mortbay.jetty"/> </dependencies>, mergeStrategy in assembly := { case inf if inf.startsWith("META-INF/") || inf.startsWith("project.clj") => MergeStrategy.discard case _ => MergeStrategy.deduplicate } ).dependsOn(thrift) lazy val hadoopjobrunner = Project( id = "zipkin-hadoop-job-runner", base = file("zipkin-hadoop-job-runner"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ assemblySettings ++ TravisCiRepos.newSettings).settings( name := "zipkin-hadoop-job-runner", version := "0.3.0-SNAPSHOT", parallelExecution in Test := false, libraryDependencies ++= Seq( "org.slf4j" % "slf4j-log4j12" % "1.6.4" % "runtime", "javax.mail" % "mail" % "1.4.3", "com.github.spullara.mustache.java" % "compiler" % "0.8.2", "com.twitter" % "util-core" % UTIL_VERSION, "com.twitter" % "util-logging" % UTIL_VERSION, /* Test dependencies */ "org.scala-tools.testing" % "specs_2.9.1" % "1.6.9" % "test" ), mergeStrategy in assembly := { case inf if inf.startsWith("META-INF/") || inf.startsWith("project.clj") => MergeStrategy.discard case _ => MergeStrategy.deduplicate } ).dependsOn(thrift) lazy val test = Project( id = "zipkin-test", base = file("zipkin-test"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ CompileThrift.newSettings ++ TravisCiRepos.newSettings).settings( name := "zipkin-test", version := "0.3.0-SNAPSHOT", libraryDependencies ++= testDependencies ) dependsOn(queryService, collectorService) lazy val thrift = Project( id = "zipkin-thrift", base = file("zipkin-thrift"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ CompileThrift.newSettings ++ TravisCiRepos.newSettings).settings( name := "zipkin-thrift", version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "org.apache.thrift" % "libthrift" % "0.5.0", "org.slf4j" % "slf4j-api" % "1.5.8" ), sources in (Compile, doc) ~= (_ filter (_.getName contains "src_managed")) ) lazy val common = Project( id = "zipkin-common", base = file("zipkin-common"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "com.twitter" % "finagle-ostrich4" % FINAGLE_VERSION, "com.twitter" % "finagle-thrift" % FINAGLE_VERSION, "com.twitter" % "finagle-zipkin" % FINAGLE_VERSION, "com.twitter" % "ostrich" % OSTRICH_VERSION, "com.twitter" % "util-core" % UTIL_VERSION, "com.twitter.common.zookeeper" % "client" % "0.0.6" ) ++ testDependencies ) lazy val scrooge = Project( id = "zipkin-scrooge", base = file("zipkin-scrooge"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ CompileThriftScrooge.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "com.twitter" % "finagle-ostrich4" % FINAGLE_VERSION, "com.twitter" % "finagle-thrift" % FINAGLE_VERSION, "com.twitter" % "finagle-zipkin" % FINAGLE_VERSION, "com.twitter" % "ostrich" % OSTRICH_VERSION, "com.twitter" % "util-core" % UTIL_VERSION, /* FIXME Scrooge 3.0.0 picks up libthrift 0.8.0, which is currently incompatible with cassie 0.21.5 so made these intransitive */ "com.twitter" % "scrooge" % "3.0.1" intransitive(), "com.twitter" % "scrooge-runtime_2.9.2" % "3.0.1" intransitive() ) ++ testDependencies, CompileThriftScrooge.scroogeVersion := "3.0.1" ).dependsOn(common) lazy val collectorCore = Project( id = "zipkin-collector-core", base = file("zipkin-collector-core"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "com.twitter" % "finagle-ostrich4" % FINAGLE_VERSION, "com.twitter" % "finagle-serversets"% FINAGLE_VERSION, "com.twitter" % "finagle-thrift" % FINAGLE_VERSION, "com.twitter" % "finagle-zipkin" % FINAGLE_VERSION, "com.twitter" % "ostrich" % OSTRICH_VERSION, "com.twitter" % "util-core" % UTIL_VERSION, "com.twitter" % "util-zk" % UTIL_VERSION, "com.twitter" % "util-zk-common" % UTIL_VERSION, "com.twitter.common.zookeeper" % "candidate" % "0.0.9", "com.twitter.common.zookeeper" % "group" % "0.0.9" ) ++ testDependencies ).dependsOn(common, scrooge) lazy val cassandra = Project( id = "zipkin-cassandra", base = file("zipkin-cassandra"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "com.twitter" % "cassie-core" % CASSIE_VERSION, "com.twitter" % "cassie-serversets" % CASSIE_VERSION, "com.twitter" % "util-logging" % UTIL_VERSION, "org.iq80.snappy" % "snappy" % "0.1" ) ++ testDependencies, /* Add configs to resource path for ConfigSpec */ unmanagedResourceDirectories in Test <<= baseDirectory { base => (base / "config" +++ base / "src" / "test" / "resources").get } ).dependsOn(scrooge) lazy val queryCore = Project( id = "zipkin-query-core", base = file("zipkin-query-core"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "com.twitter" % "finagle-ostrich4" % FINAGLE_VERSION, "com.twitter" % "finagle-serversets"% FINAGLE_VERSION, "com.twitter" % "finagle-thrift" % FINAGLE_VERSION, "com.twitter" % "finagle-zipkin" % FINAGLE_VERSION, "com.twitter" % "ostrich" % OSTRICH_VERSION, "com.twitter" % "util-core" % UTIL_VERSION, "com.twitter" % "util-zk" % UTIL_VERSION, "com.twitter" % "util-zk-common" % UTIL_VERSION, "com.twitter.common.zookeeper" % "candidate" % "0.0.9", "com.twitter.common.zookeeper" % "group" % "0.0.9" ) ++ testDependencies ).dependsOn(common, scrooge) lazy val queryService = Project( id = "zipkin-query-service", base = file("zipkin-query-service"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= testDependencies, PackageDist.packageDistZipName := "zipkin-query-service.zip", BuildProperties.buildPropertiesPackage := "com.twitter.zipkin", /* Add configs to resource path for ConfigSpec */ unmanagedResourceDirectories in Test <<= baseDirectory { base => (base / "config" +++ base / "src" / "test" / "resources").get } ).dependsOn(queryCore, cassandra) lazy val collectorScribe = Project( id = "zipkin-collector-scribe", base = file("zipkin-collector-scribe"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= testDependencies ).dependsOn(collectorCore, scrooge) lazy val kafka = Project( id = "zipkin-kafka", base = file("zipkin-kafka"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= Seq( "org.clojars.jasonjckn" % "kafka_2.9.1" % "0.7.0" ) ++ testDependencies, resolvers ++= (proxyRepo match { case None => Seq( "clojars" at "http://clojars.org/repo") case Some(pr) => Seq() // if proxy is set we assume that it has the artifacts we would get from the above repo }) ).dependsOn(collectorCore, scrooge) lazy val collectorService = Project( id = "zipkin-collector-service", base = file("zipkin-collector-service"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ SubversionPublisher.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", libraryDependencies ++= testDependencies, PackageDist.packageDistZipName := "zipkin-collector-service.zip", BuildProperties.buildPropertiesPackage := "com.twitter.zipkin", /* Add configs to resource path for ConfigSpec */ unmanagedResourceDirectories in Test <<= baseDirectory { base => (base / "config" +++ base / "src" / "test" / "resources").get } ).dependsOn(collectorCore, collectorScribe, cassandra, kafka) lazy val web = Project( id = "zipkin-finatra", base = file("zipkin-finatra"), settings = Project.defaultSettings ++ StandardProject.newSettings ++ TravisCiRepos.newSettings ).settings( version := "0.3.0-SNAPSHOT", resolvers += "finatra" at "http://repo.juliocapote.com", resolvers += "codahale" at "http://repo.codahale.com", libraryDependencies ++= Seq( "com.twitter" % "finatra" % "0.2.4", "com.twitter.common.zookeeper" % "server-set" % "1.0.7", "com.twitter" % "finagle-serversets" % FINAGLE_VERSION, "com.twitter" % "finagle-zipkin" % FINAGLE_VERSION ) ++ testDependencies, PackageDist.packageDistZipName := "zipkin-finatra.zip", BuildProperties.buildPropertiesPackage := "com.twitter.zipkin", /* Add configs to resource path for ConfigSpec */ unmanagedResourceDirectories in Test <<= baseDirectory { base => (base / "config" +++ base / "src" / "test" / "resources").get } ).dependsOn(common, scrooge) } /* * We build our project using Travis CI. In order for it to finish in the max run time, * we need to use their local maven mirrors. */ object TravisCiRepos extends Plugin with Environmentalist { val travisCiResolvers = SettingKey[Seq[Resolver]]( "travisci-central", "Use these resolvers when building on travis-ci" ) val localRepo = SettingKey[File]( "local-repo", "local folder to use as a repo (and where publish-local publishes to)" ) val newSettings = Seq( travisCiResolvers := Seq( "travisci-central" at "http://maven.travis-ci.org/nexus/content/repositories/central/", "travisci-sonatype" at "http://maven.travis-ci.org/nexus/content/repositories/sonatype/" ), // configure resolvers for the build resolvers <<= (resolvers, travisCiResolvers) { (resolvers, travisCiResolvers) => if("true".equalsIgnoreCase(System.getenv("SBT_TRAVIS_CI"))) { travisCiResolvers ++ resolvers } else { resolvers } }, // don't add any special resolvers. externalResolvers <<= (resolvers) map identity ) }
{ "content_hash": "ff11e8ad7223c8c05978f1a92ae4688d", "timestamp": "", "source": "github", "line_count": 407, "max_line_length": 169, "avg_line_length": 36.62899262899263, "alnum_prop": 0.6100751274483499, "repo_name": "viktortnk/zipkin", "id": "436e82516e37098f38467eba025f36088571af87", "size": "14908", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "project/Project.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "438115" }, { "name": "Ruby", "bytes": "40660" }, { "name": "Scala", "bytes": "555359" }, { "name": "Shell", "bytes": "1943" } ], "symlink_target": "" }
@interface KFDataTableViewDataSource () @end @implementation KFDataTableViewDataSource - (instancetype)initWithTableView:(UITableView *)tableView fetchedResultsController:(NSFetchedResultsController *)fetchedResultsController { NSParameterAssert(tableView != nil); NSParameterAssert(fetchedResultsController != nil); if (self = [super init]) { _tableView = tableView; tableView.dataSource = self; _fetchedResultsController = fetchedResultsController; _fetchedResultsController.delegate = self; } return self; } - (instancetype)initWithTableView:(UITableView *)tableView managedObjectContext:(NSManagedObjectContext *)managedObjectContext fetchRequest:(NSFetchRequest *)fetchRequest sectionNameKeyPath:(NSString *)sectionNameKeyPath cacheName:(NSString *)cacheName { NSParameterAssert(managedObjectContext != nil); NSParameterAssert(fetchRequest != nil); NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionNameKeyPath cacheName:cacheName]; return [self initWithTableView:tableView fetchedResultsController:fetchedResultsController]; } - (instancetype)initWithTableView:(UITableView *)tableView objectManager:(KFObjectManager *)objectManager sectionNameKeyPath:(NSString *)sectionNameKeyPath cacheName:(NSString *)cacheName { NSParameterAssert(objectManager != nil); return [self initWithTableView:tableView managedObjectContext:objectManager.managedObjectContext fetchRequest:[objectManager fetchRequest] sectionNameKeyPath:sectionNameKeyPath cacheName:cacheName]; } - (NSManagedObjectContext *)managedObjectContext { return [_fetchedResultsController managedObjectContext]; } - (NSFetchRequest *)fetchRequest { return [_fetchedResultsController fetchRequest]; } - (BOOL)performFetch:(NSError **)error { BOOL result = [self.fetchedResultsController performFetch:error]; [self.tableView reloadData]; return result; } #pragma mark - - (id <NSFetchedResultsSectionInfo>)sectionInfoForSection:(NSUInteger)section { return self.fetchedResultsController.sections[section]; } - (id <NSObject>)objectAtIndexPath:(NSIndexPath *)indexPath { return [self sectionInfoForSection:indexPath.section].objects[indexPath.row]; } #pragma mark - NSFetchedResultsControllerDelegate - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:sectionIndex]; switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: { [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; break; } case NSFetchedResultsChangeMove: [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } #pragma mark - UITableViewDataSource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSUInteger count = [self.fetchedResultsController.sections count]; return (NSInteger)count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> sectionInfo = [self sectionInfoForSection:section]; return (NSInteger)sectionInfo.numberOfObjects; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *reason = [NSStringFromClass([self class]) stringByAppendingString:@" : You must override tableView:cellForRowAtIndexpath:"]; @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:reason userInfo:nil]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [[self sectionInfoForSection:section] name]; } - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { return nil; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { switch (editingStyle) { case UITableViewCellEditingStyleDelete: { NSManagedObject *managedObject = [self objectAtIndexPath:indexPath]; [self.managedObjectContext deleteObject:managedObject]; NSError *error; if ([self.managedObjectContext save:&error] == NO) { NSLog(@"%@: Failed to save managed object context after deleting %@", NSStringFromClass([self class]), error); } break; } case UITableViewCellEditingStyleInsert: break; case UITableViewCellEditingStyleNone: break; } } // Index //- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { // NSArray *sectionIndexTitles = [[[self fetchedResultsController] sections] valueForKeyPath:@"indexTitle"]; // return sectionIndexTitles; //} // //- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { // return index; //} //- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath; //- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath; //- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath; @end #endif
{ "content_hash": "eb2dfe2626d441f7d7a5c167287a068c", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 230, "avg_line_length": 38.043243243243246, "alnum_prop": 0.7499289570900824, "repo_name": "QueryKit/TodoExample", "id": "0dc999cbe8e441ea6204ad247797a3882158c105", "size": "7248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/KFData/KFData/UI/KFDataTableViewDataSource.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Makefile", "bytes": "117" }, { "name": "Ruby", "bytes": "162" }, { "name": "Swift", "bytes": "5649" } ], "symlink_target": "" }
package dotty.tools.dotc.util import scala.collection.mutable.ArrayBuffer import scala.util.chaining._ import language.experimental.pureFunctions /** A wrapper for a list of cached instances of a type `T`. * The wrapper is recursion-reentrant: several instances are kept, so * at each depth of reentrance we are reusing the instance for that. * * An instance is created upon creating this object, and more instances * are allocated dynamically, on demand, when reentrance occurs. * * Not thread safe. * * Ported from scala.reflect.internal.util.ReusableInstance */ final class ReusableInstance[T <: AnyRef] private (make: -> T) { private[this] val cache = new ArrayBuffer[T](ReusableInstance.InitialSize).tap(_.addOne(make)) private[this] var taken = 0 inline def withInstance[R](action: T => R): R ={ if (taken == cache.size) cache += make taken += 1 try action(cache(taken-1)) finally taken -= 1 } } object ReusableInstance { private inline val InitialSize = 4 def apply[T <: AnyRef](make: -> T): ReusableInstance[T] = new ReusableInstance[T](make) }
{ "content_hash": "be452dddc090b16297070a953e3da8e9", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 96, "avg_line_length": 32.588235294117645, "alnum_prop": 0.7138989169675091, "repo_name": "lampepfl/dotty", "id": "75addc916b780eb887acd36bfa7ae9bf17e565f6", "size": "1108", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tests/pos-with-compiler-cc/dotc/util/ReusableInstance.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "836" }, { "name": "CSS", "bytes": "136099" }, { "name": "HTML", "bytes": "2829" }, { "name": "Java", "bytes": "238326" }, { "name": "JavaScript", "bytes": "153556" }, { "name": "Scala", "bytes": "24095901" }, { "name": "Shell", "bytes": "23566" }, { "name": "TypeScript", "bytes": "8378" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RobotsFactory.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RobotsFactory.Data")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c71efd50-50f7-46bb-856e-9a4c54d6f404")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "e708c3bd8c72e3557705b21122948b54", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 39.142857142857146, "alnum_prop": 0.7423357664233576, "repo_name": "Team-Zealot-Databases/Databases-Teamwork-2014", "id": "ce6544b7f1b5b9647028fcbca87b3faa250e39bf", "size": "1373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RobotsFactory/RobotsFactory.Data/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "105650" } ], "symlink_target": "" }