text
stringlengths
2
1.04M
meta
dict
Usage: ``` Javascript var conf = require('./config'); var passport = require('passport'); var CoggleBearerStrategy = require('coggle-auth-bearer').Strategy; var User = require('./models/User'); passport.use(new CoggleBearerStrategy({}, function(profile, done) { done(false, new User(profile)); } )); ```
{ "content_hash": "d84c56db9133b087e7f6e6bfd4f73e3f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 66, "avg_line_length": 22.357142857142858, "alnum_prop": 0.6869009584664537, "repo_name": "Coggle/passport-coggle-bearer", "id": "14ecb4e4c47488795d3c1a41b9cfdb6946ac1f9d", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1786" } ], "symlink_target": "" }
namespace calcc { namespace parser { //! Parse the file from istream:sin ast::Expr *parse(std::istream &sin); } } #endif //CALCCOMPILER_PARSER_H
{ "content_hash": "086dd7d5514e9f702cb06689219f1053", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 40, "avg_line_length": 19.75, "alnum_prop": 0.6582278481012658, "repo_name": "ztuowen/calc-compiler", "id": "48c566421decb3716596ab3d981fc05d0c1757f9", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/calcc/parser.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "641" }, { "name": "C++", "bytes": "42704" }, { "name": "CMake", "bytes": "1449" }, { "name": "LLVM", "bytes": "10360580" }, { "name": "Perl", "bytes": "3638" } ], "symlink_target": "" }
public class Driver { @SuppressWarnings("unused") public static void main(String[] args) { final int width = 425; final int height = 325; Gui driver = new Gui(width, height); } }
{ "content_hash": "7fbc27d3eb845533cc68e65897faa934", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 41, "avg_line_length": 21.11111111111111, "alnum_prop": 0.6736842105263158, "repo_name": "Mobliz640/DAoC-Auto-Twister", "id": "2e0d7422db33c40a451498e8ab257a3b12a1100d", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Driver.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "Java", "bytes": "20274" } ], "symlink_target": "" }
/*jshint node:true,forin:false,strict:false*/ /*global suite,test,suiteSetup,suiteTeardown,setup,teardown*/ var assert = require('chai').assert; var gulpPkgs = require('../gulp-packages'); suite('gulp-packages', function () { suiteSetup(function () { this.dummyGulp = { task: function () {} }; this.pkg = gulpPkgs(this.dummyGulp, [ 'uglify', 'minify-css', 'html-minifier as minHtm', 'taskListing as help', 'xxx' ]); }); suiteTeardown(function () { }); setup(function () { }); teardown(function () { }); test('converted package names', function () { assert.deepEqual(Object.keys(this.pkg), [ 'uglify', 'minifyCss', 'minHtm', 'help' ]); }); test('loaded object is function', function () { for (var p in this.pkg) { assert.isFunction(this.pkg[p], p); } }); test('loaded function: uglify', function () { assert.isTrue(this.pkg.uglify.toString().indexOf('uglify') !== -1); }); test('loaded function: minify-css', function () { assert.isTrue(this.pkg.minifyCss.toString().indexOf('minifyCSS') !== -1); }); test('loaded function: minHtm', function () { assert.isTrue(this.pkg.minHtm.toString().indexOf('gulp-htmlmin') !== -1); }); test('loaded function: help', function () { assert.isTrue(this.pkg.help.toString().indexOf('Main Tasks') !== -1); }); });
{ "content_hash": "eca0c9e456846f4327e0f2a547365341", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 77, "avg_line_length": 25.418181818181818, "alnum_prop": 0.5987124463519313, "repo_name": "ktty1220/gulp-packages", "id": "3d5730f966615d8130999da35475e98bcbd2e30b", "size": "1398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3664" } ], "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.batchai.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.batchai.fluent.OperationsClient; import com.azure.resourcemanager.batchai.fluent.models.OperationInner; import com.azure.resourcemanager.batchai.models.OperationListResult; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in OperationsClient. */ public final class OperationsClientImpl implements OperationsClient { private final ClientLogger logger = new ClientLogger(OperationsClientImpl.class); /** The proxy service used to perform REST calls. */ private final OperationsService service; /** The service client containing this operation class. */ private final BatchAIImpl client; /** * Initializes an instance of OperationsClientImpl. * * @param client the instance of the service client containing this operation class. */ OperationsClientImpl(BatchAIImpl client) { this.service = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for BatchAIOperations to be used by the proxy service to perform REST * calls. */ @Host("{$host}") @ServiceInterface(name = "BatchAIOperations") private interface OperationsService { @Headers({"Content-Type: application/json"}) @Get("/providers/Microsoft.BatchAI/operations") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> list( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> listNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listSinglePageAsync() { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) .<PagedResponse<OperationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listSinglePageAsync(Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<OperationInner> listAsync() { return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<OperationInner> listAsync(Context context) { return new PagedFlux<>( () -> listSinglePageAsync(context), nextLink -> listNextSinglePageAsync(nextLink, context)); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationInner> list() { return new PagedIterable<>(listAsync()); } /** * Lists available operations for the Microsoft.BatchAI provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationInner> list(Context context) { return new PagedIterable<>(listAsync(context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<OperationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return contains the list of all operations supported by BatchAI resource provider. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationInner>> listNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
{ "content_hash": "3e71086180e894e0c54b60a40492b92b", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 117, "avg_line_length": 45.88104089219331, "alnum_prop": 0.6567817209528439, "repo_name": "Azure/azure-sdk-for-java", "id": "ac01be2dd9326ec8fe9e86adfd244527f54e3cbd", "size": "12342", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/batchai/azure-resourcemanager-batchai/src/main/java/com/azure/resourcemanager/batchai/implementation/OperationsClientImpl.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 rx.facebook.app; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; //import android.support.v4.app.NavUtils; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; //import android.support.v7.widget.StaggeredGridLayoutManager; //import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.os.Handler; import butterknife.ButterKnife; import butterknife.InjectView; import com.facebook.drawee.view.SimpleDraweeView; import com.sromku.simple.fb.entities.*; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.*; import rx.android.app.*; import rx.facebook.*; import android.support.v4.widget.SwipeRefreshLayout; public class MainFragment extends Fragment { @InjectView(R.id.list) RecyclerView listView; @InjectView(R.id.loading) SwipeRefreshLayout loading; private Handler handler; private SwipeRefreshLayout.OnRefreshListener refresher; private ListRecyclerAdapter<Photo, PhotoViewHolder> listAdapter; public MainFragment() { handler = new Handler(); } @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { android.util.Log.d("RxFacebook", "onCreateView"); View view = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.inject(this, view); listAdapter = ListRecyclerAdapter.create(); listAdapter.createViewHolder(new Func2<ViewGroup, Integer, PhotoViewHolder>() { @Override public PhotoViewHolder call(@Nullable ViewGroup viewGroup, Integer position) { return new PhotoViewHolder(inflater.inflate(R.layout.item_photo, viewGroup, false)); } }); listView.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity())); listView.setAdapter(listAdapter); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); refresher = new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loading.setRefreshing(true); AppObservable.bindFragment(MainFragment.this, FacebookObservable.getUploadedPhotos(getActivity())) .doOnNext(p -> { android.util.Log.d("RxFacebook", "user: " + p.getFrom().getName()); android.util.Log.d("RxFacebook", "link: " + p.getLink()); }) .toList() .subscribe(new Action1<List<Photo>>() { @Override public void call(final List<Photo> users) { loading.setRefreshing(false); handler.post(new Runnable() { @Override public void run() { listAdapter.getList().clear(); listAdapter.getList().addAll(users); listAdapter.notifyDataSetChanged(); } }); } }); } }; loading.setOnRefreshListener(refresher); handler.post(new Runnable() { @Override public void run() { refresher.onRefresh(); } }); } public static class PhotoViewHolder extends BindViewHolder<Photo> { @InjectView(R.id.icon) SimpleDraweeView icon; @InjectView(R.id.text1) TextView text1; public PhotoViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); }; @Override public void onBind(int position, Photo item) { icon.setImageURI(Uri.parse(item.getImages().get(0).getSource())); text1.setText(item.getFrom().getName()); } } }
{ "content_hash": "160efee3099971cbcc6310ef13c14c22", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 129, "avg_line_length": 33.796992481203006, "alnum_prop": 0.6026696329254727, "repo_name": "yongjhih/RxFacebook", "id": "79c6caaf4a7f25847c9f1421cece24afbf9a1de6", "size": "4495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rxfacebook-app/src/main/java/rx/facebook/app/MainFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "46494" }, { "name": "Shell", "bytes": "551" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Altair\Data\Exception; class PropertyNotFoundException extends InvalidArgumentException { }
{ "content_hash": "3831ce7af70288629b26fad27e4e9d6f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 15.222222222222221, "alnum_prop": 0.8102189781021898, "repo_name": "univeros/framework", "id": "ef74ccbdcae9e89d6c0ca9ade8ac1209ef81d42f", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Altair/Data/Exception/PropertyNotFoundException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1212922" }, { "name": "Shell", "bytes": "1537" } ], "symlink_target": "" }
package org.apache.tomcat.jdbc.pool; import java.util.Properties; public class PoolUtilities { public static final String PROP_USER = "user"; public static final String PROP_PASSWORD = "password"; public static Properties clone(Properties p) { Properties c = new Properties(); c.putAll(p); return c; } public static Properties cloneWithoutPassword(Properties p) { Properties result = clone(p); result.remove(PROP_PASSWORD); return result; } }
{ "content_hash": "c598974252392e090b913c2fdc87552e", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 65, "avg_line_length": 22.695652173913043, "alnum_prop": 0.6590038314176245, "repo_name": "plumer/codana", "id": "0da0d0b159d304395e191ea10b63322542fbdb75", "size": "1324", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "tomcat_files/8.0.21/PoolUtilities.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "101920653" }, { "name": "Python", "bytes": "58358" } ], "symlink_target": "" }
require File.expand_path('../../../../spec_helper', __FILE__) ruby_version_is "2.2" do describe "File::Stat#birthtime" do before :each do @file = tmp('i_exist') touch(@file) { |f| f.write "rubinius" } end after :each do rm_r @file end platform_is :windows, :darwin, :freebsd, :netbsd do it "returns the birthtime of a File::Stat object" do st = File.stat(@file) st.birthtime.should be_kind_of(Time) st.birthtime.should <= Time.now end end platform_is :linux, :openbsd do it "raises an NotImplementedError" do st = File.stat(@file) lambda { st.birthtime }.should raise_error(NotImplementedError) end end end end
{ "content_hash": "300212072a0689dc20894ca86f4d6a6e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 71, "avg_line_length": 25.275862068965516, "alnum_prop": 0.5948158253751705, "repo_name": "BanzaiMan/rubyspec", "id": "448fddd73dbb7ddf919e3c64fd7da3441854d2ef", "size": "733", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/file/stat/birthtime_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "184978" }, { "name": "Ruby", "bytes": "5241348" } ], "symlink_target": "" }
.PHONY: build push PREFIX=staging-k8s.gcr.io TAG = 2.1.1 BUILD_DEPS="make gcc g++ libc6-dev ruby-dev libffi-dev" build: docker build --pull -t $(PREFIX)/fluentd-gcp:$(TAG) . push: gcloud docker -- push $(PREFIX)/fluentd-gcp:$(TAG) update-dependencies: build docker run -it --name fluentd-gcp-refreeze $(PREFIX)/fluentd-gcp:$(TAG) /bin/sh -c 'clean-install "$(BUILD_DEPS)" && rm /Gemfile.lock && gem install --file Gemfile' docker cp fluentd-gcp-refreeze:/Gemfile.lock . docker rm fluentd-gcp-refreeze
{ "content_hash": "d97e357fdd976597538a2263da3883be", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 165, "avg_line_length": 28.444444444444443, "alnum_prop": 0.703125, "repo_name": "kawych/k8s-stackdriver", "id": "b918bc227cb976e2033a0fb3181bbd4c2b9104c8", "size": "1221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "archived/fluentd-gcp-image/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "9038" }, { "name": "Go", "bytes": "442098" }, { "name": "Makefile", "bytes": "7245" }, { "name": "Python", "bytes": "16013" }, { "name": "Ruby", "bytes": "4240" }, { "name": "Shell", "bytes": "14082" } ], "symlink_target": "" }
//****************************************************************************************************** // ISupportBinaryImage.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 12/04/2008 - J. Ritchie Carroll // Generated original version of source code. // 09/14/2009 - Stephen C. Wills // Added new header and license agreement. // 11/22/2011 - J. Ritchie Carroll // Converted interface to use a write based image method instead of a property as an optimization. // 12/14/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.IO; namespace GSF.Parsing { /// <summary> /// Specifies that an object can support production or consumption of a binary image that represents the object. /// </summary> public interface ISupportBinaryImage { /// <summary> /// Gets the length of the binary image. /// </summary> int BinaryLength { get; } /// <summary> /// Initializes object by parsing the specified <paramref name="buffer"/> containing a binary image. /// </summary> /// <param name="buffer">Buffer containing binary image to parse.</param> /// <param name="startIndex">0-based starting index in the <paramref name="buffer"/> to start parsing.</param> /// <param name="length">Valid number of bytes within <paramref name="buffer"/> to read from <paramref name="startIndex"/>.</param> /// <returns>The number of bytes used for initialization in the <paramref name="buffer"/> (i.e., the number of bytes parsed).</returns> /// <remarks> /// Implementers should validate <paramref name="startIndex"/> and <paramref name="length"/> against <paramref name="buffer"/> length. /// The <see cref="ArrayExtensions.ValidateParameters{T}"/> method can be used to perform this validation. /// </remarks> int ParseBinaryImage(byte[] buffer, int startIndex, int length); /// <summary> /// Generates binary image of the object and copies it into the given buffer, for <see cref="BinaryLength"/> bytes. /// </summary> /// <param name="buffer">Buffer used to hold generated binary image of the source object.</param> /// <param name="startIndex">0-based starting index in the <paramref name="buffer"/> to start writing.</param> /// <returns>The number of bytes written to the <paramref name="buffer"/>.</returns> /// <remarks> /// Implementers should validate <paramref name="startIndex"/> and <see cref="BinaryLength"/> against <paramref name="buffer"/> length. /// The <see cref="ArrayExtensions.ValidateParameters{T}"/> method can be used to perform this validation. /// </remarks> int GenerateBinaryImage(byte[] buffer, int startIndex); } /// <summary> /// Defines extension functions related to <see cref="ISupportBinaryImage"/> implementations. /// </summary> public static class ISupportBinaryImageExtensions { /// <summary> /// Returns a binary image of an object that implements <see cref="ISupportBinaryImage"/>. /// </summary> /// <param name="imageSource"><see cref="ISupportBinaryImage"/> source.</param> /// <returns>A binary image of an object that implements <see cref="ISupportBinaryImage"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="imageSource"/> cannot be null.</exception> /// <remarks> /// This is a convenience method. It is often optimal to use <see cref="ISupportBinaryImage.GenerateBinaryImage"/> /// directly using a common buffer instead of always allocating new buffers. /// </remarks> public static byte[] BinaryImage(this ISupportBinaryImage imageSource) { if ((object)imageSource == null) throw new ArgumentNullException(nameof(imageSource)); byte[] buffer = new byte[imageSource.BinaryLength]; imageSource.GenerateBinaryImage(buffer, 0); return buffer; } /// <summary> /// Copies binary image of object that implements <see cref="ISupportBinaryImage"/> to a <see cref="Stream"/>. /// </summary> /// <param name="imageSource"><see cref="ISupportBinaryImage"/> source.</param> /// <param name="stream">Destination <see cref="Stream"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="imageSource"/> cannot be null.</exception> public static void CopyBinaryImageToStream(this ISupportBinaryImage imageSource, Stream stream) { if ((object)imageSource == null) throw new ArgumentNullException(nameof(imageSource)); int length = imageSource.BinaryLength; byte[] buffer = new byte[length]; // Copy generated binary image to buffer int writeCount = imageSource.GenerateBinaryImage(buffer, 0); // Write buffer bytes to stream, if any were generated if (writeCount > 0) stream.Write(buffer, 0, writeCount); } /// <summary> /// Parses binary image of object that implements <see cref="ISupportBinaryImage"/> from a <see cref="Stream"/>. /// </summary> /// <param name="imageSource"><see cref="ISupportBinaryImage"/> source.</param> /// <param name="stream">Source <see cref="Stream"/>.</param> /// <returns>The number of bytes parsed from the <paramref name="stream"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="imageSource"/> cannot be null.</exception> public static int ParseBinaryImageFromStream(this ISupportBinaryImage imageSource, Stream stream) { if ((object)imageSource == null) throw new ArgumentNullException(nameof(imageSource)); int length = imageSource.BinaryLength; byte[] buffer = new byte[length]; // Read buffer bytes from stream int readCount = stream.Read(buffer, 0, length); // Parse binary image from buffer bytes read from stream return imageSource.ParseBinaryImage(buffer, 0, readCount); } } }
{ "content_hash": "154fbafdb79c60429337e2be4f125e6e", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 143, "avg_line_length": 50.50344827586207, "alnum_prop": 0.6213300559879831, "repo_name": "rmc00/gsf", "id": "5c0339a2af0b5ad4fe963bc401d7af9a9099b1c6", "size": "7326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Libraries/GSF.Core/Parsing/ISupportBinaryImage.cs", "mode": "33261", "license": "mit", "language": [ { "name": "ASP", "bytes": "17182" }, { "name": "Batchfile", "bytes": "8635" }, { "name": "C", "bytes": "24478" }, { "name": "C#", "bytes": "30052352" }, { "name": "C++", "bytes": "135084" }, { "name": "CMake", "bytes": "3519" }, { "name": "CSS", "bytes": "4763" }, { "name": "HTML", "bytes": "3914" }, { "name": "Java", "bytes": "955418" }, { "name": "JavaScript", "bytes": "1274735" }, { "name": "Objective-C", "bytes": "173" }, { "name": "PLSQL", "bytes": "107859" }, { "name": "PLpgSQL", "bytes": "88792" }, { "name": "Pascal", "bytes": "515" }, { "name": "SQLPL", "bytes": "186015" }, { "name": "ShaderLab", "bytes": "137" }, { "name": "Shell", "bytes": "11035" }, { "name": "Smalltalk", "bytes": "8510" }, { "name": "Visual Basic", "bytes": "72875" }, { "name": "XSLT", "bytes": "1070" } ], "symlink_target": "" }
""" DeepFool tutorial on mnist using advbox tool. Deepfool is a simple and accurate adversarial attack method. It supports both targeted attack and non-targeted attack. """ import sys sys.path.append("..") import matplotlib.pyplot as plt import paddle.fluid as fluid import paddle.v2 as paddle from advbox.adversary import Adversary from advbox.attacks.deepfool import DeepFoolAttack from advbox.models.paddle import PaddleModel from tutorials.mnist_model import mnist_cnn_model def main(): """ Advbox demo which demonstrate how to use advbox. """ TOTAL_NUM = 500 IMG_NAME = 'img' LABEL_NAME = 'label' img = fluid.layers.data(name=IMG_NAME, shape=[1, 28, 28], dtype='float32') # gradient should flow img.stop_gradient = False label = fluid.layers.data(name=LABEL_NAME, shape=[1], dtype='int64') logits = mnist_cnn_model(img) cost = fluid.layers.cross_entropy(input=logits, label=label) avg_cost = fluid.layers.mean(x=cost) # use CPU place = fluid.CPUPlace() # use GPU # place = fluid.CUDAPlace(0) exe = fluid.Executor(place) BATCH_SIZE = 1 train_reader = paddle.batch( paddle.reader.shuffle( paddle.dataset.mnist.train(), buf_size=128 * 10), batch_size=BATCH_SIZE) test_reader = paddle.batch( paddle.reader.shuffle( paddle.dataset.mnist.test(), buf_size=128 * 10), batch_size=BATCH_SIZE) fluid.io.load_params( exe, "./mnist/", main_program=fluid.default_main_program()) # advbox demo m = PaddleModel( fluid.default_main_program(), IMG_NAME, LABEL_NAME, logits.name, avg_cost.name, (-1, 1), channel_axis=1) attack = DeepFoolAttack(m) attack_config = {"iterations": 100, "overshoot": 9} # use train data to generate adversarial examples total_count = 0 fooling_count = 0 for data in train_reader(): total_count += 1 adversary = Adversary(data[0][0], data[0][1]) # DeepFool non-targeted attack adversary = attack(adversary, **attack_config) # DeepFool targeted attack # tlabel = 0 # adversary.set_target(is_targeted_attack=True, target_label=tlabel) # adversary = attack(adversary, **attack_config) if adversary.is_successful(): fooling_count += 1 print( 'attack success, original_label=%d, adversarial_label=%d, count=%d' % (data[0][1], adversary.adversarial_label, total_count)) # plt.imshow(adversary.target, cmap='Greys_r') # plt.show() # np.save('adv_img', adversary.target) else: print('attack failed, original_label=%d, count=%d' % (data[0][1], total_count)) if total_count >= TOTAL_NUM: print( "[TRAIN_DATASET]: fooling_count=%d, total_count=%d, fooling_rate=%f" % (fooling_count, total_count, float(fooling_count) / total_count)) break # use test data to generate adversarial examples total_count = 0 fooling_count = 0 for data in test_reader(): total_count += 1 adversary = Adversary(data[0][0], data[0][1]) # DeepFool non-targeted attack adversary = attack(adversary, **attack_config) # DeepFool targeted attack # tlabel = 0 # adversary.set_target(is_targeted_attack=True, target_label=tlabel) # adversary = attack(adversary, **attack_config) if adversary.is_successful(): fooling_count += 1 print( 'attack success, original_label=%d, adversarial_label=%d, count=%d' % (data[0][1], adversary.adversarial_label, total_count)) # plt.imshow(adversary.target, cmap='Greys_r') # plt.show() # np.save('adv_img', adversary.target) else: print('attack failed, original_label=%d, count=%d' % (data[0][1], total_count)) if total_count >= TOTAL_NUM: print( "[TEST_DATASET]: fooling_count=%d, total_count=%d, fooling_rate=%f" % (fooling_count, total_count, float(fooling_count) / total_count)) break print("deelfool attack done") if __name__ == '__main__': main()
{ "content_hash": "5b0ece1e4e0c9232484bf8404999d9dc", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 84, "avg_line_length": 32.175182481751825, "alnum_prop": 0.5905172413793104, "repo_name": "qingqing01/models", "id": "2b12c81945859b42809e33ccd74ead53f4d4eb05", "size": "4408", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "fluid/adversarial/tutorials/mnist_tutorial_deepfool.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "15149" }, { "name": "Python", "bytes": "1397018" }, { "name": "Shell", "bytes": "24648" } ], "symlink_target": "" }
#include <errno.h> #include <fcntl.h> /* Advice the system about the expected behaviour of the application with respect to the file associated with FD. */ int posix_fadvise64 (int fd, __off64_t offset, __off64_t len, int advise) { return ENOSYS; } stub_warning (posix_fadvise64) #include <stub-tag.h>
{ "content_hash": "b641ffe27aeaad6963ce83e2f93aecfc", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 73, "avg_line_length": 20.733333333333334, "alnum_prop": 0.7138263665594855, "repo_name": "endplay/omniplay", "id": "e7eae5e6e33740e10c5cd17eebe70aa9e59ca36d", "size": "1166", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "eglibc-2.15/io/posix_fadvise64.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "17491433" }, { "name": "Awk", "bytes": "79791" }, { "name": "Batchfile", "bytes": "903" }, { "name": "C", "bytes": "444772157" }, { "name": "C++", "bytes": "10631343" }, { "name": "GDB", "bytes": "17950" }, { "name": "HTML", "bytes": "47935" }, { "name": "Java", "bytes": "2193" }, { "name": "Lex", "bytes": "44513" }, { "name": "M4", "bytes": "9029" }, { "name": "Makefile", "bytes": "1758605" }, { "name": "Objective-C", "bytes": "5278898" }, { "name": "Perl", "bytes": "649746" }, { "name": "Perl 6", "bytes": "1101" }, { "name": "Python", "bytes": "585875" }, { "name": "RPC", "bytes": "97869" }, { "name": "Roff", "bytes": "2522798" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "426172" }, { "name": "TeX", "bytes": "283872" }, { "name": "UnrealScript", "bytes": "6143" }, { "name": "XS", "bytes": "1240" }, { "name": "Yacc", "bytes": "93190" }, { "name": "sed", "bytes": "9202" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Torreya 14:67. 1914 #### Original name null ### Remarks null
{ "content_hash": "1a3dd2566bb809a607f6bcb4ff6a4529", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.461538461538462, "alnum_prop": 0.697986577181208, "repo_name": "mdoering/backbone", "id": "21e29d7a6269de973414b84a1656cfd5770b1ff2", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Geocarpon/Geocarpon minimum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ES5Harness.registerTest({ id: "15.2.3.7-6-a-55", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-55.js", description: "Object.defineProperties - both desc.writable and P.writable are boolean values with the same value (8.12.9 step 6)", test: function testcase() { var obj = {}; var desc = { writable: false }; Object.defineProperty(obj, "foo", desc); Object.defineProperties(obj, { foo: { writable: false } }); return dataPropertyAttributesAreCorrect(obj, "foo", undefined, false, false, false); }, precondition: function prereq() { return fnExists(Object.defineProperties) && fnExists(Object.defineProperty); } });
{ "content_hash": "c4ffba90e28a01051d17519724753207", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 134, "avg_line_length": 29.23076923076923, "alnum_prop": 0.5986842105263158, "repo_name": "hnafar/IronJS", "id": "84a2172745c03eb7a6e74702bc9a85639598846a", "size": "2319", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-55.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "280" }, { "name": "C#", "bytes": "2984769" }, { "name": "CSS", "bytes": "1167" }, { "name": "F#", "bytes": "353515" }, { "name": "HTML", "bytes": "9405" }, { "name": "JavaScript", "bytes": "19853921" }, { "name": "Python", "bytes": "13630" }, { "name": "Shell", "bytes": "1454" } ], "symlink_target": "" }
import mysql.connector import send_to_db from os.path import join, dirname import json def main(config): output = [] db = mysql.connector.Connect(**config) cursor = db.cursor() stmts = ["SELECT * FROM top_cities(cities)"] with open ('top_cities.txt','w') as file: for item in suggestion_list: file.write(str(item)) file.write('\n') if __name__ == '__main__': config = { 'host': 'localhost', 'port': 3306, 'database': 'udest', 'user': 'root', 'password': '', 'charset': 'utf8', 'use_unicode': True, 'get_warnings': True, } #out = main(config) #print('\n'.join(out)) send_to_db.main(config)
{ "content_hash": "358de27d6a75497f58042177753760ca", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 48, "avg_line_length": 21.303030303030305, "alnum_prop": 0.5533428165007113, "repo_name": "jpmunic/udest", "id": "1adc6b101bcdea07ecaf652931c0c717ec2d01c4", "size": "703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/watson_receive_from_db.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "77582" }, { "name": "JavaScript", "bytes": "43347" }, { "name": "PHP", "bytes": "17162" }, { "name": "Python", "bytes": "62795" } ], "symlink_target": "" }
<?php # MantisBT - a php based bugtracking system # MantisBT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # MantisBT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * MantisBT Core API's */ require_once( 'core.php' ); /** * requires ajax_api */ require_once( 'ajax_api.php' ); /** * requires tag_api */ require_once( 'tag_api.php' ); compress_enable(); $f_tag_id = gpc_get_int( 'tag_id' ); $t_tag_row = tag_get( $f_tag_id ); $t_name = string_display_line( $t_tag_row['name'] ); $t_description = string_display( $t_tag_row['description'] ); if ( !( access_has_global_level( config_get( 'tag_edit_threshold' ) ) || ( auth_get_current_user_id() == $t_tag_row['user_id'] ) && access_has_global_level( config_get( 'tag_edit_own_threshold' ) ) ) ) { access_denied(); } html_page_top( sprintf( lang_get( 'tag_update' ), $t_name ) ); ?> <br /> <form method="post" action="tag_update.php"> <?php echo form_security_field( 'tag_update' ) ?> <table class="width100" cellspacing="1"> <!-- Title --> <tr> <td class="form-title" colspan="2"> <?php echo sprintf( lang_get( 'tag_update' ), $t_name ) ?> <input type="hidden" name="tag_id" value="<?php echo $f_tag_id ?>"/> </td> <td class="right" colspan="3"> <?php print_bracket_link( 'tag_view_page.php?tag_id='.$f_tag_id, lang_get( 'tag_update_return' ) ); ?> </td> </tr> <!-- Info --> <tr class="row-category"> <td width="15%"><?php echo lang_get( 'tag_id' ) ?></td> <td width="25%"><?php echo lang_get( 'tag_name' ) ?></td> <td width="20%"><?php echo lang_get( 'tag_creator' ) ?></td> <td width="20%"><?php echo lang_get( 'tag_created' ) ?></td> <td width="20%"><?php echo lang_get( 'tag_updated' ) ?></td> </tr> <tr <?php echo helper_alternate_class() ?>> <td><?php echo $t_tag_row['id'] ?></td> <td><input type="text" <?php echo helper_get_tab_index() ?> name="name" value="<?php echo $t_name ?>"/></td> <td><?php if ( access_has_global_level( config_get( 'tag_edit_threshold' ) ) ) { if ( ON == config_get( 'use_javascript' ) ) { $t_username = prepare_user_name( $t_tag_row['user_id'] ); echo ajax_click_to_edit( $t_username, 'user_id', 'entrypoint=user_combobox&user_id=' . $t_tag_row['user_id'] . '&access_level=' . config_get( 'tag_create_threshold' ) ); } else { echo '<select ', helper_get_tab_index(), ' name="user_id">'; print_user_option_list( $t_tag_row['user_id'], ALL_PROJECTS, config_get( 'tag_create_threshold' ) ); echo '</select>'; } } else { echo string_display_line( user_get_name($t_tag_row['user_id']) ); } ?></td> <td><?php echo date( config_get( 'normal_date_format' ), $t_tag_row['date_created'] ) ?> </td> <td><?php echo date( config_get( 'normal_date_format' ), $t_tag_row['date_updated'] ) ?> </td> </tr> <!-- spacer --> <tr class="spacer"> <td colspan="5"></td> </tr> <!-- Description --> <tr <?php echo helper_alternate_class() ?>> <td class="category"><?php echo lang_get( 'tag_description' ) ?></td> <td colspan="4"> <textarea name="description" <?php echo helper_get_tab_index() ?> cols="80" rows="6"><?php echo string_textarea( $t_description ) ?></textarea> </td> </tr> <!-- Submit Button --> <tr> <td class="center" colspan="6"> <input <?php echo helper_get_tab_index() ?> type="submit" class="button" value="<?php echo lang_get( 'tag_update_button' ) ?>" /> </td> </tr> </table> </form> <?php html_page_bottom();
{ "content_hash": "31161607d9bb8b54620a45142ebcd6b7", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 174, "avg_line_length": 32.81666666666667, "alnum_prop": 0.6163026917216862, "repo_name": "nicholasio/nicholasandre.com.br", "id": "549740ac67c76445045d665b8dd526d5eb8ad423", "size": "4095", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "mantisbt/tag_update_page.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "635" }, { "name": "CSS", "bytes": "68736" }, { "name": "HTML", "bytes": "971438" }, { "name": "JavaScript", "bytes": "32266" }, { "name": "PHP", "bytes": "12448113" }, { "name": "Shell", "bytes": "6708" }, { "name": "XSLT", "bytes": "240134" } ], "symlink_target": "" }
/* eslint-disable-next-line no-unused-expressions */ import(/* webpackChunkName: "async-1" */ './async-1.css'); /* eslint-disable-next-line no-unused-expressions */ import(/* webpackChunkName: "async-2" */ './async-2.css');
{ "content_hash": "37dd88b5a463c0aafe3817151a53c69e", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 58, "avg_line_length": 56, "alnum_prop": 0.6875, "repo_name": "faceyspacey/extract-css-chunks-webpack-plugin", "id": "3f7d88080b1332ec251dc8697c1d93a2194d871b", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/cases/composes-async/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9214" }, { "name": "HTML", "bytes": "8066" }, { "name": "JavaScript", "bytes": "116065" } ], "symlink_target": "" }
function engine = gaussian_inf_engine(bnet) % GAUSSIAN_INF_ENGINE Computes the joint multivariate Gaussian corresponding to the bnet % engine = gaussian_inf_engine(bnet) % % For details on how to compute the joint Gaussian from the bnet, see % - "Gaussian Influence Diagrams", R. Shachter and C. R. Kenley, Management Science, 35(5):527--550, 1989. % Once we have the Gaussian, we can apply the standard formulas for conditioning and marginalization. assert(isequal(bnet.cnodes, 1:length(bnet.dag))); [W, D, mu] = extract_params_from_gbn(bnet); U = inv(eye(size(W)) - W')'; Sigma = U' * D * U; engine.mu = mu; engine.Sigma = Sigma; %engine.logp = log(normal_coef(Sigma)); % This is where we will store the results between enter_evidence and marginal_nodes engine.Hmu = []; engine.HSigma = []; engine.hnodes = []; engine = class(engine, 'gaussian_inf_engine', inf_engine(bnet));
{ "content_hash": "52a9d76913e52102f22f2a1de8b50419", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 106, "avg_line_length": 35.44, "alnum_prop": 0.718961625282167, "repo_name": "ushadow/gesture-recog", "id": "3e34c166e0e6a66d5528ccc4066348bfd2cef88d", "size": "886", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "matlab/3rdparty/FullBNT-1.0.7/bnt/BNT/inference/static/@gaussian_inf_engine/gaussian_inf_engine.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "15280" }, { "name": "M", "bytes": "6280" }, { "name": "Matlab", "bytes": "236884" }, { "name": "Objective-C", "bytes": "261" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Csla.Rules; namespace ProjectTracker.Library { /// <summary> /// Ensure the Role property value exists /// in RoleList /// </summary> public class ValidRole : BusinessRule { public ValidRole(Csla.Core.IPropertyInfo primaryProperty) : base(primaryProperty) { IsAsync = true; InputProperties = new System.Collections.Generic.List<Csla.Core.IPropertyInfo> { primaryProperty }; } protected override async void Execute(IRuleContext context) { int role = (int)context.InputPropertyValues[PrimaryProperty]; var roles = await RoleList.CacheListAsync(); if (!roles.ContainsKey(role)) context.AddErrorResult("Role must be in RoleList"); context.Complete(); } } }
{ "content_hash": "ed8a6d3e8fb5149e8059ab24fd2d3e5d", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 105, "avg_line_length": 27.35483870967742, "alnum_prop": 0.6851415094339622, "repo_name": "jonnybee/csla", "id": "4fb7a7394c00db380e9dfef94755b255c31ddfd8", "size": "850", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Samples/ProjectTracker/ProjectTracker.BusinessLibrary.Shared/ValidRole.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "123" }, { "name": "C#", "bytes": "4084184" }, { "name": "HTML", "bytes": "31684" }, { "name": "PowerShell", "bytes": "25158" }, { "name": "Shell", "bytes": "533" }, { "name": "Visual Basic", "bytes": "35331" } ], "symlink_target": "" }
module AllMyCircuits module Strategies # Public: opens the circuit whenever failures threshold is reached # within the window. Threshold is represented by absolute number of # failures within the window. # class NumberOverWindowStrategy < AbstractWindowStrategy # Public: initializes a new instance. # # Options # # requests_window - number of consecutive requests tracked by the window. # failures_threshold - number of failures within the window after which # the circuit is tripped open. # def initialize(failures_threshold:, **kwargs) @failures_threshold = failures_threshold super(**kwargs) end def should_open? return unless @window.full? failures = @window.count(:failed) failures >= @failures_threshold end end end end
{ "content_hash": "b3d8a91e92d22fd4d56051d1ea839705", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 84, "avg_line_length": 28.1875, "alnum_prop": 0.6385809312638581, "repo_name": "remind101/all_my_circuits", "id": "cce95e8491e01a447f02a085516b7e6fc0895af0", "size": "902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/all_my_circuits/strategies/number_over_window_strategy.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "44680" } ], "symlink_target": "" }
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $uri_segments</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:15:14 2014 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_variables'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logVariable('uri_segments'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Variable Cross Reference</h3> <h2><a href="index.html#uri_segments">$uri_segments</a></h2> <b>Defined at:</b><ul> <li><a href="../bonfire/libraries/assets.php.html">/bonfire/libraries/assets.php</A> -> <a href="../bonfire/libraries/assets.php.source.html#l974"> line 974</A></li> </ul> <br><b>Referenced 4 times:</b><ul> <li><a href="../bonfire/libraries/assets.php.html">/bonfire/libraries/assets.php</a> -> <a href="../bonfire/libraries/assets.php.source.html#l974"> line 974</a></li> <li><a href="../bonfire/libraries/assets.php.html">/bonfire/libraries/assets.php</a> -> <a href="../bonfire/libraries/assets.php.source.html#l977"> line 977</a></li> <li><a href="../bonfire/libraries/assets.php.html">/bonfire/libraries/assets.php</a> -> <a href="../bonfire/libraries/assets.php.source.html#l981"> line 981</a></li> <li><a href="../bonfire/libraries/assets.php.html">/bonfire/libraries/assets.php</a> -> <a href="../bonfire/libraries/assets.php.source.html#l983"> line 983</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Thu Oct 23 19:15:14 2014</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
{ "content_hash": "308669d644e53c2744a833bacac15441", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 253, "avg_line_length": 52.92929292929293, "alnum_prop": 0.6694656488549618, "repo_name": "inputx/code-ref-doc", "id": "38fc6b86bf8873821c68a0a8f72f36e51bf7cde9", "size": "5240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rebbit/_variables/uri_segments.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17952" }, { "name": "JavaScript", "bytes": "255489" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Welcome to Angular.js</title> <script src="/libs/jquery/dist/jquery.js"></script> <script src="/libs/angular/angular.js"></script> <script src="/libs/angular-ui-router/release/angular-ui-router.js"></script> <base href="/"> </head> <body> <div ng-app="MyApp"> <div ui-view></div> </div> <script> angular.module("MyApp", ["ui.router"]) .constant("WidgetsUrl", "/api/widgets") .config(function($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise("/"); $locationProvider.html5Mode(true); $stateProvider .state("home", { url: "/", controller: function($scope, $state, widgetsData) { $scope.widgets = widgetsData $scope.createWidget = function() { $state.go("edit", { widgetId: null }); }; $scope.$on("$stateChangeError", function(e, msg) { alert("Failed to change the view"); }) }, templateUrl: "/tpl/widget_list.html", resolve: { widgetsData: function(Widgets) { return Widgets.getAll().then(function(results) { return results.data; }); } } }) .state("view", { url: "/widgets/:widgetId", controller: function($scope, $stateParams, $state, widgetData) { $scope.widget = widgetData; $scope.editWidget = function() { $state.go("edit", { widgetId: $scope.widget._id }); }; $scope.returnToList = function() { $state.go("home"); }; }, templateUrl: "/tpl/widget_view.html", resolve: { widgetData: function(Widgets, $stateParams) { return Widgets.get($stateParams.widgetId).then(function(results) { return results.data; }); } } }) .state("edit", { url: "/widgets/:widgetId/edit", controller: function($scope, Widgets, $stateParams, $state) { $scope.widget = {}; if ($stateParams.widgetId) { Widgets.get($stateParams.widgetId).then(function(results) { $scope.widget = results.data; }); } $scope.saveWidget = function() { ($scope.widget._id ? Widgets.update($scope.widget) : Widgets.insert($scope.widget)).then(function() { $state.go("home"); }); }; $scope.deleteWidget = function() { if (confirm("Are you really sure?")) { if (confirm("Are you really really sure?")) { Widgets.delete($scope.widget._id).then(function() { $state.go("home"); }); } } }; $scope.returnToList = function() { $state.go("home"); }; }, templateUrl: "/tpl/widget_edit.html" }) .state("about", { templateUrl: "/tpl/about.html" }) .state("about.details", { url: "/about", views: { history: { templateUrl: "/tpl/history.html" }, team: { templateUrl: "/tpl/team.html" }, mission: { templateUrl: "/tpl/mission.html", controller: function($scope) { $scope.message = "Our mission is to..."; } } } }); }) .factory("Widgets", function($http, WidgetsUrl) { return { getAll: function() { return $http.get(WidgetsUrl).catch(function() { }); }, get: function(widgetId) { return $http.get(WidgetsUrl + "/" + encodeURIComponent(widgetId)); }, insert: function(widget) { return $http.post(WidgetsUrl, widget); }, update: function(widget) { return $http.put(WidgetsUrl + "/" + encodeURIComponent(widget._id), widget); }, delete: function(widgetId) { return $http.delete(WidgetsUrl + "/" + encodeURIComponent(widgetId)); } } }); </script> </body> </html>
{ "content_hash": "aed6a8c5a6ffc4548ba336c69cbb01b8", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 78, "avg_line_length": 24.993827160493826, "alnum_prop": 0.5169177574709805, "repo_name": "training4developers/angular-10262015", "id": "52299b5bc8788c3586f3882d3d18f3064e8e30d4", "size": "4049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/www/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "62580" }, { "name": "JavaScript", "bytes": "1455069" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Metronome = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _instrument = require('./instrument'); var _track = require('./track'); var _part3 = require('./part'); var _parse_events = require('./parse_events'); var _midi_event = require('./midi_event'); var _util = require('./util'); var _position = require('./position'); var _sampler = require('./sampler'); var _init_audio = require('./init_audio'); var _constants = require('./constants'); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var methodMap = new Map([['volume', 'setVolume'], ['instrument', 'setInstrument'], ['noteNumberAccentedTick', 'setNoteNumberAccentedTick'], ['noteNumberNonAccentedTick', 'setNoteNumberNonAccentedTick'], ['velocityAccentedTick', 'setVelocityAccentedTick'], ['velocityNonAccentedTick', 'setVelocityNonAccentedTick'], ['noteLengthAccentedTick', 'setNoteLengthAccentedTick'], ['noteLengthNonAccentedTick', 'setNoteLengthNonAccentedTick']]); var Metronome = exports.Metronome = function () { function Metronome(song) { _classCallCheck(this, Metronome); this.song = song; this.track = new _track.Track({ name: this.song.id + '_metronome' }); this.part = new _part3.Part(); this.track.addParts(this.part); this.track._gainNode.connect(this.song._gainNode); this.events = []; this.precountEvents = []; this.precountDuration = 0; this.bars = 0; this.index = 0; this.index2 = 0; this.precountIndex = 0; this.reset(); } _createClass(Metronome, [{ key: 'reset', value: function reset() { var data = (0, _init_audio.getInitData)(); var instrument = new _sampler.Sampler('metronome'); instrument.updateSampleData({ note: 60, buffer: data.lowtick }, { note: 61, buffer: data.hightick }); this.track.setInstrument(instrument); this.volume = 1; this.noteNumberAccented = 61; this.noteNumberNonAccented = 60; this.velocityAccented = 100; this.velocityNonAccented = 100; this.noteLengthAccented = this.song.ppq / 4; // sixteenth notes -> don't make this too short if your sample has a long attack! this.noteLengthNonAccented = this.song.ppq / 4; } }, { key: 'createEvents', value: function createEvents(startBar, endBar) { var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'init'; var i = void 0, j = void 0; var position = void 0; var velocity = void 0; var noteLength = void 0; var noteNumber = void 0; var beatsPerBar = void 0; var ticksPerBeat = void 0; var ticks = 0; var noteOn = void 0, noteOff = void 0; var events = []; //console.log(startBar, endBar); for (i = startBar; i <= endBar; i++) { position = (0, _position.calculatePosition)(this.song, { type: 'barsbeats', target: [i] }); beatsPerBar = position.nominator; ticksPerBeat = position.ticksPerBeat; ticks = position.ticks; for (j = 0; j < beatsPerBar; j++) { noteNumber = j === 0 ? this.noteNumberAccented : this.noteNumberNonAccented; noteLength = j === 0 ? this.noteLengthAccented : this.noteLengthNonAccented; velocity = j === 0 ? this.velocityAccented : this.velocityNonAccented; noteOn = new _midi_event.MIDIEvent(ticks, 144, noteNumber, velocity); noteOff = new _midi_event.MIDIEvent(ticks + noteLength, 128, noteNumber, 0); if (id === 'precount') { noteOn._track = this.track; noteOff._track = this.track; noteOn._part = {}; noteOff._part = {}; } events.push(noteOn, noteOff); ticks += ticksPerBeat; } } return events; } }, { key: 'getEvents', value: function getEvents() { var startBar = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var _part; var endBar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.song.bars; var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'init'; this.part.removeEvents(this.part.getEvents()); this.events = this.createEvents(startBar, endBar, id); (_part = this.part).addEvents.apply(_part, _toConsumableArray(this.events)); this.bars = this.song.bars; //console.log('getEvents %O', this.events) this.allEvents = [].concat(_toConsumableArray(this.events), _toConsumableArray(this.song._timeEvents)); // console.log(this.allEvents) (0, _util.sortEvents)(this.allEvents); (0, _parse_events.parseMIDINotes)(this.events); return this.events; } }, { key: 'setIndex2', value: function setIndex2(millis) { this.index2 = 0; } }, { key: 'getEvents2', value: function getEvents2(maxtime, timeStamp) { var result = []; for (var i = this.index2, maxi = this.allEvents.length; i < maxi; i++) { var event = this.allEvents[i]; if (event.type === _constants.MIDIEventTypes.TEMPO || event.type === _constants.MIDIEventTypes.TIME_SIGNATURE) { if (event.millis < maxtime) { this.millisPerTick = event.millisPerTick; this.index2++; } else { break; } } else { var millis = event.ticks * this.millisPerTick; if (millis < maxtime) { event.time = millis + timeStamp; event.millis = millis; result.push(event); this.index2++; } else { break; } } } return result; } }, { key: 'addEvents', value: function addEvents() { var startBar = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var _events, _part2; var endBar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.song.bars; var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'add'; // console.log(startBar, endBar) var events = this.createEvents(startBar, endBar, id); (_events = this.events).push.apply(_events, _toConsumableArray(events)); (_part2 = this.part).addEvents.apply(_part2, _toConsumableArray(events)); this.bars = endBar; //console.log('getEvents %O', this.events, endBar) return events; } }, { key: 'createPrecountEvents', value: function createPrecountEvents(startBar, endBar, timeStamp) { this.timeStamp = timeStamp; // let songStartPosition = this.song.getPosition() var songStartPosition = (0, _position.calculatePosition)(this.song, { type: 'barsbeats', target: [startBar], result: 'millis' }); //console.log('starBar', songStartPosition.bar) var endPos = (0, _position.calculatePosition)(this.song, { type: 'barsbeats', //target: [songStartPosition.bar + precount, songStartPosition.beat, songStartPosition.sixteenth, songStartPosition.tick], target: [endBar], result: 'millis' }); //console.log(songStartPosition, endPos) this.precountIndex = 0; this.startMillis = songStartPosition.millis; this.endMillis = endPos.millis; this.precountDuration = endPos.millis - this.startMillis; // do this so you can start precounting at any position in the song this.timeStamp -= this.startMillis; //console.log(this.precountDuration, this.startMillis, this.endMillis) this.precountEvents = this.createEvents(startBar, endBar - 1, 'precount'); this.precountEvents = (0, _parse_events.parseEvents)([].concat(_toConsumableArray(this.song._timeEvents), _toConsumableArray(this.precountEvents))); //console.log(songStartPosition.bar, endPos.bar, precount, this.precountEvents.length); //console.log(this.precountEvents.length, this.precountDuration); return this.precountDuration; } }, { key: 'setPrecountIndex', value: function setPrecountIndex(millis) { var i = 0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.events[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var event = _step.value; if (event.millis >= millis) { this.precountIndex = i; break; } i++; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } console.log(this.precountIndex); } // called by scheduler.js }, { key: 'getPrecountEvents', value: function getPrecountEvents(maxtime) { var events = this.precountEvents, maxi = events.length, i = void 0, evt = void 0, result = []; //maxtime += this.precountDuration for (i = this.precountIndex; i < maxi; i++) { evt = events[i]; //console.log(event.millis, maxtime, this.millis); if (evt.millis < maxtime) { evt.time = this.timeStamp + evt.millis; result.push(evt); this.precountIndex++; } else { break; } } //console.log(result.length); return result; } }, { key: 'mute', value: function mute(flag) { this.track.muted = flag; } }, { key: 'allNotesOff', value: function allNotesOff() { this.track._instrument.allNotesOff(); } // =========== CONFIGURATION =========== }, { key: 'updateConfig', value: function updateConfig() { this.init(1, this.bars, 'update'); this.allNotesOff(); this.song.update(); } // added to public API: Song.configureMetronome({}) }, { key: 'configure', value: function configure(config) { Object.keys(config).forEach(function (key) { this[methodMap.get(key)](config.key); }, this); this.updateConfig(); } }, { key: 'setInstrument', value: function setInstrument(instrument) { if (!instrument instanceof _instrument.Instrument) { console.warn('not an instance of Instrument'); return; } this.track.setInstrument(instrument); this.updateConfig(); } }, { key: 'setNoteLengthAccentedTick', value: function setNoteLengthAccentedTick(value) { if (isNaN(value)) { console.warn('please provide a number'); } this.noteLengthAccented = value; this.updateConfig(); } }, { key: 'setNoteLengthNonAccentedTick', value: function setNoteLengthNonAccentedTick(value) { if (isNaN(value)) { console.warn('please provide a number'); } this.noteLengthNonAccented = value; this.updateConfig(); } }, { key: 'setVelocityAccentedTick', value: function setVelocityAccentedTick(value) { value = (0, _util.checkMIDINumber)(value); if (value !== false) { this.velocityAccented = value; } else { console.warn('please provide a number'); } this.updateConfig(); } }, { key: 'setVelocityNonAccentedTick', value: function setVelocityNonAccentedTick(value) { value = (0, _util.checkMIDINumber)(value); if (value !== false) { this.velocityNonAccented = value; } else { console.warn('please provide a number'); } this.updateConfig(); } }, { key: 'setNoteNumberAccentedTick', value: function setNoteNumberAccentedTick(value) { value = (0, _util.checkMIDINumber)(value); if (value !== false) { this.noteNumberAccented = value; } else { console.warn('please provide a number'); } this.updateConfig(); } }, { key: 'setNoteNumberNonAccentedTick', value: function setNoteNumberNonAccentedTick(value) { value = (0, _util.checkMIDINumber)(value); if (value !== false) { this.noteNumberNonAccented = value; } else { console.warn('please provide a number'); } this.updateConfig(); } }, { key: 'setVolume', value: function setVolume(value) { this.track.setVolume(value); } }]); return Metronome; }();
{ "content_hash": "24bbd1ceb4d143b3932df430889129e7", "timestamp": "", "source": "github", "line_count": 426, "max_line_length": 564, "avg_line_length": 31.941314553990612, "alnum_prop": 0.6037333725288454, "repo_name": "abudaan/qambi", "id": "24d9776041f39057ec95f1943a283d79c5d8bd49", "size": "13607", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "dist/metronome.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10026" }, { "name": "HTML", "bytes": "2814" }, { "name": "JavaScript", "bytes": "435515" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources name="en" flag="gb" title="English"> <string name="_bx_quoteofday"><![CDATA[Quote of the Day]]></string> <string name="_bx_quoteofday_option_rss_url"><![CDATA[Url of external RSS feed]]></string> <string name="_bx_quoteofday_lmi_cpt_quotes"><![CDATA[Quotes List]]></string> <string name="_bx_quoteofday_source"><![CDATA[Source]]></string> <string name="_bx_quoteofday_rss_max_items"><![CDATA[Max number of items from RSS]]></string> <string name="_bx_quoteofday_source_internal"><![CDATA[Internal List]]></string> <string name="_bx_quoteofday_source_rss"><![CDATA[Rss feed]]></string> <string name="_bx_quoteofday_grid_column_title_adm_active"><![CDATA[Active]]></string> <string name="_bx_quoteofday_grid_column_title_adm_text"><![CDATA[Text]]></string> <string name="_bx_quoteofday_grid_column_title_adm_added"><![CDATA[Added]]></string> <string name="_bx_quoteofday_grid_action_title_adm_add"><![CDATA[Add new]]></string> <string name="_bx_quoteofday_grid_action_title_adm_edit"><![CDATA[Edit]]></string> <string name="_bx_quoteofday_grid_action_title_adm_delete"><![CDATA[Delete]]></string> <string name="_bx_quoteofday_grid_action_title_adm_publish"><![CDATA[Mark as Today Quote]]></string> <string name="_bx_quoteofday_grid_action_title_adm_audit_content"><![CDATA[Audit actions]]></string> <string name="_bx_quoteofday_grid_action_title_adm_publish_text"><![CDATA[Item set as Today Quote]]></string> <string name="_bx_quoteofday_form_entry"><![CDATA[Quote of the Day]]></string> <string name="_bx_quoteofday_form_entry_input_do_submit"><![CDATA[Save]]></string> <string name="_bx_quoteofday_form_add_title"><![CDATA[Add new]]></string> <string name="_bx_quoteofday_form_entry_input_text"><![CDATA[Text]]></string> <string name="_bx_quoteofday_form_edit_title"><![CDATA[Edit]]></string> <string name="_bx_quoteofday_form_entry_input_cancel"><![CDATA[Cancel]]></string> <string name="_bx_quoteofday_form_entry_input_text_err"><![CDATA[Text field can't be empty]]></string> <string name="_bx_quoteofday_page_title_manage"><![CDATA[Quote of the Day management]]></string> <string name="_bx_quoteofday_page_block_title_manage"><![CDATA[Quote of the Day management]]></string> <string name="_bx_quoteofday_page_block_title"><![CDATA[Quote of the Day]]></string> <string name="_bx_quoteofday_menu_item_title_system_admt_manage"><![CDATA[Quotes of the day]]></string> <string name="_bx_quoteofday_adm_stg_cpt_type"><![CDATA[Quote of the Day]]></string> <string name="_bx_quoteofday_selection_mode"><![CDATA[Quote of the Day selected by]]></string> <string name="_bx_quoteofday_selection_mode_by_order"><![CDATA[By order]]></string> <string name="_bx_quoteofday_selection_mode_by_random"><![CDATA[By random]]></string> </resources>
{ "content_hash": "6af82c984f1ec92fe77358a0ccbc4e85", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 110, "avg_line_length": 73.3076923076923, "alnum_prop": 0.6935991605456453, "repo_name": "unaio/una", "id": "ced8d4ae5b7ba3feb2e4eab988d5bb395a7fa855", "size": "2859", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "modules/boonex/quoteofday/install/langs/en.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9522763" }, { "name": "Dockerfile", "bytes": "2367" }, { "name": "HTML", "bytes": "6194660" }, { "name": "JavaScript", "bytes": "24733694" }, { "name": "Less", "bytes": "3020615" }, { "name": "Makefile", "bytes": "1196" }, { "name": "PHP", "bytes": "158741504" }, { "name": "Ruby", "bytes": "210" }, { "name": "Shell", "bytes": "3327" }, { "name": "Smarty", "bytes": "3461" } ], "symlink_target": "" }
"""Config flow to configure demo component.""" from homeassistant import config_entries # pylint: disable=unused-import from . import DOMAIN class DemoConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Demo configuration flow.""" VERSION = 1 async def async_step_import(self, import_info): """Set the config entry up from yaml.""" return self.async_create_entry(title="Demo", data={})
{ "content_hash": "7eb34d19c05959ac0d84fc173367cef5", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 63, "avg_line_length": 26.5625, "alnum_prop": 0.6988235294117647, "repo_name": "Teagan42/home-assistant", "id": "e6b275920c8c16ea0f4dd2d3ddeadaf3fb35ce34", "size": "425", "binary": false, "copies": "4", "ref": "refs/heads/dev", "path": "homeassistant/components/demo/config_flow.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "19774313" }, { "name": "Shell", "bytes": "6846" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18331 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Articulate.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
{ "content_hash": "b52b88477658dd683633d93dffa494fe", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 151, "avg_line_length": 35.5, "alnum_prop": 0.5812206572769953, "repo_name": "Mpstark/articulate", "id": "931186e0e9998a72e20dbf0429316d42085feff4", "size": "1067", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Articulate/Properties/Settings.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "219478" }, { "name": "Inno Setup", "bytes": "21276" } ], "symlink_target": "" }
""" A fantastic python code to determine the quenched SFH parameters of galaxies using emcee (http://dan.iel.fm/emcee/current/). This file contains all the functions needed to determine the mean SFH parameters of a population. N.B. The data files .ised_ASCII contain the extracted bc03 models and have a 0 in the origin at [0,0]. The first row contains the model ages (from the second column) - data[0,1:]. The first column contains the model lambda values (from the second row) - data[1:,0]. The remaining data[1:,1:] are the flux values at each of the ages (columns, x) and lambda (rows, y) values """ import numpy as N import scipy as S import pylab as P import pyfits as F from scipy.io.idl import readsav import pyfits as F import emcee import triangle import time import os import matplotlib.image as mpimg from astropy.cosmology import FlatLambdaCDM from scipy.stats import kde from scipy.interpolate import LinearNDInterpolator from scipy.interpolate import interp2d from itertools import product import sys cosmo = FlatLambdaCDM(H0 = 71.0, Om0 = 0.26) font = {'family':'serif', 'size':16} P.rc('font', **font) P.rc('xtick', labelsize='medium') P.rc('ytick', labelsize='medium') P.rc('axes', labelsize='medium') method = raw_input('Do you wish to use a look-up table? (yes/no) :') if method == 'yes' or method =='y': prov = raw_input('Do you wish to use the provided u-r and NUV-u look up tables? (yes/no) :') if prov == 'yes' or prov =='y': print 'gridding...' tq = N.linspace(0.003, 13.8, 100) tau = N.linspace(0.003, 4, 100) ages = N.linspace(10.88861228, 13.67023409, 50) grid = N.array(list(product(ages, tau, tq))) print 'loading...' nuv_pred = N.load('nuv_look_up_ssfr.npy') ur_pred = N.load('ur_look_up_ssfr.npy') lu = N.append(nuv_pred.reshape(-1,1), ur_pred.reshape(-1,1), axis=1) elif prov=='no' or prov=='n': col1 = str(raw_input('Location of your NUV-u colour look up table :')) col2 = str(raw_input('Location of your u-r colour look up table :')) one = N.array(input('Define first axis values (ages) of look up table start, stop, len(axis1); e.g. 10, 13.8, 50 :')) ages = N.linspace(float(one[0]), float(one[1]), float(one[2])) two = N.array(input('Define second axis values (tau) of look up table start, stop, len(axis1); e.g. 0, 4, 100 : ')) tau = N.linspace(float(two[0]), float(two[1]), float(two[2])) three = N.array(input('Define third axis values (tq) of look up table start, stop, len(axis1); e.g. 0, 13.8, 100 : ')) tq = N.linspace(float(three[0]), float(three[1]), float(three[2])) grid = N.array(list(product(ages, tau, tq))) print 'loading...' nuv_pred = N.load(col1) ur_pred = N.load(col2) lu = N.append(nuv_pred.reshape(-1,1), ur_pred.reshape(-1,1), axis=1) else: sys.exit("You didn't give a valid answer (yes/no). Try running again.") def lnlike_one(theta, ur, sigma_ur, nuvu, sigma_nuvu, age): """ Function for determining the likelihood of ONE quenching model described by theta = [tq, tau] for all the galaxies in the sample. Simple chi squared likelihood between predicted and observed colours of the galaxies. :theta: An array of size (1,2) containing the values [tq, tau] in Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. :ur: Observed u-r colour of a galaxy; k-corrected. :sigma_ur: Error on the observed u-r colour of a galaxy :nuvu: Observed nuv-u colour of a galaxy; k-corrected. :sigma_nuvu: Error on the observed nuv-u colour of a galaxy :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. RETURNS: Array of same shape as :age: containing the likelihood for each galaxy at the given :theta: """ tq, tau = theta pred_nuvu, pred_ur = lookup_col_one(theta, age) return -0.5*N.log(2*N.pi*sigma_ur**2)-0.5*((ur-pred_ur)**2/sigma_ur**2)-0.5*N.log10(2*N.pi*sigma_nuvu**2)-0.5*((nuvu-pred_nuvu)**2/sigma_nuvu**2) elif method == 'no' or method =='n': """We first define the directory in which we will find the BC03 model, extracted from the original files downloaded from the BC03 website into a usable format. Here we implement a solar metallicity model with a Chabrier IMF.""" model = str(raw_input('Location of the extracted (.ised_ASCII) SPS model to use to predict the u-r and NUV-u colours, e.g. ~/extracted_bc2003_lr_m62_chab_ssp.ised_ASCII :')) data = N.loadtxt(model) import fluxes def lnlike_one(theta, ur, sigma_ur, nuvu, sigma_nuvu, age): """ Function for determining the likelihood of ONE quenching model described by theta = [tq, tau] for all the galaxies in the sample. Simple chi squared likelihood between predicted and observed colours of the galaxies. :theta: An array of size (1,2) containing the values [tq, tau] in Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. :ur: Observed u-r colour of a galaxy; k-corrected. :sigma_ur: Error on the observed u-r colour of a galaxy :nuvu: Observed nuv-u colour of a galaxy; k-corrected. :sigma_nuvu: Error on the observed nuv-u colour of a galaxy :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. RETURNS: Array of same shape as :age: containing the likelihood for each galaxy at the given :theta: """ tq, tau = theta pred_nuvu, pred_ur = predict_c_one(theta, age) return -0.5*N.log(2*N.pi*sigma_ur**2)-0.5*((ur-pred_ur)**2/sigma_ur**2)-0.5*N.log10(2*N.pi*sigma_nuvu**2)-0.5*((nuvu-pred_nuvu)**2/sigma_nuvu**2) else: sys.exit("You didn't give a valid answer (yes/no). Try running again.") n=0 def expsfh(tq, tau, time): """ This function when given a single combination of [tq, tau] values will calcualte the SFR at all times. First calculate the sSFR at all times as defined by Peng et al. (2010) - then the SFR at the specified time of quenching, tq and set the SFR at this value at all times before tq. Beyond this time the SFR is an exponentially declining function with timescale tau. INPUT: :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. :time: An array of time values at which the SFR is calcualted at each step. RETURNS: :sfr: Array of the same dimensions of time containing the sfr at each timestep. """ ssfr = 2.5*(((10**10.27)/1E10)**(-0.1))*(time/3.5)**(-2.2) c = time.searchsorted(3.0) ssfr[:c] = N.interp(3.0, time, ssfr) c_sfr = N.interp(tq, time, ssfr)*(1E10)/(1E9) ### definition is for 10^10 M_solar galaxies and per gyr - convert to M_solar/year ### a = time.searchsorted(tq) sfr = N.ones(len(time))*c_sfr sfr[a:] = c_sfr*N.exp(-(time[a:]-tq)/tau) return sfr def expsfh_mass(ur, Mr, age, tq, tau, time): """Calculate exponential decline star formation rates at each time step input by matching to the mass of the observed galaxy at the observed time. This is calculated from the mass-to-light ratio that is a function of one color band u-r as in Bladry et al. (2006; see Figure 5) who fit to data from Glazebrrok et al (2004) and Kauffmann et al (2003). INPUT: :ur: u-r optical colour, needed to calculate the mass of the observed galaxy :Mr: Absolute r-band magnitude, needed to calculate the mass of the observed galaxy :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. :time: An array of time values at which the SFR is calcualted at each step. RETURNS: :sfr: Array of the same dimensions of time containing the sfr at each timestep. """ t_end = age # time at which to integrate under the exponential curve until to gain the final mass if ur <=2.1: log_m_l = -0.95 + 0.56 * ur else: log_m_l = -0.16 + 0.18 * ur m_msun = 10**(((4.62 - Mr)/2.5) + log_m_l) print 'Mass [M_solar]', m_msun c_sfr = (m_msun/(tq + tau*(1 - N.exp((tq - t_end)/tau)))) / 1E9 a = time.searchsorted(tq) sfr = N.ones(len(time))*c_sfr sfr[a:] = c_sfr*N.exp(-(time[a:]-tq)/tau) return sfr def predict_c_one(theta, age): """ This function predicts the u-r and nuv-u colours of a galaxy with a SFH defined by [tq, tau], according to the BC03 model at a given "age" i.e. observation time. It calculates the colours at all times then interpolates for the observed age - it has to this in order to work out the cumulative mass across the SFH to determine how much each population of stars contributes to the flux at each time step. :theta: An array of size (1,2) containing the values [tq, tau] in Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. RETURNS: :nuv_u_age: Array the same shape as :age: with the nuv-u colour values at each given age for the specified :theta: values :u_r_age: Array the same shape as :age: with the u-r colour values at each given age for the specified :theta: values """ ti = N.arange(0, 0.01, 0.003) t = N.linspace(0,14.0,100) t = N.append(ti, t[1:]) tq, tau = theta sfr = expsfh(tq, tau, t) ### Work out total flux at each time given the sfh model of tau and tq (calls fluxes function) ### total_flux = fluxes.assign_total_flux(data[0,1:], data[1:,0], data[1:,1:], t*1E9, sfr) ### Calculate fluxes from the flux at all times then interpolate to get one colour for the age you are observing the galaxy at - if many galaxies are being observed, this also works with an array of ages to give back an array of colours ### nuv_u, u_r = get_colours(t*1E9, total_flux, data) nuv_u_age = N.interp(age, t, nuv_u) u_r_age = N.interp(age, t, u_r) return nuv_u_age, u_r_age def get_colours(time, flux, data): """" Calculates the colours of a given sfh fluxes across time given the BC03 models from the magnitudes of the SED. :time: Array of times at which the colours should be calculated. In units of Gyrs. :flux: SED of fluxes describing the calcualted SFH. Returned from the assign_total_flux function in fluxes.py :data: BC03 model values for wavelengths, time steps and fluxes. The wavelengths are needed to calculate the magnitudes. RETURNS: :nuv_u: :u_r: Arrays the same shape as :time: with the predicted nuv-u and u-r colours """ nuvmag = fluxes.calculate_AB_mag(time, data[1:,0], flux, nuvwave, nuvtrans) umag = fluxes.calculate_AB_mag(time, data[1:,0], flux, uwave, utrans) rmag = fluxes.calculate_AB_mag(time, data[1:,0], flux, rwave, rtrans) nuv_u = nuvmag - umag u_r = umag - rmag return nuv_u, u_r def lookup_col_one(theta, age): ur_pred = u(theta[0], theta[1]) nuv_pred = v(theta[0], theta[1]) return nuv_pred, ur_pred # Prior likelihood on theta values given the inital w values assumed for the mean and stdev def lnprior(theta): """ Function to calcualted the prior likelihood on theta values given the inital w values assumed for the mean and standard deviation of the tq and tau parameters. Defined ranges are specified - outside these ranges the function returns -N.inf and does not calculate the posterior probability. :theta: An array of size (1,4) containing the values [tq, tau] for both smooth and disc galaxies in Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. Can be either for smooth or disc galaxies. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. Can be either for smooth or disc galaxies. RETURNS: Value of the prior at the specified :theta: value. """ tq, tau = theta if 0.003 <= tq <= 13.807108309208775 and 0.003 <= tau <= 4.0: return 0.0 else: return -N.inf # Overall likelihood function combining prior and model def lnprob(theta, ur, sigma_ur, nuvu, sigma_nuvu, age): """Overall posterior function combiningin the prior and calculating the likelihood. Also prints out the progress through the code with the use of n. :theta: An array of size (1,4) containing the values [tq, tau] for both smooth and disc galaxies in Gyr. :tq: The time at which the onset of quenching begins in Gyr. Allowed ranges from the beginning to the end of known cosmic time. Can be either for smooth or disc galaxies. :tau: The exponential timescale decay rate of the star formation history in Gyr. Allowed range from the rest of the functions is 0 < tau [Gyr] < 5. Can be either for smooth or disc galaxies. :ur: Observed u-r colour of a galaxy; k-corrected. An array of shape (N,1) or (N,). :sigma_ur: Error on the observed u-r colour of a galaxy. An array of shape (N,1) or (N,). :nuvu: Observed nuv-u colour of a galaxy; k-corrected. An array of shape (N,1) or (N,). :sigma_nuvu: Error on the observed nuv-u colour of a galaxy. An array of shape (N,1) or (N,). :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. An array of shape (N,1) or (N,). RETURNS: Value of the posterior function for the given :theta: value. """ global n n+=1 if n %100 == 0: print 'step number', n/100 lp = lnprior(theta) if not N.isfinite(lp): return -N.inf return lp + lnlike_one(theta, ur, sigma_ur, nuvu, sigma_nuvu, age) def sample(ndim, nwalkers, nsteps, burnin, start, ur, sigma_ur, nuvu, sigma_nuvu, age, id, ra, dec): """ Function to implement the emcee EnsembleSampler function for the sample of galaxies input. Burn in is run and calcualted fir the length specified before the sampler is reset and then run for the length of steps specified. :ndim: The number of parameters in the model that emcee must find. In this case it always 2 with tq, tau. :nwalkers: The number of walkers that step around the parameter space. Must be an even integer number larger than ndim. :nsteps: The number of steps to take in the final run of the MCMC sampler. Integer. :burnin: The number of steps to take in the inital burn-in run of the MCMC sampler. Integer. :start: The positions in the tq and tau parameter space to start for both disc and smooth parameters. An array of shape (1,4). :ur: Observed u-r colour of a galaxy; k-corrected. An array of shape (N,1) or (N,). :sigma_ur: Error on the observed u-r colour of a galaxy. An array of shape (N,1) or (N,). :nuvu: Observed nuv-u colour of a galaxy; k-corrected. An array of shape (N,1) or (N,). :sigma_nuvu: Error on the observed nuv-u colour of a galaxy. An array of shape (N,1) or (N,). :age: Observed age of a galaxy, often calculated from the redshift i.e. at z=0.1 the age ~ 12.5. Must be in units of Gyr. An array of shape (N,1) or (N,). :id: ID number to specify which galaxy this run is for. :ra: right ascension of source, used for identification purposes :dec: declination of source, used for identification purposes RETURNS: :samples: Array of shape (nsteps*nwalkers, 4) containing the positions of the walkers at all steps for all 4 parameters. :samples_save: Location at which the :samples: array was saved to. """ if method == 'yes' or method=='y': global u global v a = N.searchsorted(ages, age) b = N.array([a-1, a]) print 'interpolating function, bear with...' g = grid[N.where(N.logical_or(grid[:,0]==ages[b[0]], grid[:,0]==ages[b[1]]))] values = lu[N.where(N.logical_or(grid[:,0]==ages[b[0]], grid[:,0]==ages[b[1]]))] f = LinearNDInterpolator(g, values, fill_value=(-N.inf)) look = f(age, grid[:10000, 1], grid[:10000, 2]) lunuv = look[:,0].reshape(100,100) v = interp2d(tq, tau, lunuv) luur = look[:,1].reshape(100,100) u = interp2d(tq, tau, luur) else: pass print 'emcee running...' p0 = [start + 1e-4*N.random.randn(ndim) for i in range(nwalkers)] sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, threads=2, args=(ur, sigma_ur, nuvu, sigma_nuvu, age)) """ Burn in run here...""" pos, prob, state = sampler.run_mcmc(p0, burnin) lnp = sampler.flatlnprobability N.save('lnprob_burnin_'+str(int(id))+'_'+str(ra)+'_'+str(dec)+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.npy', lnp) samples = sampler.chain[:,:,:].reshape((-1,ndim)) samples_save = 'samples_burn_in_'+str(int(id))+'_'+str(ra)+'_'+str(dec)+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.npy' N.save(samples_save, samples) sampler.reset() print 'Burn in complete...' """ Main sampler run here...""" sampler.run_mcmc(pos, nsteps) lnpr = sampler.flatlnprobability N.save('lnprob_run_'+str(int(id))+'_'+str(ra)+'_'+str(dec)+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.npy', lnpr) samples = sampler.chain[:,:,:].reshape((-1,ndim)) samples_save = 'samples_'+str(int(id))+'_'+str(ra)+'_'+str(dec)+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.npy' N.save(samples_save, samples) print 'Main emcee run completed.' return samples, samples_save #Define function to plot the walker positions as a function of the step def walker_plot(samples, nwalkers, limit, id): """ Plotting function to visualise the steps of the walkers in each parameter dimension for smooth and disc theta values. :samples: Array of shape (nsteps*nwalkers, 4) produced by the emcee EnsembleSampler in the sample function. :nwalkers: The number of walkers that step around the parameter space used to produce the samples by the sample function. Must be an even integer number larger than ndim. :limit: Integer value less than nsteps to plot the walker steps to. :id: ID number to specify which galaxy this plot is for. RETURNS: :fig: The figure object """ s = samples.reshape(nwalkers, -1, 2) s = s[:,:limit, :] fig = P.figure(figsize=(8,5)) ax1 = P.subplot(2,1,1) ax2 = P.subplot(2,1,2) for n in range(len(s)): ax1.plot(s[n,:,0], 'k') ax2.plot(s[n,:,1], 'k') ax1.tick_params(axis='x', labelbottom='off') ax2.set_xlabel(r'step number') ax1.set_ylabel(r'$t_{quench}$') ax2.set_ylabel(r'$\tau$') P.subplots_adjust(hspace=0.1) save_fig = 'walkers_steps_'+str(int(id))+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.pdf' fig.savefig(save_fig) return fig def corner_plot(s, labels, extents, bf, id): """ Plotting function to visualise the gaussian peaks found by the sampler function. 2D contour plots of tq against tau are plotted along with kernelly smooth histograms for each parameter. :s: Array of shape (#, 2) for either the smooth or disc produced by the emcee EnsembleSampler in the sample function of length determined by the number of walkers which resulted at the specified peak. :labels: List of x and y axes labels i.e. disc or smooth parameters :extents: Range over which to plot the samples, list shape [[xmin, xmax], [ymin, ymax]] :bf: Best fit values for the distribution peaks in both tq and tau found from mapping the samples. List shape [(tq, poserrtq, negerrtq), (tau, poserrtau, negerrtau)] :id: ID number to specify which galaxy this plot is for. RETURNS: :fig: The figure object """ x, y = s[:,0], s[:,1] fig = P.figure(figsize=(6.25,6.25)) ax2 = P.subplot2grid((3,3), (1,0), colspan=2, rowspan=2) ax2.set_xlabel(labels[0]) ax2.set_ylabel(labels[1]) triangle.hist2d(x, y, ax=ax2, bins=100, extent=extents, plot_contours=True) ax2.axvline(x=bf[0][0], linewidth=1) ax2.axhline(y=bf[1][0], linewidth=1) [l.set_rotation(45) for l in ax2.get_xticklabels()] [j.set_rotation(45) for j in ax2.get_yticklabels()] ax2.tick_params(axis='x', labeltop='off') ax1 = P.subplot2grid((3,3), (0,0),colspan=2) den = kde.gaussian_kde(x[N.logical_and(x>=extents[0][0], x<=extents[0][1])]) pos = N.linspace(extents[0][0], extents[0][1], 750) ax1.plot(pos, den(pos), 'k-', linewidth=1) ax1.axvline(x=bf[0][0], linewidth=1) ax1.axvline(x=bf[0][0]+bf[0][1], c='b', linestyle='--') ax1.axvline(x=bf[0][0]-bf[0][2], c='b', linestyle='--') ax1.set_xlim(extents[0][0], extents[0][1]) ax12 = ax1.twiny() ax12.set_xlim(extents[0][0], extents[0][1]) ax12.set_xticks(N.array([1.87, 3.40, 6.03, 8.77, 10.9, 12.5])) ax12.set_xticklabels(N.array([3.5, 2.0 , 1.0, 0.5, 0.25, 0.1])) [l.set_rotation(45) for l in ax12.get_xticklabels()] ax12.tick_params(axis='x', labelbottom='off') ax12.set_xlabel(r'$z$') ax1.tick_params(axis='x', labelbottom='off', labeltop='off') ax1.tick_params(axis='y', labelleft='off') ax3 = P.subplot2grid((3,3), (1,2), rowspan=2) ax3.tick_params(axis='x', labelbottom='off') ax3.tick_params(axis='y', labelleft='off') den = kde.gaussian_kde(y[N.logical_and(y>=extents[1][0], y<=extents[1][1])]) pos = N.linspace(extents[1][0], extents[1][1], 750) ax3.plot(den(pos), pos, 'k-', linewidth=1) ax3.axhline(y=bf[1][0], linewidth=1) ax3.axhline(y=bf[1][0]+bf[1][1], c='b', linestyle='--') ax3.axhline(y=bf[1][0]-bf[1][2], c='b', linestyle='--') ax3.set_ylim(extents[1][0], extents[1][1]) if os.path.exists(str(int(id))+'.jpeg') == True: ax4 = P.subplot2grid((3,3), (0,2), rowspan=1, colspan=1) img = mpimg.imread(str(int(id))+'.jpeg') ax4.imshow(img) ax4.tick_params(axis='x', labelbottom='off', labeltop='off') ax4.tick_params(axis='y', labelleft='off', labelright='off') P.tight_layout() P.subplots_adjust(wspace=0.0) P.subplots_adjust(hspace=0.0) return fig """ Load the magnitude bandpass filters using idl save """ filters = readsav('ugriz.sav') fuvwave= filters.ugriz.fuvwave[0] fuvtrans = filters.ugriz.fuvtrans[0] nuvwave= filters.ugriz.nuvwave[0] nuvtrans = filters.ugriz.nuvtrans[0] uwave= filters.ugriz.uwave[0] utrans = filters.ugriz.utrans[0] gwave= filters.ugriz.gwave[0] gtrans = filters.ugriz.gtrans[0] rwave= filters.ugriz.rwave[0] rtrans = filters.ugriz.rtrans[0] iwave= filters.ugriz.iwave[0] itrans = filters.ugriz.itrans[0] zwave= filters.ugriz.zwave[0] ztrans = filters.ugriz.ztrans[0] vwave= filters.ugriz.vwave[0] vtrans = filters.ugriz.vtrans[0] jwave= filters.ugriz.jwave[0] jtrans = filters.ugriz.jtrans[0] hwave= filters.ugriz.hwave[0] htrans = filters.ugriz.htrans[0] kwave= filters.ugriz.kwave[0] ktrans = filters.ugriz.ktrans[0]
{ "content_hash": "e22c884bb96703493e97894ad851a4cd", "timestamp": "", "source": "github", "line_count": 555, "max_line_length": 411, "avg_line_length": 46.38558558558559, "alnum_prop": 0.6239123679303915, "repo_name": "zooniverse/starpy", "id": "090b00647e1c412e963c9b3ffaa70f92e1ae0e3b", "size": "25744", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "posterior.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "53011" } ], "symlink_target": "" }
Landuse and patten recognition project This is code written to run automatic classifiers on multiband rasters. [![DOI](https://zenodo.org/badge/63271494.svg)](https://zenodo.org/badge/latestdoi/63271494) ##Usage## Necessary libraries: GDAL, Spectral Python, Numpy, Python Imaging Library This script will take a multiband raster and a set of training images as input, and output images classified with Mahalanobis, Gaussian, and K-Means classifiers. The first step is to group all of the individual band images from the Landsat level 1 product into one multiband tif. This should be done with the included gdal_merge.py script with the following syntax gdal_merge.py -o output.tif -seperate -v band1img_path band2img_path band3img_path band4img_path ... Here is what is needed to merge the example data: gdal_merge.py -o ./sample_input/output.tif -seperate -v ./sample_input/LM50270391984196AAA03_B1.TIF ./sample_input/LM50270391984196AAA03_B2.TIF ./sample_input/LM50270391984196AAA03_B3.TIF ./sample_input/LM50270391984196AAA03_B4.TIF This will create a file "output.tif" with all of the bands merged into it. This file can be used with the python script. Next you will need to open "output.tif" in your favorite GIS and crop out homogenous (in terms of feature type) sections of the image. This is for the trained classifiers. Next make a file in the format of "./sample_input/training.txt" - a file path and an integer "class" to associate with the training data in that file. The integers must start from 1. To run the classification, call the classify.py script with the data raster and training image text file as arguments: python ./sample_input/output.tif ./sample_input/training.txt The script will run and save an image for each classification. Coming soon: Georeferenced output Getting rid of Spectral Python (seems to be dead) probably replacing it with scikit-learn Better documentation
{ "content_hash": "2d25f41adf43a2e45d83813005b7d195", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 354, "avg_line_length": 56.705882352941174, "alnum_prop": 0.7863070539419087, "repo_name": "mchristoffersen/landuse", "id": "c55e22c664392966a5eed384fd98cf2da4ace25d", "size": "1938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "20335" } ], "symlink_target": "" }
#ifndef BGFX_C99_H_HEADER_GUARD #define BGFX_C99_H_HEADER_GUARD #include <stdarg.h> // va_list #include <stdbool.h> // bool #include <stdint.h> // uint32_t #include <stdlib.h> // size_t #include <bgfx/bgfxdefines.h> typedef enum bgfx_renderer_type { BGFX_RENDERER_TYPE_NULL, BGFX_RENDERER_TYPE_DIRECT3D9, BGFX_RENDERER_TYPE_DIRECT3D11, BGFX_RENDERER_TYPE_DIRECT3D12, BGFX_RENDERER_TYPE_METAL, BGFX_RENDERER_TYPE_OPENGLES, BGFX_RENDERER_TYPE_OPENGL, BGFX_RENDERER_TYPE_VULKAN, BGFX_RENDERER_TYPE_COUNT } bgfx_renderer_type_t; typedef enum bgfx_access { BGFX_ACCESS_READ, BGFX_ACCESS_WRITE, BGFX_ACCESS_READWRITE, BGFX_ACCESS_COUNT } bgfx_access_t; typedef enum bgfx_attrib { BGFX_ATTRIB_POSITION, BGFX_ATTRIB_NORMAL, BGFX_ATTRIB_TANGENT, BGFX_ATTRIB_BITANGENT, BGFX_ATTRIB_COLOR0, BGFX_ATTRIB_COLOR1, BGFX_ATTRIB_INDICES, BGFX_ATTRIB_WEIGHT, BGFX_ATTRIB_TEXCOORD0, BGFX_ATTRIB_TEXCOORD1, BGFX_ATTRIB_TEXCOORD2, BGFX_ATTRIB_TEXCOORD3, BGFX_ATTRIB_TEXCOORD4, BGFX_ATTRIB_TEXCOORD5, BGFX_ATTRIB_TEXCOORD6, BGFX_ATTRIB_TEXCOORD7, BGFX_ATTRIB_COUNT } bgfx_attrib_t; typedef enum bgfx_attrib_type { BGFX_ATTRIB_TYPE_UINT8, BGFX_ATTRIB_TYPE_UINT10, BGFX_ATTRIB_TYPE_INT16, BGFX_ATTRIB_TYPE_HALF, BGFX_ATTRIB_TYPE_FLOAT, BGFX_ATTRIB_TYPE_COUNT } bgfx_attrib_type_t; typedef enum bgfx_texture_format { BGFX_TEXTURE_FORMAT_BC1, BGFX_TEXTURE_FORMAT_BC2, BGFX_TEXTURE_FORMAT_BC3, BGFX_TEXTURE_FORMAT_BC4, BGFX_TEXTURE_FORMAT_BC5, BGFX_TEXTURE_FORMAT_BC6H, BGFX_TEXTURE_FORMAT_BC7, BGFX_TEXTURE_FORMAT_ETC1, BGFX_TEXTURE_FORMAT_ETC2, BGFX_TEXTURE_FORMAT_ETC2A, BGFX_TEXTURE_FORMAT_ETC2A1, BGFX_TEXTURE_FORMAT_PTC12, BGFX_TEXTURE_FORMAT_PTC14, BGFX_TEXTURE_FORMAT_PTC12A, BGFX_TEXTURE_FORMAT_PTC14A, BGFX_TEXTURE_FORMAT_PTC22, BGFX_TEXTURE_FORMAT_PTC24, BGFX_TEXTURE_FORMAT_UNKNOWN, BGFX_TEXTURE_FORMAT_R1, BGFX_TEXTURE_FORMAT_A8, BGFX_TEXTURE_FORMAT_R8, BGFX_TEXTURE_FORMAT_R8I, BGFX_TEXTURE_FORMAT_R8U, BGFX_TEXTURE_FORMAT_R8S, BGFX_TEXTURE_FORMAT_R16, BGFX_TEXTURE_FORMAT_R16I, BGFX_TEXTURE_FORMAT_R16U, BGFX_TEXTURE_FORMAT_R16F, BGFX_TEXTURE_FORMAT_R16S, BGFX_TEXTURE_FORMAT_R32I, BGFX_TEXTURE_FORMAT_R32U, BGFX_TEXTURE_FORMAT_R32F, BGFX_TEXTURE_FORMAT_RG8, BGFX_TEXTURE_FORMAT_RG8I, BGFX_TEXTURE_FORMAT_RG8U, BGFX_TEXTURE_FORMAT_RG8S, BGFX_TEXTURE_FORMAT_RG16, BGFX_TEXTURE_FORMAT_RG16I, BGFX_TEXTURE_FORMAT_RG16U, BGFX_TEXTURE_FORMAT_RG16F, BGFX_TEXTURE_FORMAT_RG16S, BGFX_TEXTURE_FORMAT_RG32I, BGFX_TEXTURE_FORMAT_RG32U, BGFX_TEXTURE_FORMAT_RG32F, BGFX_TEXTURE_FORMAT_RGB9E5F, BGFX_TEXTURE_FORMAT_BGRA8, BGFX_TEXTURE_FORMAT_RGBA8, BGFX_TEXTURE_FORMAT_RGBA8I, BGFX_TEXTURE_FORMAT_RGBA8U, BGFX_TEXTURE_FORMAT_RGBA8S, BGFX_TEXTURE_FORMAT_RGBA16, BGFX_TEXTURE_FORMAT_RGBA16I, BGFX_TEXTURE_FORMAT_RGBA16U, BGFX_TEXTURE_FORMAT_RGBA16F, BGFX_TEXTURE_FORMAT_RGBA16S, BGFX_TEXTURE_FORMAT_RGBA32I, BGFX_TEXTURE_FORMAT_RGBA32U, BGFX_TEXTURE_FORMAT_RGBA32F, BGFX_TEXTURE_FORMAT_R5G6B5, BGFX_TEXTURE_FORMAT_RGBA4, BGFX_TEXTURE_FORMAT_RGB5A1, BGFX_TEXTURE_FORMAT_RGB10A2, BGFX_TEXTURE_FORMAT_R11G11B10F, BGFX_TEXTURE_FORMAT_UNKNOWN_DEPTH, BGFX_TEXTURE_FORMAT_D16, BGFX_TEXTURE_FORMAT_D24, BGFX_TEXTURE_FORMAT_D24S8, BGFX_TEXTURE_FORMAT_D32, BGFX_TEXTURE_FORMAT_D16F, BGFX_TEXTURE_FORMAT_D24F, BGFX_TEXTURE_FORMAT_D32F, BGFX_TEXTURE_FORMAT_D0S8, BGFX_TEXTURE_FORMAT_COUNT } bgfx_texture_format_t; typedef enum bgfx_uniform_type { BGFX_UNIFORM_TYPE_INT1, BGFX_UNIFORM_TYPE_END, BGFX_UNIFORM_TYPE_VEC4, BGFX_UNIFORM_TYPE_MAT3, BGFX_UNIFORM_TYPE_MAT4, BGFX_UNIFORM_TYPE_COUNT } bgfx_uniform_type_t; typedef enum bgfx_backbuffer_ratio { BGFX_BACKBUFFER_RATIO_EQUAL, BGFX_BACKBUFFER_RATIO_HALF, BGFX_BACKBUFFER_RATIO_QUARTER, BGFX_BACKBUFFER_RATIO_EIGHTH, BGFX_BACKBUFFER_RATIO_SIXTEENTH, BGFX_BACKBUFFER_RATIO_DOUBLE, BGFX_BACKBUFFER_RATIO_COUNT } bgfx_backbuffer_ratio_t; #define BGFX_HANDLE_T(_name) \ typedef struct _name { uint16_t idx; } _name##_t BGFX_HANDLE_T(bgfx_indirect_buffer_handle); BGFX_HANDLE_T(bgfx_dynamic_index_buffer_handle); BGFX_HANDLE_T(bgfx_dynamic_vertex_buffer_handle); BGFX_HANDLE_T(bgfx_frame_buffer_handle); BGFX_HANDLE_T(bgfx_index_buffer_handle); BGFX_HANDLE_T(bgfx_program_handle); BGFX_HANDLE_T(bgfx_shader_handle); BGFX_HANDLE_T(bgfx_texture_handle); BGFX_HANDLE_T(bgfx_uniform_handle); BGFX_HANDLE_T(bgfx_vertex_buffer_handle); BGFX_HANDLE_T(bgfx_vertex_decl_handle); #undef BGFX_HANDLE_T /**/ typedef void (*bgfx_release_fn_t)(void* _ptr, void* _userData); /**/ typedef struct bgfx_memory { uint8_t* data; uint32_t size; } bgfx_memory_t; /**/ typedef struct bgfx_transform { float* data; uint16_t num; } bgfx_transform_t; /**/ typedef struct bgfx_hmd_eye { float rotation[4]; float translation[3]; float fov[4]; float adjust[3]; float pixelsPerTanAngle[2]; } bgfx_hmd_eye_t; /**/ typedef struct bgfx_hmd { bgfx_hmd_eye_t eye[2]; uint16_t width; uint16_t height; uint32_t deviceWidth; uint32_t deviceHeight; uint8_t flags; } bgfx_hmd_t; /**/ typedef struct bgfx_stats { uint64_t cpuTime; uint64_t cpuTimerFreq; uint64_t gpuTime; uint64_t gpuTimerFreq; } bgfx_stats_t; /**/ typedef struct bgfx_vertex_decl { uint32_t hash; uint16_t stride; uint16_t offset[BGFX_ATTRIB_COUNT]; uint16_t attributes[BGFX_ATTRIB_COUNT]; } bgfx_vertex_decl_t; /**/ typedef struct bgfx_transient_index_buffer { uint8_t* data; uint32_t size; bgfx_index_buffer_handle_t handle; uint32_t startIndex; } bgfx_transient_index_buffer_t; /**/ typedef struct bgfx_transient_vertex_buffer { uint8_t* data; uint32_t size; uint32_t startVertex; uint16_t stride; bgfx_vertex_buffer_handle_t handle; bgfx_vertex_decl_handle_t decl; } bgfx_transient_vertex_buffer_t; /**/ typedef struct bgfx_instance_data_buffer { uint8_t* data; uint32_t size; uint32_t offset; uint32_t num; uint16_t stride; bgfx_vertex_buffer_handle_t handle; } bgfx_instance_data_buffer_t; /**/ typedef struct bgfx_texture_info { bgfx_texture_format_t format; uint32_t storageSize; uint16_t width; uint16_t height; uint16_t depth; uint8_t numMips; uint8_t bitsPerPixel; bool cubeMap; } bgfx_texture_info_t; /**/ typedef struct bgfx_caps_gpu { uint16_t vendorId; uint16_t deviceId; } bgfx_caps_gpu_t; /**/ typedef struct bgfx_caps { bgfx_renderer_type_t rendererType; uint64_t supported; uint32_t maxDrawCalls; uint16_t maxTextureSize; uint16_t maxViews; uint8_t maxFBAttachments; uint8_t numGPUs; uint16_t vendorId; uint16_t deviceId; bgfx_caps_gpu_t gpu[4]; uint16_t formats[BGFX_TEXTURE_FORMAT_COUNT]; } bgfx_caps_t; /**/ typedef enum bgfx_fatal { BGFX_FATAL_DEBUG_CHECK, BGFX_FATAL_MINIMUM_REQUIRED_SPECS, BGFX_FATAL_INVALID_SHADER, BGFX_FATAL_UNABLE_TO_INITIALIZE, BGFX_FATAL_UNABLE_TO_CREATE_TEXTURE, BGFX_FATAL_DEVICE_LOST, BGFX_FATAL_COUNT } bgfx_fatal_t; #ifndef BGFX_SHARED_LIB_BUILD # define BGFX_SHARED_LIB_BUILD 0 #endif // BGFX_SHARED_LIB_BUILD #ifndef BGFX_SHARED_LIB_USE # define BGFX_SHARED_LIB_USE 0 #endif // BGFX_SHARED_LIB_USE #if defined(_MSC_VER) # if BGFX_SHARED_LIB_BUILD # define BGFX_SHARED_LIB_API __declspec(dllexport) # elif BGFX_SHARED_LIB_USE # define BGFX_SHARED_LIB_API __declspec(dllimport) # else # define BGFX_SHARED_LIB_API # endif // BGFX_SHARED_LIB_* #else # define BGFX_SHARED_LIB_API #endif // defined(_MSC_VER) #if defined(__cplusplus) # define BGFX_C_API extern "C" BGFX_SHARED_LIB_API #else # define BGFX_C_API BGFX_SHARED_LIB_API #endif // defined(__cplusplus) /**/ typedef struct bgfx_callback_interface { const struct bgfx_callback_vtbl* vtbl; } bgfx_callback_interface_t; /**/ typedef struct bgfx_callback_vtbl { void (*fatal)(bgfx_callback_interface_t* _this, bgfx_fatal_t _code, const char* _str); void (*trace_vargs)(bgfx_callback_interface_t* _this, const char* _filePath, uint16_t _line, const char* _format, va_list _argList); uint32_t (*cache_read_size)(bgfx_callback_interface_t* _this, uint64_t _id); bool (*cache_read)(bgfx_callback_interface_t* _this, uint64_t _id, void* _data, uint32_t _size); void (*cache_write)(bgfx_callback_interface_t* _this, uint64_t _id, const void* _data, uint32_t _size); void (*screen_shot)(bgfx_callback_interface_t* _this, const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip); void (*capture_begin)(bgfx_callback_interface_t* _this, uint32_t _width, uint32_t _height, uint32_t _pitch, bgfx_texture_format_t _format, bool _yflip); void (*capture_end)(bgfx_callback_interface_t* _this); void (*capture_frame)(bgfx_callback_interface_t* _this, const void* _data, uint32_t _size); } bgfx_callback_vtbl_t; /**/ typedef struct bgfx_reallocator_interface { const struct bgfx_reallocator_vtbl* vtbl; } bgfx_reallocator_interface_t; /**/ typedef struct bgfx_reallocator_vtbl { void* (*alloc)(bgfx_reallocator_interface_t* _this, size_t _size, size_t _align, const char* _file, uint32_t _line); void (*free)(bgfx_reallocator_interface_t* _this, void* _ptr, size_t _align, const char* _file, uint32_t _line); void* (*realloc)(bgfx_reallocator_interface_t* _this, void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line); } bgfx_reallocator_vtbl_t; /**/ BGFX_C_API void bgfx_vertex_decl_begin(bgfx_vertex_decl_t* _decl, bgfx_renderer_type_t _renderer); /**/ BGFX_C_API void bgfx_vertex_decl_add(bgfx_vertex_decl_t* _decl, bgfx_attrib_t _attrib, uint8_t _num, bgfx_attrib_type_t _type, bool _normalized, bool _asInt); /**/ BGFX_C_API void bgfx_vertex_decl_skip(bgfx_vertex_decl_t* _decl, uint8_t _num); /**/ BGFX_C_API void bgfx_vertex_decl_end(bgfx_vertex_decl_t* _decl); /**/ BGFX_C_API void bgfx_vertex_pack(const float _input[4], bool _inputNormalized, bgfx_attrib_t _attr, const bgfx_vertex_decl_t* _decl, void* _data, uint32_t _index); /**/ BGFX_C_API void bgfx_vertex_unpack(float _output[4], bgfx_attrib_t _attr, const bgfx_vertex_decl_t* _decl, const void* _data, uint32_t _index); /**/ BGFX_C_API void bgfx_vertex_convert(const bgfx_vertex_decl_t* _destDecl, void* _destData, const bgfx_vertex_decl_t* _srcDecl, const void* _srcData, uint32_t _num); /**/ BGFX_C_API uint16_t bgfx_weld_vertices(uint16_t* _output, const bgfx_vertex_decl_t* _decl, const void* _data, uint16_t _num, float _epsilon); /**/ BGFX_C_API void bgfx_image_swizzle_bgra8(uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _src, void* _dst); /**/ BGFX_C_API void bgfx_image_rgba8_downsample_2x2(uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _src, void* _dst); /**/ BGFX_C_API uint8_t bgfx_get_supported_renderers(bgfx_renderer_type_t _enum[BGFX_RENDERER_TYPE_COUNT]); /**/ BGFX_C_API const char* bgfx_get_renderer_name(bgfx_renderer_type_t _type); /**/ BGFX_C_API bool bgfx_init(bgfx_renderer_type_t _type, uint16_t _vendorId, uint16_t _deviceId, bgfx_callback_interface_t* _callback, bgfx_reallocator_interface_t* _allocator); /**/ BGFX_C_API void bgfx_shutdown(); /**/ BGFX_C_API void bgfx_reset(uint32_t _width, uint32_t _height, uint32_t _flags); /**/ BGFX_C_API uint32_t bgfx_frame(); /**/ BGFX_C_API bgfx_renderer_type_t bgfx_get_renderer_type(); /**/ BGFX_C_API const bgfx_caps_t* bgfx_get_caps(); /**/ BGFX_C_API const bgfx_hmd_t* bgfx_get_hmd(); /**/ BGFX_C_API const bgfx_stats_t* bgfx_get_stats(); /**/ BGFX_C_API const bgfx_memory_t* bgfx_alloc(uint32_t _size); /**/ BGFX_C_API const bgfx_memory_t* bgfx_copy(const void* _data, uint32_t _size); /**/ BGFX_C_API const bgfx_memory_t* bgfx_make_ref(const void* _data, uint32_t _size); /**/ BGFX_C_API const bgfx_memory_t* bgfx_make_ref_release(const void* _data, uint32_t _size, bgfx_release_fn_t _releaseFn, void* _userData); /**/ BGFX_C_API void bgfx_set_debug(uint32_t _debug); /**/ BGFX_C_API void bgfx_dbg_text_clear(uint8_t _attr, bool _small); /**/ BGFX_C_API void bgfx_dbg_text_printf(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, ...); /**/ BGFX_C_API void bgfx_dbg_text_image(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const void* _data, uint16_t _pitch); /**/ BGFX_C_API bgfx_index_buffer_handle_t bgfx_create_index_buffer(const bgfx_memory_t* _mem, uint16_t _flags); /**/ BGFX_C_API void bgfx_destroy_index_buffer(bgfx_index_buffer_handle_t _handle); /**/ BGFX_C_API bgfx_vertex_buffer_handle_t bgfx_create_vertex_buffer(const bgfx_memory_t* _mem, const bgfx_vertex_decl_t* _decl, uint16_t _flags); /**/ BGFX_C_API void bgfx_destroy_vertex_buffer(bgfx_vertex_buffer_handle_t _handle); /**/ BGFX_C_API bgfx_dynamic_index_buffer_handle_t bgfx_create_dynamic_index_buffer(uint32_t _num, uint16_t _flags); /**/ BGFX_C_API bgfx_dynamic_index_buffer_handle_t bgfx_create_dynamic_index_buffer_mem(const bgfx_memory_t* _mem, uint16_t _flags); /**/ BGFX_C_API void bgfx_update_dynamic_index_buffer(bgfx_dynamic_index_buffer_handle_t _handle, uint32_t _startIndex, const bgfx_memory_t* _mem); /**/ BGFX_C_API void bgfx_destroy_dynamic_index_buffer(bgfx_dynamic_index_buffer_handle_t _handle); /**/ BGFX_C_API bgfx_dynamic_vertex_buffer_handle_t bgfx_create_dynamic_vertex_buffer(uint32_t _num, const bgfx_vertex_decl_t* _decl, uint16_t _flags); /**/ BGFX_C_API bgfx_dynamic_vertex_buffer_handle_t bgfx_create_dynamic_vertex_buffer_mem(const bgfx_memory_t* _mem, const bgfx_vertex_decl_t* _decl, uint16_t _flags); /**/ BGFX_C_API void bgfx_update_dynamic_vertex_buffer(bgfx_dynamic_vertex_buffer_handle_t _handle, uint32_t _startVertex, const bgfx_memory_t* _mem); /**/ BGFX_C_API void bgfx_destroy_dynamic_vertex_buffer(bgfx_dynamic_vertex_buffer_handle_t _handle); /**/ BGFX_C_API bool bgfx_check_avail_transient_index_buffer(uint32_t _num); /**/ BGFX_C_API bool bgfx_check_avail_transient_vertex_buffer(uint32_t _num, const bgfx_vertex_decl_t* _decl); /**/ BGFX_C_API bool bgfx_check_avail_instance_data_buffer(uint32_t _num, uint16_t _stride); /**/ BGFX_C_API bool bgfx_check_avail_transient_buffers(uint32_t _numVertices, const bgfx_vertex_decl_t* _decl, uint32_t _numIndices); /**/ BGFX_C_API void bgfx_alloc_transient_index_buffer(bgfx_transient_index_buffer_t* _tib, uint32_t _num); /**/ BGFX_C_API void bgfx_alloc_transient_vertex_buffer(bgfx_transient_vertex_buffer_t* _tvb, uint32_t _num, const bgfx_vertex_decl_t* _decl); /**/ BGFX_C_API bool bgfx_alloc_transient_buffers(bgfx_transient_vertex_buffer_t* _tvb, const bgfx_vertex_decl_t* _decl, uint32_t _numVertices, bgfx_transient_index_buffer_t* _tib, uint32_t _numIndices); /**/ BGFX_C_API const bgfx_instance_data_buffer_t* bgfx_alloc_instance_data_buffer(uint32_t _num, uint16_t _stride); /**/ BGFX_C_API bgfx_indirect_buffer_handle_t bgfx_create_indirect_buffer(uint32_t _num); /**/ BGFX_C_API void bgfx_destroy_indirect_buffer(bgfx_indirect_buffer_handle_t _handle); /**/ BGFX_C_API bgfx_shader_handle_t bgfx_create_shader(const bgfx_memory_t* _mem); /**/ BGFX_C_API uint16_t bgfx_get_shader_uniforms(bgfx_shader_handle_t _handle, bgfx_uniform_handle_t* _uniforms, uint16_t _max); /**/ BGFX_C_API void bgfx_destroy_shader(bgfx_shader_handle_t _handle); /**/ BGFX_C_API bgfx_program_handle_t bgfx_create_program(bgfx_shader_handle_t _vsh, bgfx_shader_handle_t _fsh, bool _destroyShaders); /**/ BGFX_C_API bgfx_program_handle_t bgfx_create_compute_program(bgfx_shader_handle_t _csh, bool _destroyShaders); /**/ BGFX_C_API void bgfx_destroy_program(bgfx_program_handle_t _handle); /**/ BGFX_C_API void bgfx_calc_texture_size(bgfx_texture_info_t* _info, uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, uint8_t _numMips, bgfx_texture_format_t _format); /**/ BGFX_C_API bgfx_texture_handle_t bgfx_create_texture(const bgfx_memory_t* _mem, uint32_t _flags, uint8_t _skip, bgfx_texture_info_t* _info); /**/ BGFX_C_API bgfx_texture_handle_t bgfx_create_texture_2d(uint16_t _width, uint16_t _height, uint8_t _numMips, bgfx_texture_format_t _format, uint32_t _flags, const bgfx_memory_t* _mem); /**/ BGFX_C_API bgfx_texture_handle_t bgfx_create_texture_2d_scaled(bgfx_backbuffer_ratio_t _ratio, uint8_t _numMips, bgfx_texture_format_t _format, uint32_t _flags); /**/ BGFX_C_API bgfx_texture_handle_t bgfx_create_texture_3d(uint16_t _width, uint16_t _height, uint16_t _depth, uint8_t _numMips, bgfx_texture_format_t _format, uint32_t _flags, const bgfx_memory_t* _mem); /**/ BGFX_C_API bgfx_texture_handle_t bgfx_create_texture_cube(uint16_t _size, uint8_t _numMips, bgfx_texture_format_t _format, uint32_t _flags, const bgfx_memory_t* _mem); /**/ BGFX_C_API void bgfx_update_texture_2d(bgfx_texture_handle_t _handle, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const bgfx_memory_t* _mem, uint16_t _pitch); /**/ BGFX_C_API void bgfx_update_texture_3d(bgfx_texture_handle_t _handle, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _width, uint16_t _height, uint16_t _depth, const bgfx_memory_t* _mem); /**/ BGFX_C_API void bgfx_update_texture_cube(bgfx_texture_handle_t _handle, uint8_t _side, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const bgfx_memory_t* _mem, uint16_t _pitch); /**/ BGFX_C_API void bgfx_destroy_texture(bgfx_texture_handle_t _handle); /**/ BGFX_C_API bgfx_frame_buffer_handle_t bgfx_create_frame_buffer(uint16_t _width, uint16_t _height, bgfx_texture_format_t _format, uint32_t _textureFlags); /**/ BGFX_C_API bgfx_frame_buffer_handle_t bgfx_create_frame_buffer_scaled(bgfx_backbuffer_ratio_t _ratio, bgfx_texture_format_t _format, uint32_t _textureFlags); /**/ BGFX_C_API bgfx_frame_buffer_handle_t bgfx_create_frame_buffer_from_handles(uint8_t _num, const bgfx_texture_handle_t* _handles, bool _destroyTextures); /**/ BGFX_C_API bgfx_frame_buffer_handle_t bgfx_create_frame_buffer_from_nwh(void* _nwh, uint16_t _width, uint16_t _height, bgfx_texture_format_t _depthFormat); /**/ BGFX_C_API void bgfx_destroy_frame_buffer(bgfx_frame_buffer_handle_t _handle); /**/ BGFX_C_API bgfx_uniform_handle_t bgfx_create_uniform(const char* _name, bgfx_uniform_type_t _type, uint16_t _num); /**/ BGFX_C_API void bgfx_destroy_uniform(bgfx_uniform_handle_t _handle); /**/ BGFX_C_API void bgfx_set_palette_color(uint8_t _index, const float _rgba[4]); /**/ BGFX_C_API void bgfx_set_view_name(uint8_t _id, const char* _name); /**/ BGFX_C_API void bgfx_set_view_rect(uint8_t _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height); /**/ BGFX_C_API void bgfx_set_view_scissor(uint8_t _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height); /**/ BGFX_C_API void bgfx_set_view_clear(uint8_t _id, uint16_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil); /**/ BGFX_C_API void bgfx_set_view_clear_mrt(uint8_t _id, uint16_t _flags, float _depth, uint8_t _stencil, uint8_t _0, uint8_t _1, uint8_t _2, uint8_t _3, uint8_t _4, uint8_t _5, uint8_t _6, uint8_t _7); /**/ BGFX_C_API void bgfx_set_view_seq(uint8_t _id, bool _enabled); /**/ BGFX_C_API void bgfx_set_view_frame_buffer(uint8_t _id, bgfx_frame_buffer_handle_t _handle); /**/ BGFX_C_API void bgfx_set_view_transform(uint8_t _id, const void* _view, const void* _proj); /**/ BGFX_C_API void bgfx_set_view_transform_stereo(uint8_t _id, const void* _view, const void* _projL, uint8_t _flags, const void* _projR); /**/ BGFX_C_API void bgfx_set_view_remap(uint8_t _id, uint8_t _num, const void* _remap); /**/ BGFX_C_API void bgfx_set_marker(const char* _marker); /**/ BGFX_C_API void bgfx_set_state(uint64_t _state, uint32_t _rgba); /**/ BGFX_C_API void bgfx_set_stencil(uint32_t _fstencil, uint32_t _bstencil); /**/ BGFX_C_API uint16_t bgfx_set_scissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height); /**/ BGFX_C_API void bgfx_set_scissor_cached(uint16_t _cache); /**/ BGFX_C_API uint32_t bgfx_set_transform(const void* _mtx, uint16_t _num); /**/ BGFX_C_API uint32_t bgfx_alloc_transform(bgfx_transform_t* _transform, uint16_t _num); /**/ BGFX_C_API void bgfx_set_transform_cached(uint32_t _cache, uint16_t _num); /**/ BGFX_C_API void bgfx_set_uniform(bgfx_uniform_handle_t _handle, const void* _value, uint16_t _num); /**/ BGFX_C_API void bgfx_set_index_buffer(bgfx_index_buffer_handle_t _handle, uint32_t _firstIndex, uint32_t _numIndices); /**/ BGFX_C_API void bgfx_set_dynamic_index_buffer(bgfx_dynamic_index_buffer_handle_t _handle, uint32_t _firstIndex, uint32_t _numIndices); /**/ BGFX_C_API void bgfx_set_transient_index_buffer(const bgfx_transient_index_buffer_t* _tib, uint32_t _firstIndex, uint32_t _numIndices); /**/ BGFX_C_API void bgfx_set_vertex_buffer(bgfx_vertex_buffer_handle_t _handle, uint32_t _startVertex, uint32_t _numVertices); /**/ BGFX_C_API void bgfx_set_dynamic_vertex_buffer(bgfx_dynamic_vertex_buffer_handle_t _handle, uint32_t _numVertices); /**/ BGFX_C_API void bgfx_set_transient_vertex_buffer(const bgfx_transient_vertex_buffer_t* _tvb, uint32_t _startVertex, uint32_t _numVertices); /**/ BGFX_C_API void bgfx_set_instance_data_buffer(const bgfx_instance_data_buffer_t* _idb, uint32_t _num); /**/ BGFX_C_API void bgfx_set_instance_data_from_vertex_buffer(bgfx_vertex_buffer_handle_t _handle, uint32_t _startVertex, uint32_t _num); /**/ BGFX_C_API void bgfx_set_instance_data_from_dynamic_vertex_buffer(bgfx_dynamic_vertex_buffer_handle_t _handle, uint32_t _startVertex, uint32_t _num); /**/ BGFX_C_API void bgfx_set_texture(uint8_t _stage, bgfx_uniform_handle_t _sampler, bgfx_texture_handle_t _handle, uint32_t _flags); /**/ BGFX_C_API void bgfx_set_texture_from_frame_buffer(uint8_t _stage, bgfx_uniform_handle_t _sampler, bgfx_frame_buffer_handle_t _handle, uint8_t _attachment, uint32_t _flags); /**/ BGFX_C_API uint32_t bgfx_touch(uint8_t _id); /**/ BGFX_C_API uint32_t bgfx_submit(uint8_t _id, bgfx_program_handle_t _handle, int32_t _depth); /**/ BGFX_C_API uint32_t bgfx_submit_indirect(uint8_t _id, bgfx_program_handle_t _handle, bgfx_indirect_buffer_handle_t _indirectHandle, uint16_t _start, uint16_t _num, int32_t _depth); /**/ BGFX_C_API void bgfx_set_image(uint8_t _stage, bgfx_uniform_handle_t _sampler, bgfx_texture_handle_t _handle, uint8_t _mip, bgfx_access_t _access, bgfx_texture_format_t _format); /**/ BGFX_C_API void bgfx_set_image_from_frame_buffer(uint8_t _stage, bgfx_uniform_handle_t _sampler, bgfx_frame_buffer_handle_t _handle, uint8_t _attachment, bgfx_access_t _access, bgfx_texture_format_t _format); /**/ BGFX_C_API void bgfx_set_compute_index_buffer(uint8_t _stage, bgfx_index_buffer_handle_t _handle, bgfx_access_t _access); /**/ BGFX_C_API void bgfx_set_compute_vertex_buffer(uint8_t _stage, bgfx_vertex_buffer_handle_t _handle, bgfx_access_t _access); /**/ BGFX_C_API void bgfx_set_compute_dynamic_index_buffer(uint8_t _stage, bgfx_dynamic_index_buffer_handle_t _handle, bgfx_access_t _access); /**/ BGFX_C_API void bgfx_set_compute_dynamic_vertex_buffer(uint8_t _stage, bgfx_dynamic_vertex_buffer_handle_t _handle, bgfx_access_t _access); /**/ BGFX_C_API void bgfx_set_compute_indirect_buffer(uint8_t _stage, bgfx_indirect_buffer_handle_t _handle, bgfx_access_t _access); /**/ BGFX_C_API uint32_t bgfx_dispatch(uint8_t _id, bgfx_program_handle_t _handle, uint16_t _numX, uint16_t _numY, uint16_t _numZ, uint8_t _flags); /**/ BGFX_C_API uint32_t bgfx_dispatch_indirect(uint8_t _id, bgfx_program_handle_t _handle, bgfx_indirect_buffer_handle_t _indirectHandle, uint16_t _start, uint16_t _num, uint8_t _flags); /**/ BGFX_C_API void bgfx_discard(); /**/ BGFX_C_API void bgfx_blit(uint8_t _id, bgfx_texture_handle_t _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, bgfx_texture_handle_t _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth); /**/ BGFX_C_API void bgfx_save_screen_shot(const char* _filePath); #endif // BGFX_C99_H_HEADER_GUARD
{ "content_hash": "03c49de9140fff1b17647fd6fb68001a", "timestamp": "", "source": "github", "line_count": 774, "max_line_length": 277, "avg_line_length": 31.543927648578812, "alnum_prop": 0.7041982387876305, "repo_name": "cuavas/bgfx", "id": "534c13f1f50503b085df1b22df8be18c08b2633d", "size": "24586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/bgfx/c99/bgfx.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "116453" }, { "name": "C++", "bytes": "1387656" }, { "name": "Lua", "bytes": "19203" }, { "name": "Makefile", "bytes": "16587" }, { "name": "Objective-C", "bytes": "146566" }, { "name": "Objective-C++", "bytes": "105087" }, { "name": "Scala", "bytes": "231" }, { "name": "Shell", "bytes": "19931" }, { "name": "SuperCollider", "bytes": "3999" } ], "symlink_target": "" }
<?php namespace Openbuildings\Postmark\Test; use Openbuildings\Postmark\Api; use PHPUnit\Framework\TestCase; /** * @covers \Openbuildings\Postmark\Api * @group api */ class ApiTest extends TestCase { public function testConstructor() { $api = new Api(); $this->assertNull($api->getToken()); $api = new Api('token'); $this->assertEquals('token', $api->getToken()); } public function testSetToken() { $api = new Api(); $api->setToken('token'); $this->assertEquals('token', $api->getToken()); } public function testGetToken() { $api = new Api(); $this->assertNull($api->getToken()); $api = new Api('custom token'); $this->assertEquals('custom token', $api->getToken()); $api->setToken('another token'); $this->assertEquals('another token', $api->getToken()); } public function testGetHeaders() { $expected = array( 'Accept: application/json', 'Content-Type: application/json', 'X-Postmark-Server-Token: custom token', ); $api = new Api('custom token'); $this->assertEquals($expected, $api->getHeaders()); } public function testGetHeadersNoTokenException() { $api = new Api(); $this->expectException('Exception'); $this->expectExceptionMessage('You must set postmark token'); $api->getHeaders(); } public function testSendWrongEmail() { $api = new Api('POSTMARK_API_TEST'); $this->expectException('Exception'); $this->expectExceptionMessage(sprintf( "Postmark delivery failed: Error parsing 'To': Illegal email domain '%s' in address '%s'", 'example.com>', 'Jimmy Kenno <test_email@example.com>' )); $response = $api->send( array( 'From' => 'support@example.com', 'To' => '"Jimmy Kenno <test_email@example.com>"', 'Subject' => 'Test', 'TextBody' => 'Hello', ) ); } public function testSend() { $api = new Api('POSTMARK_API_TEST'); $response = $api->send( array( 'From' => 'Mark Smith <support@example.com>', 'To' => 'test_email@example.com,test_email2@example.com,test_email3@example.com', 'Subject' => 'Test', 'HtmlBody' => '<b>Hello</b>', 'TextBody' => 'Hello', 'ReplyTo' => 'reply@example.com', 'Cc' => 'test2_email@example.com,"Tom ,\'\\" Smith" <test4_email@example.com>', 'Bcc' => 'test3_email@example.com,test5_email@example.com', 'Attachments' => array( array( 'Name' => 'readme.txt', 'Content' => 'dGVzdCBjb250ZW50', 'ContentType' => 'text/plain' ), array( 'Name' => 'report.pdf', 'Content' => 'dGVzdCBjb250ZW50', 'ContentType' => 'application/octet-stream' ) ) ) ); $this->assertArrayHasKey('To', $response); $this->assertArrayHasKey('SubmittedAt', $response); $this->assertArrayHasKey('MessageID', $response); $this->assertArrayHasKey('ErrorCode', $response); $this->assertArrayHasKey('Message', $response); $this->assertEquals(0, $response['ErrorCode']); $this->assertThat( $response['Message'], $this->logicalOr( $this->equalTo('Test job accepted'), $this->equalTo('Message accepted, but delivery may be delayed.') ) ); $this->expectException('Openbuildings\Postmark\Exception'); $this->expectExceptionMessage('Postmark delivery failed: Invalid \'From\' value.'); $this->expectExceptionCode(300); $response = $api->send(array( 'Wrong' => 'support@example.com', )); } public function testIsSecure() { $api = new Api(); $this->assertTrue($api->isSecure()); $api->setSecure(false); $this->assertFalse($api->isSecure()); $api->setSecure(true); $this->assertTrue($api->isSecure()); } public function testSetSecure() { $api = new Api(); $this->assertSame($api, $api->setSecure(false)); $this->assertFalse($api->isSecure()); $api->setSecure(true); $this->assertTrue($api->isSecure()); } public function testGetSendUri() { $api = new Api(); $this->assertEquals(Api::SEND_URI_SECURE, $api->getSendUri()); $api->setSecure(false); $this->assertEquals(Api::SEND_URI, $api->getSendUri()); $api->setSecure(true); $this->assertEquals(Api::SEND_URI_SECURE, $api->getSendUri()); } public function testSendWrongJson() { $apiMock = $this->getMockBuilder('Openbuildings\Postmark\Api') ->setMethods(array('getSendUri')) ->setConstructorArgs(array('POSTMARK_API_TEST')) ->getMock(); $pathToWrongJson = 'file://'.realpath(__DIR__.'/../test_data/wrong-json.json'); $apiMock ->expects($this->once()) ->method('getSendUri') ->will($this->returnValue($pathToWrongJson)); $this->expectException('Exception'); $this->expectExceptionMessage('Postmark delivery failed: wrong json response'); $response = $apiMock->send(array( 'From' => 'Mark Smith <support@example.com>', 'To' => 'test_email@example.com,test_email2@example.com,test_email3@example.com', 'Subject' => 'Test', 'HtmlBody' => '<b>Hello</b>', 'TextBody' => 'Hello', 'ReplyTo' => 'reply@example.com', )); } }
{ "content_hash": "a1da14dc9d5f6f4f3cd789ef4ae92ca1", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 102, "avg_line_length": 30.685279187817258, "alnum_prop": 0.5232423490488006, "repo_name": "OpenBuildings/postmark", "id": "bbcdc772e8d3a5bb0740eb1227a8788a0096d315", "size": "6045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/src/ApiTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "39326" } ], "symlink_target": "" }
.class Landroid/support/v4/app/TaskStackBuilder$TaskStackBuilderImplJellybean; .super Ljava/lang/Object; .source "TaskStackBuilder.java" # interfaces .implements Landroid/support/v4/app/TaskStackBuilder$TaskStackBuilderImpl; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/support/v4/app/TaskStackBuilder; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x8 name = "TaskStackBuilderImplJellybean" .end annotation # direct methods .method constructor <init>()V .registers 1 .prologue .line 101 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public getPendingIntent(Landroid/content/Context;[Landroid/content/Intent;IILandroid/os/Bundle;)Landroid/app/PendingIntent; .registers 9 .param p1, "context" # Landroid/content/Context; .param p2, "intents" # [Landroid/content/Intent; .param p3, "requestCode" # I .param p4, "flags" # I .param p5, "options" # Landroid/os/Bundle; .prologue const/4 v2, 0x0 .line 104 new-instance v0, Landroid/content/Intent; aget-object v1, p2, v2 invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Landroid/content/Intent;)V const v1, 0x1000c000 invoke-virtual {v0, v1}, Landroid/content/Intent;->addFlags(I)Landroid/content/Intent; move-result-object v0 aput-object v0, p2, v2 .line 107 invoke-static {p1, p3, p2, p4, p5}, Landroid/support/v4/app/TaskStackBuilderJellybean;->getActivitiesPendingIntent(Landroid/content/Context;I[Landroid/content/Intent;ILandroid/os/Bundle;)Landroid/app/PendingIntent; move-result-object v0 return-object v0 .end method
{ "content_hash": "431905cb02810397629b9c58eb2b082a", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 218, "avg_line_length": 26.984615384615385, "alnum_prop": 0.7263397947548461, "repo_name": "shenxdtw/PokemonGo-Plugin", "id": "710e18d65bb53efbdde2e8e5f1a1f1780b01d791", "size": "1754", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "PokemonGo_Smali/android/support/v4/app/TaskStackBuilder$TaskStackBuilderImplJellybean.smali", "mode": "33188", "license": "mit", "language": [ { "name": "Smali", "bytes": "35925787" } ], "symlink_target": "" }
import commentApi from '../../api/commentApi' import * as types from '../mutation-types' const state = { currStatementComments: [] } const getters = { currStatementComments: state => state.currStatementComments, currStatementCommentCount: state => state.currStatementComments.length } const actions = { initComments ({commit}, stmtId) { commentApi.getComments(stmtId, data => { commit(types.SET_CURRSTATEMENT_COMMENTS, {data}) }) }, addComment ({commit}, payload) { commentApi.addComment(payload, () => { commit(types.ADD_STATEMENT_STMTCOMMENTCOUNT) }) }, deleteComment ({commit}, payload) { commentApi.deleteComment(payload, () => { commit(types.DECLARE_STATEMENT_STMTCOMMENTCOUNT) commit(types.DELETE_COMMENT, payload.cmtId) }) } } const mutations = { [types.SET_CURRSTATEMENT_COMMENTS] (state, {data}) { state.currStatementComments = data }, [types.DELETE_COMMENT] (state, cmtId) { for (let i = 0; i < state.currStatementComments.length; i++) { if (state.currStatementComments[i].cmtId === cmtId) { state.currStatementComments.splice(i, 1) } } }, [types.UPDATE_CMTPRAISECOUNT] (state, payload) { let count = payload.isPraised ? -1 : 1 state.currStatementComments.find(c => c.cmtId === payload.cmtId).cmtPraiseCount += count } } export default { state, getters, actions, mutations }
{ "content_hash": "5b08a3d144a61ba7a49382f52108c64b", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 90, "avg_line_length": 25.055555555555557, "alnum_prop": 0.6999260901699926, "repo_name": "shuangbofu/ustate", "id": "b153a5699c053b86b272b4a5893e80cfd248172a", "size": "1353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vue部分/ustate/temp/comment.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5645" }, { "name": "HTML", "bytes": "436" }, { "name": "Java", "bytes": "51644" }, { "name": "JavaScript", "bytes": "66544" }, { "name": "Vue", "bytes": "114741" } ], "symlink_target": "" }
status=published date=2009-12-30 tags=blog type=post title=Retrospectiva TáSafo 2009 ~~~~~~ Olá pessoal, preparamos um formulário para obter um feedback sobre a atuação do TáSafo em 2009 e esperamos a participação de todos. Nele, gostaríamos de levantar os pontos positivos e negativos relacionados a qualquer assunto que o grupo TáSafo tenha abordado em 2009 (ou deixado de abordar). Por exemplo, você gostou da cobertura dos eventos mas achou que faltou uma movimentação maior na lista de discussão? Opine! Não esqueça de dar sugestões para que ano que vem o TáSafo possa continuar a crescer e se tornar um grupo ainda mais comunitário e participativo. Na semana que vem (de 04/jan a 08/jan) nos reuniremos em algum lugar a ser definido para fazer uma retrospectiva presencial; juntaremos as informações coletadas através deste formulário para fazer uma retrospectiva, como a ensinada pessoalmente por Diana Larsen - autora do livro Agile Retrospectives: Making Good Teams Great. **A participação nessa retrospectiva é aberta a todos**. Apesar das férias e festas de final de ano a participação dos que ficarem em Belém será muito apreciada. No formulário também há um espaço para sugerir o local onde ocorrerá a retrospectiva. Só para refrescar a memória, algumas das principais realizações do TáSafo este ano foram: a cobertura dos eventos Porto Alegre Agile Weekend, Fisl e Ágiles; a realização dos eventos Visão Ágil Academic Meeting (VAAM) e Maré de Agilidade; e o workshop Agile Software Development with Extreme Programming. Acesse o formulário sobre a retrospectiva [aqui](http://spreadsheets.google.com/viewform?formkey=dFp3ZEZOalUtRkxlTm5Ea3FMSS1teUE6MA).
{ "content_hash": "8e729f1c4a99d859da57772d7394f9b5", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 574, "avg_line_length": 98.41176470588235, "alnum_prop": 0.8147041243275552, "repo_name": "aldrinleal/www.tasafo.com.br", "id": "7598f732276cecb492c5f35e18f6d0c84a76bda4", "size": "1724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/jbake/content/blog/2009/retrospectiva-tasafo-2009.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "29973" }, { "name": "Java", "bytes": "8261" } ], "symlink_target": "" }
package org.apache.samza.util; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import com.google.common.collect.ImmutableMap; import org.apache.samza.config.ApplicationConfig; import org.apache.samza.config.Config; import org.apache.samza.config.MapConfig; import org.apache.samza.config.TaskConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(Util.class) // need this to be able to use powermock with system classes like InetAddress public class TestUtil { @Test public void testEnvVarEscape() { // no special characters in original String noSpecialCharacters = "hello world 123 .?! '"; assertEquals(noSpecialCharacters, Util.envVarEscape(noSpecialCharacters)); String withSpecialCharacters = "quotation \" backslash \\ grave accent `"; String escaped = "quotation \\\" backslash \\\\ grave accent \\`"; assertEquals(escaped, Util.envVarEscape(withSpecialCharacters)); } /** * It's difficult to explicitly test having an actual version and using the fallback, due to the usage of methods of * Class. */ @Test public void testGetSamzaVersion() { String utilImplementationVersion = Util.class.getPackage().getImplementationVersion(); String expectedVersion = (utilImplementationVersion != null) ? utilImplementationVersion : Util.FALLBACK_VERSION; assertEquals(expectedVersion, Util.getSamzaVersion()); } /** * It's difficult to explicitly test having an actual version and using the fallback, due to the usage of methods of * Class. */ @Test public void testGetTaskClassVersion() { // cannot find app nor task assertEquals(Util.FALLBACK_VERSION, Util.getTaskClassVersion(new MapConfig())); // only app String appClassVersion = MyAppClass.class.getPackage().getImplementationVersion(); String expectedAppClassVersion = (appClassVersion != null) ? appClassVersion : Util.FALLBACK_VERSION; Config config = new MapConfig(ImmutableMap.of(ApplicationConfig.APP_CLASS, MyAppClass.class.getName())); assertEquals(expectedAppClassVersion, Util.getTaskClassVersion(config)); // only task String taskClassVersion = MyTaskClass.class.getPackage().getImplementationVersion(); String expectedTaskClassVersion = (taskClassVersion != null) ? taskClassVersion : Util.FALLBACK_VERSION; config = new MapConfig(ImmutableMap.of(TaskConfig.TASK_CLASS, MyTaskClass.class.getName())); assertEquals(expectedTaskClassVersion, Util.getTaskClassVersion(config)); // both app and task; choose app config = new MapConfig(ImmutableMap.of(ApplicationConfig.APP_CLASS, MyAppClass.class.getName(), // shouldn't even try to load the task class TaskConfig.TASK_CLASS, "this_is_not_a_class")); assertEquals(expectedAppClassVersion, Util.getTaskClassVersion(config)); } @Test public void testGetLocalHostNotLoopbackAddress() throws UnknownHostException { mockStatic(InetAddress.class); InetAddress inetAddressLocalHost = mock(InetAddress.class); when(inetAddressLocalHost.isLoopbackAddress()).thenReturn(false); when(InetAddress.getLocalHost()).thenReturn(inetAddressLocalHost); assertEquals(inetAddressLocalHost, Util.getLocalHost()); } @Test public void testGetLocalHostLoopbackAddressNoExternalAddressFound() throws Exception { mockStatic(InetAddress.class, NetworkInterface.class); InetAddress inetAddressLocalHost = mock(InetAddress.class); when(inetAddressLocalHost.isLoopbackAddress()).thenReturn(true); when(InetAddress.getLocalHost()).thenReturn(inetAddressLocalHost); // network interfaces return addresses which are not external InetAddress linkLocalAddress = mock(InetAddress.class); when(linkLocalAddress.isLinkLocalAddress()).thenReturn(true); InetAddress loopbackAddress = mock(InetAddress.class); when(loopbackAddress.isLinkLocalAddress()).thenReturn(false); when(loopbackAddress.isLoopbackAddress()).thenReturn(true); NetworkInterface networkInterface0 = mock(NetworkInterface.class); when(networkInterface0.getInetAddresses()).thenReturn( Collections.enumeration(Arrays.asList(linkLocalAddress, loopbackAddress))); NetworkInterface networkInterface1 = mock(NetworkInterface.class); when(networkInterface1.getInetAddresses()).thenReturn( Collections.enumeration(Collections.singletonList(loopbackAddress))); when(NetworkInterface.getNetworkInterfaces()).thenReturn( Collections.enumeration(Arrays.asList(networkInterface0, networkInterface1))); assertEquals(inetAddressLocalHost, Util.getLocalHost()); } @Test public void testGetLocalHostExternalInet4Address() throws Exception { mockStatic(InetAddress.class, NetworkInterface.class); InetAddress inetAddressLocalHost = mock(InetAddress.class); when(inetAddressLocalHost.isLoopbackAddress()).thenReturn(true); when(InetAddress.getLocalHost()).thenReturn(inetAddressLocalHost); InetAddress linkLocalAddress = mock(InetAddress.class); when(linkLocalAddress.isLinkLocalAddress()).thenReturn(true); Inet4Address externalInet4Address = mock(Inet4Address.class); when(externalInet4Address.isLinkLocalAddress()).thenReturn(false); when(externalInet4Address.isLoopbackAddress()).thenReturn(false); byte[] externalInet4AddressBytes = new byte[]{0, 1, 2, 3}; when(externalInet4Address.getAddress()).thenReturn(externalInet4AddressBytes); InetAddress otherExternalAddress = mock(InetAddress.class); // not Inet4Address when(otherExternalAddress.isLinkLocalAddress()).thenReturn(false); when(otherExternalAddress.isLoopbackAddress()).thenReturn(false); NetworkInterface networkInterfaceLinkLocal = mock(NetworkInterface.class); when(networkInterfaceLinkLocal.getInetAddresses()).thenReturn( Collections.enumeration(Collections.singletonList(linkLocalAddress))); NetworkInterface networkInterfaceExternal = mock(NetworkInterface.class); when(networkInterfaceExternal.getInetAddresses()).thenReturn( Collections.enumeration(Arrays.asList(otherExternalAddress, externalInet4Address))); when(NetworkInterface.getNetworkInterfaces()).thenReturn( Collections.enumeration(Arrays.asList(networkInterfaceLinkLocal, networkInterfaceExternal))); InetAddress finalInetAddress = mock(InetAddress.class); when(InetAddress.getByAddress(aryEq(externalInet4AddressBytes))).thenReturn(finalInetAddress); assertEquals(finalInetAddress, Util.getLocalHost()); } @Test public void testGetLocalHostExternalAddressNotInet4Address() throws Exception { mockStatic(InetAddress.class, NetworkInterface.class); InetAddress inetAddressLocalHost = mock(InetAddress.class); when(inetAddressLocalHost.isLoopbackAddress()).thenReturn(true); when(InetAddress.getLocalHost()).thenReturn(inetAddressLocalHost); byte[] externalAddressBytes = new byte[]{0, 1, 2, 3, 4, 5}; InetAddress externalAddress = mock(InetAddress.class); when(externalAddress.isLinkLocalAddress()).thenReturn(false); when(externalAddress.isLoopbackAddress()).thenReturn(false); when(externalAddress.getAddress()).thenReturn(externalAddressBytes); NetworkInterface networkInterface = mock(NetworkInterface.class); when(networkInterface.getInetAddresses()).thenReturn( Collections.enumeration(Collections.singletonList(externalAddress))); when(NetworkInterface.getNetworkInterfaces()).thenReturn( Collections.enumeration(Collections.singletonList(networkInterface))); InetAddress finalInetAddress = mock(InetAddress.class); when(InetAddress.getByAddress(aryEq(externalAddressBytes))).thenReturn(finalInetAddress); assertEquals(finalInetAddress, Util.getLocalHost()); } /** * No requirement for this test that this extends any other class. Just need some placeholder class. */ public static class MyAppClass { } /** * No requirement for this test that this extends any other class. Just need some placeholder class. */ public static class MyTaskClass { } }
{ "content_hash": "27cd678be8dc07c938a5ed4f8c3cf5d2", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 119, "avg_line_length": 46.94021739130435, "alnum_prop": 0.7777005904828065, "repo_name": "abhishekshivanna/samza", "id": "4fbd8cbc22ab0d0f332c3348dd94f8e9cde74300", "size": "9444", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "samza-core/src/test/java/org/apache/samza/util/TestUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4148" }, { "name": "HTML", "bytes": "13819" }, { "name": "Java", "bytes": "7183326" }, { "name": "JavaScript", "bytes": "3373" }, { "name": "Python", "bytes": "88154" }, { "name": "Scala", "bytes": "1145175" }, { "name": "Shell", "bytes": "48673" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
'use strict'; var invariant = require('invariant'); import type ContentBlock from 'ContentBlock'; import type {DraftRange} from 'DraftRange'; /** * Obtain the start and end positions of the range that has the * specified entity applied to it. * * Entity keys are applied only to contiguous stretches of text, so this * method searches for the first instance of the entity key and returns * the subsequent range. */ function getRangesForDraftEntity( block: ContentBlock, key: string ): Array<DraftRange> { var ranges = []; block.findEntityRanges( c => c.getEntity() === key, (start, end) => { ranges.push({start, end}); } ); invariant( !!ranges.length, 'Entity key not found in this range.' ); return ranges; } module.exports = getRangesForDraftEntity;
{ "content_hash": "c0c973ac137a306e87a19a271354623f", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 72, "avg_line_length": 21.289473684210527, "alnum_prop": 0.6860321384425216, "repo_name": "SciMts/draft-js", "id": "4f9937ebf6e65dcf99ea0f47a8f91bcdcb48ab4c", "size": "1187", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/model/modifier/getRangesForDraftEntity.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "24059" }, { "name": "JavaScript", "bytes": "620537" }, { "name": "Shell", "bytes": "1204" } ], "symlink_target": "" }
import asyncio import logging import regex import synapse.common as s_common import synapse.lib.scrape as s_scrape import synapse.lib.spooled as s_spooled import synapse.lib.stormtypes as s_stormtypes logger = logging.getLogger(__name__) @s_stormtypes.registry.registerLib class LibScrape(s_stormtypes.Lib): ''' A Storm Library for providing helpers for scraping nodes from text. ''' _storm_locals = ( {'name': 'context', 'desc': ''' Attempt to scrape information from a blob of text, getting the context information about the values found. Notes: This does call the ``scrape`` Storm interface if that behavior is enabled on the Cortex. Examples: Scrape some text and make nodes out of it:: for ($form, $valu, $info) in $lib.scrape.context($text) { [ ( *$form ?= $valu ) ] } ''', 'type': {'type': 'function', '_funcname': '_methContext', 'args': ( {'name': 'text', 'type': 'str', 'desc': 'The text to scrape', }, ), 'returns': {'name': 'yields', 'type': 'dict', 'desc': 'A dictionary of scraped values, rule types, and offsets scraped from the text.', }}}, {'name': 'ndefs', 'desc': ''' Attempt to scrape node form, value tuples from a blob of text. Examples: Scrape some text and attempt to make nodes out of it:: for ($form, $valu) in $lib.scrape($text) { [ ( *$form ?= $valu ) ] }''', 'type': {'type': 'function', '_funcname': '_methNdefs', 'args': ( {'name': 'text', 'type': 'str', 'desc': 'The text to scrape', }, ), 'returns': {'name': 'yields', 'type': 'list', 'desc': 'A list of (form, value) tuples scraped from the text.', }}}, {'name': 'genMatches', 'desc': ''' genMatches is a generic helper function for constructing scrape interfaces using pure Storm. It accepts the text, a regex pattern, and produce results that can easily be used to create Notes: The pattern must have a named regular expression match for the key ``valu`` using the named group syntax. For example ``(somekey\\s)(?P<valu>[a-z0-9]+)\\s``. Examples: A scrape implementation with a regex that matches name keys in text:: $re="(Name\\:\\s)(?P<valu>[a-z0-9]+)\\s" $form="ps:name" function scrape(text, form) { $ret = $lib.list() for ($valu, $info) in $lib.scrape.genMatches($text, $re) { $ret.append(($form, $valu, $info)) } return ( $ret ) } ''', 'type': {'type': 'function', '_funcname': '_methGenMatches', 'args': ( {'name': 'text', 'type': 'str', 'desc': 'The text to scrape', }, {'name': 'pattern', 'type': 'str', 'desc': 'The regular expression pattern to match against.', }, {'name': 'fangs', 'type': 'list', 'default': None, 'desc': 'A list of (src, dst) pairs to refang from text. The src must be equal or larger ' 'than the dst in length.'}, {'name': 'flags', 'type': 'int', 'default': regex.IGNORECASE, 'desc': 'Regex flags to use (defaults to IGNORECASE).'}, ), 'returns': {'name': 'yields', 'type': 'list', 'desc': ''}}} ) _storm_lib_path = ('scrape', ) def getObjLocals(self): return { 'ndefs': self._methNdefs, 'context': self._methContext, 'genMatches': self._methGenMatches, } async def __call__(self, text, ptype=None, refang=True, unique=True): text = await s_stormtypes.tostr(text) form = await s_stormtypes.tostr(ptype, noneok=True) refang = await s_stormtypes.tobool(refang) unique = await s_stormtypes.tobool(unique) # Remove this in 3.0.0 since it is deprecated. s_common.deprecated('Directly calling $lib.scrape()') await self.runt.warnonce('$lib.scrape() is deprecated. Use $lib.scrape.ndefs().') async with await s_spooled.Set.anit() as items: # type: s_spooled.Set for item in s_scrape.scrape(text, ptype=form, refang=refang, first=False): if unique: if item in items: continue await items.add(item) yield item await asyncio.sleep(0) @s_stormtypes.stormfunc(readonly=True) async def _methContext(self, text): text = await s_stormtypes.tostr(text) genr = self.runt.snap.view.scrapeIface(text) async for (form, valu, info) in genr: yield (form, valu, info) @s_stormtypes.stormfunc(readonly=True) async def _methNdefs(self, text): text = await s_stormtypes.tostr(text) genr = self.runt.snap.view.scrapeIface(text, unique=True) async for (form, valu, _) in genr: yield (form, valu) @s_stormtypes.stormfunc(readonly=True) async def _methGenMatches(self, text, pattern, fangs=None, flags=regex.IGNORECASE): text = await s_stormtypes.tostr(text) pattern = await s_stormtypes.tostr(pattern) fangs = await s_stormtypes.toprim(fangs) flags = await s_stormtypes.toint(flags) opts = {} regx = regex.compile(pattern, flags=flags) _fangs = None _fangre = None offsets = None scrape_text = text if fangs: _fangs = {src: dst for (src, dst) in fangs} _fangre = s_scrape.genFangRegex(_fangs) scrape_text, offsets = s_scrape.refang_text2(text, re=_fangre, fangs=_fangs) for info in s_scrape.genMatches(scrape_text, regx, opts=opts): valu = info.pop('valu') if _fangs and offsets: s_scrape._rewriteRawValu(text, offsets, info) yield valu, info
{ "content_hash": "d88791ce5cbb8101f9ec3fca8873d6e4", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 119, "avg_line_length": 40.263803680981596, "alnum_prop": 0.5125704708212707, "repo_name": "vertexproject/synapse", "id": "86fe9e1b7917a808e5a9f1f55efe55fa2b627b25", "size": "6563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "synapse/lib/stormlib/scrape.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "4010" }, { "name": "HTML", "bytes": "3" }, { "name": "Python", "bytes": "5894053" }, { "name": "Shell", "bytes": "10776" } ], "symlink_target": "" }
package co.fingerprintsoft.spring.hibernate.audit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories( repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class, basePackages = {"co.fingerprintsoft.spring.hibernate.audit"} ) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
{ "content_hash": "b4b964228eb45e74091a5d2b63f3f1b8", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 94, "avg_line_length": 36.73684210526316, "alnum_prop": 0.8151862464183381, "repo_name": "fingerprints/spring-profile", "id": "1230d29e7d996c4f2b66dbeba8a5b01aba7a379c", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-envers/src/test/java/co/fingerprintsoft/spring/hibernate/audit/Application.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "39331" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_11) on Mon Mar 17 10:51:55 PDT 2014 --> <title>IBoxResponse</title> <meta name="date" content="2014-03-17"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="IBoxResponse"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IBoxResponse.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/box/restclientv2/responses/DefaultBoxResponseTest.html" title="class in com.box.restclientv2.responses"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/box/restclientv2/responses/IBoxResponse.html" target="_top">Frames</a></li> <li><a href="IBoxResponse.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.box.restclientv2.responses</div> <h2 title="Interface IBoxResponse" class="title">Interface IBoxResponse</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../com/box/restclientv2/responses/DefaultBoxResponse.html" title="class in com.box.restclientv2.responses">DefaultBoxResponse</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">IBoxResponse</span></pre> <div class="block">Interface for API response.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../com/box/restclientv2/responses/IBoxResponse.html#getContentLength()">getContentLength</a></strong>()</code> <div class="block">Get content length of the response.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../com/box/restclientv2/responses/IBoxResponse.html#parseResponse(com.box.restclientv2.responseparsers.IBoxResponseParser, com.box.restclientv2.responseparsers.IBoxResponseParser)">parseResponse</a></strong>(<a href="../../../../com/box/restclientv2/responseparsers/IBoxResponseParser.html" title="interface in com.box.restclientv2.responseparsers">IBoxResponseParser</a>&nbsp;responseParser, <a href="../../../../com/box/restclientv2/responseparsers/IBoxResponseParser.html" title="interface in com.box.restclientv2.responseparsers">IBoxResponseParser</a>&nbsp;errorParser)</code> <div class="block">Parese HttpResponse into IResponseObject.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="parseResponse(com.box.restclientv2.responseparsers.IBoxResponseParser, com.box.restclientv2.responseparsers.IBoxResponseParser)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>parseResponse</h4> <pre>java.lang.Object&nbsp;parseResponse(<a href="../../../../com/box/restclientv2/responseparsers/IBoxResponseParser.html" title="interface in com.box.restclientv2.responseparsers">IBoxResponseParser</a>&nbsp;responseParser, <a href="../../../../com/box/restclientv2/responseparsers/IBoxResponseParser.html" title="interface in com.box.restclientv2.responseparsers">IBoxResponseParser</a>&nbsp;errorParser) throws <a href="../../../../com/box/restclientv2/exceptions/BoxRestException.html" title="class in com.box.restclientv2.exceptions">BoxRestException</a></pre> <div class="block">Parese HttpResponse into IResponseObject.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>boxResponseObject</code> - </dd> <dt><span class="strong">Returns:</span></dt><dd>parsed object</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../com/box/restclientv2/exceptions/BoxRestException.html" title="class in com.box.restclientv2.exceptions">BoxRestException</a></code></dd></dl> </li> </ul> <a name="getContentLength()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getContentLength</h4> <pre>double&nbsp;getContentLength()</pre> <div class="block">Get content length of the response.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IBoxResponse.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/box/restclientv2/responses/DefaultBoxResponseTest.html" title="class in com.box.restclientv2.responses"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/box/restclientv2/responses/IBoxResponse.html" target="_top">Frames</a></li> <li><a href="IBoxResponse.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "3c86d66e08a157a0bc8340cf7e7b3427", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 444, "avg_line_length": 37.641350210970465, "alnum_prop": 0.6508238986660688, "repo_name": "shelsonjava/box-java-sdk-v2", "id": "e21a5b7a5f8510490e8bc2fdae47194c077d487e", "size": "8921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/com/box/restclientv2/responses/IBoxResponse.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "737981" }, { "name": "Shell", "bytes": "1413" } ], "symlink_target": "" }
SELECT i FROM t1 WHERE b>0 AND b<'zzz'
{ "content_hash": "897ecdfba4f7d742baa2757bc74b8f2b", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 38, "avg_line_length": 38, "alnum_prop": 0.7105263157894737, "repo_name": "bkiers/sqlite-parser", "id": "557aa347d40668a485b658f83fb5b68a93f799c9", "size": "123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/descidx3.test_10.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "20112" }, { "name": "Java", "bytes": "6273" }, { "name": "PLpgSQL", "bytes": "324108" } ], "symlink_target": "" }
if RAILS_ENV == 'development' ActiveSupport::Dependencies.load_once_paths.reject!{|x| x =~ /^#{Regexp.escape(File.dirname(__FILE__))}/} end require 'linktv_platform'
{ "content_hash": "a3dfaaf041b4b713171c93ee84fd3184", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 107, "avg_line_length": 33.6, "alnum_prop": 0.7023809523809523, "repo_name": "definitionstudio/linktv_platform", "id": "0a24c07d5afa59a879d08e46587706bc82fa5d71", "size": "222", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "init.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "196830" }, { "name": "Ruby", "bytes": "302640" } ], "symlink_target": "" }
''' Created on Oct 24, 2014 This is to split a csv dataset into fixed number of rows and then splitting that into training and testing @author: wahib ''' from __future__ import print_function from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn import svm import numpy as np import csv import pylab as pl from sklearn.metrics import roc_curve, auc from sklearn import preprocessing import pandas as pd import random import sys print(__doc__) def splitForLibsvm(folderPath, csvPath, rowExtractCount): trainTargetArray = [] trainDataArray = [] #folderPath = '10000rows/' #fullData = pd.read_csv('csv/1percent_of_200mels.csv', delimiter=",",skiprows=0, dtype=np.float16) #fullData = pd.read_csv('csv/200mels.csv', delimiter=",",skiprows=0, dtype=np.float16) fullData = pd.read_csv(csvPath, delimiter=",",skiprows=0, dtype=np.float16) shape = fullData.shape print('size of full data ', shape) trainData = fullData.iloc[:,:-1] #all except last column trainTarget = fullData.iloc[:,-1] # only last column print('len of traindata', len(trainData)) #print('print traindata', trainData) #only commented when full dataset needs to be used print('count of rows to extract', rowExtractCount) rows = random.sample(trainData.index,rowExtractCount) trainData = trainData.ix[rows] trainTarget = trainTarget.ix[rows] print('target size', trainTarget.shape) #print('target values', trainTarget) trainData = np.array(trainData) trainTarget = np.array(trainTarget) trainTarget = np.squeeze(trainTarget) #print(trainTarget) #print(trainData) #only commented for 200k dataset because it was nullifying all values trainData = preprocessing.scale(trainData) print('scaling-normalization over for trainData') # Split the dataset in two equal parts X_train, X_test, y_train, y_test = train_test_split( trainData, trainTarget, test_size=0.2, random_state=123) print('X_train : ', X_train.shape) print('y_train : ', y_train.shape) print('X_test : ', X_test.shape) print('y_test : ', y_test.shape) #with open('csv/libsvm/'+folderPath+'/Ytr.txt', 'w') as FOUT: with open(folderPath+'/Ytr.txt', 'w') as FOUT: np.savetxt(FOUT, y_train ,fmt='%d',delimiter=',') with open(folderPath+'/Xtr.csv', 'w') as FOUT: np.savetxt(FOUT, X_train, fmt='%1.5f',delimiter=',') with open(folderPath+'/Xte.csv', 'w') as FOUT: np.savetxt(FOUT, X_test, fmt='%1.5f',delimiter=',') with open(folderPath+'/Yte.txt', 'w') as FOUT: np.savetxt(FOUT, y_test, fmt='%d',delimiter=',') print('train and test csv files created') if __name__ == '__main__': if len(sys.argv) < 4: print('3 Arguments required i.e [folderPath] [csvPath] [rowExtractCount] ') else: folderPath = sys.argv[1] csvPath = sys.argv[2] rowExtractCount = sys.argv[3] splitForLibsvm(folderPath, csvPath, rowExtractCount)
{ "content_hash": "94238c57bbf57ff48996981873c5d814", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 106, "avg_line_length": 29.184466019417474, "alnum_prop": 0.7082501663339986, "repo_name": "wahibhaq/android-speaker-audioanalysis", "id": "3fa8b0d5d544ec66e51799e441c1ad628e683398", "size": "3006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/Basic/split_for_libsvm.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "98" }, { "name": "C", "bytes": "5311" }, { "name": "C++", "bytes": "142895" }, { "name": "Java", "bytes": "415228" }, { "name": "Makefile", "bytes": "201515" }, { "name": "Matlab", "bytes": "7068" }, { "name": "Python", "bytes": "15695" }, { "name": "Shell", "bytes": "238" }, { "name": "TeX", "bytes": "9581" } ], "symlink_target": "" }
namespace mandoline { static void LaunchURL(JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& jurl) { LaunchHandlerPtr launch_handler; mojo::runner::GetContext()->application_manager()->ConnectToService( GURL("mojo:phone_ui"), &launch_handler); launch_handler->LaunchURL( base::android::ConvertJavaStringToUTF8(env, jurl)); } bool RegisterMandolineActivity(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace mandoline
{ "content_hash": "2953dfc9ddf876c99634aff247c2b34b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 70, "avg_line_length": 31, "alnum_prop": 0.683111954459203, "repo_name": "Chilledheart/chromium", "id": "0d05724fcf4b00c2cf22a0ca7bc8cea70cd516ee", "size": "917", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mandoline/app/android/mandoline_activity.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "37073" }, { "name": "Batchfile", "bytes": "8451" }, { "name": "C", "bytes": "9549264" }, { "name": "C++", "bytes": "246614934" }, { "name": "CSS", "bytes": "941919" }, { "name": "DM", "bytes": "60" }, { "name": "Groff", "bytes": "2494" }, { "name": "HTML", "bytes": "27365379" }, { "name": "Java", "bytes": "15257671" }, { "name": "JavaScript", "bytes": "20820575" }, { "name": "Makefile", "bytes": "70983" }, { "name": "Objective-C", "bytes": "1798644" }, { "name": "Objective-C++", "bytes": "10138304" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "180150" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "494625" }, { "name": "Python", "bytes": "8581270" }, { "name": "Shell", "bytes": "485812" }, { "name": "Standard ML", "bytes": "5106" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
package org.scalaide.core.internal.project import org.scalaide.core.internal.jdt.util.ClasspathContainerSetter import org.eclipse.jface.preference.IPreferenceStore import org.scalaide.util.internal.CompilerUtils import scala.util.Try import org.scalaide.ui.internal.preferences.CompilerSettings import org.eclipse.jface.util.IPropertyChangeListener import org.scalaide.util.internal.SettingConverterUtil import org.scalaide.core.IScalaPlugin import org.eclipse.core.resources.IMarker import scala.tools.nsc.settings.ScalaVersion import scala.util.Failure import org.eclipse.jface.util.PropertyChangeEvent import scala.util.Success import org.scalaide.core.resources.MarkerFactory import org.eclipse.core.runtime.Path import org.scalaide.core.IScalaPlugin import org.scalaide.core.ScalaInstallationChange import org.scalaide.core.SdtConstants import org.scalaide.core.internal.compiler.ScalaPresentationCompiler trait InstallationManagement { this: ScalaProject => case class WithValidation[A, B](isValid: A => Boolean, unsafeGetter: A => B, registerDefault: (A, B) => WithValidation[A,B]) { def get(key: A)(implicit default: B): B = { if (!isValid(key)) registerDefault(key, default).unsafeGetter(key) else unsafeGetter(key) } } implicit private def validatedProjectPrefStore(p:IPreferenceStore): WithValidation[String, String] = WithValidation( p.contains, p.getString, { (key:String, default:String) => eclipseLog.warn(s"Preference ${key} was uninitialized for ${underlying.getName()}, setting default to ${default}.") p.setDefault(key, default); validatedProjectPrefStore(p) } ) // this is technically generic and could apply to any A => Option[B] // except for its logged message implicit private def validatedScalaInstallationChoice(parse: String => Option[ScalaInstallationChoice]): WithValidation[String, ScalaInstallationChoice] = WithValidation( ((str: String) => parse(str).isDefined), ((str: String) => parse(str).get), { (key: String, default: ScalaInstallationChoice) => eclipseLog.warn(s"Found an unparseable preference set for ${key}, resetting to ${default.toString}.") validatedScalaInstallationChoice({ (str: String) => if (str equals key) Some(default) else parse(str) }) } ) implicit private def validatedLabeledScalaInstallation(resolve: ScalaInstallationChoice => Option[LabeledScalaInstallation]): WithValidation[ScalaInstallationChoice, LabeledScalaInstallation] = WithValidation( ((choice:ScalaInstallationChoice) => resolve(choice).isDefined), ((choice:ScalaInstallationChoice) => resolve(choice).get), { (key: ScalaInstallationChoice, default: LabeledScalaInstallation) => val displayChoice: String = key.marker match { case Left(version) => s"Latest ${CompilerUtils.shortString(version)} bundle (dynamic)" case Right(hash) => s"Fixed Scala Installation with hash ${hash}" } val msg = s"The specified installation choice for this project ($displayChoice) could not be found. Please configure a Scala Installation for this specific project." object svMarkerFactory extends MarkerFactory(SdtConstants.ScalaVersionProblemMarkerId) svMarkerFactory.create(underlying, IMarker.SEVERITY_ERROR, msg) validatedLabeledScalaInstallation({ (choice: ScalaInstallationChoice) => if (choice equals key) Some(default) else resolve(choice) }) } ) /** Which Scala source level is this project configured to work with ? */ def desiredSourceLevel(): String = { implicit val sourceLevelDefault = IScalaPlugin().shortScalaVersion val sourceLevelPrefName = SettingConverterUtil.SCALA_DESIRED_SOURCELEVEL if (!usesProjectSettings) { logger.warn(s"Project ${this.underlying.getName()} has platform default sourceLevel.") sourceLevelDefault } else projectSpecificStorage.get(sourceLevelPrefName) } /** Which Scala installation is this project wished to work with ? - always returns a valid choice, but it may or not resolve */ def desiredinstallationChoice(): ScalaInstallationChoice = { implicit val desiredinstallationChoiceDefault: ScalaInstallationChoice = ScalaInstallationChoice(ScalaVersion(desiredSourceLevel())) implicit val desiredinstallationChoicePrefDefault: String = desiredinstallationChoiceDefault.toString() val desiredinstallationChoicePrefName = SettingConverterUtil.SCALA_DESIRED_INSTALLATION if (!usesProjectSettings) { logger.warn(s"Project ${this.underlying.getName()} runs on platform default installation.") desiredinstallationChoiceDefault } else { (parseScalaInstallationChoice _ ).get(projectSpecificStorage.get(desiredinstallationChoicePrefName)) } } /** Which Scala installation is this project configured to work with ? - always returns a valid installation that resolves */ def effectiveScalaInstallation(): LabeledScalaInstallation = { implicit val desiredInstallationDefault: LabeledScalaInstallation = ScalaInstallation.resolve(ScalaInstallationChoice(IScalaPlugin().scalaVersion)).get (ScalaInstallation.resolve _).get(desiredinstallationChoice()) } private def turnOnProjectSpecificSettings(reason: String): Unit ={ if (!usesProjectSettings) { val pName = this.toString eclipseLog.debug(s"Turning on project-specific settings for $pName because of $reason") projectSpecificStorage.setValue(SettingConverterUtil.USE_PROJECT_SETTINGS_PREFERENCE, true) } } private def turnOffProjectSpecificSettings(reason: String): Unit ={ if (usesProjectSettings){ val pName = this.toString eclipseLog.debug(s"Turning off project-specific settings for $pName because of $reason") projectSpecificStorage.setValue(SettingConverterUtil.USE_PROJECT_SETTINGS_PREFERENCE, false) } } private def parseScalaInstallationChoice(str: String): Option[ScalaInstallationChoice] = Try(str.toInt) match { case Success(int) => Some(ScalaInstallationChoice(Right(int))) case Failure(t) => t match { case ex: NumberFormatException => Try(ScalaVersion(str)).toOption map (ScalaInstallationChoice(_)) } } def setDesiredInstallation(choice: ScalaInstallationChoice = desiredinstallationChoice(), slReason: String = "requested Scala Installation change") : Unit = { val optsi = ScalaInstallation.resolve(choice) // This shouldn't do anything if the choice doesn't resolve val sourceLevel = optsi map {si => CompilerUtils.shortString(si.version)} def bundleUpdater(si: ScalaInstallation): () => Unit = {() => val updater = new ClasspathContainerSetter(javaProject) updater.updateBundleFromScalaInstallation(new Path(SdtConstants.ScalaLibContId), si) updater.updateBundleFromScalaInstallation(new Path(SdtConstants.ScalaCompilerContId), si) } // This is a precaution against scala installation loss and does not set anything by itself, see `SettingConverterUtil.SCALA_DESIRED_SOURCELEVEL` sourceLevel foreach {sl => projectSpecificStorage.setValue(SettingConverterUtil.SCALA_DESIRED_SOURCELEVEL, sl)} optsi foreach {si => setDesiredSourceLevel(si.version, slReason, Some(bundleUpdater(si)))} publish(ScalaInstallationChange()) } def setDesiredSourceLevel( scalaVersion: ScalaVersion = ScalaVersion(desiredSourceLevel()), slReason: String = "requested Source Level change", customBundleUpdater: Option[() => Unit] = None): Unit = { projectSpecificStorage.removePropertyChangeListener(compilerSettingsListener) turnOnProjectSpecificSettings(slReason) if (CompilerUtils.isBinarySame(IScalaPlugin().scalaVersion, scalaVersion)) unsetXSourceAndMaybeTurnOffProjectSettings(slReason) else turnOnProjectSpecificSettingsAndSetXSource(scalaVersion, slReason) // The ordering from here until reactivating the listener is important projectSpecificStorage.setValue(SettingConverterUtil.SCALA_DESIRED_SOURCELEVEL, CompilerUtils.shortString(scalaVersion)) val updater = customBundleUpdater getOrElse { () => val setter = new ClasspathContainerSetter(javaProject) setter.updateBundleFromSourceLevel(new Path(SdtConstants.ScalaLibContId), scalaVersion) setter.updateBundleFromSourceLevel(new Path(SdtConstants.ScalaCompilerContId), scalaVersion) } updater() classpathHasChanged() projectSpecificStorage.addPropertyChangeListener(compilerSettingsListener) } private def turnOnProjectSpecificSettingsAndSetXSource(scalaVersion: ScalaVersion, reason: String) = { turnOnProjectSpecificSettings("requested Xsource change") val scalaVersionString = CompilerUtils.shortString(scalaVersion) // initial space here is important val optionString = s" -Xsource:$scalaVersionString -Ymacro-expand:none" eclipseLog.debug(s"Adding $optionString to compiler arguments of ${this.underlying.getName()} because of: $reason") val extraArgs = ScalaPresentationCompiler.defaultScalaSettings().splitParams(storage.getString(CompilerSettings.ADDITIONAL_PARAMS)) val curatedArgs = extraArgs.filter { s => !s.startsWith("-Xsource") && !s.startsWith("-Ymacro-expand") } storage.setValue(CompilerSettings.ADDITIONAL_PARAMS, curatedArgs.mkString(" ") + optionString) } private def unsetXSourceAndMaybeTurnOffProjectSettings(reason: String) = { if (usesProjectSettings) { val extraArgs = ScalaPresentationCompiler.defaultScalaSettings().splitParams(storage.getString(CompilerSettings.ADDITIONAL_PARAMS)) val (superfluousArgs, curatedArgs) = extraArgs.partition { s => s.startsWith("-Xsource") || s.equals("-Ymacro-expand:none") } val superfluousString = superfluousArgs.mkString(" ") eclipseLog.debug(s"Removing $superfluousString from compiler arguments of ${this.underlying.getName()} because of: $reason") storage.setValue(CompilerSettings.ADDITIONAL_PARAMS, curatedArgs.mkString(" ")) // values in shownSettings are fetched from currentStorage, which here means projectSpecificSettings def projectSettingsSameAsWorkspace = shownSettings(ScalaPresentationCompiler.defaultScalaSettings(), _ => true) forall { case (setting, value) => IScalaPlugin().getPreferenceStore().getString(SettingConverterUtil.convertNameToProperty(setting.name)) == value } def scalaInstallationIsSameAsDefault = { val desiredInstallChoice = desiredinstallationChoice() desiredInstallChoice.marker match { case Left(scalaVersion) => CompilerUtils.isBinarySame(IScalaPlugin().scalaVersion, scalaVersion) case Right(_) => false } } def workspaceAdditionalParams = ScalaPresentationCompiler.defaultScalaSettings().splitParams(IScalaPlugin().getPreferenceStore().getString(CompilerSettings.ADDITIONAL_PARAMS)).toSet def additionalSettingsSameAsWorskspace = curatedArgs forall workspaceAdditionalParams if (projectSettingsSameAsWorkspace && scalaInstallationIsSameAsDefault && additionalSettingsSameAsWorskspace) { turnOffProjectSpecificSettings("Settings are all identical to workspace after Xsource removal.") } } } /** * This compares the bundled version and the Xsource version found * in arguments, and returns false if they are binary-compatible, * and true otherwise. Since this is the final, observable * setting on the running presentation Compiler (independently of * Eclipse's settings), it's considered to be the reference on * whether the PC is in compatibility mode or not. It's a bad * idea to cache this one (desired sourcelevel & al. need to sync * on it). */ private[core] def getCompatibilityMode: CompatibilityMode = { val versionInArguments = this.scalacArguments filter { _.startsWith("-Xsource:") } map { _.stripPrefix("-Xsource:")} val l = versionInArguments.length val specdVersion = versionInArguments.headOption if (l >= 2) eclipseLog.error(s"Found two versions of -Xsource in compiler options, only considering the first! ($specdVersion)") if (l < 1 || (specdVersion exists (x => CompilerUtils.isBinarySame(IScalaPlugin().scalaVersion, ScalaVersion(x))))) Same else if (specdVersion exists (x => CompilerUtils.isBinaryPrevious(IScalaPlugin().scalaVersion, ScalaVersion(x)))) Previous else Subsequent } /** TODO: letting this be a workspace-wide setting. */ def isUsingCompatibilityMode: Boolean = getCompatibilityMode != Same /** Does this project use project-specific compiler settings? */ def usesProjectSettings: Boolean = projectSpecificStorage.getBoolean(SettingConverterUtil.USE_PROJECT_SETTINGS_PREFERENCE) import org.scalaide.util.eclipse.SWTUtils.fnToPropertyChangeListener val compilerSettingsListener: IPropertyChangeListener = { (event: PropertyChangeEvent) => import org.scalaide.util.Utils.WithAsInstanceOfOpt if (event.getProperty() == SettingConverterUtil.SCALA_DESIRED_INSTALLATION) { val installString = (event.getNewValue()).asInstanceOfOpt[String] val installChoice = installString flatMap (parseScalaInstallationChoice(_)) // This can't use the default argument of setDesiredInstallation: getDesiredXXX() ... // will not turn on the project settings and depends on them being set right beforehand installChoice foreach (setDesiredInstallation(_, "requested Scala Installation change from settings update")) } if (event.getProperty() == CompilerSettings.ADDITIONAL_PARAMS || event.getProperty() == SettingConverterUtil.USE_PROJECT_SETTINGS_PREFERENCE) if (isUnderlyingValid) classpathHasChanged() } }
{ "content_hash": "eb966141c7a469fbfe2ecaf4b712d669", "timestamp": "", "source": "github", "line_count": 251, "max_line_length": 195, "avg_line_length": 54.72908366533864, "alnum_prop": 0.7580257698187377, "repo_name": "sschaef/scala-ide", "id": "c5341aa4d21765844f0ebf99ce66c5fc9385864d", "size": "13737", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "org.scala-ide.sdt.core/src/org/scalaide/core/internal/project/InstallationManagement.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AspectJ", "bytes": "105688" }, { "name": "CSS", "bytes": "481" }, { "name": "HTML", "bytes": "23065" }, { "name": "Java", "bytes": "200284" }, { "name": "R", "bytes": "694" }, { "name": "Scala", "bytes": "3749703" }, { "name": "Shell", "bytes": "19242" } ], "symlink_target": "" }
package com.rtg.reader; import static com.rtg.util.cli.CommonFlagCategories.FILTERING; import static com.rtg.util.cli.CommonFlagCategories.INPUT_OUTPUT; import static com.rtg.util.cli.CommonFlagCategories.UTILITY; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Map; import com.rtg.launcher.AbstractCli; import com.rtg.launcher.CommonFlags; import com.rtg.mode.DNA; import com.rtg.mode.DNAFastaSymbolTable; import com.rtg.mode.ProteinFastaSymbolTable; import com.rtg.mode.SequenceType; import com.rtg.util.cli.CFlags; import com.rtg.util.cli.CommonFlagCategories; import com.rtg.util.cli.Validator; import com.rtg.util.diagnostic.ErrorType; import com.rtg.util.diagnostic.NoTalkbackSlimException; import com.rtg.util.intervals.RegionRestriction; /** * Class returns a subsequence of the residues in the given sequence. * */ public final class SdfSubseq extends AbstractCli { /** System dependent line separator, as byte array. */ private static final byte[] LS_BYTES = System.lineSeparator().getBytes(); private static final String FASTA_FLAG = "fasta"; private static final String FASTQ_FLAG = "fastq"; private static final String INPUT_FLAG = "input"; private static final String SEQ_ID_FLAG = "sequence-id"; private static final String REVERSE_FLAG = "reverse-complement"; private static final String PRESERVE_FLAG = "Xpreserve-coordinates"; private static final Validator VALIDATOR = new Validator() { @Override public boolean isValid(final CFlags flags) { if (!flags.checkNand(FASTA_FLAG, FASTQ_FLAG)) { return false; } if (!flags.checkNand(PRESERVE_FLAG, REVERSE_FLAG)) { return false; } for (Object o : flags.getAnonymousValues(0)) { final String restrictionString = (String) o; if (!RegionRestriction.validateRegion(restrictionString)) { flags.setParseMessage("The region value \"" + restrictionString + "\" is malformed."); return false; } final RegionRestriction restriction = new RegionRestriction(restrictionString); if (flags.isSet(SEQ_ID_FLAG)) { long seqId; try { seqId = Long.parseLong(restriction.getSequenceName()); } catch (NumberFormatException e) { seqId = -1; } if (seqId < 0) { flags.setParseMessage("When --" + SEQ_ID_FLAG + " is set the <sequence_name> of the region \"" + restrictionString + "\" must be an integer greater than or equal to 0."); return false; } } } final File inputFile = (File) flags.getValue(INPUT_FLAG); if (ReaderUtils.isPairedEndDirectory(inputFile)) { flags.setParseMessage("Paired-end SDF not supported."); return false; } return true; } }; private byte[] mCodeToBytes = null; private Map<String, Long> mNames = null; private final AbstractSdfWriter.SequenceNameHandler mHandler = new AbstractSdfWriter.SequenceNameHandler(); @Override protected void initFlags() { CommonFlagCategories.setCategories(mFlags); mFlags.setDescription("Prints a subsequence of a given sequence in an SDF."); mFlags.registerRequired('i', INPUT_FLAG, File.class, CommonFlags.SDF, "input SDF").setCategory(INPUT_OUTPUT); mFlags.registerRequired(String.class, CommonFlags.REGION, "the range to display. " + CommonFlags.REGION_SPEC) .setCategory(FILTERING) .setMaxCount(Integer.MAX_VALUE); mFlags.registerOptional('r', REVERSE_FLAG, "if set, output in reverse complement").setCategory(UTILITY); mFlags.registerOptional('f', FASTA_FLAG, "if set, output in FASTA format").setCategory(UTILITY); mFlags.registerOptional('q', FASTQ_FLAG, "if set, output in FASTQ format").setCategory(UTILITY); mFlags.registerOptional('I', SEQ_ID_FLAG, "if set, use sequence id instead of sequence name in region (0-based)").setCategory(FILTERING); mFlags.registerOptional(PRESERVE_FLAG, "if set, pad start of sequence with N's to ensure sequence coordinates are preserved").setCategory(UTILITY); mFlags.setValidator(VALIDATOR); } @Override public String moduleName() { return "sdfsubseq"; } @Override public String description() { return "extract a subsequence from an SDF as text"; } @Override protected int mainExec(final OutputStream out, final PrintStream err) throws IOException { final boolean reverseComplement = mFlags.isSet(REVERSE_FLAG); try (SequencesReader reader = SequencesReaderFactory.createDefaultSequencesReaderCheckEmpty((File) mFlags.getValue(INPUT_FLAG))) { if (!mFlags.isSet(SEQ_ID_FLAG) && !reader.hasNames()) { throw new NoTalkbackSlimException(ErrorType.INFO_ERROR, "The input SDF does not have name data."); } if (mFlags.isSet(FASTQ_FLAG) && !reader.hasQualityData()) { throw new NoTalkbackSlimException(ErrorType.INFO_ERROR, "The input SDF does not have quality data."); } mCodeToBytes = getByteMapping(reader.type(), reverseComplement); if (!mFlags.isSet(SEQ_ID_FLAG)) { mNames = ReaderUtils.getSequenceNameMap(reader); } for (Object o : mFlags.getAnonymousValues(0)) { final RegionRestriction restriction = new RegionRestriction((String) o); final int result = extractSubseq(reader, restriction, reverseComplement, out, err); if (result != 0) { return result; } } out.flush(); } return 0; } private int extractSubseq(final SequencesReader reader, final RegionRestriction restriction, final boolean reverseComplement, final OutputStream out, final PrintStream err) throws IOException { final int start = restriction.getStart() == RegionRestriction.MISSING ? 0 : restriction.getStart(); final long sequenceId; if (!mFlags.isSet(SEQ_ID_FLAG)) { final String sequence = restriction.getSequenceName(); final Long seqId = mNames.get(mHandler.handleSequenceName(sequence).label()); if (seqId == null) { err.println("The sequence \"" + sequence + "\" could not be found."); return 1; } sequenceId = seqId; } else { sequenceId = Long.parseLong(restriction.getSequenceName()); } if (sequenceId < 0 || sequenceId >= reader.numberSequences()) { err.println("The sequence id " + sequenceId + " is out of range, must be from 0 to " + (reader.numberSequences() - 1) + "."); return 1; } final int seqlength = reader.length(sequenceId); final int endpos = restriction.getEnd() == RegionRestriction.MISSING ? seqlength : restriction.getEnd(); // Convert from 1-based inclusive to 0-based exclusive final int length = endpos - start; if (start > seqlength) { err.println("Supplied start position \"" + (start + 1) + "\" reads past sequence end."); return 1; } else if (endpos > seqlength) { err.println("Supplied end position \"" + endpos + "\" reads past sequence end."); return 1; } final boolean isCoordsAltered = length < seqlength && !mFlags.isSet(PRESERVE_FLAG); char sequenceNameIdentifier = '>'; if (mFlags.isSet(FASTQ_FLAG)) { sequenceNameIdentifier = '@'; } if (mFlags.isSet(FASTA_FLAG) || mFlags.isSet(FASTQ_FLAG)) { final String name; if (reader.hasNames()) { name = isCoordsAltered ? reader.name(sequenceId) : reader.fullName(sequenceId); } else { name = String.valueOf(sequenceId); } out.write((sequenceNameIdentifier + name).getBytes()); final String coords = isCoordsAltered ? ":" + (start + 1) + "-" + (start + length) : ""; out.write(coords.getBytes()); if (reverseComplement) { out.write("-rc".getBytes()); } out.write(LS_BYTES); } byte[] buff = new byte[length]; reader.read(sequenceId, buff, start, length); if (reverseComplement) { for (int i = length - 1; i >= 0; --i) { out.write(mCodeToBytes[buff[i]]); } } else { if (mFlags.isSet(PRESERVE_FLAG)) { for (int i = 0; i < start; ++i) { out.write(mCodeToBytes[0]); } } for (int i = 0; i < length; ++i) { out.write(mCodeToBytes[buff[i]]); } } out.write(LS_BYTES); if (mFlags.isSet(FASTQ_FLAG)) { out.write('+'); out.write(LS_BYTES); buff = new byte[length]; reader.readQuality(sequenceId, buff, start, length); if (reverseComplement) { for (int i = length - 1; i >= 0; --i) { out.write(buff[i] + 33); } } else { if (mFlags.isSet(PRESERVE_FLAG)) { for (int i = 0; i < start; ++i) { out.write(33); } } for (int i = 0; i < length; ++i) { out.write(buff[i] + 33); } } out.write(LS_BYTES); } return 0; } static byte[] getByteMapping(SequenceType type, boolean reverseComplement) { if (type == SequenceType.DNA) { if (reverseComplement) { final byte[] dnaCodes = new DNAFastaSymbolTable().getOrdinalToAsciiTable(); final byte[] compCodes = new byte[dnaCodes.length]; for (final DNA d : DNA.values()) { compCodes[d.ordinal()] = dnaCodes[d.complement().ordinal()]; } return compCodes; } else { return new DNAFastaSymbolTable().getOrdinalToAsciiTable(); } } else { if (reverseComplement) { throw new NoTalkbackSlimException("Reverse complement cannot be used with protein SDFs."); } return new ProteinFastaSymbolTable().getOrdinalToAsciiTable(); } } }
{ "content_hash": "b648ec505149c56b38dce1ba397aa224", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 195, "avg_line_length": 38.476190476190474, "alnum_prop": 0.654496699669967, "repo_name": "RealTimeGenomics/rtg-tools", "id": "a035f9591fd8d93c92c09e6ff343e2fc047a603a", "size": "11097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/rtg/reader/SdfSubseq.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6360" }, { "name": "CSS", "bytes": "26925" }, { "name": "HTML", "bytes": "500647" }, { "name": "Java", "bytes": "8289543" }, { "name": "JavaScript", "bytes": "194293" }, { "name": "Shell", "bytes": "40973" }, { "name": "XSLT", "bytes": "39426" } ], "symlink_target": "" }
package edu.purdue.voltag.data; /** * Class which stores static constants for object names and fields in the parse backend */ public abstract class ParseConstants { /** * Parse keys please dont stealerino */ public static final String PARSE_APPLICATION_KEY = "RP4GH0ySHN7O2LdJQxGAlFEKgfN5s4aM4gOmpGAs"; public static final String PARSE_CLIENT_KEY = "pcNQ7PZCQv4gGWjCjR9ia6SVhNIetod2LNvb5ZhX"; /** * Object names */ public static final String PARSE_CLASS_PLAYER = "Player"; public static final String PARSE_CLASS_GAME = "Game"; public static final String PARSE_CLASS_TAG = "Tag"; /** * General class columns */ public static final String CLASS_ID = "objectId"; public static final String CLASS_CREATED_AT = "createdAt"; public static final String CLASS_UPDATED_AT = "updatedAt"; public static final String CLASS_ACL = "ACL"; /** * Player class */ public static final String PLAYER_HARDWARE_ID = "hardwareID"; public static final String PLAYER_NAME = "name"; public static final String PLAYER_EMAIL = "email"; /** * Game class */ public static final String GAME_NAME = "name"; public static final String GAME_TAGGED = "tagged"; public static final String GAME_PLAYERS = "players"; /** * Tag class */ public static final String TAG_GAME = "game"; public static final String TAG_PLAYER_IT = "player_it"; public static final String TAG_PLAYER_TAGGED = "player_tagged"; }
{ "content_hash": "d7e1114aa4052a5eb912548e654fa5ef", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 98, "avg_line_length": 30.64, "alnum_prop": 0.672976501305483, "repo_name": "voltag/voltag", "id": "5d96ace72351d9e079b84a3d86ec81f81e1ea41d", "size": "1532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/voltag/src/main/java/edu/purdue/voltag/data/ParseConstants.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "950" }, { "name": "Java", "bytes": "93274" } ], "symlink_target": "" }
import gulp from 'gulp'; import plugins from 'gulp-load-plugins'; import browser from 'browser-sync'; import rimraf from 'rimraf'; import panini from 'panini'; import yargs from 'yargs'; import lazypipe from 'lazypipe'; import inky from 'inky'; import fs from 'fs'; import siphon from 'siphon-media-query'; import path from 'path'; import merge from 'merge-stream'; import beep from 'beepbeep'; import colors from 'colors'; import cheerio from 'cheerio'; import sparkpost from 'sparkpost'; import azureStorage from 'azure-storage'; const $ = plugins(); // Look for the --production flag const PRODUCTION = !!(yargs.argv.production); const EMAIL = yargs.argv.to; // Declar var so that Azure and Sparkpost can use it. let CONFIG; const configPath = './config.json'; try { CONFIG = JSON.parse(fs.readFileSync(configPath)); } catch(e) { beep(); console.log('[CONFIG]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md'); process.exit(); } // Build the "dist" folder by running all of the below tasks gulp.task('build', gulp.series(clean, pages, sass, images, inline, azure)); // Build emails, then send to litmus gulp.task('litmus', gulp.series('build', litmus)); // Build emails, then send to EMAIL gulp.task('mail', gulp.series('build', mail)); // Build emails, then zip gulp.task('zip', gulp.series('build', zip)); gulp.task('preview', gulp.series('build', preview)); // Build emails, run the server, and watch for file changes gulp.task('default', gulp.series('preview', server, watch)); // Delete the "dist" folder // This happens every time a build starts function clean(done) { rimraf('dist', done); } // Compile layouts, pages, and partials into flat HTML files // Then parse using Inky templates function pages() { return gulp.src(['src/pages/**/*.html', '!src/pages/archive/**/*.html']) .pipe(panini({ root: 'src/pages', layouts: 'src/layouts', partials: 'src/partials', helpers: 'src/helpers' })) .pipe(inky()) .pipe(gulp.dest('dist')); } // Reset Panini's cache of layouts and partials function resetPages(done) { panini.refresh(); done(); } // Compile Sass into CSS function sass() { return gulp.src('src/assets/scss/app.scss') .pipe($.if(!PRODUCTION, $.sourcemaps.init())) .pipe($.sass({ includePaths: ['node_modules/foundation-emails/scss'], }).on('error', $.sass.logError)) .pipe($.if(PRODUCTION, $.uncss( { html: ['dist/**/*.html'] }))) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest('dist/css')); } // Copy and compress images function images() { return gulp.src(['src/assets/img/**/*', '!src/assets/img/archive/**/*']) .pipe($.imagemin()) .pipe(gulp.dest('./dist/assets/img')); } // Inline CSS, swap external URL, and minify HTML function inline() { const azureURL = !!CONFIG && !!CONFIG.azure && !!CONFIG.azure.url ? CONFIG.azure.url : false; return gulp.src('dist/**/*.html') .pipe($.if(PRODUCTION, inliner('dist/css/app.css'))) .pipe($.if(!!azureURL, $.replace(/=('|")(\/?assets\/img)/g, '=$1' + azureURL))) .pipe(gulp.dest('dist')); } // Start a server with LiveReload to preview the site in function server(done) { browser.init({ server: 'dist', }); done(); } // Watch for file changes function watch() { gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, preview, browser.reload)); gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, preview, browser.reload)); gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, preview, browser.reload)); gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, preview, browser.reload)); gulp.watch('etc/data/**/*.json').on('all', gulp.series(preview, browser.reload)); } // Inlines CSS into HTML, adds media query CSS into the <style> tag of the email, and compresses the HTML function inliner(css) { var css = fs.readFileSync(css).toString(); const mqCss = siphon(css); const pipe = lazypipe() .pipe($.inlineCss, { applyStyleTags: false, removeStyleTags: true, preserveMediaQueries: true, removeLinkTags: false, }) .pipe($.replace, '<!-- <style> -->', `<style>${mqCss}</style>`) .pipe($.replace, '<link rel="stylesheet" type="text/css" href="css/app.css">', '') .pipe($.replace, '@media', '@@media') .pipe($.htmlmin, { collapseWhitespace: true, minifyCSS: true, }); return pipe(); } // Post images to Azure Blob Storage so they are accessible to emails function azure() { if (!CONFIG.azure) return Promise.resolve(); const blobService = azureStorage.createBlobService(CONFIG.azure.accountName, CONFIG.azure.accountKey); const dir = path.join(__dirname, './dist/assets/img'); const tasks = fs.readdirSync(dir) .filter((filename) => { const file = path.join(dir, filename); return fs.statSync(file).isFile(); }) .map(filename => new Promise((r, x) => { blobService.createBlockBlobFromLocalFile( CONFIG.azure.containerName, filename, path.join(dir, filename), (err, result, response) => { if (err) return x(err); console.log('[AZURE]', result); return r(result); }); })); return Promise.all(tasks); } // Send email to Litmus for testing. If no Azure creds then do not replace img urls. function litmus() { return gulp.src('dist/**/*.html') .pipe($.litmus(CONFIG.litmus)) .pipe(gulp.dest('dist')); } // Send email to specified email for testing. If no Azure creds then do not replace img urls. function mail() { if (EMAIL) { CONFIG.mail.to = [EMAIL]; } return gulp.src('dist/**/*.html') .pipe($.mail(CONFIG.mail)) .pipe(gulp.dest('dist')); } function getHtmlFiles(dir) { const ext = '.html'; return fs.readdirSync(dir) .filter((file) => { const fileExt = path.join(dir, file); const isHtml = path.extname(fileExt) === ext; return fs.statSync(fileExt).isFile() && isHtml; }); } // Copy and compress into Zip function zip() { const dist = 'dist'; const ext = '.html'; const htmlFiles = getHtmlFiles(dist); const moveTasks = htmlFiles.map((file) => { const sourcePath = path.join(dist, file); const fileName = path.basename(sourcePath, ext); const moveHTML = gulp.src(sourcePath) .pipe($.rename(function (path) { path.dirname = fileName; return path; })); const moveImages = gulp.src(sourcePath) .pipe($.htmlSrc({ selector: 'img'})) .pipe($.rename(function (path) { path.dirname = fileName + path.dirname.replace('dist', ''); return path; })); return merge(moveHTML, moveImages) .pipe($.zip(fileName + '.zip')) .pipe(gulp.dest('dist')); }); return merge(moveTasks); } function getTemplate(dir, filename) { let html = fs.readFileSync(path.join(__dirname, dir, filename), 'utf-8'); const azureURL = !!CONFIG && !!CONFIG.azure && !!CONFIG.azure.url ? CONFIG.azure.url : false; if (!!azureURL) { html = html.replace(/(=|url\()('|")?(\/?assets\/img)/g, '$1$2'+ azureURL); } const dom = cheerio.load(html); const id = dom('meta[name="id"]').attr('content'); const name = dom('meta[name="name"]').attr('content'); const subject = dom('title').text(); const template = { id, name, content: { subject, html, }, }; // build from info const fromEmail = dom('meta[name="from_email"]').attr('content'); if (fromEmail) { template.content.from = fromEmail; } else { template.content.from = 'donotreply@payments-mail.ucdavis.edu'; } const fromName = dom('meta[name="from_name"]').attr('content'); if (fromName) { template.content.from = { name: fromName, email: template.content.from, }; } // build reply info const replyEmail = dom('meta[name="reply_email"]').attr('content'); if (replyEmail) { template.content.reply_to = replyEmail; } return template; } function getSubstitutionFiles(dir) { const ext = '.json'; return fs.readdirSync(dir) .filter((file) => { const fileExt = path.join(dir, file); const isJson = path.extname(fileExt) === ext; return fs.statSync(fileExt).isFile() && isJson; }); } function preview() { if (!CONFIG.sparkpost) { return Promise.resolve(); } const key = CONFIG.sparkpost.apikey; const client = new sparkpost(key); const options = { update_published: false, }; let dist = path.join(__dirname, 'dist'); if (!fs.existsSync(dist)) { fs.mkdirSync(dist); } dist = path.join(dist, 'preview'); if (!fs.existsSync(dist)) { fs.mkdirSync(dist); } const dir = './etc/data'; const tasks = getSubstitutionFiles(dir).map(s => { const id = s.replace(/\.json$/, ''); const data = JSON.parse(fs.readFileSync(path.join(__dirname, dir, s))); const template = getTemplate('dist', `${id}.html`); template.id = 'preview'; template.name = 'preview'; // first upload the template return client.templates.update('preview', template) .then(result => { console.log(result); return client.templates.preview('preview', { draft: true, substitution_data: data, }); }) .then(result => { // write files to dist fs.writeFileSync(path.join(dist, `${id}.html`), result.results.html); }) .catch(err => console.log(err)); }); return Promise.all(tasks); }
{ "content_hash": "7574efb916730d4cd0d2f8052caf94b2", "timestamp": "", "source": "github", "line_count": 351, "max_line_length": 146, "avg_line_length": 27.626780626780626, "alnum_prop": 0.624007424976797, "repo_name": "ucdavis/Anlab", "id": "8f7df0cb833ea81cfd84ba7601a0eef7df50b567", "size": "9697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "email-templates/gulpfile.babel.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "89" }, { "name": "C#", "bytes": "818537" }, { "name": "HTML", "bytes": "520071" }, { "name": "JavaScript", "bytes": "9977" }, { "name": "SCSS", "bytes": "31506" }, { "name": "TSQL", "bytes": "206460" }, { "name": "TypeScript", "bytes": "136385" } ], "symlink_target": "" }
/*********** Page Header ***********/ /* Header search bar, toggler button & top menu */ .page-header.navbar { background-color: #1f1f1f; /* Top notification menu/bar */ /* Header seaech box */ /* Toggler button for sidebar expand/collapse and responsive sidebar menu */ } .page-header.navbar .top-menu .navbar-nav { /* Extended Dropdowns */ /* Notification */ /* Inbox */ /* Tasks */ /* User */ /* Language */ /* Dark version */ } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle > i { color: #999999; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle .badge.badge-default { background-color: #d64635; color: white; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle:hover { background-color: #393939; } .page-header.navbar .top-menu .navbar-nav > li.dropdown .dropdown-toggle:hover > i { color: #bfbfbf; } .page-header.navbar .top-menu .navbar-nav > li.dropdown.open .dropdown-toggle { background-color: #393939; } .page-header.navbar .top-menu .navbar-nav > li.dropdown.open .dropdown-toggle > i { color: #bfbfbf; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu { border-color: #e7eaf0; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu:after { border-bottom-color: #eaedf2; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external { background: #eaedf2; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > h3 { color: #62878f; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > a { color: #5b9bd1; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu > li.external > a:hover { color: #3175af; text-decoration: none; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu .dropdown-menu-list > li > a { border-bottom: 1px solid #eff2f6 !important; color: #888888; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-extended .dropdown-menu .dropdown-menu-list > li > a:hover { background: #f8f9fa; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification .dropdown-menu .dropdown-menu-list > li > a .time { background: #f1f1f1; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification .dropdown-menu .dropdown-menu-list > li > a:hover .time { background: #e4e4e4; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox > .dropdown-toggle > .circle { background-color: #d64635; color: white; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox > .dropdown-toggle > .corner { border-color: transparent #d64635 transparent transparent; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-inbox .dropdown-menu .dropdown-menu-list .subject .from { color: #5b9bd1; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-tasks .dropdown-menu .dropdown-menu-list .progress { background-color: #dfe2e9; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-toggle > .username { color: #c5c5c5; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-toggle > i { color: #c5c5c5; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user > .dropdown-menu { width: 195px; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-language > .dropdown-toggle > .langname { color: #c5c5c5; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu { background: #393939; border: 0; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu:after { border-bottom-color: #393939; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external { background: #242424; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external > h3 { color: #a4a4a4; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu > li.external > a:hover { color: #87b6dd; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a { color: #b0b0b0; border-bottom: 1px solid #484848 !important; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a > i, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a > i { color: #979797; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a:hover, .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu .dropdown-menu-list > li a:hover { background: #434343; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li a { border-bottom: 0 !important; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-dark .dropdown-menu.dropdown-menu-default > li.divider { background: #484848; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification.dropdown-dark .dropdown-menu .dropdown-menu-list > li > a .time { background: #2c2c2c; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-notification.dropdown-dark .dropdown-menu .dropdown-menu-list > li > a:hover .time { background: #1f1f1f; } .page-header.navbar .search-form { background: #151515; } .page-header.navbar .search-form:hover { background: #393939; } .page-header.navbar .search-form .input-group .form-control { color: #999999; } .page-header.navbar .search-form .input-group .form-control::-moz-placeholder { color: #969696; opacity: 1; } .page-header.navbar .search-form .input-group .form-control:-ms-input-placeholder { color: #969696; } .page-header.navbar .search-form .input-group .form-control::-webkit-input-placeholder { color: #969696; } .page-header.navbar .search-form .input-group .input-group-btn .btn.submit > i { color: #999999; } .page-header.navbar .search-form.open { background: #393939; } .page-header.navbar .menu-toggler { background-image: url(../../img/sidebar_toggler_icon_default.png); } /* Default Horizontal Menu */ .page-header.navbar { /* Default Mega Menu */ /* Light Mega Menu */ } .page-header.navbar .hor-menu .navbar-nav { /* Mega menu content */ /* Classic menu */ } .page-header.navbar .hor-menu .navbar-nav > li.mega-menu-dropdown > .dropdown-menu { box-shadow: 5px 5px rgba(57, 57, 57, 0.2); } .page-header.navbar .hor-menu .navbar-nav > li.mega-menu-dropdown > .dropdown-menu .mega-menu-content .mega-menu-submenu li > h3 { color: #c5c5c5; } .page-header.navbar .hor-menu .navbar-nav > li > a { color: #c5c5c5; } .page-header.navbar .hor-menu .navbar-nav > li > a > i { color: #787878; } .page-header.navbar .hor-menu .navbar-nav > li.open > a, .page-header.navbar .hor-menu .navbar-nav > li > a:hover { color: #d2d2d2; background: #393939 !important; } .page-header.navbar .hor-menu .navbar-nav > li.open > a > i, .page-header.navbar .hor-menu .navbar-nav > li > a:hover > i { color: #858585; } .page-header.navbar .hor-menu .navbar-nav > li.active > a, .page-header.navbar .hor-menu .navbar-nav > li.active > a, .page-header.navbar .hor-menu .navbar-nav > li.current > a, .page-header.navbar .hor-menu .navbar-nav > li.current > a { color: white; background: #d64635 !important; } .page-header.navbar .hor-menu .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li.current > a > i, .page-header.navbar .hor-menu .navbar-nav > li.current > a > i { color: #787878; } .page-header.navbar .hor-menu .navbar-nav > li.active .selected, .page-header.navbar .hor-menu .navbar-nav > li.current .selected { border-top: 6px solid #d64635; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu { box-shadow: 5px 5px rgba(57, 57, 57, 0.2); background: #393939; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li > a { color: #b8b8b8; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li > a > i { color: #b8b8b8; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li:hover > a { color: gainsboro; background: #434343; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li:hover > a > i { color: gainsboro; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a:hover, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a:hover { color: gainsboro; background: #434343; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.active > a:hover > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a > i, .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.current > a:hover > i { color: gainsboro; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-menu li.divider { background-color: #454545; } .page-header.navbar .hor-menu .navbar-nav > li .dropdown-submenu > a:after { color: #b8b8b8; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav { /* Mega menu content */ /* Classic menu */ } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.mega-menu-dropdown > .dropdown-menu { box-shadow: 5px 5px rgba(102, 102, 102, 0.1); } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.mega-menu-dropdown > .dropdown-menu .mega-menu-content .mega-menu-submenu li > h3 { color: #666666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a { color: #c5c5c5; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a > i { color: #787878; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a:hover { color: #d2d2d2; background: #393939; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > a:hover > i { color: #858585; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.open > a { color: #333333 !important; background: white !important; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.open > a > i { color: #333333 !important; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a:hover, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a:hover { color: white; background: #d64635; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.active > a:hover > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li.current > a:hover > i { color: #787878; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu { box-shadow: 5px 5px rgba(102, 102, 102, 0.1); background: white; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li > a { color: black; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li > a > i { color: #888888; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li:hover > a { color: black; background: #f2f2f7; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li:hover > a > i { color: #666666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a:hover, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a:hover { color: black; background: #f2f2f7; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.active > a:hover > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a > i, .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.current > a:hover > i { color: #666666; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu li.divider { background-color: #f2f2f7; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li .dropdown-menu { border: 1px solid #efeff5; } .page-header.navbar .hor-menu.hor-menu-light .navbar-nav > li > .dropdown-menu { border-top: 0; } /* Page sidebar */ .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover, .page-sidebar { background-color: #3d3d3d; /* Default sidebar */ /* light sidebar */ /* Sidebar search */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu, .page-sidebar .page-sidebar-menu { /* 1st level links */ /* All links */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a, .page-sidebar .page-sidebar-menu > li > a { border-top: 1px solid #484848; color: #d9d9d9; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i, .page-sidebar .page-sidebar-menu > li > a > i { color: #888888; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i[class^="icon-"], .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > i[class*="icon-"], .page-sidebar .page-sidebar-menu > li > a > i[class^="icon-"], .page-sidebar .page-sidebar-menu > li > a > i[class*="icon-"] { color: #959595; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li > a > .arrow:before, .page-sidebar .page-sidebar-menu > li > a > .arrow.open:before { color: #777777; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.heading > h3, .page-sidebar .page-sidebar-menu > li.heading > h3 { color: #9e9e9e; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a, .page-sidebar .page-sidebar-menu > li:hover > a, .page-sidebar .page-sidebar-menu > li.open > a { background: #303030; color: #d9d9d9; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > i, .page-sidebar .page-sidebar-menu > li:hover > a > i, .page-sidebar .page-sidebar-menu > li.open > a > i { color: #888888; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:hover > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu > li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.open > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.open > a > .arrow.open:before { color: #888888; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a, .page-sidebar .page-sidebar-menu > li.active > a, .page-sidebar .page-sidebar-menu > li.active.open > a { background: #d64635; border-top-color: transparent; color: white; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a:hover, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a:hover, .page-sidebar .page-sidebar-menu > li.active > a:hover, .page-sidebar .page-sidebar-menu > li.active.open > a:hover { background: #d64635; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > i, .page-sidebar .page-sidebar-menu > li.active > a > i, .page-sidebar .page-sidebar-menu > li.active.open > a > i { color: white; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu > li.active.open > a > .arrow:before, .page-sidebar .page-sidebar-menu > li.active.open > a > .arrow.open:before { color: white; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active + li > a, .page-sidebar .page-sidebar-menu > li.active + li > a { border-top-color: transparent; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li.active.open + li > a, .page-sidebar .page-sidebar-menu > li.active.open + li > a { border-top-color: #484848; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu > li:last-child > a, .page-sidebar .page-sidebar-menu > li:last-child > a { border-bottom: 1px solid transparent !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li > a > .arrow:before, .page-sidebar .page-sidebar-menu li > a > .arrow.open:before { color: #777777; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu li:hover > a > .arrow.open:before { color: #888888; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu li.active > a > .arrow.open:before { color: white; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu:hover .sub-menu, .page-sidebar-closed .page-sidebar .page-sidebar-menu:hover .sub-menu { background-color: #3d3d3d; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a, .page-sidebar .page-sidebar-menu .sub-menu > li > a { color: #bdbdbd; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li > a > i { color: #777777; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i[class^="icon-"], .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > i[class*="icon-"], .page-sidebar .page-sidebar-menu .sub-menu > li > a > i[class^="icon-"], .page-sidebar .page-sidebar-menu .sub-menu > li > a > i[class*="icon-"] { color: #959595; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li > a > .arrow.open:before { color: #777777; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a { background: #474747 !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > i, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > i { color: #888888; color: #bbbbbb; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li:hover > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.open > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu .sub-menu > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li:hover > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu .sub-menu > li.active > a > .arrow.open:before { color: #888888; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.open > a { background: #424242; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { background: #474747; border-right: 4px solid #d64635; color: #f1f1f1; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { border-right: 4px solid #d64635; background: #424242; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > i, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > i, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > i, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > i { color: #eeeeee; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow.open:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow:before, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow.open:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a > .arrow.open:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow:before, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a > .arrow.open:before { color: #eeeeee; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu { background: #424242; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a { background: #474747 !important; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-toggler, .page-sidebar .sidebar-toggler { background: url(../../img/sidebar_inline_toggler_icon_default.jpg); } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group, .page-sidebar .sidebar-search .input-group { border-bottom: 1px solid #484848; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control, .page-sidebar .sidebar-search .input-group .form-control { background-color: #3d3d3d; color: #5c5c5c; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control::-moz-placeholder, .page-sidebar .sidebar-search .input-group .form-control::-moz-placeholder { color: #5c5c5c; opacity: 1; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control:-ms-input-placeholder, .page-sidebar .sidebar-search .input-group .form-control:-ms-input-placeholder { color: #5c5c5c; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .form-control::-webkit-input-placeholder, .page-sidebar .sidebar-search .input-group .form-control::-webkit-input-placeholder { color: #5c5c5c; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search .input-group .input-group-btn .btn > i, .page-sidebar .sidebar-search .input-group .input-group-btn .btn > i { color: #5c5c5c; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-bordered .input-group, .page-sidebar .sidebar-search.sidebar-search-bordered .input-group { border: 1px solid #484848; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.open .input-group, .page-sidebar-closed .page-sidebar .sidebar-search.open .input-group { background-color: #3d3d3d; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.open .remove > i, .page-sidebar-closed .page-sidebar .sidebar-search.open .remove > i { color: #5c5c5c; } .page-sidebar-closed .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group, .page-sidebar-closed .page-sidebar .sidebar-search.sidebar-search-solid .input-group { background: none; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group, .page-sidebar .sidebar-search.sidebar-search-solid .input-group { border: 1px solid #303030; background: #303030; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid .input-group .form-control, .page-sidebar .sidebar-search.sidebar-search-solid .input-group .form-control { background: #303030; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid.open .input-group, .page-sidebar .sidebar-search.sidebar-search-solid.open .input-group { border: 1px solid #3d3d3d; background: #3d3d3d; } .page-sidebar-closed.page-sidebar-fixed .page-sidebar:hover .sidebar-search.sidebar-search-solid.open .input-group .form-control, .page-sidebar .sidebar-search.sidebar-search-solid.open .input-group .form-control { background: #3d3d3d; } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { border-right: 0; border-left: 4px solid #d64635; } .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar-reversed .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { border-right: 0; border-left: 4px solid #d64635; } /************* Quick Sidebar *************/ /*** Quick Sidebar Layout ***/ .page-quick-sidebar-wrapper { background: #393939; } .page-quick-sidebar-wrapper .page-quick-sidebar { background: #393939; } /*** Quick Sidebar Toggler ***/ .page-quick-sidebar-toggler { background: #525252; } .page-quick-sidebar-toggler:hover { background: #4a4a4a; } .page-quick-sidebar-toggler > i { color: #a2a2a2; } /*** Quick Sidebar Content ***/ .page-quick-sidebar-wrapper { color: #a2a2a2; /* Quick sidebar chat */ /* Quick sidebar alerts */ } .page-quick-sidebar-wrapper .page-quick-sidebar { /* Quick sidebar tabs */ /* Quick sidebar general list heading */ /* Quick sidebar general list-items */ } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li > a { color: #9a9a9a; background: #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li > a:hover { background: #454545; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li.open > a { color: #9a9a9a; background: #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li.active > a { border: 0; background: #393939; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu { border: 0; background: #525252; box-shadow: 5px 5px rgba(133, 133, 133, 0.1); } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu:before { border-bottom: 7px solid #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu:after { border-bottom: 7px solid #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li > a { color: #a2a2a2; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li > a > i { color: #9c9c9c; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li > a:hover { background: #5a5a5a; color: #a2a2a2; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li > a:hover > i { color: #a4a4a4; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li.active > a { background: #555555; color: #a2a2a2; } .page-quick-sidebar-wrapper .page-quick-sidebar .nav-justified > li .dropdown-menu > li.divider { background-color: #5a5a5a; } .page-quick-sidebar-wrapper .page-quick-sidebar .list-heading { color: #7b7b7b; } .page-quick-sidebar-wrapper .page-quick-sidebar .list-items { margin: 0; padding: 0; list-style: none; } .page-quick-sidebar-wrapper .page-quick-sidebar .list-items > li { border-bottom-color: #404040; } .page-quick-sidebar-wrapper .page-quick-sidebar .list-items > li:hover { background: #404040; } .page-quick-sidebar-wrapper .page-quick-sidebar-item { /* back to list */ } .page-quick-sidebar-wrapper .page-quick-sidebar-item .page-quick-sidebar-nav .page-quick-sidebar-back-to-list { color: #9a9a9a; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-users .media-list .media .media-body .media-heading-sub { color: #747474; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-users .media-list .media .media-body .media-heading-small { color: dimgray; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-user .page-quick-sidebar-chat-user-messages .post .name { color: #909090; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-user .page-quick-sidebar-chat-user-messages .post .datetime { color: #909090; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-user .page-quick-sidebar-chat-user-messages .post .message { color: #9a9a9a; background: #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-user .page-quick-sidebar-chat-user-messages .post.in .message .arrow { border-left-color: #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar-chat .page-quick-sidebar-chat-user .page-quick-sidebar-chat-user-messages .post.out .message .arrow { border-right-color: #525252; } .page-quick-sidebar-wrapper .page-quick-sidebar-alerts .page-quick-sidebar-alerts-list .feeds li a { color: #8b8b8b; } .page-quick-sidebar-wrapper .page-quick-sidebar-alerts .page-quick-sidebar-alerts-list .feeds li a .desc { text-decoration: underline; } .page-quick-sidebar-wrapper .page-quick-sidebar-alerts .page-quick-sidebar-alerts-list .feeds li .desc { color: #858585; } .page-quick-sidebar-wrapper .page-quick-sidebar-alerts .page-quick-sidebar-alerts-list .feeds li .date { color: dimgray; } /****** Page Footer ******/ .page-footer .page-footer-inner { color: #a3a3a3; } .page-footer-fixed .page-footer { background-color: #2b2b2b; } @media (min-width: 992px) { /* 992px */ /* Sidebar menu closed */ .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu { box-shadow: 5px 5px rgba(48, 48, 48, 0.2); } .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-hover-submenu > li:hover > .sub-menu.sidebar-search-wrapper { box-shadow: none; } .page-sidebar-menu.page-sidebar-menu-closed > li:hover { box-shadow: 5px 5px rgba(48, 48, 48, 0.2); } .page-sidebar-menu.page-sidebar-menu-closed > li:hover.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-closed > li:hover.sidebar-search-wrapper { box-shadow: none; } .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu { box-shadow: 5px 5px rgba(48, 48, 48, 0.2); } .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu.sidebar-toggler-wrapper, .page-sidebar-menu.page-sidebar-menu-closed > li:hover > .sub-menu.sidebar-search-wrapper { box-shadow: none; } /* Light sidebar menu */ .page-sidebar-menu.page-sidebar-menu-light.page-sidebar-menu-closed > li.heading { padding: 0; margin-top: 15px; margin-bottom: 15px; border-top: 1px solid #484848 !important; } /* Fixed Sidebar */ .page-sidebar-fixed:not(.page-footer-fixed) .page-content { border-bottom: 0; } .page-sidebar-fixed:not(.page-footer-fixed) .page-footer { background-color: #fff; } .page-sidebar-fixed:not(.page-footer-fixed) .page-footer .page-footer-inner { color: #333; } /* Boxed Layout */ .page-boxed { background-color: #353535 !important; /* Page container */ /* Page sidebar */ /* Page footer */ } .page-boxed .page-container { background-color: #3d3d3d; border-right: 1px solid #484848; border-bottom: 1px solid #484848; } .page-boxed.page-sidebar-reversed .page-container { border-right: 0; border-left: 1px solid #484848; } .page-boxed.page-sidebar-fixed .page-container { border-right: 0; border-bottom: 0; } .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-container { border-right: 0; border-left: 0; border-bottom: 0; } .page-boxed.page-sidebar-fixed .page-sidebar { border-right: 1px solid #484848; } .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-sidebar { border-left: 1px solid #484848; border-right: 0; } .page-boxed.page-sidebar-fixed.page-footer-fixed .page-footer { background-color: #353535 !important; } .page-boxed.page-sidebar-fixed.page-footer-fixed .page-footer .page-footer-inner { color: #a3a3a3; } /* Sidebar Menu Wirh Hoverable Submenu */ .page-sidebar-menu-hover-submenu li:hover a > .arrow { border-left: 8px solid #3a3a3a; } .page-sidebar-reversed .page-sidebar-menu-hover-submenu li:hover a > .arrow { border-right: 8px solid #3a3a3a; } .page-sidebar-menu-hover-submenu li:hover > .sub-menu { background: #3a3a3a !important; } } @media (max-width: 991px) { /* 991px */ /* Page sidebar */ .page-sidebar { background-color: #2b2b2b; /* light sidebar */ } .page-sidebar .page-sidebar-menu > li > a { border-top: 1px solid #3d3d3d; } .page-sidebar .page-sidebar-menu > li:hover > a, .page-sidebar .page-sidebar-menu > li.open > a { background: #333333; } .page-sidebar .page-sidebar-menu > li:last-child > a { border-bottom: 0 !important; } .page-sidebar .page-sidebar-menu > li .sub-menu { background-color: #2b2b2b !important; } .page-sidebar .page-sidebar-menu .sidebar-search input { background-color: #2b2b2b !important; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light { /* 1st level links */ } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.open > a { background: #333333; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a { background: #333333; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active > a:hover, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li.active.open > a:hover { background: #333333; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu { background: #2b2b2b !important; } .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li:hover > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.open > a, .page-sidebar .page-sidebar-menu.page-sidebar-menu-light > li .sub-menu > li.active > a { background: #333333 !important; } } @media (max-width: 480px) { /* 480px */ .page-header.navbar { /* Top menu */ } .page-header.navbar .top-menu { background-color: #3d3d3d; } .page-header-fixed-mobile .page-header.navbar .top-menu { background-color: #1f1f1f; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle { background-color: #3b3b3b; } .page-header-fixed-mobile .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle { background: none; } .page-header.navbar .top-menu .navbar-nav > li.dropdown-user .dropdown-toggle:hover { background-color: #393939; } } /**** Boby ****/ body { background-color: #3d3d3d; } /**** CSS3 Spinner Bar ****/ .page-spinner-bar > div, .block-spinner-bar > div { background: #da594a; }
{ "content_hash": "660e2df04a158fd9bab8a652dac45293", "timestamp": "", "source": "github", "line_count": 912, "max_line_length": 740, "avg_line_length": 45.2828947368421, "alnum_prop": 0.7098406702503753, "repo_name": "zzsoszz/metronicv37", "id": "95be054c438daa2b833ab4ba643cffccafacb9a5", "size": "41298", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "theme_rtl/assets/admin/layout/css/themes/default-rtl.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "580" }, { "name": "ApacheConf", "bytes": "932" }, { "name": "CSS", "bytes": "9993928" }, { "name": "CoffeeScript", "bytes": "167262" }, { "name": "HTML", "bytes": "155512809" }, { "name": "JavaScript", "bytes": "12960293" }, { "name": "PHP", "bytes": "599248" }, { "name": "Shell", "bytes": "888" } ], "symlink_target": "" }
class <%= migration_class_name %> < ActiveRecord::Migration def up execute <<-EOS -- DELETE from <%=search_context %>; INSERT into <%=search_context %>(name, count,created_at, updated_at) SELECT word, ndoc as count, now() as created_at, now() as updated_at FROM ts_stat( 'SELECT to_tsvector(''simple'', <% sep='';columns.each do |column| -%> <%=sep%>coalesce(<%=column %>,'''') <%sep=" || '' '' ||" -%> <% end -%> ) FROM <%=table_name %> ') EOS end def down execute %Q{DELETE from <%=search_context %>} end end
{ "content_hash": "88c4570c5a6f049db0575ad6d5aa5cab", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 75, "avg_line_length": 29.761904761904763, "alnum_prop": 0.5136, "repo_name": "robmathews/search_steriods", "id": "a272669d45a495b656c57ec492421004f1c936e4", "size": "625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/enable_tsearch/templates/populate_search_terms_migration.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "71409" } ], "symlink_target": "" }
local window = {} window.dressing_visible = true window.showfps = false window.screen_width = 1056 window.screen_height = 672 window.scale = 0.5 window.width = window.screen_width * window.scale --528 window.height = window.screen_height * window.scale --336 return window
{ "content_hash": "0372e34adb8b8707d4205dba089e2145", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 57, "avg_line_length": 25.181818181818183, "alnum_prop": 0.7472924187725631, "repo_name": "hawkthorne/hawkthorne-server-lua", "id": "55e21fb5623295bc53bb7768ff2208d8fcd6584b", "size": "277", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/window.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "551079" }, { "name": "Python", "bytes": "18331" }, { "name": "Shell", "bytes": "656" } ], "symlink_target": "" }
/* **GRUSER -- get user name. *+ * SUBROUTINE GRUSER(STRING, L) * CHARACTER*(*) STRING * INTEGER L * * Return the name of the user running the program. * * Arguments: * STRING : receives user name, truncated or extended with * blanks as necessary. * L : receives the number of characters in VALUE, excluding * trailing blanks. *-- * 13-Nov-1994 [mcs] Absoft FORTRAN callable version for NeXT. *----------------------------------------------------------------------- */ char *getlogin(); void GRUSER(string, length, maxlen, w_length) char *string; int *length; int maxlen; int w_length; { int i; /* * Get the login name of the PGPLOT user. */ char *user = getlogin(); /* * If the user name is not available substitute an empty string. */ if(!user) user = ""; /* * Copy the user name to the output string. */ for(i=0; i<maxlen && user[i]; i++) string[i] = user[i]; /* * Return the un-padded length of the user name string. */ *length = i; /* * Pad to the end of the output string with spaces. */ for( ; i<maxlen; i++) string[i] = ' '; return; }
{ "content_hash": "5a438eb4f0281a8caab23faec3c652bd", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 73, "avg_line_length": 22.830188679245282, "alnum_prop": 0.5355371900826447, "repo_name": "RobinsonLab/pgplot", "id": "c0706fd2924a4e1ab579ec765053541dce3ab2be", "size": "1210", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sys_linux/af77_src/gruser.c", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1460" }, { "name": "C", "bytes": "1069423" }, { "name": "Erlang", "bytes": "33941" }, { "name": "FORTRAN", "bytes": "2375374" }, { "name": "Gnuplot", "bytes": "260" }, { "name": "Objective-C", "bytes": "20150" }, { "name": "Perl", "bytes": "78745" }, { "name": "Shell", "bytes": "97503" }, { "name": "Tcl", "bytes": "16360" } ], "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. --> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="alpha"> <provider>no.such.Provider</provider> <properties> <property name="org.apache.aries.jpa.provider.version" value="[1.0.0,1.0.1]"/> </properties> </persistence-unit> <persistence-unit name="bravo"> <provider>no.such.Provider</provider> <properties> <property name="org.apache.aries.jpa.provider.version" value="[1.1.0,1.1.1]"/> </properties> </persistence-unit> </persistence>
{ "content_hash": "22f974f579ec4c1eabcc07783d19e017", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 121, "avg_line_length": 40.282051282051285, "alnum_prop": 0.7122851686823679, "repo_name": "Cloudyle/aries", "id": "e01a8e32fd3fdc5cd3ad586fd455a5d13e5be710", "size": "1571", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "jpa/jpa-container/src/test/resources/file17/META-INF/persistence.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// ----------------------------------------------------------------------- // <copyright file="IIdentityStorage.cs" company="Asynkron AB"> // Copyright (C) 2015-2020 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; namespace Proto.Cluster.Identity { public interface IIdentityStorage : IDisposable { public Task<StoredActivation?> TryGetExistingActivation( ClusterIdentity clusterIdentity, CancellationToken ct ); public Task<SpawnLock?> TryAcquireLock(ClusterIdentity clusterIdentity, CancellationToken ct); /// <summary> /// Wait on lock, return activation when present. Responsible for deleting stale locks /// </summary> /// <param name="clusterIdentity"></param> /// <param name="ct"></param> /// <returns></returns> public Task<StoredActivation?> WaitForActivation(ClusterIdentity clusterIdentity, CancellationToken ct); public Task RemoveLock(SpawnLock spawnLock, CancellationToken ct); public Task StoreActivation(string memberId, SpawnLock spawnLock, PID pid, CancellationToken ct); public Task RemoveActivation(ClusterIdentity clusterIdentity, PID pid, CancellationToken ct); public Task RemoveMember(string memberId, CancellationToken ct); public Task Init(); } public class SpawnLock { public SpawnLock(string lockId, ClusterIdentity clusterIdentity) { LockId = lockId; ClusterIdentity = clusterIdentity; } public string LockId { get; } public ClusterIdentity ClusterIdentity { get; } } public class StoredActivation { public StoredActivation(string memberId, PID pid) { MemberId = memberId; Pid = pid; } public PID Pid { get; } public string MemberId { get; } } public class StorageFailure : Exception { public StorageFailure(string message) : base(message) { } public StorageFailure(string message, Exception innerException) : base(message, innerException) { } } public class LockNotFoundException : StorageFailure { public LockNotFoundException(string message) : base(message) { } } }
{ "content_hash": "e3a4c446ef40cc22fe689084d6a4a076", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 112, "avg_line_length": 30.493827160493826, "alnum_prop": 0.6060728744939271, "repo_name": "AsynkronIT/protoactor-dotnet", "id": "4ff7cb445ed4939610671b5f34705ee7fe0ce5e8", "size": "2472", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/Proto.Cluster/Identity/IIdentityStorage.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "282" }, { "name": "C#", "bytes": "626451" }, { "name": "Dockerfile", "bytes": "916" } ], "symlink_target": "" }
<!-- GENERATED FROM SOURCE --> # vjs.Button __EXTENDS__: [vjs.Component](vjs.Component.md) __DEFINED IN__: [src/js/button.js#L10](https://github.com/videojs/video.js/blob/master/src/js/button.js#L10) Base class for all buttons --- ## INDEX - [METHODS](#methods) - [init](#init-player-options-ready-) - [addChild](#addchild-child-options-) _`inherited`_ - [addClass](#addclass-classtoadd-) _`inherited`_ - [buildCSSClass](#buildcssclass) _`inherited`_ - [children](#children) _`inherited`_ - [contentEl](#contentel) _`inherited`_ - [createEl](#createel-tagname-attributes-) _`inherited`_ - [dimensions](#dimensions-width-height-) _`inherited`_ - [dispose](#dispose) _`inherited`_ - [el](#el) _`inherited`_ - [enableTouchActivity](#enabletouchactivity) _`inherited`_ - [getChild](#getchild-name-) _`inherited`_ - [getChildById](#getchildbyid-id-) _`inherited`_ - [hasClass](#hasclass-classtocheck-) _`inherited`_ - [height](#height-num-skiplisteners-) _`inherited`_ - [hide](#hide) _`inherited`_ - [id](#id) _`inherited`_ - [initChildren](#initchildren) _`inherited`_ - [name](#name) _`inherited`_ - [off](#off-type-fn-) _`inherited`_ - [on](#on-type-fn-) _`inherited`_ - [one](#one-type-fn-) _`inherited`_ - [options](#options-obj-) _`inherited`_ - [player](#player) _`inherited`_ - [ready](#ready-fn-) _`inherited`_ - [removeChild](#removechild-component-) _`inherited`_ - [removeClass](#removeclass-classtoremove-) _`inherited`_ - [show](#show) _`inherited`_ - [trigger](#trigger-event-) _`inherited`_ - [triggerReady](#triggerready) _`inherited`_ - [width](#width-num-skiplisteners-) _`inherited`_ - [EVENTS](#events) - [resize](#resize-event) _`inherited`_ --- ## METHODS ### addChild( child, [options] ) > Adds a child component inside this component > > myComponent.el(); > // -> <div class='my-component'></div> > myComonent.children(); > // [empty array] > > var myButton = myComponent.addChild('MyButton'); > // -> <div class='my-component'><div class="my-button">myButton<div></div> > // -> myButton === myComonent.children()[0]; > > Pass in options for child constructors and options for children of the child > > var myButton = myComponent.addChild('MyButton', { > text: 'Press Me', > children: { > buttonChildExample: { > buttonChildOption: true > } > } > }); ##### PARAMETERS: * __child__ `String|vjs.Component` The class name or instance of a child to add * __options__ `Object` _(OPTIONAL)_ Options, including options to be passed to children of the child. ##### RETURNS: * `vjs.Component` The child component (created by this process if a string was used) _inherited from_: [src/js/component.js#L356](https://github.com/videojs/video.js/blob/master/src/js/component.js#L356) --- ### addClass( classToAdd ) > Add a CSS class name to the component's element ##### PARAMETERS: * __classToAdd__ `String` Classname to add ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L682](https://github.com/videojs/video.js/blob/master/src/js/component.js#L682) --- ### buildCSSClass() > Allows sub components to stack CSS class names ##### RETURNS: * `String` The constructed class name _inherited from_: [src/js/component.js#L515](https://github.com/videojs/video.js/blob/master/src/js/component.js#L515) --- ### children() > Get an array of all child components > > var kids = myComponent.children(); ##### RETURNS: * `Array` The children _inherited from_: [src/js/component.js#L290](https://github.com/videojs/video.js/blob/master/src/js/component.js#L290) --- ### contentEl() > Return the component's DOM element for embedding content. > Will either be el_ or a new element defined in createEl. ##### RETURNS: * `Element` _inherited from_: [src/js/component.js#L233](https://github.com/videojs/video.js/blob/master/src/js/component.js#L233) --- ### createEl( [tagName], [attributes] ) > Create the component's DOM element ##### PARAMETERS: * __tagName__ `String` _(OPTIONAL)_ Element's node type. e.g. 'div' * __attributes__ `Object` _(OPTIONAL)_ An object of element attributes that should be set on the element ##### RETURNS: * `Element` _inherited from_: [src/js/component.js#L194](https://github.com/videojs/video.js/blob/master/src/js/component.js#L194) --- ### dimensions( width, height ) > Set both width and height at the same time ##### PARAMETERS: * __width__ `Number|String` * __height__ `Number|String` ##### RETURNS: * `vjs.Component` The component _inherited from_: [src/js/component.js#L794](https://github.com/videojs/video.js/blob/master/src/js/component.js#L794) --- ### dispose() > Dispose of the component and all child components _inherited from_: [src/js/component.js#L78](https://github.com/videojs/video.js/blob/master/src/js/component.js#L78) --- ### el() > Get the component's DOM element > > var domEl = myComponent.el(); ##### RETURNS: * `Element` _inherited from_: [src/js/component.js#L214](https://github.com/videojs/video.js/blob/master/src/js/component.js#L214) --- ### enableTouchActivity() > Report user touch activity when touch events occur > > User activity is used to determine when controls should show/hide. It's > relatively simple when it comes to mouse events, because any mouse event > should show the controls. So we capture mouse events that bubble up to the > player and report activity when that happens. > > With touch events it isn't as easy. We can't rely on touch events at the > player level, because a tap (touchstart + touchend) on the video itself on > mobile devices is meant to turn controls off (and on). User activity is > checked asynchronously, so what could happen is a tap event on the video > turns the controls off, then the touchend event bubbles up to the player, > which if it reported user activity, would turn the controls right back on. > (We also don't want to completely block touch events from bubbling up) > > Also a touchmove, touch+hold, and anything other than a tap is not supposed > to turn the controls back on on a mobile device. > > Here we're setting the default component behavior to report user activity > whenever touch events happen, and this can be turned off by components that > want touch events to act differently. _inherited from_: [src/js/component.js#L976](https://github.com/videojs/video.js/blob/master/src/js/component.js#L976) --- ### getChild( name ) > Returns a child component with the provided name ##### PARAMETERS: * __name__ ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L324](https://github.com/videojs/video.js/blob/master/src/js/component.js#L324) --- ### getChildById( id ) > Returns a child component with the provided ID ##### PARAMETERS: * __id__ ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L307](https://github.com/videojs/video.js/blob/master/src/js/component.js#L307) --- ### hasClass( classToCheck ) > Check if a component's element has a CSS class name ##### PARAMETERS: * __classToCheck__ `String` Classname to check ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L672](https://github.com/videojs/video.js/blob/master/src/js/component.js#L672) --- ### height( [num], [skipListeners] ) > Get or set the height of the component (CSS values) > > Setting the video tag dimension values only works with values in pixels. > Percent values will not work. > Some percents can be used, but width()/height() will return the number + %, > not the actual computed width/height. ##### PARAMETERS: * __num__ `Number|String` _(OPTIONAL)_ New component height * __skipListeners__ `Boolean` _(OPTIONAL)_ Skip the resize event trigger ##### RETURNS: * `vjs.Component` This component, when setting the height * `Number|String` The height, when getting _inherited from_: [src/js/component.js#L783](https://github.com/videojs/video.js/blob/master/src/js/component.js#L783) --- ### hide() > Hide the component element if currently showing ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L713](https://github.com/videojs/video.js/blob/master/src/js/component.js#L713) --- ### id() > Get the component's ID > > var id = myComponent.id(); ##### RETURNS: * `String` _inherited from_: [src/js/component.js#L252](https://github.com/videojs/video.js/blob/master/src/js/component.js#L252) --- ### init( player, options, ready ) > the constructor function for the class ##### PARAMETERS: * __player__ * __options__ * __ready__ _defined in_: [src/js/button.js#L15](https://github.com/videojs/video.js/blob/master/src/js/button.js#L15) --- ### initChildren() > Add and initialize default child components from options > > // when an instance of MyComponent is created, all children in options > // will be added to the instance by their name strings and options > MyComponent.prototype.options_.children = { > myChildComponent: { > myChildOption: true > } > } > > // Or when creating the component > var myComp = new MyComponent(player, { > children: { > myChildComponent: { > myChildOption: true > } > } > }); > > The children option can also be an Array of child names or > child options objects (that also include a 'name' key). > > var myComp = new MyComponent(player, { > children: [ > 'button', > { > name: 'button', > someOtherOption: true > } > ] > }); _inherited from_: [src/js/component.js#L475](https://github.com/videojs/video.js/blob/master/src/js/component.js#L475) --- ### name() > Get the component's name. The name is often used to reference the component. > > var name = myComponent.name(); ##### RETURNS: * `String` _inherited from_: [src/js/component.js#L271](https://github.com/videojs/video.js/blob/master/src/js/component.js#L271) --- ### off( [type], [fn] ) > Remove an event listener from the component's element > > myComponent.off("eventName", myFunc); ##### PARAMETERS: * __type__ `String` _(OPTIONAL)_ Event type. Without type it will remove all listeners. * __fn__ `Function` _(OPTIONAL)_ Event listener. Without fn it will remove all listeners for a type. ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L554](https://github.com/videojs/video.js/blob/master/src/js/component.js#L554) --- ### on( type, fn ) > Add an event listener to this component's element > > var myFunc = function(){ > var myPlayer = this; > // Do something when the event is fired > }; > > myPlayer.on("eventName", myFunc); > > The context will be the component. ##### PARAMETERS: * __type__ `String` The event type e.g. 'click' * __fn__ `Function` The event listener ##### RETURNS: * `vjs.Component` self _inherited from_: [src/js/component.js#L540](https://github.com/videojs/video.js/blob/master/src/js/component.js#L540) --- ### one( type, fn ) > Add an event listener to be triggered only once and then removed ##### PARAMETERS: * __type__ `String` Event type * __fn__ `Function` Event listener ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L566](https://github.com/videojs/video.js/blob/master/src/js/component.js#L566) --- ### options( obj ) > Deep merge of options objects > > Whenever a property is an object on both options objects > the two properties will be merged using vjs.obj.deepMerge. > > This is used for merging options for child components. We > want it to be easy to override individual options on a child > component without having to rewrite all the other default options. > > Parent.prototype.options_ = { > children: { > 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, > 'childTwo': {}, > 'childThree': {} > } > } > newOptions = { > children: { > 'childOne': { 'foo': 'baz', 'abc': '123' } > 'childTwo': null, > 'childFour': {} > } > } > > this.options(newOptions); > > RESULT > > { > children: { > 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, > 'childTwo': null, // Disabled. Won't be initialized. > 'childThree': {}, > 'childFour': {} > } > } ##### PARAMETERS: * __obj__ `Object` Object of new option values ##### RETURNS: * `Object` A NEW object of this.options_ and obj merged _inherited from_: [src/js/component.js#L173](https://github.com/videojs/video.js/blob/master/src/js/component.js#L173) --- ### player() > Return the component's player ##### RETURNS: * `vjs.Player` _inherited from_: [src/js/component.js#L120](https://github.com/videojs/video.js/blob/master/src/js/component.js#L120) --- ### ready( fn ) > Bind a listener to the component's ready state > > Different from event listeners in that if the ready event has already happend > it will trigger the function immediately. ##### PARAMETERS: * __fn__ `Function` Ready listener ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L625](https://github.com/videojs/video.js/blob/master/src/js/component.js#L625) --- ### removeChild( component ) > Remove a child component from this component's list of children, and the > child component's element from this component's element ##### PARAMETERS: * __component__ `vjs.Component` Component to remove _inherited from_: [src/js/component.js#L414](https://github.com/videojs/video.js/blob/master/src/js/component.js#L414) --- ### removeClass( classToRemove ) > Remove a CSS class name from the component's element ##### PARAMETERS: * __classToRemove__ `String` Classname to remove ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L693](https://github.com/videojs/video.js/blob/master/src/js/component.js#L693) --- ### show() > Show the component element if hidden ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L703](https://github.com/videojs/video.js/blob/master/src/js/component.js#L703) --- ### trigger( event ) > Trigger an event on an element > > myComponent.trigger('eventName'); > myComponent.trigger({'type':'eventName'}); ##### PARAMETERS: * __event__ `Event|Object|String` A string (the type) or an event object with a type attribute ##### RETURNS: * `vjs.Component` self _inherited from_: [src/js/component.js#L580](https://github.com/videojs/video.js/blob/master/src/js/component.js#L580) --- ### triggerReady() > Trigger the ready listeners ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L644](https://github.com/videojs/video.js/blob/master/src/js/component.js#L644) --- ### width( [num], skipListeners ) > Set or get the width of the component (CSS values) > > Setting the video tag dimension values only works with values in pixels. > Percent values will not work. > Some percents can be used, but width()/height() will return the number + %, > not the actual computed width/height. ##### PARAMETERS: * __num__ `Number|String` _(OPTIONAL)_ Optional width number * __skipListeners__ `Boolean` Skip the 'resize' event trigger ##### RETURNS: * `vjs.Component` This component, when setting the width * `Number|String` The width, when getting _inherited from_: [src/js/component.js#L766](https://github.com/videojs/video.js/blob/master/src/js/component.js#L766) --- ## EVENTS ### resize `EVENT` > Fired when the width and/or height of the component changes _inherited from_: [src/js/component.js#L876](https://github.com/videojs/video.js/blob/master/src/js/component.js#L876) ---
{ "content_hash": "a63b9bcc962225b0c0265f3747195453", "timestamp": "", "source": "github", "line_count": 565, "max_line_length": 118, "avg_line_length": 27.87787610619469, "alnum_prop": 0.6661799250841216, "repo_name": "aregee/vloging", "id": "c151620c63687dd5b66c70fb671bd2412814e52c", "size": "15751", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "packages/contrib/video/public/assets/lib/videojs/docs/api/vjs.Button.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "184045" }, { "name": "Java", "bytes": "3095" }, { "name": "JavaScript", "bytes": "533847" }, { "name": "Perl", "bytes": "48" }, { "name": "Shell", "bytes": "250" } ], "symlink_target": "" }
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * * @category PhpStorm * @author aurelien * @copyright 2014 Efidev * @version CVS: Id:$ */ namespace Funkyproject\Service; interface ServiceInterface { public static function getName(); public static function build(); }
{ "content_hash": "b8e115d6054190c88fb842015a4dcdc0", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 16.25, "alnum_prop": 0.6615384615384615, "repo_name": "funkyproject/symfony-cli-distribution", "id": "0b39eb664638747db7ecf952b5bd942664ac1ecc", "size": "325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Service/ServiceInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "3678" } ], "symlink_target": "" }
package com.alibaba.dubbo.config.spring.schema; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.ConsumerConfig; import com.alibaba.dubbo.config.ModuleConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.ProtocolConfig; import com.alibaba.dubbo.config.ProviderConfig; import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.dubbo.config.spring.AnnotationBean; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.ServiceBean; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * DubboNamespaceHandler * * @author william.liangf * @export */ public class DubboNamespaceHandler extends NamespaceHandlerSupport { static { Version.checkDuplicate(DubboNamespaceHandler.class); } public void init() { registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true)); registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true)); registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true)); registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true)); registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true)); registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true)); registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); } }
{ "content_hash": "045943577f7b307b4d6d8d8b37510433", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 114, "avg_line_length": 47.627906976744185, "alnum_prop": 0.783203125, "repo_name": "way-way/dubbo", "id": "5801c33b66ec50fffa861fbb66975146637f635e", "size": "2671", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3447" }, { "name": "CSS", "bytes": "21097" }, { "name": "Java", "bytes": "5500070" }, { "name": "JavaScript", "bytes": "76109" }, { "name": "Lex", "bytes": "2077" }, { "name": "Shell", "bytes": "7012" }, { "name": "Thrift", "bytes": "668" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>maths: 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.14.0 / maths - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> maths <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-14 11:14:17 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-14 11:14:17 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.0 Formal proof management system dune 3.4.1 Fast, portable, and opinionated build system ocaml 4.12.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.12.1 Official release 4.12.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/maths&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/Maths&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: mathematics&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; ] authors: [ &quot;Jean-Christophe Filliâtre&quot; ] bug-reports: &quot;https://github.com/coq-contribs/maths/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/maths.git&quot; synopsis: &quot;Basic mathematics&quot; description: &quot;&quot;&quot; Basic mathematics (gcd, primality, etc.) from French ``Mathematiques Superieures&#39;&#39; (first year of preparation to high schools)&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/maths/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=c41fb2a85a1a015d2c6188dbe75211ec&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-maths.8.8.0 coq.8.14.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.14.0). The following dependencies couldn&#39;t be met: - coq-maths -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) 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-maths.8.8.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"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </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": "89556700a3408887572b3eab5cdf2adf", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 159, "avg_line_length": 41.74096385542169, "alnum_prop": 0.5380285755520277, "repo_name": "coq-bench/coq-bench.github.io", "id": "b83248d948dc2b5fae82e5961bfc670fb7c38b91", "size": "6955", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.12.1-2.0.8/released/8.14.0/maths/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
{% extends "base.html" %} {% load navigation_tags %} {% load authorization_tags %} {% block content %} {{ block.super }} <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading tight"> <h3 class="has-filters"> Environment List <div class="dropdown pull-right"> <button id="show-filters" data-toggle="collapse" data-target="#the-filters" class="btn btn-primary toggle-filters"> <i class="fa fa-filter"></i> <i class="caret"></i> </button> {% if "dojo.add_development_environment"|has_configuration_permission:"staff" %} <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-wrench"></span> <span class="caret"></span> </button> <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation"> <a href="{% url 'add_dev_env' %}"> <i class="fa fa-plus"></i> New Environment </a> </li> </ul> {% endif %} </div> </h3> </div> <div id="the-filters" class="is-filters panel-body collapse {% if dts.form.has_changed %}in{% endif %}"> {% include "dojo/filter_snippet.html" with form=dts.form %} </div> </div> {% if devs %} <div class="clearfix"> {% include "dojo/paging_snippet.html" with page=devs page_size=True%} </div> <div class="panel panel-default table-responsive"> <table id="test_types" class="tablesorter-bootstrap table table-bordered table-condensed table-striped"> <thead> <tr> <th>{% dojo_sort request 'Environment' 'name' 'asc' %}</th> </tr> </thead> <tbody> {% for de in devs %} <tr> {% if "dojo.change_development_environment"|has_configuration_permission:"staff" %} <td><a href="{% url 'edit_dev_env' de.id %}"> {{ de.name }} </a></td> {% else %} <td> {{ de.name }} </a> </td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> <div class="clearfix"> {% include "dojo/paging_snippet.html" with page=devs page_size=True%} </div> {% else %} <p class="text-center">No environments found.</p> {% endif %} </div> </div> {% endblock %} {% block postscript %} {{ block.super }} <script> $(function () { var availableTags = [ {% for word in name_words %} "{{word}}", {% endfor %} ]; $("#id_name").autocomplete({ source: availableTags }); }); </script> {% include "dojo/filter_js_snippet.html" %} {% endblock %}
{ "content_hash": "3eefcb0822d010c3d84e9d743047b5bc", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 204, "avg_line_length": 45.705882352941174, "alnum_prop": 0.39021879021879025, "repo_name": "rackerlabs/django-DefectDojo", "id": "39dfc8ce2e110b00fb88af00ee2ca589bc0fd0c8", "size": "3885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dojo/templates/dojo/dev_env.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "18132" }, { "name": "Groff", "bytes": "91" }, { "name": "HTML", "bytes": "666571" }, { "name": "JavaScript", "bytes": "6393" }, { "name": "Python", "bytes": "524728" }, { "name": "Shell", "bytes": "20558" }, { "name": "XSLT", "bytes": "6624" } ], "symlink_target": "" }
Template.navigation.events({ 'click .logout': function(event) { event.preventDefault(); Meteor.logout(); Router.go('login'); } });
{ "content_hash": "0e2db090ddde2c7c807c18308c5dfb26", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 35, "avg_line_length": 15.777777777777779, "alnum_prop": 0.647887323943662, "repo_name": "quanbinn/healthygeek", "id": "1e3ae532ed110f21adf04f325bfb11d2ae7e701f", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/templates/navigation.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "255" }, { "name": "HTML", "bytes": "8789" }, { "name": "JavaScript", "bytes": "18508" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//livefyre-cdn.s3.amazonaws.com/libs/sdk/v2.5.1/rc/builds/11/streamhub-sdk.min.css"> <link rel="stylesheet" type="text/css" href="src/css/fycon.css"> <link rel="stylesheet" type="text/css" href="src/css/lf-bootstrap.css"> <link rel="stylesheet" type="text/css" href="src/css/style.css"> <style> #view { /*width:500px;*/ } #comment-editor { width:500px; position: absolute; top: 12px; right: 12px; } legend { text-decoration: underline; text-transform: uppercase; } label { font-style: italic; text-transform: capitalize; padding-left: 2em; } label:after { content: ":"; } button { margin-right: 2em; } </style> <script type="text/javascript" src="//platform.twitter.com/widgets.js"></script> <!--script src="//livefyre-cdn.s3.amazonaws.com/libs/sdk/v2.5.1/rc/builds/11/streamhub-sdk.min.js"></script> <script type="text/javascript" src="http://cdn.livefyre.com/libs/apps/Livefyre/streamhub-wall/v2.2.4-build.159/streamhub-wall.min.js"></script--> </head> <body class="lf"> <form> <legend>authentication</legend> <label>token</label> <button class="auth-login">Log in</button> <input type="text" id="lftoken" value="" /> <br><br> <legend>collection</legend> <label>network</label> <input type="text" id="network" value="livefyre.com" /> <br> <label>environment</label> <input type="text" id="environment" value="qa-ext.livefyre.com" /> <br> <label>site ID</label> <input type="text" id="siteId" value="290596" /> <br> <label>article ID</label> <input type="text" id="articleId" value="136" /> <br> <input type="submit" /><button id="refresh">refresh</button> </form> <section id="upper-controls"> <button id="top-upload">Post Your Photo <i class="fycon-composer-photo"></i></button> <button id="top-comment">Post Your Comment</button> </section> <div id="view"></div> <section id="lower-controls"> <button id="btm-upload">Post Your Photo <i class="fycon-composer-photo"></i></button> <button id="btm-comment">Post Your Comment</button> </section> <div id="comment-editor"></div> <script src="lib/cajon/cajon.js" type="text/javascript"></script> <script src="requirejs.conf.js" type="text/javascript"></script> <script> requirejs({ baseUrl: "" }); </script> <script> require([ // 'streamhub-sdk/content/views/content-list-view', 'streamhub-wall', 'streamhub-sdk/collection', 'streamhub-sdk/auth', 'streamhub-input/upload', 'streamhub-input/upload/button', 'streamhub-input/comment', 'streamhub-input/comment/button', 'auth-delegates/delegates/livefyre' ],function (View, Collection, Auth, Upload, UploadButton, CommentView, CommentButton, LivefyreAuthDelegate) { /* var opts = { "network": "labs-t402.fyre.co", "siteId": "303827", "articleId": "xbox-0", "environment": "t402.livefyre.com" }; */ // var opts = {/* TESTING OPTS */ // "network": "livefyre.com", // "siteId": "290596", // "articleId": "177", // "environment": "qa-ext.livefyre.com" // }; var opts, view, collection, archive, inputs, embUp, embCom, topUp, topCom, btmUp, btmCom, $form; var authDelegate = window.AD = new LivefyreAuthDelegate('136', '290596', 'https://qa-ext.livefyre.com'); var authUser = authDelegate.getUser(); authUser.on('login', function () { var $tokenInput = $('#lftoken'); var token = authUser.get('token'); $tokenInput.val(token); }); Auth.setDelegate(authDelegate); view = new View({ initial: 5, showMore: 4, el: document.getElementById("view") }); // var onwriteFn = collection._writableState.onwrite; // collection._writableState.onwrite = function(err) { // onwriteFn(err); // if (err === 'FORBIDDEN') { // if (Auth.getToken()) { // throw 'User is not permitted to write content to this collection'; // } // //User needs to authenticate // //TODO (joao) authenticate user // //TODO (joao) retry the upload? // } // } embCom = new CommentView({ el: document.getElementById("comment-editor") }); embCom.render(); topUp = new UploadButton({ el: document.getElementById("top-upload") }); topCom = new CommentButton({ el: document.getElementById("top-comment") }); // btmUp = new UploadButton({ // el: document.getElementById("btm-upload") // }); btmCom = new CommentButton({ el: document.getElementById("btm-comment") }); inputs = [embCom, topUp, topCom, btmUp, btmCom]; $(function () { $('.auth-login').click(function () { authDelegate.login(); }); var url = window.location.href; var query = url.split('?')[1]; if (!query) { return $; } var pairs = query.split('&'); opts = {}; pairs.forEach(function(s) { var pair = s.split('='); opts[pair[0]] = pair[1]; $('#' + pair[0]).val(pair[1]); }); submit(); }); $('#refresh').click(function () { submit(); !opts && (opts = {}); opts.lftoken = Auth.getToken(); var subStr = $.param(opts); var loc = window.location.href.split('?')[0]; loc += '?' + subStr; window.location.href = loc; }); $form = $('form'); $form.submit(submit); function submit(e) { e && e.preventDefault(); var token = $('#lftoken').val(), network = $('#network').val(), environment = $('#environment').val(), site = $('#siteId').val(), article = $('#articleId').val(); token && Auth.setToken(token); if (!network || !environment || !site || !article) { return; } opts = { network: network, environment: environment, siteId: site, articleId: article } if (collection) { destroy(); } build(opts); } function build(opts) { collection = new Collection(opts); collection.pipe(view); archive = collection.createArchive(); archive.pipe(view.more); inputs.forEach(function (o) { o && o.pipe(collection); }); } function destroy() { inputs.forEach(function (o) { o && o.unpipe(collection); }); collection.unpipe(view); archive.unpipe(view); //TODO (joao) Destroy collection? archive = collection = null; } }); </script> </body> </html>
{ "content_hash": "0b3d5b680f2a26cef388998b2a80d828", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 149, "avg_line_length": 33.049056603773586, "alnum_prop": 0.44370860927152317, "repo_name": "Joao-S-Martins/streamhub-input", "id": "c6cbc04767893dd06ad545e1defe4c3776513dbf", "size": "8758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11292" }, { "name": "JavaScript", "bytes": "75013" } ], "symlink_target": "" }
package org.camunda.bpm.model.xml.testmodel; import org.camunda.bpm.model.xml.ModelInstance; import org.camunda.bpm.model.xml.impl.ModelInstanceImpl; import org.camunda.bpm.model.xml.impl.parser.AbstractModelParser; import org.camunda.bpm.model.xml.testmodel.instance.*; import org.junit.After; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.InputStream; /** * @author Sebastian Menski */ @RunWith(Parameterized.class) public abstract class TestModelTest { protected final String testName; private final ModelInstance testModelInstance; private final AbstractModelParser modelParser; // cloned model instance for every test method (see subclasses) protected ModelInstance modelInstance; public TestModelTest(String testName, ModelInstance testModelInstance, AbstractModelParser modelParser) { this.testName = testName; this.testModelInstance = testModelInstance; this.modelParser = modelParser; } public ModelInstance cloneModelInstance() { return testModelInstance.clone(); } protected static Object[] parseModel(Class<?> test) { TestModelParser modelParser = new TestModelParser(); String testXml = test.getSimpleName() + ".xml"; InputStream testXmlAsStream = test.getResourceAsStream(testXml); ModelInstance modelInstance = modelParser.parseModelFromStream(testXmlAsStream); return new Object[]{"parsed", modelInstance, modelParser}; } public static Bird createBird(ModelInstance modelInstance, String id, Gender gender) { Bird bird = modelInstance.newInstance(Bird.class, id); bird.setGender(gender); Animals animals = (Animals) modelInstance.getDocumentElement(); animals.getAnimals().add(bird); return bird; } protected static RelationshipDefinition createRelationshipDefinition(ModelInstance modelInstance, Animal animalInRelationshipWith, Class<? extends RelationshipDefinition> relationshipDefinitionClass) { RelationshipDefinition relationshipDefinition = modelInstance.newInstance(relationshipDefinitionClass, "relationship-" + animalInRelationshipWith.getId()); relationshipDefinition.setAnimal(animalInRelationshipWith); return relationshipDefinition; } public static void addRelationshipDefinition(Animal animalWithRelationship, RelationshipDefinition relationshipDefinition) { Animal animalInRelationshipWith = relationshipDefinition.getAnimal(); relationshipDefinition.setId(animalWithRelationship.getId() + "-" + animalInRelationshipWith.getId()); animalWithRelationship.getRelationshipDefinitions().add(relationshipDefinition); } public static Egg createEgg(ModelInstance modelInstance, String id) { Egg egg = modelInstance.newInstance(Egg.class, id); return egg; } @After public void validateModel() { modelParser.validateModel(modelInstance.getDocument()); } }
{ "content_hash": "393d517b4352711d26ca612b3e57f60d", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 203, "avg_line_length": 38.83783783783784, "alnum_prop": 0.7894919972164232, "repo_name": "camunda/camunda-bpm-platform", "id": "1e0ddec08281c9564ae4519e699c74d782e5be1e", "size": "3681", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "model-api/xml-model/src/test/java/org/camunda/bpm/model/xml/testmodel/TestModelTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8608" }, { "name": "CSS", "bytes": "5486" }, { "name": "Fluent", "bytes": "3111" }, { "name": "FreeMarker", "bytes": "1443842" }, { "name": "Groovy", "bytes": "1904" }, { "name": "HTML", "bytes": "961289" }, { "name": "Handlebars", "bytes": "759" }, { "name": "Java", "bytes": "44079665" }, { "name": "JavaScript", "bytes": "3064086" }, { "name": "Less", "bytes": "154956" }, { "name": "Python", "bytes": "192" }, { "name": "Ruby", "bytes": "60" }, { "name": "SQLPL", "bytes": "44180" }, { "name": "Shell", "bytes": "11634" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.RedisCache { using Microsoft.Azure.Commands.RedisCache.Models; using Microsoft.Azure.Commands.RedisCache.Properties; using ResourceManager.Common.ArgumentCompleters; using System; using System.Management.Automation; [Cmdlet(VerbsCommon.Set, "AzureRmRedisCacheDiagnostics", SupportsShouldProcess = true), OutputType(typeof(void))] public class SetAzureRedisCacheDiagnostics : RedisCacheCmdletBase { [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = false, HelpMessage = "Name of resource group under which cache exists.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Name of redis cache.")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "ARM Resource Id for storage account.")] [ValidateNotNullOrEmpty] public string StorageAccountId { get; set; } public override void ExecuteCmdlet() { Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name); ResourceGroupName = CacheClient.GetResourceGroupNameIfNotProvided(ResourceGroupName, Name); string storageAccountName = GetStorageAccountName(StorageAccountId); RedisCacheAttributes cache = new RedisCacheAttributes(CacheClient.GetCache(ResourceGroupName, Name), ResourceGroupName); ConfirmAction( string.Format(Resources.SetRedisCacheDiagnostics, Name), Name, () => { CacheClient.SetDiagnostics(cache.Id, storageAccountName); }); } private string GetStorageAccountName(string storageAccountId) { Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name); if (string.IsNullOrEmpty(storageAccountId)) { throw new ArgumentException(Resources.StorageAccountIdException); } else { string[] resourceParts = storageAccountId.Split('/'); // Valid ARM uri when split on '/' should have 9 parts. Ex: /subscriptions/<sub-id>/resourceGroups/<resource group name>/providers/Microsoft.ClassicStorage/storageAccounts/<account name> if (resourceParts.Length != 9) { throw new ArgumentException(Resources.StorageAccountIdException); } return resourceParts[8]; } } } }
{ "content_hash": "f6a8ff98537dc06cb3b48b8404e628dd", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 202, "avg_line_length": 47.16216216216216, "alnum_prop": 0.645272206303725, "repo_name": "devigned/azure-powershell", "id": "0d57cf15feb6a0b6dc46bb5ba9c23dba89c5e396", "size": "3492", "binary": false, "copies": "3", "ref": "refs/heads/preview", "path": "src/ResourceManager/RedisCache/Commands.RedisCache/Commands/SetAzureRedisCacheDiagnostics.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "18388" }, { "name": "C#", "bytes": "60706952" }, { "name": "HTML", "bytes": "209" }, { "name": "JavaScript", "bytes": "4979" }, { "name": "PHP", "bytes": "41" }, { "name": "PowerShell", "bytes": "7187413" }, { "name": "Ruby", "bytes": "398" }, { "name": "Shell", "bytes": "50" }, { "name": "Smalltalk", "bytes": "2510" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
package org.apache.calcite.prepare; import org.apache.calcite.jdbc.CalciteSchema; import org.apache.calcite.linq4j.Enumerable; import org.apache.calcite.linq4j.Grouping; import org.apache.calcite.linq4j.OrderedQueryable; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.linq4j.QueryableDefaults; import org.apache.calcite.linq4j.QueryableFactory; import org.apache.calcite.linq4j.function.BigDecimalFunction1; import org.apache.calcite.linq4j.function.DoubleFunction1; import org.apache.calcite.linq4j.function.EqualityComparer; import org.apache.calcite.linq4j.function.FloatFunction1; import org.apache.calcite.linq4j.function.Function1; import org.apache.calcite.linq4j.function.Function2; import org.apache.calcite.linq4j.function.IntegerFunction1; import org.apache.calcite.linq4j.function.LongFunction1; import org.apache.calcite.linq4j.function.NullableBigDecimalFunction1; import org.apache.calcite.linq4j.function.NullableDoubleFunction1; import org.apache.calcite.linq4j.function.NullableFloatFunction1; import org.apache.calcite.linq4j.function.NullableIntegerFunction1; import org.apache.calcite.linq4j.function.NullableLongFunction1; import org.apache.calcite.linq4j.function.Predicate1; import org.apache.calcite.linq4j.function.Predicate2; import org.apache.calcite.linq4j.tree.FunctionExpression; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.logical.LogicalFilter; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.logical.LogicalTableScan; import org.apache.calcite.rex.RexNode; import org.apache.calcite.schema.QueryableTable; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.schema.impl.AbstractTableQueryable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import java.math.BigDecimal; import java.util.Comparator; import java.util.List; import static org.apache.calcite.linq4j.Nullness.castNonNull; import static java.util.Objects.requireNonNull; /** * Implementation of {@link QueryableFactory} * that builds a tree of {@link RelNode} planner nodes. Used by * {@link LixToRelTranslator}. * * <p>Each of the methods that implements a {@code Replayer} method creates * a tree of {@code RelNode}s equivalent to the arguments, and calls * {@link #setRel} to assign the root of that tree to the {@link #rel} member * variable.</p> * * <p>To comply with the {@link org.apache.calcite.linq4j.QueryableFactory} * interface, which is after all a factory, each method returns a dummy result * such as {@code null} or {@code 0}. * The caller will not use the result. * The real effect of the method is to * call {@link #setRel} with a {@code RelNode}.</p> * * <p>NOTE: Many methods currently throw {@link UnsupportedOperationException}. * These method need to be implemented.</p> * * @param <T> Element type */ class QueryableRelBuilder<T> implements QueryableFactory<T> { private final LixToRelTranslator translator; private @Nullable RelNode rel; QueryableRelBuilder(LixToRelTranslator translator) { this.translator = translator; } RelNode toRel(Queryable<T> queryable) { if (queryable instanceof QueryableDefaults.Replayable) { //noinspection unchecked ((QueryableDefaults.Replayable) queryable).replay(this); return requireNonNull(rel, "rel"); } if (queryable instanceof AbstractTableQueryable) { final AbstractTableQueryable tableQueryable = (AbstractTableQueryable) queryable; final QueryableTable table = tableQueryable.table; final CalciteSchema.TableEntry tableEntry = CalciteSchema.from(tableQueryable.schema) .add(tableQueryable.tableName, tableQueryable.table); final RelOptTableImpl relOptTable = RelOptTableImpl.create(null, table.getRowType(translator.typeFactory), tableEntry, null); if (table instanceof TranslatableTable) { return ((TranslatableTable) table).toRel(translator.toRelContext(), relOptTable); } else { return LogicalTableScan.create(translator.cluster, relOptTable, ImmutableList.of()); } } return translator.translate( requireNonNull( queryable.getExpression(), () -> "null expression from " + queryable)); } /** Sets the output of this event. */ private void setRel(RelNode rel) { this.rel = rel; } // ~ Methods from QueryableFactory ----------------------------------------- @Override public <TAccumulate, TResult> TResult aggregate( Queryable<T> source, TAccumulate seed, FunctionExpression<Function2<TAccumulate, T, TAccumulate>> func, FunctionExpression<Function1<TAccumulate, TResult>> selector) { throw new UnsupportedOperationException(); } @Override public T aggregate( Queryable<T> source, FunctionExpression<Function2<@Nullable T, T, T>> selector) { throw new UnsupportedOperationException(); } @Override public <TAccumulate> TAccumulate aggregate( Queryable<T> source, TAccumulate seed, FunctionExpression<Function2<TAccumulate, T, TAccumulate>> selector) { throw new UnsupportedOperationException(); } @Override public boolean all( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public boolean any(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public boolean any( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public BigDecimal averageBigDecimal( Queryable<T> source, FunctionExpression<BigDecimalFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public BigDecimal averageNullableBigDecimal( Queryable<T> source, FunctionExpression<NullableBigDecimalFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public double averageDouble( Queryable<T> source, FunctionExpression<DoubleFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Double averageNullableDouble( Queryable<T> source, FunctionExpression<NullableDoubleFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public int averageInteger( Queryable<T> source, FunctionExpression<IntegerFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Integer averageNullableInteger( Queryable<T> source, FunctionExpression<NullableIntegerFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public float averageFloat( Queryable<T> source, FunctionExpression<FloatFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Float averageNullableFloat( Queryable<T> source, FunctionExpression<NullableFloatFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public long averageLong( Queryable<T> source, FunctionExpression<LongFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Long averageNullableLong( Queryable<T> source, FunctionExpression<NullableLongFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Queryable<T> concat( Queryable<T> source, Enumerable<T> source2) { throw new UnsupportedOperationException(); } @Override public boolean contains( Queryable<T> source, T element) { throw new UnsupportedOperationException(); } @Override public boolean contains( Queryable<T> source, T element, EqualityComparer<T> comparer) { throw new UnsupportedOperationException(); } @Override public int count(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public int count( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public Queryable<@Nullable T> defaultIfEmpty(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public Queryable<@PolyNull T> defaultIfEmpty(Queryable<T> source, @PolyNull T value) { throw new UnsupportedOperationException(); } @Override public Queryable<T> distinct( Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public Queryable<T> distinct( Queryable<T> source, EqualityComparer<T> comparer) { throw new UnsupportedOperationException(); } @Override public T elementAt(Queryable<T> source, int index) { throw new UnsupportedOperationException(); } @Override public T elementAtOrDefault(Queryable<T> source, int index) { throw new UnsupportedOperationException(); } @Override public Queryable<T> except( Queryable<T> source, Enumerable<T> enumerable) { return except(source, enumerable, false); } @Override public Queryable<T> except( Queryable<T> source, Enumerable<T> enumerable, boolean all) { throw new UnsupportedOperationException(); } @Override public Queryable<T> except( Queryable<T> source, Enumerable<T> enumerable, EqualityComparer<T> tEqualityComparer) { return except(source, enumerable, tEqualityComparer, false); } @Override public Queryable<T> except( Queryable<T> source, Enumerable<T> enumerable, EqualityComparer<T> tEqualityComparer, boolean all) { throw new UnsupportedOperationException(); } @Override public T first(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T first( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public T firstOrDefault( Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T firstOrDefault( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public <TKey> Queryable<Grouping<TKey, T>> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector) { throw new UnsupportedOperationException(); } @Override public <TKey> Queryable<Grouping<TKey, T>> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public <TKey, TElement> Queryable<Grouping<TKey, TElement>> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function1<T, TElement>> elementSelector) { throw new UnsupportedOperationException(); } @Override public <TKey, TResult> Queryable<TResult> groupByK( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function2<TKey, Enumerable<T>, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public <TKey, TElement> Queryable<Grouping<TKey, TElement>> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function1<T, TElement>> elementSelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public <TKey, TResult> Queryable<TResult> groupByK( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function2<TKey, Enumerable<T>, TResult>> elementSelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public <TKey, TElement, TResult> Queryable<TResult> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function1<T, TElement>> elementSelector, FunctionExpression<Function2<TKey, Enumerable<TElement>, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public <TKey, TElement, TResult> Queryable<TResult> groupBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, FunctionExpression<Function1<T, TElement>> elementSelector, FunctionExpression<Function2<TKey, Enumerable<TElement>, TResult>> resultSelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public <TInner, TKey, TResult> Queryable<TResult> groupJoin( Queryable<T> source, Enumerable<TInner> inner, FunctionExpression<Function1<T, TKey>> outerKeySelector, FunctionExpression<Function1<TInner, TKey>> innerKeySelector, FunctionExpression<Function2<T, Enumerable<TInner>, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public <TInner, TKey, TResult> Queryable<TResult> groupJoin( Queryable<T> source, Enumerable<TInner> inner, FunctionExpression<Function1<T, TKey>> outerKeySelector, FunctionExpression<Function1<TInner, TKey>> innerKeySelector, FunctionExpression<Function2<T, Enumerable<TInner>, TResult>> resultSelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public Queryable<T> intersect( Queryable<T> source, Enumerable<T> enumerable) { return intersect(source, enumerable, false); } @Override public Queryable<T> intersect( Queryable<T> source, Enumerable<T> enumerable, boolean all) { throw new UnsupportedOperationException(); } @Override public Queryable<T> intersect( Queryable<T> source, Enumerable<T> enumerable, EqualityComparer<T> tEqualityComparer) { return intersect(source, enumerable, tEqualityComparer, false); } @Override public Queryable<T> intersect( Queryable<T> source, Enumerable<T> enumerable, EqualityComparer<T> tEqualityComparer, boolean all) { throw new UnsupportedOperationException(); } @Override public <TInner, TKey, TResult> Queryable<TResult> join( Queryable<T> source, Enumerable<TInner> inner, FunctionExpression<Function1<T, TKey>> outerKeySelector, FunctionExpression<Function1<TInner, TKey>> innerKeySelector, FunctionExpression<Function2<T, TInner, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public <TInner, TKey, TResult> Queryable<TResult> join( Queryable<T> source, Enumerable<TInner> inner, FunctionExpression<Function1<T, TKey>> outerKeySelector, FunctionExpression<Function1<TInner, TKey>> innerKeySelector, FunctionExpression<Function2<T, TInner, TResult>> resultSelector, EqualityComparer<TKey> comparer) { throw new UnsupportedOperationException(); } @Override public T last(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T last( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public T lastOrDefault( Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T lastOrDefault( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public long longCount(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public long longCount( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public T max(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public <TResult extends Comparable<TResult>> TResult max( Queryable<T> source, FunctionExpression<Function1<T, TResult>> selector) { throw new UnsupportedOperationException(); } @Override public T min(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public <TResult extends Comparable<TResult>> TResult min( Queryable<T> source, FunctionExpression<Function1<T, TResult>> selector) { throw new UnsupportedOperationException(); } @Override public <TResult> Queryable<TResult> ofType( Queryable<T> source, Class<TResult> clazz) { throw new UnsupportedOperationException(); } @Override public <T2> Queryable<T2> cast( Queryable<T> source, Class<T2> clazz) { throw new UnsupportedOperationException(); } @Override public <TKey extends Comparable> OrderedQueryable<T> orderBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector) { throw new UnsupportedOperationException(); } @Override public <TKey> OrderedQueryable<T> orderBy( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, Comparator<TKey> comparator) { throw new UnsupportedOperationException(); } @Override public <TKey extends Comparable> OrderedQueryable<T> orderByDescending( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector) { throw new UnsupportedOperationException(); } @Override public <TKey> OrderedQueryable<T> orderByDescending( Queryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, Comparator<TKey> comparator) { throw new UnsupportedOperationException(); } @Override public Queryable<T> reverse( Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public <TResult> Queryable<TResult> select( Queryable<T> source, FunctionExpression<Function1<T, TResult>> selector) { RelNode child = toRel(source); List<RexNode> nodes = translator.toRexList(selector, child); setRel( LogicalProject.create(child, ImmutableList.of(), nodes, (List<String>) null, ImmutableSet.of())); return castNonNull(null); } @Override public <TResult> Queryable<TResult> selectN( Queryable<T> source, FunctionExpression<Function2<T, Integer, TResult>> selector) { throw new UnsupportedOperationException(); } @Override public <TResult> Queryable<TResult> selectMany( Queryable<T> source, FunctionExpression<Function1<T, Enumerable<TResult>>> selector) { throw new UnsupportedOperationException(); } @Override public <TResult> Queryable<TResult> selectManyN( Queryable<T> source, FunctionExpression<Function2<T, Integer, Enumerable<TResult>>> selector) { throw new UnsupportedOperationException(); } @Override public <TCollection, TResult> Queryable<TResult> selectMany( Queryable<T> source, FunctionExpression<Function2<T, Integer, Enumerable<TCollection>>> collectionSelector, FunctionExpression<Function2<T, TCollection, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public <TCollection, TResult> Queryable<TResult> selectManyN( Queryable<T> source, FunctionExpression<Function1<T, Enumerable<TCollection>>> collectionSelector, FunctionExpression<Function2<T, TCollection, TResult>> resultSelector) { throw new UnsupportedOperationException(); } @Override public boolean sequenceEqual( Queryable<T> source, Enumerable<T> enumerable) { throw new UnsupportedOperationException(); } @Override public boolean sequenceEqual( Queryable<T> source, Enumerable<T> enumerable, EqualityComparer<T> tEqualityComparer) { throw new UnsupportedOperationException(); } @Override public T single(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T single( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public T singleOrDefault(Queryable<T> source) { throw new UnsupportedOperationException(); } @Override public T singleOrDefault( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public Queryable<T> skip( Queryable<T> source, int count) { throw new UnsupportedOperationException(); } @Override public Queryable<T> skipWhile( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public Queryable<T> skipWhileN( Queryable<T> source, FunctionExpression<Predicate2<T, Integer>> predicate) { throw new UnsupportedOperationException(); } @Override public BigDecimal sumBigDecimal( Queryable<T> source, FunctionExpression<BigDecimalFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public BigDecimal sumNullableBigDecimal( Queryable<T> source, FunctionExpression<NullableBigDecimalFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public double sumDouble( Queryable<T> source, FunctionExpression<DoubleFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Double sumNullableDouble( Queryable<T> source, FunctionExpression<NullableDoubleFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public int sumInteger( Queryable<T> source, FunctionExpression<IntegerFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Integer sumNullableInteger( Queryable<T> source, FunctionExpression<NullableIntegerFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public long sumLong( Queryable<T> source, FunctionExpression<LongFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Long sumNullableLong( Queryable<T> source, FunctionExpression<NullableLongFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public float sumFloat( Queryable<T> source, FunctionExpression<FloatFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Float sumNullableFloat( Queryable<T> source, FunctionExpression<NullableFloatFunction1<T>> selector) { throw new UnsupportedOperationException(); } @Override public Queryable<T> take( Queryable<T> source, int count) { throw new UnsupportedOperationException(); } @Override public Queryable<T> takeWhile( Queryable<T> source, FunctionExpression<Predicate1<T>> predicate) { throw new UnsupportedOperationException(); } @Override public Queryable<T> takeWhileN( Queryable<T> source, FunctionExpression<Predicate2<T, Integer>> predicate) { throw new UnsupportedOperationException(); } @Override public <TKey extends Comparable<TKey>> OrderedQueryable<T> thenBy( OrderedQueryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector) { throw new UnsupportedOperationException(); } @Override public <TKey> OrderedQueryable<T> thenBy( OrderedQueryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, Comparator<TKey> comparator) { throw new UnsupportedOperationException(); } @Override public <TKey extends Comparable<TKey>> OrderedQueryable<T> thenByDescending( OrderedQueryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector) { throw new UnsupportedOperationException(); } @Override public <TKey> OrderedQueryable<T> thenByDescending( OrderedQueryable<T> source, FunctionExpression<Function1<T, TKey>> keySelector, Comparator<TKey> comparator) { throw new UnsupportedOperationException(); } @Override public Queryable<T> union( Queryable<T> source, Enumerable<T> source1) { throw new UnsupportedOperationException(); } @Override public Queryable<T> union( Queryable<T> source, Enumerable<T> source1, EqualityComparer<T> tEqualityComparer) { throw new UnsupportedOperationException(); } @Override public Queryable<T> where( Queryable<T> source, FunctionExpression<? extends Predicate1<T>> predicate) { RelNode child = toRel(source); RexNode node = translator.toRex(predicate, child); setRel(LogicalFilter.create(child, node)); return source; } @Override public Queryable<T> whereN( Queryable<T> source, FunctionExpression<? extends Predicate2<T, Integer>> predicate) { throw new UnsupportedOperationException(); } @Override public <T1, TResult> Queryable<TResult> zip( Queryable<T> source, Enumerable<T1> source1, FunctionExpression<Function2<T, T1, TResult>> resultSelector) { throw new UnsupportedOperationException(); } }
{ "content_hash": "9e65db145eb5c6283231473e97bd3c39", "timestamp": "", "source": "github", "line_count": 762, "max_line_length": 92, "avg_line_length": 33.49737532808399, "alnum_prop": 0.7249363369245837, "repo_name": "looker-open-source/calcite", "id": "4731e029ddcb7697b92874cb297eda80f25f7b4c", "size": "26322", "binary": false, "copies": "3", "ref": "refs/heads/looker", "path": "core/src/main/java/org/apache/calcite/prepare/QueryableRelBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4392" }, { "name": "FreeMarker", "bytes": "20115" }, { "name": "HTML", "bytes": "40994" }, { "name": "Java", "bytes": "21031100" }, { "name": "Kotlin", "bytes": "157472" }, { "name": "PigLatin", "bytes": "1419" }, { "name": "Python", "bytes": "1610" }, { "name": "Ruby", "bytes": "2851" }, { "name": "SCSS", "bytes": "36833" }, { "name": "Shell", "bytes": "8012" } ], "symlink_target": "" }
<?php /** * Created by mcfedr on 27/06/15 12:42 */ namespace Ekreative\RedmineLoginBundle\Client; use Ekreative\RedmineLoginBundle\Security\RedmineUser; use GuzzleHttp\Client; class ClientProvider { public function __construct($redmine) { $this->redmine = $redmine; } public function get(RedmineUser $user) { return new Client([ 'base_uri' => $this->redmine, 'headers' => [ 'X-Redmine-API-Key' => $user->getApiKey() ] ]); } }
{ "content_hash": "3da3b22a22c2338ab9ac0fc106d8a1b7", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 57, "avg_line_length": 19.703703703703702, "alnum_prop": 0.575187969924812, "repo_name": "ahonymous/redmine-login", "id": "83c2e8d8723aa83fed69d934df2d467047d1be0c", "size": "532", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Ekreative/RedmineLoginBundle/Client/ClientProvider.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "839" }, { "name": "PHP", "bytes": "22049" } ], "symlink_target": "" }
var express = require('express') var bodyParser = require('body-parser'); var multer = require('multer'); var app = express(); var cool = require('cool-ascii-faces'); var pg = require('pg'); var connectionString = process.env.DATABASE_URL || 'postgres://yerojcuolrgxkw:slt5jv9rdW35yBUkYDco0xWTlQ@ec2-107-21-102-69.compute-1.amazonaws.com:5432/d6phr6fpg5fdgg?ssl=true'; app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data app.set('port', (process.env.PORT || 5000)) // app.get('/', function(request, response) { // response.send(cool()); // }); var api = express() api.get('/todos', function(request, response) { pg.connect(connectionString, function(err, client, done) { client.query('SELECT * FROM todos', function(err, result) { done(); if (err) { console.error(err); response.send("Error " + err); } else { response.send(result.rows); } }); }); }); api.post('/todos', function(request, response) { pg.connect(connectionString, function(err, client, done) { client.query("INSERT INTO todos(story) values($1)", [request.body.story], function(err, result) { done(); if (err) { console.error(err); response.send("Error " + err); } else { response.send(result); // response.json(request.body); } }); }); }); api.get('/equipments', function(request, response) { pg.connect(connectionString, function(err, client, done) { client.query('SELECT * FROM equipments', function(err, result) { done(); if (err) { console.error(err); response.send("Error " + err); } else { response.send(result.rows); } }); }); }); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')) }); app // .use('/assets', express.static(path.join(__dirname, 'assets'))) .use('/api', api) .use(express.static('www')) // .use(renderApp) ;
{ "content_hash": "d52454e5b41a93e54736dc0a7730c53d", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 177, "avg_line_length": 26.324675324675326, "alnum_prop": 0.6517020226936359, "repo_name": "kronis/kronis-server-boilerplate", "id": "c2c5717950076cd8b1601b57774385a79379ef08", "size": "2027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2027" } ], "symlink_target": "" }
var utils = utils || []; (function() { /** * Flip-flops two classes * @param {HTMLElement} $el * @param {String} _class * @return {Object} * * Usage: * utils.swapClass(document.getElementById('some-element'), 'class1').forClass('class2'); */ var swapClass = function($el, _class) { $el.classList.remove(_class); // chain this method return { forClass: function(__class) { return forClass.call(this, $el, __class); } }; }; ///////////////////////////////////////////////////////////////////// function forClass($el, _class) { $el.classList.add(_class); } utils.swapClass = swapClass; }());
{ "content_hash": "729e018a9b96c0a40160eddfd42a4368", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 91, "avg_line_length": 19.970588235294116, "alnum_prop": 0.5051546391752577, "repo_name": "jzucadi/web-animations", "id": "5d147e651843a9c3d0101900ad7b1d7aeba93d3f", "size": "888", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/lib/scripts/utils/swap-class.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23758" }, { "name": "HTML", "bytes": "12728" }, { "name": "JavaScript", "bytes": "43732" } ], "symlink_target": "" }
#pragma once #include <string> #include <reflectionzeug/reflectionzeug_api.h> namespace reflectionzeug { /** * @brief * Interface for typed values to be accessed via strings * * @remarks * Since toString/fromString exist in every property, * this interface is empty. It is still important and can be * used to indicate that a property type shall be treated as * a string value. */ class REFLECTIONZEUG_API AbstractStringInterface { public: /** * @brief * Constructor */ AbstractStringInterface(); /** * @brief * Destructor */ virtual ~AbstractStringInterface(); }; } // namespace reflectionzeug
{ "content_hash": "21abe16eb7515a67545f7a1310e0f7e9", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 62, "avg_line_length": 16.365853658536587, "alnum_prop": 0.6676602086438153, "repo_name": "cginternals/libzeug", "id": "b06053c4ec98165c7857d7e365ddee720ff2ce30", "size": "671", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "source/reflectionzeug/include/reflectionzeug/property/AbstractStringInterface.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3652052" }, { "name": "C++", "bytes": "4403953" }, { "name": "CMake", "bytes": "124201" }, { "name": "M4", "bytes": "25387" }, { "name": "Makefile", "bytes": "25779" }, { "name": "Objective-C", "bytes": "4379" }, { "name": "Python", "bytes": "471029" }, { "name": "Shell", "bytes": "26517" } ], "symlink_target": "" }
package sqlancer.common.ast.newast; import sqlancer.common.ast.BinaryOperatorNode.Operator; public class NewUnaryPrefixOperatorNode<T> implements Node<T> { protected final Operator op; private final Node<T> expr; public NewUnaryPrefixOperatorNode(Node<T> expr, Operator op) { this.expr = expr; this.op = op; } public String getOperatorRepresentation() { return op.getTextRepresentation(); } public Node<T> getExpr() { return expr; } }
{ "content_hash": "36edad0ad9a28422bcde71504312d5f9", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 66, "avg_line_length": 22, "alnum_prop": 0.6758893280632411, "repo_name": "sqlancer/sqlancer", "id": "5274bd94224e01b6f31ecf17763d1d4999d058d9", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sqlancer/common/ast/newast/NewUnaryPrefixOperatorNode.java", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "313" }, { "name": "Java", "bytes": "2657308" }, { "name": "Python", "bytes": "951" } ], "symlink_target": "" }
#ifndef KALLISTO_MULTINOMIAL_H #define KALLISTO_MULTINOMIAL_H #include <stdexcept> #include <random> class Multinomial { public: Multinomial(const std::vector<int>& counts, size_t seed = 42) : counts_(counts), gen_(seed), dd_(counts_.begin(), counts_.end()), n_(0) { for (auto c : counts_) { n_ += c; } } /** * Generate a sample from the multinomial distribution * * Note that calling this function with nsamp != n() will not result in * a "proper" multinomial, though, it might be useful as long as it is * understood that only samples that have the same nsamp are * comparable. Call sample() for a standard multinomial. * * @param nsamp the number of samples. default == -1, which means it * will default to n_ * @return a vector of counts * */ std::vector<int> sample(int nsamp) { if (nsamp < 1) { throw std::domain_error("nsamp must be -1 or >=1"); } std::vector<int> samp(counts_.size(), 0.0); for (auto i = 0; i < nsamp; ++i) { ++samp[dd_(gen_)]; } return samp; } /** * @return a vector of ints with nsamp == n() */ std::vector<int> sample() { return sample(n_); } int n() const { return n_; } const std::vector<int>& counts() { return counts_; } private: const std::vector<int>& counts_; std::default_random_engine gen_; std::discrete_distribution<int> dd_; int n_; }; #endif
{ "content_hash": "425412ba5edd18454f216fc988094dac", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 79, "avg_line_length": 27.77777777777778, "alnum_prop": 0.49314285714285716, "repo_name": "govinda-kamath/clustering_on_transcript_compatibility_counts", "id": "286adef9fc5112852e5cf723be625ae57ffa6b6f", "size": "1750", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modified-kallisto-source/kallisto_pseudo_paired/src/Multinomial.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "17594" }, { "name": "C++", "bytes": "386530" }, { "name": "CMake", "bytes": "7790" }, { "name": "Jupyter Notebook", "bytes": "5797702" }, { "name": "Python", "bytes": "85180" }, { "name": "Shell", "bytes": "1795" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace MyLittleWallpaper\classes\Navigation; use MyLittleWallpaper\classes\Format; /** * Navigation element class. */ class NavigationElement { /** * @var string */ private string $url; /** * @var string */ private string $title; /** * @var NavigationElement[] */ private array $subMenuItems = []; /** * @param string $url * @param string $title */ public function __construct(string $url, string $title) { $this->url = $url; $this->title = $title; } /** * @param string $key * @param NavigationElement $navigationElement * * @return void */ public function addSubMenuItem(string $key, NavigationElement $navigationElement): void { $this->subMenuItems[$key] = $navigationElement; } /** * @return NavigationElement[] */ public function getSubMenuItems(): array { return $this->subMenuItems; } /** * @return string */ public function __toString(): string { return '<a href="' . $this->url . '">' . Format::htmlEntities($this->title) . '</a>'; } }
{ "content_hash": "5ea382e37b611e6ee9d412a2faaf254d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 93, "avg_line_length": 19.078125, "alnum_prop": 0.552006552006552, "repo_name": "MyLittleWallpaper/MyLittleWallpaper", "id": "13537bce8290ebaa95316b0da66af6e0907883b0", "size": "1221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "classes/Navigation/NavigationElement.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "48757" }, { "name": "JavaScript", "bytes": "117791" }, { "name": "PHP", "bytes": "472721" }, { "name": "Shell", "bytes": "9700" } ], "symlink_target": "" }
<?php namespace Gedmo\SoftDeleteable\Traits; use Doctrine\ORM\Mapping as ORM; /** * SoftDeletable Trait, usable with PHP >= 5.4 * * @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ trait SoftDeleteableEntity { /** * @var \DateTime * @ORM\Column(name="deleted_at", type="datetime", nullable=true) */ protected $deletedAt; /** * Sets deletedAt. * * @param \Datetime|null $deletedAt * * @return $this */ public function setDeletedAt(\DateTime $deletedAt = null) { $this->deletedAt = $deletedAt; return $this; } /** * Returns deletedAt. * * @return \DateTime */ public function getDeletedAt() { return $this->deletedAt; } /** * Is deleted? * * @return bool */ public function isDeleted() { return null !== $this->deletedAt; } }
{ "content_hash": "2df17011ae3f81af18e06a2f673369c7", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 76, "avg_line_length": 18.51851851851852, "alnum_prop": 0.571, "repo_name": "blazarecki/DoctrineExtensions", "id": "5dbe535aff2db508de3b1961b7dbb49e1ddb007d", "size": "1000", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/Gedmo/SoftDeleteable/Traits/SoftDeleteableEntity.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1752345" } ], "symlink_target": "" }
typedef void (*SendVarProxyFn)( const SendProp *pProp, const void *pStructBase, const void *pData, DVariant *pOut, int iElement, int objectID ); // Return the pointer to the data for the datatable. // If the proxy returns null, it's the same as if pRecipients->ClearAllRecipients() was called. class CSendProxyRecipients; typedef void* (*SendTableProxyFn)( const SendProp *pProp, const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID ); class CNonModifiedPointerProxy { public: CNonModifiedPointerProxy( SendTableProxyFn fn ); public: SendTableProxyFn m_Fn; CNonModifiedPointerProxy *m_pNext; }; // This tells the engine that the send proxy will not modify the pointer // - it only plays with the recipients. This must be set on proxies that work // this way, otherwise the engine can't track which properties changed // in NetworkStateChanged(). #define REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( sendProxyFn ) static CNonModifiedPointerProxy __proxy_##sendProxyFn( sendProxyFn ); class CStandardSendProxiesV1 { public: CStandardSendProxiesV1(); SendVarProxyFn m_Int8ToInt32; SendVarProxyFn m_Int16ToInt32; SendVarProxyFn m_Int32ToInt32; SendVarProxyFn m_UInt8ToInt32; SendVarProxyFn m_UInt16ToInt32; SendVarProxyFn m_UInt32ToInt32; SendVarProxyFn m_FloatToFloat; SendVarProxyFn m_VectorToVector; #ifdef SUPPORTS_INT64 SendVarProxyFn m_Int64ToInt64; SendVarProxyFn m_UInt64ToInt64; #endif }; class CStandardSendProxies : public CStandardSendProxiesV1 { public: CStandardSendProxies(); SendTableProxyFn m_DataTableToDataTable; SendTableProxyFn m_SendLocalDataTable; CNonModifiedPointerProxy **m_ppNonModifiedPointerProxies; }; extern CStandardSendProxies g_StandardSendProxies; // Max # of datatable send proxies you can have in a tree. #define MAX_DATATABLE_PROXIES 32 // ------------------------------------------------------------------------ // // Datatable send proxies are used to tell the engine where the datatable's // data is and to specify which clients should get the data. // // pRecipients is the object that allows you to specify which clients will // receive the data. // ------------------------------------------------------------------------ // class CSendProxyRecipients { public: void SetAllRecipients(); // Note: recipients are all set by default when each proxy is called. void ClearAllRecipients(); void SetRecipient( int iClient ); // Note: these are CLIENT indices, not entity indices (so the first player's index is 0). void ClearRecipient( int iClient ); // Clear all recipients and set only the specified one. void SetOnly( int iClient ); public: // Make sure we have enough room for the max possible player count CBitVec< ABSOLUTE_PLAYER_LIMIT > m_Bits; }; inline void CSendProxyRecipients::SetAllRecipients() { m_Bits.SetAll(); } inline void CSendProxyRecipients::ClearAllRecipients() { m_Bits.ClearAll(); } inline void CSendProxyRecipients::SetRecipient( int iClient ) { m_Bits.Set( iClient ); } inline void CSendProxyRecipients::ClearRecipient( int iClient ) { m_Bits.Clear( iClient ); } inline void CSendProxyRecipients::SetOnly( int iClient ) { m_Bits.ClearAll(); m_Bits.Set( iClient ); } // ------------------------------------------------------------------------ // // ArrayLengthSendProxies are used when you want to specify an array's length // dynamically. // ------------------------------------------------------------------------ // typedef int (*ArrayLengthSendProxyFn)( const void *pStruct, int objectID ); class RecvProp; class SendTable; class CSendTablePrecalc; // -------------------------------------------------------------------------------------------------------------- // // SendProp. // -------------------------------------------------------------------------------------------------------------- // // If SendProp::GetDataTableProxyIndex() returns this, then the proxy is one that always sends // the data to all clients, so we don't need to store the results. #define DATATABLE_PROXY_INDEX_NOPROXY 255 #define DATATABLE_PROXY_INDEX_INVALID 254 class SendProp { public: SendProp(); virtual ~SendProp(); void Clear(); int GetOffset() const; void SetOffset( int i ); SendVarProxyFn GetProxyFn() const; void SetProxyFn( SendVarProxyFn f ); SendTableProxyFn GetDataTableProxyFn() const; void SetDataTableProxyFn( SendTableProxyFn f ); SendTable* GetDataTable() const; void SetDataTable( SendTable *pTable ); char const* GetExcludeDTName() const; // If it's one of the numbered "000", "001", etc properties in an array, then // these can be used to get its array property name for debugging. const char* GetParentArrayPropName() const; void SetParentArrayPropName( char *pArrayPropName ); const char* GetName() const; bool IsSigned() const; bool IsExcludeProp() const; bool IsInsideArray() const; // Returns true if SPROP_INSIDEARRAY is set. void SetInsideArray(); // Arrays only. void SetArrayProp( SendProp *pProp ); SendProp* GetArrayProp() const; // Arrays only. void SetArrayLengthProxy( ArrayLengthSendProxyFn fn ); ArrayLengthSendProxyFn GetArrayLengthProxy() const; int GetNumElements() const; void SetNumElements( int nElements ); // Return the # of bits to encode an array length (must hold GetNumElements()). int GetNumArrayLengthBits() const; int GetElementStride() const; SendPropType GetType() const; int GetFlags() const; void SetFlags( int flags ); // Some property types bind more data to the SendProp in here. const void* GetExtraData() const; void SetExtraData( const void *pData ); public: RecvProp *m_pMatchingRecvProp; // This is temporary and only used while precalculating // data for the decoders. SendPropType m_Type; int m_nBits; float m_fLowValue; float m_fHighValue; SendProp *m_pArrayProp; // If this is an array, this is the property that defines each array element. ArrayLengthSendProxyFn m_ArrayLengthProxy; // This callback returns the array length. int m_nElements; // Number of elements in the array (or 1 if it's not an array). int m_ElementStride; // Pointer distance between array elements. const char *m_pExcludeDTName; // If this is an exclude prop, then this is the name of the datatable to exclude a prop from. const char *m_pParentArrayPropName; const char *m_pVarName; float m_fHighLowMul; private: int m_Flags; // SPROP_ flags. SendVarProxyFn m_ProxyFn; // NULL for DPT_DataTable. SendTableProxyFn m_DataTableProxyFn; // Valid for DPT_DataTable. SendTable *m_pDataTable; // SENDPROP_VECTORELEM makes this negative to start with so we can detect that and // set the SPROP_IS_VECTOR_ELEM flag. int m_Offset; // Extra data bound to this property. const void *m_pExtraData; }; inline int SendProp::GetOffset() const { return m_Offset; } inline void SendProp::SetOffset( int i ) { m_Offset = i; } inline SendVarProxyFn SendProp::GetProxyFn() const { Assert( m_Type != DPT_DataTable ); return m_ProxyFn; } inline void SendProp::SetProxyFn( SendVarProxyFn f ) { m_ProxyFn = f; } inline SendTableProxyFn SendProp::GetDataTableProxyFn() const { Assert( m_Type == DPT_DataTable ); return m_DataTableProxyFn; } inline void SendProp::SetDataTableProxyFn( SendTableProxyFn f ) { m_DataTableProxyFn = f; } inline SendTable* SendProp::GetDataTable() const { return m_pDataTable; } inline void SendProp::SetDataTable( SendTable *pTable ) { m_pDataTable = pTable; } inline char const* SendProp::GetExcludeDTName() const { return m_pExcludeDTName; } inline const char* SendProp::GetParentArrayPropName() const { return m_pParentArrayPropName; } inline void SendProp::SetParentArrayPropName( char *pArrayPropName ) { Assert( !m_pParentArrayPropName ); m_pParentArrayPropName = pArrayPropName; } inline const char* SendProp::GetName() const { return m_pVarName; } inline bool SendProp::IsSigned() const { return !(m_Flags & SPROP_UNSIGNED); } inline bool SendProp::IsExcludeProp() const { return (m_Flags & SPROP_EXCLUDE) != 0; } inline bool SendProp::IsInsideArray() const { return (m_Flags & SPROP_INSIDEARRAY) != 0; } inline void SendProp::SetInsideArray() { m_Flags |= SPROP_INSIDEARRAY; } inline void SendProp::SetArrayProp( SendProp *pProp ) { m_pArrayProp = pProp; } inline SendProp* SendProp::GetArrayProp() const { return m_pArrayProp; } inline void SendProp::SetArrayLengthProxy( ArrayLengthSendProxyFn fn ) { m_ArrayLengthProxy = fn; } inline ArrayLengthSendProxyFn SendProp::GetArrayLengthProxy() const { return m_ArrayLengthProxy; } inline int SendProp::GetNumElements() const { return m_nElements; } inline void SendProp::SetNumElements( int nElements ) { m_nElements = nElements; } inline int SendProp::GetElementStride() const { return m_ElementStride; } inline SendPropType SendProp::GetType() const { return m_Type; } inline int SendProp::GetFlags() const { return m_Flags; } inline void SendProp::SetFlags( int flags ) { // Make sure they're using something from the valid set of flags. Assert( !( flags & ~((1 << SPROP_NUMFLAGBITS) - 1) ) ); m_Flags = flags; } inline const void* SendProp::GetExtraData() const { return m_pExtraData; } inline void SendProp::SetExtraData( const void *pData ) { m_pExtraData = pData; } // -------------------------------------------------------------------------------------------------------------- // // SendTable. // -------------------------------------------------------------------------------------------------------------- // class SendTable { public: typedef SendProp PropType; SendTable(); SendTable( SendProp *pProps, int nProps, const char *pNetTableName ); ~SendTable(); void Construct( SendProp *pProps, int nProps, const char *pNetTableName ); const char* GetName() const; int GetNumProps() const; SendProp* GetProp( int i ); // Used by the engine. bool IsInitialized() const; void SetInitialized( bool bInitialized ); // Used by the engine while writing info into the signon. void SetWriteFlag(bool bHasBeenWritten); bool GetWriteFlag() const; bool HasPropsEncodedAgainstTickCount() const; void SetHasPropsEncodedAgainstTickcount( bool bState ); public: SendProp *m_pProps; int m_nProps; const char *m_pNetTableName; // The name matched between client and server. // The engine hooks the SendTable here. CSendTablePrecalc *m_pPrecalc; protected: bool m_bInitialized : 1; bool m_bHasBeenWritten : 1; bool m_bHasPropsEncodedAgainstCurrentTickCount : 1; // m_flSimulationTime and m_flAnimTime, e.g. }; inline const char* SendTable::GetName() const { return m_pNetTableName; } inline int SendTable::GetNumProps() const { return m_nProps; } inline SendProp* SendTable::GetProp( int i ) { Assert( i >= 0 && i < m_nProps ); return &m_pProps[i]; } inline bool SendTable::IsInitialized() const { return m_bInitialized; } inline void SendTable::SetInitialized( bool bInitialized ) { m_bInitialized = bInitialized; } inline bool SendTable::GetWriteFlag() const { return m_bHasBeenWritten; } inline void SendTable::SetWriteFlag(bool bHasBeenWritten) { m_bHasBeenWritten = bHasBeenWritten; } inline bool SendTable::HasPropsEncodedAgainstTickCount() const { return m_bHasPropsEncodedAgainstCurrentTickCount; } inline void SendTable::SetHasPropsEncodedAgainstTickcount( bool bState ) { m_bHasPropsEncodedAgainstCurrentTickCount = bState; } // ------------------------------------------------------------------------------------------------------ // // Use BEGIN_SEND_TABLE if you want to declare a SendTable and have it inherit all the properties from // its base class. There are two requirements for this to work: // 1. Its base class must have a static SendTable pointer member variable called m_pClassSendTable which // points to its send table. The DECLARE_SERVERCLASS and IMPLEMENT_SERVERCLASS macros do this automatically. // 2. Your class must typedef its base class as BaseClass. So it would look like this: // class Derived : public CBaseEntity // { // typedef CBaseEntity BaseClass; // }; // If you don't want to interit a base class's properties, use BEGIN_SEND_TABLE_NOBASE. // ------------------------------------------------------------------------------------------------------ // #define BEGIN_SEND_TABLE(className, tableName) \ BEGIN_SEND_TABLE_NOBASE(className, tableName) \ SendPropDataTable("baseclass", 0, className::BaseClass::m_pClassSendTable, SendProxy_DataTableToDataTable), #define BEGIN_SEND_TABLE_NOBASE(className, tableName) \ template <typename T> int ServerClassInit(T *); \ namespace tableName { \ struct ignored; \ } \ template <> int ServerClassInit<tableName::ignored>(tableName::ignored *); \ namespace tableName { \ SendTable g_SendTable;\ int g_SendTableInit = ServerClassInit((tableName::ignored *)NULL); \ } \ template <> int ServerClassInit<tableName::ignored>(tableName::ignored *) \ { \ typedef className currentSendDTClass; \ static const char *g_pSendTableName = #tableName; \ SendTable &sendTable = tableName::g_SendTable; \ static SendProp g_SendProps[] = { \ SendPropInt("should_never_see_this", 0, sizeof(int)), // It adds a dummy property at the start so you can define "empty" SendTables. #define END_SEND_TABLE() \ };\ sendTable.Construct(g_SendProps+1, sizeof(g_SendProps) / sizeof(SendProp) - 1, g_pSendTableName);\ return 1; \ } // These can simplify creating the variables. // Note: currentSendDTClass::MakeANetworkVar_##varName equates to currentSendDTClass. It's // there as a check to make sure all networked variables use the CNetworkXXXX macros in network_var.h. #define SENDINFO(varName) #varName, offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName), sizeof(((currentSendDTClass*)0)->varName) #define SENDINFO_ARRAY(varName) #varName, offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName), sizeof(((currentSendDTClass*)0)->varName[0]) #define SENDINFO_ARRAY3(varName) #varName, offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName), sizeof(((currentSendDTClass*)0)->varName[0]), sizeof(((currentSendDTClass*)0)->varName)/sizeof(((currentSendDTClass*)0)->varName[0]) #define SENDINFO_ARRAYELEM(varName, i) #varName "[" #i "]", offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName[i]), sizeof(((currentSendDTClass*)0)->varName[0]) #define SENDINFO_NETWORKARRAYELEM(varName, i)#varName "[" #i "]", offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName.m_Value[i]), sizeof(((currentSendDTClass*)0)->varName.m_Value[0]) // NOTE: Be VERY careful to specify any other vector elems for the same vector IN ORDER and // right after each other, otherwise it might miss the Y or Z component in SP. // // Note: this macro specifies a negative offset so the engine can detect it and setup m_pNext #define SENDINFO_VECTORELEM(varName, i) #varName "[" #i "]", -(int)offsetof(currentSendDTClass::MakeANetworkVar_##varName, varName.m_Value[i]), sizeof(((currentSendDTClass*)0)->varName.m_Value[0]) #define SENDINFO_STRUCTELEM(varName) #varName, offsetof(currentSendDTClass, varName), sizeof(((currentSendDTClass*)0)->varName.m_Value) #define SENDINFO_STRUCTARRAYELEM(varName, i)#varName "[" #i "]", offsetof(currentSendDTClass, varName.m_Value[i]), sizeof(((currentSendDTClass*)0)->varName.m_Value[0]) // Use this when you're not using a CNetworkVar to represent the data you're sending. #define SENDINFO_NOCHECK(varName) #varName, offsetof(currentSendDTClass, varName), sizeof(((currentSendDTClass*)0)->varName) #define SENDINFO_STRING_NOCHECK(varName) #varName, offsetof(currentSendDTClass, varName) #define SENDINFO_DT(varName) #varName, offsetof(currentSendDTClass, varName) #define SENDINFO_DT_NAME(varName, remoteVarName) #remoteVarName, offsetof(currentSendDTClass, varName) #define SENDINFO_NAME(varName,remoteVarName) #remoteVarName, offsetof(currentSendDTClass, varName), sizeof(((currentSendDTClass*)0)->varName) // ------------------------------------------------------------------------ // // Built-in proxy types. // See the definition of SendVarProxyFn for information about these. // ------------------------------------------------------------------------ // void SendProxy_QAngles ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_AngleToFloat ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_FloatToFloat ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_VectorToVector ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_VectorXYToVectorXY( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); #if 0 // We can't ship this since it changes the size of DTVariant to be 20 bytes instead of 16 and that breaks MODs!!! void SendProxy_QuaternionToQuaternion( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); #endif void SendProxy_Int8ToInt32 ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_Int16ToInt32 ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); void SendProxy_Int32ToInt32 ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); #ifdef SUPPORTS_INT64 void SendProxy_Int64ToInt64 ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); #endif void SendProxy_StringToString ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); // pData is the address of a data table. void* SendProxy_DataTableToDataTable( const SendProp *pProp, const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID ); // pData is the address of a pointer to a data table. void* SendProxy_DataTablePtrToDataTable( const SendProp *pProp, const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID ); // Used on player entities - only sends the data to the local player (objectID-1). void* SendProxy_SendLocalDataTable( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID ); // ------------------------------------------------------------------------ // // Use these functions to setup your data tables. // ------------------------------------------------------------------------ // SendProp SendPropFloat( const char *pVarName, // Variable name. int offset, // Offset into container structure. int sizeofVar=SIZEOF_IGNORE, int nBits=32, // Number of bits to use when encoding. int flags=0, float fLowValue=0.0f, // For floating point, low and high values. float fHighValue=HIGH_DEFAULT, // High value. If HIGH_DEFAULT, it's (1<<nBits). SendVarProxyFn varProxy=SendProxy_FloatToFloat ); SendProp SendPropVector( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, int nBits=32, // Number of bits (for each floating-point component) to use when encoding. int flags=SPROP_NOSCALE, float fLowValue=0.0f, // For floating point, low and high values. float fHighValue=HIGH_DEFAULT, // High value. If HIGH_DEFAULT, it's (1<<nBits). SendVarProxyFn varProxy=SendProxy_VectorToVector ); SendProp SendPropVectorXY( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, int nBits=32, // Number of bits (for each floating-point component) to use when encoding. int flags=SPROP_NOSCALE, float fLowValue=0.0f, // For floating point, low and high values. float fHighValue=HIGH_DEFAULT, // High value. If HIGH_DEFAULT, it's (1<<nBits). SendVarProxyFn varProxy=SendProxy_VectorXYToVectorXY ); #if 0 // We can't ship this since it changes the size of DTVariant to be 20 bytes instead of 16 and that breaks MODs!!! SendProp SendPropQuaternion( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, int nBits=32, // Number of bits (for each floating-point component) to use when encoding. int flags=SPROP_NOSCALE, float fLowValue=0.0f, // For floating point, low and high values. float fHighValue=HIGH_DEFAULT, // High value. If HIGH_DEFAULT, it's (1<<nBits). SendVarProxyFn varProxy=SendProxy_QuaternionToQuaternion ); #endif SendProp SendPropAngle( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, int nBits=32, int flags=0, SendVarProxyFn varProxy=SendProxy_AngleToFloat ); SendProp SendPropQAngles( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, int nBits=32, int flags=0, SendVarProxyFn varProxy=SendProxy_QAngles ); SendProp SendPropInt( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE, // Handled by SENDINFO macro. int nBits=-1, // Set to -1 to automatically pick (max) number of bits based on size of element. int flags=0, SendVarProxyFn varProxy=0 ); inline SendProp SendPropModelIndex( const char *pVarName, int offset, int sizeofVar=SIZEOF_IGNORE ) { return SendPropInt( pVarName, offset, sizeofVar, SP_MODEL_INDEX_BITS, 0 ); } SendProp SendPropString( const char *pVarName, int offset, int bufferLen, int flags=0, SendVarProxyFn varProxy=SendProxy_StringToString); // The data table encoder looks at DVariant::m_pData. SendProp SendPropDataTable( const char *pVarName, int offset, SendTable *pTable, SendTableProxyFn varProxy=SendProxy_DataTableToDataTable ); SendProp SendPropArray3( const char *pVarName, int offset, int sizeofVar, int elements, SendProp pArrayProp, SendTableProxyFn varProxy=SendProxy_DataTableToDataTable ); // Use the macro to let it automatically generate a table name. You shouldn't // ever need to reference the table name. If you want to exclude this array, then // reference the name of the variable in varTemplate. SendProp InternalSendPropArray( const int elementCount, const int elementStride, const char *pName, ArrayLengthSendProxyFn proxy ); // Use this and pass the array name and it will figure out the count and stride automatically. #define SendPropArray( varTemplate, arrayName ) \ SendPropVariableLengthArray( \ 0, \ varTemplate, \ arrayName ) // // Use this when you want to send a variable-length array of data but there is no physical array you can point it at. // You need to provide: // 1. A proxy function that returns the current length of the array. // 2. The maximum length the array will ever be. // 2. A SendProp describing what the elements are comprised of. // 3. In the SendProp, you'll want to specify a proxy function so you can go grab the data from wherever it is. // 4. A property name that matches the definition on the client. // #define SendPropVirtualArray( arrayLengthSendProxy, maxArrayLength, varTemplate, propertyName ) \ varTemplate, \ InternalSendPropArray( \ maxArrayLength, \ 0, \ #propertyName, \ arrayLengthSendProxy \ ) #define SendPropVariableLengthArray( arrayLengthSendProxy, varTemplate, arrayName ) \ varTemplate, \ InternalSendPropArray( \ sizeof(((currentSendDTClass*)0)->arrayName) / PROPSIZEOF(currentSendDTClass, arrayName[0]), \ PROPSIZEOF(currentSendDTClass, arrayName[0]), \ #arrayName, \ arrayLengthSendProxy \ ) // Use this one to specify the element count and stride manually. #define SendPropArray2( arrayLengthSendProxy, varTemplate, elementCount, elementStride, arrayName ) \ varTemplate, \ InternalSendPropArray( elementCount, elementStride, #arrayName, arrayLengthSendProxy ) // Use these to create properties that exclude other properties. This is useful if you want to use most of // a base class's datatable data, but you want to override some of its variables. SendProp SendPropExclude( const char *pDataTableName, // Data table name (given to BEGIN_SEND_TABLE and BEGIN_RECV_TABLE). const char *pPropName // Name of the property to exclude. ); #endif // DATATABLE_SEND_H
{ "content_hash": "f5086df1f8a9fc03938ea1e96afc539b", "timestamp": "", "source": "github", "line_count": 768, "max_line_length": 243, "avg_line_length": 32, "alnum_prop": 0.7045491536458334, "repo_name": "BerntA/tfo-code", "id": "d84b00ae585a3b220399558671f612a20981931f", "size": "26040", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "public/dt_send.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "238" }, { "name": "Batchfile", "bytes": "9897" }, { "name": "C", "bytes": "1255315" }, { "name": "C++", "bytes": "39642849" }, { "name": "GLSL", "bytes": "126492" }, { "name": "Makefile", "bytes": "28908" }, { "name": "Objective-C", "bytes": "72895" }, { "name": "Objective-C++", "bytes": "369" }, { "name": "Perl", "bytes": "93035" }, { "name": "Perl 6", "bytes": "1820" }, { "name": "Shell", "bytes": "1362" } ], "symlink_target": "" }
var server = params.server.replace(/[\/]+$/, '') + '/searchApi/' + params.version + '/'; var commands = { 'threat-crowd-email': { url: 'email', title: 'Threat crowd report for email %email%', defaultFields: { 'type': 'Email', }, translator: [ {to: 'ThreatCrowd-Domains', from: 'domains'}, {to: 'Address', from: 'email'}, {to: 'Type', from: 'type'}, ], contextKey: 'Account.Email(val.Address==obj.Address)', }, 'threat-crowd-domain': { url: 'domain', title: 'Threat crowd report for domain %domain%', translator: [ {to: 'Name', from: 'domain'}, {to: 'ThreatCrowd-Emails', from: 'emails'}, {to: 'ThreatCrowd-SubDomains', from: 'subdomains'}, {to: 'ThreatCrowd-References', from: 'references'}, {to: 'ThreatCrowd-Votes', from: 'votes'}, ], contextKey: 'Domain(val.Name==obj.Name)', }, 'threat-crowd-ip': { url: 'ip', title: 'Threat crowd report for ip %ip%', translator: [ {to: 'Address', from: 'ip'}, {to: 'ThreatCrowd-Hashes', from: 'hashes'}, {to: 'ThreatCrowd-References', from: 'references'}, {to: 'ThreatCrowd-Resolutions', from: 'resolutions'}, {to: 'ThreatCrowd-Votes', from: 'votes'}, ], contextKey: 'IP(val.Address==obj.Address)', }, 'threat-crowd-antivirus': { url: 'antivirus', title: 'Threat crowd report for antivirus %antivirus%', translator: [ {to: 'Name', from: 'antivirus'}, {to: 'Hashes', from: 'hashes'}, {to: 'References', from: 'references'}, ], contextKey: 'ThreatCrowd.AntiVirus(val.Name==obj.Name)', }, 'threat-crowd-file': { url: 'file', title: 'Threat crowd report for file with hash %resource%', translator: [ {to: 'MD5', from: 'md5'}, {to: 'ThreatCrowd-IPs', from: 'ips'}, {to: 'ThreatCrowd-Domains', from: 'domains'}, {to: 'ThreatCrowd-Resource', from: 'resource'}, {to: 'ThreatCrowd-SHA1', from: 'sha1'}, {to: 'ThreatCrowd-References', from: 'references'}, {to: 'ThreatCrowd-Scans', from: 'scans'}, ], contextKey: 'File(val.MD5==obj.MD5)', }, 'test-module': { url: 'email', defaultArgs: { email: 'william19770319@yahoo.com', }, }, }; function createContext(data, dbotScore) { var createContextSingle = function(obj) { var res = {}; var keys = Object.keys(obj); keys.forEach(function(k) { var values = k.split('-'); var current = res; for (var j = 0; j<values.length - 1; j++) { if (!current[values[j]]) { current[values[j]] = {}; } current = current[values[j]]; } current[values[j]] = obj[k]; }); if (dbotScore == 3) { res.Malicious = { "Vendor": 'Threat Crowd', "Description": 'Most users have voted this entity malicious' }; } return res; }; if (data instanceof Array) { var res = []; for (var j=0; j < data.length; j++) { res.push(createContextSingle(data[j])); } if (dbotScore == 3) { res.Malicious = { "Vendor": 'Threat Crowd', "Description": 'Most users have voted this entity malicious1' }; } return res; } return createContextSingle(data); } function mapObjFunction(mapFields) { var transformSingleObj= function(obj) { var res = {}; mapFields.forEach(function(f) { res[f.to] = dq(obj, f.from); }); return res; }; return function(obj) { if (obj instanceof Array) { var res = []; for (var j=0; j < obj.length; j++) { res.push(transformSingleObj(obj[j])); } return res; } return transformSingleObj(obj); }; } function merge(obj1, obj2) { if (!obj2) { return obj1; } keys = Object.keys(obj2); for (var k in keys) { if (obj1[keys[k]] === undefined) { obj1[keys[k]] = obj2[keys[k]] } } return obj1; } if (args.file) { args.resource = args.file; delete(args.file); } function calculateDBotScore(res, args, commandData) { var dbotScore = 0; if (res.response_code == 1){ if ('votes' in res){ switch (res.votes) { case -1: //malicious dbotScore = 3 break; case 0: //suspicious dbotScore = 2; break; case 1: //clean dbotScore = 1; break; } } } return dbotScore; } function createDbotEntry(commandData, dbotScore){ var DbotEntry = {}; if (commandData.url == 'ip'){ DbotEntry = { "Indicator": args.ip, "Type": "IP", "Vendor": "Threat Crowd", "Score": dbotScore }; } else { DbotEntry = { "Indicator": args.domain, "Type": "Domain", "Vendor": "Threat Crowd", "Score": dbotScore }; } return DbotEntry; } function sendRequestAndParse(commandData) { res = http( server + commandData.url + '/report/' + encodeToURLQuery(args && Object.keys(args).length ? args : commandData.defaultArgs), {}, params.insecure, params.proxy ); if (res.StatusCode < 200 || res.StatusCode >= 300) { throw 'Failed to ' + commandData.url + ' , request status code: ' + res.StatusCode + ' and Body: ' + res.Body + '.'; } entry = { Type: entryTypes.note, Contents: JSON.parse(res.Body), ContentsFormat: formats.json, }; if (commandData.translator) { data = mapObjFunction(commandData.translator)(merge(merge(entry.Contents, args), commandData.defaultFields)); entry.ReadableContentsFormat = formats.markdown; entry.HumanReadable = tableToMarkdown(replaceInTemplates(commandData.title, args), data); entry.EntryContext = {}; var dbotScore = -1; if (commandData.url == 'domain' || commandData.url== 'ip') { // the only commands with dbotScore dbotScore = calculateDBotScore(JSON.parse(res.Body), args, commandData); entry.EntryContext = {}; entry.EntryContext['DBotScore'] = createDbotEntry(commandData, dbotScore); } entry.EntryContext[commandData.contextKey] = createContext(data, dbotScore); } return entry; } res = sendRequestAndParse(commands[command]); if (command === 'test-module') { return 'ok'; } return res;
{ "content_hash": "af0d7384be4e03fec96558c1a2670c96", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 132, "avg_line_length": 31.08695652173913, "alnum_prop": 0.502937062937063, "repo_name": "demisto/content", "id": "272805bd64f0812c3984a5f02359bef8e754a9d1", "size": "7150", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Packs/Threat_Crowd/Integrations/ThreatCrowd/ThreatCrowd.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2146" }, { "name": "HTML", "bytes": "205901" }, { "name": "JavaScript", "bytes": "1584075" }, { "name": "PowerShell", "bytes": "442288" }, { "name": "Python", "bytes": "47881712" }, { "name": "Rich Text Format", "bytes": "480911" }, { "name": "Shell", "bytes": "108066" }, { "name": "YARA", "bytes": "1185" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------------- // // FXMaker // Created by ismoon - 2012 - ismoonto@gmail.com // // ---------------------------------------------------------------------------------- using UnityEngine; public class NcSafeTool : MonoBehaviour { public static bool m_bShuttingDown; public static bool m_bLoadLevel; private static NcSafeTool s_Instance = null; // Property ------------------------------------------------------------------------- private static void Instance() { if (s_Instance == null) { GameObject gm; gm = UnityEngine.GameObject.Find("_GlobalManager"); if (gm == null) gm = new GameObject("_GlobalManager"); else s_Instance = (NcSafeTool)gm.GetComponent(typeof(NcSafeTool)); if (s_Instance == null) s_Instance = (NcSafeTool)gm.AddComponent(typeof(NcSafeTool)); } } public static bool IsSafe() { return (!m_bShuttingDown && !m_bLoadLevel); } public static Object SafeInstantiate(Object original) { if (m_bShuttingDown) return null; if (s_Instance == null) Instance(); return Object.Instantiate(original); } public static Object SafeInstantiate(Object original, Vector3 position, Quaternion rotation) { if (m_bShuttingDown) return null; if (s_Instance == null) Instance(); return Object.Instantiate(original, position, rotation); } public static void LoadLevel(int nLoadLevel) { if (m_bShuttingDown) return; if (s_Instance == null) Instance(); m_bLoadLevel = true; Debug.Log("Safe LoadLevel start " + nLoadLevel); Application.LoadLevel(nLoadLevel); Debug.Log("Safe LoadLevel end"); m_bLoadLevel = false; } public void OnApplicationQuit() { m_bShuttingDown = true; } }
{ "content_hash": "5706aa8d41d2f723356fdfc4c3207dec", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 93, "avg_line_length": 23.945205479452056, "alnum_prop": 0.5966819221967964, "repo_name": "1510649869/ARPG_project", "id": "d4d54cd02c3dc64f1ea7e0e42b63bf6d143afc47", "size": "1750", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Assets/IGSoft_Tools/CommonLib/Utility/NcSafeTool.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3536602" }, { "name": "GLSL", "bytes": "62950" }, { "name": "JavaScript", "bytes": "69361" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include <cassert> #include <cstdlib> #include <vector> #include <string> #include <sstream> #include <iostream> #include "popen.h" #include "sp-data.h" #include "features.h" #include "simple-api.h" // externed variables int debug_level = 0; bool absolute_counts = true; bool collect_correct = false; bool collect_incorrect = false; RerankerError::RerankerError(const std::string msg) { this->description = msg; } void setOptions(int debug, bool abs_counts) { debug_level = debug; absolute_counts = abs_counts; } RerankerModel::RerankerModel(const char* feature_class, const char* feature_ids_filename, const char* feature_weights_filename) { fcps = new FeatureClassPtrs(feature_class); if (!std::ifstream(feature_ids_filename).good()) { throw RerankerError("Can't open feature IDs file."); } izstream fdin(feature_ids_filename); maxid = fcps->read_feature_ids(fdin); izstream fwin(feature_weights_filename); if (!std::ifstream(feature_weights_filename).good()) { throw RerankerError("Can't open feature weights file."); } weights = new Weights(maxid + 1); Id id; Float weight; while (fwin >> id >> "=" >> weight) { assert(id <= maxid); assert((*weights)[id] == 0); (*weights)[id] = weight; } } Weights* RerankerModel::scoreNBestList(const sp_sentence_type& nbest_list) const { Id_Floats p_i_v(nbest_list.nparses()); cforeach (FeatureClassPtrs, it, *fcps) (*it)->feature_values(nbest_list, p_i_v); Weights* parse_scores = new Weights(); for (size_type i = 0; i < nbest_list.nparses(); ++i) { const Id_Float& i_v = p_i_v[i]; Float w = 0; cforeach (Id_Float, ivit, i_v) { assert(ivit->first < weights->size()); w += ivit->second * (*weights)[ivit->first]; } parse_scores->push_back(w); } return parse_scores; } sp_sentence_type* readNBestList(const std::string nbest_list, bool lowercase) { std::stringstream text(nbest_list); sp_sentence_type* s = new sp_sentence_type(); s->read(text, lowercase); return s; }
{ "content_hash": "ea41e00f1d8d0af8163f966fbb68ba5c", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 79, "avg_line_length": 27.785714285714285, "alnum_prop": 0.6522218141755417, "repo_name": "dmcc/bllip-parser", "id": "150de9511100aaafaaa66296ab61a985195c40aa", "size": "2723", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "second-stage/programs/features/simple-api.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "406" }, { "name": "C", "bytes": "682774" }, { "name": "C++", "bytes": "2188548" }, { "name": "Common Lisp", "bytes": "1233" }, { "name": "GAP", "bytes": "35887650" }, { "name": "Java", "bytes": "9098" }, { "name": "Lex", "bytes": "16820" }, { "name": "M", "bytes": "876" }, { "name": "Makefile", "bytes": "51245" }, { "name": "Objective-C", "bytes": "2633" }, { "name": "Perl6", "bytes": "484" }, { "name": "Python", "bytes": "254799" }, { "name": "Rebol", "bytes": "1217" }, { "name": "Ruby", "bytes": "195" }, { "name": "Shell", "bytes": "20258" } ], "symlink_target": "" }
{% extends "base.html" %} {% block title %}No Organization | Savage Leads | SavageAutomation{% endblock %} {% block content %} <div class="col-md-offset-3 col-md-5 text-left"> <h2>No Organization</h2> <p> Looks like you don't have an organization. You should get one. </p> </div> {% endblock %}
{ "content_hash": "b5f5851da430e188754955ac7e922d6f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 80, "avg_line_length": 30.5, "alnum_prop": 0.6557377049180327, "repo_name": "russorat/savage-leads", "id": "adfeb027e53b8c098478871e4b3c54e64086b0fe", "size": "305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/no-org.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11232" }, { "name": "HTML", "bytes": "14454" }, { "name": "JavaScript", "bytes": "628023" }, { "name": "Python", "bytes": "50156" } ], "symlink_target": "" }
/** * @file templates/halconf.h * @brief HAL configuration header. * @details HAL configuration file, this file allows to enable or disable the * various device drivers from your application. You may also use * this file in order to override the device drivers default settings. * * @addtogroup HAL_CONF * @{ */ #ifndef _HALCONF_H_ #define _HALCONF_H_ /*#include "mcuconf.h"*/ /** * @brief Enables the TM subsystem. */ #if !defined(HAL_USE_TM) || defined(__DOXYGEN__) #define HAL_USE_TM FALSE #endif /** * @brief Enables the PAL subsystem. */ #if !defined(HAL_USE_PAL) || defined(__DOXYGEN__) #define HAL_USE_PAL FALSE #endif /** * @brief Enables the ADC subsystem. */ #if !defined(HAL_USE_ADC) || defined(__DOXYGEN__) #define HAL_USE_ADC FALSE #endif /** * @brief Enables the CAN subsystem. */ #if !defined(HAL_USE_CAN) || defined(__DOXYGEN__) #define HAL_USE_CAN FALSE #endif /** * @brief Enables the DAC subsystem. */ #if !defined(HAL_USE_DAC) || defined(__DOXYGEN__) #define HAL_USE_DAC FALSE #endif /** * @brief Enables the EXT subsystem. */ #if !defined(HAL_USE_EXT) || defined(__DOXYGEN__) #define HAL_USE_EXT FALSE #endif /** * @brief Enables the GPT subsystem. */ #if !defined(HAL_USE_GPT) || defined(__DOXYGEN__) #define HAL_USE_GPT FALSE #endif /** * @brief Enables the I2C subsystem. */ #if !defined(HAL_USE_I2C) || defined(__DOXYGEN__) #define HAL_USE_I2C FALSE #endif /** * @brief Enables the I2S subsystem. */ #if !defined(HAL_USE_I2S) || defined(__DOXYGEN__) #define HAL_USE_I2S FALSE #endif /** * @brief Enables the ICU subsystem. */ #if !defined(HAL_USE_ICU) || defined(__DOXYGEN__) #define HAL_USE_ICU FALSE #endif /** * @brief Enables the MAC subsystem. */ #if !defined(HAL_USE_MAC) || defined(__DOXYGEN__) #define HAL_USE_MAC FALSE #endif /** * @brief Enables the MMC_SPI subsystem. */ #if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__) #define HAL_USE_MMC_SPI FALSE #endif /** * @brief Enables the PWM subsystem. */ #if !defined(HAL_USE_PWM) || defined(__DOXYGEN__) #define HAL_USE_PWM FALSE #endif /** * @brief Enables the RTC subsystem. */ #if !defined(HAL_USE_RTC) || defined(__DOXYGEN__) #define HAL_USE_RTC FALSE #endif /** * @brief Enables the SDC subsystem. */ #if !defined(HAL_USE_SDC) || defined(__DOXYGEN__) #define HAL_USE_SDC FALSE #endif /** * @brief Enables the SERIAL subsystem. */ #if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__) #define HAL_USE_SERIAL FALSE #endif /** * @brief Enables the SERIAL over USB subsystem. */ #if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__) #define HAL_USE_SERIAL_USB FALSE #endif /** * @brief Enables the SPI subsystem. */ #if !defined(HAL_USE_SPI) || defined(__DOXYGEN__) #define HAL_USE_SPI FALSE #endif /** * @brief Enables the UART subsystem. */ #if !defined(HAL_USE_UART) || defined(__DOXYGEN__) #define HAL_USE_UART FALSE #endif /** * @brief Enables the USB subsystem. */ #if !defined(HAL_USE_USB) || defined(__DOXYGEN__) #define HAL_USE_USB FALSE #endif /*===========================================================================*/ /* ADC driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__) #define ADC_USE_WAIT TRUE #endif /** * @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs. * @note Disabling this option saves both code and data space. */ #if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define ADC_USE_MUTUAL_EXCLUSION TRUE #endif /*===========================================================================*/ /* CAN driver related settings. */ /*===========================================================================*/ /** * @brief Sleep mode related APIs inclusion switch. */ #if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__) #define CAN_USE_SLEEP_MODE TRUE #endif /*===========================================================================*/ /* I2C driver related settings. */ /*===========================================================================*/ /** * @brief Enables the mutual exclusion APIs on the I2C bus. */ #if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define I2C_USE_MUTUAL_EXCLUSION TRUE #endif /*===========================================================================*/ /* MAC driver related settings. */ /*===========================================================================*/ /** * @brief Enables an event sources for incoming packets. */ #if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__) #define MAC_USE_ZERO_COPY FALSE #endif /** * @brief Enables an event sources for incoming packets. */ #if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__) #define MAC_USE_EVENTS TRUE #endif /*===========================================================================*/ /* MMC_SPI driver related settings. */ /*===========================================================================*/ /** * @brief Delays insertions. * @details If enabled this options inserts delays into the MMC waiting * routines releasing some extra CPU time for the threads with * lower priority, this may slow down the driver a bit however. * This option is recommended also if the SPI driver does not * use a DMA channel and heavily loads the CPU. */ #if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__) #define MMC_NICE_WAITING TRUE #endif /*===========================================================================*/ /* SDC driver related settings. */ /*===========================================================================*/ /** * @brief Number of initialization attempts before rejecting the card. * @note Attempts are performed at 10mS intervals. */ #if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__) #define SDC_INIT_RETRY 100 #endif /** * @brief Include support for MMC cards. * @note MMC support is not yet implemented so this option must be kept * at @p FALSE. */ #if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__) #define SDC_MMC_SUPPORT FALSE #endif /** * @brief Delays insertions. * @details If enabled this options inserts delays into the MMC waiting * routines releasing some extra CPU time for the threads with * lower priority, this may slow down the driver a bit however. */ #if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__) #define SDC_NICE_WAITING TRUE #endif /*===========================================================================*/ /* SERIAL driver related settings. */ /*===========================================================================*/ /** * @brief Default bit rate. * @details Configuration parameter, this is the baud rate selected for the * default configuration. */ #if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__) #define SERIAL_DEFAULT_BITRATE 38400 #endif /** * @brief Serial buffers size. * @details Configuration parameter, you can change the depth of the queue * buffers depending on the requirements of your application. * @note The default is 64 bytes for both the transmission and receive * buffers. */ #if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__) #define SERIAL_BUFFERS_SIZE 32 #endif /*===========================================================================*/ /* SPI driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__) #define SPI_USE_WAIT TRUE #endif /** * @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs. * @note Disabling this option saves both code and data space. */ #if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define SPI_USE_MUTUAL_EXCLUSION TRUE #endif #endif /* _HALCONF_H_ */ /** @} */
{ "content_hash": "671b0de004f8ec93b10d581f47bf5cbf", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 79, "avg_line_length": 29.746794871794872, "alnum_prop": 0.4959594871242323, "repo_name": "raphaelchang/quadthingy-software", "id": "286864be0a83f7e37cc56f7f076c88799d19e481", "size": "9918", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "quadrotor/ChibiOS_16.1.4/community/demos/various/RT-Win32-TriBuf/halconf.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "2697" }, { "name": "Assembly", "bytes": "850772" }, { "name": "Batchfile", "bytes": "972" }, { "name": "C", "bytes": "134554272" }, { "name": "C++", "bytes": "33621621" }, { "name": "CMake", "bytes": "198987" }, { "name": "CSS", "bytes": "58816" }, { "name": "Cuda", "bytes": "92781" }, { "name": "Fortran", "bytes": "1326303" }, { "name": "FreeMarker", "bytes": "962618" }, { "name": "HTML", "bytes": "215008" }, { "name": "JavaScript", "bytes": "7839" }, { "name": "Makefile", "bytes": "2771973" }, { "name": "Objective-C", "bytes": "6517968" }, { "name": "Python", "bytes": "8937" }, { "name": "Shell", "bytes": "26480" } ], "symlink_target": "" }
Google Cloud Video Intelligence API makes videos searchable, and discoverable, by extracting metadata with an easy to use API. For more information, see [cloud.google.com](https://cloud.google.com/video-intelligence/).
{ "content_hash": "8ff3ea0a427bf54d656cbc5855ab4aaa", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 126, "avg_line_length": 73.33333333333333, "alnum_prop": 0.8, "repo_name": "kl82/gadatabquery", "id": "45254ec9fc85a1f5f0da727f0f8408e30da32789", "size": "248", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/VideoIntelligence/V1beta2/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4383" }, { "name": "JavaScript", "bytes": "34410" }, { "name": "PHP", "bytes": "102331015" } ], "symlink_target": "" }
package appfw type Appfwprofilecontenttypebinding struct { Alertonly string `json:"alertonly,omitempty"` Comment string `json:"comment,omitempty"` Contenttype string `json:"contenttype,omitempty"` Isautodeployed string `json:"isautodeployed,omitempty"` Name string `json:"name,omitempty"` Resourceid string `json:"resourceid,omitempty"` State string `json:"state,omitempty"` }
{ "content_hash": "e5a2c88a39b65a6d02349aa779daee27", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 56, "avg_line_length": 38.45454545454545, "alnum_prop": 0.7210401891252955, "repo_name": "chiradeep/go-nitro", "id": "e229512be261a9615008f17213210de21bb000ce", "size": "423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/appfw/appfwprofile_contenttype_binding.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "870653" }, { "name": "Makefile", "bytes": "975" }, { "name": "Shell", "bytes": "865" } ], "symlink_target": "" }
using System.Linq; using NUnit.Framework; namespace TestStack.BDDfy.Tests.Exceptions { [TestFixture] public class WhenAnInconclusiveTestIsRun { public class InconclusiveTestClass { public void GivenAClassUnderTest() { } public void WhenInconclusiveExceptionIsThrownInOneOfTheMethods() { } public void ThenTheContextIsFlaggedAsInconclusive() { Assert.Inconclusive(); } public void TearDownThis() { } } Engine _engine; private Scenario _scenario; Step GivenStep { get { return _scenario.Steps.Single(s => s.Title == "Given a class under test"); } } Step WhenStep { get { return _scenario.Steps.Single(s => s.Title == "When inconclusive exception is thrown in one of the methods"); } } Step ThenStep { get { return _scenario.Steps.Single(s => s.Title == "Then the context is flagged as inconclusive"); } } Step DisposeStep { get { return _scenario.Steps.Single(s => s.Title == "Tear down this"); } } [SetUp] public void InconclusiveExceptionSetup() { _engine = new InconclusiveTestClass().LazyBDDfy(); Assert.Throws<InconclusiveException>(() => _engine.Run()); _scenario = _engine.Story.Scenarios.First(); } [Test] public void ResultIsInconclusive() { Assert.That(_scenario.Result, Is.EqualTo(Result.Inconclusive)); } [Test] public void ThenIsFlaggedAsInconclusive() { Assert.That(ThenStep.Result, Is.EqualTo(Result.Inconclusive)); } [Test] public void ThenHasAnInconclusiveExceptionOnIt() { Assert.That(ThenStep.Exception, Is.AssignableFrom(typeof(InconclusiveException))); } [Test] public void GivenIsFlaggedAsSuccessful() { Assert.That(GivenStep.Result, Is.EqualTo(Result.Passed)); } [Test] public void WhenIsFlaggedAsSuccessful() { Assert.That(WhenStep.Result, Is.EqualTo(Result.Passed)); } [Test] public void ScenarioResultReturnsInconclusive() { Assert.That(_scenario.Result, Is.EqualTo(Result.Inconclusive)); } [Test] public void StoryResultReturnsInconclusive() { Assert.That(_scenario.Result, Is.EqualTo(Result.Inconclusive)); } [Test] public void TearDownMethodIsExecuted() { Assert.That(DisposeStep.Result, Is.EqualTo(Result.Passed)); } } }
{ "content_hash": "81b0e895f2d6749792c60de8b95d3cc2", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 125, "avg_line_length": 24.983471074380166, "alnum_prop": 0.5210056235527621, "repo_name": "JakeGinnivan/TestStack.BDDfy", "id": "94721470557365c72cd6ddd7aaa2dd14825410b3", "size": "3023", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TestStack.BDDfy.Tests/Exceptions/WhenAnInconclusiveTestIsRun.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "399064" }, { "name": "CSS", "bytes": "25954" }, { "name": "JavaScript", "bytes": "1548" }, { "name": "Shell", "bytes": "120" } ], "symlink_target": "" }
PetscErrorCode regular_ida (Mat A, const PetscInt M, const PetscInt N, const PetscInt m, const PetscInt n, const PetscInt mg, const PetscInt localfirstcol_l, const PetscInt localfirstrow_l, const PetscInt localfirstcol_g, const PetscInt localfirstrow_g, const PetscBool init_guess_flg, const PetscBool init_guess_file_flg, const PetscBool initguesscalc, const char * restrict const initguessfilename, const MPI_Datatype doublefiletype, const unsigned char * restrict const W, Vec x, const int rank, KSP * ksp);
{ "content_hash": "663e2d8598affbf2e0e5279a69ca2527", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 78, "avg_line_length": 54.3, "alnum_prop": 0.7587476979742173, "repo_name": "csdms-contrib/ida", "id": "91bf861dfae19f052b98f3bd3487f5acdeadc8e8", "size": "543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "regular_ida.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "62094" }, { "name": "Perl", "bytes": "436" } ], "symlink_target": "" }
namespace sudoku { template<int size> class Dimensions { public: static const int BOX = size; static const int UNIT = BOX * BOX; static const int GRID = UNIT * UNIT; static const bitmask_t MASK = ((1 << (UNIT + 1)) - 2); }; } #endif //CSUDOKU_PUZZLEDIMENSIONS_H
{ "content_hash": "fce59b83b8a8fa4b192c1adcd4012526", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 25.916666666666668, "alnum_prop": 0.5819935691318328, "repo_name": "binarii/CSudokuLib", "id": "627d1074070a158692936dc1432edb454f8b38b1", "size": "409", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/include/CSudokuLib/Dimensions.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "274" }, { "name": "C++", "bytes": "396314" }, { "name": "CMake", "bytes": "2280" } ], "symlink_target": "" }
// Declare app level module which depends on filters, and services angular.module('dibsApp', [ 'ngRoute', 'ngCookies', 'ui.bootstrap', 'dibsApp.filters', 'dibsApp.services', 'dibsApp.directives', 'dibsApp.controllers' ]). config(['$routeProvider', function($routeProvider) { 'use strict'; /* TODO: somehow inject '/static/' */ $routeProvider.when('/', {templateUrl: '/static/dibsangular/partials/main.html', controller: 'ListCtrl'}); // $routeProvider.when('/view2', {templateUrl: '/static/dibsangular/partials/partial2.html', controller: 'MyCtrl2'}); $routeProvider.otherwise({redirectTo: '/'}); }]).config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.xsrfCookieName = 'csrftoken'; }]);
{ "content_hash": "b7079dc1f8128b3f1657569b07573e77", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 119, "avg_line_length": 34.608695652173914, "alnum_prop": 0.7022613065326633, "repo_name": "slafs/dibs", "id": "57f232b61fd950ce54207fd42798236d14d77401", "size": "796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dibsangular/static/dibsangular/js/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "681" }, { "name": "JavaScript", "bytes": "12769" }, { "name": "Makefile", "bytes": "8137" }, { "name": "Python", "bytes": "36968" }, { "name": "Shell", "bytes": "6774" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2012 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <module rename-to="hello_gwt_plugins"> <!-- Inherit the core Web Toolkit stuff. --> <inherits name="com.google.gwt.user.User"/> <!-- Other module inherits --> <inherits name="com.google.gerrit.Plugin"/> <inherits name="com.google.gwt.http.HTTP"/> <!-- Using GWT built-in themes adds a number of static --> <!-- resources to the plugin. No theme inherits lines were --> <!-- added in order to make this plugin as simple as possible --> <!-- Specify the app entry point class. --> <entry-point class="${package}.client.HelloPlugins"/> <stylesheet src="hello.css"/> </module>
{ "content_hash": "9b8399236e4c6779408eece8825aa1db", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 73, "avg_line_length": 45.689655172413794, "alnum_prop": 0.6641509433962264, "repo_name": "basilgor/gerrit", "id": "4c70fcc0f6c84bab0656b73993509e1b26eefb3c", "size": "1325", "binary": false, "copies": "5", "ref": "refs/heads/cvs_submit", "path": "gerrit-plugin-gwt-archetype/src/main/resources/archetype-resources/src/main/java/HelloPlugins.gwt.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5346642" }, { "name": "JavaScript", "bytes": "1590" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17421" }, { "name": "Python", "bytes": "12182" }, { "name": "Shell", "bytes": "36339" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace Link2chat { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
{ "content_hash": "2928b64adcb4f6199dfb32a0dfdd4e2f", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 62, "avg_line_length": 24.333333333333332, "alnum_prop": 0.5787671232876712, "repo_name": "longday/Link2chat", "id": "3a32f48c522f2c01079b0e077817456108d6153a", "size": "586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Link2chat/App_Start/WebApiConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "92" }, { "name": "C#", "bytes": "2411" }, { "name": "HTML", "bytes": "313" }, { "name": "JavaScript", "bytes": "122396" } ], "symlink_target": "" }
package org.assertj.core.api.zoneddatetime; import static java.time.ZoneOffset.UTC; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.time.ZoneId; import java.time.ZonedDateTime; import org.junit.Test; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; /** * @author Paweł Stawicki * @author Joel Costigliola * @author Marcin Zajączkowski */ @RunWith(Theories.class) public class ZonedDateTimeAssert_isAfterOrEqualTo_Test extends ZonedDateTimeAssertBaseTest { @Theory public void test_isAfterOrEqual_assertion(ZonedDateTime referenceDate, ZonedDateTime dateBefore, ZonedDateTime dateAfter) { // GIVEN testAssumptions(referenceDate, dateBefore, dateAfter); // WHEN assertThat(dateAfter).isAfterOrEqualTo(referenceDate); assertThat(dateAfter).isAfterOrEqualTo(referenceDate.toString()); assertThat(referenceDate).isAfterOrEqualTo(referenceDate); assertThat(referenceDate).isAfterOrEqualTo(referenceDate.toString()); // THEN verify_that_isAfterOrEqual_assertion_fails_and_throws_AssertionError(dateBefore, referenceDate); } @Test public void isAfterOrEqualTo_should_compare_datetimes_in_actual_timezone() { ZonedDateTime utcDateTime = ZonedDateTime.of(2013, 6, 10, 0, 0, 0, 0, UTC); ZoneId cestTimeZone = ZoneId.of("Europe/Berlin"); ZonedDateTime cestDateTime1 = ZonedDateTime.of(2013, 6, 10, 2, 0, 0, 0, cestTimeZone); ZonedDateTime cestDateTime2 = ZonedDateTime.of(2013, 6, 10, 1, 0, 0, 0, cestTimeZone); // utcDateTime = cestDateTime1 assertThat(utcDateTime).as("in UTC time zone").isAfterOrEqualTo(cestDateTime1); // utcDateTime > cestDateTime2 assertThat(utcDateTime).as("in UTC time zone").isAfterOrEqualTo(cestDateTime2); } @Test public void test_isAfterOrEqual_assertion_error_message() { thrown.expectAssertionError("%nExpecting:%n <2000-01-05T03:00:05Z>%nto be after or equals to:%n <2012-01-01T03:03:03Z>"); assertThat(ZonedDateTime.of(2000, 1, 5, 3, 0, 5, 0, UTC)).isAfterOrEqualTo(ZonedDateTime.of(2012, 1, 1, 3, 3, 3, 0, UTC)); } @Test public void should_fail_if_actual_is_null() { expectException(AssertionError.class, actualIsNull()); ZonedDateTime actual = null; assertThat(actual).isAfterOrEqualTo(ZonedDateTime.now()); } @Test public void should_fail_if_dateTime_parameter_is_null() { expectException(IllegalArgumentException.class, "The ZonedDateTime to compare actual with should not be null"); assertThat(ZonedDateTime.now()).isAfterOrEqualTo((ZonedDateTime) null); } @Test public void should_fail_if_dateTime_as_string_parameter_is_null() { expectException(IllegalArgumentException.class, "The String representing the ZonedDateTime to compare actual with should not be null"); assertThat(ZonedDateTime.now()).isAfterOrEqualTo((String) null); } private static void verify_that_isAfterOrEqual_assertion_fails_and_throws_AssertionError(ZonedDateTime dateToCheck, ZonedDateTime reference) { try { assertThat(dateToCheck).isAfterOrEqualTo(reference); } catch (AssertionError e) { // AssertionError was expected, test same assertion with String based parameter try { assertThat(dateToCheck).isAfterOrEqualTo(reference.toString()); } catch (AssertionError e2) { // AssertionError was expected (again) return; } } fail("Should have thrown AssertionError"); } }
{ "content_hash": "bcc2a718c8f87c28e5e6c29e1045aeaf", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 127, "avg_line_length": 39.65217391304348, "alnum_prop": 0.7436951754385965, "repo_name": "ChrisA89/assertj-core", "id": "36d99addbf4709cd70c157c374877386d682f715", "size": "4257", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isAfterOrEqualTo_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9353819" }, { "name": "Shell", "bytes": "40820" } ], "symlink_target": "" }
// // MediaLaunchObject.h // ConnectSDK // // Created by Ibrahim Adnan on 1/19/15. // Copyright (c) 2015 LG Electronics. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import "MediaControl.h" #import "PlayListControl.h" #import "LaunchSession.h" /*! MediaLaunchObject is a container object which holds LaunchSession object,MediaControl object/or and PlayListControl object*/ @interface MediaLaunchObject : NSObject /*! MediaControl object of Media player*/ @property (nonatomic, strong) id<MediaControl> mediaControl; /*! PlayList Control Object of Media player*/ @property (nonatomic, strong) id<PlayListControl> playListControl; /*! Launch Session object of Media player*/ @property (nonatomic, strong) LaunchSession *session; /*! * Creates an instance of MediaLaunchObject with given property values. * * @param launchSession LaunchSession to allow closing this media player * @param mediaControl MediaControl object used to control playback * @param playListControl PlayListControl object used to control playlist */ - (instancetype) initWithLaunchSession:(LaunchSession *)session andMediaControl:(id<MediaControl>)mediaControl; - (instancetype) initWithLaunchSession:(LaunchSession *)session andMediaControl:(id<MediaControl>)mediaControl andPlayListControl:(id<PlayListControl>)playListControl; @end
{ "content_hash": "a3247bc975f53fcc1da34d79ed6867d3", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 167, "avg_line_length": 38.83673469387755, "alnum_prop": 0.7714135575407252, "repo_name": "david-fenton/Connect-SDK-Cordova-Plugin", "id": "3e8fb1adf502ee67912bd1b7a4fdea9448978828", "size": "1903", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Connect-SDK-iOS/ConnectSDK.framework/Versions/A/Headers/MediaLaunchObject.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1447" }, { "name": "Java", "bytes": "1181430" }, { "name": "JavaScript", "bytes": "75797" }, { "name": "Objective-C", "bytes": "611588" } ], "symlink_target": "" }
<?php final class AphrontDialogView extends AphrontView implements AphrontResponseProducerInterface { private $title; private $shortTitle; private $submitButton; private $cancelURI; private $cancelText = 'Cancel'; private $submitURI; private $hidden = array(); private $class; private $renderAsForm = true; private $formID; private $footers = array(); private $isStandalone; private $method = 'POST'; private $disableWorkflowOnSubmit; private $disableWorkflowOnCancel; private $width = 'default'; private $errors = array(); private $flush; private $validationException; private $objectList; private $resizeX; private $resizeY; const WIDTH_DEFAULT = 'default'; const WIDTH_FORM = 'form'; const WIDTH_FULL = 'full'; public function setMethod($method) { $this->method = $method; return $this; } public function setIsStandalone($is_standalone) { $this->isStandalone = $is_standalone; return $this; } public function setErrors(array $errors) { $this->errors = $errors; return $this; } public function getIsStandalone() { return $this->isStandalone; } public function setSubmitURI($uri) { $this->submitURI = $uri; return $this; } public function setTitle($title) { $this->title = $title; return $this; } public function getTitle() { return $this->title; } public function setShortTitle($short_title) { $this->shortTitle = $short_title; return $this; } public function getShortTitle() { return $this->shortTitle; } public function setResizeY($resize_y) { $this->resizeY = $resize_y; return $this; } public function getResizeY() { return $this->resizeY; } public function setResizeX($resize_x) { $this->resizeX = $resize_x; return $this; } public function getResizeX() { return $this->resizeX; } public function addSubmitButton($text = null) { if (!$text) { $text = pht('Okay'); } $this->submitButton = $text; return $this; } public function addCancelButton($uri, $text = null) { if (!$text) { $text = pht('Cancel'); } $this->cancelURI = $uri; $this->cancelText = $text; return $this; } public function addFooter($footer) { $this->footers[] = $footer; return $this; } public function addHiddenInput($key, $value) { if (is_array($value)) { foreach ($value as $hidden_key => $hidden_value) { $this->hidden[] = array($key.'['.$hidden_key.']', $hidden_value); } } else { $this->hidden[] = array($key, $value); } return $this; } public function setClass($class) { $this->class = $class; return $this; } public function setFlush($flush) { $this->flush = $flush; return $this; } public function setRenderDialogAsDiv() { // TODO: This API is awkward. $this->renderAsForm = false; return $this; } public function setFormID($id) { $this->formID = $id; return $this; } public function setWidth($width) { $this->width = $width; return $this; } public function setObjectList(PHUIObjectItemListView $list) { $this->objectList = true; $box = id(new PHUIObjectBoxView()) ->setObjectList($list); return $this->appendChild($box); } public function appendParagraph($paragraph) { return $this->appendChild( phutil_tag( 'p', array( 'class' => 'aphront-dialog-view-paragraph', ), $paragraph)); } public function appendList(array $items) { $listitems = array(); foreach ($items as $item) { $listitems[] = phutil_tag( 'li', array( 'class' => 'remarkup-list-item', ), $item); } return $this->appendChild( phutil_tag( 'ul', array( 'class' => 'remarkup-list', ), $listitems)); } public function appendForm(AphrontFormView $form) { return $this->appendChild($form->buildLayoutView()); } public function setDisableWorkflowOnSubmit($disable_workflow_on_submit) { $this->disableWorkflowOnSubmit = $disable_workflow_on_submit; return $this; } public function getDisableWorkflowOnSubmit() { return $this->disableWorkflowOnSubmit; } public function setDisableWorkflowOnCancel($disable_workflow_on_cancel) { $this->disableWorkflowOnCancel = $disable_workflow_on_cancel; return $this; } public function getDisableWorkflowOnCancel() { return $this->disableWorkflowOnCancel; } public function setValidationException( PhabricatorApplicationTransactionValidationException $ex = null) { $this->validationException = $ex; return $this; } public function render() { require_celerity_resource('aphront-dialog-view-css'); $buttons = array(); if ($this->submitButton) { $meta = array(); if ($this->disableWorkflowOnSubmit) { $meta['disableWorkflow'] = true; } $buttons[] = javelin_tag( 'button', array( 'name' => '__submit__', 'sigil' => '__default__', 'type' => 'submit', 'meta' => $meta, ), $this->submitButton); } if ($this->cancelURI) { $meta = array(); if ($this->disableWorkflowOnCancel) { $meta['disableWorkflow'] = true; } $buttons[] = javelin_tag( 'a', array( 'href' => $this->cancelURI, 'class' => 'button grey', 'name' => '__cancel__', 'sigil' => 'jx-workflow-button', 'meta' => $meta, ), $this->cancelText); } if (!$this->hasViewer()) { throw new Exception( pht( 'You must call %s when rendering an %s.', 'setViewer()', __CLASS__)); } $classes = array(); $classes[] = 'aphront-dialog-view'; $classes[] = $this->class; if ($this->flush) { $classes[] = 'aphront-dialog-flush'; } switch ($this->width) { case self::WIDTH_FORM: case self::WIDTH_FULL: $classes[] = 'aphront-dialog-view-width-'.$this->width; break; case self::WIDTH_DEFAULT: break; default: throw new Exception( pht( "Unknown dialog width '%s'!", $this->width)); } if ($this->isStandalone) { $classes[] = 'aphront-dialog-view-standalone'; } if ($this->objectList) { $classes[] = 'aphront-dialog-object-list'; } $attributes = array( 'class' => implode(' ', $classes), 'sigil' => 'jx-dialog', 'role' => 'dialog', ); $form_attributes = array( 'action' => $this->submitURI, 'method' => $this->method, 'id' => $this->formID, ); $hidden_inputs = array(); $hidden_inputs[] = phutil_tag( 'input', array( 'type' => 'hidden', 'name' => '__dialog__', 'value' => '1', )); foreach ($this->hidden as $desc) { list($key, $value) = $desc; $hidden_inputs[] = javelin_tag( 'input', array( 'type' => 'hidden', 'name' => $key, 'value' => $value, 'sigil' => 'aphront-dialog-application-input', )); } if (!$this->renderAsForm) { $buttons = array( phabricator_form( $this->getViewer(), $form_attributes, array_merge($hidden_inputs, $buttons)), ); } $children = $this->renderChildren(); $errors = $this->errors; $ex = $this->validationException; $exception_errors = null; if ($ex) { foreach ($ex->getErrors() as $error) { $errors[] = $error->getMessage(); } } if ($errors) { $children = array( id(new PHUIInfoView())->setErrors($errors), $children, ); } $header = new PHUIHeaderView(); $header->setHeader($this->title); $footer = null; if ($this->footers) { $footer = phutil_tag( 'div', array( 'class' => 'aphront-dialog-foot', ), $this->footers); } $resize = null; if ($this->resizeX || $this->resizeY) { $resize = javelin_tag( 'div', array( 'class' => 'aphront-dialog-resize', 'sigil' => 'jx-dialog-resize', 'meta' => array( 'resizeX' => $this->resizeX, 'resizeY' => $this->resizeY, ), )); } $tail = null; if ($buttons || $footer) { $tail = phutil_tag( 'div', array( 'class' => 'aphront-dialog-tail grouped', ), array( $buttons, $footer, $resize, )); } $content = array( phutil_tag( 'div', array( 'class' => 'aphront-dialog-head', ), $header), phutil_tag('div', array( 'class' => 'aphront-dialog-body phabricator-remarkup grouped', ), $children), $tail, ); if ($this->renderAsForm) { return phabricator_form( $this->getViewer(), $form_attributes + $attributes, array($hidden_inputs, $content)); } else { return javelin_tag( 'div', $attributes, $content); } } /* -( AphrontResponseProducerInterface )----------------------------------- */ public function produceAphrontResponse() { return id(new AphrontDialogResponse()) ->setDialog($this); } }
{ "content_hash": "43f62d34d77d85d37cb184296bc75bc5", "timestamp": "", "source": "github", "line_count": 435, "max_line_length": 80, "avg_line_length": 22.06206896551724, "alnum_prop": 0.5440241742211107, "repo_name": "huangjimmy/phabricator-1", "id": "46163938131648d9c23e365cd8c17b57b1124ee9", "size": "9597", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/view/AphrontDialogView.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "160255" }, { "name": "CSS", "bytes": "374350" }, { "name": "JavaScript", "bytes": "907941" }, { "name": "Makefile", "bytes": "9933" }, { "name": "PHP", "bytes": "15911021" }, { "name": "PLSQL", "bytes": "80" }, { "name": "Python", "bytes": "7385" }, { "name": "Roff", "bytes": "30134" }, { "name": "Shell", "bytes": "15982" } ], "symlink_target": "" }
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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from "react"; import PropTypes from "prop-types"; import { isDefined, noop } from "../../utils"; import { getCurrentItem } from "../../utils/ChartDataUtil"; import ClickableCircle from "../components/ClickableCircle"; import ChannelWithArea from "../components/ChannelWithArea"; import HoverTextNearMouse from "../components/HoverTextNearMouse"; var EachEquidistantChannel = function (_Component) { _inherits(EachEquidistantChannel, _Component); function EachEquidistantChannel(props) { _classCallCheck(this, EachEquidistantChannel); var _this = _possibleConstructorReturn(this, (EachEquidistantChannel.__proto__ || Object.getPrototypeOf(EachEquidistantChannel)).call(this, props)); _this.handleLine1Edge1Drag = _this.handleLine1Edge1Drag.bind(_this); _this.handleLine1Edge2Drag = _this.handleLine1Edge2Drag.bind(_this); _this.handleDragStart = _this.handleDragStart.bind(_this); _this.handleChannelDrag = _this.handleChannelDrag.bind(_this); _this.handleDragComplete = _this.handleDragComplete.bind(_this); _this.handleChannelHeightChange = _this.handleChannelHeightChange.bind(_this); _this.handleHover = _this.handleHover.bind(_this); _this.handleSelect = _this.handleSelect.bind(_this); _this.handleUnSelect = _this.handleUnSelect.bind(_this); _this.getEdgeCircle = _this.getEdgeCircle.bind(_this); _this.state = { selected: false, hover: false }; return _this; } _createClass(EachEquidistantChannel, [{ key: "handleHover", value: function handleHover(moreProps) { if (this.state.hover !== moreProps.hovering) { this.setState({ hover: moreProps.hovering }); } } }, { key: "handleSelect", value: function handleSelect() { if (!this.state.selected) { this.setState({ selected: true }); } } }, { key: "handleUnSelect", value: function handleUnSelect() { if (this.state.selected) { this.setState({ selected: false }); } } }, { key: "handleDragStart", value: function handleDragStart() { var _props = this.props, startXY = _props.startXY, endXY = _props.endXY, dy = _props.dy; this.dragStart = { startXY: startXY, endXY: endXY, dy: dy }; } }, { key: "handleChannelDrag", value: function handleChannelDrag(moreProps) { var _props2 = this.props, index = _props2.index, onDrag = _props2.onDrag; var _dragStart = this.dragStart, startXY = _dragStart.startXY, endXY = _dragStart.endXY; var xScale = moreProps.xScale, yScale = moreProps.chartConfig.yScale, xAccessor = moreProps.xAccessor, fullData = moreProps.fullData; var startPos = moreProps.startPos, mouseXY = moreProps.mouseXY; var x1 = xScale(startXY[0]); var y1 = yScale(startXY[1]); var x2 = xScale(endXY[0]); var y2 = yScale(endXY[1]); var dx = startPos[0] - mouseXY[0]; var dy = startPos[1] - mouseXY[1]; var newX1Value = xAccessor(getCurrentItem(xScale, xAccessor, [x1 - dx, y1 - dy], fullData)); var newY1Value = yScale.invert(y1 - dy); var newX2Value = xAccessor(getCurrentItem(xScale, xAccessor, [x2 - dx, y2 - dy], fullData)); var newY2Value = yScale.invert(y2 - dy); // const newDy = newY2Value - endXY[1] + this.dragStart.dy; onDrag(index, { startXY: [newX1Value, newY1Value], endXY: [newX2Value, newY2Value], dy: this.dragStart.dy }); } }, { key: "handleLine1Edge1Drag", value: function handleLine1Edge1Drag(moreProps) { var _props3 = this.props, index = _props3.index, onDrag = _props3.onDrag; var startXY = this.dragStart.startXY; var startPos = moreProps.startPos, mouseXY = moreProps.mouseXY, xAccessor = moreProps.xAccessor, xScale = moreProps.xScale, fullData = moreProps.fullData, yScale = moreProps.chartConfig.yScale; var dx = startPos[0] - mouseXY[0]; var dy = startPos[1] - mouseXY[1]; var x1 = xScale(startXY[0]); var y1 = yScale(startXY[1]); var newX1Value = xAccessor(getCurrentItem(xScale, xAccessor, [x1 - dx, y1 - dy], fullData)); var newY1Value = yScale.invert(y1 - dy); onDrag(index, { startXY: [newX1Value, newY1Value], endXY: this.dragStart.endXY, dy: this.dragStart.dy }); } }, { key: "handleLine1Edge2Drag", value: function handleLine1Edge2Drag(moreProps) { var _props4 = this.props, index = _props4.index, onDrag = _props4.onDrag; var endXY = this.dragStart.endXY; var startPos = moreProps.startPos, mouseXY = moreProps.mouseXY, xAccessor = moreProps.xAccessor, xScale = moreProps.xScale, fullData = moreProps.fullData, yScale = moreProps.chartConfig.yScale; var dx = startPos[0] - mouseXY[0]; var dy = startPos[1] - mouseXY[1]; var x1 = xScale(endXY[0]); var y1 = yScale(endXY[1]); var newX1Value = xAccessor(getCurrentItem(xScale, xAccessor, [x1 - dx, y1 - dy], fullData)); var newY1Value = yScale.invert(y1 - dy); onDrag(index, { startXY: this.dragStart.startXY, endXY: [newX1Value, newY1Value], dy: this.dragStart.dy }); } }, { key: "handleChannelHeightChange", value: function handleChannelHeightChange(moreProps) { var _props5 = this.props, index = _props5.index, onDrag = _props5.onDrag; var _dragStart2 = this.dragStart, startXY = _dragStart2.startXY, endXY = _dragStart2.endXY; var yScale = moreProps.chartConfig.yScale; var startPos = moreProps.startPos, mouseXY = moreProps.mouseXY; var y2 = yScale(endXY[1]); var dy = startPos[1] - mouseXY[1]; var newY2Value = yScale.invert(y2 - dy); var newDy = newY2Value - endXY[1] + this.dragStart.dy; onDrag(index, { startXY: startXY, endXY: endXY, dy: newDy }); } }, { key: "handleDragComplete", value: function handleDragComplete() { var onDragComplete = this.props.onDragComplete; if (!this.state.selected) { this.setState({ selected: true }); } onDragComplete(); } }, { key: "getEdgeCircle", value: function getEdgeCircle(_ref) { var xy = _ref.xy, dragHandler = _ref.dragHandler, cursor = _ref.cursor, fill = _ref.fill; var _state = this.state, selected = _state.selected, hover = _state.hover; var _props6 = this.props, edgeStroke = _props6.edgeStroke, edgeStrokeWidth = _props6.edgeStrokeWidth, r = _props6.r; return React.createElement(ClickableCircle, { show: selected || hover, cx: xy[0], cy: xy[1], r: r, fill: fill, stroke: edgeStroke, strokeWidth: edgeStrokeWidth, opacity: 1, interactiveCursorClass: cursor, onDragStart: this.handleDragStart, onDrag: dragHandler, onDragComplete: this.handleDragComplete }); } }, { key: "render", value: function render() { var _props7 = this.props, startXY = _props7.startXY, endXY = _props7.endXY, dy = _props7.dy; var _props8 = this.props, interactive = _props8.interactive, edgeFill = _props8.edgeFill, hoverText = _props8.hoverText; var _props9 = this.props, stroke = _props9.stroke, strokeWidth = _props9.strokeWidth, fill = _props9.fill, opacity = _props9.opacity; var _state2 = this.state, selected = _state2.selected, hover = _state2.hover; var hoverTextEnabled = hoverText.enable, restHoverTextProps = _objectWithoutProperties(hoverText, ["enable"]); var hoverHandler = interactive ? { onHover: this.handleHover, onBlur: this.handleHover } : {}; var line1Edge = isDefined(startXY) && isDefined(endXY) ? React.createElement( "g", null, this.getEdgeCircle({ xy: startXY, dragHandler: this.handleLine1Edge1Drag, cursor: "react-stockcharts-move-cursor", fill: edgeFill }), this.getEdgeCircle({ xy: endXY, dragHandler: this.handleLine1Edge2Drag, cursor: "react-stockcharts-move-cursor", fill: edgeFill }) ) : null; var line2Edge = isDefined(dy) ? React.createElement( "g", null, this.getEdgeCircle({ xy: [startXY[0], startXY[1] + dy], dragHandler: this.handleChannelHeightChange, cursor: "react-stockcharts-ns-resize-cursor", fill: "#250B98" }), this.getEdgeCircle({ xy: [endXY[0], endXY[1] + dy], dragHandler: this.handleChannelHeightChange, cursor: "react-stockcharts-ns-resize-cursor", fill: "#250B98" }) ) : null; return React.createElement( "g", null, React.createElement(ChannelWithArea, _extends({ selected: selected || hover }, hoverHandler, { onClick: this.handleSelect, onClickOutside: this.handleUnSelect, startXY: startXY, endXY: endXY, dy: dy, stroke: stroke, strokeWidth: hover || selected ? strokeWidth + 1 : strokeWidth, fill: fill, opacity: opacity, interactiveCursorClass: "react-stockcharts-move-cursor", onDragStart: this.handleDragStart, onDrag: this.handleChannelDrag, onDragComplete: this.handleDragComplete })), line1Edge, line2Edge, React.createElement(HoverTextNearMouse, _extends({ show: hoverTextEnabled && hover && !selected }, restHoverTextProps)) ); } }]); return EachEquidistantChannel; }(Component); EachEquidistantChannel.propTypes = { startXY: PropTypes.arrayOf(PropTypes.number).isRequired, endXY: PropTypes.arrayOf(PropTypes.number).isRequired, dy: PropTypes.number, stroke: PropTypes.string.isRequired, strokeWidth: PropTypes.number.isRequired, fill: PropTypes.string.isRequired, opacity: PropTypes.number.isRequired, interactive: PropTypes.bool.isRequired, r: PropTypes.number.isRequired, edgeFill: PropTypes.string.isRequired, edgeStroke: PropTypes.string.isRequired, edgeStrokeWidth: PropTypes.number.isRequired, hoverText: PropTypes.object.isRequired, index: PropTypes.number, onDrag: PropTypes.func.isRequired, onDragComplete: PropTypes.func.isRequired }; EachEquidistantChannel.defaultProps = { yDisplayFormat: function yDisplayFormat(d) { return d.toFixed(2); }, interactive: true, edgeStroke: "#000000", edgeFill: "#FFFFFF", edgeStrokeWidth: 1, r: 5, onDrag: noop, onDragComplete: noop, hoverText: { enable: false } }; export default EachEquidistantChannel;
{ "content_hash": "f9c773a97f9dba0d431737d2d60c0347", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 564, "avg_line_length": 31.258227848101267, "alnum_prop": 0.6732809589373937, "repo_name": "rrag/rrag.github.io", "id": "ea752a12c84a39ffa97d44a72bccdbba4cbdbff6", "size": "12347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "react-stockcharts-next/es/lib/interactive/hoc/EachEquidistantChannel.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "243899" }, { "name": "HTML", "bytes": "425316" }, { "name": "JavaScript", "bytes": "2980093" } ], "symlink_target": "" }
This is a place holder to keep custom chaincodes
{ "content_hash": "84cb1cfad4786f7ed884187297a84f2a", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 48, "avg_line_length": 49, "alnum_prop": 0.8163265306122449, "repo_name": "tkuhrt/fabric", "id": "aa1483ad772439e20b5a185afd3fe9bf1def33cc", "size": "49", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "test/regression/daily/chaincodeTests/fabricFeatureChaincodes/go/README.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "845" }, { "name": "Gherkin", "bytes": "39417" }, { "name": "Go", "bytes": "4552001" }, { "name": "HTML", "bytes": "9373" }, { "name": "Java", "bytes": "101170" }, { "name": "JavaScript", "bytes": "149351" }, { "name": "Makefile", "bytes": "18794" }, { "name": "Protocol Buffer", "bytes": "94439" }, { "name": "Python", "bytes": "239318" }, { "name": "Ruby", "bytes": "3473" }, { "name": "Shell", "bytes": "139125" } ], "symlink_target": "" }
#ifndef __itkMaximumRatioDecisionRule2_h #define __itkMaximumRatioDecisionRule2_h #include <vector> #include "vnl/vnl_matrix.h" #include "itkNumericTraits.h" #include "itkDecisionRule.h" namespace itk { namespace Statistics { /** \class MaximumRatioDecisionRule2 * \brief This rule returns \f$i\f$ if * \f$\frac{f_{i}(\overrightarrow{x})}{f_{j}(\overrightarrow{x})} > * \frac{K_{j}}{K_{i}}\f$ for all \f$j \not= i\f$, * where the \f$i\f$ is the index of a class which has * membership function \f$f_{i}\f$ and its prior value * (usually, the a priori probability or the size of a class) is * \f$K_{i}\f$ * * Users should set the a priori values before calling the Evaluate method. * * \sa MaximumDecisionRule, MinimumDecisionRule * \ingroup ITK-Statistics */ class ITK_EXPORT MaximumRatioDecisionRule2: public DecisionRule { public: /** Standard class typedefs */ typedef MaximumRatioDecisionRule2 Self; typedef DecisionRule Superclass; typedef SmartPointer< Self > Pointer; /** Run-time type information (and related methods) */ itkTypeMacro(MaximumRatioDecisionRule2, DecisionRule); /** Standard New() method support */ itkNewMacro(Self); typedef float APrioriValueType; typedef std::vector< APrioriValueType > APrioriVectorType; typedef APrioriVectorType::size_type APrioriVectorSizeType; typedef Superclass::MembershipVectorType MembershipVectorType; /** The return value of this function is a class label. * Basically, using its internal logic based on the discriminant * scores, this function decides best class label and return it. */ virtual unsigned int Evaluate(const MembershipVectorType & discriminantScores) const; /** Sets the a priori probabilities */ void SetAPriori(APrioriVectorType & values); protected: MaximumRatioDecisionRule2(); virtual ~MaximumRatioDecisionRule2() {} private: MaximumRatioDecisionRule2(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented /** Number of classes */ APrioriVectorSizeType m_NumberOfClasses; /** a priori probability ratio matrix: internal use */ vnl_matrix< double > m_APrioriRatioMatrix; }; // end of class } // end of Statistics namespace } // end of ITK namespace #endif
{ "content_hash": "9f12a6c586c540ff7bc12a21b178c0b3", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 87, "avg_line_length": 31.04, "alnum_prop": 0.7186426116838488, "repo_name": "wkjeong/ITK", "id": "343bd080a8aa152311200c8cf8d3ff09cfe13089", "size": "3103", "binary": false, "copies": "5", "ref": "refs/heads/GPU-Beta", "path": "Modules/Numerics/Statistics/include/itkMaximumRatioDecisionRule2.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "26423634" }, { "name": "C#", "bytes": "1714" }, { "name": "C++", "bytes": "29008852" }, { "name": "FORTRAN", "bytes": "2241251" }, { "name": "Java", "bytes": "60339" }, { "name": "Objective-C", "bytes": "6591" }, { "name": "Perl", "bytes": "17899" }, { "name": "Prolog", "bytes": "4406" }, { "name": "Python", "bytes": "928115" }, { "name": "Ruby", "bytes": "296" }, { "name": "Shell", "bytes": "179616" }, { "name": "Tcl", "bytes": "133660" } ], "symlink_target": "" }
// This is a compatibilty file for Windows Builds ONLY #if (defined(WIN32) || defined(UNDER_CE)) && !defined(CYGWIN) #include <windows.h> #ifndef __attribute__ #define __attribute__(x) #endif #ifndef unused #define unused #endif #ifndef restrict #define restrict #endif #ifndef _STDINT_H // this is the Standard C99 header define lock #define _STDINT_H typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef signed long long int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; #endif #endif
{ "content_hash": "52d03e889432959374d14d599b000827", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 64, "avg_line_length": 18.805555555555557, "alnum_prop": 0.6957163958641064, "repo_name": "aosp/dvp", "id": "fd54ac0a960f0fa7e9ba1497f7520a8dcbd720e8", "size": "1290", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/win32/stdint.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "149270" }, { "name": "C", "bytes": "2265570" }, { "name": "C++", "bytes": "1234648" }, { "name": "Makefile", "bytes": "160815" }, { "name": "Objective-C", "bytes": "1698" }, { "name": "Perl", "bytes": "17877" }, { "name": "Shell", "bytes": "121061" } ], "symlink_target": "" }
using UnityEngine; using System.Collections.Generic; /// <summary> /// UI Panel is responsible for collecting, sorting and updating widgets in addition to generating widgets' geometry. /// </summary> [ExecuteInEditMode] [AddComponentMenu("NGUI/UI/NGUI Panel")] public class UIPanel : UIRect { /// <summary> /// List of active panels. /// </summary> static public List<UIPanel> list = new List<UIPanel>(); public enum RenderQueue { Automatic, StartAt, Explicit, } public delegate void OnGeometryUpdated (); /// <summary> /// Notification triggered when the panel's geometry get rebuilt. It's mainly here for debugging purposes. /// </summary> public OnGeometryUpdated onGeometryUpdated; /// <summary> /// Whether this panel will show up in the panel tool (set this to 'false' for dynamically created temporary panels) /// </summary> public bool showInPanelTool = true; /// <summary> /// Whether normals and tangents will be generated for all meshes /// </summary> public bool generateNormals = false; /// <summary> /// Whether widgets drawn by this panel are static (won't move). This will improve performance. /// </summary> public bool widgetsAreStatic = false; /// <summary> /// Whether widgets will be culled while the panel is being dragged. /// Having this on improves performance, but turning it off will reduce garbage collection. /// </summary> public bool cullWhileDragging = true; /// <summary> /// Optimization flag. Makes the assumption that the panel's geometry /// will always be on screen and the bounds don't need to be re-calculated. /// </summary> public bool alwaysOnScreen = false; /// <summary> /// By default, non-clipped panels use the camera's bounds, and the panel's position has no effect. /// If you want the panel's position to actually be used with anchors, set this field to 'true'. /// </summary> public bool anchorOffset = false; /// <summary> /// Whether the soft border will be used as padding. /// </summary> public bool softBorderPadding = true; /// <summary> /// By default all panels manage render queues of their draw calls themselves by incrementing them /// so that the geometry is drawn in the proper order. You can alter this behaviour. /// </summary> public RenderQueue renderQueue = RenderQueue.Automatic; /// <summary> /// Render queue used by the panel. The default value of '3000' is the equivalent of "Transparent". /// This property is only used if 'renderQueue' is set to something other than "Automatic". /// </summary> public int startingRenderQueue = 3000; /// <summary> /// List of widgets managed by this panel. Do not attempt to modify this list yourself. /// </summary> [System.NonSerialized] public List<UIWidget> widgets = new List<UIWidget>(); /// <summary> /// List of draw calls created by this panel. Do not attempt to modify this list yourself. /// </summary> [System.NonSerialized] public List<UIDrawCall> drawCalls = new List<UIDrawCall>(); /// <summary> /// Matrix that will transform the specified world coordinates to relative-to-panel coordinates. /// </summary> [System.NonSerialized] public Matrix4x4 worldToLocal = Matrix4x4.identity; /// <summary> /// Cached clip range passed to the draw call's shader. /// </summary> [System.NonSerialized] public Vector4 drawCallClipRange = new Vector4(0f, 0f, 1f, 1f); public delegate void OnClippingMoved (UIPanel panel); /// <summary> /// Event callback that's triggered when the panel's clip region gets moved. /// </summary> public OnClippingMoved onClipMove; // Panel's alpha (affects the alpha of all widgets) [HideInInspector][SerializeField] float mAlpha = 1f; // Clipping rectangle [HideInInspector][SerializeField] UIDrawCall.Clipping mClipping = UIDrawCall.Clipping.None; [HideInInspector][SerializeField] Vector4 mClipRange = new Vector4(0f, 0f, 300f, 200f); [HideInInspector][SerializeField] Vector2 mClipSoftness = new Vector2(4f, 4f); [HideInInspector][SerializeField] int mDepth = 0; [HideInInspector][SerializeField] int mSortingOrder = 0; // Whether a full rebuild of geometry buffers is required bool mRebuild = false; bool mResized = false; [SerializeField] Vector2 mClipOffset = Vector2.zero; float mCullTime = 0f; float mUpdateTime = 0f; int mMatrixFrame = -1; int mAlphaFrameID = 0; int mLayer = -1; // Values used for visibility checks static float[] mTemp = new float[4]; Vector2 mMin = Vector2.zero; Vector2 mMax = Vector2.zero; bool mHalfPixelOffset = false; bool mSortWidgets = false; bool mUpdateScroll = false; /// <summary> /// Helper property that returns the first unused depth value. /// </summary> static public int nextUnusedDepth { get { int highest = int.MinValue; for (int i = 0, imax = list.Count; i < imax; ++i) highest = Mathf.Max(highest, list[i].depth); return (highest == int.MinValue) ? 0 : highest + 1; } } /// <summary> /// Whether the rectangle can be anchored. /// </summary> public override bool canBeAnchored { get { return mClipping != UIDrawCall.Clipping.None; } } /// <summary> /// Panel's alpha affects everything drawn by the panel. /// </summary> public override float alpha { get { return mAlpha; } set { float val = Mathf.Clamp01(value); if (mAlpha != val) { mAlphaFrameID = -1; mResized = true; mAlpha = val; SetDirty(); } } } /// <summary> /// Panels can have their own depth value that will change the order with which everything they manage gets drawn. /// </summary> public int depth { get { return mDepth; } set { if (mDepth != value) { mDepth = value; #if UNITY_EDITOR NGUITools.SetDirty(this); #endif list.Sort(CompareFunc); } } } /// <summary> /// Sorting order value for the panel's draw calls, to be used with Unity's 2D system. /// </summary> public int sortingOrder { get { return mSortingOrder; } set { if (mSortingOrder != value) { mSortingOrder = value; #if UNITY_EDITOR NGUITools.SetDirty(this); #endif UpdateDrawCalls(); } } } /// <summary> /// Function that can be used to depth-sort panels. /// </summary> static public int CompareFunc (UIPanel a, UIPanel b) { if (a != b && a != null && b != null) { if (a.mDepth < b.mDepth) return -1; if (a.mDepth > b.mDepth) return 1; return (a.GetInstanceID() < b.GetInstanceID()) ? -1 : 1; } return 0; } /// <summary> /// Panel's width in pixels. /// </summary> public float width { get { return GetViewSize().x; } } /// <summary> /// Panel's height in pixels. /// </summary> public float height { get { return GetViewSize().y; } } /// <summary> /// Whether the panel's drawn geometry needs to be offset by a half-pixel. /// </summary> public bool halfPixelOffset { get { return mHalfPixelOffset; } } /// <summary> /// Whether the camera is used to draw UI geometry. /// </summary> public bool usedForUI { get { return (anchorCamera != null && mCam.orthographic); } } /// <summary> /// Directx9 pixel offset, used for drawing. /// </summary> public Vector3 drawCallOffset { get { if (mHalfPixelOffset && anchorCamera != null && mCam.orthographic) { Vector2 size = GetWindowSize(); float mod = (1f / size.y) / mCam.orthographicSize; return new Vector3(-mod, mod); } return Vector3.zero; } } /// <summary> /// Clipping method used by all draw calls. /// </summary> public UIDrawCall.Clipping clipping { get { return mClipping; } set { if (mClipping != value) { mResized = true; mClipping = value; mMatrixFrame = -1; #if UNITY_EDITOR if (!Application.isPlaying) UpdateDrawCalls(); #endif } } } UIPanel mParentPanel = null; /// <summary> /// Reference to the parent panel, if any. /// </summary> public UIPanel parentPanel { get { return mParentPanel; } } /// <summary> /// Number of times the panel's contents get clipped. /// </summary> public int clipCount { get { int count = 0; UIPanel p = this; while (p != null) { if (p.mClipping == UIDrawCall.Clipping.SoftClip) ++count; p = p.mParentPanel; } return count; } } /// <summary> /// Whether the panel will actually perform clipping of children. /// </summary> public bool hasClipping { get { return mClipping == UIDrawCall.Clipping.SoftClip; } } /// <summary> /// Whether the panel will actually perform clipping of children. /// </summary> public bool hasCumulativeClipping { get { return clipCount != 0; } } [System.Obsolete("Use 'hasClipping' or 'hasCumulativeClipping' instead")] public bool clipsChildren { get { return hasCumulativeClipping; } } /// <summary> /// Clipping area offset used to make it possible to move clipped panels (scroll views) efficiently. /// Scroll views move by adjusting the clip offset by one value, and the transform position by the inverse. /// This makes it possible to not have to rebuild the geometry, greatly improving performance. /// </summary> public Vector2 clipOffset { get { return mClipOffset; } set { if (Mathf.Abs(mClipOffset.x - value.x) > 0.001f || Mathf.Abs(mClipOffset.y - value.y) > 0.001f) { mClipOffset = value; InvalidateClipping(); // Call the event delegate if (onClipMove != null) onClipMove(this); #if UNITY_EDITOR if (!Application.isPlaying) UpdateDrawCalls(); #endif } } } /// <summary> /// Invalidate the panel's clipping, calling child panels in turn. /// </summary> void InvalidateClipping () { mResized = true; mMatrixFrame = -1; mCullTime = (mCullTime == 0f) ? 0.001f : RealTime.time + 0.15f; for (int i = 0, imax = list.Count; i < imax; ++i) { UIPanel p = list[i]; if (p != this && p.parentPanel == this) p.InvalidateClipping(); } } /// <summary> /// Clipping position (XY) and size (ZW). /// Note that you should not be modifying this property at run-time to reposition the clipping. Adjust clipOffset instead. /// </summary> [System.Obsolete("Use 'finalClipRegion' or 'baseClipRegion' instead")] public Vector4 clipRange { get { return baseClipRegion; } set { baseClipRegion = value; } } /// <summary> /// Clipping position (XY) and size (ZW). /// Note that you should not be modifying this property at run-time to reposition the clipping. Adjust clipOffset instead. /// </summary> public Vector4 baseClipRegion { get { return mClipRange; } set { if (Mathf.Abs(mClipRange.x - value.x) > 0.001f || Mathf.Abs(mClipRange.y - value.y) > 0.001f || Mathf.Abs(mClipRange.z - value.z) > 0.001f || Mathf.Abs(mClipRange.w - value.w) > 0.001f) { mResized = true; mCullTime = (mCullTime == 0f) ? 0.001f : RealTime.time + 0.15f; mClipRange = value; mMatrixFrame = -1; UIScrollView sv = GetComponent<UIScrollView>(); if (sv != null) sv.UpdatePosition(); if (onClipMove != null) onClipMove(this); #if UNITY_EDITOR if (!Application.isPlaying) UpdateDrawCalls(); #endif } } } /// <summary> /// Final clipping region after the offset has been taken into consideration. XY = center, ZW = size. /// </summary> public Vector4 finalClipRegion { get { Vector2 size = GetViewSize(); if (mClipping != UIDrawCall.Clipping.None) { return new Vector4(mClipRange.x + mClipOffset.x, mClipRange.y + mClipOffset.y, size.x, size.y); } return new Vector4(0f, 0f, size.x, size.y); } } /// <summary> /// Clipping softness is used if the clipped style is set to "Soft". /// </summary> public Vector2 clipSoftness { get { return mClipSoftness; } set { if (mClipSoftness != value) { mClipSoftness = value; #if UNITY_EDITOR if (!Application.isPlaying) UpdateDrawCalls(); #endif } } } // Temporary variable to avoid GC allocation static Vector3[] mCorners = new Vector3[4]; /// <summary> /// Local-space corners of the panel's clipping rectangle. The order is bottom-left, top-left, top-right, bottom-right. /// </summary> public override Vector3[] localCorners { get { if (mClipping == UIDrawCall.Clipping.None) { Vector3[] corners = worldCorners; Transform wt = cachedTransform; for (int i = 0; i < 4; ++i) corners[i] = wt.InverseTransformPoint(corners[i]); return corners; } else { float x0 = mClipOffset.x + mClipRange.x - 0.5f * mClipRange.z; float y0 = mClipOffset.y + mClipRange.y - 0.5f * mClipRange.w; float x1 = x0 + mClipRange.z; float y1 = y0 + mClipRange.w; mCorners[0] = new Vector3(x0, y0); mCorners[1] = new Vector3(x0, y1); mCorners[2] = new Vector3(x1, y1); mCorners[3] = new Vector3(x1, y0); } return mCorners; } } /// <summary> /// World-space corners of the panel's clipping rectangle. The order is bottom-left, top-left, top-right, bottom-right. /// </summary> public override Vector3[] worldCorners { get { if (mClipping != UIDrawCall.Clipping.None) { float x0 = mClipOffset.x + mClipRange.x - 0.5f * mClipRange.z; float y0 = mClipOffset.y + mClipRange.y - 0.5f * mClipRange.w; float x1 = x0 + mClipRange.z; float y1 = y0 + mClipRange.w; Transform wt = cachedTransform; mCorners[0] = wt.TransformPoint(x0, y0, 0f); mCorners[1] = wt.TransformPoint(x0, y1, 0f); mCorners[2] = wt.TransformPoint(x1, y1, 0f); mCorners[3] = wt.TransformPoint(x1, y0, 0f); } else if (anchorCamera != null) { Vector3[] corners = mCam.GetWorldCorners(cameraRayDistance); //if (anchorOffset && mCam == null || mCam.transform.parent != cachedTransform) //{ // Vector3 off = cachedTransform.position; // for (int i = 0; i < 4; ++i) // corners[i] += off; //} return corners; } else { Vector2 size = GetViewSize(); float x0 = -0.5f * size.x; float y0 = -0.5f * size.y; float x1 = x0 + size.x; float y1 = y0 + size.y; mCorners[0] = new Vector3(x0, y0); mCorners[1] = new Vector3(x0, y1); mCorners[2] = new Vector3(x1, y1); mCorners[3] = new Vector3(x1, y0); if (anchorOffset && mCam == null || mCam.transform.parent != cachedTransform) { Vector3 off = cachedTransform.position; for (int i = 0; i < 4; ++i) mCorners[i] += off; } } return mCorners; } } /// <summary> /// Get the sides of the rectangle relative to the specified transform. /// The order is left, top, right, bottom. /// </summary> public override Vector3[] GetSides (Transform relativeTo) { if (mClipping != UIDrawCall.Clipping.None) { float x0 = mClipOffset.x + mClipRange.x - 0.5f * mClipRange.z; float y0 = mClipOffset.y + mClipRange.y - 0.5f * mClipRange.w; float x1 = x0 + mClipRange.z; float y1 = y0 + mClipRange.w; float hx = (x0 + x1) * 0.5f; float hy = (y0 + y1) * 0.5f; Transform wt = cachedTransform; mSides[0] = wt.TransformPoint(x0, hy, 0f); mSides[1] = wt.TransformPoint(hx, y1, 0f); mSides[2] = wt.TransformPoint(x1, hy, 0f); mSides[3] = wt.TransformPoint(hx, y0, 0f); if (relativeTo != null) { for (int i = 0; i < 4; ++i) mSides[i] = relativeTo.InverseTransformPoint(mSides[i]); } return mSides; } else if (anchorCamera != null && anchorOffset) { Vector3[] sides = mCam.GetSides(cameraRayDistance); Vector3 off = cachedTransform.position; for (int i = 0; i < 4; ++i) sides[i] += off; if (relativeTo != null) { for (int i = 0; i < 4; ++i) sides[i] = relativeTo.InverseTransformPoint(sides[i]); } return sides; } return base.GetSides(relativeTo); } /// <summary> /// Invalidating the panel should reset its alpha. /// </summary> public override void Invalidate (bool includeChildren) { mAlphaFrameID = -1; base.Invalidate(includeChildren); } /// <summary> /// Widget's final alpha, after taking the panel's alpha into account. /// </summary> public override float CalculateFinalAlpha (int frameID) { #if UNITY_EDITOR if (mAlphaFrameID != frameID || !Application.isPlaying) #else if (mAlphaFrameID != frameID) #endif { mAlphaFrameID = frameID; UIRect pt = parent; finalAlpha = (parent != null) ? pt.CalculateFinalAlpha(frameID) * mAlpha : mAlpha; } return finalAlpha; } /// <summary> /// Set the panel's rectangle. /// </summary> public override void SetRect (float x, float y, float width, float height) { int finalWidth = Mathf.FloorToInt(width + 0.5f); int finalHeight = Mathf.FloorToInt(height + 0.5f); finalWidth = ((finalWidth >> 1) << 1); finalHeight = ((finalHeight >> 1) << 1); Transform t = cachedTransform; Vector3 pos = t.localPosition; pos.x = Mathf.Floor(x + 0.5f); pos.y = Mathf.Floor(y + 0.5f); if (finalWidth < 2) finalWidth = 2; if (finalHeight < 2) finalHeight = 2; baseClipRegion = new Vector4(pos.x, pos.y, finalWidth, finalHeight); if (isAnchored) { t = t.parent; if (leftAnchor.target) leftAnchor.SetHorizontal(t, x); if (rightAnchor.target) rightAnchor.SetHorizontal(t, x + width); if (bottomAnchor.target) bottomAnchor.SetVertical(t, y); if (topAnchor.target) topAnchor.SetVertical(t, y + height); #if UNITY_EDITOR NGUITools.SetDirty(this); #endif } } /// <summary> /// Returns whether the specified rectangle is visible by the panel. The coordinates must be in world space. /// </summary> public bool IsVisible (Vector3 a, Vector3 b, Vector3 c, Vector3 d) { UpdateTransformMatrix(); // Transform the specified points from world space to local space a = worldToLocal.MultiplyPoint3x4(a); b = worldToLocal.MultiplyPoint3x4(b); c = worldToLocal.MultiplyPoint3x4(c); d = worldToLocal.MultiplyPoint3x4(d); mTemp[0] = a.x; mTemp[1] = b.x; mTemp[2] = c.x; mTemp[3] = d.x; float minX = Mathf.Min(mTemp); float maxX = Mathf.Max(mTemp); mTemp[0] = a.y; mTemp[1] = b.y; mTemp[2] = c.y; mTemp[3] = d.y; float minY = Mathf.Min(mTemp); float maxY = Mathf.Max(mTemp); if (maxX < mMin.x) return false; if (maxY < mMin.y) return false; if (minX > mMax.x) return false; if (minY > mMax.y) return false; return true; } /// <summary> /// Returns whether the specified world position is within the panel's bounds determined by the clipping rect. /// </summary> public bool IsVisible (Vector3 worldPos) { if (mAlpha < 0.001f) return false; if (mClipping == UIDrawCall.Clipping.None || mClipping == UIDrawCall.Clipping.ConstrainButDontClip) return true; UpdateTransformMatrix(); Vector3 pos = worldToLocal.MultiplyPoint3x4(worldPos); if (pos.x < mMin.x) return false; if (pos.y < mMin.y) return false; if (pos.x > mMax.x) return false; if (pos.y > mMax.y) return false; return true; } /// <summary> /// Returns whether the specified widget is visible by the panel. /// </summary> public bool IsVisible (UIWidget w) { UIPanel p = this; Vector3[] corners = null; while (p != null) { if ((p.mClipping == UIDrawCall.Clipping.None || p.mClipping == UIDrawCall.Clipping.ConstrainButDontClip) && !w.hideIfOffScreen) { p = p.mParentPanel; continue; } if (corners == null) corners = w.worldCorners; if (!p.IsVisible(corners[0], corners[1], corners[2], corners[3])) return false; p = p.mParentPanel; } return true; } /// <summary> /// Whether the specified widget is going to be affected by this panel in any way. /// </summary> public bool Affects (UIWidget w) { if (w == null) return false; UIPanel expected = w.panel; if (expected == null) return false; UIPanel p = this; while (p != null) { if (p == expected) return true; if (!p.hasCumulativeClipping) return false; p = p.mParentPanel; } return false; } /// <summary> /// Causes all draw calls to be re-created on the next update. /// </summary> [ContextMenu("Force Refresh")] public void RebuildAllDrawCalls () { mRebuild = true; } /// <summary> /// Invalidate the panel's draw calls, forcing them to be rebuilt on the next update. /// This call also affects all children. /// </summary> public void SetDirty () { for (int i = 0, imax = drawCalls.Count; i < imax; ++i) drawCalls[i].isDirty = true; Invalidate(true); } /// <summary> /// Cache components. /// </summary> void Awake () { mGo = gameObject; mTrans = transform; mHalfPixelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.XBOX360 || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); // Only DirectX 9 needs the half-pixel offset if (mHalfPixelOffset) mHalfPixelOffset = (SystemInfo.graphicsShaderLevel < 40); } /// <summary> /// Find the parent panel, if we have one. /// </summary> void FindParent () { Transform parent = cachedTransform.parent; mParentPanel = (parent != null) ? NGUITools.FindInParents<UIPanel>(parent.gameObject) : null; } /// <summary> /// Find the parent panel, if we have one. /// </summary> public override void ParentHasChanged () { base.ParentHasChanged(); FindParent(); } /// <summary> /// Layer is used to ensure that if it changes, widgets get moved as well. /// </summary> protected override void OnStart () { mLayer = mGo.layer; } /// <summary> /// Reset the frame IDs. /// </summary> protected override void OnEnable () { mRebuild = true; mAlphaFrameID = -1; mMatrixFrame = -1; OnStart(); base.OnEnable(); mMatrixFrame = -1; } /// <summary> /// Mark all widgets as having been changed so the draw calls get re-created. /// </summary> protected override void OnInit () { base.OnInit(); // Apparently having a rigidbody helps if (GetComponent<Rigidbody>() == null) { UICamera uic = (anchorCamera != null) ? mCam.GetComponent<UICamera>() : null; if (uic != null) { if (uic.eventType == UICamera.EventType.UI_3D || uic.eventType == UICamera.EventType.World_3D) { Rigidbody rb = gameObject.AddComponent<Rigidbody>(); rb.isKinematic = true; rb.useGravity = false; } // It's unclear if this helps 2D physics or not, so leaving it disabled for now. // Note that when enabling this, the 'if (rigidbody == null)' statement above should be adjusted as well. //else //{ // Rigidbody2D rb = gameObject.AddComponent<Rigidbody2D>(); // rb.isKinematic = true; //} } } FindParent(); mRebuild = true; mAlphaFrameID = -1; mMatrixFrame = -1; list.Add(this); list.Sort(CompareFunc); } /// <summary> /// Destroy all draw calls we've created when this script gets disabled. /// </summary> protected override void OnDisable () { for (int i = 0, imax = drawCalls.Count; i < imax; ++i) { UIDrawCall dc = drawCalls[i]; if (dc != null) UIDrawCall.Destroy(dc); } drawCalls.Clear(); list.Remove(this); mAlphaFrameID = -1; mMatrixFrame = -1; if (list.Count == 0) { UIDrawCall.ReleaseAll(); mUpdateFrame = -1; } base.OnDisable(); } /// <summary> /// Update the world-to-local transform matrix as well as clipping bounds. /// </summary> void UpdateTransformMatrix () { int fc = Time.frameCount; if (mMatrixFrame != fc) { mMatrixFrame = fc; worldToLocal = cachedTransform.worldToLocalMatrix; Vector2 size = GetViewSize() * 0.5f; float x = mClipOffset.x + mClipRange.x; float y = mClipOffset.y + mClipRange.y; mMin.x = x - size.x; mMin.y = y - size.y; mMax.x = x + size.x; mMax.y = y + size.y; } } /// <summary> /// Update the edges after the anchors have been updated. /// </summary> protected override void OnAnchor () { // No clipping = no edges to anchor if (mClipping == UIDrawCall.Clipping.None) return; Transform trans = cachedTransform; Transform parent = trans.parent; Vector2 size = GetViewSize(); Vector2 offset = trans.localPosition; float lt, bt, rt, tt; // Attempt to fast-path if all anchors match if (leftAnchor.target == bottomAnchor.target && leftAnchor.target == rightAnchor.target && leftAnchor.target == topAnchor.target) { Vector3[] sides = leftAnchor.GetSides(parent); if (sides != null) { lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute; rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute; bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute; tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute; } else { // Anchored to a single transform Vector2 lp = GetLocalPos(leftAnchor, parent); lt = lp.x + leftAnchor.absolute; bt = lp.y + bottomAnchor.absolute; rt = lp.x + rightAnchor.absolute; tt = lp.y + topAnchor.absolute; } } else { // Left anchor point if (leftAnchor.target) { Vector3[] sides = leftAnchor.GetSides(parent); if (sides != null) { lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute; } else { lt = GetLocalPos(leftAnchor, parent).x + leftAnchor.absolute; } } else lt = mClipRange.x - 0.5f * size.x; // Right anchor point if (rightAnchor.target) { Vector3[] sides = rightAnchor.GetSides(parent); if (sides != null) { rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute; } else { rt = GetLocalPos(rightAnchor, parent).x + rightAnchor.absolute; } } else rt = mClipRange.x + 0.5f * size.x; // Bottom anchor point if (bottomAnchor.target) { Vector3[] sides = bottomAnchor.GetSides(parent); if (sides != null) { bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute; } else { bt = GetLocalPos(bottomAnchor, parent).y + bottomAnchor.absolute; } } else bt = mClipRange.y - 0.5f * size.y; // Top anchor point if (topAnchor.target) { Vector3[] sides = topAnchor.GetSides(parent); if (sides != null) { tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute; } else { tt = GetLocalPos(topAnchor, parent).y + topAnchor.absolute; } } else tt = mClipRange.y + 0.5f * size.y; } // Take the offset into consideration lt -= offset.x + mClipOffset.x; rt -= offset.x + mClipOffset.x; bt -= offset.y + mClipOffset.y; tt -= offset.y + mClipOffset.y; // Calculate the new position, width and height float newX = Mathf.Lerp(lt, rt, 0.5f); float newY = Mathf.Lerp(bt, tt, 0.5f); float w = rt - lt; float h = tt - bt; float minx = Mathf.Max(2f, mClipSoftness.x); float miny = Mathf.Max(2f, mClipSoftness.y); if (w < minx) w = minx; if (h < miny) h = miny; // Update the clipping range baseClipRegion = new Vector4(newX, newY, w, h); } static int mUpdateFrame = -1; /// <summary> /// Update all panels and draw calls. /// </summary> void LateUpdate () { #if UNITY_EDITOR if (mUpdateFrame != Time.frameCount || !Application.isPlaying) #else if (mUpdateFrame != Time.frameCount) #endif { mUpdateFrame = Time.frameCount; // Update each panel in order for (int i = 0, imax = list.Count; i < imax; ++i) list[i].UpdateSelf(); int rq = 3000; // Update all draw calls, making them draw in the right order for (int i = 0, imax = list.Count; i < imax; ++i) { UIPanel p = list[i]; if (p.renderQueue == RenderQueue.Automatic) { p.startingRenderQueue = rq; p.UpdateDrawCalls(); rq += p.drawCalls.Count; } else if (p.renderQueue == RenderQueue.StartAt) { p.UpdateDrawCalls(); if (p.drawCalls.Count != 0) rq = Mathf.Max(rq, p.startingRenderQueue + p.drawCalls.Count); } else // Explicit { p.UpdateDrawCalls(); if (p.drawCalls.Count != 0) rq = Mathf.Max(rq, p.startingRenderQueue + 1); } } } } /// <summary> /// Update the panel, all of its widgets and draw calls. /// </summary> void UpdateSelf () { mUpdateTime = RealTime.time; UpdateTransformMatrix(); UpdateLayers(); UpdateWidgets(); if (mRebuild) { mRebuild = false; FillAllDrawCalls(); } else { for (int i = 0; i < drawCalls.Count; ) { UIDrawCall dc = drawCalls[i]; if (dc.isDirty && !FillDrawCall(dc)) { UIDrawCall.Destroy(dc); drawCalls.RemoveAt(i); continue; } ++i; } } if (mUpdateScroll) { mUpdateScroll = false; UIScrollView sv = GetComponent<UIScrollView>(); if (sv != null) sv.UpdateScrollbars(); } } /// <summary> /// Immediately sort all child widgets. /// </summary> public void SortWidgets () { mSortWidgets = false; widgets.Sort(UIWidget.PanelCompareFunc); } /// <summary> /// Fill the geometry fully, processing all widgets and re-creating all draw calls. /// </summary> void FillAllDrawCalls () { for (int i = 0; i < drawCalls.Count; ++i) UIDrawCall.Destroy(drawCalls[i]); drawCalls.Clear(); Material mat = null; Texture tex = null; Shader sdr = null; UIDrawCall dc = null; int count = 0; if (mSortWidgets) SortWidgets(); for (int i = 0; i < widgets.Count; ++i) { UIWidget w = widgets[i]; if (w.isVisible && w.hasVertices) { Material mt = w.material; Texture tx = w.mainTexture; Shader sd = w.shader; if (mat != mt || tex != tx || sdr != sd) { if (dc != null && dc.verts.size != 0) { drawCalls.Add(dc); dc.UpdateGeometry(count); dc.onRender = mOnRender; mOnRender = null; count = 0; dc = null; } mat = mt; tex = tx; sdr = sd; } if (mat != null || sdr != null || tex != null) { if (dc == null) { dc = UIDrawCall.Create(this, mat, tex, sdr); dc.depthStart = w.depth; dc.depthEnd = dc.depthStart; dc.panel = this; } else { int rd = w.depth; if (rd < dc.depthStart) dc.depthStart = rd; if (rd > dc.depthEnd) dc.depthEnd = rd; } w.drawCall = dc; ++count; if (generateNormals) w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, dc.norms, dc.tans); else w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, null, null); if (w.mOnRender != null) { if (mOnRender == null) mOnRender = w.mOnRender; else mOnRender += w.mOnRender; } } } else w.drawCall = null; } if (dc != null && dc.verts.size != 0) { drawCalls.Add(dc); dc.UpdateGeometry(count); dc.onRender = mOnRender; mOnRender = null; } } UIDrawCall.OnRenderCallback mOnRender; /// <summary> /// Fill the geometry for the specified draw call. /// </summary> bool FillDrawCall (UIDrawCall dc) { if (dc != null) { dc.isDirty = false; int count = 0; for (int i = 0; i < widgets.Count; ) { UIWidget w = widgets[i]; if (w == null) { #if UNITY_EDITOR Debug.LogError("This should never happen"); #endif widgets.RemoveAt(i); continue; } if (w.drawCall == dc) { if (w.isVisible && w.hasVertices) { ++count; if (generateNormals) w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, dc.norms, dc.tans); else w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, null, null); if (w.mOnRender != null) { if (mOnRender == null) mOnRender = w.mOnRender; else mOnRender += w.mOnRender; } } else w.drawCall = null; } ++i; } if (dc.verts.size != 0) { dc.UpdateGeometry(count); dc.onRender = mOnRender; mOnRender = null; return true; } } return false; } /// <summary> /// Update all draw calls associated with the panel. /// </summary> void UpdateDrawCalls () { Transform trans = cachedTransform; bool isUI = usedForUI; if (clipping != UIDrawCall.Clipping.None) { drawCallClipRange = finalClipRegion; drawCallClipRange.z *= 0.5f; drawCallClipRange.w *= 0.5f; } else drawCallClipRange = Vector4.zero; // Legacy functionality if (drawCallClipRange.z == 0f) drawCallClipRange.z = Screen.width * 0.5f; if (drawCallClipRange.w == 0f) drawCallClipRange.w = Screen.height * 0.5f; // DirectX 9 half-pixel offset if (halfPixelOffset) { drawCallClipRange.x -= 0.5f; drawCallClipRange.y += 0.5f; } Vector3 pos; if (isUI) { Transform parent = cachedTransform.parent; pos = cachedTransform.localPosition; if (parent != null) pos = parent.TransformPoint(pos); pos += drawCallOffset; } else pos = trans.position; Quaternion rot = trans.rotation; Vector3 scale = trans.lossyScale; for (int i = 0; i < drawCalls.Count; ++i) { UIDrawCall dc = drawCalls[i]; Transform t = dc.cachedTransform; t.position = pos; t.rotation = rot; t.localScale = scale; dc.renderQueue = (renderQueue == RenderQueue.Explicit) ? startingRenderQueue : startingRenderQueue + i; dc.alwaysOnScreen = alwaysOnScreen && (mClipping == UIDrawCall.Clipping.None || mClipping == UIDrawCall.Clipping.ConstrainButDontClip); dc.sortingOrder = mSortingOrder; } } /// <summary> /// Update the widget layers if the panel's layer has changed. /// </summary> void UpdateLayers () { // Always move widgets to the panel's layer if (mLayer != cachedGameObject.layer) { mLayer = mGo.layer; NGUITools.SetChildLayer(cachedTransform, mLayer); ResetAnchors(); for (int i = 0; i < drawCalls.Count; ++i) drawCalls[i].gameObject.layer = mLayer; } } bool mForced = false; /// <summary> /// Update all of the widgets belonging to this panel. /// </summary> void UpdateWidgets() { #if UNITY_EDITOR bool forceVisible = cullWhileDragging ? false : (Application.isPlaying && mCullTime > mUpdateTime); #else bool forceVisible = cullWhileDragging ? false : (mCullTime > mUpdateTime); #endif bool changed = false; if (mForced != forceVisible) { mForced = forceVisible; mResized = true; } bool clipped = hasCumulativeClipping; // Update all widgets for (int i = 0, imax = widgets.Count; i < imax; ++i) { UIWidget w = widgets[i]; // If the widget is visible, update it if (w.panel == this && w.enabled) { #if UNITY_EDITOR // When an object is dragged from Project view to Scene view, its Z is... // odd, to say the least. Force it if possible. if (!Application.isPlaying) { Transform t = w.cachedTransform; if (t.hideFlags != HideFlags.HideInHierarchy) { t = (t.parent != null && t.parent.hideFlags == HideFlags.HideInHierarchy) ? t.parent : null; } if (t != null) { for (; ; ) { if (t.parent == null) break; if (t.parent.hideFlags == HideFlags.HideInHierarchy) t = t.parent; else break; } if (t != null) { Vector3 pos = t.localPosition; pos.x = Mathf.Round(pos.x); pos.y = Mathf.Round(pos.y); pos.z = 0f; if (Vector3.SqrMagnitude(t.localPosition - pos) > 0.0001f) t.localPosition = pos; } } } #endif int frame = Time.frameCount; // First update the widget's transform if (w.UpdateTransform(frame) || mResized) { // Only proceed to checking the widget's visibility if it actually moved bool vis = forceVisible || (w.CalculateCumulativeAlpha(frame) > 0.001f); w.UpdateVisibility(vis, forceVisible || ((clipped || w.hideIfOffScreen) ? IsVisible(w) : true)); } // Update the widget's geometry if necessary if (w.UpdateGeometry(frame)) { changed = true; if (!mRebuild) { if (w.drawCall != null) { w.drawCall.isDirty = true; } else { // Find an existing draw call, if possible FindDrawCall(w); } } } } } // Inform the changed event listeners if (changed && onGeometryUpdated != null) onGeometryUpdated(); mResized = false; } /// <summary> /// Insert the specified widget into one of the existing draw calls if possible. /// If it's not possible, and a new draw call is required, 'null' is returned /// because draw call creation is a delayed operation. /// </summary> public UIDrawCall FindDrawCall (UIWidget w) { Material mat = w.material; Texture tex = w.mainTexture; int depth = w.depth; for (int i = 0; i < drawCalls.Count; ++i) { UIDrawCall dc = drawCalls[i]; int dcStart = (i == 0) ? int.MinValue : drawCalls[i - 1].depthEnd + 1; int dcEnd = (i + 1 == drawCalls.Count) ? int.MaxValue : drawCalls[i + 1].depthStart - 1; if (dcStart <= depth && dcEnd >= depth) { if (dc.baseMaterial == mat && dc.mainTexture == tex) { if (w.isVisible) { w.drawCall = dc; if (w.hasVertices) dc.isDirty = true; return dc; } } else mRebuild = true; return null; } } mRebuild = true; return null; } /// <summary> /// Make the following widget be managed by the panel. /// </summary> public void AddWidget (UIWidget w) { mUpdateScroll = true; if (widgets.Count == 0) { widgets.Add(w); } else if (mSortWidgets) { widgets.Add(w); SortWidgets(); } else if (UIWidget.PanelCompareFunc(w, widgets[0]) == -1) { widgets.Insert(0, w); } else { for (int i = widgets.Count; i > 0; ) { if (UIWidget.PanelCompareFunc(w, widgets[--i]) == -1) continue; widgets.Insert(i+1, w); break; } } FindDrawCall(w); } /// <summary> /// Remove the widget from its current draw call, invalidating everything as needed. /// </summary> public void RemoveWidget (UIWidget w) { if (widgets.Remove(w) && w.drawCall != null) { int depth = w.depth; if (depth == w.drawCall.depthStart || depth == w.drawCall.depthEnd) mRebuild = true; w.drawCall.isDirty = true; w.drawCall = null; } } /// <summary> /// Immediately refresh the panel. /// </summary> public void Refresh () { mRebuild = true; mUpdateFrame = -1; if (list.Count > 0) list[0].LateUpdate(); } /// <summary> /// Calculate the offset needed to be constrained within the panel's bounds. /// </summary> public virtual Vector3 CalculateConstrainOffset (Vector2 min, Vector2 max) { Vector4 cr = finalClipRegion; float offsetX = cr.z * 0.5f; float offsetY = cr.w * 0.5f; Vector2 minRect = new Vector2(min.x, min.y); Vector2 maxRect = new Vector2(max.x, max.y); Vector2 minArea = new Vector2(cr.x - offsetX, cr.y - offsetY); Vector2 maxArea = new Vector2(cr.x + offsetX, cr.y + offsetY); if (softBorderPadding && clipping == UIDrawCall.Clipping.SoftClip) { minArea.x += mClipSoftness.x; minArea.y += mClipSoftness.y; maxArea.x -= mClipSoftness.x; maxArea.y -= mClipSoftness.y; } return NGUIMath.ConstrainRect(minRect, maxRect, minArea, maxArea); } /// <summary> /// Constrain the current target position to be within panel bounds. /// </summary> public bool ConstrainTargetToBounds (Transform target, ref Bounds targetBounds, bool immediate) { Vector3 offset = CalculateConstrainOffset(targetBounds.min, targetBounds.max); if (offset.sqrMagnitude > 0f) { if (immediate) { target.localPosition += offset; targetBounds.center += offset; SpringPosition sp = target.GetComponent<SpringPosition>(); if (sp != null) sp.enabled = false; } else { SpringPosition sp = SpringPosition.Begin(target.gameObject, target.localPosition + offset, 13f); sp.ignoreTimeScale = true; sp.worldSpace = false; } return true; } return false; } /// <summary> /// Constrain the specified target to be within the panel's bounds. /// </summary> public bool ConstrainTargetToBounds (Transform target, bool immediate) { Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(cachedTransform, target); return ConstrainTargetToBounds(target, ref bounds, immediate); } /// <summary> /// Find the UIPanel responsible for handling the specified transform. /// </summary> static public UIPanel Find (Transform trans) { return Find(trans, false, -1); } /// <summary> /// Find the UIPanel responsible for handling the specified transform. /// </summary> static public UIPanel Find (Transform trans, bool createIfMissing) { return Find(trans, createIfMissing, -1); } /// <summary> /// Find the UIPanel responsible for handling the specified transform. /// </summary> static public UIPanel Find (Transform trans, bool createIfMissing, int layer) { UIPanel panel = NGUITools.FindInParents<UIPanel>(trans); if (panel != null) return panel; return createIfMissing ? NGUITools.CreateUI(trans, false, layer) : null; } /// <summary> /// Get the size of the game window in pixels. /// </summary> Vector2 GetWindowSize () { UIRoot rt = root; Vector2 size = NGUITools.screenSize; if (rt != null) size *= rt.GetPixelSizeAdjustment(Mathf.RoundToInt(size.y)); return size; } /// <summary> /// Panel's size -- which is either the clipping rect, or the screen dimensions. /// </summary> public Vector2 GetViewSize () { if (mClipping != UIDrawCall.Clipping.None) return new Vector2(mClipRange.z, mClipRange.w); Vector2 size = NGUITools.screenSize; //UIRoot rt = root; //if (rt != null) size *= rt.pixelSizeAdjustment; return size; } #if UNITY_EDITOR /// <summary> /// Draw a visible pink outline for the clipped area. /// </summary> void OnDrawGizmos () { if (anchorCamera == null) return; bool clip = (mClipping != UIDrawCall.Clipping.None); Transform t = clip ? transform : mCam.transform; Vector3[] corners = worldCorners; for (int i = 0; i < 4; ++i) corners[i] = t.InverseTransformPoint(corners[i]); Vector3 pos = Vector3.Lerp(corners[0], corners[2], 0.5f); Vector3 size = corners[2] - corners[0]; GameObject go = UnityEditor.Selection.activeGameObject; bool isUsingThisPanel = (go != null) && (NGUITools.FindInParents<UIPanel>(go) == this); bool isSelected = (UnityEditor.Selection.activeGameObject == gameObject); bool detailedView = (isSelected && isUsingThisPanel); bool detailedClipped = detailedView && mClipping == UIDrawCall.Clipping.SoftClip; Gizmos.matrix = t.localToWorldMatrix; if (isUsingThisPanel && !clip && mCam.orthographic) { UIRoot rt = root; if (rt != null && rt.scalingStyle != UIRoot.Scaling.Flexible) { float width = rt.manualWidth; float height = rt.manualHeight; float x0 = -0.5f * width; float y0 = -0.5f * height; float x1 = x0 + width; float y1 = y0 + height; corners[0] = new Vector3(x0, y0); corners[1] = new Vector3(x0, y1); corners[2] = new Vector3(x1, y1); corners[3] = new Vector3(x1, y0); Vector3 szPos = Vector3.Lerp(corners[0], corners[2], 0.5f); Vector3 szSize = corners[2] - corners[0]; Gizmos.color = new Color(0f, 0.75f, 1f); Gizmos.DrawWireCube(szPos, szSize); } } Gizmos.color = (isUsingThisPanel && !detailedClipped) ? new Color(1f, 0f, 0.5f) : new Color(0.5f, 0f, 0.5f); Gizmos.DrawWireCube(pos, size); if (detailedView) { if (detailedClipped) { Gizmos.color = new Color(1f, 0f, 0.5f); size.x -= mClipSoftness.x * 2f; size.y -= mClipSoftness.y * 2f; Gizmos.DrawWireCube(pos, size); } } } #endif // UNITY_EDITOR }
{ "content_hash": "cf091390a9282d960a4013284302d866", "timestamp": "", "source": "github", "line_count": 1820, "max_line_length": 130, "avg_line_length": 23.90714285714286, "alnum_prop": 0.6417227827445933, "repo_name": "chrisjz/sm64vr", "id": "9b5d78b62e1ec8d1b8bbbb941a6367e6351a1abe", "size": "43695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/NGUI/Scripts/UI/UIPanel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2263456" }, { "name": "HLSL", "bytes": "7602" }, { "name": "JavaScript", "bytes": "216" }, { "name": "ShaderLab", "bytes": "58062" } ], "symlink_target": "" }
package sg.yikjiun.scf4j.map; import it.unimi.dsi.fastutil.longs.Long2ShortMap; /** * @author Lee Yik Jiun */ public class FastUtilLongShortMapAdapter implements LongShortMap { private final Long2ShortMap map; public FastUtilLongShortMapAdapter(Long2ShortMap map) { this.map = map; } public void clear() { map.clear(); } public boolean containsKey(long key) { return map.containsKey(key); } public boolean containsValue(short value) { return map.containsValue(value); } public short get(long key) { return map.get(key); } public boolean isEmpty() { return map.isEmpty(); } public short put(long key, short value) { return map.put(key, value); } public short remove(long key) { return map.remove(key); } public int size() { return map.size(); } }
{ "content_hash": "3ef7b68fe1f090596a0d636b88e1b53a", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 66, "avg_line_length": 18.916666666666668, "alnum_prop": 0.6167400881057269, "repo_name": "leeyikjiun/scf4j", "id": "7a4fbc5eea1faa4889ce47a3879ad33941250f2b", "size": "1503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scf4j-fastutil/src/main/java/sg/yikjiun/scf4j/map/FastUtilLongShortMapAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "618541" } ], "symlink_target": "" }
<?php namespace phpManufaktur\ConfirmationLog\Data\Setup; use phpManufaktur\ConfirmationLog\Data\Setup\Addons; class SetupTool { protected $app = null; /** * Install the Admin-Tool for the ConfirmationLog * * @throws \Exception */ protected function installTool() { $extension = $this->app['utils']->readJSON(MANUFAKTUR_PATH.'/ConfirmationLog/extension.json'); if (!isset($extension['name'])) { throw new \Exception('The extension.json does not contain the extension name!'); } if (!isset($extension['description']['en']['short'])) { throw new \Exception('Missing the short description for the extension in english language!'); } if (!isset($extension['release']['number'])) { throw new \Exception('Missing the release number of the extension!'); } if (!isset($extension['vendor'])) { throw new \Exception('Missing the vendor name of the extension!'); } if (!isset($extension['license'])) { throw new \Exception('Missing the license type for the extension!'); } try { // begin transaction $this->app['db']->beginTransaction(); $data = array( 'name' => $extension['name'], 'directory' => 'syncdata_'.strtolower(trim($extension['name'])), 'guid' => isset($extension['guid']) ? $extension['guid'] : '', 'description' => $extension['description']['en']['short'], 'version' => $extension['release']['number'], 'author' => $extension['vendor'], 'license' => $extension['license'], 'platform' => (CMS_TYPE == 'WebsiteBaker') ? '2.8.x' : '1.x', 'type' => 'module', 'function' => 'tool', ); if (CMS_TYPE == 'WebsiteBaker') { unset($data['guid']); } $addon = new Addons($this->app); // check for the first version ... if (false !== ($check = $addon->existsDirectory('kit_framework_confirmationlog'))) { $check = $addon->select('kit_framework_confirmationlog'); if (($check['version'] == '0.10') ||($check['version'] == '0.11')) { // this was the "alpha" of the ConfirmationLog, remove it and install the new one $addon->delete('kit_framework_confirmationlog'); $this->app['utils']->rrmdir(CMS_PATH.'/modules/kit_framework_confirmationlog'); $this->app['monolog']->addInfo('Removed "alpha" version of the ConfirmationLog, previous installed by SyncData.', array(__METHOD__, __LINE__)); } else { // using the kitFramework - no need to install the tool twice! $this->app['db']->commit(); $message = 'The ConfirmationLog is already installed by the kitFramework, installation cancelled.'; $this->app['monolog']->addInfo($message, array(__METHOD__, __LINE__)); return $this->app['translator']->trans($message); } } if ($addon->existsDirectory($data['directory'])) { // update the existing record $addon->update($data['directory'], $data); } else { // insert a new record $addon->insert($data); } if (CMS_TYPE == 'WebsiteBaker') { $data['guid'] = isset($extension['guid']) ? $extension['guid'] : ''; } $data['css_url'] = CMS_URL.'/syncdata/vendor/phpManufaktur/ConfirmationLog/Template/default/backend/css/syncdata.backend.css'; if (!file_exists(CMS_PATH.'/modules/'.$data['directory']) && !@mkdir(CMS_PATH.'/modules/'.$data['directory'])) { throw new \Exception("Can't create the directory ".CMS_PATH.'/modules/'.$data['directory']); } $search = array(); $replace = array(); foreach ($data as $key => $value) { $search[] = sprintf('{%s}', strtoupper($key)); $replace[] = $value; } // generate files $files = array('index.php', 'info.php', 'tool.php', 'install.php', 'uninstall.php', 'backend.css'); foreach ($files as $file) { // loop through the files, replace content and write them to the desired /modules directory if (file_exists(MANUFAKTUR_PATH."/ConfirmationLog/Template/default/cms/setup/websitebaker/{$file}.htt")) { $content = file_get_contents(MANUFAKTUR_PATH."/ConfirmationLog/Template/default/cms/setup/websitebaker/{$file}.htt"); file_put_contents(CMS_PATH.'/modules/'.$data['directory'].'/'.$file, str_ireplace($search, $replace, $content)); } } if (file_exists(MANUFAKTUR_PATH."/ConfirmationLog/Template/default/cms/setup/websitebaker/language.htt")) { $content = file_get_contents(MANUFAKTUR_PATH."/ConfirmationLog/Template/default/cms/setup/websitebaker/language.htt"); // create a language directory if (!file_exists(CMS_PATH.'/modules/'.$data['directory'].'/languages') && !@mkdir(CMS_PATH.'/modules/'.$data['directory'].'/languages', 0777, true)) { throw new \Exception("Can't create the directory ".CMS_PATH.'/modules/'.$data['directory'].'/languages'); } // loop through the languages available in the extension.json and create module descriptions for the CMS foreach ($extension['description'] as $lang => $lang_array) { $lang_search = array('{NAME}', '{AUTHOR}', '{DESCRIPTION}'); $lang_replace = array($data['name'], $data['author'], $lang_array['short']); file_put_contents(CMS_PATH.'/modules/'.$data['directory'].'/languages/'.strtoupper($lang).'.php', str_ireplace($lang_search, $lang_replace, $content)); } } // commit the transaction $this->app['db']->commit(); // install the droplet for the fronten usage of the reports $Droplet = new Droplet($this->app); $Droplet->setDropletInfo( 'syncdata_confirmation_report', MANUFAKTUR_PATH.'/ConfirmationLog/Data/Setup/Droplet/syncdata_confirmation_report.php', 'Show reports to the confirmations in the frontend', 'Please visit https://addons.phpmanufaktur.de/syncdata' ); // install the droplet $Droplet->install(); // return the result $message = 'The admin-tool for the ConfirmationLog has successfull installed.'; $this->app['monolog']->addInfo($message, array(__METHOD__, __LINE__)); return $this->app['translator']->trans($message); } catch (\Exception $e) { // roolback the transaction $this->app['db']->rollback(); throw new \Exception($e); } } /** * Execute the installation * * @param Application $app */ public function exec($app) { $this->app = $app; return $this->installTool(); } }
{ "content_hash": "75a557618cbd46c9cb945fd95c21bb49", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 138, "avg_line_length": 44.77514792899408, "alnum_prop": 0.5290075327078102, "repo_name": "phpManufaktur/kfConfirmationLog", "id": "5ad8596e971754a2f9d425a06d5eec6a2ab310e3", "size": "7838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Data/Setup/SetupTool.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8239" }, { "name": "PHP", "bytes": "145687" } ], "symlink_target": "" }
module WhereIn1 where --A definition can be removed if it is not used by other declarations. --Where a definition is removed, it's type signature should also be removed. --In this Example: remove defintion 'main' fac,fib :: Int -> Int fac 0 = 1 fac 1 = 1 fac n = n * fac (n-1) fib 0 = 1 fib 1 = 1 fib n = (fib (n-1)) + (fib (n-2)) --This comment will not be removed.
{ "content_hash": "9c335c70b2ce67a3c4f198af6f063c80", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 76, "avg_line_length": 20.72222222222222, "alnum_prop": 0.6675603217158177, "repo_name": "RefactoringTools/HaRe", "id": "32d6a9cfb3a95195b8a3aace1443ac3a3077edfc", "size": "373", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "old/testing/removeDef/WhereIn1_TokOut.hs", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7740" }, { "name": "Emacs Lisp", "bytes": "118898" }, { "name": "HTML", "bytes": "231247" }, { "name": "Haskell", "bytes": "6486673" }, { "name": "Isabelle", "bytes": "5201" }, { "name": "LLVM", "bytes": "384" }, { "name": "Makefile", "bytes": "18020" }, { "name": "Objective-C++", "bytes": "404" }, { "name": "Roff", "bytes": "107" }, { "name": "Ruby", "bytes": "4178" }, { "name": "Shell", "bytes": "67129" }, { "name": "TeX", "bytes": "334772" }, { "name": "Vim script", "bytes": "35502" }, { "name": "Yacc", "bytes": "120163" } ], "symlink_target": "" }
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2007-2009 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// // // The option that yields to non-floating point 1/sqrt(2) alpha is taken // from the scapegoat tree implementation of the PSPP library. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_SGTREE_HPP #define BOOST_INTRUSIVE_SGTREE_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <algorithm> #include <cstddef> #include <functional> #include <iterator> #include <utility> #include <cmath> #include <cstddef> #include <boost/intrusive/detail/assert.hpp> #include <boost/static_assert.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/bs_set_hook.hpp> #include <boost/intrusive/detail/tree_node.hpp> #include <boost/intrusive/detail/ebo_functor_holder.hpp> #include <boost/intrusive/detail/pointer_to_other.hpp> #include <boost/intrusive/detail/clear_on_destructor_base.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <boost/intrusive/options.hpp> #include <boost/intrusive/sgtree_algorithms.hpp> #include <boost/intrusive/link_mode.hpp> namespace boost { namespace intrusive { /// @cond namespace detail{ //! Returns floor(log(n)/log(sqrt(2))) -> floor(2*log2(n)) //! Undefined if N is 0. //! //! This function does not use float point operations. inline std::size_t calculate_h_sqrt2 (std::size_t n) { std::size_t f_log2 = detail::floor_log2(n); return (2*f_log2) + (n >= detail::sqrt2_pow_2xplus1 (f_log2)); } struct h_alpha_sqrt2_t { h_alpha_sqrt2_t(void){} std::size_t operator()(std::size_t n) const { return calculate_h_sqrt2(n); } }; struct alpha_0_75_by_max_size_t { alpha_0_75_by_max_size_t(void){} std::size_t operator()(std::size_t max_tree_size) const { const std::size_t max_tree_size_limit = ((~std::size_t(0))/std::size_t(3)); return max_tree_size > max_tree_size_limit ? max_tree_size/4*3 : max_tree_size*3/4; } }; struct h_alpha_t { h_alpha_t(float inv_minus_logalpha) : inv_minus_logalpha_(inv_minus_logalpha) {} std::size_t operator()(std::size_t n) const { //Returns floor(log1/alpha(n)) -> // floor(log(n)/log(1/alpha)) -> // floor(log(n)/(-log(alpha))) //return static_cast<std::size_t>(std::log(float(n))*inv_minus_logalpha_); return static_cast<std::size_t>(detail::fast_log2(float(n))*inv_minus_logalpha_); } private: //Since the function will be repeatedly called //precalculate constant data to avoid repeated //calls to log and division. //This will store 1/(-std::log(alpha_)) float inv_minus_logalpha_; }; struct alpha_by_max_size_t { alpha_by_max_size_t(float alpha) : alpha_(alpha) {} float operator()(std::size_t max_tree_size) const { return float(max_tree_size)*alpha_; } private: float alpha_; float inv_minus_logalpha_; }; template<bool Activate> struct alpha_holder { typedef boost::intrusive::detail::h_alpha_t h_alpha_t; typedef boost::intrusive::detail::alpha_by_max_size_t multiply_by_alpha_t; alpha_holder() { set_alpha(0.7f); } float get_alpha() const { return alpha_; } void set_alpha(float alpha) { alpha_ = alpha; inv_minus_logalpha_ = 1/(-detail::fast_log2(alpha)); } h_alpha_t get_h_alpha_t() const { return h_alpha_t(inv_minus_logalpha_); } multiply_by_alpha_t get_multiply_by_alpha_t() const { return multiply_by_alpha_t(alpha_); } private: float alpha_; float inv_minus_logalpha_; }; template<> struct alpha_holder<false> { //This specialization uses alpha = 1/sqrt(2) //without using floating point operations //Downside: alpha CAN't be changed. typedef boost::intrusive::detail::h_alpha_sqrt2_t h_alpha_t; typedef boost::intrusive::detail::alpha_0_75_by_max_size_t multiply_by_alpha_t; float get_alpha() const { return 0.70710677f; } void set_alpha(float) { //alpha CAN't be changed. BOOST_INTRUSIVE_INVARIANT_ASSERT(0); } h_alpha_t get_h_alpha_t() const { return h_alpha_t(); } multiply_by_alpha_t get_multiply_by_alpha_t() const { return multiply_by_alpha_t(); } }; } //namespace detail{ template <class ValueTraits, class Compare, class SizeType, bool FloatingPoint> struct sg_setopt { typedef ValueTraits value_traits; typedef Compare compare; typedef SizeType size_type; static const bool floating_point = FloatingPoint; }; template <class T> struct sg_set_defaults : pack_options < none , base_hook<detail::default_bs_set_hook> , floating_point<true> , size_type<std::size_t> , compare<std::less<T> > >::type {}; /// @endcond //! The class template sgtree is an intrusive scapegoat tree container, that //! is used to construct intrusive sg_set and sg_multiset containers. //! The no-throw guarantee holds only, if the value_compare object //! doesn't throw. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c floating_point<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif class sgtree_impl : private detail::clear_on_destructor_base<sgtree_impl<Config> > { template<class C> friend class detail::clear_on_destructor_base; public: typedef typename Config::value_traits value_traits; /// @cond static const bool external_value_traits = detail::external_value_traits_is_true<value_traits>::value; typedef typename detail::eval_if_c < external_value_traits , detail::eval_value_traits<value_traits> , detail::identity<value_traits> >::type real_value_traits; /// @endcond typedef typename real_value_traits::pointer pointer; typedef typename real_value_traits::const_pointer const_pointer; typedef typename std::iterator_traits<pointer>::value_type value_type; typedef value_type key_type; typedef typename std::iterator_traits<pointer>::reference reference; typedef typename std::iterator_traits<const_pointer>::reference const_reference; typedef typename std::iterator_traits<pointer>::difference_type difference_type; typedef typename Config::size_type size_type; typedef typename Config::compare value_compare; typedef value_compare key_compare; typedef tree_iterator<sgtree_impl, false> iterator; typedef tree_iterator<sgtree_impl, true> const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef typename real_value_traits::node_traits node_traits; typedef typename node_traits::node node; typedef typename boost::pointer_to_other <pointer, node>::type node_ptr; typedef typename boost::pointer_to_other <node_ptr, const node>::type const_node_ptr; typedef sgtree_algorithms<node_traits> node_algorithms; static const bool floating_point = Config::floating_point; static const bool constant_time_size = true; static const bool stateful_value_traits = detail::is_stateful_value_traits<real_value_traits>::value; /// @cond private: typedef detail::size_holder<true, size_type> size_traits; typedef detail::alpha_holder<floating_point> alpha_traits; typedef typename alpha_traits::h_alpha_t h_alpha_t; typedef typename alpha_traits::multiply_by_alpha_t multiply_by_alpha_t; //noncopyable sgtree_impl (const sgtree_impl&); sgtree_impl operator =(const sgtree_impl&); enum { safemode_or_autounlink = (int)real_value_traits::link_mode == (int)auto_unlink || (int)real_value_traits::link_mode == (int)safe_link }; BOOST_STATIC_ASSERT(((int)real_value_traits::link_mode != (int)auto_unlink)); //BOOST_STATIC_ASSERT(( // (int)real_value_traits::link_mode != (int)auto_unlink || // !floating_point // )); struct header_plus_alpha : public alpha_traits { node header_; }; struct node_plus_pred_t : public detail::ebo_functor_holder<value_compare> { node_plus_pred_t(const value_compare &comp) : detail::ebo_functor_holder<value_compare>(comp) {} header_plus_alpha header_plus_alpha_; size_traits size_traits_; }; struct data_t : public sgtree_impl::value_traits { typedef typename sgtree_impl::value_traits value_traits; data_t(const value_compare & comp, const value_traits &val_traits) : value_traits(val_traits), node_plus_pred_(comp) , max_tree_size_(0) {} node_plus_pred_t node_plus_pred_; size_type max_tree_size_; } data_; float priv_alpha() const { return this->priv_alpha_traits().get_alpha(); } void priv_alpha(float alpha) { return this->priv_alpha_traits().set_alpha(alpha); } const value_compare &priv_comp() const { return data_.node_plus_pred_.get(); } value_compare &priv_comp() { return data_.node_plus_pred_.get(); } const node &priv_header() const { return data_.node_plus_pred_.header_plus_alpha_.header_; } node &priv_header() { return data_.node_plus_pred_.header_plus_alpha_.header_; } static node_ptr uncast(const_node_ptr ptr) { return node_ptr(const_cast<node*>(detail::boost_intrusive_get_pointer(ptr))); } size_traits &priv_size_traits() { return data_.node_plus_pred_.size_traits_; } const size_traits &priv_size_traits() const { return data_.node_plus_pred_.size_traits_; } alpha_traits &priv_alpha_traits() { return data_.node_plus_pred_.header_plus_alpha_; } const alpha_traits &priv_alpha_traits() const { return data_.node_plus_pred_.header_plus_alpha_; } const real_value_traits &get_real_value_traits(detail::bool_<false>) const { return data_; } const real_value_traits &get_real_value_traits(detail::bool_<true>) const { return data_.get_value_traits(*this); } real_value_traits &get_real_value_traits(detail::bool_<false>) { return data_; } real_value_traits &get_real_value_traits(detail::bool_<true>) { return data_.get_value_traits(*this); } h_alpha_t get_h_alpha_func() const { return priv_alpha_traits().get_h_alpha_t(); } multiply_by_alpha_t get_alpha_by_max_size_func() const { return priv_alpha_traits().get_multiply_by_alpha_t(); } /// @endcond public: const real_value_traits &get_real_value_traits() const { return this->get_real_value_traits(detail::bool_<external_value_traits>()); } real_value_traits &get_real_value_traits() { return this->get_real_value_traits(detail::bool_<external_value_traits>()); } typedef typename node_algorithms::insert_commit_data insert_commit_data; //! <b>Effects</b>: Constructs an empty tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructorof the value_compare object throws. Basic guarantee. sgtree_impl( const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : data_(cmp, v_traits) { node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(size_type(0)); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue of type value_type. //! cmp must be a comparison function that induces a strict weak ordering. //! //! <b>Effects</b>: Constructs an empty tree and inserts elements from //! [b, e). //! //! <b>Complexity</b>: Linear in N if [b, e) is already sorted using //! comp and otherwise N * log N, where N is the distance between first and last. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor/operator() of the value_compare object throws. Basic guarantee. template<class Iterator> sgtree_impl( bool unique, Iterator b, Iterator e , const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : data_(cmp, v_traits) { node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(size_type(0)); if(unique) this->insert_unique(b, e); else this->insert_equal(b, e); } //! <b>Effects</b>: Detaches all elements from this. The objects in the set //! are not deleted (i.e. no destructors are called), but the nodes according to //! the value_traits template parameter are reinitialized and thus can be reused. //! //! <b>Complexity</b>: Linear to elements contained in *this. //! //! <b>Throws</b>: Nothing. ~sgtree_impl() {} //! <b>Effects</b>: Returns an iterator pointing to the beginning of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator begin() { return iterator (node_traits::get_left(node_ptr(&priv_header())), this); } //! <b>Effects</b>: Returns a const_iterator pointing to the beginning of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator begin() const { return cbegin(); } //! <b>Effects</b>: Returns a const_iterator pointing to the beginning of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator cbegin() const { return const_iterator (node_traits::get_left(const_node_ptr(&priv_header())), this); } //! <b>Effects</b>: Returns an iterator pointing to the end of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator end() { return iterator (node_ptr(&priv_header()), this); } //! <b>Effects</b>: Returns a const_iterator pointing to the end of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator end() const { return cend(); } //! <b>Effects</b>: Returns a const_iterator pointing to the end of the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator cend() const { return const_iterator (uncast(const_node_ptr(&priv_header())), this); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning of the //! reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. reverse_iterator rbegin() { return reverse_iterator(end()); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the end //! of the reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. reverse_iterator rend() { return reverse_iterator(begin()); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } //! <b>Precondition</b>: end_iterator must be a valid end iterator //! of sgtree. //! //! <b>Effects</b>: Returns a const reference to the sgtree associated to the end iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. static sgtree_impl &container_from_end_iterator(iterator end_iterator) { return priv_container_from_end_iterator(end_iterator); } //! <b>Precondition</b>: end_iterator must be a valid end const_iterator //! of sgtree. //! //! <b>Effects</b>: Returns a const reference to the sgtree associated to the end iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. static const sgtree_impl &container_from_end_iterator(const_iterator end_iterator) { return priv_container_from_end_iterator(end_iterator); } //! <b>Precondition</b>: it must be a valid iterator //! of rbtree. //! //! <b>Effects</b>: Returns a const reference to the tree associated to the iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Logarithmic. static sgtree_impl &container_from_iterator(iterator it) { return priv_container_from_iterator(it); } //! <b>Precondition</b>: it must be a valid end const_iterator //! of rbtree. //! //! <b>Effects</b>: Returns a const reference to the tree associated to the iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Logarithmic. static const sgtree_impl &container_from_iterator(const_iterator it) { return priv_container_from_iterator(it); } //! <b>Effects</b>: Returns the value_compare object used by the tree. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_compare copy-constructor throws. value_compare value_comp() const { return priv_comp(); } //! <b>Effects</b>: Returns true if the container is empty. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. bool empty() const { return node_algorithms::unique(const_node_ptr(&priv_header())); } //! <b>Effects</b>: Returns the number of elements stored in the tree. //! //! <b>Complexity</b>: Linear to elements contained in *this //! if constant-time size option is disabled. Constant time otherwise. //! //! <b>Throws</b>: Nothing. size_type size() const { if(constant_time_size) return this->priv_size_traits().get_size(); else{ return (size_type)node_algorithms::size(const_node_ptr(&priv_header())); } } //! <b>Effects</b>: Swaps the contents of two sgtrees. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the comparison functor's swap call throws. void swap(sgtree_impl& other) { //This can throw using std::swap; swap(priv_comp(), priv_comp()); swap(priv_alpha_traits(), priv_alpha_traits()); swap(data_.max_tree_size_, other.data_.max_tree_size_); //These can't throw node_algorithms::swap_tree(node_ptr(&priv_header()), node_ptr(&other.priv_header())); if(constant_time_size){ size_type backup = this->priv_size_traits().get_size(); this->priv_size_traits().set_size(other.priv_size_traits().get_size()); other.priv_size_traits().set_size(backup); } } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Inserts value into the tree before the upper bound. //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: If the internal value_compare ordering function throws. Strong guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(reference value) { detail::key_nodeptr_comp<value_compare, sgtree_impl> key_node_comp(priv_comp(), this); node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_ptr p = node_algorithms::insert_equal_upper_bound (node_ptr(&priv_header()), to_insert, key_node_comp , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; return iterator(p, this); } //! <b>Requires</b>: value must be an lvalue, and "hint" must be //! a valid iterator. //! //! <b>Effects</b>: Inserts x into the tree, using "hint" as a hint to //! where it will be inserted. If "hint" is the upper_bound //! the insertion takes constant time (two comparisons in the worst case) //! //! <b>Complexity</b>: Logarithmic in general, but it is amortized //! constant time if t is inserted immediately before hint. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(const_iterator hint, reference value) { detail::key_nodeptr_comp<value_compare, sgtree_impl> key_node_comp(priv_comp(), this); node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_ptr p = node_algorithms::insert_equal (node_ptr(&priv_header()), hint.pointed_node(), to_insert, key_node_comp , (std::size_t)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; return iterator(p, this); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Inserts a each element of a range into the tree //! before the upper bound of the key of each element. //! //! <b>Complexity</b>: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_equal(Iterator b, Iterator e) { iterator end(this->end()); for (; b != e; ++b) this->insert_equal(end, *b); } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Inserts value into the tree if the value //! is not already present. //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. std::pair<iterator, bool> insert_unique(reference value) { insert_commit_data commit_data; std::pair<iterator, bool> ret = insert_unique_check(value, priv_comp(), commit_data); if(!ret.second) return ret; return std::pair<iterator, bool> (insert_unique_commit(value, commit_data), true); } //! <b>Requires</b>: value must be an lvalue, and "hint" must be //! a valid iterator //! //! <b>Effects</b>: Tries to insert x into the tree, using "hint" as a hint //! to where it will be inserted. //! //! <b>Complexity</b>: Logarithmic in general, but it is amortized //! constant time (two comparisons in the worst case) //! if t is inserted immediately before hint. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_unique(const_iterator hint, reference value) { insert_commit_data commit_data; std::pair<iterator, bool> ret = insert_unique_check(hint, value, priv_comp(), commit_data); if(!ret.second) return ret.first; return insert_unique_commit(value, commit_data); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Tries to insert each element of a range into the tree. //! //! <b>Complexity</b>: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_unique(Iterator b, Iterator e) { if(this->empty()){ iterator end(this->end()); for (; b != e; ++b) this->insert_unique(end, *b); } else{ for (; b != e; ++b) this->insert_unique(*b); } } //! <b>Requires</b>: key_value_comp must be a comparison function that induces //! the same strict weak ordering as value_compare. The difference is that //! key_value_comp compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Average complexity is at most logarithmic. //! //! <b>Throws</b>: If the key_value_comp ordering function throws. Strong guarantee. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that //! part to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! "insert_commit" to insert the object in constant-time. This gives a total //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_commit" only if no more //! objects are inserted or erased from the container. template<class KeyType, class KeyValueCompare> std::pair<iterator, bool> insert_unique_check (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> comp(key_value_comp, this); std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (node_ptr(&priv_header()), key, comp, commit_data)); return std::pair<iterator, bool>(iterator(ret.first, this), ret.second); } //! <b>Requires</b>: key_value_comp must be a comparison function that induces //! the same strict weak ordering as value_compare. The difference is that //! key_value_comp compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself, using "hint" //! as a hint to where it will be inserted. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Logarithmic in general, but it's amortized //! constant time if t is inserted immediately before hint. //! //! <b>Throws</b>: If the key_value_comp ordering function throws. Strong guarantee. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! constructing that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that key //! to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! "insert_commit" to insert the object in constant-time. This can give a total //! constant-time complexity to the insertion: check(O(1)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_commit" only if no more //! objects are inserted or erased from the container. template<class KeyType, class KeyValueCompare> std::pair<iterator, bool> insert_unique_check (const_iterator hint, const KeyType &key ,KeyValueCompare key_value_comp, insert_commit_data &commit_data) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> comp(key_value_comp, this); std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (node_ptr(&priv_header()), hint.pointed_node(), key, comp, commit_data)); return std::pair<iterator, bool>(iterator(ret.first, this), ret.second); } //! <b>Requires</b>: value must be an lvalue of type value_type. commit_data //! must have been obtained from a previous call to "insert_check". //! No objects should have been inserted or erased from the container between //! the "insert_check" that filled "commit_data" and the call to "insert_commit". //! //! <b>Effects</b>: Inserts the value in the avl_set using the information obtained //! from the "commit_data" that a previous "insert_check" filled. //! //! <b>Returns</b>: An iterator to the newly inserted object. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function has only sense if a "insert_check" has been //! previously executed to fill "commit_data". No value should be inserted or //! erased between the "insert_check" and "insert_commit" calls. iterator insert_unique_commit(reference value, const insert_commit_data &commit_data) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_algorithms::insert_unique_commit ( node_ptr(&priv_header()), to_insert, commit_data , (std::size_t)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; return iterator(to_insert, this); } //! <b>Requires</b>: value must be an lvalue, "pos" must be //! a valid iterator (or end) and must be the succesor of value //! once inserted according to the predicate //! //! <b>Effects</b>: Inserts x into the tree before "pos". //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if "pos" is not //! the successor of "value" tree ordering invariant will be broken. //! This is a low-level function to be used only for performance reasons //! by advanced users. iterator insert_before(const_iterator pos, reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_ptr p = node_algorithms::insert_before ( node_ptr(&priv_header()), pos.pointed_node(), to_insert , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; return iterator(p, this); } //! <b>Requires</b>: value must be an lvalue, and it must be no less //! than the greatest inserted key //! //! <b>Effects</b>: Inserts x into the tree in the last position. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if value is //! less than the greatest inserted key tree ordering invariant will be broken. //! This function is slightly more efficient than using "insert_before". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_back(reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_algorithms::push_back ( node_ptr(&priv_header()), to_insert , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; } //! <b>Requires</b>: value must be an lvalue, and it must be no greater //! than the minimum inserted key //! //! <b>Effects</b>: Inserts x into the tree in the first position. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if value is //! greater than the minimum inserted key tree ordering invariant will be broken. //! This function is slightly more efficient than using "insert_before". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_front(reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); std::size_t max_tree_size = (std::size_t)data_.max_tree_size_; node_algorithms::push_front ( node_ptr(&priv_header()), to_insert , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size); this->priv_size_traits().increment(); data_.max_tree_size_ = (size_type)max_tree_size; } //! <b>Effects</b>: Erases the element pointed to by pos. //! //! <b>Complexity</b>: Average complexity for erase element is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator i) { const_iterator ret(i); ++ret; node_ptr to_erase(i.pointed_node()); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!node_algorithms::unique(to_erase)); std::size_t max_tree_size = data_.max_tree_size_; node_algorithms::erase ( &priv_header(), to_erase, (std::size_t)this->size() , max_tree_size, this->get_alpha_by_max_size_func()); data_.max_tree_size_ = (size_type)max_tree_size; this->priv_size_traits().decrement(); if(safemode_or_autounlink) node_algorithms::init(to_erase); return ret.unconst(); } //! <b>Effects</b>: Erases the range pointed to by b end e. //! //! <b>Complexity</b>: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator b, const_iterator e) { size_type n; return private_erase(b, e, n); } //! <b>Effects</b>: Erases all the elements with the given value. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. size_type erase(const_reference value) { return this->erase(value, priv_comp()); } //! <b>Effects</b>: Erases all the elements with the given key. //! according to the comparison functor "comp". //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class KeyType, class KeyValueCompare> size_type erase(const KeyType& key, KeyValueCompare comp /// @cond , typename detail::enable_if_c<!detail::is_convertible<KeyValueCompare, const_iterator>::value >::type * = 0 /// @endcond ) { std::pair<iterator,iterator> p = this->equal_range(key, comp); size_type n; private_erase(p.first, p.second, n); return n; } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the element pointed to by pos. //! Disposer::operator()(pointer) is called for the removed element. //! //! <b>Complexity</b>: Average complexity for erase element is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer) { node_ptr to_erase(i.pointed_node()); iterator ret(this->erase(i)); disposer(get_real_value_traits().to_value_ptr(to_erase)); return ret; } #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class Disposer> iterator erase_and_dispose(iterator i, Disposer disposer) { return this->erase_and_dispose(const_iterator(i), disposer); } #endif //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the range pointed to by b end e. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Complexity</b>: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) { size_type n; return private_erase(b, e, n, disposer); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given value. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class Disposer> size_type erase_and_dispose(const_reference value, Disposer disposer) { std::pair<iterator,iterator> p = this->equal_range(value); size_type n; private_erase(p.first, p.second, n, disposer); return n; } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given key. //! according to the comparison functor "comp". //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class KeyType, class KeyValueCompare, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer /// @cond , typename detail::enable_if_c<!detail::is_convertible<KeyValueCompare, const_iterator>::value >::type * = 0 /// @endcond ) { std::pair<iterator,iterator> p = this->equal_range(key, comp); size_type n; private_erase(p.first, p.second, n, disposer); return n; } //! <b>Effects</b>: Erases all of the elements. //! //! <b>Complexity</b>: Linear to the number of elements on the container. //! if it's a safe-mode or auto-unlink value_type. Constant time otherwise. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. void clear() { if(safemode_or_autounlink){ this->clear_and_dispose(detail::null_disposer()); } else{ node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(0); } } //! <b>Effects</b>: Erases all of the elements calling disposer(p) for //! each node to be erased. //! <b>Complexity</b>: Average complexity for is at most O(log(size() + N)), //! where N is the number of elements in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. Calls N times to disposer functor. template<class Disposer> void clear_and_dispose(Disposer disposer) { node_algorithms::clear_and_dispose(node_ptr(&priv_header()) , detail::node_disposer<Disposer, sgtree_impl>(disposer, this)); this->priv_size_traits().set_size(0); } //! <b>Effects</b>: Returns the number of contained elements with the given value //! //! <b>Complexity</b>: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given value. //! //! <b>Throws</b>: Nothing. size_type count(const_reference value) const { return this->count(value, priv_comp()); } //! <b>Effects</b>: Returns the number of contained elements with the given key //! //! <b>Complexity</b>: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given key. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> size_type count(const KeyType &key, KeyValueCompare comp) const { std::pair<const_iterator, const_iterator> ret = this->equal_range(key, comp); return std::distance(ret.first, ret.second); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. iterator lower_bound(const_reference value) { return this->lower_bound(value, priv_comp()); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. const_iterator lower_bound(const_reference value) const { return this->lower_bound(value, priv_comp()); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> iterator lower_bound(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return iterator(node_algorithms::lower_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Returns a const iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> const_iterator lower_bound(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return const_iterator(node_algorithms::lower_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. iterator upper_bound(const_reference value) { return this->upper_bound(value, priv_comp()); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k according to comp or end() if that element //! does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> iterator upper_bound(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return iterator(node_algorithms::upper_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. const_iterator upper_bound(const_reference value) const { return this->upper_bound(value, priv_comp()); } //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k according to comp or end() if that element //! does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> const_iterator upper_bound(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return const_iterator(node_algorithms::upper_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. iterator find(const_reference value) { return this->find(value, priv_comp()); } //! <b>Effects</b>: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> iterator find(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return iterator (node_algorithms::find(const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Finds a const_iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. const_iterator find(const_reference value) const { return this->find(value, priv_comp()); } //! <b>Effects</b>: Finds a const_iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> const_iterator find(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); return const_iterator (node_algorithms::find(const_node_ptr(&priv_header()), key, key_node_comp), this); } //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. std::pair<iterator,iterator> equal_range(const_reference value) { return this->equal_range(value, priv_comp()); } //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> std::pair<iterator,iterator> equal_range(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); std::pair<node_ptr, node_ptr> ret (node_algorithms::equal_range(const_node_ptr(&priv_header()), key, key_node_comp)); return std::pair<iterator, iterator>(iterator(ret.first, this), iterator(ret.second, this)); } //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. std::pair<const_iterator, const_iterator> equal_range(const_reference value) const { return this->equal_range(value, priv_comp()); } //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: Nothing. template<class KeyType, class KeyValueCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp<KeyValueCompare, sgtree_impl> key_node_comp(comp, this); std::pair<node_ptr, node_ptr> ret (node_algorithms::equal_range(const_node_ptr(&priv_header()), key, key_node_comp)); return std::pair<const_iterator, const_iterator>(const_iterator(ret.first, this), const_iterator(ret.second, this)); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! Cloner should yield to nodes equivalent to the original nodes. //! //! <b>Effects</b>: Erases all the elements from *this //! calling Disposer::operator()(pointer), clones all the //! elements from src calling Cloner::operator()(const_reference ) //! and inserts them on *this. Copies the predicate from the source container. //! //! If cloner throws, all cloned elements are unlinked and disposed //! calling Disposer::operator()(pointer). //! //! <b>Complexity</b>: Linear to erased plus inserted elements. //! //! <b>Throws</b>: If cloner throws or predicate copy assignment throws. Basic guarantee. template <class Cloner, class Disposer> void clone_from(const sgtree_impl &src, Cloner cloner, Disposer disposer) { this->clear_and_dispose(disposer); if(!src.empty()){ detail::exception_disposer<sgtree_impl, Disposer> rollback(*this, disposer); node_algorithms::clone (const_node_ptr(&src.priv_header()) ,node_ptr(&this->priv_header()) ,detail::node_cloner<Cloner, sgtree_impl>(cloner, this) ,detail::node_disposer<Disposer, sgtree_impl>(disposer, this)); this->priv_size_traits().set_size(src.priv_size_traits().get_size()); this->priv_comp() = src.priv_comp(); rollback.release(); } } //! <b>Effects</b>: Unlinks the leftmost node from the tree. //! //! <b>Complexity</b>: Average complexity is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function breaks the tree and the tree can //! only be used for more unlink_leftmost_without_rebalance calls. //! This function is normally used to achieve a step by step //! controlled destruction of the tree. pointer unlink_leftmost_without_rebalance() { node_ptr to_be_disposed(node_algorithms::unlink_leftmost_without_rebalance (node_ptr(&priv_header()))); if(!to_be_disposed) return 0; this->priv_size_traits().decrement(); if(safemode_or_autounlink)//If this is commented does not work with normal_link node_algorithms::init(to_be_disposed); return get_real_value_traits().to_value_ptr(to_be_disposed); } //! <b>Requires</b>: replace_this must be a valid iterator of *this //! and with_this must not be inserted in any tree. //! //! <b>Effects</b>: Replaces replace_this in its position in the //! tree with with_this. The tree does not need to be rebalanced. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! with_this is not equivalent to *replace_this according to the //! ordering rules. This function is faster than erasing and inserting //! the node, since no rebalancing or comparison is needed. void replace_node(iterator replace_this, reference with_this) { node_algorithms::replace_node( get_real_value_traits().to_node_ptr(*replace_this) , node_ptr(&priv_header()) , get_real_value_traits().to_node_ptr(with_this)); } //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid iterator i belonging to the set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static iterator s_iterator_to(reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); return iterator (value_traits::to_node_ptr(value), 0); } //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static const_iterator s_iterator_to(const_reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); return const_iterator (value_traits::to_node_ptr(const_cast<reference> (value)), 0); } //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid iterator i belonging to the set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator iterator_to(reference value) { return iterator (value_traits::to_node_ptr(value), this); } //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator iterator_to(const_reference value) const { return const_iterator (value_traits::to_node_ptr(const_cast<reference> (value)), this); } //! <b>Requires</b>: value shall not be in a tree. //! //! <b>Effects</b>: init_node puts the hook of a value in a well-known default //! state. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant time. //! //! <b>Note</b>: This function puts the hook in the well-known default state //! used by auto_unlink and safe hooks. static void init_node(reference value) { node_algorithms::init(value_traits::to_node_ptr(value)); } //! <b>Effects</b>: Rebalances the tree. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear. void rebalance() { node_algorithms::rebalance(node_ptr(&priv_header())); } //! <b>Requires</b>: old_root is a node of a tree. //! //! <b>Effects</b>: Rebalances the subtree rooted at old_root. //! //! <b>Returns</b>: The new root of the subtree. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear to the elements in the subtree. iterator rebalance_subtree(iterator root) { return iterator(node_algorithms::rebalance_subtree(root.pointed_node()), this); } //! <b>Returns</b>: The balance factor (alpha) used in this tree //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. float balance_factor() const { return this->priv_alpha(); } //! <b>Requires</b>: new_alpha must be a value between 0.5 and 1.0 //! //! <b>Effects</b>: Establishes a new balance factor (alpha) and rebalances //! the tree if the new balance factor is stricter (less) than the old factor. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear to the elements in the subtree. void balance_factor(float new_alpha) { BOOST_INTRUSIVE_INVARIANT_ASSERT((new_alpha > 0.5f && new_alpha < 1.0f)); if(new_alpha < 0.5f && new_alpha >= 1.0f) return; //The alpha factor CAN't be changed if the fixed, floating operation-less //1/sqrt(2) alpha factor option is activated BOOST_STATIC_ASSERT((floating_point)); float old_alpha = this->priv_alpha(); this->priv_alpha(new_alpha); if(new_alpha < old_alpha){ data_.max_tree_size_ = this->size(); this->rebalance(); } } /* //! <b>Effects</b>: removes x from a tree of the appropriate type. It has no effect, //! if x is not in such a tree. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant time. //! //! <b>Note</b>: This static function is only usable with the "safe mode" //! hook and non-constant time size lists. Otherwise, the user must use //! the non-static "erase(reference )" member. If the user calls //! this function with a non "safe mode" or constant time size list //! a compilation error will be issued. template<class T> static void remove_node(T& value) { //This function is only usable for safe mode hooks and non-constant //time lists. //BOOST_STATIC_ASSERT((!(safemode_or_autounlink && constant_time_size))); BOOST_STATIC_ASSERT((!constant_time_size)); BOOST_STATIC_ASSERT((boost::is_convertible<T, value_type>::value)); node_ptr to_remove(value_traits::to_node_ptr(value)); node_algorithms::unlink_and_rebalance(to_remove); if(safemode_or_autounlink) node_algorithms::init(to_remove); } */ /// @cond private: template<class Disposer> iterator private_erase(const_iterator b, const_iterator e, size_type &n, Disposer disposer) { for(n = 0; b != e; ++n) this->erase_and_dispose(b++, disposer); return b.unconst(); } iterator private_erase(const_iterator b, const_iterator e, size_type &n) { for(n = 0; b != e; ++n) this->erase(b++); return b.unconst(); } /// @endcond private: static sgtree_impl &priv_container_from_end_iterator(const const_iterator &end_iterator) { header_plus_alpha *r = detail::parent_from_member<header_plus_alpha, node> ( detail::boost_intrusive_get_pointer(end_iterator.pointed_node()), &header_plus_alpha::header_); node_plus_pred_t *n = detail::parent_from_member <node_plus_pred_t, header_plus_alpha>(r, &node_plus_pred_t::header_plus_alpha_); data_t *d = detail::parent_from_member<data_t, node_plus_pred_t>(n, &data_t::node_plus_pred_); sgtree_impl *scapegoat = detail::parent_from_member<sgtree_impl, data_t>(d, &sgtree_impl::data_); return *scapegoat; } static sgtree_impl &priv_container_from_iterator(const const_iterator &it) { return priv_container_from_end_iterator(it.end_iterator_from_it()); } }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline bool operator< #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif bool operator== #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { typedef sgtree_impl<Config> tree_type; typedef typename tree_type::const_iterator const_iterator; if(tree_type::constant_time_size && x.size() != y.size()){ return false; } const_iterator end1 = x.end(); const_iterator i1 = x.begin(); const_iterator i2 = y.begin(); if(tree_type::constant_time_size){ while (i1 != end1 && *i1 == *i2) { ++i1; ++i2; } return i1 == end1; } else{ const_iterator end2 = y.end(); while (i1 != end1 && i2 != end2 && *i1 == *i2) { ++i1; ++i2; } return i1 == end1 && i2 == end2; } } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline bool operator!= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { return !(x == y); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline bool operator> #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { return y < x; } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline bool operator<= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { return !(y < x); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline bool operator>= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const sgtree_impl<T, Options...> &x, const sgtree_impl<T, Options...> &y) #else (const sgtree_impl<Config> &x, const sgtree_impl<Config> &y) #endif { return !(x < y); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class Config> #endif inline void swap #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (sgtree_impl<T, Options...> &x, sgtree_impl<T, Options...> &y) #else (sgtree_impl<Config> &x, sgtree_impl<Config> &y) #endif { x.swap(y); } /// @cond #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1 = none, class O2 = none , class O3 = none, class O4 = none> #else template<class T, class ...Options> #endif struct make_sgtree_opt { typedef typename pack_options < sg_set_defaults<T>, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::value_traits>::type value_traits; typedef sg_setopt < value_traits , typename packed_options::compare , typename packed_options::size_type , packed_options::floating_point > type; }; /// @endcond //! Helper metafunction to define a \c sgtree that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = none, class O2 = none , class O3 = none, class O4 = none> #endif struct make_sgtree { /// @cond typedef sgtree_impl < typename make_sgtree_opt<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4> #else template<class T, class ...Options> #endif class sgtree : public make_sgtree<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type { typedef typename make_sgtree <T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type Base; public: typedef typename Base::value_compare value_compare; typedef typename Base::value_traits value_traits; typedef typename Base::real_value_traits real_value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename real_value_traits::value_type, T>::value)); sgtree( const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> sgtree( bool unique, Iterator b, Iterator e , const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : Base(unique, b, e, cmp, v_traits) {} static sgtree &container_from_end_iterator(iterator end_iterator) { return static_cast<sgtree &>(Base::container_from_end_iterator(end_iterator)); } static const sgtree &container_from_end_iterator(const_iterator end_iterator) { return static_cast<const sgtree &>(Base::container_from_end_iterator(end_iterator)); } }; #endif } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_SGTREE_HPP
{ "content_hash": "32f3583c655be6adcff7c2f7c103e822", "timestamp": "", "source": "github", "line_count": 1876, "max_line_length": 126, "avg_line_length": 38.24626865671642, "alnum_prop": 0.6098118466898955, "repo_name": "pennwin2013/netsvr", "id": "5e4efe914bf89ac2bf9ebd61700a7b2c627d3cd3", "size": "71750", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "include/boost/intrusive/sgtree.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "67355" }, { "name": "C++", "bytes": "52439988" }, { "name": "Python", "bytes": "2525" } ], "symlink_target": "" }
import os from typet import Object from typet import String class EnvironmentVariable(Object): name: String[1:] @property def value(self): return os.environ.get(self.name)
{ "content_hash": "d4a1477b4a51142559f70d5f818d12d0", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 40, "avg_line_length": 16.333333333333332, "alnum_prop": 0.6989795918367347, "repo_name": "zancas/containenv", "id": "75c937670cc1b6845e7348e88fb3ab86c2d3247c", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "containment/types/environment.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "39438" }, { "name": "Shell", "bytes": "268" } ], "symlink_target": "" }
class NewDefaultToHoldTips < ActiveRecord::Migration def change change_column :projects, :hold_tips, :boolean, default: true end end
{ "content_hash": "845e9edf2ecf8d6a6c9fc8c5ac6615c6", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 64, "avg_line_length": 28.2, "alnum_prop": 0.7588652482269503, "repo_name": "vlajos/peer4commit", "id": "9781d64567d7e845af8b55c5974820885780cbcb", "size": "141", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "db/migrate/20140601103950_new_default_to_hold_tips.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9981" }, { "name": "CoffeeScript", "bytes": "4094" }, { "name": "Cucumber", "bytes": "44758" }, { "name": "HTML", "bytes": "46693" }, { "name": "JavaScript", "bytes": "32232" }, { "name": "Ruby", "bytes": "164539" } ], "symlink_target": "" }
from __future__ import absolute_import try: from urllib.request import urlopen import urllib.parse as urlparse from urllib.parse import urlencode except ImportError: import urlparse from urllib2 import urlopen from urllib import urlencode
{ "content_hash": "f7196fb5dd870a79774d465e064ac6d0", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 38, "avg_line_length": 26.4, "alnum_prop": 0.7575757575757576, "repo_name": "kmike/imobis", "id": "9e4a850f337696c677aec7bc0094cbb9cdc05e4a", "size": "288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "imobis/compat.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "8396" } ], "symlink_target": "" }