hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
909a7848165f1d933297a6cc07162b2099cb931e
1,325
go
Go
x/wta/types/msgs.go
cosmic-casino/ledger
72c1dd949c06ed1f81d9b2e67ca368fb6a68d265
[ "MIT" ]
2
2021-03-29T09:12:28.000Z
2021-03-31T17:31:19.000Z
x/wta/types/msgs.go
cosmic-casino/ledger
72c1dd949c06ed1f81d9b2e67ca368fb6a68d265
[ "MIT" ]
13
2021-02-12T19:26:54.000Z
2021-04-23T21:18:35.000Z
x/wta/types/msgs.go
cosmicbet/ledger
72c1dd949c06ed1f81d9b2e67ca368fb6a68d265
[ "MIT" ]
null
null
null
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) const ( TypeMsgBuyTickets = "buy_tickets" ) var _ sdk.Msg = &MsgBuyTickets{} // NewMsgBuyTickets allows to build a new MsgBuyTickets instance func NewMsgBuyTickets(quantity uint32, user string) *MsgBuyTickets { return &MsgBuyTickets{ Quantity: quantity, Buyer: user, } } // Route implements sdk.Msg func (m *MsgBuyTickets) Route() string { return RouterKey } // Type implements sdk.Msg func (m *MsgBuyTickets) Type() string { return TypeMsgBuyTickets } // ValidateBasic implements sdk.Msg func (m *MsgBuyTickets) ValidateBasic() error { if m.Quantity <= 0 { return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid tickets quantity: %d", m.Quantity) } if _, err := sdk.AccAddressFromBech32(m.Buyer); err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid buyer address") } return nil } // GetSignBytes implements sdk.Msg func (m *MsgBuyTickets) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(m) return sdk.MustSortJSON(bz) } // GetSigners implements sdk.Msg func (m *MsgBuyTickets) GetSigners() []sdk.AccAddress { buyerAddr, err := sdk.AccAddressFromBech32(m.Buyer) if err != nil { panic(err) } return []sdk.AccAddress{buyerAddr} }
22.457627
97
0.735094
cb54da03a90015a98422a7fe2b42ba0d93fbd3bd
6,092
h
C
Source/VALibrary/include/VistaAspects/VistaLocatable.h
VRGroupRWTH/UE4-VirtualAcousticsPlugin
d6db01f7b2550f36cd6515e4fac52006fcc22385
[ "BSD-3-Clause" ]
null
null
null
Source/VALibrary/include/VistaAspects/VistaLocatable.h
VRGroupRWTH/UE4-VirtualAcousticsPlugin
d6db01f7b2550f36cd6515e4fac52006fcc22385
[ "BSD-3-Clause" ]
null
null
null
Source/VALibrary/include/VistaAspects/VistaLocatable.h
VRGroupRWTH/UE4-VirtualAcousticsPlugin
d6db01f7b2550f36cd6515e4fac52006fcc22385
[ "BSD-3-Clause" ]
1
2020-11-27T15:39:12.000Z
2020-11-27T15:39:12.000Z
/*============================================================================*/ /* ViSTA VR toolkit */ /* Copyright (c) 1997-2016 RWTH Aachen University */ /*============================================================================*/ /* License */ /* */ /* This program is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU Lesser General Public License as published */ /* by the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*============================================================================*/ /* Contributors */ /* */ /*============================================================================*/ #ifndef _VISTALOCATABLE_H #define _VISTALOCATABLE_H /*============================================================================*/ /* INCLUDES */ /*============================================================================*/ #include "VistaAspectsConfig.h" #include <VistaBase/VistaVectorMath.h> /*============================================================================*/ /* MACROS AND DEFINES */ /*============================================================================*/ /*============================================================================*/ /* FORWARD DECLARATIONS */ /*============================================================================*/ /*============================================================================*/ /* CLASS DEFINITIONS */ /*============================================================================*/ class VISTAASPECTSAPI IVistaLocatable { public: virtual ~IVistaLocatable(); virtual bool GetTranslation( VistaVector3D& v3Translation ) const = 0; virtual bool GetTranslation( float& fX, float& fY, float& fZ ) const = 0; virtual bool GetTranslation( float a3fTranslation[3] ) const = 0; virtual bool GetTranslation( double a3dTranslation[3] ) const = 0; virtual bool GetWorldPosition( VistaVector3D& v3Position ) const = 0; virtual bool GetWorldPosition( float& fX, float& fY, float& fZ ) const = 0; virtual bool GetWorldPosition( float a3fPosition[3] ) const = 0; virtual bool GetWorldPosition( double a3dPosition[3] ) const = 0; virtual bool GetRotation( VistaQuaternion& qRotation ) const = 0; virtual bool GetRotation( float& fX, float& fY, float& fZ, float& fW ) const = 0; virtual bool GetRotation( float a4fRotation[4] ) const = 0; virtual bool GetRotation( double a4dRotation[4] ) const = 0; virtual bool GetWorldOrientation( VistaQuaternion& qOrientation ) const = 0; virtual bool GetWorldOrientation( float& fX, float& fY, float& fZ, float& fW ) const = 0; virtual bool GetWorldOrientation( float a4fOrientation[4] ) const = 0; virtual bool GetWorldOrientation( double a4dOrientation[4] ) const = 0; virtual bool GetScale( VistaVector3D& v3Scale ) const = 0; virtual bool GetScale( float& fX, float& fY, float& fZ ) const = 0; virtual bool GetScale( float a3fScale[3] ) const = 0; virtual bool GetScale( double a3dScale[3] ) const = 0; virtual bool GetWorldScale( VistaVector3D& v3Scale ) const = 0; virtual bool GetWorldScale( float& fX, float& fY, float& fZ ) const = 0; virtual bool GetWorldScale( float a3fScale[3] ) const = 0; virtual bool GetWorldScale( double a3dScale[3] ) const = 0; virtual bool GetTransform( VistaTransformMatrix& matTransform ) const = 0; virtual bool GetTransform( float a16fTransform[16], const bool bColumnMajor = false ) const = 0; virtual bool GetTransform( double a16dTransform[16], const bool bColumnMajor = false ) const = 0; virtual bool GetWorldTransform( VistaTransformMatrix& matTransform ) const = 0; virtual bool GetWorldTransform( float a16fTransform[16], const bool bColumnMajor = false ) const = 0; virtual bool GetWorldTransform( double a16dTransform[16], const bool bColumnMajor = false ) const = 0; /** * returns true and gets the WorldTransform of the parent if the locatable is in * a hierarchy (even if it does not have a parent, e.g. if it is a rootnode, in which * case a unit matrix is returned). * returns false if the locatable is not in a hierarchy. */ virtual bool GetParentWorldTransform( VistaTransformMatrix& matTransform ) const = 0; virtual bool GetParentWorldTransform( float a16fTransform[16], const bool bColumnMajor = false ) const = 0; virtual bool GetParentWorldTransform( double a16dTransform[16], const bool bColumnMajor = false ) const = 0; protected: IVistaLocatable(); private: }; /*============================================================================*/ /* LOCAL VARS AND FUNCS */ /*============================================================================*/ #endif //_VISTALOCATABLE_H
54.882883
110
0.48736
272ca8f00f08162bef7890180e6619d8e2b78ff9
182
asm
Assembly
Tests/Z80 Programs/testZ80AsmCharIncTRS80/testZ80AsmCharIncTRS80.asm
Simulators/PiBusRaider
ec091f3c74ea25c3287d26d990ff5d1b90e97e92
[ "MIT" ]
7
2021-01-23T04:37:18.000Z
2022-01-08T04:44:00.000Z
Tests/Z80 Programs/testZ80AsmCharIncTRS80/testZ80AsmCharIncTRS80.asm
Simulators/PiBusRaider
ec091f3c74ea25c3287d26d990ff5d1b90e97e92
[ "MIT" ]
3
2021-04-01T11:28:31.000Z
2021-05-10T09:56:05.000Z
Tests/Z80 Programs/testZ80AsmCharIncTRS80/testZ80AsmCharIncTRS80.asm
robdobsn/BusRaider
691e7882a06408208ca2abece5e7c4bcb4b4fa45
[ "MIT" ]
null
null
null
org 0 loopstart: ld e,0x30 loophere: ld hl,0x3c00 ld (hl),e ld bc,0x0001 loopin: dec bc ld a,b or c jp nz, loopin inc e ld a, e cp a,0x3a jp nz,loophere jp loopstart
8.666667
15
0.653846
719f7a1047f47c81ef3770dd6ae998095b58a142
565
ts
TypeScript
containers/IndexContainer.ts
jdtzmn/nextjs-advanced-starter
0d53b5d145741b808e2e9f99dc5b2bd291d1fa8c
[ "MIT" ]
null
null
null
containers/IndexContainer.ts
jdtzmn/nextjs-advanced-starter
0d53b5d145741b808e2e9f99dc5b2bd291d1fa8c
[ "MIT" ]
2
2019-04-12T23:39:51.000Z
2019-04-28T22:39:45.000Z
containers/IndexContainer.ts
jdtzmn/nextjs-advanced-starter
0d53b5d145741b808e2e9f99dc5b2bd291d1fa8c
[ "MIT" ]
null
null
null
import React from 'react' import { connect } from 'react-redux' import { welcomeAction } from '../actions' import { WelcomeState } from '../reducers/welcomeReducer' const mapStateToProps = (state): WelcomeState => ({ count: state.welcome.count }) interface WithoutCount { increment: () => any } const mapDispatchToProps = (dispatch): WithoutCount => ({ increment: async () => dispatch(welcomeAction()) }) export const connectIndexContainer = (component): React.Component => { return connect( mapStateToProps, mapDispatchToProps )(component) }
23.541667
70
0.709735
044bdbf0d0c6edacbfbb21c3e2e30d1532718b99
3,241
java
Java
aimbrain/src/main/java/com/aimbrain/sdk/privacy/PrivacyGuard.java
jesobremonte/aimbrain-android-sdk
428de643631778994cb44736ccf4306f40e83744
[ "MIT" ]
3
2016-10-29T23:43:42.000Z
2018-06-05T10:02:13.000Z
aimbrain/src/main/java/com/aimbrain/sdk/privacy/PrivacyGuard.java
jesobremonte/aimbrain-android-sdk
428de643631778994cb44736ccf4306f40e83744
[ "MIT" ]
3
2016-12-01T07:16:25.000Z
2019-04-08T13:11:26.000Z
aimbrain/src/main/java/com/aimbrain/sdk/privacy/PrivacyGuard.java
jesobremonte/aimbrain-android-sdk
428de643631778994cb44736ccf4306f40e83744
[ "MIT" ]
3
2017-02-01T18:45:16.000Z
2019-04-04T03:59:35.000Z
package com.aimbrain.sdk.privacy; import android.support.annotation.VisibleForTesting; import android.view.View; import android.view.ViewParent; import android.widget.EditText; import com.aimbrain.sdk.util.Logger; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * Class used to keep and free non-capturing guards on selected views. * Typical use case is to store reference to this object as long as there is need to exclude given views from capturing. Then call {@link #invalidate() invalidate} method and remove the reference. */ public class PrivacyGuard { public static final String TAG = PrivacyGuard.class.getSimpleName(); private Set<WeakReference<View>> ignoredViews; private boolean ignoreAllViews; private boolean valid; /** * Creates instance of the class with given set of protected views. * @param ignoredViews set of protected views */ public PrivacyGuard(Set<View> ignoredViews) { Logger.v(TAG, "privacy guard, " + ignoredViews.size() + " views"); this.ignoreAllViews = false; this.valid = true; this.ignoredViews = new HashSet<>(); for(View view : ignoredViews) this.ignoredViews.add(new WeakReference<>(view)); } /** * Allows creating instance of the class protecting all views. * @param ignoreAllViews true if all views in the application should be protected */ public PrivacyGuard(boolean ignoreAllViews) { Logger.v(TAG, "privacy guard, all views"); this.ignoreAllViews = ignoreAllViews; this.ignoredViews = new HashSet<>(); this.valid = true; } /** * Method used to test whether given view is protected and should be ignored. * @param view view to test * @return true if view is protected by the privacy guard */ public boolean isViewIgnored(View view) { if(!valid) return false; if(ignoreAllViews) return true; if (view == null) { return false; } return isDescendantOfIgnoredView(view); } @VisibleForTesting protected boolean isDescendantOfIgnoredView(View view) { if (view == null) { return false; } for(WeakReference<View> reference : ignoredViews) { if(reference.get() == view) return true; } ViewParent parent = view.getParent(); if( parent != null && parent instanceof View) return isDescendantOfIgnoredView((View)parent); return false; } public void revokeEditTextFocus(){ if(ignoredViews != null) { for(WeakReference<View> reference : ignoredViews) { View view = reference.get(); if(view instanceof EditText && view.hasFocus()){ view.clearFocus(); view.requestFocus(); return; } } } } /** * Invalidates guard. Calling this method causes guard to stop preventing from capturing. */ public void invalidate() { ignoredViews.clear(); this.valid = false; } }
28.681416
196
0.617711
0afecc0be6708635d4d626ba2c3282fe43fc0517
3,455
kt
Kotlin
src/main/kotlin/jp/assasans/protanki/server/client/User.kt
Assasans/protanki-server
3c30a9b02c50e421c237949e92e463f5a68e1118
[ "MIT" ]
9
2022-01-30T20:31:52.000Z
2022-03-24T15:07:49.000Z
src/main/kotlin/jp/assasans/protanki/server/client/User.kt
Assasans/protanki-server
3c30a9b02c50e421c237949e92e463f5a68e1118
[ "MIT" ]
15
2022-02-16T00:07:27.000Z
2022-03-27T17:44:38.000Z
src/main/kotlin/jp/assasans/protanki/server/client/User.kt
Assasans/protanki-server
3c30a9b02c50e421c237949e92e463f5a68e1118
[ "MIT" ]
1
2022-01-30T22:04:27.000Z
2022-01-30T22:04:27.000Z
package jp.assasans.protanki.server.client import jakarta.persistence.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.hibernate.annotations.Parent import jp.assasans.protanki.server.HibernateUtils import jp.assasans.protanki.server.garage.ServerGarageUserItem import jp.assasans.protanki.server.garage.ServerGarageUserItemHull import jp.assasans.protanki.server.garage.ServerGarageUserItemPaint import jp.assasans.protanki.server.garage.ServerGarageUserItemWeapon @Embeddable data class UserEquipment( @Column(name = "equipment_hull", nullable = false) var hullId: String, @Column(name = "equipment_weapon", nullable = false) var weaponId: String, @Column(name = "equipment_paint", nullable = false) var paintId: String ) { @Suppress("JpaAttributeTypeInspection") @Parent lateinit var user: User // IntelliJ IDEA still shows error for this line. @get:Transient var hull: ServerGarageUserItemHull get() = user.items.single { item -> item.id.itemName == hullId } as ServerGarageUserItemHull set(value) { hullId = value.id.itemName } @get:Transient var weapon: ServerGarageUserItemWeapon get() = user.items.single { item -> item.id.itemName == weaponId } as ServerGarageUserItemWeapon set(value) { weaponId = value.id.itemName } @get:Transient var paint: ServerGarageUserItemPaint get() = user.items.single { item -> item.id.itemName == paintId } as ServerGarageUserItemPaint set(value) { paintId = value.id.itemName } } interface IUserRepository { suspend fun getUser(id: Int): User? suspend fun getUser(username: String): User? } class UserRepository : IUserRepository { private val entityManager = HibernateUtils.createEntityManager() override suspend fun getUser(id: Int): User? = withContext(Dispatchers.IO) { entityManager.find(User::class.java, id) } override suspend fun getUser(username: String): User? { return try { withContext(Dispatchers.IO) { entityManager .createQuery("FROM User WHERE username = :username", User::class.java) .setParameter("username", username) .singleResult } } catch(exception: NoResultException) { null } } } @Entity @Table( name = "users", indexes = [ Index(name = "idx_users_username", columnList = "username") ] ) class User( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Int = 0, @Column(nullable = false, unique = true, length = 64) var username: String, @Column(nullable = false) var password: String, @Column(nullable = false) var score: Int, @Column(nullable = false) var crystals: Int, @OneToMany(targetEntity = ServerGarageUserItem::class, mappedBy = "id.user") val items: MutableList<ServerGarageUserItem> ) { @AttributeOverride(name = "hullId", column = Column(name = "equipment_hull_id")) @AttributeOverride(name = "weaponId", column = Column(name = "equipment_weapon_id")) @AttributeOverride(name = "paintId", column = Column(name = "equipment_paint_id")) @Embedded lateinit var equipment: UserEquipment val rank: UserRank get() { var rank = UserRank.Recruit var nextRank: UserRank = rank.nextRank ?: return rank while(score >= nextRank.score) { rank = nextRank nextRank = rank.nextRank ?: return rank } return rank } val currentRankScore: Int get() = rank.score - score }
31.409091
100
0.713459
f47ca4cd1a33f657a6e5dbe8a79e70574fde9832
6,352
go
Go
pkg/apiserver/service_providers.go
kolly83/kore
a0b11be9bd3a7d998807d4ff062c3fc8f73565c2
[ "Apache-2.0" ]
null
null
null
pkg/apiserver/service_providers.go
kolly83/kore
a0b11be9bd3a7d998807d4ff062c3fc8f73565c2
[ "Apache-2.0" ]
2
2021-04-29T19:30:30.000Z
2021-04-29T19:31:01.000Z
pkg/apiserver/service_providers.go
kolly83/kore
a0b11be9bd3a7d998807d4ff062c3fc8f73565c2
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Appvia Ltd <info@appvia.io> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package apiserver import ( "fmt" "net/http" "github.com/appvia/kore/pkg/apiserver/filters" servicesv1 "github.com/appvia/kore/pkg/apis/services/v1" "github.com/appvia/kore/pkg/kore" "github.com/appvia/kore/pkg/utils" restful "github.com/emicklei/go-restful" log "github.com/sirupsen/logrus" ) func init() { RegisterHandler(&serviceProvidersHandler{}) } type serviceProvidersHandler struct { kore.Interface // DefaultHandler implements default features DefaultHandler } func (p *serviceProvidersHandler) systemServiceProviderFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { handleErrors(req, resp, func() error { name := req.PathParameter("name") serviceProvider, err := p.ServiceProviders().Get(req.Request.Context(), name) if err != nil && err != kore.ErrNotFound { return err } if serviceProvider != nil && serviceProvider.Annotations[kore.AnnotationSystem] == "true" { resp.WriteHeader(http.StatusForbidden) return nil } // @step: continue with the chain chain.ProcessFilter(req, resp) return nil }) } // Register is called by the api server on registration func (p *serviceProvidersHandler) Register(i kore.Interface, builder utils.PathBuilder) (*restful.WebService, error) { path := builder.Add("serviceproviders") log.WithFields(log.Fields{ "path": path.Base(), }).Info("registering the serviceproviders webservice") p.Interface = i ws := &restful.WebService{} ws.Consumes(restful.MIME_JSON) ws.Produces(restful.MIME_JSON) ws.Path(path.Base()) ws.Route( withAllNonValidationErrors(ws.GET("")).To(p.findServiceProviders). Doc("Returns all the available service providers"). Operation("ListServiceProviders"). Param(ws.QueryParameter("kind", "Filters service providers for a specific kind")). Returns(http.StatusOK, "A list of service providers", servicesv1.ServiceProviderList{}), ) ws.Route( withAllNonValidationErrors(ws.GET("/{name}")).To(p.findServiceProvider). Doc("Returns a specific service provider"). Operation("GetServiceProvider"). Param(ws.PathParameter("name", "The name of the service provider you wish to retrieve")). Returns(http.StatusNotFound, "the service provider with the given name doesn't exist", nil). Returns(http.StatusOK, "Contains the service provider definition", servicesv1.ServiceProvider{}), ) ws.Route( withAllErrors(ws.PUT("/{name}")).To(p.updateServiceProvider). Filter(filters.Admin). Filter(p.systemServiceProviderFilter). Doc("Creates or updates a service provider"). Operation("UpdateServiceProvider"). Param(ws.PathParameter("name", "The name of the service provider you wish to create or update")). Reads(servicesv1.ServiceProvider{}, "The specification for the service provider you are creating or updating"). Returns(http.StatusOK, "Contains the service provider definition", servicesv1.ServiceProvider{}), ) ws.Route( withAllErrors(ws.DELETE("/{name}")).To(p.deleteServiceProvider). Filter(filters.Admin). Filter(p.systemServiceProviderFilter). Doc("Deletes a service provider"). Operation("DeleteServiceProvider"). Param(ws.PathParameter("name", "The name of the service provider you wish to delete")). Returns(http.StatusNotFound, "the service provider with the given name doesn't exist", nil). Returns(http.StatusOK, "Contains the service provider definition", servicesv1.ServiceProvider{}), ) return ws, nil } // findServiceProvider returns a specific service provider func (p serviceProvidersHandler) findServiceProvider(req *restful.Request, resp *restful.Response) { handleErrors(req, resp, func() error { provider, err := p.ServiceProviders().Get(req.Request.Context(), req.PathParameter("name")) if err != nil { return err } return resp.WriteHeaderAndEntity(http.StatusOK, provider) }) } // findServiceProviders returns all service providers in the kore func (p serviceProvidersHandler) findServiceProviders(req *restful.Request, resp *restful.Response) { handleErrors(req, resp, func() error { res, err := p.ServiceProviders().List(req.Request.Context()) if err != nil { return err } return resp.WriteHeaderAndEntity(http.StatusOK, res) }) } // updateServiceProvider is used to update or create a service provider in the kore func (p serviceProvidersHandler) updateServiceProvider(req *restful.Request, resp *restful.Response) { handleErrors(req, resp, func() error { name := req.PathParameter("name") provider := &servicesv1.ServiceProvider{} if err := req.ReadEntity(provider); err != nil { return err } provider.Name = name if provider.Annotations[kore.AnnotationSystem] != "" { writeError(req, resp, fmt.Errorf("setting %q annotation is not allowed", kore.AnnotationSystem), http.StatusForbidden) return nil } if err := p.ServiceProviders().Update(req.Request.Context(), provider); err != nil { return err } return resp.WriteHeaderAndEntity(http.StatusOK, provider) }) } // deleteServiceProvider is used to update or create a service provider in the kore func (p serviceProvidersHandler) deleteServiceProvider(req *restful.Request, resp *restful.Response) { handleErrors(req, resp, func() error { name := req.PathParameter("name") provider, err := p.ServiceProviders().Delete(req.Request.Context(), name) if err != nil { return err } return resp.WriteHeaderAndEntity(http.StatusOK, provider) }) } // Name returns the name of the handler func (p serviceProvidersHandler) Name() string { return "serviceproviders" } // Enabled returns true if the services feature gate is enabled func (p serviceProvidersHandler) Enabled() bool { return p.Config().IsFeatureGateEnabled(kore.FeatureGateServices) }
33.256545
137
0.741184
12273d6760e3e8a200992f57b4e5559ea58d420c
1,062
c
C
libc/winsup/testsuite/winsup.api/pthread/cancel12.c
The0x539/wasp
5f83aab7bf0c0915b1d3491034d35b091c7aebdf
[ "MIT" ]
7
2016-11-08T15:51:54.000Z
2021-07-27T08:44:27.000Z
libc/winsup/testsuite/winsup.api/pthread/cancel12.c
The0x539/wasp
5f83aab7bf0c0915b1d3491034d35b091c7aebdf
[ "MIT" ]
1
2022-01-28T19:16:53.000Z
2022-02-02T21:38:17.000Z
libc/winsup/testsuite/winsup.api/pthread/cancel12.c
The0x539/wasp
5f83aab7bf0c0915b1d3491034d35b091c7aebdf
[ "MIT" ]
9
2016-10-05T08:41:38.000Z
2020-10-22T18:09:47.000Z
/* * File: cancel12.c * * Test Synopsis: Test if system is a cancellation point. * * Test Method (Validation or Falsification): * - * * Requirements Tested: * - * * Features Tested: * - * * Cases Tested: * - * * Description: * - * * Environment: * - * * Input: * - None. * * Output: * - File name, Line number, and failed expression on failure. * - No output on success. * * Assumptions: * - have working pthread_create, pthread_cancel, pthread_setcancelstate * pthread_join * * Pass Criteria: * - Process returns zero exit status. * * Fail Criteria: * - Process returns non-zero exit status. */ #include "test.h" static void sig_handler(int sig) { } static void *Thread(void *punused) { signal (SIGINT, sig_handler); system ("sleep 5"); assert ((void *)signal (SIGINT, NULL) == sig_handler); return NULL; } int main (void) { void * result; pthread_t t; assert (pthread_create (&t, NULL, Thread, NULL) == 0); assert (pthread_join (t, &result) == 0); assert (result == NULL); return 0; }
15.171429
72
0.627119
21697792f24c95827b0f33c9d94d6eec28a3e55a
1,084
rs
Rust
src/register/currentel.rs
RusPiRo/ruspiro-arch-aarch64
3d9d1797962b4f7c87b44a8c9736f02b066a0173
[ "Apache-2.0", "MIT" ]
null
null
null
src/register/currentel.rs
RusPiRo/ruspiro-arch-aarch64
3d9d1797962b4f7c87b44a8c9736f02b066a0173
[ "Apache-2.0", "MIT" ]
1
2021-08-29T13:32:47.000Z
2021-08-30T11:03:34.000Z
src/register/currentel.rs
RusPiRo/ruspiro-arch-aarch64
3d9d1797962b4f7c87b44a8c9736f02b066a0173
[ "Apache-2.0", "MIT" ]
null
null
null
/*********************************************************************************************************************** * Copyright (c) 2020 by the authors * * Author: André Borrmann <pspwizard@gmx.de> * License: Apache License 2.0 / MIT **********************************************************************************************************************/ //! # CurrentEL - Current Exception Level //! //! Holds the current exception level //! //! ```no_run //! # use ruspiro_arch_aarch64::register::*; //! //! // read the current exeption level - do this by accessing the predefined //! // register field //! let current_el = currentel::read(currentel::EL::Field); //! //! if current_el == currentel::EL::EL2 { //! /* do something */ //! } //! ``` use crate::register::*; use crate::{define_aarch64_register, impl_system_register_rw}; define_aarch64_register! { @currentEl<u64> { /// The current exception level EL OFFSET(2) BITS(2) [ EL0 = 0b00, EL1 = 0b01, EL2 = 0b10, EL3 = 0b11 ] } }
28.526316
120
0.461255
a7007cde727b36caa804f67398b9ffd9cda35c3e
31,833
sql
SQL
layolanda_2017-04-01.sql
frankpaul142/layolanda
b88db7f4b1416eee216ff0923b4fc04cef9a7666
[ "BSD-3-Clause" ]
null
null
null
layolanda_2017-04-01.sql
frankpaul142/layolanda
b88db7f4b1416eee216ff0923b4fc04cef9a7666
[ "BSD-3-Clause" ]
null
null
null
layolanda_2017-04-01.sql
frankpaul142/layolanda
b88db7f4b1416eee216ff0923b4fc04cef9a7666
[ "BSD-3-Clause" ]
null
null
null
# ************************************************************ # Sequel Pro SQL dump # Versión 4541 # # http://www.sequelpro.com/ # https://github.com/sequelpro/sequelpro # # Host: 127.0.0.1 (MySQL 5.7.17) # Base de datos: layolanda # Tiempo de Generación: 2017-04-01 16:11:51 +0000 # ************************************************************ /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Volcado de tabla address # ------------------------------------------------------------ DROP TABLE IF EXISTS `address`; CREATE TABLE `address` ( `id` int(11) NOT NULL AUTO_INCREMENT, `address_line_1` varchar(255) NOT NULL, `address_line_2` varchar(255) DEFAULT NULL, `type` enum('BILLING','DELIVERY','BILLING-DELIVERY') NOT NULL, `creation_date` datetime NOT NULL, `city` varchar(150) NOT NULL, `province` varchar(150) NOT NULL, `country_id` int(11) NOT NULL, `zip` varchar(45) NOT NULL, `phone` varchar(45) NOT NULL, `user_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `fk_address_country1_idx` (`country_id`), KEY `fk_address_user1_idx` (`user_id`), CONSTRAINT `fk_address_country1` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_address_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `address` WRITE; /*!40000 ALTER TABLE `address` DISABLE KEYS */; INSERT INTO `address` (`id`, `address_line_1`, `address_line_2`, `type`, `creation_date`, `city`, `province`, `country_id`, `zip`, `phone`, `user_id`) VALUES (1,'Rio Rumiyacu N71-144 y Juan Procel','Casa 3 pisos blanca bordes naranjas','BILLING','2017-02-01 00:01:21','Quito','Pichincha',1,'EC170305','022495310',3), (3,'Rio Rumiyacu N71-144 y Juan Procel','Casa 3 pisos blanca bordes naranjas','DELIVERY','2017-02-01 00:01:21','Quito','Pichincha',1,'EC170305','022495310',3); /*!40000 ALTER TABLE `address` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla artist # ------------------------------------------------------------ DROP TABLE IF EXISTS `artist`; CREATE TABLE `artist` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `name` varchar(150) NOT NULL, `birthday` date NOT NULL, `death_date` date DEFAULT NULL, `country_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `fk_artist_country1_idx` (`country_id`), CONSTRAINT `fk_artist_country1` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `artist` WRITE; /*!40000 ALTER TABLE `artist` DISABLE KEYS */; INSERT INTO `artist` (`id`, `creation_date`, `name`, `birthday`, `death_date`, `country_id`) VALUES (1,'2017-01-20 00:00:00','Franklin Paula','1990-11-14',NULL,1); /*!40000 ALTER TABLE `artist` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla bill # ------------------------------------------------------------ DROP TABLE IF EXISTS `bill`; CREATE TABLE `bill` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `creation_date` datetime NOT NULL, `billing_id` int(11) NOT NULL, `delivery_id` int(11) NOT NULL, `status` enum('PAYED','FAILED','PENDING') NOT NULL DEFAULT 'PENDING', `observation` text, `subtotal` double(10,2) DEFAULT NULL, `pay_method` enum('PAYPAL') DEFAULT 'PAYPAL', PRIMARY KEY (`id`), KEY `fk_bill_user1_idx` (`user_id`), KEY `fk_bill_baddress` (`billing_id`), KEY `fk_bill_daddress` (`delivery_id`), CONSTRAINT `fk_bill_baddress` FOREIGN KEY (`billing_id`) REFERENCES `address` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_bill_daddress` FOREIGN KEY (`delivery_id`) REFERENCES `address` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_bill_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `bill` WRITE; /*!40000 ALTER TABLE `bill` DISABLE KEYS */; INSERT INTO `bill` (`id`, `user_id`, `creation_date`, `billing_id`, `delivery_id`, `status`, `observation`, `subtotal`, `pay_method`) VALUES (5,3,'2017-02-01 23:02:50',1,3,'PENDING','',150.00,'PAYPAL'), (6,3,'2017-02-01 23:04:39',1,3,'PENDING','',150.00,'PAYPAL'), (7,3,'2017-02-01 23:05:34',1,3,'PAYED','',150.00,'PAYPAL'), (8,3,'2017-02-01 23:08:01',1,3,'PENDING','',150.00,'PAYPAL'), (9,3,'2017-02-01 23:15:02',1,3,'PENDING','',273.00,'PAYPAL'), (10,3,'2017-02-01 23:26:10',1,3,'PENDING','',273.00,'PAYPAL'), (11,3,'2017-02-02 23:43:30',1,3,'PENDING','',273.00,'PAYPAL'), (12,3,'2017-02-02 23:43:57',1,3,'PENDING','',273.00,'PAYPAL'), (13,3,'2017-02-02 23:54:39',1,3,'PENDING','',423.00,'PAYPAL'); /*!40000 ALTER TABLE `bill` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla category # ------------------------------------------------------------ DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `category_id` int(11) DEFAULT NULL, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, PRIMARY KEY (`id`), KEY `fk_category_category_idx` (`category_id`), CONSTRAINT `fk_category_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `category` WRITE; /*!40000 ALTER TABLE `category` DISABLE KEYS */; INSERT INTO `category` (`id`, `category_id`, `creation_date`, `description`) VALUES (1,NULL,'2017-01-20 00:00:00','ARTE'), (2,NULL,'2017-01-20 00:00:00','ARTESANIA FINA'), (3,NULL,'2017-01-20 00:00:00','NUEVA COLECCIÓN'), (4,1,'2017-01-20 00:00:00','Arte'), (5,4,'2017-01-20 00:00:00','Figurativa'), (6,1,'2017-01-20 00:00:00','Pintura'), (7,4,'2017-01-20 00:00:00','Abstracta'), (8,4,'2017-01-20 00:00:00','Conceptual'), (12,1,'2017-01-20 00:00:00','Abstracta'); /*!40000 ALTER TABLE `category` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla content # ------------------------------------------------------------ DROP TABLE IF EXISTS `content`; CREATE TABLE `content` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL DEFAULT '', `description` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `content` WRITE; /*!40000 ALTER TABLE `content` DISABLE KEYS */; INSERT INTO `content` (`id`, `title`, `description`) VALUES (1,'Envío','<p>lkasdljads</p>'), (2,'Contáctenos','<p>adasdasd</p>'), (3,'¿Cómo Llegar?','<p>asdasdasd</p>'), (4,'Políticas de Privacidad','<p>adsklasdads</p>'), (5,'Términos y Condiciones de Compra','<p>hkjaskjhdas</p>'); /*!40000 ALTER TABLE `content` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla country # ------------------------------------------------------------ DROP TABLE IF EXISTS `country`; CREATE TABLE `country` ( `id` int(11) NOT NULL AUTO_INCREMENT, `country_code` varchar(2) DEFAULT NULL, `country_name` varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `country` WRITE; /*!40000 ALTER TABLE `country` DISABLE KEYS */; INSERT INTO `country` (`id`, `country_code`, `country_name`) VALUES (1,'EC','Ecuador'), (2,'AF','Afghanistan'), (3,'AL','Albania'), (4,'DZ','Algeria'), (5,'DS','American Samoa'), (6,'AD','Andorra'), (7,'AO','Angola'), (8,'AI','Anguilla'), (9,'AQ','Antarctica'), (10,'AG','Antigua and Barbuda'), (11,'AR','Argentina'), (12,'AM','Armenia'), (13,'AW','Aruba'), (14,'AU','Australia'), (15,'AT','Austria'), (16,'AZ','Azerbaijan'), (17,'BS','Bahamas'), (18,'BH','Bahrain'), (19,'BD','Bangladesh'), (20,'BB','Barbados'), (21,'BY','Belarus'), (22,'BE','Belgium'), (23,'BZ','Belize'), (24,'BJ','Benin'), (25,'BM','Bermuda'), (26,'BT','Bhutan'), (27,'BO','Bolivia'), (28,'BA','Bosnia and Herzegovina'), (29,'BW','Botswana'), (30,'BV','Bouvet Island'), (31,'BR','Brazil'), (32,'IO','British Indian Ocean Territory'), (33,'BN','Brunei Darussalam'), (34,'BG','Bulgaria'), (35,'BF','Burkina Faso'), (36,'BI','Burundi'), (37,'KH','Cambodia'), (38,'CM','Cameroon'), (39,'CA','Canada'), (40,'CV','Cape Verde'), (41,'KY','Cayman Islands'), (42,'CF','Central African Republic'), (43,'TD','Chad'), (44,'CL','Chile'), (45,'CN','China'), (46,'CX','Christmas Island'), (47,'CC','Cocos (Keeling) Islands'), (48,'CO','Colombia'), (49,'KM','Comoros'), (50,'CG','Congo'), (51,'CK','Cook Islands'), (52,'CR','Costa Rica'), (53,'HR','Croatia (Hrvatska)'), (54,'CU','Cuba'), (55,'CY','Cyprus'), (56,'CZ','Czech Republic'), (57,'DK','Denmark'), (58,'DJ','Djibouti'), (59,'DM','Dominica'), (60,'DO','Dominican Republic'), (61,'TP','East Timor'), (63,'EG','Egypt'), (64,'SV','El Salvador'), (65,'GQ','Equatorial Guinea'), (66,'ER','Eritrea'), (67,'EE','Estonia'), (68,'ET','Ethiopia'), (69,'FK','Falkland Islands (Malvinas)'), (70,'FO','Faroe Islands'), (71,'FJ','Fiji'), (72,'FI','Finland'), (73,'FR','France'), (74,'FX','France, Metropolitan'), (75,'GF','French Guiana'), (76,'PF','French Polynesia'), (77,'TF','French Southern Territories'), (78,'GA','Gabon'), (79,'GM','Gambia'), (80,'GE','Georgia'), (81,'DE','Germany'), (82,'GH','Ghana'), (83,'GI','Gibraltar'), (84,'GK','Guernsey'), (85,'GR','Greece'), (86,'GL','Greenland'), (87,'GD','Grenada'), (88,'GP','Guadeloupe'), (89,'GU','Guam'), (90,'GT','Guatemala'), (91,'GN','Guinea'), (92,'GW','Guinea-Bissau'), (93,'GY','Guyana'), (94,'HT','Haiti'), (95,'HM','Heard and Mc Donald Islands'), (96,'HN','Honduras'), (97,'HK','Hong Kong'), (98,'HU','Hungary'), (99,'IS','Iceland'), (100,'IN','India'), (101,'IM','Isle of Man'), (102,'ID','Indonesia'), (103,'IR','Iran (Islamic Republic of)'), (104,'IQ','Iraq'), (105,'IE','Ireland'), (106,'IL','Israel'), (107,'IT','Italy'), (108,'CI','Ivory Coast'), (109,'JE','Jersey'), (110,'JM','Jamaica'), (111,'JP','Japan'), (112,'JO','Jordan'), (113,'KZ','Kazakhstan'), (114,'KE','Kenya'), (115,'KI','Kiribati'), (116,'KP','Korea, Democratic People\'s Republic of'), (117,'KR','Korea, Republic of'), (118,'XK','Kosovo'), (119,'KW','Kuwait'), (120,'KG','Kyrgyzstan'), (121,'LA','Lao People\'s Democratic Republic'), (122,'LV','Latvia'), (123,'LB','Lebanon'), (124,'LS','Lesotho'), (125,'LR','Liberia'), (126,'LY','Libyan Arab Jamahiriya'), (127,'LI','Liechtenstein'), (128,'LT','Lithuania'), (129,'LU','Luxembourg'), (130,'MO','Macau'), (131,'MK','Macedonia'), (132,'MG','Madagascar'), (133,'MW','Malawi'), (134,'MY','Malaysia'), (135,'MV','Maldives'), (136,'ML','Mali'), (137,'MT','Malta'), (138,'MH','Marshall Islands'), (139,'MQ','Martinique'), (140,'MR','Mauritania'), (141,'MU','Mauritius'), (142,'TY','Mayotte'), (143,'MX','Mexico'), (144,'FM','Micronesia, Federated States of'), (145,'MD','Moldova, Republic of'), (146,'MC','Monaco'), (147,'MN','Mongolia'), (148,'ME','Montenegro'), (149,'MS','Montserrat'), (150,'MA','Morocco'), (151,'MZ','Mozambique'), (152,'MM','Myanmar'), (153,'NA','Namibia'), (154,'NR','Nauru'), (155,'NP','Nepal'), (156,'NL','Netherlands'), (157,'AN','Netherlands Antilles'), (158,'NC','New Caledonia'), (159,'NZ','New Zealand'), (160,'NI','Nicaragua'), (161,'NE','Niger'), (162,'NG','Nigeria'), (163,'NU','Niue'), (164,'NF','Norfolk Island'), (165,'MP','Northern Mariana Islands'), (166,'NO','Norway'), (167,'OM','Oman'), (168,'PK','Pakistan'), (169,'PW','Palau'), (170,'PS','Palestine'), (171,'PA','Panama'), (172,'PG','Papua New Guinea'), (173,'PY','Paraguay'), (174,'PE','Peru'), (175,'PH','Philippines'), (176,'PN','Pitcairn'), (177,'PL','Poland'), (178,'PT','Portugal'), (179,'PR','Puerto Rico'), (180,'QA','Qatar'), (181,'RE','Reunion'), (182,'RO','Romania'), (183,'RU','Russian Federation'), (184,'RW','Rwanda'), (185,'KN','Saint Kitts and Nevis'), (186,'LC','Saint Lucia'), (187,'VC','Saint Vincent and the Grenadines'), (188,'WS','Samoa'), (189,'SM','San Marino'), (190,'ST','Sao Tome and Principe'), (191,'SA','Saudi Arabia'), (192,'SN','Senegal'), (193,'RS','Serbia'), (194,'SC','Seychelles'), (195,'SL','Sierra Leone'), (196,'SG','Singapore'), (197,'SK','Slovakia'), (198,'SI','Slovenia'), (199,'SB','Solomon Islands'), (200,'SO','Somalia'), (201,'ZA','South Africa'), (202,'GS','South Georgia South Sandwich Islands'), (203,'ES','Spain'), (204,'LK','Sri Lanka'), (205,'SH','St. Helena'), (206,'PM','St. Pierre and Miquelon'), (207,'SD','Sudan'), (208,'SR','Suriname'), (209,'SJ','Svalbard and Jan Mayen Islands'), (210,'SZ','Swaziland'), (211,'SE','Sweden'), (212,'CH','Switzerland'), (213,'SY','Syrian Arab Republic'), (214,'TW','Taiwan'), (215,'TJ','Tajikistan'), (216,'TZ','Tanzania, United Republic of'), (217,'TH','Thailand'), (218,'TG','Togo'), (219,'TK','Tokelau'), (220,'TO','Tonga'), (221,'TT','Trinidad and Tobago'), (222,'TN','Tunisia'), (223,'TR','Turkey'), (224,'TM','Turkmenistan'), (225,'TC','Turks and Caicos Islands'), (226,'TV','Tuvalu'), (227,'UG','Uganda'), (228,'UA','Ukraine'), (229,'AE','United Arab Emirates'), (230,'GB','United Kingdom'), (231,'US','United States'), (232,'UM','United States minor outlying islands'), (233,'UY','Uruguay'), (234,'UZ','Uzbekistan'), (235,'VU','Vanuatu'), (236,'VA','Vatican City State'), (237,'VE','Venezuela'), (238,'VN','Vietnam'), (239,'VG','Virgin Islands (British)'), (240,'VI','Virgin Islands (U.S.)'), (241,'WF','Wallis and Futuna Islands'), (242,'EH','Western Sahara'), (243,'YE','Yemen'), (244,'ZR','Zaire'), (245,'ZM','Zambia'), (246,'ZW','Zimbabwe'); /*!40000 ALTER TABLE `country` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla detail # ------------------------------------------------------------ DROP TABLE IF EXISTS `detail`; CREATE TABLE `detail` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bill_id` int(11) NOT NULL, `product_has_mesure_type_id` int(11) NOT NULL, `creation_date` datetime NOT NULL, `price` double(10,2) NOT NULL, PRIMARY KEY (`id`), KEY `fk_detail_bill1_idx` (`bill_id`), KEY `fk_detail_product_has_mesure_type1_idx` (`product_has_mesure_type_id`), CONSTRAINT `fk_detail_bill1` FOREIGN KEY (`bill_id`) REFERENCES `bill` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_detail_product_has_mesure_type1` FOREIGN KEY (`product_has_mesure_type_id`) REFERENCES `product_has_mesure_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `detail` WRITE; /*!40000 ALTER TABLE `detail` DISABLE KEYS */; INSERT INTO `detail` (`id`, `bill_id`, `product_has_mesure_type_id`, `creation_date`, `price`) VALUES (1,5,1,'2017-02-01 23:02:50',150.00), (3,7,1,'2017-02-01 23:05:34',150.00), (4,8,1,'2017-02-01 23:08:01',150.00), (5,9,1,'2017-02-01 23:15:02',150.00), (6,5,6,'2017-02-01 23:15:02',123.00), (7,10,1,'2017-02-01 23:26:10',150.00), (8,10,6,'2017-02-01 23:26:10',123.00), (9,11,1,'2017-02-02 23:43:30',150.00), (10,11,6,'2017-02-02 23:43:30',123.00), (11,12,1,'2017-02-02 23:43:57',150.00), (12,12,6,'2017-02-02 23:43:57',123.00), (13,13,1,'2017-02-02 23:54:39',150.00), (14,13,6,'2017-02-02 23:54:39',123.00); /*!40000 ALTER TABLE `detail` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla flowing # ------------------------------------------------------------ DROP TABLE IF EXISTS `flowing`; CREATE TABLE `flowing` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `flowing` WRITE; /*!40000 ALTER TABLE `flowing` DISABLE KEYS */; INSERT INTO `flowing` (`id`, `creation_date`, `description`) VALUES (1,'2017-01-20 00:00:00','Corriente'); /*!40000 ALTER TABLE `flowing` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla material # ------------------------------------------------------------ DROP TABLE IF EXISTS `material`; CREATE TABLE `material` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `material` WRITE; /*!40000 ALTER TABLE `material` DISABLE KEYS */; INSERT INTO `material` (`id`, `creation_date`, `description`) VALUES (1,'2917-01-20 00:00:00','Barro, Cerámica'); /*!40000 ALTER TABLE `material` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla mesure # ------------------------------------------------------------ DROP TABLE IF EXISTS `mesure`; CREATE TABLE `mesure` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `mesure` WRITE; /*!40000 ALTER TABLE `mesure` DISABLE KEYS */; INSERT INTO `mesure` (`id`, `creation_date`, `description`) VALUES (1,'2017-01-26 00:00:00','42.92 x 30.00 cm'); /*!40000 ALTER TABLE `mesure` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla picture # ------------------------------------------------------------ DROP TABLE IF EXISTS `picture`; CREATE TABLE `picture` ( `id` int(11) NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, `sort` varchar(2) DEFAULT '0', PRIMARY KEY (`id`), KEY `fk_picture_product1_idx` (`product_id`), CONSTRAINT `fk_picture_product1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `picture` WRITE; /*!40000 ALTER TABLE `picture` DISABLE KEYS */; INSERT INTO `picture` (`id`, `product_id`, `creation_date`, `description`, `sort`) VALUES (5,4,'2017-01-21 00:00:00','foto4.jpg','7'), (6,5,'2017-01-21 00:00:00','foto2.jpg','0'), (7,6,'2017-01-21 00:00:00','foto3.jpg','0'), (8,7,'2017-01-21 00:00:00','foto4.jpg','0'), (9,8,'2017-01-21 00:00:00','foto5.jpg','0'), (10,9,'2017-01-21 00:00:00','foto6.jpg','0'), (11,10,'2017-01-21 00:00:00','foto7.jpg','0'), (12,11,'2017-01-21 00:00:00','foto1.jpg','0'), (13,12,'2017-01-21 00:00:00','foto2.jpg','0'), (14,13,'2017-01-21 00:00:00','foto3.jpg','0'), (15,14,'2017-01-21 00:00:00','foto4.jpg','0'), (16,15,'2017-01-21 00:00:00','foto5.jpg','0'), (17,16,'2017-01-21 00:00:00','foto6.jpg','0'), (18,17,'2017-01-21 00:00:00','foto7.jpg','0'), (19,18,'2017-01-21 00:00:00','foto1.jpg','0'), (20,19,'2017-01-21 00:00:00','foto2.jpg','0'), (21,20,'2017-01-21 00:00:00','foto2.jpg','0'), (22,4,'2017-01-21 00:00:00','foto4-d.jpg','1'), (23,4,'2017-01-21 00:00:00','foto4-d2.jpg','2'), (24,4,'2017-01-21 00:00:00','foto4-d3.jpg','3'), (25,4,'2017-01-21 00:00:00','foto4-d4.jpg','4'); /*!40000 ALTER TABLE `picture` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla product # ------------------------------------------------------------ DROP TABLE IF EXISTS `product`; CREATE TABLE `product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `artist_id` int(11) NOT NULL, `category_id` int(11) NOT NULL, `creation_date` datetime NOT NULL, `description` varchar(255) NOT NULL DEFAULT '', `product_date` date DEFAULT NULL, `technique_id` int(11) NOT NULL, `material_id` int(11) NOT NULL, `flowing_id` int(11) NOT NULL, `support` varchar(45) DEFAULT NULL, `title` varchar(150) DEFAULT NULL, `important` enum('YES','NO') DEFAULT 'NO', `status` enum('ACTIVE','INACTIVE') DEFAULT 'ACTIVE', PRIMARY KEY (`id`), KEY `fk_product_artist1_idx` (`artist_id`), KEY `fk_product_category1_idx` (`category_id`), KEY `fk_product_technique1_idx` (`technique_id`), KEY `fk_product_material1_idx` (`material_id`), KEY `fk_product_flowing1_idx` (`flowing_id`), CONSTRAINT `fk_product_artist1` FOREIGN KEY (`artist_id`) REFERENCES `artist` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_category1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_flowing1` FOREIGN KEY (`flowing_id`) REFERENCES `flowing` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_material1` FOREIGN KEY (`material_id`) REFERENCES `material` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_technique1` FOREIGN KEY (`technique_id`) REFERENCES `technique` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `product` WRITE; /*!40000 ALTER TABLE `product` DISABLE KEYS */; INSERT INTO `product` (`id`, `artist_id`, `category_id`, `creation_date`, `description`, `product_date`, `technique_id`, `material_id`, `flowing_id`, `support`, `title`, `important`, `status`) VALUES (4,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 1','YES','ACTIVE'), (5,1,7,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 2','YES','ACTIVE'), (6,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 3','YES','ACTIVE'), (7,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 4','NO','ACTIVE'), (8,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 5','NO','ACTIVE'), (9,1,7,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 6','NO','ACTIVE'), (10,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 7','NO','ACTIVE'), (11,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 8','NO','ACTIVE'), (12,1,7,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 9','NO','ACTIVE'), (13,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 10','NO','ACTIVE'), (14,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 11','NO','ACTIVE'), (15,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 12','NO','ACTIVE'), (16,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 13','NO','ACTIVE'), (17,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 14','NO','ACTIVE'), (18,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 15','NO','ACTIVE'), (19,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 16','NO','ACTIVE'), (20,1,5,'2017-01-20 00:00:00',' <li>\n Papel estandar sin enmarcar\n </li>\n <li>\n Papel fotográfico RC de alta resolución,\n mínimo de 240 gr / m2 acabado brillo.\n </li>\n <li>\n Margen si','2017-01-20',1,1,1,NULL,'Anita Aarons 17','NO','ACTIVE'); /*!40000 ALTER TABLE `product` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla product_has_mesure_type # ------------------------------------------------------------ DROP TABLE IF EXISTS `product_has_mesure_type`; CREATE TABLE `product_has_mesure_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL, `mesure_id` int(11) NOT NULL, `price` double NOT NULL, `type_id` int(11) NOT NULL, `creation_date` datetime NOT NULL, `size` enum('S','M','L') DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_product_has_mesure_mesure1_idx` (`mesure_id`), KEY `fk_product_has_mesure_product1_idx` (`product_id`), KEY `fk_product_has_mesure_type1_idx` (`type_id`), CONSTRAINT `fk_product_has_mesure_mesure1` FOREIGN KEY (`mesure_id`) REFERENCES `mesure` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_has_mesure_product1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_product_has_mesure_type1` FOREIGN KEY (`type_id`) REFERENCES `type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `product_has_mesure_type` WRITE; /*!40000 ALTER TABLE `product_has_mesure_type` DISABLE KEYS */; INSERT INTO `product_has_mesure_type` (`id`, `product_id`, `mesure_id`, `price`, `type_id`, `creation_date`, `size`) VALUES (1,4,1,150,1,'2017-01-26 00:00:00','S'), (2,4,1,300,2,'2017-01-26 00:00:00','S'), (3,6,1,123,1,'2017-01-26 00:00:00','S'), (4,7,1,4141,1,'2017-01-26 00:00:00','S'), (5,8,1,1231,1,'2017-01-26 00:00:00','S'), (6,9,1,123,1,'2017-01-26 00:00:00','S'), (7,10,1,1255,1,'2017-01-26 00:00:00','S'), (8,6,1,300,2,'2017-01-26 00:00:00','S'), (9,6,1,150,1,'2017-01-26 00:00:00','S'); /*!40000 ALTER TABLE `product_has_mesure_type` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla technique # ------------------------------------------------------------ DROP TABLE IF EXISTS `technique`; CREATE TABLE `technique` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `description` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `technique` WRITE; /*!40000 ALTER TABLE `technique` DISABLE KEYS */; INSERT INTO `technique` (`id`, `creation_date`, `description`) VALUES (1,'2017-01-20 00:00:00','Técnica'); /*!40000 ALTER TABLE `technique` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla type # ------------------------------------------------------------ DROP TABLE IF EXISTS `type`; CREATE TABLE `type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `description` varchar(250) NOT NULL, `title` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `type` WRITE; /*!40000 ALTER TABLE `type` DISABLE KEYS */; INSERT INTO `type` (`id`, `creation_date`, `description`, `title`) VALUES (1,'2017-01-26 00:00:00','ORIGINAL','ORIGINAL'), (2,'2017-01-26 00:00:00','LAMINA','LAMINA'), (3,'2017-01-26 00:00:00','EDICIÓN LIMITADA','EDICIÓN LIMITADA'); /*!40000 ALTER TABLE `type` ENABLE KEYS */; UNLOCK TABLES; # Volcado de tabla user # ------------------------------------------------------------ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `creation_date` datetime NOT NULL, `username` varchar(150) NOT NULL DEFAULT '', `names` varchar(150) NOT NULL, `lastnames` varchar(150) NOT NULL, `birthday` date NOT NULL, `sex` enum('MALE','FEMALE') NOT NULL, `type` enum('CLIENT','ADMIN') NOT NULL, `password` varchar(255) NOT NULL, `auth_key` varchar(255) NOT NULL, `password_reset_token` varchar(255) DEFAULT NULL, `status` enum('ACTIVE','INACTIVE') DEFAULT 'INACTIVE', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` (`id`, `creation_date`, `username`, `names`, `lastnames`, `birthday`, `sex`, `type`, `password`, `auth_key`, `password_reset_token`, `status`) VALUES (3,'2017-01-24 16:26:39','frankpaul142@gmail.com','Franklin','Paula','1990-11-14','MALE','ADMIN','$2y$13$oXDX8ZMCOU96nittcDX7Fu3VsWn/12ZQAYrVIebracHXv5nBAjDL2','-zfRhEytHG1bdG0wZpv7bu4tC-ARyH7_','GPIOuYUaoWryKLtGs6sQBf0h3zSuB9pB_1485295008','ACTIVE'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
39.64259
354
0.598121
bd74ff68b19499a45cea26830aa1ae35d3003cd2
11,716
swift
Swift
Kapesni zachranar/Controller/Tools/ToolsChildBurnDetailVC.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
Kapesni zachranar/Controller/Tools/ToolsChildBurnDetailVC.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
Kapesni zachranar/Controller/Tools/ToolsChildBurnDetailVC.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
// // ToolsChildBurnDetailVC.swift // Kapesni zachranar // // Created by Tomáš Melichar on 17/04/2020. // Copyright © 2020 Tomáš Melichar. All rights reserved. // import UIKit import Swinject class ToolsChildBurnDetailVC: BasicViewController { public var containerDI: Container! { didSet { feedbackManager = containerDI.resolve(FeedbackManager.self, name: "FeedbackManager") } } public var nameForTitle: String! public var burnsChildItem: BurnsChildItem? public var frontBurnsOption: [BurnOptionStructure] = [] public var backBurnsOption: [BurnOptionStructure] = [] private var currentValueOfBurn: Double = 0.0 { didSet { self.precentLabelOutlet.text = "\(self.currentValueOfBurn) %" } } /// Private private var feedbackManager: FeedbackManager! /// Other UI @IBOutlet private weak var precentLabelOutlet: UILabel! @IBOutlet private weak var resetValueButtonOutlet: UIButton! @IBOutlet private weak var setWeightButtonOutlet: UIButton! @IBOutlet private weak var segmentedControlOutlet: UISegmentedControl! // MARK: Child front @IBOutlet private weak var childFrontHeadImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childFrontBodyImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childFrontRightArmImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childFrontLeftArmImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childFrontRightLegImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childFrontLeftLegImageOutlet: TMImageDetailUIImageView! @IBOutlet private var childFrontImagesOutletCollection: [TMImageDetailUIImageView]! /// Front child collection of image // MARK: Child back @IBOutlet private weak var childBackHeadImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackBodyImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackRightArmImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackLeftArmImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackRightAssImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackLeftAssImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackRightLegImageOutlet: TMImageDetailUIImageView! @IBOutlet private weak var childBackLeftLegImageOutlet: TMImageDetailUIImageView! @IBOutlet private var backChildImageOutletCollection: [TMImageDetailUIImageView]! /// Back child collection of image override func viewDidLoad() { super.viewDidLoad() configureUI() } override func configureUI() { self.title = nameForTitle setDefaultImageToUIView(isSelected: false) super.configureAndSetPowerMode(isOn: true) resetValueButtonOutlet.setTitle(NSLocalizedString("titleReset", comment: ""), for: .normal) setWeightButtonOutlet.setTitle(NSLocalizedString("tools_setWeight", comment: ""), for: .normal) segmentedControlOutlet.setTitle(NSLocalizedString("tools_segmentedControlerFront", comment: ""), forSegmentAt: 0) segmentedControlOutlet.setTitle(NSLocalizedString("tools_segmentedControlerBack", comment: ""), forSegmentAt: 1) precentLabelOutlet.text = "\(currentValueOfBurn) %" showSectionChild(position: 0) self.navigationController?.navigationBar.topItem?.backBarButtonItem = super.returnBackButtonForNavigationBar(with: nil) /// Front for index in 0...burnsChildItem!.burnsFrontItem.count-1 { self.frontBurnsOption.append(BurnOptionStructure(name: self.burnsChildItem!.burnsFrontItem[index].name, valuePrecent: self.burnsChildItem!.burnsFrontItem[index].value, isAdult: false, isSelected: false, childBurnNameImage: TMChildBurnNameImage(rawValue: TMChildBurnNameImage.allNameImage[index]), adultBurnNameImage: nil)) } let maxIndexFrontPosition: Int = burnsChildItem!.burnsFrontItem.count /// Back for index in 0...burnsChildItem!.burnsBackItem.count-1 { self.backBurnsOption.append(BurnOptionStructure(name: self.burnsChildItem!.burnsBackItem[index].name, valuePrecent: self.burnsChildItem!.burnsBackItem[index].value, isAdult: false, isSelected: false, childBurnNameImage: TMChildBurnNameImage(rawValue: TMChildBurnNameImage.allNameImage[maxIndexFrontPosition + index]), adultBurnNameImage: nil)) } } @IBAction func positionSegmentedControlerAction(_ sender: UISegmentedControl) { feedbackManager.selectFeedback() showSectionChild(position: sender.selectedSegmentIndex) } func showSectionChild(position: Int) { switch position { case 0: hideSection(collectionImage: childFrontImagesOutletCollection, isHidden: false, alpha: 1) hideSection(collectionImage: backChildImageOutletCollection, isHidden: true, alpha: 0) case 1: hideSection(collectionImage: backChildImageOutletCollection, isHidden: false, alpha: 1) hideSection(collectionImage: childFrontImagesOutletCollection, isHidden: true, alpha: 0) default: break } } /// Show or hide sectoon of selection public func hideSection(collectionImage: [TMImageDetailUIImageView], isHidden: Bool, alpha: CGFloat) { collectionImage.forEach { $0.alpha = alpha $0.isHidden = isHidden } } @IBAction func setWeightButtonAction(_ sender: UIButton) { feedbackManager.selectFeedback() performSegue(withIdentifier: segueBurnsToResults, sender: self) } @IBAction func resetPrecentButtonAction(_ sender: UIButton) { feedbackManager.succesFeedback() currentValueOfBurn = 0 precentLabelOutlet.text = "\(currentValueOfBurn) %" setDefaultImageToUIView(isSelected: false) /// Front for position in 0...frontBurnsOption.count-1 { frontBurnsOption[position].isSelected = false } /// Back for position in 0...backBurnsOption.count-1 { backBurnsOption[position].isSelected = false } } @IBAction func addBurnItemsBarButtonAction(_ sender: UIBarButtonItem) { feedbackManager.selectFeedback() performSegue(withIdentifier: segeuBurnsToOptions, sender: self) } func setDefaultImageToUIView(isSelected: Bool) { childFrontHeadImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_Head, isSelected: isSelected) childFrontBodyImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_Body, isSelected: isSelected) childFrontRightArmImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_RightArm, isSelected: isSelected) childFrontLeftArmImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_LeftArm, isSelected: isSelected) childFrontRightLegImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_RightLeg, isSelected: isSelected) childFrontLeftLegImageOutlet.setBurnImage(childBurnNameImage: .ChildFront_LeftLeg, isSelected: isSelected) childBackHeadImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_Head, isSelected: isSelected) childBackBodyImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_Body, isSelected: isSelected) childBackRightArmImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_RightArm, isSelected: isSelected) childBackLeftArmImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_LeftArm, isSelected: isSelected) childBackRightAssImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_RightAss, isSelected: isSelected) childBackLeftAssImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_LeftAss, isSelected: isSelected) childBackRightLegImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_RightLeg, isSelected: isSelected) childBackLeftLegImageOutlet.setBurnImage(childBurnNameImage: .ChildBack_LeftLeg, isSelected: isSelected) } func changeStateBurnImage(current image: TMChildBurnNameImage, isSelected: Bool) { switch image { case .ChildFront_Head: childFrontHeadImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildFront_Body: childFrontBodyImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildFront_RightArm: childFrontRightArmImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildFront_LeftArm: childFrontLeftArmImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildFront_RightLeg: childFrontRightLegImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildFront_LeftLeg: childFrontLeftLegImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_Head: childBackHeadImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_Body: childBackBodyImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_RightArm: childBackRightArmImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_LeftArm: childBackLeftArmImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_RightAss: childBackRightAssImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_LeftAss: childBackLeftAssImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_RightLeg: childBackRightLegImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) case .ChildBack_LeftLeg: childBackLeftLegImageOutlet.setBurnImage(childBurnNameImage: image, isSelected: isSelected) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let resultVC = segue.destination as? ToolsCalcResultVC { // super.assignVariableToNextVC(for: resultVC) resultVC.containerDI = containerDI resultVC.currentValueOfBurn = self.currentValueOfBurn }else if let burnsOptionVC = segue.destination as? BurnsOptionVC { burnsOptionVC.frontBurnsOption = self.frontBurnsOption burnsOptionVC.backBurnsOption = self.backBurnsOption burnsOptionVC.currentValueOfBurn = self.currentValueOfBurn // super.assignVariableToNextVC(for: burnsOptionVC) burnsOptionVC.containerDI = containerDI burnsOptionVC.delegateSendDataToChild = self } } } extension ToolsChildBurnDetailVC: TMSendDataToChildProtocol { func passDataToChildBurnVC(front: [BurnOptionStructure], back: [BurnOptionStructure], precentValue: Double) { self.frontBurnsOption = [] self.backBurnsOption = [] self.currentValueOfBurn = precentValue self.frontBurnsOption = front self.backBurnsOption = back /// Front frontBurnsOption.forEach { self.changeStateBurnImage(current: $0.childBurnNameImage!, isSelected: $0.isSelected) } /// Back backBurnsOption.forEach { self.changeStateBurnImage(current: $0.childBurnNameImage!, isSelected: $0.isSelected) } feedbackManager.succesFeedback() } }
54.493023
355
0.738307
6c891e086cb53e908ff5f9507275dbdb3a3a07dc
775
kt
Kotlin
webapp-common/src/main/kotlin/net/corda/server/CorsConfiguration.kt
yunxi-zhang/Corda
9af4854e0628974915602b36a05b864dd2992ac8
[ "Apache-2.0" ]
null
null
null
webapp-common/src/main/kotlin/net/corda/server/CorsConfiguration.kt
yunxi-zhang/Corda
9af4854e0628974915602b36a05b864dd2992ac8
[ "Apache-2.0" ]
null
null
null
webapp-common/src/main/kotlin/net/corda/server/CorsConfiguration.kt
yunxi-zhang/Corda
9af4854e0628974915602b36a05b864dd2992ac8
[ "Apache-2.0" ]
null
null
null
package net.corda.server import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.CorsRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration open class CorsConfiguration { @Bean open fun corsConfigurer(): WebMvcConfigurer { return object : WebMvcConfigurerAdapter() { override fun addCorsMappings(registry: CorsRegistry) { registry.addMapping("/**") .allowedOrigins( "*" ) } } } }
32.291667
80
0.663226
f11651c2cca8d50b968c59afc87fe79c7850e00a
2,948
rb
Ruby
test/buildmaster/common/tc_tree_to_object.rb
wolfdancer/buildmaster
74d81f7597986cb6f171bf474b8285064a81798c
[ "Apache-2.0" ]
1
2016-05-08T12:37:33.000Z
2016-05-08T12:37:33.000Z
test/buildmaster/common/tc_tree_to_object.rb
wolfdancer/buildmaster
74d81f7597986cb6f171bf474b8285064a81798c
[ "Apache-2.0" ]
null
null
null
test/buildmaster/common/tc_tree_to_object.rb
wolfdancer/buildmaster
74d81f7597986cb6f171bf474b8285064a81798c
[ "Apache-2.0" ]
null
null
null
require 'spec' require File.dirname(__FILE__) + '/../../../lib/buildmaster/common/tree_to_object' module BuildMaster class SampleObject attr_reader :field_one, :field_two, :object_two, :array_field attr_writer :field_one, :field_two def initialize @object_two = SampleTwo.new @array_field = Array.new end def add_to_array_field item = SampleTwo.new @array_field.push(item) return item end end class SampleTwo attr_reader :field, :index attr_writer :field, :index end describe TreeToObject do it 'should_populate_string_fields' do content = <<CONTENT field_one: value_one field_two: value_two CONTENT tree = YAML.load(content) object = SampleObject.new TreeToObject.new(tree, object).convert object.field_one.should == 'value_one' object.field_two.should == 'value_two' end it 'should_populate_array_fields' do content = <<CONTENT array_field: - field: valueone index: 1 - field: valuetwo index: 2 CONTENT object = TreeToObject.from_yaml(content, SampleObject.new) array = object.array_field array.size.should == 2 array[0].field.should == 'valueone' array[0].index.to_s.should == '1' array[1].field.should == 'valuetwo' array[1].index.to_s.should == '2' end it 'should_populate_instance_fields' do content = <<CONTENT object_two: field: my_field index: 5 CONTENT object = TreeToObject.from_yaml(content, SampleObject.new) actual = object.object_two actual.field.should == 'my_field' actual.index.to_s.should == '5' end it 'should_raise_error_if_property_not_found' do content = <<CONTENT not_field: value CONTENT begin object = TreeToObject.from_yaml(content, SampleObject.new) fail('exception should have been thrown') rescue PropertyMatchError => error error.message.include?('not_field').should == true error.message.include?('string').should == true end end it 'should_raise_error_if_sub_property_not_found' do content = <<CONTENT not_sub_property: field: value CONTENT begin object = TreeToObject.from_yaml(content, SampleObject.new) fail('exception should have been thrown') rescue PropertyMatchError => error error.message.include?('not_sub_property').should == true error.message.include?('sub property').should == true end end it 'should_raise_error_if_array_property_not_found' do content = <<CONTENT not_array_property: - name: title - name: title CONTENT begin object = TreeToObject.from_yaml(content, SampleObject.new) fail('exception should have been thrown') rescue PropertyMatchError => error error.message.include?('not_array_property').should == true error.message.include?('array').should == true end end it 'empty_content' do object = TreeToObject.from_yaml('', SampleObject.new) object.field_one.should == nil end end end
24.566667
82
0.708616
6b798bd0a625aa1b3fd3d70de0924f6c820e1063
1,268
lua
Lua
BGAnimations/ScreenGameplay decorations/default.lua
excessive/danfordmania
68c9e774985b6020bda36538dc932f00fb69620e
[ "MIT" ]
5
2015-10-22T21:53:16.000Z
2021-05-31T13:09:25.000Z
BGAnimations/ScreenGameplay decorations/default.lua
excessive/danfordmania
68c9e774985b6020bda36538dc932f00fb69620e
[ "MIT" ]
null
null
null
BGAnimations/ScreenGameplay decorations/default.lua
excessive/danfordmania
68c9e774985b6020bda36538dc932f00fb69620e
[ "MIT" ]
null
null
null
local frame = LoadFallbackB() table.insert(frame, StandardDecorationFromFile("StageFrame", "StageFrame")) table.insert(frame, Def.Sprite { Texture = "_warning", InitCommand = function(self) self :xy(SCREEN_CENTER_X, SCREEN_CENTER_Y) :vertalign(top) :wag() :effectmagnitude(0, 0, 10) :effectperiod(2) end, OnCommand = function(self) self:diffusealpha(0) end, ShowDangerAllMessageCommand = function(self) self :stoptweening() :accelerate(0.3) :diffusealpha(1) end, HideDangerAllMessageCommand = function(self) self :stoptweening() :accelerate(0.3) :diffusealpha(0) end }) table.insert(frame, StandardDecorationFromFile("LifeFrame", "LifeFrame")) --[[ table.insert(frame, StandardDecorationFromFile("ScoreFrame", "ScoreFrame")) table.insert(frame, StandardDecorationFromFile("LeftFrame", "LeftFrame")) table.insert(frame, StandardDecorationFromFile("RightFrame", "RightFrame")) if ShowStandardDecoration("ModIconRows") then for pn in ivalues(PlayerNumber) do table.insert(frame, StandardDecorationFromTable("ModIconRow" .. ToEnumShortString(pn), Def.ModIconRow { InitCommand = function(self) self:Load("ModIconRowGameplay" .. ToEnumShortString(pn), pn) end }) ) end end --]] return frame
23.924528
75
0.731073
f54c42cc2d356334800143c1cbcb7472924ed750
1,213
cpp
C++
src/private/renderer.cpp
seanchas116/Malachite
51370497148201b23aa2b78dff27e88c6038955c
[ "MIT" ]
2
2017-04-21T07:22:37.000Z
2018-04-27T03:51:03.000Z
src/private/renderer.cpp
seanchas116/Malachite
51370497148201b23aa2b78dff27e88c6038955c
[ "MIT" ]
null
null
null
src/private/renderer.cpp
seanchas116/Malachite
51370497148201b23aa2b78dff27e88c6038955c
[ "MIT" ]
null
null
null
#include "renderer.h" namespace Malachite { unsigned QPainterPath_vs::vertex(double *x, double *y) { forever { if (_subdIndex) { if (_subdIndex == _subdPolygon.size()) { _subdIndex = 0; continue; } const Vec2D p = _subdPolygon.at(_subdIndex); *x = p.x(); *y = p.y(); _subdIndex++; _totalCount++; return agg::path_cmd_line_to; } if (_index == _path.elementCount()) // path終わり return agg::path_cmd_stop; const QPainterPath::Element element = _path.elementAt(_index); if (element.type == QPainterPath::CurveToElement) { QPainterPath::Element e1, e2, e3, e4; e1 = _path.elementAt(_index - 1); e2 = _path.elementAt(_index); e3 = _path.elementAt(_index + 1); e4 = _path.elementAt(_index + 2); _subdPolygon = CurveSubdivision(Vec2D(e1.x, e1.y), Vec2D(e2.x, e2.y), Vec2D(e3.x, e3.y), Vec2D(e4.x, e4.y)).polygon(); _subdIndex = 1; _index += 3; continue; } _index++; *x = element.x; *y = element.y; _totalCount++; switch (element.type) { case QPainterPath::MoveToElement: return agg::path_cmd_move_to; case QPainterPath::LineToElement: default: return agg::path_cmd_line_to; } } } }
19.253968
121
0.629843
dda8526a093f3bf4ba91eb803f8b039b9449461f
899
kt
Kotlin
Android/Simplebudget/app/src/main/java/com/simplebudget/view/welcome/Onboarding1Fragment.kt
WaheedNazir/EasyBudget
35cd2268485b18d020e4a241bcfc4ca66e78606c
[ "Apache-2.0" ]
3
2021-10-01T10:00:29.000Z
2022-01-05T21:52:45.000Z
Android/Simplebudget/app/src/main/java/com/simplebudget/view/welcome/Onboarding1Fragment.kt
WaheedNazir/EasyBudget
35cd2268485b18d020e4a241bcfc4ca66e78606c
[ "Apache-2.0" ]
null
null
null
Android/Simplebudget/app/src/main/java/com/simplebudget/view/welcome/Onboarding1Fragment.kt
WaheedNazir/EasyBudget
35cd2268485b18d020e4a241bcfc4ca66e78606c
[ "Apache-2.0" ]
null
null
null
package com.simplebudget.view.welcome import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.simplebudget.R import kotlinx.android.synthetic.main.fragment_onboarding1.* /** * Onboarding step 1 fragment * * @author Benoit LETONDOR */ class Onboarding1Fragment : OnboardingFragment() { override val statusBarColor: Int get() = R.color.primary_dark override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_onboarding1, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) onboarding_screen1_next_button.setOnClickListener { next(onboarding_screen1_next_button) } } }
27.242424
116
0.747497
bb60d554596ed99cc46ff10cecc685a0fd7ce09c
197
psd1
PowerShell
data/AzureAD/New-AzureADTrustedCertificateAuthority.psd1
FriedrichWeinmann/PSAzureMigrationAdvisor
e4e512a595246e1d1cdf1e9cfafe6121dca61758
[ "MIT" ]
16
2022-03-13T13:42:56.000Z
2022-03-31T08:59:39.000Z
data/AzureAD/New-AzureADTrustedCertificateAuthority.psd1
FriedrichWeinmann/PSAzureMigrationAdvisor
e4e512a595246e1d1cdf1e9cfafe6121dca61758
[ "MIT" ]
null
null
null
data/AzureAD/New-AzureADTrustedCertificateAuthority.psd1
FriedrichWeinmann/PSAzureMigrationAdvisor
e4e512a595246e1d1cdf1e9cfafe6121dca61758
[ "MIT" ]
1
2022-03-14T13:12:57.000Z
2022-03-14T13:12:57.000Z
@{ 'New-AzureADTrustedCertificateAuthority' = @{ Name = 'New-AzureADTrustedCertificateAuthority' MsgError = 'No Graph counterpart known for New-AzureADTrustedCertificateAuthority' } }
32.833333
84
0.756345
66e701a67f9c7b83838c4a2fc120e45f29599404
344
html
HTML
app/views/blocks/comboboxblock.scala.html
tsvhun/infostroy
a1c608f9de34ac3617596a72be5a410e868c2ac2
[ "Apache-2.0" ]
null
null
null
app/views/blocks/comboboxblock.scala.html
tsvhun/infostroy
a1c608f9de34ac3617596a72be5a410e868c2ac2
[ "Apache-2.0" ]
null
null
null
app/views/blocks/comboboxblock.scala.html
tsvhun/infostroy
a1c608f9de34ac3617596a72be5a410e868c2ac2
[ "Apache-2.0" ]
null
null
null
@(field: models.Field) <div class="block"> @field.getLabel@if(field.isRequired==true){*} <select class=" @if(field.isRequired==true){required='requried'} form-control combo" name="@field.getFieldId"> @for(option <- field.getOptions) { <option value="@option.getId">@option.getName</option> } </select> </div>
38.222222
114
0.639535
c12ce8e758183501920d02b1653000792fce38be
1,522
ps1
PowerShell
Alba/LateEmailerFunction/run.ps1
territorytools/territory-tools
540a4f448dfe716597f53b1a3dbf64580fc5d868
[ "MIT" ]
1
2021-08-20T11:59:32.000Z
2021-08-20T11:59:32.000Z
Alba/LateEmailerFunction/run.ps1
territorytools/territory-tools
540a4f448dfe716597f53b1a3dbf64580fc5d868
[ "MIT" ]
3
2020-07-28T20:40:07.000Z
2020-11-19T17:50:40.000Z
Alba/LateEmailerFunction/run.ps1
territorytools/territorytools
540a4f448dfe716597f53b1a3dbf64580fc5d868
[ "MIT" ]
null
null
null
# Input bindings are passed in via param block. param($Timer) # Get the current universal time in the default string format. $currentUTCtime = (Get-Date).ToUniversalTime() # The 'IsPastDue' property is 'true' when the current function invocation is later than scheduled. if ($Timer.IsPastDue) { Write-Host "PowerShell timer is running late!" } # Write an information log with the current time. Write-Host "PowerShell timer trigger function ran! TIME: $currentUTCtime" $ErrorActionPreference = "Stop" Write-Host "Importing TerritoryTools module from folder..." Import-Module "$PSScriptRoot\TerritoryTools\TerritoryTools.dll"; Write-Host "Importing TerritoryTools *.psm1 modules from folder..." Import-Module "$PSScriptRoot\TerritoryTools\*.psm1" Write-Host "Getting password from key vault..." $albaPassword = Get-AzKeyVaultSecret -VaultName TerritoryToolsEmailer -Name "ALBA-PASSWORD" -AsPlainText $env:ALBA_PASSWORD = $albaPassword Write-Host "Getting SendGrid API Key from key vault..." $sendGridApiKey = Get-AzKeyVaultSecret -VaultName TerritoryToolsEmailer -Name "SEND-GRID-API-KEY" -AsPlainText $env:SENDGRID_API_KEY = $sendGridApiKey Write-Host "Connecting to Alba..." Get-AlbaConnection -AlbaHost $env:ALBA_HOST -Account $env:ALBA_ACCOUNT -User $env:ALBA_USER -Password $albaPassword Write-Host "Start file generating script..." & $PSScriptRoot\Stage-1-GenerateUserReportFiles.ps1 Write-Host "Sending emails from Outbox..." & $PSScriptRoot\Stage-2-SendOneEmailPerFile.ps1 -Confirm Write-Host "Done"
38.05
115
0.785151
752922ef64e1787fe65167ab2694b3439ee3b58f
4,315
cs
C#
Numeric/BigIntegerExt.cs
chaowlert/algorithm
7b00ab1f620361584393cf39b133ed4938d1cda5
[ "MIT" ]
3
2018-02-08T11:56:23.000Z
2020-11-28T01:01:59.000Z
Numeric/BigIntegerExt.cs
chaowlert/algorithm
7b00ab1f620361584393cf39b133ed4938d1cda5
[ "MIT" ]
null
null
null
Numeric/BigIntegerExt.cs
chaowlert/algorithm
7b00ab1f620361584393cf39b133ed4938d1cda5
[ "MIT" ]
3
2016-07-24T02:46:16.000Z
2018-12-30T13:30:51.000Z
using System; using System.Numerics; namespace Chaow.Numeric { public static class BigIntegerExt { public static BigInteger Abs(this BigInteger num) { if (num.Sign < 0) return -num; return num; } public static BigInteger Power(this BigInteger num, int pow) { if (pow < 0) throw new ArgumentOutOfRangeException("pow", "pow cannot be negative"); var result = BigInteger.One; while (pow != 0) { if ((pow & 1) == 1) { result *= num; if (pow == 1) return result; } num *= num; pow >>= 1; } return result; } public static BigInteger Power(this BigInteger num, long pow) { if (pow < 0L) throw new ArgumentOutOfRangeException("pow", "pow cannot be negative"); var result = BigInteger.One; while (pow != 0L) { if ((pow & 1L) == 1L) { result *= num; if (pow == 1L) return result; } num *= num; pow >>= 1; } return result; } public static BigInteger Power(this BigInteger num, BigInteger pow) { if (pow.Sign < 0) throw new ArgumentOutOfRangeException("pow", "pow cannot be negative"); var result = BigInteger.One; while (!pow.IsZero) { if (!pow.IsEven) { result *= num; if (pow == BigInteger.One) return result; } num *= num; pow >>= 1; } return result; } public static BigInteger ModPow(this BigInteger num, BigInteger pow, BigInteger mod) { if (pow < 0) throw new ArgumentOutOfRangeException("pow", "pow cannot be negative"); var result = BigInteger.One; while (!pow.IsZero) { num %= mod; if (!pow.IsEven) { result = (result * num) % mod; if (pow == BigInteger.One) return result; } num *= num; pow >>= 1; } return result; } public static BigInteger Gcd(BigInteger a, BigInteger b) { while (!b.IsZero) { var r = a % b; a = b; b = r; } return a; } public static BigInteger Lcm(BigInteger a, BigInteger b) { return (b / Gcd(a, b)) * a; } static readonly BigInteger Two = 2; public static BigInteger Sqrt(this BigInteger num) { if (num.Sign < 0) throw new ArgumentOutOfRangeException("num", "num cannot be negative"); if (num.IsZero) return BigInteger.Zero; var x = num; var y = (x + BigInteger.One) / Two; while (y < x) { x = y; y = (x + (num / x)) / Two; } return x; } public static BigInteger Mod(this BigInteger num, BigInteger mod) { var num2 = num % mod; if (num2.Sign < 0 == mod.Sign > 0) return num2 + mod; return num2; } public static BigInteger[] ExtGcd(BigInteger m, BigInteger n) { var ma = new[] {m, BigInteger.One, BigInteger.Zero}; var na = new[] {n, BigInteger.Zero, BigInteger.One}; while (!na[0].IsZero) { var q = ma[0] / na[0]; for (var i = 0; i < 3; i++) { var r = ma[i] - q * na[i]; ma[i] = na[i]; na[i] = r; } } return ma; } } }
27.660256
92
0.393975
9b1f663d25439f444d32e695f6a2efec5ef2760a
53
sql
SQL
appng-core/src/main/resources/db/migration/mssql/V2_7__modify_resource_name.sql
appNG/appng
1027d46779f07f7ed94faf280b84d01d01d0b962
[ "ECL-2.0", "Apache-2.0" ]
35
2017-06-29T21:37:41.000Z
2022-02-06T04:08:53.000Z
appng-core/src/main/resources/db/migration/mssql/V2_7__modify_resource_name.sql
appNG/appng
1027d46779f07f7ed94faf280b84d01d01d0b962
[ "ECL-2.0", "Apache-2.0" ]
41
2017-11-06T11:03:39.000Z
2022-03-08T21:13:18.000Z
appng-core/src/main/resources/db/migration/mssql/V2_7__modify_resource_name.sql
appNG/appng
1027d46779f07f7ed94faf280b84d01d01d0b962
[ "ECL-2.0", "Apache-2.0" ]
16
2017-07-18T15:45:09.000Z
2022-03-29T15:06:35.000Z
alter table resource alter column name nvarchar(255);
53
53
0.830189
fbd5a2fd9deed7996e47c76bdcfd5e98446d3141
13,834
java
Java
src/main/java/com/mobiusflip/crimsonrevelations/recipes/CrimsonRecipes.java
Determancer/CrimsonRevelations
bb0d5020835d564b7f6178b7b7471d1c08831209
[ "MIT" ]
1
2020-06-06T17:50:39.000Z
2020-06-06T17:50:39.000Z
src/main/java/com/mobiusflip/crimsonrevelations/recipes/CrimsonRecipes.java
Determancer/CrimsonRevelations
bb0d5020835d564b7f6178b7b7471d1c08831209
[ "MIT" ]
2
2020-01-30T14:24:11.000Z
2022-03-07T22:33:21.000Z
src/main/java/com/mobiusflip/crimsonrevelations/recipes/CrimsonRecipes.java
Determancer/CrimsonRevelations
bb0d5020835d564b7f6178b7b7471d1c08831209
[ "MIT" ]
2
2020-12-12T09:58:41.000Z
2021-08-18T19:57:24.000Z
package com.mobiusflip.crimsonrevelations.recipes; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemMonsterPlacer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import thaumcraft.api.ThaumcraftApi; import thaumcraft.api.ThaumcraftApiHelper; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.api.blocks.BlocksTC; import thaumcraft.api.crafting.CrucibleRecipe; import thaumcraft.api.crafting.InfusionRecipe; import thaumcraft.api.crafting.ShapedArcaneRecipe; import thaumcraft.api.items.ItemsTC; import thaumcraft.api.research.ResearchCategories; public class CrimsonRecipes { public static void initRecipes() { initInfusion(); initCrucible(); initArcaneCrafting(); } private static void initInfusion() { ThaumcraftApi.addInfusionCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimsonblade"), new InfusionRecipe("CRIMSON_BLADE", new ItemStack(ItemsTC.crimsonBlade), 7, new AspectList().add(Aspect.AVERSION, 75).add(Aspect.DEATH, 75).add(Aspect.TRAP, 25).add(Aspect.DESIRE, 25), new ItemStack(ItemsTC.voidSword), new Object[] { ThaumcraftApiHelper.makeCrystal(Aspect.AVERSION), ThaumcraftApiHelper.makeCrystal(Aspect.DEATH), new ItemStack(ItemsTC.plate, 1, 3), BlocksTC.bannerCrimsonCult } )); ThaumcraftApi.addInfusionCraftingRecipe(new ResourceLocation("crimsonrevelations", "praetor_helm"), new InfusionRecipe("PRAETOR_ARMOR", new ItemStack(ItemsTC.crimsonPraetorHelm), 2, new AspectList().add(Aspect.METAL, 50).add(Aspect.ELDRITCH, 25).add(Aspect.PROTECT, 20), new ItemStack(ItemsTC.crimsonPlateHelm), new Object[] { new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 0), new ItemStack(ItemsTC.plate, 1, 0), BlocksTC.bannerCrimsonCult } )); ThaumcraftApi.addInfusionCraftingRecipe(new ResourceLocation("crimsonrevelations", "praetor_chestplate"), new InfusionRecipe("PRAETOR_ARMOR", new ItemStack(ItemsTC.crimsonPraetorChest), 2, new AspectList().add(Aspect.METAL, 50).add(Aspect.ELDRITCH, 25).add(Aspect.PROTECT, 30), new ItemStack(ItemsTC.crimsonPlateChest), new Object[] { new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 0), BlocksTC.bannerCrimsonCult } )); ThaumcraftApi.addInfusionCraftingRecipe(new ResourceLocation("crimsonrevelations", "praetor_greaves"), new InfusionRecipe("PRAETOR_ARMOR", new ItemStack(ItemsTC.crimsonPraetorLegs), 2, new AspectList().add(Aspect.METAL, 50).add(Aspect.ELDRITCH, 25).add(Aspect.PROTECT, 25), new ItemStack(ItemsTC.crimsonPlateLegs), new Object[] { new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 0), BlocksTC.bannerCrimsonCult } )); ItemStack crabStack = new ItemStack(Items.SPAWN_EGG); ItemMonsterPlacer.applyEntityIdToItemStack(crabStack, new ResourceLocation("thaumcraft", "eldritchcrab")); ThaumcraftApi.addInfusionCraftingRecipe(new ResourceLocation("crimsonrevelations", "eldritchcrab"), new InfusionRecipe("PRAETOR_ARMOR", crabStack, 9, new AspectList().add(Aspect.UNDEAD, 50).add(Aspect.ELDRITCH, 75).add(Aspect.PROTECT, 50), new ItemStack(ItemsTC.voidSeed), new Object[] { new ItemStack(Items.ENDER_EYE), new ItemStack(BlocksTC.stoneAncientGlyphed), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 0), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(ItemsTC.plate, 1, 1), new ItemStack(BlocksTC.stoneAncientGlyphed) } )); } private static void initCrucible() { ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "ancientstone"), new CrucibleRecipe("ANCIENT_STONE", new ItemStack(BlocksTC.stoneAncient), new ItemStack(BlocksTC.stoneArcane), new AspectList().add(Aspect.ELDRITCH, 5).add(Aspect.EARTH, 5))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropyblazepowder"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.BLAZE_POWDER, 4, 0), new ItemStack(Items.BLAZE_ROD), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropybonemeal"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.DYE, 6, 15), new ItemStack(Items.BONE), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropysunflower"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.DYE, 4, 11), new ItemStack(Blocks.DOUBLE_PLANT, 1, 0), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropylilac"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.DYE, 4, 13), new ItemStack(Blocks.DOUBLE_PLANT, 1, 1), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropyrose"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.DYE, 4, 1), new ItemStack(Blocks.DOUBLE_PLANT, 1, 4), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropypeony"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.DYE, 4, 9), new ItemStack(Blocks.DOUBLE_PLANT, 1, 5), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "entropysugar"), new CrucibleRecipe("ENTROPIC_PROCESSING", new ItemStack(Items.SUGAR, 2, 0), new ItemStack(Items.REEDS, 1, 0), new AspectList().add(Aspect.ENTROPY, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "orderwool"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.STRING, 4, 0), new ItemStack(Blocks.WOOL, 1, 0), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "orderbrick"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.BRICK, 4, 0), new ItemStack(Blocks.BRICK_BLOCK), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "ordernetherbrick"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.NETHERBRICK, 4, 0), new ItemStack(Blocks.NETHER_BRICK), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "orderquartz"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.QUARTZ, 4, 0), new ItemStack(Blocks.QUARTZ_BLOCK), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "orderprismarine"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.PRISMARINE_SHARD, 9, 0), new ItemStack(Blocks.PRISMARINE, 1, 1), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "orderchorus"), new CrucibleRecipe("ORDERED_DECONSTRUCTION", new ItemStack(Items.CHORUS_FRUIT_POPPED, 4, 0), new ItemStack(Blocks.PURPUR_BLOCK), new AspectList().add(Aspect.ORDER, 25))); ThaumcraftApi.addCrucibleRecipe(new ResourceLocation("crimsonrevelations", "quartzcluster"), new CrucibleRecipe("QUARTZ_PURIFICATION", new ItemStack(ItemsTC.clusters, 1, 7), "oreQuartz", new AspectList().add(Aspect.ORDER, 5).add(Aspect.CRYSTAL, 5))); } private static void initArcaneCrafting() { ResourceLocation defaultGroup = new ResourceLocation(""); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimsonbanner"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_REVELATIONS", 10, new AspectList(), new ItemStack(BlocksTC.bannerCrimsonCult), new Object[] { "WS", "IS", "WD", 'S', Items.STICK, 'D', new ItemStack(Blocks.WOODEN_SLAB), 'W', new ItemStack(Blocks.WOOL, 1, 14), 'I', new ItemStack(BlocksTC.inlay) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "ancientstonetile"), new ShapedArcaneRecipe( defaultGroup, "ANCIENT_STONE", 5, new AspectList(), new ItemStack(BlocksTC.stoneAncientTile), new Object[] { "SS", "SS", 'S', BlocksTC.stoneAncient } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "glyphstone"), new ShapedArcaneRecipe( defaultGroup, "ANCIENT_STONE", 15, new AspectList().add(Aspect.ORDER, 1).add(Aspect.EARTH, 1), new ItemStack(BlocksTC.stoneAncientGlyphed, 6, 0), new Object[] { "SBS", "SBS", "SBS", 'S', BlocksTC.stoneAncient, 'B', Blocks.BOOKSHELF } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_helm"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 25, new AspectList().add(Aspect.FIRE, 1), new ItemStack(ItemsTC.crimsonPlateHelm), new Object[] { "IBI", "I I", 'I', new ItemStack(ItemsTC.plate, 1, 1), 'B', new ItemStack(ItemsTC.plate, 1, 0) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_chestplate"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 25, new AspectList().add(Aspect.FIRE, 1), new ItemStack(ItemsTC.crimsonPlateChest), new Object[] { "I I", "WBW", "III", 'I', new ItemStack(ItemsTC.plate, 1, 1), 'B', new ItemStack(BlocksTC.bannerCrimsonCult), 'W', new ItemStack(Blocks.WOOL, 1, 14) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_greaves"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 25, new AspectList().add(Aspect.FIRE, 1), new ItemStack(ItemsTC.crimsonPlateLegs), new Object[] { "WBW", "I I", "I I", 'I', new ItemStack(ItemsTC.plate, 1, 1), 'B', new ItemStack(BlocksTC.bannerCrimsonCult), 'W', new ItemStack(Blocks.WOOL, 1, 14) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_hood"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 50, new AspectList().add(Aspect.FIRE, 1).add(Aspect.AIR, 1).add(Aspect.ENTROPY, 1), new ItemStack(ItemsTC.crimsonRobeHelm), new Object[] { "FBF", "F F", 'F', ItemsTC.fabric, 'B', new ItemStack(BlocksTC.bannerCrimsonCult) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_robes"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 50, new AspectList().add(Aspect.FIRE, 1).add(Aspect.AIR, 1).add(Aspect.ENTROPY, 1), new ItemStack(ItemsTC.crimsonRobeChest), new Object[] { "F F", "IBI", "FWF", 'F', ItemsTC.fabric, 'B', new ItemStack(BlocksTC.bannerCrimsonCult), 'I', new ItemStack(ItemsTC.plate, 1, 1), 'W', new ItemStack(Blocks.WOOL, 1, 14) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_leggings"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 50, new AspectList().add(Aspect.FIRE, 1).add(Aspect.AIR, 1).add(Aspect.ENTROPY, 1), new ItemStack(ItemsTC.crimsonRobeLegs), new Object[] { "WBW", "F F", "F F", 'F', ItemsTC.fabric, 'B', new ItemStack(BlocksTC.bannerCrimsonCult), 'W', new ItemStack(Blocks.WOOL, 1, 14) } )); ThaumcraftApi.addArcaneCraftingRecipe(new ResourceLocation("crimsonrevelations", "crimson_boots"), new ShapedArcaneRecipe( defaultGroup, "CRIMSON_ARMOR", 50, new AspectList().add(Aspect.FIRE, 1).add(Aspect.AIR, 1).add(Aspect.ENTROPY, 1), new ItemStack(ItemsTC.crimsonBoots), new Object[] { "I I", "W W", 'I', new ItemStack(ItemsTC.plate, 1, 1), 'W', new ItemStack(Blocks.WOOL, 1, 14) } )); } }
63.458716
309
0.650499
5a5c98be23ba04a24092a8fddd58fadd024c563d
1,392
html
HTML
layouts/partials/cookie_consent.html
Andro/academic-kickstart
460a3219820736677c31a63bb38a97af03c5407b
[ "MIT" ]
null
null
null
layouts/partials/cookie_consent.html
Andro/academic-kickstart
460a3219820736677c31a63bb38a97af03c5407b
[ "MIT" ]
null
null
null
layouts/partials/cookie_consent.html
Andro/academic-kickstart
460a3219820736677c31a63bb38a97af03c5407b
[ "MIT" ]
null
null
null
{{ if site.Params.privacy_pack }} {{ $scr := .Scratch }} {{ $js := site.Data.assets.js }} {{ $css := site.Data.assets.css }} {{ if ($scr.Get "use_cdn") }} {{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.cookieconsent.url $js.cookieconsent.version) $js.cookieconsent.sri | safeHTML }} {{ printf "<link rel=\"stylesheet\" href=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\">" (printf $css.cookieconsent.url $css.cookieconsent.version) $css.cookieconsent.sri | safeHTML }} {{ end }} <script> window.addEventListener("load", function(){ window.cookieconsent.initialise({ "palette": { "popup": { "background": "{{ $scr.Get "primary" }}", "text": "{{ $scr.Get "background" }}" }, "button": { "background": "{{ $scr.Get "background" }}", "text": "{{ $scr.Get "primary" }}" } }, "theme": "classic", "content": { "message": {{ i18n "cookie_message" | default "This website uses cookies to ensure you get the best experience on our website." }}, "dismiss": {{ i18n "cookie_dismiss" | default "I understand." }}, "link": {{ i18n "cookie_learn" | default "" }}, "href": {{ with site.GetPage "privacy.md" }}{{ printf "%s" .RelPermalink }}{{ else }}""{{ end }} } })}); </script> {{ end }}
43.5
192
0.552443
862d1b26d42831f8a08e0b9d1228c71919eb96ed
7,921
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_ht_zr_un_/i9-9900K_12_0xa0.log_21829_1161.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_ht_zr_un_/i9-9900K_12_0xa0.log_21829_1161.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_ht_zr_un_/i9-9900K_12_0xa0.log_21829_1161.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r15 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_WC_ht+0x15519, %rsi lea addresses_normal_ht+0x11999, %rdi nop nop nop sub %rax, %rax mov $1, %rcx rep movsb nop cmp $48868, %rdi lea addresses_WT_ht+0x1405f, %r11 clflush (%r11) nop inc %r15 mov $0x6162636465666768, %r12 movq %r12, %xmm3 and $0xffffffffffffffc0, %r11 vmovaps %ymm3, (%r11) nop nop nop and $17896, %r11 lea addresses_WT_ht+0xcec9, %rsi lea addresses_WT_ht+0x10399, %rdi nop nop nop nop cmp %r9, %r9 mov $60, %rcx rep movsw nop and %r9, %r9 lea addresses_normal_ht+0x1ab99, %r9 clflush (%r9) sub %rdi, %rdi movb (%r9), %r15b nop nop nop nop add %r12, %r12 lea addresses_D_ht+0x27c5, %r15 nop nop nop nop add $63635, %rsi movups (%r15), %xmm6 vpextrq $1, %xmm6, %r11 nop nop nop nop and $38371, %r11 lea addresses_UC_ht+0xea3b, %rax clflush (%rax) nop dec %r15 mov (%rax), %si nop nop and $21910, %rsi lea addresses_normal_ht+0x1c699, %r9 nop nop nop xor $4702, %r11 movw $0x6162, (%r9) nop nop nop and $55732, %rsi lea addresses_UC_ht+0x1ad99, %rsi nop nop nop nop xor %r9, %r9 movups (%rsi), %xmm4 vpextrq $1, %xmm4, %rcx nop nop and $29001, %rax lea addresses_WC_ht+0x13fc9, %r9 nop nop nop add %rax, %rax movw $0x6162, (%r9) nop nop nop nop nop sub %r9, %r9 lea addresses_UC_ht+0xef99, %rsi lea addresses_A_ht+0x1afb9, %rdi nop sub %r12, %r12 mov $69, %rcx rep movsq nop nop and %rcx, %rcx lea addresses_normal_ht+0x1b99, %rdi nop nop nop add %rax, %rax movb (%rdi), %r12b nop nop nop and $61452, %r12 lea addresses_UC_ht+0x145d9, %r11 nop nop nop sub $63095, %rcx mov (%r11), %r15 nop nop nop add %r11, %r11 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r14 push %rax push %rdi push %rdx push %rsi // Store mov $0x27a1aa0000000e99, %rdx clflush (%rdx) nop nop nop nop and %r12, %r12 movl $0x51525354, (%rdx) nop nop nop nop nop sub %r10, %r10 // Store lea addresses_normal+0x9399, %rax nop cmp %r14, %r14 mov $0x5152535455565758, %r12 movq %r12, (%rax) nop inc %rdx // Store lea addresses_WT+0xb019, %r14 nop nop nop xor $35802, %r12 mov $0x5152535455565758, %rax movq %rax, (%r14) nop nop and %r10, %r10 // Faulty Load lea addresses_A+0xa399, %rsi clflush (%rsi) nop nop nop nop xor $20253, %rdx vmovntdqa (%rsi), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $1, %xmm1, %rax lea oracles, %r12 and $0xff, %rax shlq $12, %rax mov (%r12,%rax,1), %rax pop %rsi pop %rdx pop %rdi pop %rax pop %r14 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_NC', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_normal', 'AVXalign': True, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WT', 'AVXalign': False, 'size': 8}} [Faulty Load] {'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 6, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT_ht', 'AVXalign': True, 'size': 32}} {'src': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2}} {'src': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 4, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2}} {'src': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_A_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'48': 120, '49': 203, '0a': 1, '00': 21498, '42': 2, '47': 1, '08': 3, '72': 1} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
32.731405
2,999
0.653705
3b07d4f11435840e966c87a485fd895f6c62f72f
25,789
swift
Swift
Toolkit/ArcGISToolkit/MeasureToolbar.swift
mhdostal/arcgis-runtime-toolkit-ios
b602b88fb6b02871f79d11ef07fc18e39468e899
[ "Apache-2.0" ]
null
null
null
Toolkit/ArcGISToolkit/MeasureToolbar.swift
mhdostal/arcgis-runtime-toolkit-ios
b602b88fb6b02871f79d11ef07fc18e39468e899
[ "Apache-2.0" ]
null
null
null
Toolkit/ArcGISToolkit/MeasureToolbar.swift
mhdostal/arcgis-runtime-toolkit-ios
b602b88fb6b02871f79d11ef07fc18e39468e899
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Esri. // 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 UIKit import ArcGIS struct Measurement { let value: Double let unit: AGSUnit } class MeasureResultView: UIView { var measurement: Measurement? { didSet { if let measurement = measurement { valueLabel.text = valueString() unitButton.setTitle(stringForUnit(measurement.unit), for: .normal) unitButton.isHidden = false invalidateIntrinsicContentSize() } } } var helpText: String? { didSet { if let helpText = helpText { valueLabel.text = helpText unitButton.isHidden = true unitButton.setTitle(nil, for: .normal) invalidateIntrinsicContentSize() } } } var valueLabel: UILabel var unitButton: UIButton var stackView: UIStackView let numberFormatter = NumberFormatter() var buttonTapHandler: (() -> Void)? override var intrinsicContentSize: CGSize { return stackView.systemLayoutSizeFitting(CGSize(width: 0, height: 0), withHorizontalFittingPriority: .fittingSizeLevel, verticalFittingPriority: .fittingSizeLevel) } override init(frame: CGRect) { numberFormatter.numberStyle = .decimal numberFormatter.minimumFractionDigits = 0 numberFormatter.maximumFractionDigits = 2 numberFormatter.roundingMode = .halfUp valueLabel = UILabel() valueLabel.translatesAutoresizingMaskIntoConstraints = false valueLabel.textAlignment = .right valueLabel.textColor = UIColor.darkGray valueLabel.font = UIFont.preferredFont(forTextStyle: .footnote) unitButton = UIButton(type: .system) unitButton.translatesAutoresizingMaskIntoConstraints = false unitButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption1) unitButton.titleLabel?.textAlignment = .left stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.spacing = 4.0 stackView.distribution = .equalSpacing stackView.alignment = .center stackView.layoutMargins = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 6) stackView.isLayoutMarginsRelativeArrangement = true super.init(frame: frame) unitButton.addTarget(self, action: #selector(buttonTap), for: .touchUpInside) layer.cornerRadius = 4 layer.borderColor = UIColor.lightGray.cgColor layer.borderWidth = 1 clipsToBounds = true stackView.addArrangedSubview(valueLabel) stackView.addArrangedSubview(unitButton) addSubview(stackView) stackView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true stackView.topAnchor.constraint(equalTo: topAnchor).isActive = true stackView.heightAnchor.constraint(equalToConstant: 32).isActive = true valueLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 500), for: .horizontal) valueLabel.setContentHuggingPriority(.required, for: .horizontal) unitButton.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 499), for: .horizontal) unitButton.setContentHuggingPriority(.required, for: .horizontal) let tgr = UITapGestureRecognizer(target: self, action: #selector(buttonTap)) addGestureRecognizer(tgr) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override class var requiresConstraintBasedLayout: Bool { return true } @objc func buttonTap() { guard unitButton.isHidden == false else { return } buttonTapHandler?() } func valueString() -> String? { guard let measurement = measurement else { return "" } // if number greater than some value then don't show fraction if measurement.value > 1_000 { numberFormatter.maximumFractionDigits = 0 } else { numberFormatter.maximumFractionDigits = 2 } guard let measurementValueString = numberFormatter.string(for: measurement.value) else { return "" } return measurementValueString } func stringForUnit(_ unit: AGSUnit?) -> String? { guard let unit = unit else { return "" } return unit.pluralDisplayName } } private enum MeasureToolbarMode { case length case area case feature } public class MeasureToolbar: UIToolbar, AGSGeoViewTouchDelegate { // Exposed so that the user can customize the sketch editor styles. // Consumers of the MeasureToolbar should not mutate the sketch editor state // other than it's style. public let lineSketchEditor = AGSSketchEditor() public let areaSketchEditor = AGSSketchEditor() // Exposed so that the symbology and selection colors can be customized. public private(set) var selectionLineSymbol: AGSSymbol? public private(set)var selectionFillSymbol: AGSSymbol? @available(iOS, deprecated, message: "Use `color` property exposed through `AGSGeoView.selectionProperties`") public var selectionColor: UIColor? { return mapView?.selectionProperties.color } public var mapView: AGSMapView? { didSet { guard mapView != oldValue else { return } unbindFromMapView(mapView: oldValue) bindToMapView(mapView: mapView) updateMeasurement() } } public var selectedLinearUnit: AGSLinearUnit = { if NSLocale.current.usesMetricSystem { return AGSLinearUnit.kilometers() } else { return AGSLinearUnit.miles() } }() { didSet { updateMeasurement() } } public var selectedAreaUnit: AGSAreaUnit = { if NSLocale.current.usesMetricSystem { return AGSAreaUnit(unitID: AGSAreaUnitID.hectares) ?? AGSAreaUnit.squareKilometers() } else { return AGSAreaUnit(unitID: AGSAreaUnitID.acres) ?? AGSAreaUnit.squareMiles() } }() { didSet { updateMeasurement() } } private static let identifyTolerance = 16.0 private var selectionOverlay: AGSGraphicsOverlay? private var selectedGeometry: AGSGeometry? { didSet { guard selectedGeometry != oldValue else { return } updateMeasurement() } } private let resultView = MeasureResultView() private var undoButton: UIBarButtonItem! private var redoButton: UIBarButtonItem! private var clearButton: UIBarButtonItem! private var segControl: UISegmentedControl! private var segControlItem: UIBarButtonItem! private var mode: MeasureToolbarMode? private let geodeticCurveType: AGSGeodeticCurveType = .geodesic // This is the threshold for which when the planar measurements are above, // it will switch to geodetic calculations. Set it to Double.infinity for // always doing geodetic calculations (but be careful, they can get slow when they have to measure // too much length/area). // Set it to 0 to never do geodetic calculations (less accurate). private let planarLengthMetersThreshold: Double = 10_000_000 private let planarAreaSquareMilesThreshold: Double = 1_000_000 deinit { unbindFromMapView(mapView: mapView) } override init(frame: CGRect) { super.init(frame: frame) sharedInitialization() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInitialization() } public convenience init(mapView: AGSMapView) { self.init(frame: .zero) self.mapView = mapView // because didSet doesn't happen in constructors bindToMapView(mapView: mapView) } private var sketchModeButtons: [UIBarButtonItem] = [] private var selectModeButtons: [UIBarButtonItem] = [] private func sharedInitialization() { let bundle = Bundle(for: type(of: self)) let measureLengthImage = UIImage(named: "MeasureLength", in: bundle, compatibleWith: traitCollection)! let measureAreaImage = UIImage(named: "MeasureArea", in: bundle, compatibleWith: traitCollection)! let measureFeatureImage = UIImage(named: "MeasureFeature", in: bundle, compatibleWith: traitCollection)! let undoImage = UIImage(named: "Undo", in: bundle, compatibleWith: traitCollection) let redoImage = UIImage(named: "Redo", in: bundle, compatibleWith: traitCollection) undoButton = UIBarButtonItem(image: undoImage, style: .plain, target: self, action: #selector(undoButtonTap)) redoButton = UIBarButtonItem(image: redoImage, style: .plain, target: self, action: #selector(redoButtonTap)) clearButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(clearButtonTap)) segControl = UISegmentedControl(items: [measureLengthImage, measureAreaImage, measureFeatureImage]) segControlItem = UIBarButtonItem(customView: segControl) resultView.buttonTapHandler = { [weak self] in self?.unitsButtonTap() } segControl.addTarget(self, action: #selector(segmentControlValueChanged), for: .valueChanged) let flexibleSpaceItem1 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let resultViewItem = UIBarButtonItem(customView: resultView) let flexibleSpaceItem2 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) selectModeButtons = [segControlItem, flexibleSpaceItem1, resultViewItem, flexibleSpaceItem2] sketchModeButtons = selectModeButtons + [undoButton, redoButton, clearButton] // notification NotificationCenter.default.addObserver(self, selector: #selector(sketchEditorGeometryDidChange(_:)), name: .AGSSketchEditorGeometryDidChange, object: nil) } private func bindToMapView(mapView: AGSMapView?) { mapView?.touchDelegate = self if let mapView = mapView { // defaults for symbology selectionLineSymbol = lineSketchEditor.style.lineSymbol let fillColor = mapView.selectionProperties.color.withAlphaComponent(0.25) let sfs = AGSSimpleFillSymbol(style: .solid, color: fillColor, outline: selectionLineSymbol as? AGSSimpleLineSymbol) selectionFillSymbol = sfs let selectionOverlay = AGSGraphicsOverlay() self.selectionOverlay = selectionOverlay mapView.graphicsOverlays.add(selectionOverlay) // set initial mode segControl.selectedSegmentIndex = 0 segmentControlValueChanged() } } private func unbindFromMapView(mapView: AGSMapView?) { mapView?.sketchEditor = nil mapView?.touchDelegate = nil if let mapView = mapView, let selectionOverlay = selectionOverlay { mapView.graphicsOverlays.remove(selectionOverlay) } } override public func layoutSubviews() { switch mode { case .length, .area: items = sketchModeButtons case .feature: items = selectModeButtons case .none: items = [] } super.layoutSubviews() } override public class var requiresConstraintBasedLayout: Bool { return true } @objc private func segmentControlValueChanged() { if segControl.selectedSegmentIndex == 0 { startLineMode() } else if segControl.selectedSegmentIndex == 1 { startAreaMode() } else if segControl.selectedSegmentIndex == 2 { startFeatureMode() } setNeedsLayout() } private func startLineMode() { guard mode != MeasureToolbarMode.length else { return } mode = .length selectionOverlay?.isVisible = false mapView?.sketchEditor = lineSketchEditor if !lineSketchEditor.isStarted { lineSketchEditor.start(with: AGSSketchCreationMode.polyline) } // updateMeasurement() requires mode property and sketch editor // properties to be current, so we do this last when changing modes updateMeasurement() } private func startAreaMode() { guard mode != MeasureToolbarMode.area else { return } mode = .area selectionOverlay?.isVisible = false mapView?.sketchEditor = areaSketchEditor if !areaSketchEditor.isStarted { areaSketchEditor.start(with: AGSSketchCreationMode.polygon) } // updateMeasurement() requires mode property and sketch editor // properties to be current, so we do this last when changing modes updateMeasurement() } private func startFeatureMode() { guard mode != MeasureToolbarMode.feature else { return } mode = .feature selectionOverlay?.isVisible = true mapView?.sketchEditor = nil // updateMeasurement() requires mode property and sketch editor // properties to be current, so we do this last when changing modes updateMeasurement() } @objc private func undoButtonTap() { mapView?.sketchEditor?.undoManager.undo() } @objc private func redoButtonTap() { mapView?.sketchEditor?.undoManager.redo() } @objc private func clearButtonTap() { mapView?.sketchEditor?.clearGeometry() } private lazy var linearUnits: [AGSLinearUnit] = { let linearUnitIDs: [AGSLinearUnitID] = [.centimeters, .feet, .inches, .kilometers, .meters, .miles, .millimeters, .nauticalMiles, .yards] return linearUnitIDs .compactMap(AGSLinearUnit.init) .sorted { $0.pluralDisplayName < $1.pluralDisplayName } }() private lazy var areaUnits: [AGSAreaUnit] = { let areaUnitIDs: [AGSAreaUnitID] = [.acres, .hectares, .squareCentimeters, .squareDecimeters, .squareFeet, .squareKilometers, .squareMeters, .squareMillimeters, .squareMiles, .squareYards] return areaUnitIDs .compactMap(AGSAreaUnit.init) .sorted { $0.pluralDisplayName < $1.pluralDisplayName } }() private func unitsButtonTap() { let units: [AGSUnit] let selectedUnit: AGSUnit guard let mode = mode else { return } switch mode { case .length: units = linearUnits selectedUnit = selectedLinearUnit case .area: units = areaUnits selectedUnit = selectedAreaUnit case .feature: if selectedGeometry?.geometryType == .polyline { units = linearUnits selectedUnit = selectedLinearUnit } else if selectedGeometry?.geometryType == .envelope || selectedGeometry?.geometryType == .polygon { units = areaUnits selectedUnit = selectedAreaUnit } else { return } } let unitsViewController = UnitsViewController() unitsViewController.delegate = self unitsViewController.units = units unitsViewController.selectedUnit = selectedUnit let navigationController = UINavigationController(rootViewController: unitsViewController) navigationController.modalPresentationStyle = .formSheet UIApplication.shared.topViewController()?.present(navigationController, animated: true) } /// Called in response to /// `Notification.Name.AGSSketchEditorGeometryDidChange` being posted. /// /// - Parameter notification: The posted notification. @objc private func sketchEditorGeometryDidChange(_ notification: Notification) { guard let sketchEditor = notification.object as? AGSSketchEditor, sketchEditor == lineSketchEditor || sketchEditor == areaSketchEditor else { return } updateMeasurement() } /// Updates the measurement displayed to the user based on the current mode. private func updateMeasurement() { guard let mode = mode else { return } switch mode { case .length: let measurement = Measurement(value: calculateSketchLength(), unit: selectedLinearUnit) resultView.measurement = measurement case .area: let measurement = Measurement(value: calculateSketchArea(), unit: selectedAreaUnit) resultView.measurement = measurement case .feature: if let geometry = selectedGeometry { let measurement = Measurement(value: calculateMeasurement(of: geometry), unit: unit(for: geometry)) resultView.measurement = measurement } else { resultView.helpText = "Tap a feature" } } } private func calculateSketchLength() -> Double { guard mapView?.sketchEditor?.isSketchValid == true, let geom = mapView?.sketchEditor?.geometry else { return 0 } return calculateLength(of: geom) } private func calculateLength(of geom: AGSGeometry) -> Double { // if planar is very large then just return that, geodetic might take too long if let linearUnit = geom.spatialReference?.unit as? AGSLinearUnit { var planar = AGSGeometryEngine.length(of: geom) planar = linearUnit.convert(toMeters: planar) if planar > planarLengthMetersThreshold { let planarDisplay = AGSLinearUnit.meters().convert(planar, to: selectedLinearUnit) //`print("returning planar length... \(planar) sq meters") return planarDisplay } } // otherwise return geodetic value return AGSGeometryEngine.geodeticLength(of: geom, lengthUnit: selectedLinearUnit, curveType: geodeticCurveType) } private func calculateSketchArea() -> Double { guard mapView?.sketchEditor?.isSketchValid == true, let geom = mapView?.sketchEditor?.geometry else { return 0 } return calculateArea(of: geom) } private func calculateArea(of geom: AGSGeometry) -> Double { // if planar is very large then just return that, geodetic might take too long if let linearUnit = geom.spatialReference?.unit as? AGSLinearUnit { let planar = AGSGeometryEngine.area(of: geom) if let planarMiles = linearUnit.toAreaUnit()?.convert(planar, to: AGSAreaUnit.squareMiles()), planarMiles > planarAreaSquareMilesThreshold { let planarDisplay = AGSAreaUnit.squareMiles().convert(planarMiles, to: selectedAreaUnit) //print("returning planar area... \(planarMiles) sq miles") return planarDisplay } } // otherwise return geodetic value return AGSGeometryEngine.geodeticArea(of: geom, areaUnit: selectedAreaUnit, curveType: geodeticCurveType) } private func calculateMeasurement(of geom: AGSGeometry) -> Double { switch geom.geometryType { case .polyline: return calculateLength(of: geom) case .polygon, .envelope: return calculateArea(of: geom) default: assertionFailure("unexpected geometry type") return 0 } } private func unit(for geom: AGSGeometry) -> AGSUnit { switch geom.geometryType { case .polyline: return selectedLinearUnit case .polygon, .envelope: return selectedAreaUnit default: fatalError("unexpected geometry type") } } private func selectionSymbol(for geom: AGSGeometry) -> AGSSymbol? { switch geom.geometryType { case .polyline: return selectionLineSymbol case .polygon, .envelope: return selectionFillSymbol default: fatalError("unexpected geometry type") } } private var lastIdentify: AGSCancelable? public func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { lastIdentify?.cancel() lastIdentify = geoView.identifyGraphicsOverlays(atScreenPoint: screenPoint, tolerance: MeasureToolbar.identifyTolerance, returnPopupsOnly: false) { [weak self] results, error in guard let self = self else { return } if let error = error { guard (error as NSError).domain != NSCocoaErrorDomain && (error as NSError).code != NSUserCancelledError else { return } } if let geom = self.firstOverlayPolyResult(in: results) { // display graphic result self.select(geom: geom) } else { // otherwise identify layers to try to find a feature self.lastIdentify = geoView.identifyLayers(atScreenPoint: screenPoint, tolerance: MeasureToolbar.identifyTolerance, returnPopupsOnly: false) { [weak self] results, error in guard let self = self else { return } if let error = error { guard (error as NSError).domain != NSCocoaErrorDomain && (error as NSError).code != NSUserCancelledError else { return } } let geom = self.firstLayerPolyResult(in: results) self.select(geom: geom) } } } } private func clearGeometrySelection() { selectionOverlay?.clearSelection() selectionOverlay?.graphics.removeAllObjects() selectedGeometry = nil } private func select(geom: AGSGeometry?) { clearGeometrySelection() guard let geom = geom else { return } let graphic = AGSGraphic(geometry: geom, symbol: selectionSymbol(for: geom), attributes: nil) graphic.isSelected = true selectionOverlay?.graphics.add(graphic) selectedGeometry = geom } private func firstOverlayPolyResult(in identifyResults: [AGSIdentifyGraphicsOverlayResult]?) -> AGSGeometry? { guard let results = identifyResults else { return nil } for result in results { for ge in result.graphics { if ge.geometry?.geometryType == .polyline || ge.geometry?.geometryType == .polygon || ge.geometry?.geometryType == .envelope { return ge.geometry! } } } return nil } private func firstLayerPolyResult(in identifyResults: [AGSIdentifyLayerResult]?) -> AGSGeometry? { guard let results = identifyResults else { return nil } for result in results { for ge in result.geoElements { if ge.geometry?.geometryType == .polyline || ge.geometry?.geometryType == .polygon || ge.geometry?.geometryType == .envelope { return ge.geometry! } } if let subGeom = firstLayerPolyResult(in: result.sublayerResults) { return subGeom } } return nil } } extension MeasureToolbar: UnitsViewControllerDelegate { public func unitsViewControllerDidCancel(_ unitsViewController: UnitsViewController) { unitsViewController.dismiss(animated: true) } public func unitsViewControllerDidSelectUnit(_ unitsViewController: UnitsViewController) { unitsViewController.dismiss(animated: true) switch unitsViewController.selectedUnit { case let linearUnit as AGSLinearUnit: selectedLinearUnit = linearUnit case let areaUnit as AGSAreaUnit: selectedAreaUnit = areaUnit default: fatalError("Unsupported unit type") } } }
37.213564
196
0.625034
04bf68574c6639bb45ae9470c75eb09c014ee9cb
2,021
swift
Swift
Code/Features/Place/CommentView.swift
crspybits/WhatDidILike
98ec693ebb9aa678f1c810748196660a73da25b0
[ "MIT" ]
null
null
null
Code/Features/Place/CommentView.swift
crspybits/WhatDidILike
98ec693ebb9aa678f1c810748196660a73da25b0
[ "MIT" ]
60
2017-10-03T03:14:10.000Z
2020-03-16T19:08:10.000Z
Code/Features/Place/CommentView.swift
crspybits/WhatDidILike
98ec693ebb9aa678f1c810748196660a73da25b0
[ "MIT" ]
1
2018-03-12T10:04:09.000Z
2018-03-12T10:04:09.000Z
// // CommentView.swift // WhatDidILike // // Created by Christopher G Prince on 9/3/17. // Copyright © 2017 Spastic Muffin, LLC. All rights reserved. // import UIKit import SMCoreLib class CommentView: UIView, XibBasics { typealias ViewType = CommentView @IBOutlet weak var bottom: NSLayoutConstraint! @IBOutlet weak var commentImagesContainer: UIView! @IBOutlet weak var ratingContainer: UIView! @IBOutlet weak var comment: TextView! private let rating = RatingView.create()! private let images = ImagesView.create()! @IBOutlet weak var removeButton: UIButton! @IBOutlet weak var separator: UIView! var removeComment:(()->())? override func awakeFromNib() { super.awakeFromNib() Layout.format(textBox: comment) comment.autocapitalizationType = .sentences rating.frameWidth = ratingContainer.frameWidth ratingContainer.addSubview(rating) images.frameWidth = commentImagesContainer.frameWidth commentImagesContainer.addSubview(images) images.lowerLeftLabel.text = "Comment pictures" Layout.format(comment: self) removeButton.tintColor = .trash } func setup(withComment comment: Comment, andParentVC vc: UIViewController) { self.comment.text = comment.comment rating.setup(withRating: comment.rating!) images.setup(withParentVC:vc, andImagesObj: comment) removeButton.isHidden = Parameters.commentStyle == .single // Assumes images are positioned at the bottom of the CommentView. if Parameters.commentStyle == .single { // This removes extra area needed for the removeButton and also makes the corner rounding look better. frameHeight -= bottom.constant bottom.constant = 0 } } @IBAction func removeCommentAction(_ sender: Any) { removeComment?() } deinit { Log.msg("deinit") } }
31.092308
114
0.65908
0a7370702fcd154e50dfd355183add9cf6f7049b
480
asm
Assembly
programs/oeis/198/A198083.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/198/A198083.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/198/A198083.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A198083: Ceiling(n*Sqrt(6)). ; 0,3,5,8,10,13,15,18,20,23,25,27,30,32,35,37,40,42,45,47,49,52,54,57,59,62,64,67,69,72,74,76,79,81,84,86,89,91,94,96,98,101,103,106,108,111,113,116,118,121,123,125,128,130,133,135,138,140,143,145,147,150,152,155,157,160,162,165,167,170,172,174,177,179,182,184,187,189,192,194,196,199,201,204,206,209,211,214,216,219,221,223,226,228,231,233,236,238,241,243 mov $1,$0 mul $0,2 pow $1,2 mul $1,5 lpb $1 sub $1,$0 add $0,2 trn $1,1 lpe div $0,2
34.285714
356
0.670833
9ae3e79a6fae95004cc605fccc4f6b2425628962
1,170
css
CSS
resources/sort_rtl.css
jsonn/gridx
8b080a51b4983cafce29b3372a2625a3d3891740
[ "AFL-2.1" ]
2
2015-06-22T13:20:53.000Z
2015-06-22T13:21:00.000Z
resources/sort_rtl.css
creativeprogramming/gridx
8ac96ff98b17b78adbd6e5f8199a7f7f09669572
[ "AFL-2.1" ]
1
2020-10-14T03:40:39.000Z
2020-10-14T03:40:39.000Z
resources/sort_rtl.css
creativeprogramming/gridx
8ac96ff98b17b78adbd6e5f8199a7f7f09669572
[ "AFL-2.1" ]
null
null
null
/*Single Sorting*/ .gridxRtl .gridxArrowButtonNode { float: left; margin-right: 0; margin-left: 7px; } /* NestedSorting */ .dijitRtl .gridxSortNode { text-align: right; } .dijitRtl .gridxSortBtn { float: left; } .dijitRtl .gridxSortBtnNested { width: 20px; background-position: -156px 5px; text-align: right; } .dijitRtl .gridxCell:hover .gridxSortBtn, .dijitRtl .gridxCellSortFocus .gridxSortBtn { border-right: 1px solid #bbb; border-left: none; } .dijitRtl .gridxCellSortedAsc .gridxSortBtnNested { background-position: -117px 5px; } .dijitRtl .gridxCellSortedDesc .gridxSortBtnNested { background-position: -97px 5px; } .dijitRtl .gridxCell:hover.gridxCellSortedAsc .gridxSortBtnNested, .dijitRtl .gridxCellSortFocus.gridxCellSortedAsc .gridxSortBtnNested { background-position: -137px 5px; } .dijitRtl .gridxCell:hover.gridxCellSortedDesc .gridxSortBtnNested, .dijitRtl .gridxCellSortFocus.gridxCellSortedDesc .gridxSortBtnNested { background-position: -177px 5px; } .dijitRtl .gridxNestedSorted .gridxCell:hover .gridxSortBtnSingle, .dijitRtl .gridxNestedSorted .gridxCellSortFocus .gridxSortBtnSingle { background-position: -159px 5px; }
22.5
71
0.780342
2f0b7ee92c992c2a7f8c7c11ee760dd3723bc794
1,453
html
HTML
blades/cclite/usr/share/cclite/templates/html/id/displaytransaction.html
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/cclite/usr/share/cclite/templates/html/id/displaytransaction.html
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/cclite/usr/share/cclite/templates/html/id/displaytransaction.html
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
<table> <tbody class="stripy"> <tr> <td class="pme-key-title"> Dari </td> <td class="pme-key-1"> $$fieldsref{tradeSource} </td> </tr> <tr> <td class="pme-key-title"> Deskripsi </td> <td class="pme-key-1"> $$fieldsref{tradeDescription} </td> </tr> <tr> <td class="pme-key-title"> Untuk </td> <td class="pme-key-1"> $$fieldsref{tradeDestination} </td> </tr> <tr> <td class="pme-key-title"> Judul </td> <td class="pme-key-1"> $$fieldsref{tradeTitle} </td> </tr> <tr> <td class="pme-key-title"> Jenis </td> <td class="pme-key-1"> $$fieldsref{tradeType} </td> </tr> <tr> <td class="pme-key-title"> Tanggal </td> <td class="pme-key-1"> $$fieldsref{tradeDate} </td> </tr> <tr> <td class="pme-key-title"> Item </td> <td class="pme-key-1"> $$fieldsref{tradeItem} </td> </tr> <tr> <td class="pme-key-title"> Cap waktu </td> <td class="pme-key-1"> $$fieldsref{tradeStamp} </td> </tr> <tr> <td class="pme-key-title"> Registri </td> <td class="pme-key-1"> $$fieldsref{tradeMirror} </td> </tr> <tr> <td class="pme-key-title"> Status </td> <td class="pme-key-1"> $$fieldsref{tradeStatus} </td> </tr> <tr> <td class="pme-key-title"> Mata uang </td> <td class="pme-key-1"> $$fieldsref{tradeCurrency} </td> </tr> <tr> <td class="pme-key-title"> Jumlah </td> <td class="pme-key-1"> $$fieldsref{tradeAmount} </td> </tr> <tr> <td class="pme-key-title"> Perdagangan referensi </td> <td class="pme-key-1"> $$fieldsref{tradeHash} </td> </tr> </tbody> </table>
11.531746
29
0.624914
80efffdab49a09efa0b2558ee194c17bd6f6fb50
529
dart
Dart
lib/src/protocol/document.dart
takenet/lime-dart
b855952d2544e4b7528deb89f7a4a31d9d0ada39
[ "BSD-3-Clause" ]
null
null
null
lib/src/protocol/document.dart
takenet/lime-dart
b855952d2544e4b7528deb89f7a4a31d9d0ada39
[ "BSD-3-Clause" ]
null
null
null
lib/src/protocol/document.dart
takenet/lime-dart
b855952d2544e4b7528deb89f7a4a31d9d0ada39
[ "BSD-3-Clause" ]
null
null
null
import 'package:flutter/material.dart'; import 'media_type.dart'; import 'plain_document.dart'; /// Defines a entity with a MediaType. abstract class Document { @protected MediaType mediaType; /// Initializes a new instance of the class. @protected Document({required this.mediaType}); /// Gets the type of the media for the document. MediaType getMediaType() => mediaType; Document? fromString(String? value) { if (value == null) return null; return PlainDocument(value, MediaType.textPlain); } }
23
53
0.718336
02f71d043f873cedd7343990153472836a8aba79
4,988
lua
Lua
gamemodes/navalwarfare/gamemode/download.lua
Jacoby6000/gm-naval-warfare
a878df4384f1f2f853816adc382b910383ce65a1
[ "MIT" ]
null
null
null
gamemodes/navalwarfare/gamemode/download.lua
Jacoby6000/gm-naval-warfare
a878df4384f1f2f853816adc382b910383ce65a1
[ "MIT" ]
null
null
null
gamemodes/navalwarfare/gamemode/download.lua
Jacoby6000/gm-naval-warfare
a878df4384f1f2f853816adc382b910383ce65a1
[ "MIT" ]
null
null
null
--Old Paths from before self contained model resource.AddFile("materials/navalwarfare/capture_ring2.vmt") resource.AddFile("materials/navalwarfare/capture_ring2.vtf") resource.AddFile("materials/navalwarfare/compass.vtf") resource.AddFile("materials/navalwarfare/compass.vmt") -- resource.AddFile("materials/navalwarfare/navalwarfare/vgui/entities/npc_ww2_ame_rifleman.vmt") -- resource.AddFile("materials/navalwarfare/navalwarfare/vgui/entities/npc_ww2_ame_rifleman.vtf") -- resource.AddFile("materials/navalwarfare/navalwarfare/vgui/entities/npc_ww2_ame_riflemanf.vmt") -- resource.AddFile("materials/navalwarfare/navalwarfare/models/american/rifleman/american_body.vmt") -- resource.AddFile("materials/navalwarfare/navalwarfare/models/american/rifleman/american_body.vtf") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_body_exp.vtf") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_body_normal.vtf") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_gear.vmt") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_gear.vtf") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_gear_exp.vtf") -- resource.AddFile("materials/navalwarfare/models/american/rifleman/american_gear_normal.vtf") -- resource.AddFile("materials/navalwarfare/vgui/entities/npc_ww2_ger_grenadier.vmt") -- resource.AddFile("materials/navalwarfare/vgui/entities/npc_ww2_ger_grenadier.vtf") -- resource.AddFile("materials/navalwarfare/vgui/entities/npc_ww2_ger_grenadierf.vmt") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_body.vmt") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_body.vtf") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_body_exp.vtf") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_body_normal.vtf") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_gear.vmt") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_gear.vtf") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_gear_exp.vtf") -- resource.AddFile("materials/navalwarfare/models/german/grenadier/german_gear_normal.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/models/american/Rifleman.mdl") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ame_rifleman.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ame_rifleman.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ame_riflemanf.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_body.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_body.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_body_exp.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_body_normal.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_gear.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_gear.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_gear_exp.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/american/rifleman/american_gear_normal.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/models/german/Grenadier_playermodel.mdl") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ger_grenadier.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ger_grenadier.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/vgui/entities/npc_ww2_ger_grenadierf.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_body.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_body.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_body_exp.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_body_normal.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_gear.vmt") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_gear.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_gear_exp.vtf") -- resource.AddFile("gamemodes/navalwarfarebeta/content/materials/models/german/grenadier/german_gear_normal.vtf")
89.071429
118
0.8334
76e8e3bab49ac638e8e01f3d4a88c6fad1b7a106
2,425
lua
Lua
lua/linebuffer.lua
allegory-software/allegory-sdk
64186b0a0323fdbb299fb30d1117df673fc74fb8
[ "MIT" ]
2
2022-01-28T17:28:19.000Z
2022-02-05T13:55:06.000Z
lua/linebuffer.lua
allegory-software/allegory-sdk
64186b0a0323fdbb299fb30d1117df673fc74fb8
[ "MIT" ]
2
2022-02-19T09:08:15.000Z
2022-02-19T09:10:34.000Z
lua/linebuffer.lua
allegory-software/allegory-sdk
64186b0a0323fdbb299fb30d1117df673fc74fb8
[ "MIT" ]
2
2022-02-05T14:11:49.000Z
2022-03-30T12:55:46.000Z
--[=[ Line buffer for text-based network protocols. Written by Cosmin Apreutesei. Public Domain. Allows reading from a socket an unknown amount of bytes into a memory buffer, and consuming the data from the buffer line by line. It is used to simplify the impl. of line-based network protocols like HTTP. ]=] if not ... then require'linebuffer_test'; return end local ffi = require'ffi' --Based on `read(buf, maxsz) -> sz`, create the API: -- `readline() -> s` -- `read(maxsz) -> buf, sz` return function(read, term, sz) local find_term if #term == 1 then local t = string.byte(term) function find_term(buf, i, j) for i = i, j-1 do if buf[i] == t then return true, i, i+1 end end return false, 0, 0 end elseif #term == 2 then local t1, t2 = string.byte(term, 1, 2) function find_term(buf, i, j) for i = i, j-2 do if buf[i] == t1 and buf[i+1] == t2 then return true, i, i+2 end end return false, 0, 0 end else assert(false) end --single-piece ring buffer (no wrap-around). assert(sz >= 1024) local buf = ffi.new('char[?]', sz) local i = 0 --index of first valid byte. local j = 0 --index right after last valid byte. local function more() if j == i then --buffer empty: reset. i, j = 0, 0 elseif j == sz then --no more space at the end. if i == 0 then --buffer full. return nil, 'line too long' else --move data to make space at the end. ffi.copy(buf, buf + i, j - i) i, j = 0, j - i end end local n, err = read(buf + j, sz - j) if n == 0 then return nil, 'eof' end if not n then return nil, err end j = j + n return true end local function readline() if j == i then --buffer empty: refill. local ok, err = more() if not ok then return nil, err end end local n = 0 while true do local found, line_j, next_i = find_term(buf, i + n, j) if found then local s = ffi.string(buf + i, line_j - i) i = next_i return s else n = j - i - (#term - 1) local ok, err = more() if not ok then return nil, err end end end end local function read(maxn) if j == i then --buffer empty: refill. local ok, err = more() if not ok then if err == 'eof' then return buf, 0 end return nil, err end end local n = math.min(maxn, j - i) local buf = buf + i i = i + n return buf, n end return { readline = readline, read = read, } end
21.651786
76
0.610722
815fc30f379ea42bf4cb0a70a90e46521e2ada0b
5,144
asm
Assembly
Transynther/x86/_processed/NC/_zr_/i7-7700_9_0xca.log_21829_879.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NC/_zr_/i7-7700_9_0xca.log_21829_879.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NC/_zr_/i7-7700_9_0xca.log_21829_879.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r9 push %rbp push %rbx push %rcx push %rdi push %rdx lea addresses_WT_ht+0x19c32, %rdi nop nop nop dec %rbx movl $0x61626364, (%rdi) nop nop and %rbp, %rbp lea addresses_WT_ht+0x4222, %rdx nop nop nop nop sub %rcx, %rcx and $0xffffffffffffffc0, %rdx movntdqa (%rdx), %xmm0 vpextrq $1, %xmm0, %rbp nop nop nop nop dec %r14 lea addresses_normal_ht+0xf222, %rdx nop nop nop nop nop add $2532, %r9 movw $0x6162, (%rdx) nop nop nop nop nop add %r9, %r9 lea addresses_normal_ht+0x150bc, %rdx clflush (%rdx) nop nop nop sub %r9, %r9 movups (%rdx), %xmm3 vpextrq $1, %xmm3, %rdi nop nop nop cmp $26596, %r9 pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rax push %rbp push %rbx push %rdx // Store mov $0x16cc10000000c22, %r10 nop nop sub $6982, %rax movw $0x5152, (%r10) // Exception!!! mov (0), %r10 nop nop nop cmp $50072, %rax // Faulty Load mov $0x67d34b0000000a22, %r10 nop nop cmp $10022, %rbx mov (%r10), %rdx lea oracles, %r10 and $0xff, %rdx shlq $12, %rdx mov (%r10,%rdx,1), %rdx pop %rdx pop %rbx pop %rbp pop %rax pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_NC'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
41.483871
2,999
0.658631
4fe54595eab669172518ee123c756c22f3087c56
755
asm
Assembly
Source/interrupt.asm
MarcusCemes/micro-210-project
789f4d5ac713cfa97d2fe5a88218a85addc91265
[ "MIT" ]
null
null
null
Source/interrupt.asm
MarcusCemes/micro-210-project
789f4d5ac713cfa97d2fe5a88218a85addc91265
[ "MIT" ]
null
null
null
Source/interrupt.asm
MarcusCemes/micro-210-project
789f4d5ac713cfa97d2fe5a88218a85addc91265
[ "MIT" ]
null
null
null
; file: interrupt.asm target: ATmega128L-4MHz-STK300 ; Handle program interruptions ; === Interrupts === ; ; Enter a temperature selection menu int6_handler: in _sreg, SREG push b3 rcall _int6_wait_on rcall show_menu rcall _int6_wait_on rcall LCD_clear ; Jump to servo recalibration routine ; Remove the return address from the stack, restore ; SREG and jump to the correct execution point. pop _w pop _w out SREG, _sreg jmp _set_unit ; === Private subroutines === ; ; Wait until the interrupt wire is active-high ; to avoid glitches _int6_wait_on: in _w, PINE sbrs _w, 6 rjmp _int6_wait_on ret
20.972222
59
0.611921
e49c6644ce6988a7e671373ed100ddbb124f0b2d
5,852
go
Go
explorer/explorertypes.go
Deus-Absconditus/hcexplorer
9342d9d61cd094f4e7eaa9e84fbdd58c7f720b03
[ "ISC" ]
3
2018-08-31T08:39:18.000Z
2019-09-27T05:45:45.000Z
explorer/explorertypes.go
Deus-Absconditus/hcexplorer
9342d9d61cd094f4e7eaa9e84fbdd58c7f720b03
[ "ISC" ]
2
2018-09-06T08:58:47.000Z
2019-06-03T16:51:47.000Z
explorer/explorertypes.go
Deus-Absconditus/hcexplorer
9342d9d61cd094f4e7eaa9e84fbdd58c7f720b03
[ "ISC" ]
7
2018-09-01T07:44:57.000Z
2020-11-30T06:50:09.000Z
// Copyright (c) 2017, The Dcrdata developers // See LICENSE for details. package explorer import ( "github.com/HcashOrg/hcd/hcjson" "github.com/HcashOrg/hcd/hcutil" "github.com/HcashOrg/hcexplorer/db/dbtypes" "github.com/HcashOrg/hcexplorer/txhelpers" ) // BlockBasic models data for the explorer's explorer page type BlockBasic struct { Height int64 `json:"height"` Size int32 `json:"size"` Valid bool `json:"valid"` Voters uint16 `json:"votes"` Transactions int `json:"tx"` FreshStake uint8 `json:"tickets"` Revocations uint32 `json:"revocations"` BlockTime int64 `json:"time"` FormattedTime string `json:"formatted_time"` FormattedBytes string } //RichList models data for the RichList's page type RichList struct { Address string `json:"address"` Value float64 `json:"value"` } // TxBasic models data for transactions on the block page type TxBasic struct { TxID string FormattedSize string Total float64 Fee hcutil.Amount FeeRate hcutil.Amount VoteInfo *VoteInfo Coinbase bool } //AddressTx models data for transactions on the address page type AddressTx struct { TxID string FormattedSize string Total float64 Confirmations uint64 Time int64 FormattedTime string RecievedTotal float64 SentTotal float64 } // TxInfo models data needed for display on the tx page type TxInfo struct { *TxBasic SpendingTxns []TxInID Type string Vin []Vin Vout []Vout BlockHeight int64 BlockIndex uint32 Confirmations int64 Time int64 FormattedTime string Mature string VoteFundsLocked string TicketMaturity int64 } // TxInID models the identity of a spending transaction input type TxInID struct { Hash string Index uint32 } // VoteInfo models data about a SSGen transaction (vote) type VoteInfo struct { Validation BlockValidation `json:"block_validation"` Version uint32 `json:"vote_version"` Bits uint16 `json:"vote_bits"` Choices []*txhelpers.VoteChoice `json:"vote_choices"` } // BlockValidation models data about a vote's decision on a block type BlockValidation struct { Hash string `json:"hash"` Height int64 `json:"height"` Validity bool `json:"validity"` } // Vin models basic data about a tx input for display type Vin struct { *hcjson.Vin Addresses []string FormattedAmount string } // Vout models basic data about a tx output for display type Vout struct { Addresses []string Amount float64 FormattedAmount string Type string Spent bool OP_RETURN string } // BlockInfo models data for display on the block page type BlockInfo struct { *BlockBasic Hash string Version int32 Confirmations int64 StakeRoot string MerkleRoot string Tx []*TxBasic Tickets []*TxBasic Revs []*TxBasic Votes []*TxBasic Nonce uint32 VoteBits uint16 FinalState string PoolSize uint32 Bits string SBits float64 Difficulty float64 ExtraData string StakeVersion uint32 PreviousHash string NextHash string TotalSent float64 MiningFee hcutil.Amount StakeValidationHeight int64 } // AddressInfo models data for display on the address page type AddressInfo struct { Address string Limit int64 Offset int64 Transactions []*AddressTx NumFundingTxns int64 NumSpendingTxns int64 KnownFundingTxns int64 NumUnconfirmed int64 TotalReceived hcutil.Amount TotalSent hcutil.Amount Unspent hcutil.Amount Balance *AddressBalance Path string } // AddressBalance represents the number and value of spent and unspent outputs // for an address. type AddressBalance struct { Address string NumSpent int64 NumUnspent int64 TotalSpent int64 TotalUnspent int64 } // ReduceAddressHistory generates a template AddressInfo from a slice of // dbtypes.AddressRow. All fields except NumUnconfirmed and Transactions are set // completely. Transactions is partially set, with each transaction having only // the TxID and ReceivedTotal set. The rest of the data should be filled in by // other means, such as RPC calls or database queries. func ReduceAddressHistory(addrHist []*dbtypes.AddressRow) *AddressInfo { if len(addrHist) == 0 { return nil } var received, sent int64 var numFundingTxns, numSpendingTxns int64 var transactions []*AddressTx for _, addrOut := range addrHist { numFundingTxns++ coin := hcutil.Amount(addrOut.Value).ToCoin() // Funding transaction received += int64(addrOut.Value) tx := AddressTx{ TxID: addrOut.FundingTxHash, RecievedTotal: coin, } transactions = append(transactions, &tx) // Is the outpoint spent? if addrOut.SpendingTxHash == "" { continue } // Spending transaction numSpendingTxns++ sent += int64(addrOut.Value) spendingTx := AddressTx{ TxID: addrOut.SpendingTxHash, SentTotal: coin, } transactions = append(transactions, &spendingTx) } return &AddressInfo{ Address: addrHist[0].Address, Transactions: transactions, NumFundingTxns: numFundingTxns, NumSpendingTxns: numSpendingTxns, TotalReceived: hcutil.Amount(received), TotalSent: hcutil.Amount(sent), Unspent: hcutil.Amount(received - sent), } } // WebsocketBlock wraps the new block info for use in the websocket type WebsocketBlock struct { Block BlockBasic `json:"block"` }
26.36036
80
0.669686
bd2e43548a092e433794ffa49b300cc14183c08d
404
lua
Lua
lib/Change.lua
jmargh/roact
37f0b13688fa0ba3612713fbf7f7e864db0dfe96
[ "Apache-2.0" ]
null
null
null
lib/Change.lua
jmargh/roact
37f0b13688fa0ba3612713fbf7f7e864db0dfe96
[ "Apache-2.0" ]
null
null
null
lib/Change.lua
jmargh/roact
37f0b13688fa0ba3612713fbf7f7e864db0dfe96
[ "Apache-2.0" ]
null
null
null
local Change = {} local changeMetatable = { __tostring = function(self) return ("ChangeListener(%s)"):format(self.name) end } setmetatable(Change, { __index = function(self, propertyName) local changeListener = { type = Change, name = propertyName } setmetatable(changeListener, changeMetatable) Change[propertyName] = changeListener return changeListener end, }) return Change
17.565217
49
0.725248
bcce217bde732e22ad8822892c92686ed9e15a62
351,615
js
JavaScript
public/assets/vendor/jTS/jTS.js
TigerStudios/solar-system
0ca86bb2e90e7ba9155a57d41ca588860de16ac4
[ "MIT" ]
null
null
null
public/assets/vendor/jTS/jTS.js
TigerStudios/solar-system
0ca86bb2e90e7ba9155a57d41ca588860de16ac4
[ "MIT" ]
null
null
null
public/assets/vendor/jTS/jTS.js
TigerStudios/solar-system
0ca86bb2e90e7ba9155a57d41ca588860de16ac4
[ "MIT" ]
null
null
null
'use strict'; jTS.prototype = Object.create(Array.prototype); jTS.prototype.constructor = jTS; jTS.fn = jTS.prototype; /** * * @param set {Array} * @param selector {Object} */ jTS.ts = function(set, selector){ /*jTS constructor fingerprint*/ for (let i = 0; i < set.length; i++) { this.push(set[i]); } this.selector = selector; }; jTS.ts.prototype = Object.create(jTS.prototype); jTS.ts.prototype.constructor = jTS.ts; const _ = jTS; /** * * @param selector {*} * @return {jTS} */ function jTS(/*string || number || window || document || Node List || DOM Element || jTS || Array[Any] || Function*/selector) { if (typeof selector === 'function') { setDocumentReady(selector); return null; } let set = init(selector); return new jTS.ts(set, selector); function init(/*String || Number || Window || Document || Node List || DOM Element || jTS Object || Array[Object]*/selector) { let set = []; if (!selector) { /*Don' t do anything*/ } else { parseSelector(selector); } function parseSelector(selector) { let constructor = String(selector.constructor); if (selector === window) { set.push(window); } else if (selector === document) { set.push(document); } else if (constructor.match(/NodeList/) || constructor.match(/HTMLCollection/)) { for (let i = 0; i < selector.length; i++) { if (selector[i].nodeType !== 3) { set.push(selector[i]); } } } else if (constructor.match(/HTML[a-zA-z]+Element/) || constructor.match(/SVG[a-zA-z]+Element/) || constructor.match(/HTMLElement/)) { set.push(selector); } else if (constructor.match(/Array/)) { parseSelectorArray(selector); } else if (constructor.match(/String/)) { parseStringSelector(selector); } else if (constructor.match(/Number/)) { parseStringSelector(String(selector)); } else if(constructor.match(/\/\*jTS constructor fingerprint\*\//)){ selector.each(function(i,e){ set.push(e); }); } else { console.log('not-a-valid-selector : ' + selector); } } function parseSelectorArray(selector) { for (let i = 0; i < selector.length; i++) { parseSelector(selector[i]); } } function parseStringSelector(selector) { if (selector.match(/^</)) { createElement(selector); } else { try { let element = document.querySelectorAll(selector); if (element && element.length !== 0) { parseSelector(element); } } catch (e) { //do nothing } } } function createElement(selector) { let canvas = document.createElement('div'); if (selector.match(/^<thead/) || selector.match(/^<tbody/) || selector.match(/^<tfoot/)) { canvas = document.createElement('table'); } else if (selector.match(/^<tr/)) { canvas = document.createElement('tbody'); } else if (selector.match(/^<td/) || selector.match(/^<th/)) { canvas = document.createElement('tr'); } canvas.innerHTML = selector; for (let i = 0; i < canvas.childNodes.length; i++) { set.push(canvas.childNodes[i]); } } return set; } function setDocumentReady(f) { if (window.addEventListener) { window.addEventListener('load', f, false) } else if (window.attachEvent) { window.attachEvent('load', f); } } } /*AJAX PACKAGE*/ /** * * @param colorScheme {Object} * @param configuration {Object} * @return {jTS} */ jTS.fn.gearsProgress =/*jTS*/function (/*Object literal || Null*/colorScheme,/*Object literal*/configuration) { const t = this; if(t.length === 0){ return t; } const GEAR_ONE_SR = 0; const GEAR_TWO_SR = 18; const GEAR_THREE_SR = 23; const ROTATION_VR = 5; let color_one = colorScheme && colorScheme.gear_one_color ? colorScheme.gear_one_color : '#ff0000'; let color_two = colorScheme && colorScheme.gear_two_color ? colorScheme.gear_two_color : '#00ff00'; let color_three = colorScheme && colorScheme.gear_three_color ? colorScheme.gear_three_color : '#0000ff'; let color_bg = colorScheme && colorScheme.container_color ? colorScheme.container_color : 'rgba(0,0,0,0.8)'; let progress_color = colorScheme && colorScheme.progress_color ? colorScheme.progress_color :'#ff0000'; let resizeID = null; let inAnimation = true; let container = document.createElement('div'); let gear_one = _('<div id="gear_one_jts_gears_progress"><i class="fa fa-cog" style="position:absolute;top:0;left:0;"></i></div>').css({ 'color' : color_one }); let gear_two = _('<div id="gear_two_jts_gears_progress"><i class="fa fa-cog" style="position:absolute;top:0;left:0;"></i></div>').css({ 'color' : color_two }); let gear_three = _('<div id="gear_three_jts_gears_progress"><i class="fa fa-cog" style="position:absolute;top:0;left:0;"></i></div>').css({ 'color' : color_three }); let gear_one_Rotation = GEAR_ONE_SR; let gear_two_Rotation = GEAR_TWO_SR; let gear_three_Rotation = GEAR_THREE_SR; addListeners(); addGraphic(); function activateProgress(){ let progressBar = document.createElement('div'); _(progressBar).css({ 'height' : 50, 'position' : 'absolute', 'left' : 0, 'bottom' : 0, 'background-color' : progress_color, 'width' : 0 }); _(container).append(progressBar); _(window).on(jTS.built_in_events.jREQUEST_PROGRESS_EVENT,function(e){ let width = 100 * (e.data.original_event.loaded / e.data.original_event.total); _(progressBar).css('width',width + '%'); }); _(window).on(jTS.built_in_events.jREQUEST_END_EVENT,function(e){ dispose(); }); jTS.jRequest(configuration.url,configuration.request_configuration); } function addGraphic() { let css = { 'position':'fixed', 'left': 0, 'top': 0, 'z-index':10000, 'width': '100%', 'height': '100vh', 'background-color': color_bg, }; gear_one.css('transform', 'rotateZ(' + GEAR_ONE_SR + 'deg)'); gear_two.css('transform', 'rotateZ(' + GEAR_TWO_SR + 'deg)'); gear_three.css('transform', 'rotateZ(' + GEAR_THREE_SR + 'deg)'); _(container).attr('id', 'jts_gears_progress').css(css); _(container).append(gear_one); _(container).append(gear_two); _(container).append(gear_three); setGearsSize(); _('body').append(container); if(configuration && configuration.show_progress){ activateProgress(); } requestAnimationFrame(animateGears); } function addListeners(){ _(window).bind('resize.jts_gears_progress',function(){ clearTimeout(resizeID); resizeID = setTimeout(function(){ setGearsSize(); },100); }); } function animateGears() { gear_one_Rotation += ROTATION_VR; gear_two_Rotation -= ROTATION_VR; gear_three_Rotation -= ROTATION_VR; gear_one.css('transform', 'rotateZ(' + gear_one_Rotation + 'deg)'); gear_two.css('transform', 'rotateZ(' + gear_two_Rotation + 'deg)'); gear_three.css('transform', 'rotateZ(' + gear_three_Rotation + 'deg)'); if(inAnimation) { requestAnimationFrame(animateGears); } } function dispose(){ inAnimation = false; _(window).unbind('.jts_gears_progress'); _(window).off(jTS.built_in_events.jREQUEST_PROGRESS_EVENT); _(window).off(jTS.built_in_events.jREQUEST_END_EVENT); _(container).dispose(); } function getGearsSize(index, width) { const INDEX_DELAY = 6; const INDEX_T_DELAY = 11; const SIZES_SET = [0, 415, 737, 1025, 1981, 10000, 120, 150, 180, 200, 230, 120, 150,180,200,230]; if (width >= SIZES_SET[index] && width < SIZES_SET[index + 1]) { return {'gear_size':SIZES_SET[index + INDEX_DELAY],'font_size':SIZES_SET[index + INDEX_T_DELAY]} } else { return getGearsSize(index + 1, width); } } function setGearsSize() { let width = _(window).width(); let height = _(window).height(); let sizes = getGearsSize(0, width); let gear_size = sizes.gear_size; let font_size = sizes.font_size; let one_left = Math.round((width * 0.5) - (gear_size * 0.89)); let one_top = Math.round((height * 0.5) - (gear_size * 0.5)); let two_left = Math.round((width * 0.5) - (gear_size * 0.15)); let two_top = Math.round((height * 0.5) - (gear_size * 1.06)); let three_left = Math.round((width * 0.5) - (gear_size * 0.030)); let three_top = Math.round((height * 0.5) - (gear_size * 0.100)); let gearCss = { 'width': gear_size, 'height': gear_size, 'position': 'absolute' }; gear_one.css(gearCss).css({ 'left': one_left, 'top': one_top, 'font-size': font_size }); gear_two.css(gearCss).css({ 'left': two_left, 'top': two_top, 'font-size': font_size }); gear_three.css(gearCss).css({ 'left': three_left, 'top': three_top, 'font-size': font_size }); } return t; }; /** * * @param url {string} * @param success {Function} * @param errorOrData {Function} * @return {void} */ jTS.jJSON = /*void*/function (/*string*/url,/*Function*/ success,/*Function*/ errorOrData) { if (arguments.length < 2) { console.log('invalid-arguments-list @ jTS.jJSON'); return; } let successCB = success; let errorCB = function (e) { console.log(e); }; let postData = {}; if (arguments.length === 3) { errorCB = arguments[2]; } /*if (arguments.length === 4) { errorCB = arguments[2]; postData = arguments[3]; } let form = new FormData(); for (let n in postData) { if(postData.hasOwnProperty(n)){ form.append(n, postData[n]); } }*/ let r = new XMLHttpRequest(); r.open('get', url); //r.setRequestHeader('X-CSRF-TOKEN', ''); r.onreadystatechange = function () { if (r.readyState === 4) { if (r.status === 200) { let currentObject; try { currentObject = JSON.parse(r.response); } catch (e) { errorCB('return-only-JSON-format @jTS.jJSON'); } if (currentObject) { successCB(currentObject); } } else { errorCB('request-server-error @ jTS.jJSON'); } } }; r.send(null); }; /** * * @param url {string} * @param configuration {Object} */ jTS.jRequest = /*void*/function (/*string*/url,/*Object literal*/configuration) { const MAXIMUM_ATTEMPTS = 3; let method = configuration && configuration.method ? configuration.method : 'get'; let successCB = configuration && configuration.success ? configuration.success : function (d) { console.log(d) }; let errorCB = configuration && configuration.error ? configuration.error : function (e) { console.log(e) }; let type = configuration && configuration.type ? configuration.type : 'download'; let data = configuration && configuration.data ? configuration.data : {}; let csrfToken = configuration && configuration.csrf_token ? configuration.csrf_token : null; let attempt = configuration && configuration.attempt ? configuration.attempt : 0; let dataForm = null; if (method.toLowerCase() === 'post') { dataForm = new FormData(); for (let n in data) { dataForm.append(n,data[n]); } } let r = new XMLHttpRequest(); r.open(method, url); if(csrfToken){ r.setRequestHeader('X-CSRF-TOKEN', csrfToken); } if (url.toLowerCase().match(/.jpg$/) || url.toLowerCase().match(/.jpg?/) || url.toLowerCase().match(/.png$/) || url.toLowerCase().match(/.png?/) || url.toLowerCase().match(/.tiff$/) || url.toLowerCase().match(/.tiff?/) || url.toLowerCase().match(/.gif$/) || url.toLowerCase().match(/.gif?/)) { r.responseType = 'arraybuffer'; } r.onreadystatechange = function () { if (r.readyState === 4) { if (r.status === 200 || r.status === 201) { successCB(r.response); } else { attempt += 1; if(attempt < MAXIMUM_ATTEMPTS){ console.log(`REQUEST ATTEMPT #${attempt} FAIL`); configuration = configuration ? configuration : {}; configuration.attempt = attempt; jTS.jRequest(url,configuration); }else{ errorCB('request-server-error @jTS.jRequest'); } } } }; r.addEventListener('loadstart', function (e) { _(window).emits(jTS.built_in_events.jREQUEST_START_EVENT, { 'original_event': e }); }); r.addEventListener('loadend', function (e) { _(window).emits(jTS.built_in_events.jREQUEST_END_EVENT, { 'original_event': e }); }); r.onerror = function (error) { attempt++; if(attempt < MAXIMUM_ATTEMPTS){ console.log(`REQUEST ATTEMPT #${attempt} FAIL`); configuration = configuration ? configuration : {}; configuration.attempt = attempt; jTS.jRequest(url,configuration); }else{ errorCB('request-server-error @jTS.jRequest'); } }; switch (type) { case 'download': r.onprogress = progress; break; case 'upload': r.upload.onprogress = progress; break; default: r.onprogress = progress; break; } try{ r.send(dataForm); }catch(e){ attempt += 1; if(attempt < MAXIMUM_ATTEMPTS){ console.log(`REQUEST ATTEMPT #${attempt} FAIL`); configuration = configuration ? configuration : {}; configuration.attempt = attempt; jTS.jRequest(url,configuration); }else{ errorCB('request-server-error @jTS.jRequest'); } } function progress(e) { _(window).emits(jTS.built_in_events.jREQUEST_PROGRESS_EVENT, {'original_event':e}); } }; /** * * @param urls {*} * @param success {Function} * @param error {Function} * @return {jTS} */ jTS.fn.load = /*jTS*/function (/*string || Array[string]*/urls,/*Function*/ success,/*Function*/ error) { const t = this; let successCB = null; let errorCB = null; let responses = []; if (arguments.length === 2) { if (typeof arguments[1] === 'function') { successCB = arguments[1]; } } if (arguments.length === 3) { if (typeof arguments[1] === 'function') { successCB = arguments[1]; } if (typeof arguments[2] === 'function') { errorCB = arguments[2]; } } if (typeof arguments[0] === 'string') { urls = [urls]; } let index = 0; pushResponse(index); function pushResponse(index) { if (index < urls.length) { let r = new XMLHttpRequest(); r.open('get', urls[index]); r.onreadystatechange = function () { if (r.readyState === 4) { if (r.status === 200) { let contentType = String(r.getResponseHeader("Content-Type")); if (contentType.indexOf("html") !== -1) { responses.push(r.responseText); pushResponse(index + 1); } else { if (errorCB) { errorCB('load-only-html-files @jTS.load'); } } } else { if (errorCB) { errorCB('request-server-error-for-index-' + index + ' @jTS.load'); } } } }; r.onerror = function (e) { if (errorCB) { errorCB(e); } }; r.send(null); } else { t.each(displayResponse); } } function displayResponse(i, e) { if (responses.length === 1 || i >= responses.length) { parseResponse(responses[0], 0); } else { parseResponse(responses[i], i); } function parseResponse(val, index) { e.innerHTML = ''; let canvas = document.createElement('div'); canvas.innerHTML = val; let counter = canvas.childNodes.length; for (let h = 0; h < counter; h++) { if (canvas.childNodes[0]) { e.appendChild(canvas.childNodes[0]); } } if (successCB) { successCB(responses[index], i, e); } } } return this; }; /*END AJAX PACKAGE*/ /*ANIMATION PACKAGE*/ /** * * @param d {int} * @param configuration {Object} * @return {jTS} */ jTS.fn.hide = /*jTS*/function (/*int*/d,/*Object literal*/configuration) { const t = this; const TIME_GAP = 100; let property = 'opacity'; let easing = 'linear'; if (arguments.length === 0) { t.each(function (i, e) { if (_(e).css('display') === 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } jTS.originalStyles.push([e, _(e).attr('style')]); _(e).css('display', 'none'); }); } else if (arguments.length === 1 && typeof arguments[0] === 'number') { t.each(fade); } else if (arguments.length === 2 && typeof arguments[0] === 'number' && typeof arguments[1] === 'object') { property = configuration.method === 'slide' ? 'height' : property; easing = configuration.easing ? configuration.easing : easing; if (configuration.method === 'fade' || !(configuration.method)) { t.each(fade); } else if (configuration.method === 'slide') { t.each(slide); } } else { console.log('invalid-arguments-list @ jTS.hide'); } function fade(i, e) { if (_(e).css('display') === 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } jTS.originalStyles.push([e, _(e).attr('style')]); _(e).attr('jts_hidden', true); if (configuration && configuration.startCB) { configuration.startCB(i, e); } let originalStyle = _(e).attr('style'); let style = null; if (originalStyle) { if (originalStyle.match('opacity:')) { style = originalStyle; } else { style = originalStyle + 'opacity:' + _(e).css('opcacity') + ';'; } } else { originalStyle = ''; style = 'opacity:' + _(e).css('opcacity') + ';'; } _(e).attr('style', style); _(e).css('transition', property + ' ' + (d / 1000) + 's ' + easing + ' 0s'); setTimeout(function () { _(e).css('opacity', 0); }, 1); setTimeout(function () { if (_(e).attr('jts_hidden')) { _(e).attr('style', originalStyle); _(e).css('display', 'none'); e.attributes.removeNamedItem('jts_hidden'); if (configuration && configuration.endCB) { configuration.endCB(i, e); } } }, d + TIME_GAP); } function slide(i, e) { if (_(e).css('display') === 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } jTS.originalStyles.push([e, _(e).attr('style')]); _(e).attr('jts_hidden', true); if (configuration && configuration.startCB) { configuration.startCB(i, e); } let wrapper = document.createElement('div'); let originalStyle = _(e).attr('style') || ''; let parent = _(e).offsetPs(); let wrapperCss = { 'overflow': 'hidden', 'box-shadow': _(e).css('box-shadow'), 'height': _(e).outerHeight(), 'width': _(e).outerWidth(), 'float': _(e).css('float'), 'margin-left': _(e).css('margin-left'), 'margin-right': _(e).css('margin-right'), 'margin-bottom': _(e).css('margin-bottom'), 'margin-top': _(e).css('margin-top'), 'border-radius': _(e).css('border-radius'), 'left': _(e).css('left'), 'top': _(e).css('top'), 'right': _(e).css('right'), 'bottom': _(e).css('bottom'), 'position': _(e).css('position'), 'z-index': _(e).css('z-index'), 'padding' : 0 }; let eCss = { 'margin-left': 0, 'margin-right': 0, 'margin-bottom': 0, 'margin-top': 0, 'box-shadow': 'none', 'border-radius': 0, 'width': '100%', 'left': 0, 'top': 0, 'right': 0, 'bottom': 0, 'position': 'absolute', 'z-index': 0 }; _(wrapper).css(wrapperCss).addClass('jts_hide_wrapper'); parent.before(wrapper, e); _(wrapper).append(e); _(e).css(eCss); _(wrapper).css('transition', property + ' ' + (d / 1000) + 's ' + easing + ' 0s'); setTimeout(function () { _(wrapper).css('height', 0); }, TIME_GAP * 0.3); setTimeout(function () { if (_(e).attr('jts_hidden')) { _(e).attr('style', originalStyle); _(e).css('display', 'none'); parent.before(e, wrapper); parent[0].removeChild(wrapper); e.attributes.removeNamedItem('jts_hidden'); if (configuration && configuration.endCB) { configuration.endCB(i, e); } } }, d + (TIME_GAP * 2)); } return this; }; /** * * @param duration {int} * @param draw {Function} * @param options {Object} * @return {void} */ jTS.jAnimate = /*void*/function (/*int*/duration,/*Function*/draw,/*Object*/options) { let start = performance.now(); let n = options.coefficient || 1; let delay = options.delay || 0; let elapsed = 0; let enabled = false; let paused = false; let timing; switch (options.timing_function){ case 'linear' : timing = linear; break; case 'accelerate' : timing = accelerate; break; case 'arc' : timing = arc; break; case 'bowShooting' : timing = bowShooting; break; case 'bounce' : timing = bounce; break; case 'elastic' : timing = elastic; break; default : timing = linear; break; } if(options.ease_out){ timing = makeEaseOut(timing); }else if(options.ease_in_out){ timing = makeEaseInOut(timing); } let target = _(`<div class="jAnimate_target"></div>`); target.on(jTS.built_in_events.jANIMATE_PAUSE,() => paused = true); target.on(jTS.built_in_events.jANIMATE_RESUME,() => { start = performance.now() - elapsed; paused = false; }); startAnimation(); function startAnimation() { requestAnimationFrame(function animate(time){ if(!paused){ elapsed = time - start; } if(elapsed >= delay && !enabled){ start = time; enabled = true; } if(enabled && !paused){ let fraction = (time - start) / duration; if(fraction > 1){ fraction = 1; } let progress = timing(fraction,n); if(options.reverse){ progress = 1 - progress; } draw(progress); if (fraction < 1){ requestAnimationFrame(animate); }else{ target.off(jTS.built_in_events.jANIMATE_PAUSE); target.off(jTS.built_in_events.jANIMATE_RESUME); if(options.callback){ options.callback(); } } }else{ requestAnimationFrame(animate); } }); } function linear(fraction){ return fraction; } function accelerate(fraction,n) { return Math.pow(fraction, n); } function arc(fraction) { return 1 - Math.sin(Math.acos(fraction)); } function bowShooting(fraction , n) { return Math.pow(fraction, 2) * ((n + 1) * fraction - n); } function bounce(fraction) { for (let a = 0, b = 1, result; 1; a += b, b /= 2) { if (fraction >= (7 - 4 * a) / 11) { return -Math.pow((11 - 6 * a - 11 * fraction) / 4, 2) + Math.pow(b, 2); } } } function elastic(fraction , n) { return Math.pow(2, 10 * (fraction - 1)) * Math.cos(20 * Math.PI * n / 3 * fraction); } function makeEaseOut(timing) { return function(fraction,n) { return 1 - timing(1 - fraction , n); } } function makeEaseInOut(timing) { return function(fraction , n) { if (fraction < .5){ return timing(2 * fraction , n) / 2; }else{ return (2 - timing(2 * (1 - fraction) , n)) / 2; } } } }; /** * * @param windowW {boolean} * @param nColumns {Array} * @param items {int} * @return {jTS} */ jTS.fn.masonry = /*jTS*/function(/*boolean*/windowW,/*Array[int]*/nColumns,/*int*/items){ const t = this; if(t.length === 0){ return t; } let container = t.offsetPs(); let initialized = false; let containerWidth = 0; let columns = 0; let currentWidth = 0; let columnsHeight = []; let orderedItems = null; let display = items; setElementsWidth(); init(); function init(){ /*Don't know if want to use this function*/ //updateOrder(); t.each(function(i,e){ _(e).css({ 'position' : 'absolute' , 'transition' : 'left 0.5s ease-out , top 0.5s ease-out', 'height' : 'auto', }); }); computeMasonry(); addListeners(); if(!initialized){ initialized = true; _(window).emits(jTS.built_in_events.jMASONRY_READY); } } function addListeners(){ _(window).bind('resize.jts_masonry_events',function(e){ computeMasonry(); }); _(window).on(jTS.built_in_events.jMASONRY_RESIZE,function(e){ if(e.data.display){ display = e.data.display; } computeMasonry(); }); _(window).on(jTS.built_in_events.jEXTERNAL_RESIZE,function(e){ computeMasonry(); }); } function computeMasonry(){ setElementsWidth(); columnsHeight = []; for(let i = 0; i < columns ; i++){ columnsHeight[i] = 0; } t.each(function(i,e){ if(i === 0){ currentWidth = _(e).outerWidth(); } let x = Math.floor(i % columns) * currentWidth; _(e).css('left',x).css('top',columnsHeight[Math.floor(i % columns)]); if(!display || i < display){ columnsHeight[Math.floor(i % columns)] += Math.floor(_(e).outerHeight()); } }); container.css('height',getColumnHeight()); } function getColumnHeight(){ let height = 0; for(let i = 0; i < columnsHeight.length ; i++){ if(columnsHeight[i] > height){ height = columnsHeight[i] } } return height; } function getContainerWidth(){ if(windowW){ return _(window).outerWidth(); } else{ return container.outerWidth(); } } function setElementsWidth(){ containerWidth = getContainerWidth(); columns = containerWidth <= 414 ? 1 : (containerWidth <= 812 ? 2 : (containerWidth <= 1024 ? 3 : 4)); if(nColumns){ columns = containerWidth <= 414 ? nColumns[0] : (containerWidth <= 812 ? nColumns[1] : (containerWidth <= 1024 ? nColumns[2] : nColumns[3])); } let width = Math.round(containerWidth / columns); t.each(function(i,e){ let currentWidth = Math.floor(i % columns) === columns - 1 ? containerWidth - (width * Math.floor(i % columns)) : width; _(e).css('width' , currentWidth); }); } function updateOrder() { let temporaryArray = []; if(!initialized){ t.each(function(i,e){ temporaryArray.push(e); }); } else{ for(let i = 0 ; i < orderedItems.length ; i++){ let random = Math.floor(Math.random() * orderedItems.length); temporaryArray.push(orderedItems[random]); orderedItems.splice(random,1); i--; } } orderedItems = null; orderedItems = _(temporaryArray); } return this; }; /** * * @param configuration {Object} * @return {jTS} */ jTS.fn.particlesFX = /*jTS*/function(/*Object literal*/configuration){ const t = this; //Function is designed for one canvas at time if(t.length !== 1 || t[0].tagName.toLowerCase() !== 'canvas'){ return t; } //Device pixel ratio let ratio = window.devicePixelRatio || 1; //Constants let PARTICLES_NUMBER = configuration && configuration.particles_number ? configuration.particles_number : [150,80,50]; let PARTICLE_SIZE = configuration && configuration.particles_size? configuration.particles_size : 15; let PARTICLE_MIN_SIZE = configuration && configuration.particles_min_size ? configuration.particles_min_size : 5; let FRAME_RATE = 16; let VELOCITY = 2 * ratio; let VELOCITY_SCALE = 1; let BOUNDARY_GAP = 30 * ratio; let MINIMUM_DISTANCE = configuration && configuration.minimum_distance ? configuration.minimum_distance * configuration.minimum_distance : 150 * 150; let POINTER_MINIMUM_DISTANCE = configuration && configuration.pointer_minimum_distance ? configuration.pointer_minimum_distance * configuration.pointer_minimum_distance : 180 * 180; let POINTER_MINIMUM_DISTANCE_ROOT_SQUARE = configuration && configuration.pointer_minimum_distance ? configuration.pointer_minimum_distance : 180; let MEDIUM_SCREEN_SIZE = 736; let SMALL_SCREEN_SIZE = 414; let RESIZE_DELAY = 100; //general variables; let canvas = t[0]; let container = t.offsetPs(); let brush = canvas.getContext('2d'); let particles = []; let stageWidth = 0; let stageHeight = 0; let pointerActive = false; let pointerX = 0; let pointerY = 0; let resizeID = null; //The Particle Object Class Particle.prototype = Object.create({}); Particle.prototype.constructor = Particle; function Particle(x,y,size){ this.x = x; this.y = y; this.size = size; //Set particle velocity this.vX = VELOCITY * ((Math.random() * (VELOCITY_SCALE - -VELOCITY_SCALE)) + -VELOCITY_SCALE); this.vY = VELOCITY * ((Math.random() * (VELOCITY_SCALE - -VELOCITY_SCALE)) + -VELOCITY_SCALE); } Particle.prototype.update = function(pointerX , pointerY){ //Update particle position this.x += this.vX; this.y += this.vY; //Check if particle is out of boundaries if(this.x < 0 - BOUNDARY_GAP || this.x > stageWidth + BOUNDARY_GAP){ this.x = this.x < 0 ? stageWidth + BOUNDARY_GAP : 0 - BOUNDARY_GAP; } if(this.y < 0 - BOUNDARY_GAP || this.y > stageHeight + BOUNDARY_GAP){ this.y = this.y < 0 ? stageHeight + BOUNDARY_GAP : 0 - BOUNDARY_GAP; } //Check pointer interaction let dX = pointerX - this.x; let dY = pointerY - this.y; let distance = dX * dX + dY * dY; if(distance < POINTER_MINIMUM_DISTANCE && pointerActive){ let radians = Math.atan2(dY,dX); this.x = pointerX - (POINTER_MINIMUM_DISTANCE_ROOT_SQUARE * Math.cos(radians)); this.y = pointerY - (POINTER_MINIMUM_DISTANCE_ROOT_SQUARE * Math.sin(radians)); } }; setSize(); init(); addListeners(); animate(); _(canvas).emits(jTS.built_in_events.jPARTICLES_FX_READY); function addListeners(){ _(window).bind('resize.jts_particles_fx_events',function(){ clearTimeout(resizeID); resizeID = setTimeout(function(){ setSize(); init(); },RESIZE_DELAY); }).bind('mousemove.jts_particles_fx_events',function(e){ let pointerLocalCoordinates = getPointerLocalCoordinates(e.globalX,e.globalY); pointerX = pointerLocalCoordinates.x; pointerY = pointerLocalCoordinates.y; }); _(canvas).bind('mouseover.jts_particles_fx_events',function(e){ pointerActive = true; }).bind('mouseout.jts_particles_fx_events',function(e){ pointerActive = false; }); } function animate(){ //Clear the stage brush.clearRect(0,0,stageWidth,stageHeight); brush.fillStyle = configuration && configuration.color ? ('rgba(' + configuration.color[0] + ',' + configuration.color[1] + ',' + configuration.color[2] + ',0.5)') : 'rgba(207,207,207,0.5)'; for(let i = 0; i < particles.length; i++){ let particle = particles[i]; //Draw particle brush.beginPath(); brush.arc(particle.x,particle.y,particle.size * 0.5,0,Math.PI * 2); brush.closePath(); brush.fill(); for(let l = i + 1 ; l < particles.length; l++){ let other = particles[l]; let dX = other.x - particle.x; let dY = other.y - particle.y; let distance = dX * dX + dY * dY; //If two particles are close enough draw connection line if(distance < (MINIMUM_DISTANCE * ratio)){ let styleData = getBrushStyle(distance); brush.lineWidth = styleData.lineWidth; brush.strokeStyle = configuration && configuration.color ? ('rgba(' + configuration.color[0] + ',' + configuration.color[1] + ',' + configuration.color[2] + ',' + styleData.opacity + ')') : 'rgba(207,207,207,' + styleData.opacity + ')'; brush.beginPath(); brush.moveTo(particle.x,particle.y); brush.lineTo(other.x,other.y); brush.closePath(); brush.stroke() } } //Update particle position for new frame particle.update(pointerX,pointerY); } setTimeout(function(){ animate(); },FRAME_RATE); } function getBrushStyle(distance){ let opacity = "0"; let lineWidth = 0; if(distance >= (MINIMUM_DISTANCE * ratio) * 0.8){ opacity = '0.1'; lineWidth = 0.2; } else if(distance < (MINIMUM_DISTANCE * ratio) * 0.8 && distance >= (MINIMUM_DISTANCE * ratio) * 0.6){ opacity = '0.2'; lineWidth = 0.3; } else if(distance < (MINIMUM_DISTANCE * ratio) * 0.6 && distance >= (MINIMUM_DISTANCE * ratio) * 0.4){ opacity = '0.3'; lineWidth = 0.4; } else if(distance < (MINIMUM_DISTANCE * ratio) * 0.4 && distance >= (MINIMUM_DISTANCE * ratio) * 0.2){ opacity = '0.4'; lineWidth = 0.4; } else{ opacity = '0.5'; lineWidth = 0.5; } return {'opacity':opacity,'lineWidth':lineWidth * ratio}; } function getParticleSize(startSize){ startSize = startSize * ratio; let random = Math.ceil(Math.random() * startSize); let size = random - Math.floor(Math.random() * (startSize * 0.5)); size = size < (PARTICLE_MIN_SIZE * ratio) ? (PARTICLE_MIN_SIZE * ratio) : size; return size; } function getPointerLocalCoordinates(x,y){ let parent = canvas; while(parent){ x -= parent.offsetLeft; y -= parent.offsetTop; parent = parent.offsetParent; } return {'x':x * ratio,'y':y * ratio}; } function init(){ makeParticle(0); //This make a new particle function makeParticle(index){ //How many particles based on stage size let numberIndex = container.outerWidth() > MEDIUM_SCREEN_SIZE ? 0 : (container.outerWidth() <= SMALL_SCREEN_SIZE ? 2 : 1 ); if(index < PARTICLES_NUMBER[numberIndex]){ let particle = new Particle(Math.random() * stageWidth , Math.random() * stageHeight , getParticleSize(PARTICLE_SIZE)); particles.push(particle); makeParticle(index + 1); } } } function setSize(){ //Reset particles if necessary particles = []; //Reset stage size if(container != null){ stageWidth = container.outerWidth(); stageHeight = container.outerHeight(); } else{ stageWidth = _(window).outerWidth(); stageHeight = _(window).outerHeight(); } stageWidth = stageWidth * ratio; stageHeight = stageHeight * ratio; canvas.width = stageWidth; canvas.height = stageHeight; } return this; }; /** * * @param d {int} * @param configuration {Object} * @return {jTS} */ jTS.fn.show = /*jTS*/function (/*int*/d,/*Object literal*/configuration) { const t = this; const TIME_GAP = 100; let property = 'opacity'; let easing = 'linear'; if (arguments.length === 0) { t.each(function (i, e) { if (_(e).css('display') !== 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } setElementStyle(e); }); } else if (arguments.length === 1 && typeof arguments[0] === 'number') { t.each(fade); } else if (arguments.length === 2 && typeof arguments[0] === 'number' && typeof arguments[1] === 'object') { property = configuration.method === 'slide' ? 'height' : property; easing = configuration.easing ? configuration.easing : easing; if (configuration.method === 'fade' || !(configuration.method)) { t.each(fade); } else if (configuration.method === 'slide') { t.each(slide); } } else { console.log('invalid-arguments-list @jTS.show'); } function fade(i, e) { if (_(e).css('display') !== 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } _(e).attr('jts_showed', true); if (configuration && configuration.startCB) { configuration.startCB(i, e); } let originalOpacity = parseFloat(_(e).css('opacity')); setElementStyle(e); jTS.originalStyles.push([e, _(e).attr('style')]); _(e).css('opacity', 0); _(e).css('transition', property + ' ' + (d / 1000) + 's ' + easing + ' 0s'); setTimeout(function () { if (_(e).length > 0) { _(e).css('opacity', originalOpacity); } }, 1); setTimeout(function () { if (_(e).attr('jts_showed')) { setElementStyle(e); e.attributes.removeNamedItem('jts_showed'); if (configuration && configuration.endCB) { configuration.endCB(i, e); } } }, d + TIME_GAP); } function slide(i, e) { if (_(e).css('display') !== 'none' || _(e).attr('jts_hidden') || _(e).attr('jts_showed')) { return; } _(e).attr('jts_showed', true); if (configuration && configuration.startCB) { configuration.startCB(i, e); } setElementStyle(e); jTS.originalStyles.push([e, _(e).attr('style')]); let wrapper = document.createElement('div'); let originalStyle = _(e).attr('style') || ''; let height = _(e).outerHeight(); let parent = _(e).offsetPs(); let wrapperCss = { 'overflow': 'hidden', 'box-shadow': _(e).css('box-shadow'), 'height': 0, 'width': _(e).outerWidth(), 'float': _(e).css('float'), 'margin-top': _(e).css('margin-top'), 'margin-left': _(e).css('margin-left'), 'margin-right': _(e).css('margin-right'), 'margin-bottom': _(e).css('margin-bottom'), 'border-radius': _(e).css('border-radius'), 'left': _(e).css('left'), 'top': _(e).css('top'), 'right': _(e).css('right'), 'bottom': _(e).css('bottom'), 'position': _(e).css('position'), 'z-index': _(e).css('z-index'), 'padding' : 0 }; let eCss = { 'margin-left': 0, 'margin-right': 0, 'margin-bottom': 0, 'margin-top': 0, 'box-shadow': 'none', 'border-radius': 0, 'width': '100%', 'left': 0, 'top': 0, 'right': 0, 'bottom': 0, 'position': 'absolute', 'z-index' : 0 }; _(wrapper).css(wrapperCss).addClass('jts_hide_wrapper'); parent.before(wrapper, e); _(wrapper).append(e); _(e).css(eCss); _(wrapper).css('transition', property + ' ' + (d / 1000) + 's ' + easing + ' 0s'); setTimeout(function () { if (_(e).attr('jts_showed')) { _(wrapper).css('height', height); } },TIME_GAP * 0.3); setTimeout(function () { if (_(e).attr('jts_showed')) { parent.before(e, wrapper); parent[0].removeChild(wrapper); setElementStyle(e); e.attributes.removeNamedItem('jts_showed'); if (configuration && configuration.endCB) { configuration.endCB(i, e); } } }, d + (TIME_GAP * 2)); } function setElementStyle(e) { let style = _(e).attr('style'); for (let i = 0 ; i < jTS.originalStyles.length; i++) { if (jTS.originalStyles[i][0] === e) { style = jTS.originalStyles[i][1]; jTS.originalStyles.splice(i, 1); break; } } style = style ? style : ''; if (style.match('display:none;') || style.match('display: none;')) { style = style.replace(/display:\s?none;/, ''); } else if(style.match('display : none;')){ style = style.replace(/display : none;/, ''); } _(e).attr('style', style); } return this; }; /** * * @param animationsUrl {string} * @param configuration {Object} * @return {jTS} */ jTS.fn.showcase =/*jTS*/ function (/*string*/animationsUrl,/*Object literal*/configuration) { const t = this; if(t.length === 0){ return t; } t.each(function(i,e){ _(e).css('opacity',0); }); let container = t.offsetPs()[0]; let animations; let currentAnimation; let usedAnimations = []; let fakeLoaderContainer = document.createElement('div'); let showcaseID = new Date().getTime() + "_" + Math.floor(Math.random() * 500); _(container).css('overflow', 'hidden'); jTS.jJSON(animationsUrl, function (data) { animations = data.animations; loadPictures(); }); function loadPictures() { let bar = document.createElement('div'); let barCSS = { 'position': 'absolute', 'height': 10, 'width': 0, 'left': 0, 'bottom': 0, 'background-color': '#ffba00' }; _(bar).addClass('jts_showcase_bar_' + showcaseID).css(barCSS); _(container).append(bar); t.each(pushPicture); function pushPicture(i,e) { let img = new Image(); img.src = _(e).attr("src"); img.alt = "showcase_img"; //this for real loading _(fakeLoaderContainer).append(img); _(e).dispose(); let percentage = (100 * ((i + 1) / (t.length - 1))) + '%'; _('.jts_showcase_bar_' + showcaseID).css('width', percentage); if(i === t.length - 1){ addFakeContainer(); } } function addFakeContainer(){ //this for real loading _(fakeLoaderContainer).css('display', 'none').attr('id', 'jts_showcase_flc_' + showcaseID); _('.jts_showcase_bar_' + showcaseID).dispose(); _('body').append(fakeLoaderContainer); setShowcase(); } } function setShowcase() { let START_FADE_IN_DURATION = 3; let FADE_IN_DELAY = 100; let READY_DELAY = (START_FADE_IN_DURATION * 1000) + 100; let ANIMATION_DELAY = configuration.animationDelay || 5000; let START_ANIMATION_DELAY = 200; let RESET_DELAY = 200; let SLIDE_DELAY = 10; let BACK_DELAY_T = 1000; let BACK_DELAY_S = 1500; let TEXT_OUT_LEFT = -300; let TEXT_IN_LEFT = 80; let fadeID = null; let readyID = null; let animationID = null; let startAnimationID = null; let disposeID = null; let resetID = null; let slideID = null; let backSID = null; let backTID = null; let currentIndex = 0; let nextIndex = 1; let inAnimation = false; let paused = false; let textContainer; let subtitleContainer; let titleContainer; let link; let previousButton; let nextButton; let pauseButton; let currentImageDiv = document.createElement('div'); let nextImageDiv = document.createElement('div'); _(currentImageDiv).attr('id', 'jts_cid_' + showcaseID).css({ 'position': 'absolute', 'z-index': 0, 'width' : '100%' , 'height' : '100%' , 'top' : 0 , 'left' : 0 ,'opacity': 0, 'transition': 'opacity ' + START_FADE_IN_DURATION + 's ease-out' }); _(nextImageDiv).attr('id', 'jts_nid_' + showcaseID).css({ 'position': 'absolute', 'z-index': 1 , 'width' : '100%' , 'height' : '100%' , 'top' : 0 , 'left' : 0}); let currentImageCanvas = document.createElement('canvas'); let currentImageBrush = currentImageCanvas.getContext('2d'); _(currentImageCanvas).attr({ 'id': 'jts_cic_' + showcaseID, 'alt': 'showcase_img' }).css({ 'position': 'absolute', 'top' : 0 , 'left' : 0 ,'width' : '100%' , 'height' : '100%'}); resize(false); drawCurrentImage(); addListeners(); _(currentImageDiv).append(currentImageCanvas); _(container).append([currentImageDiv, nextImageDiv]); fadeIn(); function addControls() { let CONTROLS_DELAY = 200; let controlsActivator = document.createElement('div'); let controlsID = null; previousButton = document.createElement('div'); nextButton = document.createElement('div'); pauseButton = document.createElement('div'); let activatorCss = { 'position': 'absolute', 'width': '100%', 'height': 65, 'z-index': 10, 'left' : 0 , 'bottom' : 0 }; let commonsButtonCSS = { 'position': 'absolute', 'width': 50, 'height': 50, 'cursor': 'pointer', 'border-radius': configuration && configuration.controls && configuration.controls.radius ? configuration.controls.radius : 3, 'background-color' : configuration && configuration.controls && configuration.controls.background ? configuration.controls.background : 'rgba(255,255,255,0.5)', 'color' : configuration && configuration.controls && configuration.controls.color ? configuration.controls.color : '#303030' , 'font-size' : 40 , 'text-align' : 'center', 'bottom': 15, 'padding' : '3px 0px 0px 0px', 'box-shadow' : configuration && configuration.controls && configuration.controls.shadow ? configuration.controls.shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'transition' : 'bottom 0.5s ease-out' }; _(controlsActivator).css(activatorCss); _(previousButton).attr('id', 'jts_showcase_previous_button_' + showcaseID).append('<i class="fa fa-step-backward"></i>').addClass('jts_showcase_controls_buttons'); _(nextButton).attr('id', 'jts_showcase_next_button_' + showcaseID).append('<i class="fa fa-step-forward"></i>').addClass('jts_showcase_controls_buttons'); _(pauseButton).attr('id', 'jts_showcase_pause_button_' + showcaseID).append('<i class="fa fa-pause"></i>').addClass('jts_showcase_controls_buttons'); _(previousButton).css(commonsButtonCSS).css('left' , 25); _(pauseButton).css(commonsButtonCSS).css('left' , 'calc(50% - 12px)'); _(nextButton).css(commonsButtonCSS).css('right' , 25); _(controlsActivator).append([previousButton,pauseButton,nextButton]); _(container).append(controlsActivator); if(!jTS.jMobile()){ controlsID = setTimeout(function(){ _('.jts_showcase_controls_buttons').css('bottom' , -65); },CONTROLS_DELAY * 5); } _(controlsActivator).bind('mouseover.jts_showcase_' + showcaseID , function(e){ clearTimeout(controlsID); _('.jts_showcase_controls_buttons').css('bottom' , 15); }).bind('mouseout.jts_showcase_' + showcaseID , function(e){ controlsID = setTimeout(function(){ _('.jts_showcase_controls_buttons').css('bottom' , -65); },CONTROLS_DELAY); }); _([previousButton, pauseButton , nextButton]).bind('click.jts_showcase_' + showcaseID, activateTransition); function activateTransition(e) { if (inAnimation) { return; } clearTimeout(animationID); animationID = null; let id = _(this).attr('id'); if (id.match('previous_button')) { nextIndex = currentIndex === 0 ? t.length - 1 : currentIndex - 1; unpause(); } else if(id.match('next_button')){ unpause(); } else if(id.match('pause_button')){ if(!paused){ paused = true; _(pauseButton).html('').append('<i class="fa fa-play"></i>'); } else{ unpause(); } } function unpause(){ paused = false; _(pauseButton).html('').append('<i class="fa fa-pause"></i>'); coreAnimation(currentAnimation); } _(window).emits(jTS.built_in_events.jSHOWCASE_CONTROLS_PRESSED); } } function addListeners() { _(window).bind('resize.jts_showcase_' + showcaseID, function (e) { if (!getRootN()) { return; } resize(true); }); _(window).bind('click.jts_showcase_' + showcaseID, function (e) { if (!getRootN()) {} }) } function addText() { textContainer = document.createElement('div'); subtitleContainer = document.createElement('div'); titleContainer = document.createElement('div'); link = document.createElement('a'); let containerCSS = { 'position': 'absolute', 'bottom': 80, 'width': '150%', 'z-index': 11, 'overflow': 'visible' }; let textCSS = { 'position': 'absolute', 'width': '100%', 'left': TEXT_OUT_LEFT, 'opacity': 0 }; let subtitleCSS = { 'position': 'absolute', 'width': '100%', 'left': TEXT_OUT_LEFT, 'top': 0, 'opacity': 0, 'color': configuration && configuration.text && configuration.text.subtitle_color ? configuration.text.subtitle_color : '#303030', 'font-weight' : configuration && configuration.text && configuration.text.subtitle_weight ? configuration.text.subtitle_weight : 700 }; let linkCSS = { 'text-decoration': 'none', 'color': configuration && configuration.text && configuration.text.link_color ? configuration.text.link_color : '#ffffff', 'font-weight' : configuration && configuration.text && configuration.text.link_weight ? configuration.text.link_weight : 700 }; let linkAttr = { 'id': 'jts_showcase_a_' + showcaseID, 'class': configuration && configuration.text && configuration.text.font_class ? configuration.text.font_class : 'ts-font-elegance', 'href': configuration.text.link[currentIndex], 'target': '_blank' }; _(textContainer).attr('id', 'jts_showcase_text_' + showcaseID).css(containerCSS); _(subtitleContainer).attr('id', 'jts_showcase_ts_' + showcaseID).css(subtitleCSS); _(titleContainer).attr('id', 'jts_showcase_tt_' + showcaseID).css(textCSS); _(link).attr(linkAttr).css(linkCSS).html(configuration.text.title[currentIndex]); _(subtitleContainer).html(configuration.text.subtitle[currentIndex]); _(titleContainer).append(link); _(textContainer).append([subtitleContainer, titleContainer]); setTextSize(); _(container).append(textContainer); slideID = setTimeout(function () { slideText(TEXT_IN_LEFT, 0.8); }, SLIDE_DELAY); } function coreAnimation(animation) { inAnimation = true; if (configuration && configuration.show_text) { slideText(TEXT_OUT_LEFT, 0); } let SMALL_SCREEN = 736; let tiles = []; let canvases = []; let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); let numberOfTiles = containerWidth <= SMALL_SCREEN ? animation.tiles[0] : animation.tiles[1]; let columns = containerWidth <= SMALL_SCREEN ? animation.columns[0] : animation.columns[1]; let rows = containerWidth <= SMALL_SCREEN ? animation.rows[0] : animation.rows[1]; let disposeDelay = containerWidth <= SMALL_SCREEN ? animation.dispose_delay[0] : animation.dispose_delay[1]; let tileWidth = Math.round(containerWidth / columns); let tileHeight = Math.round(containerHeight / rows); let lastTileWidth = containerWidth - (tileWidth * (columns - 1)); let lastTileHeight = containerHeight - (tileHeight * (rows - 1)); setTiles(0); let pos = null; let size = null; let opacity = null; let transform = null; if (animation.double) { setTiles(1); } if (animation.start_pos) { pos = containerWidth <= SMALL_SCREEN ? animation.start_pos[0] : animation.start_pos[1]; } if (animation.start_size) { size = containerWidth <= SMALL_SCREEN ? animation.start_size[0] : animation.start_size[1]; } if (animation.start_opacity) { opacity = containerWidth <= SMALL_SCREEN ? animation.start_opacity[0] : animation.start_opacity[1]; } if (animation.start_transform) { transform = containerWidth <= SMALL_SCREEN ? animation.start_transform[0] : animation.start_transform[1]; } let transition = containerWidth <= SMALL_SCREEN ? animation.transition[0] : animation.transition[1]; setCanvases(0); if (animation.double) { setCanvases(1); } startAnimationID = setTimeout(startAnimation, START_ANIMATION_DELAY); function setCanvases(canvasIndex) { let image = animation.double && canvasIndex === 0 ? t[currentIndex] : t[nextIndex]; let add = canvasIndex > 0 ? numberOfTiles : 0; let cropData = getImageSizeAndOffset(image); let cropWidth = tileWidth * (cropData.width / containerWidth); let cropHeight = tileHeight * (cropData.height / containerHeight); for (let i = 0; i < numberOfTiles; i++) { let cropCurrentW = Math.floor(i % columns) === columns - 1 ? _(tiles[i]).outerWidth() * (cropData.width / containerWidth) : cropWidth; let cropCurrentH = Math.floor(i / columns) === rows - 1 ? _(tiles[i]).outerHeight() * (cropData.height / containerHeight) : cropHeight; if (cropCurrentW > image.naturalWidth) { // cropCurrentW = image.naturalWidth; } if (cropCurrentH > image.naturalHeight) { // cropCurrentH = image.naturalHeight; } let canvas = document.createElement('canvas'); canvas.setAttribute('id', animation.name + '_canvas_' + canvasIndex + i + showcaseID); canvas.width = cropCurrentW; canvas.height = cropCurrentH; let css = { 'position': 'absolute', 'width': '100%', 'height': '100%', 'z-index': canvasIndex > 0 ? 1 : 2, 'transition': transition[i] }; if (pos) { css.left = pos[i + (add * (canvasIndex * 2))]; css.top = pos[(i + numberOfTiles) + (add * (canvasIndex * 2))]; } if (size) { css.width = size[i + (add * (canvasIndex * 2))]; css.height = size[(i + numberOfTiles) + (add * (canvasIndex * 2))]; } if (opacity) { css.opacity = opacity[i + add]; } if (transform) { css.transform = transform[i + add]; } _(canvas).css(css); let drawX = (Math.floor(i % columns) * cropWidth) + cropData.offsetX; let drawY = (Math.floor(i / columns) * cropHeight) + cropData.offsetY; let b = canvas.getContext('2d'); b.drawImage( image, drawX, drawY, cropCurrentW, cropCurrentH, 0, 0, canvas.width, canvas.height ); _(tiles[i + add]).append(canvas); canvases.push(canvas); } } function setTiles(tileIndex) { for (let i = 0; i < numberOfTiles; i++) { let tileX = Math.floor(i % columns) * tileWidth; let tileY = Math.floor(i / columns) * tileHeight; let tileCurrentW = Math.floor(i % columns) === columns - 1 ? lastTileWidth : tileWidth; let tileCurrentH = Math.floor(i / columns) === rows - 1 ? lastTileHeight : tileHeight; let tile = document.createElement('div'); tile.setAttribute('id', animation.name + '_tile_' + tileIndex + i + showcaseID); let css = { 'position': 'absolute', 'width': tileCurrentW, 'height': tileCurrentH, 'left': tileX, 'top': tileY, 'overflow': animation.overflow }; _(tile).css(css); _(nextImageDiv).append(tile); tiles.push(tile); } } function startAnimation() { if (!animation.back_visible) { _(currentImageDiv).css('visibility', 'hidden'); } startTransition(); function startTransition() { let add = animation.double ? 2 : 1; let pos = null; let size = null; let opacity = null; let transform = null; if (animation.stop_pos) { pos = containerWidth <= SMALL_SCREEN ? animation.stop_pos[0] : animation.stop_pos[1]; } if (animation.stop_size) { size = containerWidth <= SMALL_SCREEN ? animation.stop_size[0] : animation.stop_size[1]; } if (animation.stop_opacity) { opacity = containerWidth <= SMALL_SCREEN ? animation.stop_opacity[0] : animation.stop_opacity[1]; } if (animation.stop_transform) { transform = containerWidth <= SMALL_SCREEN ? animation.stop_transform[0] : animation.stop_transform[1]; } for (let i = 0 ; i < canvases.length; i++) { let css = {}; if (pos) { css.left = pos[i]; css.top = pos[i + (numberOfTiles * add)]; } if (size) { css.width = size[i]; css.height = size[i + (numberOfTiles * add)]; } if (opacity) { css.opacity = opacity[i]; } if (transform) { css.transform = transform[i] } _(canvases[i]).css(css); } _(window).emits(jTS.built_in_events.jSHOWCASE_ANIMATION_START); disposeID = setTimeout(clearAnimation, disposeDelay); } } function clearAnimation() { if (configuration && configuration.show_text) { _(subtitleContainer).html(configuration.text.subtitle[nextIndex]); _(link).attr('href', configuration.text.link[nextIndex]).html(configuration.text.title[nextIndex]); slideText(TEXT_IN_LEFT, 0.8); } currentIndex = nextIndex; nextIndex = nextIndex === t.length - 1 ? 0 : nextIndex + 1; drawCurrentImage(); _(currentImageDiv).css('visibility', 'visible'); resetID = setTimeout(function () { nextImageDiv.innerHTML = ''; _(window).emits(jTS.built_in_events.jSHOWCASE_ANIMATION_END); setNextAnimation(); }, RESET_DELAY); } } function drawCurrentImage(){ let cropData = getImageSizeAndOffset(t[currentIndex]); currentImageBrush.clearRect(0,0,currentImageCanvas.width,currentImageCanvas.height); currentImageBrush.drawImage( t[currentIndex], cropData.offsetX,cropData.offsetY,cropData.width,cropData.height, 0,0,currentImageCanvas.width,currentImageCanvas.height ); } function fadeIn() { fadeID = setTimeout(innerFadeIn, FADE_IN_DELAY); function innerFadeIn(){ _(currentImageDiv).css('opacity', 1); readyID = setTimeout(function () { _(window).emits(jTS.built_in_events.jSHOWCASE_READY); setNextAnimation(); if (configuration && configuration.controllable) { addControls(); } if (configuration && configuration.show_text) { addText(); } }, READY_DELAY); } } function getImageSizeAndOffset(image){ let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); let originalWidth = image.naturalWidth; let originalHeight = image.naturalHeight; let width , height , offsetX , offsetY; if (containerWidth >= containerHeight) { parseHeight(containerWidth); } else { parseWidth(containerHeight); } offsetX = Math.abs((containerWidth * 0.5) - (width * 0.5)); offsetY = Math.abs((containerHeight * 0.5) - (height * 0.5)); function parseHeight(w) { width = w; height = originalHeight * (w / originalWidth); if (height < containerHeight) { parseHeight(w + 1); } } function parseWidth(h) { height = h; width = originalWidth * (h / originalHeight); if (width < containerWidth) { parseWidth(h + 1); } } let cropWidth = containerWidth * (originalWidth / width); let cropHeight = containerHeight * (originalHeight / height); offsetX = offsetX * (originalWidth / width); offsetY = offsetY * (originalHeight / height); return { 'width': cropWidth, 'height': cropHeight, 'offsetX': offsetX, 'offsetY': offsetY }; } function getRootN() { let e_parent = container; let r_parent = e_parent; while (e_parent) { e_parent = _(e_parent).offsetPs()[0]; if (e_parent) { r_parent = e_parent; } } if (r_parent.nodeName.toLowerCase() !== '#document') { _(window).unbind('.jts_showcase_' + showcaseID); if (previousButton && nextButton) { _([previousButton, nextButton]).unbind('click'); } return false; } else { return true; } } function resize(needRedraw) { let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); currentImageCanvas.width = containerWidth * devicePixelRatio; currentImageCanvas.height = containerHeight * devicePixelRatio; if(needRedraw && !inAnimation){ drawCurrentImage(); } if (configuration && configuration.show_text) { if (_('#jts_showcase_text_' + showcaseID)) { setTextSize(); } } } function setNextAnimation() { if (animations.length === 0) { for (let i = 0; i < usedAnimations.length; i++) { animations.push(usedAnimations[i]); } usedAnimations.length = 0; } let animationIndex = Math.floor(Math.random() * animations.length); currentAnimation = animations[animationIndex]; usedAnimations.push(animations[animationIndex]); animations.splice(animationIndex, 1); inAnimation = false; animationID = setTimeout(function () { coreAnimation(currentAnimation); }, ANIMATION_DELAY); } function setTextSize() { let WIDTH_SET = [0, 360, 560, 760, 1000, 1400, 10000]; let CONTAINER_LEFT = [15, 30, 50, 60, 65, 65]; let CONTAINER_HEIGHT = [62, 83, 95, 106, 116, 120]; let SUBTITLE_HEIGHT = [20, 25, 28, 28, 30, 30]; let SUBTITLE_FONT = [16, 21, 23, 23, 25, 25]; let TITLE_HEIGHT = [47, 65, 77, 89, 101, 105]; let TITLE_TOP = [15, 18, 18, 17, 15, 15]; let LINK_FONT = [40, 55, 65, 76, 85, 90]; let w = _(container).outerWidth(); for (let i = 0; i < WIDTH_SET.length - 1; i++) { if (w > WIDTH_SET[i] && w <= WIDTH_SET[i + 1]) { _(textContainer).css({ 'height': CONTAINER_HEIGHT[i], 'left': CONTAINER_LEFT[i] }); _(subtitleContainer).css({ 'height': SUBTITLE_HEIGHT[i], 'font-size': SUBTITLE_FONT[i] }); _(titleContainer).css({ 'height': TITLE_HEIGHT[i], 'top': TITLE_TOP[i] }); _(link).css('font-size', LINK_FONT[i]); break; } } } function slideText(left, opacity) { clearTimeout(backTID); clearTimeout(backSID); let css = { 'left': left, 'opacity': opacity }; _('#jts_showcase_ts_' + showcaseID).css('transition', 'opacity 1s ease-out 0.3s , left 1s ease-out 0.3s'); _('#jts_showcase_tt_' + showcaseID).css('transition', 'opacity 1s ease-out 0s , left 1s ease-out 0s'); _('#jts_showcase_ts_' + showcaseID).css(css); _('#jts_showcase_tt_' + showcaseID).css(css); if (left > 0) { backTID = setTimeout(function () { _('#jts_showcase_tt_' + showcaseID).css('transition', 'opacity 0.5s ease-out , left 0.8s ease-in-out'); _('#jts_showcase_tt_' + showcaseID).css('left', 0).css('opacity', 1); }, BACK_DELAY_T); backSID = setTimeout(function () { _('#jts_showcase_ts_' + showcaseID).css('transition', 'opacity 0.5s ease-out , left 0.8s ease-in-out'); _('#jts_showcase_ts_' + showcaseID).css('left', 0).css('opacity', 1); }, BACK_DELAY_S); } } } return this; }; /** * * @param delay {int} * @return {jTS} */ jTS.fn.simpleSlide =/*jTS*/ function(/*int*/delay){ const t = this; if(t.length === 0){ return t; } if(delay && delay < 3000){ delay = 3000; } let container = t.offsetPs(); let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); let showedImageIndex = 0; let resizeID = null; let slideDelay = delay ? delay : 10000; let slideID = new Date().getTime() + "_" + Math.floor(Math.random() * 500); container.css("background-color","#ffffff"); setPicturesSize(); setShowedImage(); addListeners(); startSlide(); function addListeners(){ _(window).bind('resize.jts_simple_slide_events_' + slideID,function(){ clearTimeout(resizeID); resizeID = setTimeout(function(){ containerWidth = _(container).outerWidth(); containerHeight = _(container).outerHeight(); setPicturesSize(); },200); }); } function getImageSize(img) { let originalWidth = img.naturalWidth; let originalHeight = img.naturalHeight; let data = null; if(containerWidth >= containerHeight){ data = parseHeight(containerWidth); } else{ data = parseWidth(containerHeight); } function parseHeight(width) { let w = width; let h = originalHeight * (w/originalWidth); if(h <= containerHeight){ return parseHeight(width + 2); } else{ return {'width':w,'height':h}; } } function parseWidth(height) { let h = height; let w = originalWidth * (h/originalHeight); if(w <= containerWidth){ return parseWidth(height + 2); } else{ return {'width':w,'height':h}; } } return data; } function setPicturesSize() { t.each(setSizeAndPosition); } function setShowedImage(){ t.css({ 'transition': 'none', 'opacity': 0 }); t.each(function(i,e){ if(i === showedImageIndex){ _(e).css('opacity',1); } }); } function setSizeAndPosition(i,e) { let size = getImageSize(e); let width = size.width; let height = size.height; _(e).css({ 'width':width, 'height':height, 'left': (containerWidth * 0.5) - (width * 0.5), 'top' : (containerHeight * 0.5) - (height * 0.5), 'position' : 'absolute' }); } function startSlide(){ setTimeout(function(){ _(t[showedImageIndex]).css('transition', 'opacity 0.7s linear'); setTimeout(function(){ _(t[showedImageIndex]).css('opacity',0); showedImageIndex = showedImageIndex + 1 === t.length ? 0 : showedImageIndex + 1; _(t[showedImageIndex]).css('transition', 'opacity 0.7s linear'); },10); setTimeout(function(){ _(t[showedImageIndex]).css('opacity',1); },1010); setTimeout(function(){ setShowedImage(); startSlide(); },1710); },slideDelay); } return this; }; /** * * @param configuration {Object} * @return {jTS} */ jTS.fn.touchScroll = /*jTS*/ function(/*Object literal*/configuration){ const t = this; t.each(activate); function activate(i,e){ /*Constants*/ const stepWidth = configuration.step_width; const totalWidth = configuration.total_width; const stepVx = configuration.step_vx;/*higher value increase the easing time*/ const showHandle = configuration.show_handle; const steps = Math.ceil(totalWidth / stepWidth); const jElement = _(e); /*Position variables*/ let stepIndex = 0; let stepsPositions = []; let translateX = 0; let targetPos = 0; let transitionTime = 0; let handle; let handleTranslateX; /*Moving variables*/ let startTouch = 0; let endTouch = 0; let currentX = 0; let currentY = 0; let previousX = 0; let previousY = 0; let vX = 0; let vY = 0; /*Find every step position*/ for(let i = 0; i < steps; i++){ stepsPositions.push(stepWidth * i); } /*Initialize handle if needed*/ if(showHandle){ handle = _(`<div class="jts-touch-scroll-handle"></div>`).css({ 'position' : 'absolute', 'top' : 0, 'left' : 0, 'height' : 5, 'width' : stepWidth * (stepWidth / totalWidth), 'border-radius' : 5, 'opacity' : 0, 'background-color' : '#9e9e9e' }).addClass(configuration.handle_class ? configuration.handle_class : ''); jElement.offsetPs().append(handle); } jElement.mouseDown(function(e){ e.preventDefault(); /*Reset transitions*/ _(this).css({ transition : 'unset' }); if(showHandle && stepWidth < totalWidth){ handle.css({ 'transition' : 'opacity 1.5s ease-out', 'opacity' : 1, }); } startTouch = new Date().getTime(); /*Initialize mouse position*/ currentX = e.type === 'mousedown' ? e.screenX : e.touches[0].clientX; currentY = e.type === 'mousedown' ? e.screenY: e.touches[0].clientY; previousX = currentX; previousY = currentY; _(window).mouseMove('touch_scroll_events',function(e){ currentX = e.type === 'mousemove' ? e.screenX : e.touches[0].clientX; currentY = e.type === 'mousemove' ? e.screenY: e.touches[0].clientY; /*Compute vX and vY*/ vX = currentX - previousX; vY = currentY - previousY; previousX = currentX; previousY = currentY; /*Check if vX need to be reduced */ if(translateX > 0 && vX > 0 || translateX + totalWidth < stepWidth && vX < 0){ vX = Math.cos(Math.atan2(vY,vX)) * 0.5; } translateX += vX; /*Apply translate*/ jElement.css({ transform : `translateX(${translateX}px)` }); if(showHandle && stepWidth < totalWidth){ translateHandle(); } /*Compute the slider step index*/ stepIndex = Math.floor(Math.abs(translateX - (stepWidth * 0.5)) / stepWidth); }).mouseUp('touch_scroll_events',function(e){ endTouch = new Date().getTime(); _(window).unbind('.touch_scroll_events'); /*Compute translate x and transition time*/ targetPos = -stepsPositions[stepIndex]; transitionTime = stepVx * (Math.abs(targetPos - translateX) / stepWidth); translateX = targetPos; /*Apply translate*/ jElement.css({ transition : `transform ${transitionTime}s ease-out`, transform : `translateX(${targetPos}px)` }); if(showHandle && stepWidth < totalWidth){ handle.css({ 'transition' : `transform ${transitionTime}s ease-out , opacity 1.5s ease-out`, 'opacity' : 0 }); translateHandle(); } /*Emits an event with the current step index for outside listeners*/ _(window).emits(jTS.built_in_events.jTOUCH_SCROLL_STEP,{'current_step' : stepIndex}); }); }); function translateHandle(){ handleTranslateX = Math.abs(translateX) * (stepWidth / totalWidth); handleTranslateX = translateX > 0 ? 0 : (translateX + totalWidth < stepWidth ? stepWidth - handle.outerWidth() : handleTranslateX); handle.css({ transform : `translateX(${handleTranslateX}px)` }); } } return t; }; /*END ANIMATION PACKAGE*/ /*CORE PACKAGE*/ /** * * @return {jTS} */ jTS.fn.clone = /*jTS*/function () { const t = this; let e = []; t.each(pushE); function pushE(index, element) { let clone = element.cloneNode(true); e.push(clone); } return _(e); }; /** * * @return {jTS} */ jTS.fn.first = /*jTS*/ function(){ const t = this; return t.length > 0 ?_(t[0]) : t; }; /** * * @param list {Array} * @param sortFlags {string} * @param sortProperty {string} * @return {Array} */ jTS.jSort = /*Array[number || string || Object literal]*/function (/*Array[number || string || Object literal]*/list,/*string*/sortFlags,/*string*/sortProperty) { for (let i = 0; i < 1 ;i++){ for (let l = 1 ; l < list.length; l++) { if (typeof list[i] !== typeof list[l]) { console.log('can-not-sort-multiple-types @ jTS.jSort'); return list; } } } let direction = 'a'; let caseSensitive = 'i'; let oProperty = null; if (arguments.length > 1 && arguments[1] != null && typeof arguments[1] === 'string') { let flags = sortFlags.split('|'); for(let h = 0; h < flags.length; h++){ flags[h] = flags[h].toLowerCase().trim(); } if (flags[0] === 'a' || flags[0] === 'd') { direction = flags[0]; } else if (flags[0] === 's' || flags[0] === 'i') { caseSensitive = flags[0]; } if (flags[1] && (flags[1] === 'a' || flags[1] === 'd')) { direction = flags[1]; } else if (flags[1] && (flags[1] === 's' || flags[1] === 'i')) { caseSensitive = flags[1]; } if(flags.length === 1 && flags[0].length > 1 && typeof list[0] === 'object'){ oProperty = flags[0]; } } if (arguments.length > 2 && typeof arguments[2] === 'string') { oProperty = arguments[2]; } let value = null; sortArray(); function sortArray() { sort(0); function sort(index) { value = list[index]; for (let i = index + 1 ; i < list.length ; i++) { let currentValue = list[i]; let valueA = typeof list[0] === 'number' ? value : (typeof list[0] === 'string' ? parseString(value) : getObjectValue(value)); let valueB = typeof list[0] === 'number' ? currentValue : (typeof list[0] === 'string' ? parseString(currentValue) : getObjectValue(currentValue)); let a = direction === 'a' ? valueB : valueA; let b = direction === 'a' ? valueA : valueB; if(a == null || b == null){ return; } if (a < b) { updateValue(i, index); } } if (index < list.length - 1) { sort(index + 1); } } } function getObjectValue(object) { if (typeof object !== 'object' || oProperty == null || object[oProperty] === undefined) { console.log('error-in-object-sorting @ jTS.jSort'); return null; } return typeof object[oProperty] === 'string' ? parseString(object[oProperty]) : object[oProperty]; } function parseString(string) { return caseSensitive === 's' ? string : string.toLowerCase(); } function updateValue(i,index) { value = list[i]; list.splice(i, 1); list.splice(index, 0, value); } return list; }; /** * * @param string {string} * @param startIndex {int} * @param contentOrLength {*} * @return {string} */ jTS.jStringSplice = /*string*/function (/*string*/string,/*int*/startIndex ,/*string || int*/contentOrLength) { let parsed = ''; if (typeof arguments[0] !== 'string') { console.log('incorrect-string-value @ jTS.jStringSplice'); return; } if (typeof arguments[1] !== 'number') { console.log('incorrect-startIndex-value @ jTS.jStringSplice'); return; } if (typeof arguments[2] === 'string') { add(); } else if (typeof arguments[2] === 'number') { dispose(); } else { console.log('unexpected_value @ jTS.jStringSplice'); return; } function add() { let sIndex = startIndex < 0 ? 0 : startIndex; let first = string.substr(0, sIndex); let second = string.substr(sIndex); parsed = first + contentOrLength + second; } function dispose() { let sIndex = startIndex < 0 ? 0 : startIndex; let first = string.substr(0, sIndex); let second = string.substr(sIndex); second = second.substr(contentOrLength); parsed = first + second; } return parsed; }; /** * * @return {jTS} */ jTS.fn.last = /*jTS*/ function(){ const t = this; return t.length > 0 ? _(t[t.length - 1]) : t; }; /** * * @param n {int} * @return {*} */ jTS.fn.raw = /*HTMLElement*/ function(/*int*/n){ let t = this; if(arguments.length === 0 || typeof arguments[0] !== 'number' || parseInt(n) < 0 || parseInt(n) > t.length - 1){ return t; } return t[parseInt(n)]; }; /** * * @param jTSObject {jTS} * @return {jTS} */ jTS.fn.weld = /*jTS*/function (/*jTS*/jTSObject) { const t = this; let e = []; t.each(pushElement); jTSObject.each(pushElement); function pushElement(index, element) { e.push(element); } return _(e); }; /*END CORE PACKAGE*/ /*CSS PACKAGE*/ /** * * @param classToAdd {string} * @return {jTS} */ jTS.fn.addClass = /*jTS*/function (/*string*/classToAdd) { const t = this; let classArray = classToAdd.trim().split(' '); t.each(addValue); function addValue(i, e) { let oldClass = e.getAttribute('class'); let oldClassArray = []; if(oldClass){ oldClass = oldClass.trim(); oldClassArray = oldClass.split(' '); } for(let i = 0; i < classArray.length; i++){ if(oldClassArray.indexOf(classArray[i]) !== -1){ classArray.splice(i,1); i--; } } let parsedClass = (oldClass ? oldClass + ' ' : '') + classArray.join(' '); e.setAttribute('class', parsedClass); } return this; }; /** * * @param classToAdd {string} * @return {jTS} */ jTS.fn.addClassRecursive = /*jTS*/function (/*string*/classToAdd) { const t = this; t.each(addValue); function addValue(i, e) { const NODE_TYPE = 1; if (e.nodeType === NODE_TYPE) { _(e).addClass(classToAdd); let children = _(e.childNodes); children.addClassRecursive(classToAdd); } } return this; }; /** * * @param properties {*} * @param value {*} * @return {*} */ jTS.fn.css = /*jTS || CSS value*/function (/*string || Object literal*/properties,/*string || number*/value) { const t = this; if(t.length ===0){ return t; } if (arguments.length === 1 && typeof arguments[0] === 'string') { return getProperty(properties); } else if (arguments.length === 1 && typeof arguments[0] === 'object') { setProperties(properties); } else if (arguments.length === 2 && typeof arguments[0] === 'string') { let propertiesObject = {}; propertiesObject[properties] = value; setProperties(propertiesObject); } else{ console.log('arguments-list-error @ jTS.css'); return t; } function getProperty(p) { let value; switch (p) { case 'bottom': value = getPropertyValue(t[0], p) || t[0].offsetParent.getBoundingClientRect().height - (t[0].offsetTop + t[0].getBoundingClientRect().height) + 'px'; break; case 'height': value = t[0].getBoundingClientRect().height + 'px'; break; case 'left': value = getPropertyValue(t[0], p) || t[0].offsetLeft + 'px'; break; case 'margin': value = JSON.stringify({ 'left': getPropertyValue(t[0], 'margin-left'), 'top': getPropertyValue(t[0], 'margin-top'), 'right': getPropertyValue(t[0], 'margin-right'), 'bottom': getPropertyValue(t[0], 'margin-bottom') }); break; case 'padding': value = JSON.stringify({ 'left': getPropertyValue(t[0], 'padding-left'), 'top': getPropertyValue(t[0], 'padding-top'), 'right': getPropertyValue(t[0], 'padding-right'), 'bottom': getPropertyValue(t[0], 'padding-bottom') }); break; case 'right': value = getPropertyValue(t[0], p) || t[0].offsetParent.getBoundingClientRect().width - (t[0].offsetLeft + t[0].getBoundingClientRect().width) + 'px'; break; case 'top': value = getPropertyValue(t[0], p) || t[0].offsetTop + 'px'; break; case 'width': value = t[0].getBoundingClientRect().width + 'px'; break; default: value = getPropertyValue(t[0], p); break; } function getPropertyValue(e, p) { return e.style[parsePropertyName(p)] || getFromComputed(e, p) || getFromStyles(e, p) || jTS.cssMap[p]; } function getFromComputed(e, p) { return getComputedStyle(e).getPropertyValue(p); } function getFromStyles(e, p) { let classList = e.getAttribute('class'); let id = e.getAttribute('id'); let tag = e.tagName; if (classList) { classList = classList.split(' '); } else { classList = []; } let stylesObjects = document.styleSheets; if (stylesObjects) { for (let i = stylesObjects.length - 1 ; i >= 0 ; i--) { let rulesSet = stylesObjects[i].cssRules || stylesObjects[i].rules; if (rulesSet) { for (let l = rulesSet.length - 1 ; l >= 0 ; l--) { let rule = rulesSet[l]; if (rule && rule.type === 1) { let selectorText = rule.selectorText; let classFlag = false; for (let h = 0; h < classList.length; h++) { if (selectorText.slice(1) === classList[h]) { classFlag = true; break; } } if (selectorText === '#' + id || classFlag || selectorText === t.selector || selectorText === tag || selectorText === '*') { let style = rule.style; if (style) { let css = style[p]; if (css) { return css; } } } } } } } } return null; } return value; } function setProperties(p) { t.each(function (i, e) { for (let cssProperty in p) { if(p.hasOwnProperty(cssProperty)){ let v = (typeof p[cssProperty]).toLowerCase() === 'number' ? getValueExtension(cssProperty, p[cssProperty]) : String(p[cssProperty]); e.style.setProperty(cssProperty,v,''); } } }); function getValueExtension(n, v) { let PROPERTIES_SET = ['z-index', 'opacity', 'font-weight', 'line-height', 'fill-opacity', 'column-count']; let flag = false; for (let i = 0; i < PROPERTIES_SET.length ; i++) { if (n === PROPERTIES_SET[i]) { flag = true; break; } } if (!flag) { v = v + 'px'; } return v; } } function parsePropertyName(p) { let array = p.split('-'); let name = array[0]; function addChunk(name, index) { if (array.length === 1) { return name; } name += array[index].charAt(0).toUpperCase() + array[index].slice(1); if (index === array.length - 1) { return name; } else { return addChunk(name, index + 1); } } return addChunk(name, 1); } return this; }; /** * * @param left {*} * @param top {*} * @return {*} */ jTS.fn.documentCoordinates = /*Object literal || jTS*/ function (/*string || number*/left, /*string || number*/top) { const t = this; if(t.length === 0){ return t; } if (arguments.length === 0) { return getCoordinates(); } else { let flag = true; if (arguments[0] != null) { if (typeof arguments[0] !== 'number' && typeof arguments[0] !== 'string') { console.log('not-valid-parameters-list @documentCoordinates'); flag = false; } } if (arguments[1]) { if (typeof arguments[1] !== 'number' && typeof arguments[1] !== 'string') { console.log('not-valid-parameters-list @documentCoordinates'); flag = false; } } processArguments(); if((left && isNaN(left)) || (top && isNaN(top))){ flag = false; } if (flag) { t.each(assignArguments); } } function processArguments() { if (left) { if (typeof left === 'string') { left = parseFloat(left); } } if (top) { if (typeof top === 'string') { top = parseFloat(top); } } } function assignArguments(i, e) { let p = e.offsetParent; while (p) { if (left || left === 0) { left -= p.offsetLeft; } if (top || top === 0) { top -= p.offsetTop; } p = p.offsetParent; } if (left || left === 0) { left = left + 'px'; e.style.left = left; } else { e.style.left = e.offsetLeft + 'px'; } if (top || top === 0) { top = top + 'px'; e.style.top = top; } else { e.style.top = e.offsetTop + 'px'; } e.style.position = 'absolute'; } function getCoordinates() { let coordinates = t.first().elementGlobalPosition(); return { "left": coordinates.x, "top": coordinates.y } } return this; }; /** * * @param classToFind {string} * @return {boolean} */ jTS.fn.hasClass = /*boolean*/function (/*string*/classToFind) { const t = this; if(t.length === 0){ return false; } let classValue = classToFind.trim().split(' ')[0]; let oldClass = t[0].getAttribute('class'); let oldClassArray = oldClass ? oldClass.split(' ') : []; return oldClassArray.indexOf(classValue) !== -1; }; /** * * @param value {*} * @return {*} */ jTS.fn.height = /*number || jTS*/function (/*number || string*/value) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerHeight; } if (t[0] === document) { return _('html').outerHeight(); } if (arguments.length !== 0) { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('height', computeBorder(e)); break; case 'content-box': e.css('height', value); break; case 'padding-box': e.css('height', computePadding(e)); break; } }); } else { let e = _(t[0]); let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); let padding = parseFloat(e.css('padding-top')) + parseFloat(e.css('padding-bottom')); return ((t[0].getBoundingClientRect().height - border) - padding); } function computeBorder(e) { let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); let padding = parseFloat(e.css('padding-top')) + parseFloat(e.css('padding-bottom')); let gap = border + padding; if (typeof value === 'number') { return value + gap; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + gap; } else { return 'calc(' + parseFloat(value) + '% + ' + gap + 'px)'; } } } function computePadding(e) { let padding = parseFloat(e.css('padding-top')) + parseFloat(e.css('padding-bottom')); if (typeof value === 'number') { return value + padding; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + padding; } else { return 'calc(' + parseFloat(value) + '% + ' + padding + 'px)'; } } } return this; }; /** * * @param left {*} * @param top {*} * @return {*} */ jTS.fn.localCoordinates = /*Object literal|| jTS*/function (/*string || number*/left,/*string || number*/top) { const t = this; if(t.length === 0){ return t; } if (arguments.length === 0) { return getCoordinates(); } else { let flag = true; if (arguments[0] != null) { if (typeof arguments[0] !== 'number' && typeof arguments[0] !== 'string') { console.log('not-valid-parameters-list @localCoordinates'); flag = false; } } if (arguments[1]) { if (typeof arguments[1] !== 'number' && typeof arguments[1] !== 'string') { console.log('not-valid-parameters-list @localCoordinates'); flag = false; } } processArguments(); if((left && isNaN(left)) || (top && isNaN(top))){ flag = false; } if (flag) { t.each(assignArguments); } } function processArguments() { if (left || left === 0) { if (typeof left === 'string') { left = parseFloat(left); } } if (top || top === 0) { if (typeof top === 'string') { top = parseFloat(top); } } } function assignArguments(i, e) { if (left || left === 0) { left = left + 'px'; e.style.left = left; } else { e.style.left = e.offsetLeft + 'px'; } if (top || top === 0) { top = top + 'px'; e.style.top = top; } else { e.style.top = e.offsetTop + 'px'; } } function getCoordinates() { return { "left": t[0].offsetLeft, "top": t[0].offsetTop } } return this; }; /** * * @param valueOrMargin {*} * @return {*} */ jTS.fn.outerHeight = /*number || jTS*/function (/*number || string || boolean*/valueOrMargin) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerHeight; } if (t[0] === document) { return _('html').outerHeight(); } if (arguments.length !== 0) { if (typeof arguments[0] === 'boolean') { let e = _(t[0]); let marginHeight = valueOrMargin ? parseFloat(e.css('margin-top')) + parseFloat(e.css('margin-bottom')) : 0; return t[0].getBoundingClientRect().height + marginHeight; } else { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('height', valueOrMargin); break; case 'content-box': e.css('height', computeContent(e)); break; case 'padding-box': e.css('height', computePadding(e)); break; } }); } } else { return t[0].getBoundingClientRect().height; } function computeContent(e) { let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); let padding = parseFloat(e.css('padding-top')) + parseFloat(e.css('padding-bottom')); let gap = border + padding; if (typeof valueOrMargin === 'number') { return valueOrMargin - gap; } else { let suffix = valueOrMargin.substring(valueOrMargin.length - 1); if (suffix === 'x') { return parseFloat(valueOrMargin) - gap; } else { return 'calc(' + parseFloat(valueOrMargin) + '% - ' + gap + 'px)'; } } } function computePadding(e) { let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); if (typeof valueOrMargin === 'number') { return valueOrMargin - border; } else { let suffix = valueOrMargin.substring(valueOrMargin.length - 1); if (suffix === 'x') { return parseFloat(valueOrMargin) - border; } else { return 'calc(' + parseFloat(valueOrMargin) + '% - ' + border + 'px)'; } } } return this; }; /** * * @param valueOrMargin {*} * @return {*} */ jTS.fn.outerWidth = /*number || jTS*/function (/*number || string || boolean*/valueOrMargin) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerWidth; } if (t[0] === document) { return _('html').outerWidth(); } if (arguments.length !== 0) { if (typeof arguments[0] === 'boolean') { let e = _(t[0]); let marginWidth = valueOrMargin ? parseFloat(e.css('margin-left')) + parseFloat(e.css('margin-right')) : 0; return t[0].getBoundingClientRect().width + marginWidth; } else { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('width', valueOrMargin); break; case 'content-box': e.css('width', computeContent(e)); break; case 'padding-box': e.css('width', computePadding(e)); break; } }); } } else { return t[0].getBoundingClientRect().width; } function computeContent(e) { let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); let padding = parseFloat(e.css('padding-left')) + parseFloat(e.css('padding-right')); let gap = border + padding; if (typeof valueOrMargin === 'number') { return valueOrMargin - gap; } else { let suffix = valueOrMargin.substring(valueOrMargin.length - 1); if (suffix === 'x') { return parseFloat(valueOrMargin) - gap; } else { return 'calc(' + parseFloat(valueOrMargin) + '% - ' + gap + 'px)'; } } } function computePadding(e) { let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); if (typeof valueOrMargin === 'number') { return valueOrMargin - border; } else { let suffix = valueOrMargin.substring(valueOrMargin.length - 1); if (suffix === 'x') { return parseFloat(valueOrMargin) - border; } else { return 'calc(' + parseFloat(valueOrMargin) + '% - ' + border + 'px)'; } } } return this; }; /** * * @param value {*} * @return {*} */ jTS.fn.paddingHeight = /*number || jTS*/function (/*number || string*/value) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerHeight; } if (t[0] === document) { return _('html').outerHeight(); } if (arguments.length !== 0) { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('height', computeBorder(e)); break; case 'content-box': e.css('height', computeContent(e)); break; case 'padding-box': e.css('height', value); break; } }); } else { let e = _(t[0]); let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); return t[0].getBoundingClientRect().height - border; } function computeBorder(e) { let border = parseFloat(e.css('border-top-width')) + parseFloat(e.css('border-bottom-width')); if (typeof value === 'number') { return value + border; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + border; } else { return 'calc(' + parseFloat(value) + '% + ' + border + 'px)'; } } } function computeContent(e) { let padding = parseFloat(e.css('padding-top')) + parseFloat(e.css('padding-bottom')); if (typeof value === 'number') { return value - padding; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) - padding; } else { return 'calc(' + parseFloat(value) + '% - ' + padding + 'px)'; } } } return this; }; /** * * @param value {*} * @return {*} */ jTS.fn.paddingWidth = /*number || jTS*/function (/*number || string*/value) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerWidth; } if (t[0] === document) { return _('html').outerWidth(); } if (arguments.length !== 0) { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('width', computeBorder(e)); break; case 'content-box': e.css('width', computeContent(e)); break; case 'padding-box': e.css('width', value); break; } }); } else { let e = _(t[0]); let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); return t[0].getBoundingClientRect().width - border; } function computeBorder(e) { let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); if (typeof value === 'number') { return value + border; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + border; } else { return 'calc(' + parseFloat(value) + '% + ' + border + 'px)'; } } } function computeContent(e) { let padding = parseFloat(e.css('padding-left')) + parseFloat(e.css('padding-right')); if (typeof value === 'number') { return value - padding; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) - padding; } else { return 'calc(' + parseFloat(value) + '% - ' + padding + 'px)'; } } } return this; }; /** * * @param classToRemove {string} * @return {jTS} */ jTS.fn.removeClass = /*jTS*/function (/*string*/classToRemove) { const t = this; let classToRemoveArray = classToRemove.trim().split(' '); t.each(rValue); function rValue(i, e) { let oldClass = e.getAttribute('class'); let oldClassArray = oldClass ? oldClass.split(' ') : []; for(let i = 0; i < classToRemoveArray.length ; i++){ let classToR = classToRemoveArray[i].trim(); if(oldClassArray.indexOf(classToR) !== -1){ oldClassArray.splice(oldClassArray.indexOf(classToR),1); } } e.setAttribute('class', oldClassArray.join(' ').trim()); } return this; }; /** * * @param left {*} * @param top {*} * @return {*} */ jTS.fn.screenCoordinates = /*Object literal|| jTS*/ function (/*string || number*/left, /*string || number*/top) { const t = this; if(t.length === 0){ return t; } let pageOffset = getPageOffset(); if (arguments.length === 0) { return getCoordinates(); } else { let flag = true; if (arguments[0] != null) { if (typeof arguments[0] !== 'number' && typeof arguments[0] !== 'string') { console.log('not-valid-parameters-list @jTSscreenCoordinates'); flag = false; } } if (arguments[1]) { if (typeof arguments[1] !== 'number' && typeof arguments[1] !== 'string') { console.log('not-valid-parameters-list @jTSscreenCoordinates'); flag = false; } } processArguments(); if((left && isNaN(left)) || (top && isNaN(top))){ flag = false; } if (flag) { t.each(assignArguments); } } function assignArguments(i, e) { let p = e.offsetParent; while (p) { if (left || left === 0) { left -= p.offsetLeft; } if (top || top === 0) { top -= p.offsetTop; } p = p.offsetParent; } if (left || left === 0) { left += pageOffset.x; left = left + 'px'; e.style.left = left; } else { e.style.left = e.offsetLeft + 'px'; } if (top || top === 0) { top += pageOffset.y; top = top + 'px'; e.style.top = top; } else { e.style.top = e.offsetTop + 'px'; } e.style.position = 'absolute'; } function getCoordinates() { let coordinates = t.first().elementGlobalPosition(); return { "left" : coordinates.x - pageOffset.x, "top" : coordinates.y - pageOffset.y } } function getPageOffset() { let w = window; let d = document; let scrollX = w.pageXOffset || d.documentElement.scrollLeft || d.body.scrollLeft; let scrollY = w.pageYOffset || d.documentElement.scrollTop || d.body.scrollTop; return { 'x': scrollX, 'y': scrollY }; } function processArguments() { if (left || left === 0) { if (typeof left === 'string') { left = parseFloat(left); } } if (top || top === 0) { if (typeof top === 'string') { top = parseFloat(top); } } } return this; }; /** * * @param classToToggle {string} * @return {jTS} */ jTS.fn.toggleClass = /*jTS*/function (/*string*/classToToggle) { const t = this; let classArray = classToToggle.split(' '); t.each(toggleVal); function toggleVal(i, e) { for(let i = 0; i < classArray.length; i++){ if (_(e).hasClass(classArray[i].trim())) { _(e).removeClass(classArray[i].trim()); } else { _(e).addClass(classArray[i].trim()); } } } return this; }; /** * * @param value {*} * @return {*} */ jTS.fn.width = /*number || jTS*/function (/*number || string*/value) { const t = this; if(t.length === 0){ return t; } if (t[0] === window) { return window.innerWidth; } if (t[0] === document) { return _('html').outerWidth(); } if (arguments.length !== 0) { t.each(function (index, element) { let e = _(element); let box = e.css('box-sizing'); switch (box) { case 'border-box': e.css('width', computeBorder(e)); break; case 'content-box': e.css('width', value); break; case 'padding-box': e.css('width', computePadding(e)); break; } }); } else { let e = _(t[0]); let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); let padding = parseFloat(e.css('padding-left')) + parseFloat(e.css('padding-right')); return ((t[0].getBoundingClientRect().width - border) - padding); } function computeBorder(e) { let border = parseFloat(e.css('border-left-width')) + parseFloat(e.css('border-right-width')); let padding = parseFloat(e.css('padding-left')) + parseFloat(e.css('padding-right')); let gap = border + padding; if (typeof value === 'number') { return value + gap; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + gap; } else { return 'calc(' + parseFloat(value) + '% + ' + gap + 'px)'; } } } function computePadding(e) { let padding = parseFloat(e.css('padding-left')) + parseFloat(e.css('padding-right')); if (typeof value === 'number') { return value + padding; } else { let suffix = value.substring(value.length - 1); if (suffix === 'x') { return parseFloat(value) + padding; } else { return 'calc(' + parseFloat(value) + '% + ' + padding + 'px)'; } } } return this; }; /*END CSS PACKAGE*/ /*DOM HANDLING PACKAGE*/ /** * * @param value {boolean} * @return {*} */ jTS.fn.active = /*boolean || jTS*/ function(/*boolean*/value){ const t = this; if(arguments.length === 1){ t.attr('active',value); return t; }else{ return t.attr('active'); } }; /** * * @param content {*} * @param after {*} * @return {jTS} */ jTS.fn.append = /*jTS*/function (/*DOM Element || Node List || string || number || Array[Any] || jTS*/content, /*string || DOM Element*/after) { const t = this; let jTSObject = []; let constructor = String(content.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = content; } else { jTSObject = _(content); } if (jTSObject.length === 0 && constructor.match(/String/)) { jTSObject = []; parseChildNodes(content); } if (jTSObject.length === 0 && constructor.match(/Number/)) { jTSObject = []; parseChildNodes(content.toString()); } if (constructor.match(/Array/)) { jTSObject = []; for (let i = 0; i < content.length; i++) { let currentObject = _(content[i]); if (currentObject.length === 0 && (typeof content[i] === 'string' || typeof content[i] === 'number')) { parseChildNodes(content[i].toString()); } else if (currentObject.length > 0) { currentObject.each(function (i, e) { jTSObject.push(e); }); } } } function parseChildNodes(val) { let canvas = document.createElement('div'); canvas.innerHTML = val; for (let i = 0; i < canvas.childNodes.length ; i++) { jTSObject.push(canvas.childNodes[i]); } } t.each(addList); function addList(index, e) { let target = null; let children = null; let flag = false; if (after) { target = _(after); if (target.length > 0) { children = e.childNodes; } } if (children) { for (let i = 0; i < children.length; i++) { let child = children[i]; for (let n = 0; n < target.length; n++) { if (child === target[n]) { flag = true; target = child; break; } } } } if (flag) { for (let l = 0; l < jTSObject.length; l++) { let clone = null; if (index === 0) { clone = jTSObject[l]; } else { clone = jTSObject[l].cloneNode(true); } if (jTSObject[l].nodeType !== 3) { target.insertAdjacentElement('afterend', clone); } else { target.insertAdjacentText('afterend', clone.textContent); } target = clone; } } else { for (let h = 0; h < jTSObject.length; h++) { let clone = null; if (index === 0) { clone = jTSObject[h]; } else { clone = jTSObject[h].cloneNode(true); } e.appendChild(clone); } } } return this; }; /** * * @param content {*} * @return {jTS} */ jTS.fn.appendOut = /*jTS*/function (/*DOM Element || Node List || string || number || Array[Any] || jTS*/content) { const t = this; let jTSObject = []; let constructor = String(content.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = content; } else { jTSObject = _(content); } if (jTSObject.length === 0 && constructor.match(/String/)) { jTSObject = []; parseChildNodes(content); } if (jTSObject.length === 0 && constructor.match(/Number/)) { jTSObject = []; parseChildNodes(content.toString()); } if (constructor.match(/Array/)) { jTSObject = []; for (let i = 0; i < content.length; i++) { let currentObject = _(content[i]); if (currentObject.length === 0 && (typeof content[i] === 'string' || typeof content[i] === 'number')) { parseChildNodes(content[i].toString()); } else if (currentObject.length > 0) { currentObject.each(function (i, e) { jTSObject.push(e); }); } } } function parseChildNodes(val) { let canvas = document.createElement('div'); canvas.innerHTML = val; for (let i = 0; i < canvas.childNodes.length ; i++) { jTSObject.push(canvas.childNodes[i]); } } t.each(addList); function addList(index, e) { let target = e; for (let i = 0; i < jTSObject.length; i++) { let clone = null; if (index === 0) { clone = jTSObject[i]; } else { clone = jTSObject[i].cloneNode(true); } if (jTSObject[i].nodeType !== 3) { target.insertAdjacentElement('afterend', clone); } else { target.insertAdjacentText('afterend', clone.textContent); } target = clone; } } return this; }; /** * * @param attributes {*} * @param value {*} * @return {*} */ jTS.fn.attr = /*jTS || string || boolean*/function (/*string || Object literal*/attributes, /*string || number*/value) { const t = this; if(t.length === 0){ return t; } if (arguments.length === 1 && typeof arguments[0] === 'string') { return getAttribute(attributes); } else if (arguments.length === 1 && typeof arguments[0] === 'object') { setAttributes(attributes); } else if (arguments.length === 2 && typeof arguments[0] === 'string') { let currentObject = {}; currentObject[attributes] = value; setAttributes(currentObject); } else { console.log('incorrect-arguments-list @jTS.attr'); } function getAttribute(a) { for (let i = 0; i < jTS.boolean.value_attribute.length; i++) { if (jTS.boolean.value_attribute[i] === a) { if(t[0].getAttribute(a) || t[0].attributes[a]){ return true; } return t[0][a]; } } return t[0].getAttribute(a); } function setAttributes(a) { t.each(function (i, e) { for (let attributeName in a) { if(a.hasOwnProperty(attributeName)){ let flag = false; let attribute = e.getAttributeNode(attributeName) || document.createAttribute(attributeName); for (let i = 0; i < jTS.boolean.value_attribute.length; i++) { if (jTS.boolean.value_attribute[i] === attributeName) { e[attributeName] = Boolean(a[attributeName]); flag = true; if (Boolean(a[attributeName])) { if (!e.getAttributeNode(attributeName)) { e.setAttributeNode(attribute); } } else { if (e.getAttributeNode(attributeName)) { e.attributes.removeNamedItem(attributeName); } } break; } } if (!flag) { attribute.value = a[attributeName]; if (jTS.jBrowser() === 'IE' && attributeName.toLocaleLowerCase() === 'type') { /*this only for IE bug*/ e.setAttribute('type', a[attributeName]); } else { e.setAttributeNode(attribute); } } } } }); } return this; }; /** * * @param content {*} * @param previousTo {*} * @return {jTS} */ jTS.fn.before = /*jTS*/function (/*DOM Element || Node List || string || number || Array[Any] || jTS*/content, /*String || DOM element*/previousTo) { const t = this; let jTSObject = []; let constructor = String(content.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = content; } else { jTSObject = _(content); } if (jTSObject.length === 0 && constructor.match(/String/)) { jTSObject = []; parseChildNodes(content); } if (jTSObject.length === 0 && constructor.match(/Number/)) { jTSObject = []; parseChildNodes(content.toString()); } if (constructor.match(/Array/)) { jTSObject = []; for (let i = 0; i < content.length; i++) { let currentObject = _(content[i]); if (currentObject.length === 0 && (typeof content[i] === 'string' || typeof content[i] === 'number')) { parseChildNodes(content[i].toString()); } else if (currentObject.length > 0) { currentObject.each(function (i, e) { jTSObject.push(e); }); } } } function parseChildNodes(val) { let canvas = document.createElement('div'); canvas.innerHTML = val; for (let i = 0; i < canvas.childNodes.length ; i++) { jTSObject.push(canvas.childNodes[i]); } } t.each(addList); function addList(index, e) { let target = null; let children = null; let flag = false; if (previousTo) { target = _(previousTo); if (target) { children = e.childNodes; } } if (children) { for (let i = 0; i < children.length; i++) { let child = children[i]; for (let n = 0; n < target.length; n++) { if (child === target[n]) { target = child; flag = true; break; } } } } if (!flag) { target = e.childNodes[0]; } if (target) { for (let l = 0; l < jTSObject.length; l++) { let clone = null; if (index === 0) { clone = jTSObject[l]; } else { clone = jTSObject[l].cloneNode(true); } e.insertBefore(clone, target); } } else { for (let h = 0; h < jTSObject.length; h++) { let clone = null; if (index === 0) { clone = jTSObject[h]; } else { clone = jTSObject[h].cloneNode(true); } e.appendChild(clone); } } } return this; }; /** * * @param content {*} * @return {jTS} */ jTS.fn.beforeOut = /*jTS*/function (/*DOM Element || Node List || string || number || Array[Any] || jTS*/content) { const t = this; let jTSObject = []; let constructor = String(content.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = content; } else { jTSObject = _(content); } if (jTSObject.lenght === 0 && constructor.match(/String/)) { jTSObject = []; parseChildNodes(content); } if (jTSObject.lenght === 0 && constructor.match(/Number/)) { jTSObject = []; parseChildNodes(content.toString()); } if (constructor.match(/Array/)) { jTSObject = []; for (let i = 0; i < content.length; i++) { let currentObject = _(content[i]); if (currentObject.length === 0 && (typeof content[i] === 'string' || typeof content[i] === 'number' )) { parseChildNodes(content[i].toString()); } else if (currentObject.length > 0) { currentObject.each(function (i, e) { jTSObject.push(e); }); } } } function parseChildNodes(val) { let canvas = document.createElement('div'); canvas.innerHTML = val; for (let i = 0; i < canvas.childNodes.length ; i++) { jTSObject.push(canvas.childNodes[i]); } } t.each(addList); function addList(index, e) { for (let i = 0; i < jTSObject.length; i++) { let clone = null; if (index === 0) { clone = jTSObject[i]; } else { clone = jTSObject[i].cloneNode(true); } _(e).offsetPs()[0].insertBefore(clone, e); } } return this; }; /** * * @param value {boolean} * @return {*} */ jTS.fn.disabled = /*boolean || jTS*/ function(/*boolean*/value){ const t = this; if(arguments.length === 1){ t.attr('disabled',value); return t; }else{ return t.attr('disabled'); } }; /** * * @return {jTS} */ jTS.fn.dispose = /*jTS*/function () { let t = this; t.each(disposeElement); function disposeElement(i, e) { _(e).offsetPs()[0].removeChild(e); } return this; }; /** * * @param content {*} * @return {*} */ jTS.fn.html = /*jTS || string*/function (/*DOM Element || Node List || string || number || Array[Any] || jTS*/content) { const t = this; if(t.length === 0){ return t; } if (content !== '' && !content) { return String(t[0].innerHTML).trim(); } let jTSObject = []; let constructor = String(content.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = content; } else { jTSObject = _(content); } if (jTSObject.length === 0 && constructor.match(/String/)) { jTSObject = []; parseChildNodes(content); } if (jTSObject.length === 0 && constructor.match(/Number/)) { jTSObject = []; parseChildNodes(content.toString()); } if (constructor.match(/Array/)) { jTSObject = []; for (let i = 0; i < content.length; i++) { let currentObject = _(content[i]); if (currentObject.length === 0 && (typeof content[i] === 'string' || typeof content[i] === 'number')) { parseChildNodes(content[i].toString()); } else if (currentObject.length > 0) { currentObject.each(function (i, e) { jTSObject.push(e); }); } } } function parseChildNodes(val) { let canvas = document.createElement('div'); canvas.innerHTML = val; for (let i = 0; i < canvas.childNodes.length ; i++) { jTSObject.push(canvas.childNodes[i]); } } t.each(addHTML); function addHTML(index, element) { element.innerHTML = ''; for (let i = 0; i < jTSObject.length; i++) { let clone = jTSObject[i].cloneNode(true); element.appendChild(clone); } } return this; }; /** * * @return {string} */ jTS.jBrowser = /*string*/function () { let browser; if (navigator.userAgent.indexOf('Firefox') !== -1) { browser = 'firefox'; } else if (navigator.userAgent.indexOf('Edg') !== -1) { browser = 'edge'; } else if (navigator.userAgent.indexOf('Chrome') !== -1 && navigator.userAgent.indexOf('Edg') === -1 && navigator.userAgent.indexOf('OPR') === -1) { browser = 'chrome'; } else if (navigator.userAgent.indexOf('OPR') !== -1) { browser = 'opera'; } else if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) { browser = 'safari'; } else if (navigator.userAgent.indexOf('Trident') !== -1) { browser = 'IE'; } return browser; }; /** * * @param loaderFile {string} * @return {void} */ jTS.jImages = /*void*/function (/*string*/loaderFile) { let container = document.createElement('div'); jTS.jJSON(loaderFile, load); function load(data) { let array; for (let name in data) { if(data.hasOwnProperty(name)){ array = data[name]; loadImage(0); } } function loadImage(index) { if (index < array.length) { let image = new Image(); let src = array[index]; image.src = String(name + array[index]); image.alt = String(new Date().getTime() + '_' + index); _(container).append(image); loadImage(index + 1); } } //this for real loading _(container).css('display', 'none').attr('id', 'jts_j_images_' + new Date().getTime()); _('body').append(container); } }; /** * * @return {boolean} */ jTS.jMobile = /*boolean*/function () { return window.navigator.userAgent.indexOf('iPhone') !== -1 || window.navigator.userAgent.indexOf('iPad') !== -1 || window.navigator.userAgent.indexOf('Android') !== -1; }; /** * * @param element {*} * @param single {boolean} * @return {jTS} */ jTS.fn.wrap = /*jTS*/function (/*string || DOM Element || Node List || jTS*/element , /*boolean*/single) { const t = this; let jTSObject = []; let constructor = String(element.constructor); if (constructor.match(/\/\*jTS constructor fingerprint\*\//)) { jTSObject = element; } else { jTSObject = _(element); } if (jTSObject.length === 0) { console.log('can-not-create-wrap-element @jTS.wrap'); } let parent = t.first().offsetPs()[0]; let sibling = t.first()[0].previousElementSibling; let wrapper = jTSObject[0].cloneNode(true); let target = findChildren(wrapper); t.each(function (i, e) { if(!single){ parent = _(e).offsetPs()[0]; sibling = e.previousElementSibling; wrapper = jTSObject[0].cloneNode(true); target = findChildren(wrapper); } _(target).append(e); if(sibling){ _(parent).append(wrapper, sibling); } else{ _(parent).before(wrapper); } }); function findChildren(node) { let flag = false; if (node.childNodes.length !== 0) { for (let i = 0; i < node.childNodes.length; i++) { if (node.childNodes[i].nodeType !== 3) { flag = true; node = node.childNodes[i]; break; } } } if (flag) { return findChildren(node); } else { return node; } } return this; }; /*END DOM HANDLING PACKAGE*/ /*EVENTS FLOW PACKAGE*/ /** * * @param eventType {string} * @param callback {Function} * @param data {Object} * @return {jTS} */ jTS.fn.bind = /*jTS*/function (/*string*/eventType,/*Function*/callback,/*Object literal*/data) { const t = this; let typeNamespaceArray = eventType.split('.'); let eventsList = typeNamespaceArray[0].split(' '); let namespace = typeNamespaceArray.length > 1 ? typeNamespaceArray[1] : 'none'; for (let i = 0; i < eventsList.length; i++) { if (!jTS.flow.events[eventsList[i]]) { let config = false; if (eventsList[i].match('touch') || eventType.match('mousewheel') || eventType.match('DOMMouseScroll') || eventType.match('MozMousePixelScroll')) { config = { 'passive': false }; } window.addEventListener(eventsList[i], callerF, config); jTS.flow.events[eventsList[i]] = true; } if (!jTS.flow.listeners[eventsList[i] + '-' + namespace]) { jTS.flow.stackIndex[eventsList[i] + '-' + namespace] = 0; jTS.flow.listeners[eventsList[i] + '-' + namespace] = []; } } function callerF(e) { let setName = []; for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ if (String(n).split('-')[0].match(e.type)) { setName.push(String(n)); } } } e.immediatePropS = false; e.propagationStopped = false; e.propagationSO = null; let target = e.target; if (target !== window && target !== document) { while (target) { triggerListener(target); target = _(target).offsetPs()[0]; } } target = document; triggerListener(target); target = window; triggerListener(target); function triggerListener(target) { for (let i = 0; i < setName.length; i++) { jTS.flow.stackIndex[setName[i]] = 0; findListener(jTS.flow.stackIndex[setName[i]],i); setName = []; for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ if (String(n).split('-')[0].match(e.type)) { setName.push(String(n)); } } } } function findListener(index,forIndex) { if (index < jTS.flow.listeners[setName[forIndex]].length) { let l = jTS.flow.listeners[setName[forIndex]][index]; if (target === l.element && l.type.match(e.type) && (!l.executed)) { if (!e.immediatePropS) { let flag = true; if (e.propagationStopped && e.propagationSO !== l.element) { flag = false; } if (flag) { let jTSEvent = new jTS.flow.Event(e, l, data); l.executed = true; l.callback.call(l.element, jTSEvent); } } } jTS.flow.stackIndex[setName[forIndex]] += 1; if (jTS.flow.stackIndex[setName[forIndex]] < 0) { jTS.flow.stackIndex[setName[forIndex]] = 0; } findListener(jTS.flow.stackIndex[setName[forIndex]],forIndex); } else { for (let m = 0; m < jTS.flow.listeners[setName[forIndex]].length; m++) { jTS.flow.listeners[setName[forIndex]][m].executed = false; } } } } jTS.flow.clearFlow(); } t.each(addListener); function addListener(index, e) { for (let i = 0; i < eventsList.length; i++) { let listener = { 'type': eventsList[i], 'element': e, 'index': index, 'callback': callback, 'namespace': namespace, 'executed': false }; jTS.flow.listeners[eventsList[i] + '-' + namespace].push(listener); } } return this; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.click = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let clickNamespace; let clickHandler; let clickData; if((typeof arguments[0]).toLowerCase() === 'string'){ clickNamespace = '.' + namespace; clickHandler = handler; if(arguments.length === 3){ clickData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ clickNamespace = ''; clickHandler = arguments[0]; if(arguments.length === 2){ clickData = arguments[1]; } } t.bind(`click${clickNamespace}`,clickHandler,clickData); return t; }; /** * * @param type {string} * @param data {Object} * @return {jTS} */ jTS.fn.emits = /*jTS*/function (/*string*/type,/*Object literal*/data) { const t = this; if (!data) { data = {}; } jTS.jFlow.jStackIndex = 0; executeQuery(jTS.jFlow.jStackIndex); function executeQuery(index) { if (index < jTS.jFlow.jListeners.length) { let l = jTS.jFlow.jListeners[index]; if (l.type === type) { if ((!l.once || l.counter === 0) && !l.executed) { let event = new jTS.jFlow.jEvent(type, t, l.element, data); l.executed = true; l.callback.call(l.element, event); l.counter += 1; } } jTS.jFlow.jStackIndex = index + 1; jTS.jFlow.jStackIndex -= jTS.jFlow.unbindIndex; jTS.jFlow.unbindIndex = 0; if (jTS.jFlow.jStackIndex < 0) { jTS.jFlow.jStackIndex = 0; } executeQuery(jTS.jFlow.jStackIndex); } else { for (let m = 0; m < jTS.jFlow.jListeners.length; m++) { jTS.jFlow.jListeners[m].executed = false; } } } return this; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.mouseDown = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let mouseDownNamespace; let mouseDownHandler; let mouseDownData; let event = jTS.jMobile() ? 'touchstart' : 'mousedown'; if((typeof arguments[0]).toLowerCase() === 'string'){ mouseDownNamespace = '.' + namespace; mouseDownHandler = handler; if(arguments.length === 3){ mouseDownData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ mouseDownNamespace = ''; mouseDownHandler = arguments[0]; if(arguments.length === 2){ mouseDownData = arguments[1]; } } t.bind(`${event}${mouseDownNamespace}`,mouseDownHandler,mouseDownData); return t; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.mouseMove = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let mouseMoveNamespace; let mouseMoveHandler; let mouseMoveData; let event = jTS.jMobile() ? 'touchmove' : 'mousemove'; if((typeof arguments[0]).toLowerCase() === 'string'){ mouseMoveNamespace = '.' + namespace; mouseMoveHandler = handler; if(arguments.length === 3){ mouseMoveData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ mouseMoveNamespace = ''; mouseMoveHandler = arguments[0]; if(arguments.length === 2){ mouseMoveData = arguments[1]; } } t.bind(`${event}${mouseMoveNamespace}`,mouseMoveHandler,mouseMoveData); return t; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.mouseOut = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let mouseOutNamespace; let mouseOutHandler; let mouseOutData; let event = jTS.jMobile() ? 'touchend' : 'mouseout'; if((typeof arguments[0]).toLowerCase() === 'string'){ mouseOutNamespace = '.' + namespace; mouseOutHandler = handler; if(arguments.length === 3){ mouseOutData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ mouseOutNamespace = ''; mouseOutHandler = arguments[0]; if(arguments.length === 2){ mouseOutData = arguments[1]; } } t.bind(`${event}${mouseOutNamespace}`,mouseOutHandler,mouseOutData); return t; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.mouseOver = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let mouseOverNamespace; let mouseOverHandler; let mouseOverData; let event = jTS.jMobile() ? 'touchstart' : 'mouseover'; if((typeof arguments[0]).toLowerCase() === 'string'){ mouseOverNamespace = '.' + namespace; mouseOverHandler = handler; if(arguments.length === 3){ mouseOverData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ mouseOverNamespace = ''; mouseOverHandler = arguments[0]; if(arguments.length === 2){ mouseOverData = arguments[1]; } } t.bind(`${event}${mouseOverNamespace}`,mouseOverHandler,mouseOverData); return t; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.mouseUp = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let mouseUpNamespace; let mouseUpHandler; let mouseUpData; let event = jTS.jMobile() ? 'touchend' : 'mouseup'; if((typeof arguments[0]).toLowerCase() === 'string'){ mouseUpNamespace = '.' + namespace; mouseUpHandler = handler; if(arguments.length === 3){ mouseUpData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ mouseUpNamespace = ''; mouseUpHandler = arguments[0]; if(arguments.length === 2){ mouseUpData = arguments[1]; } } t.bind(`${event}${mouseUpNamespace}`,mouseUpHandler,mouseUpData); return t; }; /** * * @param typeOrFamily {string} * @return {jTS} */ jTS.fn.off = /*jTS*/function (/*string*/typeOrFamily) { const t = this; let types = ''; let family = ''; let isFamily = false; let isEvent = false; jTS.jFlow.unbindIndex = 0; if (typeOrFamily.match(/^\./)) { family = typeOrFamily.substring(1); isFamily = true; } else if (typeOrFamily.match(/\w+\.\w+/)) { types = typeOrFamily.split('.')[0]; family = typeOrFamily.split('.')[1]; isFamily = true; isEvent = true; } else { types = typeOrFamily; isEvent = true; } t.each(unbindListener); function unbindListener(index, element) { if (isFamily && !isEvent) { for (let i = 0; i < jTS.jFlow.jListeners.length; i++) { let listener = jTS.jFlow.jListeners[i]; let regExp = '\\s' + listener.surname + '\\s'; let regExp2 = '\\s' + listener.surname + '$'; let regExp3 = '^' + listener.surname + '\\s'; let regExp4 = '^' + listener.surname + '$'; if (listener.element === element && (family.match(RegExp(regExp)) || family.match(RegExp(regExp2)) || family.match(RegExp(regExp3)) || family.match(RegExp(regExp4)))) { jTS.jFlow.jListeners.splice(i, 1); jTS.jFlow.unbindIndex += 1; i -= 1; } } } else if (isFamily && isEvent) { for (let i = 0; i < jTS.jFlow.jListeners.length; i++) { let listener = jTS.jFlow.jListeners[i]; let regExp = '\\s' + listener.surname + '\\s'; let regExp2 = '\\s' + listener.surname + '$'; let regExp3 = '^' + listener.surname + '\\s'; let regExp4 = '^' + listener.surname + '$'; let regExp5 = '\\s' + listener.type + '\\s'; let regExp6 = '\\s' + listener.type + '$'; let regExp7 = '^' + listener.type + '\\s'; let regExp8 = '^' + listener.type + '$'; if (listener.element === element && (family.match(RegExp(regExp)) || family.match(RegExp(regExp2)) || family.match(RegExp(regExp3)) || family.match(RegExp(regExp4))) && (types.match(RegExp(regExp5)) || types.match(RegExp(regExp6)) || types.match(RegExp(regExp7)) || types.match(RegExp(regExp8)))) { jTS.jFlow.jListeners.splice(i, 1); jTS.jFlow.unbindIndex += 1; i -= 1; } } } else if (isEvent && !isFamily) { for (let i = 0; i < jTS.jFlow.jListeners.length; i++) { let listener = jTS.jFlow.jListeners[i]; let regExp = '\\s' + listener.type + '\\s'; let regExp2 = '\\s' + listener.type + '$'; let regExp3 = '^' + listener.type + '\\s'; let regExp4 = '^' + listener.type + '$'; if (listener.element === element && (types.match(RegExp(regExp)) || types.match(RegExp(regExp2)) || types.match(RegExp(regExp3)) || types.match(RegExp(regExp4)))) { jTS.jFlow.jListeners.splice(i, 1); jTS.jFlow.unbindIndex += 1; i -= 1; } } } } return this; }; /** * * @param type {string} * @param callback {Function} * @return {jTS} */ jTS.fn.on = /*jTS*/function (/*string*/type,/*Function*/callback) { const t = this; let typesAndNamespaces = type.split('.'); let types = typesAndNamespaces[0].split(' '); let namespace = typesAndNamespaces.length > 1 ? typesAndNamespaces[1] : 'none'; t.each(addListener); function addListener(i, e) { for (let i = 0; i < types.length; i++) { let l = { 'type': types[i], 'callback': callback, 'namespace': namespace, 'element': e, 'once': false, 'counter': 0, 'executed': false }; jTS.jFlow.jListeners.push(l); } } return this; }; /** * * @param type {string} * @param callback {Function} * @return {jTS} */ jTS.fn.once = /*jTS*/function (/*string*/type,/*Function*/callback) { const t = this; let typesAndNamespace = type.split('.'); let types = typesAndNamespace[0].split(' '); let namespace = typesAndNamespace.length > 1 ? typesAndNamespace[1] : 'none'; t.each(addListener); function addListener(i, e) { for (let i = 0; i < types.length; i++) { let l = { 'type': types[i], 'callback': callback, 'namespace': namespace, 'element': e, 'once': true, 'counter': 0, 'executed': false }; jTS.jFlow.jListeners.push(l); } } return this; }; /** * * @param namespace {string} * @param handler {Function} * @param data {Object} * @return {jTS} */ jTS.fn.scroll = /*jTS*/function(/*string*/namespace,/*Function*/handler,/*Object literal*/data){ const t = this; let scrollNamespace; let scrollHandler; let scrollData; let event = jTS.jMobile() ? 'touchmove' : 'mousewheel DOMMouseScroll MozMousePixelScroll'; if((typeof arguments[0]).toLowerCase() === 'string'){ scrollNamespace = '.' + namespace; scrollHandler = handler; if(arguments.length === 3){ scrollData = data; } }else if((typeof arguments[0]).toLowerCase() === 'function'){ scrollNamespace = ''; scrollHandler = arguments[0]; if(arguments.length === 2){ scrollData = arguments[1]; } } t.bind(`${event}${scrollNamespace}`,scrollHandler,scrollData); t.each((i,e) => { e.onscroll = scrollHandler; }); return t; }; /** * * @param typeOrFamily {string} * @return {jTS} */ jTS.fn.unbind = /*jTS*/function (/*string*/typeOrFamily) { const t = this; let types = []; let family = []; let list = []; if (typeOrFamily.match(/^\./)) { family = typeOrFamily.substring(1).split(' '); for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ for (let i = 0; i < family.length; i++) { if (String(n).match(RegExp('-' + family[i] + '$'))) { list.push(String(n)) } } } } } else if (typeOrFamily.match(/\w+\.\w+/)) { types = typeOrFamily.split('.')[0].split(' '); family = typeOrFamily.split('.')[1].split(' '); for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ for (let l = 0; l < types.length; l++) { for (let h = 0; h < family.length; h++) { if (String(n) === types[l] + '-' + family[h]) { list.push(String(n)) } } } } } } else { types = typeOrFamily.split(' '); for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ for (let m = 0; m < types.length; m++) { if (String(n).match(RegExp('^' + types[m] + '-'))) { list.push(String(n)); } } } } } t.each(disposeListener); function disposeListener(i, e) { for (let i = 0; i < list.length; i++) { let lSet = jTS.flow.listeners[list[i]]; for (let l = 0; l < lSet.length; l++) { let listener = lSet[l]; if (listener.element === e) { lSet.splice(l, 1); jTS.flow.stackIndex[list[i]] -= 1; l -= 1; } } } } return this; }; /*END EVENTS FLOW PACKAGE*/ /*FORMS PACKAGE*/ /** * * @param add {Object} * @param filter {string} * @return {Object} */ jTS.fn.serialize = /*Object literal*/function (/*Object literal*/add,/*string*/filter) { const t = this; let toAdd = null; let toFilter = null; if (arguments.length === 1) { if (typeof arguments[0] === 'string') { toFilter = arguments[0]; } else { toAdd = arguments[0]; } } else if (arguments.length === 2) { toAdd = add; toFilter = filter; } let types = { 'select' : 0, 'textarea' : 0, 'optgroup' : 0, 'option' : 0, 'text' : 0, 'checkbox' : 0, 'password' : 0, 'radio' : 0, 'color' : 0, 'date' : 0, 'file' : 0, 'datetime-local' : 0, 'email' : 0, 'month' : 0, 'number' : 0, 'range' : 0, 'search' : 0, 'tel' : 0, 'image' : 0, 'time' : 0, 'url' : 0, 'week' : 0, 'hidden' : 0 }; let object = {}; let elements = []; let values = []; let names = []; t.each(pushSet); _(elements).each(getValues); fillObject(0); if (toAdd) { addValues(); } function pushSet(index, element) { if(element === window){ element = _('body')[0]; } recursivePush(0, [element]); function recursivePush(i, set) { if (!set) { return; } if (i < set.length) { if (set[i].nodeType === 1 && ((set[i].tagName).toLowerCase() === 'input' || (set[i].tagName).toLowerCase() === 'select' || (set[i].tagName).toLowerCase() === 'textarea' || (set[i].tagName).toLowerCase() === 'optgroup' || (set[i].tagName).toLowerCase() === 'option')) { let flag = false; let name = _(set[i]).attr('name'); if (name) { for (let k = 0; k < names.length; k++) { if (name === names[k]) { flag = true; break; } } names.push(name); } if (toFilter) { if (toFilter.match(RegExp(set[i].tagName, 'i')) || toFilter.match(RegExp(_(set[i]).attr('type'), 'i')) || toFilter.match(RegExp(name))) { flag = true; } } if (!flag) { elements.push(set[i]); } } else { recursivePush(0, set[i].childNodes); } recursivePush(i + 1, set); } } } function getValues(index, element) { values.push(_(element).value()); } function fillObject(index) { if (index < elements.length) { let tag = (elements[index].tagName).toLowerCase(); let type = tag === 'select' || tag === 'textarea' || tag === 'optgropup' || tag === 'option' ? '' : _(elements[index]).attr('type'); let name = getName(elements[index], tag, type); let value = values[index]; if (tag === 'select' || type === 'checkbox' || type === 'file' || tag === 'optgroup' || tag === 'option') { parseValue(name, value); } else { object[name] = values[index]; } fillObject(index + 1); } } function addValues() { for (let n in toAdd) { if(toAdd.hasOwnProperty(n)){ parseValue(n, toAdd[n]); } } } function getName(e, tag, type) { let id = type || tag; let idCounter = types[id] === 0 ? '' : '_' + types[id]; let parsedType = type ? '_' + type : ''; let name = _(e).attr('name') || 'serialized_' + tag + parsedType + idCounter; if (!_(e).attr('name')) { types[id] = types[id] + 1; } return name; } function parseValue(name, value) { if (!value) { object[name] = false; return; } let constructor = String(value.constructor); if (constructor.match(/Array/) || constructor.match(/FileList/)) { for (let i = 0; i < value.length; i++) { let id = i === 0 ? '' : '_v' + i; object[name + id] = value[i]; } } else { object[name] = value; } } return object; }; /** * * @param val {*} * @return {*} */ jTS.fn.value = /*jTS || string || Array || boolean || FileList*/function (/*Any || Array[Any]*/val) { const t = this; let constructor = null; if(t.length === 0){ return t; } if (arguments.length === 0) { return getValue(); } else { if (val !== null) { constructor = String(val.constructor); } t.each(setValue); } function getValue() { let tag = (t[0].tagName).toLowerCase(); switch (tag) { case 'select': case 'option': case 'optgroup': return getSelect(); case 'input': if (t[0].type === 'checkbox') { return getCheckbox(); } else if (t[0].type === 'radio') { return getRadio(); } else if (t[0].type === 'file') { return t[0].files.length === 0 ? getSingle() : t[0].files; } else { return getSingle(); } case 'textarea': case 'li': case 'param': case 'progress': case 'button': return getSingle(); default: return null; } function getSingle() { return t[0].value; } function getSelect() { let array = []; let options; if (tag === 'select') { options = []; for (let n = 0; n < t[0].childNodes.length; n++) { let node = t[0].childNodes[n]; if (node.nodeType === 1 && (node.tagName).toLowerCase() === 'option') { options.push(node); } else if (node.nodeType === 1 && (node.tagName).toLowerCase() === 'optgroup') { for (let b = 0; b < node.childNodes.length; b++) { if (node.childNodes[b].nodeType === 1) { options.push(node.childNodes[b]); } } } } } else if (tag === 'optgroup') { options = t[0].childNodes; } else if (tag === 'option') { options = [t[0]]; } for (let i = 0; i < options.length; i++) { if (options[i].nodeType === 1) { if ((options[i].tagName).toLowerCase() === 'option' && options[i].selected) { array.push(options[i].value); } } } return array.length > 0 ? array : false; } function getCheckbox() { let name = _(t[0]).attr('name'); if (name) { let list = document.querySelectorAll('input[type=checkbox][name=' + name + ']'); if (list.length > 1) { let array = []; for (let i = 0; i < list.length; i++) { if (list[i].checked) { array.push(list[i].value); } } if (array.length > 0) { return array; } } } return t[0].checked ? t[0].value : false; } function getRadio() { let name = _(t[0]).attr('name'); if (name) { let list = document.querySelectorAll('input[type=radio][name=' + name + ']'); if (list.length > 1) { for (let i = 0; i < list.length; i++) { if (list[i].checked) { return list[i].value; } } } } return t[0].checked ? t[0].value : false; } } function setValue(index, element) { let tag = (element.tagName).toLowerCase(); switch (tag) { case 'select': case 'option': case 'optgroup': setSelect(); break; case 'input': if (element.type === 'checkbox' || element.type === 'radio') { setRadioOrCheckbox(); } else { setSingle(); } break; case 'textarea': case 'li': case 'param': case 'progress': case 'button': setSingle(); break; default: break; } function setSingle() { let parsedValue = null; if (constructor != null) { parsedValue = constructor.match(/Array/) ? val[0] : val; } element.value = parsedValue; } function setSelect() { let options; if (tag === 'select') { options = []; for (let n = 0; n < element.childNodes.length; n++) { let node = element.childNodes[n]; if (node.nodeType === 1 && (node.tagName).toLowerCase() === 'option') { options.push(node); } else if (node.nodeType === 1 && (node.tagName).toLowerCase() === 'optgroup') { for (let b = 0; b < node.childNodes.length; b++) { if (node.childNodes[b].nodeType === 1) { options.push(node.childNodes[b]); } } } } } else if (tag === 'optgroup') { options = element.childNodes; } else if (tag === 'option') { options = [element]; } if (constructor.match(/Array/)) { for (let i = 0; i < options.length; i++) { _(options[i]).attr('selected', false); for (let l = 0; l < val.length; l++) { if (options[i].value === String(val[l])) { _(options[i]).attr('selected', true); break; } } } } else { for (let h = 0; h < options.length; h++) { _(options[h]).attr('selected', false); if (options[h].value === String(val)) { _(options[h]).attr('selected', true); } } } } function setRadioOrCheckbox() { if (constructor.match(/Array/)) { for (let i = 0; i < val.length; i++) { if (String(val[i]) === element.value) { _(element).attr('checked', true); break; } } } else { if (String(val) === element.value) { _(element).attr('checked', true); } } } } return this; }; /*END FORMS PACKAGE*/ /*TOOLS PACKAGE*/ /** * * @return {jTS} */ jTS.fn.centerImage = /*JTS*/function () { const t = this; t.each(setPositionAndSize); function setPositionAndSize(i,e) { let tag = e.tagName.toLowerCase(); if (!(tag === 'img' || tag === 'div')) { return; } let image = null; let flag = false; if (tag === 'img') { image = e; flag = true; } else { let nodes = e.children; for (let i = 0; i < nodes.length; i++) { if (nodes[i].nodeType === 1 && nodes[i].tagName.toLowerCase() === 'img') { image = nodes[i]; flag = true; break; } } } if (!flag) { return; } _(image).css('position', 'absolute'); let imageOriginalWidth = 0; let imageOriginalHeight = 0; let imgLoader = new Image(); imgLoader.onload = function () { imageOriginalWidth = this.naturalWidth || this.originalWidth; imageOriginalHeight = this.naturalHeight || this.originalHeight; query(); }; let parent = _(image).offsetPs()[0]; if (parent === document.querySelector('body')) { parent = window; } let parentWidth = _(parent).outerWidth(); let parentHeight = _(parent).outerHeight(); imgLoader.src = image.src; function query() { _(image).css(getValues(parentWidth,parentHeight)); } function getValues(parentWidth,parentHeight) { let imageWidth = 0 , imageHeight = 0, imageLeft , imageTop ; if (parentWidth >= parentHeight) { parseHeight(parentWidth); } else { parseWidth(parentHeight); } imageLeft = (parentWidth * 0.5) - (imageWidth * 0.5); imageTop = (parentHeight * 0.5) - (imageHeight * 0.5); function parseHeight(width) { imageWidth = width; imageHeight = imageOriginalHeight * (width / imageOriginalWidth); if (imageHeight < parentHeight) { parseHeight(width + 1); } } function parseWidth(height) { imageHeight = height; imageWidth = imageOriginalWidth * (height / imageOriginalHeight); if (imageWidth < parentWidth) { parseWidth(height + 1); } } return { 'width': imageWidth, 'height': imageHeight, 'left': imageLeft, 'top': imageTop }; } } return t; }; /** * * @param configuration {Object} * @return {jTS} */ jTS.fn.colorPicker = /*jTS*/function (/*Object literal*/configuration) { const t = this; let SATURATION_BRIGHTNESS_SIZE = 130, HUE_CONTAINER_HEIGHT = 130, HUE_RANGE = 360; let DARK_STYLE = 0 , LIGHT_STYLE = 1 , DEEP_DARK_STYLE = 2; let backgroundColor = ['#333333', '#cecdcd', '#111111']; let hueSelectorImage = ['huesdark.png', 'hueslight.png', 'huesdark.png']; let valueNameBG = ['#262323', '#f3f3f3', '#333333']; let valueValueBG = ['#ffffff', '#333333', '#ffffff']; let textColor = ['#6ba9d7', '#000000', '#f50069']; let valueColor = ['#000000', '#ffffff', '#000000']; let style = DARK_STYLE; switch (configuration.style) { case 'dark': case 'dark-round': style = DARK_STYLE; break; case 'light': case 'light-round': style = LIGHT_STYLE; break; case 'deep-dark': case 'deep-dark-round': style = DEEP_DARK_STYLE; break; } t.each(setPicker); function setPicker(index, element) { _(element).css('cursor', 'pointer'); let container, startRGBColor, startHSBColor; let pickerOut = false; let parsedID = '' + new Date().getTime() + index; _(element).bind('click.jts_picker_events_' + parsedID, function (e) { if (!pickerOut) { pickerOut = true; startRGBColor = parseRGBColor(element); startHSBColor = rGBtoHSB(startRGBColor); addInterface(e); } }); function addInterface(e) { container = document.createElement('div'); let css = { 'position': 'absolute', 'box-shadow': '0px 2px 2px 0px rgba(0,0,0,0.3)', 'top': e.screenY + (window.pageYOffset || document.documentElement.scrollTop), 'left': e.screenX, 'z-index': 500, 'width': 300, 'height': 210, 'background-color': backgroundColor[style], 'border-radius': (configuration.style).match('round') ? 10 : 0 }; _(container).attr('id', 'jts_picker_container_' + parsedID).css(css); _(container).load(configuration.path + 'color_picker/picker_html.html', initPicker); } function initPicker() { _('body').append(container); _('#jts_picker_container_' + parsedID + ' .jts_picker_value , #jts_picker_container_' + parsedID + ' .jts_picker_selector').each(function (i, e) { _(e).attr('id', _(e).attr('id') + '_' + parsedID); }); _('#jts_picker_container_' + parsedID + ' .jts_picker_shade_image').attr('src', configuration.path + 'color_picker/shade.png'); _('#jts_picker_container_' + parsedID + ' .jts_picker_sbs_image').attr('src', configuration.path + 'color_picker/sbselector.png'); _('#jts_picker_container_' + parsedID + ' .jts_picker_hue_image').attr('src', configuration.path + 'color_picker/hue.png'); _('#jts_picker_container_' + parsedID + ' .jts_picker_hues_image').attr('src', configuration.path + 'color_picker/' + hueSelectorImage[style]); _('#jts_picker_container_' + parsedID + ' .jts_picker_name_rgb').css({ 'background-color': valueNameBG[style], 'color': textColor[style] }); _('#jts_picker_container_' + parsedID + ' .jts_picker_value').css({ 'background-color': valueValueBG[style], 'color': valueColor[style] }); _('#jts_picker_container_' + parsedID + ' .jts_picker_compare_container div').css('color', textColor[style]); _('#jts_picker_container_' + parsedID + ' .jts_picker_submit').css({ 'background-color': valueNameBG[style], 'color': textColor[style] }); let rgbColor = 'rgb(' + startRGBColor[0] + ',' + startRGBColor[1] + ',' + startRGBColor[2] + ')'; _('#jts_picker_container_' + parsedID + ' .jts_picker_table').css('background-color', 'hsl(' + startHSBColor[0] + ', 100% , 50%)'); _('#jts_picker_container_' + parsedID + ' .jts_picker_current_color').css('background-color', rgbColor); _('#jts_picker_container_' + parsedID + ' .jts_picker_next_color').css('background-color', rgbColor); _('#jts_red_val_' + parsedID).html(String(startRGBColor[0])); _('#jts_green_val_' + parsedID).html(String(startRGBColor[1])); _('#jts_blue_val_' + parsedID).html(String(startRGBColor[2])); _('#jts_exadecimal_val_' + parsedID).html(String(rGBtoEXADECIMAL(startRGBColor))); let sbX = SATURATION_BRIGHTNESS_SIZE * (startHSBColor[1] / 100); let sbY = SATURATION_BRIGHTNESS_SIZE * (startHSBColor[2] / 100); sbY = SATURATION_BRIGHTNESS_SIZE + (-sbY); let hueY = startHSBColor[0] * (HUE_CONTAINER_HEIGHT / HUE_RANGE); hueY = HUE_CONTAINER_HEIGHT + (-hueY); _('#jts_sb_selector_' + parsedID).css({ 'left': sbX, 'top': sbY }); _('#jts_hue_selector_' + parsedID).css('top', hueY); setPickerListeners(); } function setPickerListeners() { let mobile = jTS.jMobile(); let mousedown = mobile ? 'touchstart' : 'mousedown'; let mousemove = mobile ? 'touchmove' : 'mousemove'; let mouseup = mobile ? 'touchend' : 'mouseup'; let currentX, currentY, previousX, previousY, vX, vY; _(container).bind(mousedown + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); if (e.target.getAttribute('id') === 'jts_picker_container_' + parsedID) { currentX = mobile ? e.touches[0].clientX : e.screenX; currentY = mobile ? e.touches[0].clientY : e.screenY; previousX = mobile ? e.touches[0].clientX : e.screenX; previousY = mobile ? e.touches[0].clientY : e.screenY; _(window).bind(mousemove + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); currentX = mobile ? e.touches[0].clientX : e.screenX; currentY = mobile ? e.touches[0].clientY : e.screenY; vX = currentX - previousX; vY = currentY - previousY; previousX = currentX; previousY = currentY; let target = document.querySelector('#jts_picker_container_' + parsedID); let x = target.offsetLeft; let y = target.offsetTop; x += vX; y += vY; target.style.left = x + 'px'; target.style.top = y + 'px'; }); _(window).bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { _(window).unbind('.jts_picker_event_' + parsedID); }); } }); _('#jts_sb_selector_' + parsedID).bind(mousedown + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); currentX = mobile ? e.touches[0].clientX : e.screenX; currentY = mobile ? e.touches[0].clientY : e.screenY; previousX = mobile ? e.touches[0].clientX : e.screenX; previousY = mobile ? e.touches[0].clientY : e.screenY; _(window).bind(mousemove + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); currentX = mobile ? e.touches[0].clientX : e.screenX; currentY = mobile ? e.touches[0].clientY : e.screenY; let localX = e.globalX, localY = e.globalY; let localParent = document.querySelector('#jts_sb_selector_' + parsedID).offsetParent; while (localParent) { localX -= localParent.offsetLeft; localY -= localParent.offsetTop; localParent = localParent.offsetParent; } vX = currentX - previousX; vY = currentY - previousY; previousX = currentX; previousY = currentY; let target = document.querySelector('#jts_sb_selector_' + parsedID); let x = target.offsetLeft; let y = target.offsetTop; x += vX; y += vY; x = localX < 0 ? 0 : (localX > SATURATION_BRIGHTNESS_SIZE ? SATURATION_BRIGHTNESS_SIZE : x); y = localY < 0 ? 0 : (localY > SATURATION_BRIGHTNESS_SIZE ? SATURATION_BRIGHTNESS_SIZE : y); x = x < 0 ? 0 : (x > SATURATION_BRIGHTNESS_SIZE ? SATURATION_BRIGHTNESS_SIZE : x); y = y < 0 ? 0 : (y > SATURATION_BRIGHTNESS_SIZE ? SATURATION_BRIGHTNESS_SIZE : y); target.style.left = x + 'px'; target.style.top = y + 'px'; let data = computeColors(x, y, document.querySelector('#jts_hue_selector_' + parsedID).offsetTop); if (configuration.update) { _(element).css('background-color', data.rgb_string); } updatePicker(data); _(element).emits(jTS.built_in_events.jCOLOR_PICKER_UPDATED , data); }); _(window).bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { _(window).unbind('.jts_picker_event_' + parsedID); }); }); _('#jts_hue_selector_' + parsedID).bind(mousedown + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); currentY = mobile ? e.touches[0].clientY : e.screenY; previousY = mobile ? e.touches[0].clientY : e.screenY; _(window).bind(mousemove + '.jts_picker_event_' + parsedID, function (e) { e.preventDefault(); currentY = mobile ? e.touches[0].clientY : e.screenY; let localY = e.globalY; let localParent = document.querySelector('#jts_hue_selector_' + parsedID).offsetParent; while (localParent) { localY -= localParent.offsetTop; localParent = localParent.offsetParent; } vY = currentY - previousY; previousY = currentY; let target = document.querySelector('#jts_hue_selector_' + parsedID); let y = target.offsetTop; y += vY; y = localY < 0 ? 0 : (localY > HUE_CONTAINER_HEIGHT ? HUE_CONTAINER_HEIGHT : y); y = y < 0 ? 0 : (y > HUE_CONTAINER_HEIGHT ? HUE_CONTAINER_HEIGHT : y); target.style.top = y + 'px'; let sb = document.querySelector('#jts_sb_selector_' + parsedID); let data = computeColors(sb.offsetLeft, sb.offsetTop, y); if (configuration.update) { _(element).css('background-color', data.rgb_string); } updatePicker(data); _(element).emits(jTS.built_in_events.jCOLOR_PICKER_UPDATED, data); }); _(window).bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { _(window).unbind('.jts_picker_event_' + parsedID); }); }); _('#jts_picker_container_' + parsedID + ' .jts_picker_shade_image').bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { let localX = e.localX, localY = e.localY; let localParent = this; while (localParent) { localX -= localParent.offsetLeft; localY -= localParent.offsetTop; localParent = localParent.offsetParent; } _('#jts_sb_selector_' + parsedID).css({ 'left': localX, 'top': localY }); let data = computeColors(localX, localY, document.querySelector('#jts_hue_selector_' + parsedID).offsetTop); if (configuration.update) { _(element).css('background-color', data.rgb_string); } updatePicker(data); _(element).emits(jTS.built_in_events.jCOLOR_PICKER_UPDATED, data); }); _('#jts_picker_container_' + parsedID + ' .jts_picker_hue_image').bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { let localY = e.localY; let localParent = this; while (localParent) { localY -= localParent.offsetTop; localParent = localParent.offsetParent; } _('#jts_hue_selector_' + parsedID).css('top', localY); let sb = document.querySelector('#jts_sb_selector_' + parsedID); let data = computeColors(sb.offsetLeft, sb.offsetTop, localY); if (configuration.update) { _(element).css('background-color', data.rgb_string); } updatePicker(data); _(element).emits(jTS.built_in_events.jCOLOR_PICKER_UPDATED , data); }); _('#jts_picker_container_' + parsedID + ' .jts_picker_submit').bind(mouseup + '.jts_picker_event_' + parsedID, function (e) { _(container).unbind('.jts_picker_event_' + parsedID); _('#jts_sb_selector_' + parsedID).unbind('.jts_picker_event_' + parsedID); _('#jts_hue_selector_' + parsedID).unbind('.jts_picker_event_' + parsedID); _('#jts_picker_container_' + parsedID + ' .jts_picker_shade_image').unbind('.jts_picker_event_' + parsedID); _('#jts_picker_container_' + parsedID + ' .jts_picker_hue_image').unbind('.jts_picker_event_' + parsedID); _('#jts_picker_container_' + parsedID + ' .jts_picker_submit').unbind('.jts_picker_event_' + parsedID); _(container).dispose(); pickerOut = false; }); } function updatePicker(data) { _('#jts_picker_container_' + parsedID + ' .jts_picker_table').css('background-color', 'hsl(' + data.hsl[0] + ', 100% , 50%)'); _('#jts_red_val_' + parsedID).html(String(data.rgb[0])); _('#jts_green_val_' + parsedID).html(String(data.rgb[1])); _('#jts_blue_val_' + parsedID).html(String(data.rgb[2])); _('#jts_exadecimal_val_' + parsedID).html(data.hexadecimal); _('#jts_picker_container_' + parsedID + ' .jts_picker_next_color').css('background-color', data.rgb_string); } } function parseRGBColor(e) { let style = getComputedStyle(e); let color = style.getPropertyValue("background-color"); color = color.indexOf('rgba') !== -1 ? 'rgb(255,0,0)' : color; let rgbPrefixLength = 4; let subString = color.substring(rgbPrefixLength, color.length - 1); let array = subString.split(','); return parse(array, 0); function parse(a, i) { if (i < a.length) { a[i] = parseInt(a[i]); return parse(a, i + 1); } else { return a; } } } function rGBtoHSB(rgb) { let hue = 0; let saturation = 0; let brightness = 0; /*Convert the RGB values to the range 0-1, this can be done by dividing the value by 255 for 8-bit color depth*/ let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; /*Find the minimum and maximum values of R, G and B. e delta*/ let valoreMassimo = Math.max(r, g); valoreMassimo = Math.max(valoreMassimo, b); let valoreMinimo = Math.min(r, g); valoreMinimo = Math.min(valoreMinimo, b); let delta = valoreMassimo - valoreMinimo; /*Now calculate the Luminace*/ brightness = Math.round(valoreMassimo * 100); /*The next step is to find the saturation and hue se delta != 0*/ if (delta !== 0) { /*trova saturazione*/ saturation = Math.round(delta / valoreMassimo * 100); /*calcolo hue*/ let deltaH = delta / 2; let deltaR = ((valoreMassimo - r) / 6) + deltaH; deltaR /= delta; let deltaG = ((valoreMassimo - g) / 6) + deltaH; deltaG /= delta; let deltaB = ((valoreMassimo - b) / 6) + deltaH; deltaB /= delta; /*The Hue formula is depending on what RGB color channel is the max value.*/ if (valoreMassimo === r) { hue = deltaB - deltaG; } else if (valoreMassimo === g) { hue = (1 / 3) + deltaR - deltaB; } else if (valoreMassimo === b) { hue = (2 / 3) + deltaG - deltaR; } if (hue < 0) { hue += 1; } if (hue > 1) { hue -= 1; } hue *= 360; hue = Math.round(hue); } return [hue, saturation, brightness]; } function rGBtoEXADECIMAL(rgb) { let value = ''; for (let i = 0; i < rgb.length; i++) { let hex = rgb[i].toString(16); hex = hex.length === 1 ? '0' + hex : hex; value += hex; } return value; } function rGBtoHSL(rgb) { /*Convert the RGB values to the range 0-1, this can be done by dividing the value by 255 for 8-bit color depth*/ let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; /*Find the minimum and maximum values of R, G and B.*/ let valoreMassimo = Math.max(r, g); valoreMassimo = Math.max(valoreMassimo, b); let valoreMinimo = Math.min(r, g); valoreMinimo = Math.min(valoreMinimo, b); /*Now calculate the Luminace value by adding the max and min values anddivide by 2.*/ let luminance = (valoreMinimo + valoreMassimo) / 2; let luminanceRow = luminance; luminance = Math.round(luminance * 100); /*The next step is to find the Saturation. If Luminance is smaller then 0.5, then Saturation = (max-min)/(max+min) If Luminance is bigger then 0.5. then Saturation = ( max-min)/(2.0-max-min)*/ let saturation = 0; if (luminance >= 0.5) { saturation = (valoreMassimo - valoreMinimo) / (2.0 - valoreMassimo + valoreMinimo); } else { saturation = (valoreMassimo - valoreMinimo) / (valoreMassimo + valoreMinimo); } saturation = Math.round(saturation * 100); /*The next step is to find the hue. The Hue formula is depending on what RGB color channel is the max value. If Red is max, then Hue = (G-B)/(max-min) If Green is max, then Hue = 2.0 + (B-R)/(max-min) If Blue is max, then Hue = 4.0 + (R-G)/(max-min)*/ let hue = 0; if (valoreMassimo === r) { hue = (g - b) / (valoreMassimo - valoreMinimo); } else if (valoreMassimo === g) { hue = 2.0 + (b - r) / (valoreMassimo - valoreMinimo); } else if (valoreMassimo === b) { hue = 4.0 + (r - g) / (valoreMassimo - valoreMinimo); } /*The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle If Hue becomes negative you need to add 360 to, because a circle has 360 degrees.*/ hue = Math.round(hue * 60); if (hue < 0) { hue += 360; } return [Math.round(hue), Math.round(saturation), Math.round(luminance)]; } function hSBtoRGB(hsb) { let r = 0; let g = 0; let bRGB = 0; let h = (hsb[0] / 360); let s = (hsb[1] / 100); let b = (hsb[2] / 100); let i = Math.floor(h * 6); let f = h * 6 - i; let p = b * (1 - s); let q = b * (1 - f * s); let t = b * (1 - (1 - f) * s); let _r, _g, _b; switch (i % 6) { case 0: _r = b; _g = t; _b = p; break; case 1: _r = q; _g = b; _b = p; break; case 2: _r = p; _g = b; _b = t; break; case 3: _r = p; _g = q; _b = b; break; case 4: _r = t; _g = p; _b = b; break; case 5: _r = b; _g = p; _b = q; break; } _r = Math.floor(_r * 255); _g = Math.floor(_g * 255); _b = Math.floor(_b * 255); r = _r; g = _g; bRGB = _b; return [r, g, bRGB]; } function computeColors(sbX, sbY, hueY) { let h = hueY * (HUE_RANGE / HUE_CONTAINER_HEIGHT); h = HUE_RANGE + (-h); let s = sbX * (100 / SATURATION_BRIGHTNESS_SIZE); let b = sbY * (100 / SATURATION_BRIGHTNESS_SIZE); b = 100 + (-b); let hsb = [h, s, b]; let rgb = hSBtoRGB(hsb); let hsl = rGBtoHSL(rgb); let hexadecimal = rGBtoEXADECIMAL(rgb); let rgbString = "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")"; let hslString = "hsl(" + hsl[0] + "," + hsl[1] + "%," + hsl[2] + "%)"; return { 'hsb': hsb, 'hsl': hsl, 'rgb': rgb, 'hexadecimal': hexadecimal, 'hsl_string': hslString, 'rgb_string': rgbString }; } return this; }; /** * * @param file {File} * @param callback {Function} * @param configuration {Object} * @return {jTS} */ jTS.fn.cropper = /*jTS*/function (/*File*/file ,/*Function*/callback ,/*Object literal*/configuration) { const t = this; let BYTES_SIZE = 1024 * 1024 * 10; let BORDER_VX = 350; if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') { console.log('accepts-only-.jpg-.png-.gif-files @jTSCropper'); return; } if (file.size > BYTES_SIZE) { console.log('max-size-allowed-10MB @jTSCropper'); return; } let onMobile = jTS.jMobile(); let cropperID = new Date().getTime() + "" + Math.floor(Math.random() * 500); let mousedown = onMobile ? 'touchstart' : 'mousedown'; let mousemove = onMobile ? 'touchmove' : 'mousemove'; let mouseup = onMobile ? 'touchend' : 'mouseup'; let originalWidth; let originalHeight; let originalBlobSrc; let type; let name; let extension; let image; let currentWidth; let currentHeight; let imageWidth; let imageHeight; let base; let cropBase; let croppedImage; let cropSpot; let cropBorder; let controls; let doneB; let closeB; let resetB; let sizeLabel; let cropperHandlesArray = []; let reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = function () { let blob = new Blob([reader.result]); let src = window.URL.createObjectURL(blob); type = file.type; originalBlobSrc = src; name = file.name.split('.')[0]; extension = '.' + file.name.split('.')[1]; setImage(); }; function addCropper() { let offsetParent = document.querySelector('body'); base = document.createElement('div'); cropBase = document.createElement('div'); cropSpot = document.createElement('div'); cropBorder = document.createElement('div'); controls = document.createElement('div'); doneB = document.createElement('div'); closeB = document.createElement('div'); resetB = document.createElement('div'); sizeLabel = document.createElement('div'); croppedImage = new Image(); croppedImage.alt = 'jts_cropper_img'; croppedImage.src = image.src; _(base).css({ 'position': 'fixed', 'left': 0, 'top': 0, 'z-index': 100, 'background-color': 'rgba(255,255,225,0)' }).addClass('jts_cropper_' + cropperID).attr('id', 'jts_cropper_base_' + cropperID); _(cropBase).css({ 'position': 'absolute', 'left': 0, 'top': 0, 'z-index': 100, 'background-color': configuration && configuration.overflow_background ? configuration.overflow_background : 'rgba(255,0,0,0.6)' }).addClass('jts_cropper_' + cropperID); _(croppedImage).css({ 'position': 'absolute' }).addClass('jts_cropper_' + cropperID); _(cropSpot).css({ 'position': 'absolute', 'overflow': 'hidden', 'z-index': 105, 'background-color': configuration && configuration.crop_background ? configuration.crop_background : '#ffffff' }).addClass('jts_cropper_' + cropperID); _(cropBorder).css({ 'position': 'absolute', 'z-index': 110 }).addClass('jts_cropper_' + cropperID).addClass('jts_cropper_border_' + cropperID); _(controls).css({ 'position': 'absolute', 'z-index': 150, 'height': 50, 'bottom': 50, 'width': 190, 'overflow': 'visible', 'left': 'calc(50% - 95px)' }).addClass('jts_cropper_' + cropperID); _(resetB).css({ 'left': 0, 'background-color' : configuration && configuration.controls_background ? configuration.controls_background : 'rgba(255,255,255,0.5)', 'color' : configuration && configuration.controls_color ? configuration.controls_color : '#303030', 'box-shadow' : configuration && configuration.controls_shadow ? configuration.controls_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'border-radius' : configuration && configuration.controls_radius ? configuration.controls_radius : 3 }).addClass('jts-crop-control').append('<i class="fab fa-rev"></i>'); _(doneB).css({ 'left': 70, 'background-color' : configuration && configuration.controls_background ? configuration.controls_background : 'rgba(255,255,255,0.5)', 'color' : configuration && configuration.controls_color ? configuration.controls_color : '#303030', 'box-shadow' : configuration && configuration.controls_shadow ? configuration.controls_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'border-radius' : configuration && configuration.controls_radius ? configuration.controls_radius : 3 }).addClass('jts-crop-control').append('<i class="fa fa-check-double"></i>'); _(closeB).css({ 'left': 140, 'background-color' : configuration && configuration.controls_background ? configuration.controls_background : 'rgba(255,255,255,0.5)', 'color' : configuration && configuration.controls_color ? configuration.controls_color : '#303030', 'box-shadow' : configuration && configuration.controls_shadow ? configuration.controls_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'border-radius' : configuration && configuration.controls_radius ? configuration.controls_radius : 3 }).addClass('jts-crop-control').append('<i class="fa fa-times-circle"></i>'); _(sizeLabel).css({ 'position' : 'absolute', 'top' : -87, 'left' : 'calc(50% - 75px)', 'border-radius': 3, 'color' : '#f1f1f1', 'background-color' : '#000000', 'padding' : 10, 'font-size' : 15, 'box-shadow' : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'font-family' : 'Helvetica', 'width': 150, 'text-align':'center' }).addClass('jts-crop-size-label'); let borderColor = configuration && configuration.border_color ? configuration.border_color : '#ffffff' let style = '<style type="text/css" id="cropper_style_' + cropperID + '">' + '.jts_cropper_border_' + cropperID + '::before{' + 'width:100%;height:100%;z-index:3;content:"";' + 'position:absolute;left:0;top:0;' + 'background-image : linear-gradient(90deg , ' + borderColor + ' , ' + borderColor + ' 50% , transparent 50% , transparent) , ' + 'linear-gradient(90deg , ' + borderColor + ' , ' + borderColor + ' 50% , transparent 50% , transparent); ' + 'background-position : top left , bottom right; ' + 'background-size : 50px 1px , 50px 1px;' + 'background-repeat : repeat-x , repeat-x;' + 'animation-delay:0s; animation-direction:normal;' + 'animation-iteration-count:infinite;animation-timing-function:linear;' + 'animation-fill-mode:initial;animation-name:cropper-border-tb;' + '}' + '@keyframes cropper-border-tb{100%{background-position:top right , bottom left;}}' + '.jts_cropper_border_' + cropperID + '::after{' + 'width:100%;height:100%;z-index:3;content:"";' + 'position:absolute;left:0;top:0;' + 'background-image : linear-gradient(transparent , transparent 50% , ' + borderColor + ' 50% , ' + borderColor + ' ) , ' + 'linear-gradient(transparent , transparent 50% , ' + borderColor + ' 50% , ' + borderColor + ' );' + 'background-position : top right , bottom left; ' + 'background-size : 1px 50px , 1px 50px;' + 'background-repeat : repeat-y , repeat-y;' + 'animation-delay:0s; animation-direction:normal;' + 'animation-iteration-count:infinite;animation-timing-function:linear;' + 'animation-fill-mode:initial;animation-name:cropper-border-lr;' + '}' + '@keyframes cropper-border-lr{100%{background-position:bottom right , top left;}}' + '.jts-crop-size-label::after{content:"";position: absolute; top : 100%; left: calc(50% - 15px);border:solid 15px transparent;border-top-color:#000000 ;}' + '</style>'; let styleBA = '<style type="text/css" id="cropper_style_ba_' + cropperID + '">' + '.jts_cropper_border_' + cropperID + '::before{animation-duration:' + Math.floor((imageWidth / BORDER_VX) * 100) / 100 + 's;}' + '.jts_cropper_border_' + cropperID + '::after{animation-duration:' + Math.floor((imageHeight / BORDER_VX) * 100) / 100 + 's;}' + '</style>'; _('head').append([style, styleBA]); _(cropSpot).append(croppedImage); _(controls).append([doneB, resetB, closeB]); _(cropBorder).append(sizeLabel); _(base).append([image, cropBase, cropSpot, cropBorder, controls]); _(offsetParent).append(base); _('.jts-crop-control').css({ 'position': 'absolute', 'width': 50, 'height': 50, 'top': 0, 'cursor': 'pointer', 'font-size' : 40, 'padding' : '3px 0px 0px 0px', 'text-align' : 'center' }); setSize(); addLiquidFunctions(); setListeners(); } function addLiquidFunctions() { let MINIMUM_SIZE = 100; let nameSet = ['lh', 'th', 'rh', 'bh', 'tlh', 'trh', 'blh', 'brh', 'mover']; let cssSet = [ { 'width': 30, 'height': 30, 'left': -15, 'top': 'calc(50% - 15px)', 'cursor': 'ew-resize' }, { 'width': 30, 'height': 30, 'left': 'calc(50% - 15px)', 'top': -15, 'cursor': 'ns-resize' }, { 'width': 30, 'height': 30, 'right': -15, 'top': 'calc(50% - 15px)', 'cursor': 'ew-resize' }, { 'width': 30, 'height': 30, 'left': 'calc(50% - 15px)', 'bottom': -15, 'cursor': 'ns-resize' }, { 'width': 30, 'height': 30, 'left': -15, 'top': -15, 'cursor': 'nw-resize' }, { 'width': 30, 'height': 30, 'right': -15, 'top': -15, 'cursor': 'ne-resize' }, { 'width': 30, 'height': 30, 'left': -15, 'bottom': -15, 'cursor': 'sw-resize' }, { 'width': 30, 'height': 30, 'right': -15, 'bottom': -15, 'cursor': 'se-resize' }, { 'width': 50, 'height': 50, 'left': 'calc(50% - 25px)', 'top': 'calc(50% - 25px)', 'cursor': 'move' } ]; createHandles(0); function createHandles(index) { if (index < nameSet.length) { let handle = document.createElement('div'); let css = { 'background-color': configuration && configuration.handles_color ? configuration.handles_color : 'rgba(255,255,255,0.5)', 'position': 'absolute', 'z-index': 10 }; handle.setAttribute('name', nameSet[index]); handle.setAttribute('class', 'jts_cropper_handle_' + cropperID); _(handle).css(css).css(cssSet[index]); _(cropBorder).append(handle); cropperHandlesArray.push(handle); createHandles(index + 1); } } let cX, cY, pX, pY, vX, vY, handle; _('.jts_cropper_handle_' + cropperID).bind(mousedown + '.jts_cropper_handle_liquid_' + cropperID, function (e) { e.preventDefault(); pX = onMobile ? e.originalEvent.touches[0].clientX : e.originalEvent.clientX; pY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; handle = _(e.target).attr('name'); _(window).bind(mousemove + '.jts_cropper_handle_liquid_' + cropperID , function (e) { cX = onMobile ? e.originalEvent.touches[0].clientX : e.originalEvent.clientX; cY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; vX = cX - pX; vY = cY - pY; pX = cX; pY = cY; switch (handle) { case 'lh': vX = -vX; vY = 0; break; case 'th': vX = 0; vY = -vY; break; case 'rh': vY = 0; break; case 'bh': vX = 0; break; case 'tlh': vX = -vX; vY = -vY; break; case 'trh': vY = -vY; break; case 'blh': vX = -vX; break; case 'brh': break; case 'mover': break; } liquidResize(vX, vY, e); }).bind(mouseup + '.jts_cropper_handle_liquid_' + cropperID , function (e) { _(window).unbind('.jts_cropper_handle_liquid_' + cropperID); }); }); function liquidResize(vX, vY, e) { let w = _(cropBorder).outerWidth(); let h = _(cropBorder).outerHeight(); let left = cropBorder.offsetLeft; let top = cropBorder.offsetTop; let x = left; let y = top; if (handle !== 'mover') { if ((e.ctrlKey && e.shiftKey) && (handle === 'trh' || handle === 'tlh' || handle === 'brh' || handle === 'blh')) { if (Math.abs(vX) > Math.abs(vY)) { vY = vX; } else { vX = vY; } } let right = left + w; let bottom = top + h; if (w + vX < MINIMUM_SIZE) { w = MINIMUM_SIZE; } else if (right + vX > image.offsetLeft + _(image).outerWidth() && (handle === 'rh' || handle === 'trh' || handle === 'brh')) { w = (image.offsetLeft + _(image).outerWidth()) - left; } else if (left + -vX < image.offsetLeft && (handle === 'lh' || handle === 'tlh' || handle === 'blh')) { w = right - image.offsetLeft; } else { w += vX; } if (h + vY < MINIMUM_SIZE) { h = MINIMUM_SIZE; } else if (bottom + vY > image.offsetTop + _(image).outerHeight() && (handle === 'blh' || handle === 'bh' || handle === 'brh')) { h = (image.offsetTop + _(image).outerHeight()) - top; } else if (top + -vY < image.offsetTop && (handle === 'th' || handle === 'tlh' || handle === 'trh')) { h = bottom - image.offsetTop; } else { h += vY; } switch (handle) { case 'lh': x = right - w; break; case 'th': y = bottom - h; break; case 'tlh': x = right - w; y = bottom - h; break; case 'trh': y = bottom - h; break; case 'blh': x = right - w; break; } } else { x += vX; y += vY; checkBorder(); } let css = { 'width': w, 'height': h, 'left': x, 'top': y }; _(cropBorder).css(css); synchronizes(); function synchronizes() { _(cropSpot).css({ 'width': _(cropBorder).outerWidth(), 'height': _(cropBorder).outerHeight(), 'left': cropBorder.offsetLeft, 'top': cropBorder.offsetTop }); _(croppedImage).css({ 'left': image.offsetLeft - cropSpot.offsetLeft, 'top': image.offsetTop - cropSpot.offsetTop }); _(sizeLabel).html('<span>width : ' + w + 'px</span><br><span>height : ' + h + 'px</span>'); let styleBA = '.jts_cropper_border_' + cropperID + '::before{animation-duration:' + Math.floor((w / BORDER_VX) * 100) / 100 + 's;}' + '.jts_cropper_border_' + cropperID + '::after{animation-duration:' + Math.floor((h / BORDER_VX) * 100) / 100 + 's;}'; _('#cropper_style_ba_' + cropperID).html(styleBA); } function checkBorder() { if (x < image.offsetLeft) { x = image.offsetLeft; } if (y < image.offsetTop) { y = image.offsetTop; } if (x + _(cropBorder).outerWidth() > image.offsetLeft + _(image).outerWidth()) { x = (image.offsetLeft + _(image).outerWidth()) - _(cropBorder).outerWidth(); } if (y + _(cropBorder).outerHeight() > image.offsetTop + _(image).outerHeight()) { y = (image.offsetTop + _(image).outerHeight()) - _(cropBorder).outerHeight(); } } } } function croppingDone(){ let cropX = cropBorder.offsetLeft - image.offsetLeft; let cropY = cropBorder.offsetTop - image.offsetTop; let cropW = _(cropBorder).outerWidth(); let cropH = _(cropBorder).outerHeight(); let parsedCX = Math.round(cropX * (originalWidth / imageWidth)); let parsedCY = Math.round(cropY * (originalHeight / imageHeight)); let parsedCW = Math.round(cropW * (originalWidth / imageWidth)); let parsedCH = Math.round(cropH * (originalHeight / imageHeight)); let canvas = document.createElement('canvas'); canvas.width = parsedCW; canvas.height = parsedCH; let brush = canvas.getContext('2d'); brush.drawImage(image, parsedCX, parsedCY, parsedCW, parsedCH, 0, 0, canvas.width, canvas.height); let src = canvas.toDataURL(type, 1.0); let r = new XMLHttpRequest(); r.open('get', src); r.responseType = 'arraybuffer'; r.onreadystatechange = function () { if (r.readyState === 4) { if (r.status === 200) { let blob = new Blob([r.response], { 'type': type }); let blobSRC = URL.createObjectURL(blob); let croppedImage = new Image(); blob.lastModified = new Date().getTime(); blob.lastModifiedDate = new Date(); blob.name = name + extension; croppedImage.alt = 'jts_cropped_image'; croppedImage.src = blobSRC; let data = { 'image_original_width': originalWidth, 'image_original_height': originalHeight, 'image_original': image, 'image_cropped': croppedImage, 'file_original': file, 'file_cropped': blob, 'type': type, 'src_original': originalBlobSrc, 'src_crop': blobSRC, 'crop_x': parsedCX, 'crop_y': parsedCY, 'crop_width': parsedCW, 'crop_height': parsedCH, 'extension': extension, 'file_name': name }; if (callback) { callback(data); } _(window).emits(jTS.built_in_events.jCROPPER_DONE, data); dispose(); } else { console.log('unknown-error @jTSCropper'); dispose(); } } }; r.send(null); } function dispose() { _(window).unbind('.jts_cropper_events_' + cropperID); _(resetB).unbind('.jts_cropper_events_' + cropperID); _(closeB).unbind('.jts_cropper_events_' + cropperID); _(doneB).unbind('.jts_cropper_events_' + cropperID); _(cropperHandlesArray).unbind('.jts_cropper_handle_liquid_' + cropperID); _('#cropper_style_ba_' + cropperID).dispose(); _('#cropper_style_' + cropperID).dispose(); if (_(base).offsetPs().length > 0) { _(base).dispose(); } } function findSize() { let SIZE_GAP = 60; currentWidth = _(window).outerWidth(); currentHeight = _(window).outerHeight(); let data = getData(currentWidth - SIZE_GAP, currentHeight - SIZE_GAP); imageWidth = Math.round(data.width); imageHeight = Math.round(data.height); function getData(w, h) { if (w > originalWidth) { w = originalWidth; } if (h > originalHeight) { h = originalHeight; } let width, height; let data = {}; if (originalWidth > originalHeight) { parseW(w); } else { parseH(h); } function parseW(w) { width = w; height = originalHeight * (width / originalWidth); if (height > currentHeight - SIZE_GAP) { parseW(w - 1); } } function parseH(h) { height = h; width = originalWidth * (height / originalHeight); if (width > currentWidth - SIZE_GAP) { parseH(h - 1); } } data.width = width; data.height = height; return data; } } function getRootN() { let e_parent = base; let r_parent = e_parent; while (e_parent) { e_parent = _(e_parent).offsetPs()[0]; if (e_parent) { r_parent = e_parent; } } if (r_parent.nodeName.toLowerCase() !== '#document') { dispose(); return false; } else { return true; } } function setImage() { image = new Image(); image.alt = 'jts_cropper_img'; image.onload = function () { originalWidth = this.naturalWidth || this.width; originalHeight = this.naturalHeight || this.height; _(window).bind('resize.jts_cropper_events_' + cropperID , function () { if (!getRootN()) { return; } findSize(); setSize(); }); _(window).bind('click.jts_cropper_events_' + cropperID, function () { if (!getRootN()) { return; } }); findSize(); addCropper(); }; image.src = originalBlobSrc; _(image).css('position', 'absolute').addClass('jts_cropper_' + cropperID); } function setListeners() { _(resetB).bind(mouseup + '.jts_cropper_events_' + cropperID , function (e) { findSize(); setSize(); }); _(closeB).bind(mouseup + '.jts_cropper_events_' + cropperID , function (e) { dispose(); _(window).emits(jTS.built_in_events.jCROPPER_ONLY_CLOSED); }); _(doneB).bind(mouseup + '.jts_cropper_events_' + cropperID, function (e) { croppingDone(); }); } function setSize() { _(base).css({ 'width': currentWidth, 'height': currentHeight }); _(image).css({ 'width': imageWidth, 'height': imageHeight, 'left': Math.round((currentWidth * 0.5) - (imageWidth * 0.5)), 'top': Math.round((currentHeight * 0.5) - (imageHeight * 0.5)) }); _(cropBase).css({ 'width': currentWidth, 'height': currentHeight }); _(cropSpot).css({ 'width': imageWidth, 'height': imageHeight, 'left': Math.round((currentWidth * 0.5) - (imageWidth * 0.5)), 'top': Math.round((currentHeight * 0.5) - (imageHeight * 0.5)) }); _(croppedImage).css({ 'width': imageWidth, 'height': imageHeight, 'left': image.offsetLeft - cropSpot.offsetLeft, 'top': image.offsetTop - cropSpot.offsetTop }); _(cropBorder).css({ 'width': imageWidth, 'height': imageHeight, 'left': Math.round((currentWidth * 0.5) - (imageWidth * 0.5)), 'top': Math.round((currentHeight * 0.5) - (imageHeight * 0.5)) }); _(sizeLabel).html('<span>width : ' + parseInt(imageWidth) + 'px</span><br><span>height : ' + parseInt(imageHeight) + 'px</span>'); let styleBA = '.jts_cropper_border_' + cropperID + '::before{animation-duration:' + Math.floor((imageWidth / BORDER_VX) * 100) / 100 + 's;}' + '.jts_cropper_border_' + cropperID + '::after{animation-duration:' + Math.floor((imageHeight / BORDER_VX) * 100) / 100 + 's;}'; _('#cropper_style_ba_' + cropperID).html(styleBA); } return this; }; /** * * @param configuration {Object} * @return {jTS} */ jTS.fn.datePicker = /*jTS*/function(/*Object literal*/ configuration){ let Y_GAP = 5; let MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"]; let WEEK_DAYS = ['Su','Mo','Tu','We','Th','Fr','Sa']; let DATE_FORMAT = configuration && configuration.format ? configuration.format : 'd/m/y'; let PRESS_DELAY = 150; addStyles(); this.each(function(i,e){ addDatePickerFeatures(i,e); }); function addDatePickerFeatures(i,e) { let pickerOpen = false; let element = e; let jElement = _(e); let mousePressed = false; let pressID = null; jElement.bind('keydown keyup.jts_date_picker_events',function(e){ e.preventDefault(); }); jElement.bind('click.jts_date_picker_events',showPicker); function showPicker(e){ e.preventDefault(); if(!pickerOpen){ pickerOpen = true; openPicker(); } } function openPicker(){ let currentDate = null; let currentMonth = null; let currentYear = null; let currentDay = null; let pickerBox = _('<div class="date_picker_box"></div>'); let previousButton = _('<div class="dp_previous_button dp_top_button"><i class="fa fa-caret-square-left"></i></div>'); let nextButton = _('<div class="dp_next_button dp_top_button"><i class="fa fa-caret-square-right"></i></div>'); let monthYearTop = _('<div class="dp_top_month_year ts-font-elegance"></div>'); let monthDaysBox = _('<div class="dp_month_days_box"></div>'); let currentShowedDays = []; setMainBoard(); setCoordinates(); if(configuration && configuration.onBeforePicker){ configuration.onBeforePicker(pickerBox); } _('body').append(pickerBox); setCurrentData(); setListeners(); function activateShowedDays(){ currentShowedDays.forEach(function(e){ e.bind('click.jts_ts_date_picker_events',function(e){ let date = _(this).attr('data-date_ref'); jElement.value(date); disposePicker(); }); }); } function deactivateShowedDays(){ currentShowedDays.forEach(function(e){ e.unbind('click'); }); } function disposePicker(){ pickerBox.unbind('mousedown mouseup'); previousButton.unbind('click'); nextButton.unbind('click'); jElement.unbind('focusout.jts_date_picker_events'); deactivateShowedDays(); pickerBox.hide(300,{ 'method' : 'fade', 'endCB' : function(){ pickerBox.dispose(); pickerOpen = false; } }); } function getCoordinates(){ let parent = element; let x = 0; let y = 0; while(parent){ x += parent.offsetLeft; y += parent.offsetTop; parent= parent.offsetParent; } return {'x':x,'y':y}; } function getFormattedDate(currentDayDate){ let currentDayString = ""; let isTheSameDate = false; if(DATE_FORMAT === 'd/m/y'){ currentDayString = currentDayDate.getDate() + "/" + (currentDayDate.getMonth() + 1) + "/" + currentDayDate.getFullYear(); if(currentDayString === currentDate.getDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear()) { isTheSameDate = true; } } else if(DATE_FORMAT === 'y/m/d'){ currentDayString = currentDayDate.getFullYear() + "/" + (currentDayDate.getMonth() + 1) + "/" + currentDayDate.getDate(); if(currentDayString === currentDate.getFullYear() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getDate()) { isTheSameDate = true; } } return {'currentDayDateString' : currentDayString , 'isTheSameDate' : isTheSameDate}; } function getNextMonth(){ currentMonth = currentMonth + 1 === 12 ? 0 : currentMonth + 1; currentYear = currentMonth === 0 ? currentYear + 1 : currentYear; setHeaderText(); deactivateShowedDays(); setMonthDays(); } function getPreviousMonth(){ currentMonth = currentMonth - 1 === -1 ? 11 : currentMonth - 1; currentYear = currentMonth === 11 ? currentYear -1 : currentYear; setHeaderText(); deactivateShowedDays(); setMonthDays(); } function pressPreviousMonth() { if(mousePressed){ getPreviousMonth(); pressID = setTimeout(pressPreviousMonth,PRESS_DELAY); } } function pressNextMonth() { if(mousePressed){ getNextMonth(); pressID = setTimeout(pressNextMonth,PRESS_DELAY); } } function setCoordinates(){ let coordinates = getCoordinates(); pickerBox.css({'top':coordinates.y + jElement.outerHeight() + Y_GAP,'left':coordinates.x}); } function setCurrentData(){ let data = jElement.value(); if(data !== ""){ data = data.split("/"); if(DATE_FORMAT === 'd/m/y'){ currentDate = new Date(parseInt(data[2]),parseInt(data[1] - 1),parseInt(data[0])); } else if(DATE_FORMAT === 'y/m/d'){ currentDate = new Date(parseInt(data[0]),parseInt(data[1] - 1),parseInt(data[2])); } } else{ currentDate = new Date(); } currentMonth = currentDate.getMonth(); currentYear = currentDate.getFullYear(); currentDay = currentDate.getDate(); setHeaderText(); setMonthDays(); } function setHeaderText(){ monthYearTop.html(MONTHS[currentMonth].toUpperCase() + ' ' + currentYear); } function setListeners(){ pickerBox.bind('mousedown mouseup.jts_date_picker_events',function(e){ e.preventDefault(); }); previousButton.bind('click.jts_date_picker_events',function(e){ getPreviousMonth(); }); nextButton.bind('click.jts_date_picker_events',function(e){ getNextMonth(); }); previousButton.mouseDown('jts_date_picker_events',(e) => { mousePressed = true; pressID = setTimeout(pressPreviousMonth,PRESS_DELAY); }); nextButton.mouseDown('jts_date_picker_events',(e) => { mousePressed = true; pressID = setTimeout(pressNextMonth,PRESS_DELAY); }); previousButton.mouseUp('jts_date_picker_events',(e) => { mousePressed = false; clearTimeout(pressID); }); nextButton.mouseUp('jts_date_picker_events',(e) => { mousePressed = false; clearTimeout(pressID); }); jElement.bind('focusout.jts_date_picker_events',function(e){ disposePicker(); }); } function setMainBoard(){ let pickerHeader = _('<div class="date_picker_header"></div>'); let weekDaysRow = _('<div class="dp_week_days_row"></div>'); for(let i = 0; i < WEEK_DAYS.length; i++){ let weekDayTh = _('<div class="dp_week_day_th ts-font-elegance">' + WEEK_DAYS[i] + '</div>'); if(configuration && configuration.onBeforeWeekDays){ configuration.onBeforeWeekDays(weekDayTh); } weekDaysRow.append(weekDayTh); } if(configuration && configuration.onBeforeInterface){ configuration.onBeforeInterface(pickerHeader,previousButton,monthYearTop,nextButton); } pickerHeader.append(previousButton).append(monthYearTop).append(nextButton); pickerBox.append(pickerHeader).append(weekDaysRow).append(monthDaysBox); } function setMonthDays(){ monthDaysBox.html(''); currentShowedDays = []; let daysInCurrentMonth = new Date(currentYear,currentMonth + 1,0).getDate(); let startGap = new Date(currentYear,currentMonth,1).getDay(); for(let i = 0; i < startGap; i++){ let fakeDay = _('<div class="dp_fake_day"></div>'); monthDaysBox.append(fakeDay); } for(let l = 0; l < daysInCurrentMonth; l++){ let currentDayDate = new Date(currentYear,currentMonth,(l + 1)); let formattedData = getFormattedDate(currentDayDate); let realDay = _('<div class="dp_real_day"></div>'); let dayInner = _('<div class="dp_inner_day ts-font-elegance" data-date_ref="' + formattedData.currentDayDateString + '">' + (l + 1) + '</div>'); if(formattedData.isTheSameDate){ dayInner.addClass("dp_current_highlighted_day"); } if(configuration && configuration.onShowDay){ configuration.onShowDay(currentDayDate,dayInner,realDay); } realDay.append(dayInner); monthDaysBox.append(realDay); currentShowedDays.push(dayInner); } activateShowedDays(); } } } function addStyles(){ let pickerStyle = '<style type="text/css" id="date_picker_style">' + '.date_picker_box{position: absolute;width: 300px;height: 300px;border-radius: 5px;' + 'z-index: 1;background-color: #ffffff;border: solid 1px #b2b2b2;box-shadow: 3px 3px 5px 0 rgba(0, 0, 0, 0.3);' + 'padding: 5px;}.date_picker_header {position: relative;width: 100%;height: 50px;border-radius: 5px;' + 'background-color: #e5e5e5;}.dp_top_button {position: relative;width: 50px;height: 100%;font-size: 40px;' + 'color: #f1f1f1;cursor: pointer;padding: 3px 5px;float: left;}.dp_top_month_year {position: relative;' + 'height: 100%;width: calc(100% - 100px);color: #fbfbfb;text-align: center;font-size: 21px;font-weight: 700;' + 'float: left;padding: 15px 0 0 0;}.dp_week_days_row {width: 100%;height: 30px;position: relative;' + 'margin: 5px 0;}.dp_week_day_th {position: relative;float: left;height: 100%;width: calc(100% / 7);' + 'text-align: center;padding: 3px;font-size: 18px;font-weight: 600;}' + '.dp_month_days_box {position: relative;width: 100%;height: 200px;}.dp_fake_day, .dp_real_day {' + 'position: relative;float: left;width: calc(100% / 7);height: 33px;padding: 2px;}' + '.dp_inner_day {position: relative;height: 100%;width: 100%;font-size: 15px;font-weight: 600;' + 'color: #a1a1a1;padding: 3px;border-radius: 3px;border: solid 1px #b2b2b2;cursor: pointer;' + 'background-color: #f1f1f1;}.dp_inner_day:hover {background-color: #63dbff;color: #ffffff;}' + '.dp_current_highlighted_day {background-color: #63dbff;color: #ffffff;}.dp_disabled {' + 'pointer-events: none;opacity: 0.2 !important;cursor: initial !important;background-color: #f1f1f1 !important;' + 'color: #a1a1a1 !important;border: solid 1px #b2b2b2 !important;}' + '</style>'; _('head').append(pickerStyle); } return this; }; /** * * @param itemsToShow {int} * @param configuration {Object} * @return {jTS} */ jTS.fn.pagination = /*jTS*/function(/*Int*/itemsToShow,/*Object literal*/configuration){ let t = this; if(t.length === 0){ return this } let pageSize = itemsToShow; let container = t.offsetPs(); let interfaceContainer = configuration && configuration.interfaceParent ? _(configuration.interfaceParent) : container; let pages = Math.ceil(t.length / pageSize); let startIndex = 0; let pageIndex = 0; let interfaceBox = null; addStyles(); displayItems(); addInterface(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); _(window).on(jTS.built_in_events.jPAGINATION_UPDATE_ITEMS,updateItemsToShow); _(window).on(jTS.built_in_events.jPAGINATION_FILTER_SORT_ITEMS,filterSortItems); function addInterface(){ let interfaceBoxClass = configuration && configuration.interface_box_class ? configuration.interface_box_class : ""; let previousNextButtonClass = configuration && configuration.previous_next_page_class ? configuration.previous_next_page_class : ""; let pageButtonClass = configuration && configuration.page_button_class ? configuration.page_button_class : ""; let previousLabel = configuration && configuration.previous_label ? configuration.previous_label : "PREVIOUS"; let nextLabel = configuration && configuration.next_label ? configuration.next_label : "NEXT"; interfaceBox = _('<div class="jts_pagination_interface_box_class ' + interfaceBoxClass + '"></div>'); let previousButton = _('<div class="jts_pagination_previous_next_button_class ' + previousNextButtonClass + '" id="jts_pagination_previous_button">' + previousLabel + '</div>'); let nextButton = _('<div class="jts_pagination_previous_next_button_class ' + previousNextButtonClass + '" id="jts_pagination_next_button">' + nextLabel + '</div>'); interfaceBox.append(previousButton); for(let i = 0; i < pages ; i++){ interfaceBox.append('<div class="jts_pagination_page_button ' + pageButtonClass + '" data-index_ref="' + i + '">' + (i + 1) + '</div>'); } interfaceBox.append(nextButton); interfaceContainer.append(interfaceBox); addListeners(); } function addListeners() { _('#jts_pagination_previous_button').bind('click.jts_pagination_events',function(e){ goToPreviousPage(); }); _('#jts_pagination_next_button').bind('click.jts_pagination_events',function(e){ goToNextPage(); }); _('.jts_pagination_page_button').bind('click.jts_pagination_events',function(e){ goToPage(parseInt(_(this).attr('data-index_ref'))); }); } function addStyles(){ let interfaceBoxClass = configuration && configuration.interface_box_class ? '' : '.jts_pagination_interface_box_class{' + 'width:100%!important;display:block!important;position:relative!important;height:auto!important;padding:15px!important;float:left!important;}'; let previousNextButtonClass = configuration && configuration.previous_next_page_class ? '' : '.jts_pagination_previous_next_button_class{' + 'width:150px!important;display:block!important;position:relative!important;height:50px!important;padding:13px 5px 0px 5px!important;font-size:20px!important;font-weight:700!important;' + 'color:#bebebe!important;border:solid 1px #bebebe!important;background-color:#ffffff!important;cursor:pointer!important;font-family:Helvetica!important;' + 'margin:5px 10px!important;float:left!important;text-align:center!important;}' + '.jts_pagination_previous_next_button_class:hover{background-color:#000000!important;color:#ffffff!important;border-color:#ffffff!important;}' + '.jts_pagination_previous_next_button_class[active]{box-shadow:2px 2px 5px 0px rgba(0,0,0,0.5)!important;background-color:#000000!important;color:#ffffff!important;border-color:#ffffff!important;}' + '.jts_pagination_previous_next_button_class[disabled]{opacity:0.3!important;pointer-events:none!important;}'; let pageButtonClass = configuration && configuration.page_button_class ? '' : '.jts_pagination_page_button{' + 'width:50px!important;display:block!important;position:relative!important;height:50px!important;padding:13px 5px 0px 5px!important;font-size:20px!important;font-weight:700!important;' + 'color:#bebebe!important;border:solid 1px #bebebe!important;background-color:#ffffff!important;cursor:pointer!important;font-family:Helvetica!important;' + 'margin:5px 10px!important;float:left!important;text-align:center!important;}' + '.jts_pagination_page_button:hover{background-color:#000000!important;color:#ffffff!important;border-color:#ffffff!important;}' + '.jts_pagination_page_button[active]{box-shadow:2px 2px 5px 0px rgba(0,0,0,0.5)!important;background-color:#000000!important;color:#ffffff!important;border-color:#ffffff!important;}'; let paginationStyle = '<style id="jts_pagination_style" type="text/css">' + interfaceBoxClass + previousNextButtonClass + pageButtonClass + '</style>'; _('head').append(paginationStyle); } function clearContainer() { container.html(""); } function displayItems() { clearContainer(); let lastIndex = startIndex + pageSize; for(let index = startIndex ; index < t.length && index < lastIndex; index++){ container.append(t[index]); } if(interfaceBox != null){ interfaceContainer.append(interfaceBox); } } function goToNextPage(){ pageIndex = pageIndex + 1; startIndex = pageIndex * pageSize; displayItems(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); } function goToPage(index){ pageIndex = index; startIndex = pageIndex * pageSize; displayItems(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); } function goToPreviousPage(){ pageIndex = pageIndex - 1; startIndex = pageIndex * pageSize; displayItems(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); } function removeListeners(){ _('#jts_pagination_previous_button').unbind('click'); _('#jts_pagination_next_button').unbind('click'); _('.jts_pagination_page_button').unbind('click'); } function resetInterface(){ removeListeners(); interfaceContainer.html(""); addInterface(); } function filterSortItems(e){ t = e.data.filtered_sorted_items; startIndex = 0; pageIndex = 0; pages = Math.ceil(t.length / pageSize); displayItems(); resetInterface(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); } function updateInterface(){ if(pages === 1 || pageIndex === 0 || t.length === 0){ _('#jts_pagination_previous_button').attr('disabled',true); }else{ _('#jts_pagination_previous_button').attr('disabled',false); } _('.jts_pagination_page_button').attr('active',false); _('.jts_pagination_page_button[data-index_ref="' + pageIndex + '"]').attr('active',true); if(pages === 1 || pageIndex === pages - 1 || t.length === 0){ _('#jts_pagination_next_button').attr('disabled',true); }else{ _('#jts_pagination_next_button').attr('disabled',false); } } function updateItemsToShow(e){ pageSize = e.data.items_displayed; startIndex = 0; pageIndex = 0; pages = Math.ceil(t.length / pageSize); displayItems(); resetInterface(); updateInterface(); _(window).emits(jTS.built_in_events.jPAGINATION_PAGE_CHANGE,{ items_displayed : itemsToShow, page_index : pageIndex + 1, total_pages : pages }); } return this; }; /** * * @param isLiquid {boolean} * @param configuration {Object} * @return {jTS} */ jTS.fn.scrollingLiquidBox = /*jTS*/function (/*boolean*/isLiquid , /*Object literal*/configuration) { const t = this; if(t.length === 0){ return t; } let onMobile = jTS.jMobile(); let boxID = new Date().getTime() + "_" + Math.floor(Math.random() * 500); let container = t[0]; let slidingBox = document.createElement('div'); let scrollMarker = document.createElement('div'); let onNoScroll = false; let inSliding = false; let alreadyLiquid = false; let size = false; let currentY = 0; let previousContainerX = 0; let previousContainerY = 0; let previousContainerWidth; let previousContainerHeight; let previousParentWidth; let previousParentHeight; let previousSlidingBoxHeight; let liquidHandlesArray = []; let mousedown = onMobile ? 'touchstart' : 'mousedown'; let mouseover = onMobile ? 'touchstart' : 'mouseover'; let mousemove = onMobile ? 'touchmove' : 'mousemove'; let mouseout = onMobile ? 'touchend' : 'mouseout'; let mouseup = onMobile ? 'touchend' : 'mouseup'; let slidingBoxCSS = { 'position' : 'absolute', 'padding' : configuration && configuration.padding ? configuration.padding : 0, 'height' : 'auto', 'width' : '100%', 'top' : 0, 'left' : 0, 'z-index' : 3 }; let scrollMarkerCss = { 'position' : 'absolute', 'right' : 0, 'top' : 0, 'width' : configuration && configuration.scroll_marker_width ? configuration.scroll_marker_width : 20, 'box-shadow' : configuration && configuration.scroll_marker_shadow ? configuration.scroll_marker_shadow : '-5px 5px 5px 0px rgba(0, 0, 0, 0.3)', 'background-color' : configuration && configuration.scroll_marker_background ? configuration.scroll_marker_background : '#0eb7da', 'border-radius' : configuration && configuration.scroll_marker_radius ? configuration.scroll_marker_radius : 5, 'cursor' : 'pointer', 'z-index' : 15 }; liquid(); function addLiquidFunctions() { let MINIMUM_SIZE = 100; let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); let parentBorderSizeX = parseInt(_(container).offsetPs().css('border-left-width')); let parentBorderSizeY = parseInt(_(container).offsetPs().css('border-top-width')); let parentBoxSizing = _(container).offsetPs().css('box-sizing'); parentBorderSizeX = parentBorderSizeX ? parentBorderSizeX : 0; parentBorderSizeY = parentBorderSizeX ? parentBorderSizeY : 0; let nameSet = ['lh', 'th', 'rh', 'bh', 'tlh', 'trh', 'blh', 'brh', 'mover']; let cssSet = [ { 'width': 10, 'height': '100%', 'left': 0, 'top': 0, 'cursor': 'ew-resize' }, { 'width': '100%', 'height': 10, 'left': 0, 'top': 0, 'cursor': 'ns-resize' }, { 'width': 10, 'height': '100%', 'right': 0, 'top': 0, 'cursor': 'ew-resize' }, { 'width': '100%', 'height': 10, 'left': 0, 'bottom': 0, 'cursor': 'ns-resize' }, { 'width': 30, 'height': 30, 'left': 0, 'top': 0, 'cursor': 'nw-resize' }, { 'width': 30, 'height': 30, 'right': 0, 'top': 0, 'cursor': 'ne-resize' }, { 'width': 30, 'height': 30, 'left': 0, 'bottom': 0, 'cursor': 'sw-resize' }, { 'width': 30, 'height': 30, 'right': 0, 'bottom': 0, 'cursor': 'se-resize' }, { 'width': 100, 'height': 100, 'left': 'calc(50% - 50px)', 'top': 'calc(50% - 50px)', 'cursor': 'move' } ]; createHandles(0); function createHandles(index) { if (index < nameSet.length) { let handle = document.createElement('div'); let css = { 'background-color': 'transparent', 'position': 'absolute', 'z-index': 10 }; handle.setAttribute('name', nameSet[index]); handle.setAttribute('class', 'jts_liquid_box_handle_' + boxID); _(handle).css(css).css(cssSet[index]); _(container).append(handle); liquidHandlesArray.push(handle); createHandles(index + 1); } } let cX, cY, pX, pY, vX, vY, handle; _('.jts_liquid_box_handle_' + boxID).bind(mousedown + '.jts_liquid_box_liquid_handle_' + boxID, function (e) { e.preventDefault(); pX = onMobile ? e.originalEvent.touches[0].clientX : e.originalEvent.clientX; pY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; handle = _(e.target).attr('name'); _(window).bind(mousemove + '.jts_liquid_box_liquid_handle_' + boxID, function (e) { cX = onMobile ? e.originalEvent.touches[0].clientX : e.originalEvent.clientX; cY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; vX = cX - pX; vY = cY - pY; pX = cX; pY = cY; switch (handle) { case 'lh': vX = -vX; vY = 0; break; case 'th': vX = 0; vY = -vY; break; case 'rh': vX = vX; vY = 0; break; case 'bh': vX = 0; vY = vY; break; case 'tlh': vX = -vX; vY = -vY; break; case 'trh': vX = vX; vY = -vY; break; case 'blh': vX = -vX; vY = vY; break; case 'brh': vX = vX; vY = vY; break; case 'mover': vX = vX; vY = vY; break; } liquidResize(vX, vY); }).bind(mouseup + '.jts_liquid_box_liquid_handle_' + boxID, function (e) { _(window).unbind('.jts_liquid_box_liquid_handle_' + boxID); }); }).bind(mouseover + '.jts_liquid_box_liquid_handle_' + boxID, function (e) { _(e.target).css('background-color', 'rgba(71, 171, 198,0.8)'); }).bind(mouseout + '.jts_liquid_box_liquid_handle_' + boxID, function (e) { _(e.target).css('background-color', 'transparent'); }); function liquidResize(vX, vY) { let w = _(container).outerWidth(); let h = _(container).outerHeight(); let left = container.offsetLeft; let top = container.offsetTop; alreadyLiquid = true; if (jTS.jBrowser() === 'firefox' && parentBoxSizing === 'border-box') { left -= parentBorderSizeX; top -= parentBorderSizeY; } let x = left; let y = top; if (handle !== 'mover') { let right = left + w; let bottom = top + h; w += vX; h += vY; w = w < MINIMUM_SIZE ? MINIMUM_SIZE : w; h = h < MINIMUM_SIZE ? MINIMUM_SIZE : h; switch (handle) { case 'lh': x = right - w; break; case 'th': y = bottom - h; break; case 'tlh': x = right - w; y = bottom - h; break; case 'trh': y = bottom - h; break; case 'blh': x = right - w; break; } } else { x += vX; y += vY; } previousContainerWidth = w; previousContainerHeight = h; previousContainerX = x; previousContainerY = y; let css = { 'width': w, 'height': h, 'left': x, 'top': y, 'margin': '0px', 'position': 'absolute' }; _(container).css(css); _(container).emits(jTS.built_in_events.jLIQUID_BOX_RESIZE); } } function desktopScroll(e) { let SCROLL_VY = 130; let dY = -(e.originalEvent.wheelDelta) || e.originalEvent.detail; let vY = dY < 0 ? -SCROLL_VY : SCROLL_VY; let containerHeight = _(container).outerHeight(); let sliderHeight = _(slidingBox).outerHeight(); let y = parseInt(slidingBox.offsetTop) - vY; if (y > 0 || sliderHeight < containerHeight) { y = 0; } else if (y < containerHeight - sliderHeight) { y = containerHeight - sliderHeight; } currentY = y; _(slidingBox).css('top', y); setMarkerY(containerHeight, sliderHeight, Math.abs(y)); } function getRootN() { let e_parent = container; let r_parent = e_parent; while (e_parent) { e_parent = _(e_parent).offsetPs()[0]; if (e_parent) { r_parent = e_parent; } } if (r_parent.nodeName.toLowerCase() !== '#document') { _(window).unbind('.jts_liquid_box_events_' + boxID); _(container).unbind('.jts_liquid_box_events_' + boxID); _(container).off(jTS.built_in_events.jLIQUID_BOX_RESIZE); /*WARNING this is hardcoded WARNING*/ delete jTS.flow.listeners[mousedown + '-jts_liquid_box_events_' + boxID] if (liquidHandlesArray.length > 0) { _(liquidHandlesArray).unbind('.jts_liquid_box_liquid_handle_' + boxID); } } } function liquid() { _(container).addClass('jts_liquid_box_' + boxID).css('overflow', 'hidden'); _(slidingBox).addClass('jts_liquid_box_slider_' + boxID).css(slidingBoxCSS); _(scrollMarker).addClass('jts_liquid_box_marker' + boxID).css(scrollMarkerCss); _(slidingBox).append(_(container).html()); _(container).html('').append(slidingBox); _(container).append(scrollMarker); _(container).addClassRecursive('jts_liquid_box_no_scroll_' + boxID); _(slidingBox).addClassRecursive('jts_liquid_box_touch_scroll_' + boxID); previousContainerWidth = _(container).outerWidth(); previousContainerHeight = _(container).outerHeight(); previousParentWidth = _(container).offsetPs().outerWidth(); previousParentHeight = _(container).offsetPs().outerHeight(); previousSlidingBoxHeight = _(slidingBox).outerHeight(); setSize(); setListeners(); if (isLiquid) { addLiquidFunctions(); } } function scrollWithMarker(vY) { let y = scrollMarker.offsetTop; let markerHeight = _(scrollMarker).outerHeight(); let containerHeight = _(container).outerHeight(); y += vY; if (y < 0) { y = 0; } else if (y > containerHeight - markerHeight) { y = containerHeight - markerHeight; } _(scrollMarker).css('top', y); setBoxY(containerHeight, y); } function scrollWithTouch(vY) { let y = slidingBox.offsetTop; let containerHeight = _(container).outerHeight(); let sliderHeight = _(slidingBox).outerHeight(); y += vY; if (y > 0 || sliderHeight < containerHeight) { y = 0; } else if (y < containerHeight - sliderHeight) { y = containerHeight - sliderHeight; } currentY = y; _(slidingBox).css('top', y); setMarkerY(containerHeight, sliderHeight, Math.abs(y)); } function setBoxY(containerHeight, y) { let sliderHeight = _(slidingBox).outerHeight(); y = y * (sliderHeight / containerHeight); currentY = -y; _(slidingBox).css('top', -y); } function setListeners() { _(window).bind('resize.' + 'jts_liquid_box_events_' + boxID, function (e) { if (!getRootN()) { return; } setSize(e); }); _(window).bind('click.jts_liquid_box_events_' + boxID, function () { if (!getRootN()) { return; } }); _(container).on(jTS.built_in_events.jLIQUID_BOX_RESIZE,setSize); _(container).bind(mouseover + '.jts_liquid_box_events_' + boxID, function (e) { onNoScroll = true; }).bind(mouseout + '.jts_liquid_box_events_' + boxID, function (e) { if (!_(e.relatedTarget) || !_(e.relatedTarget).hasClass('jts_liquid_box_no_scroll_' + boxID)) { onNoScroll = false; } }); _(window).bind('mousewheel DOMMouseScroll MozMousePixelScroll.' + 'jts_liquid_box_events_' + boxID, function (e) { if (onNoScroll) { e.preventDefault(); desktopScroll(e); } }); _(scrollMarker).bind(mousedown + '.jts_liquid_box_events_' + boxID, function (e) { e.preventDefault(); let currentY; let previousY; let vY; previousY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; _(window).bind(mousemove + '.jts_liquid_box_events_' + boxID, function (e) { currentY = onMobile ? e.originalEvent.touches[0].clientY : e.originalEvent.clientY; vY = currentY - previousY; previousY = currentY; scrollWithMarker(vY); }).bind(mouseup + '.jts_liquid_box_events_' + boxID, function (e) { _(window).unbind(mousemove + '.jts_liquid_box_events_' + boxID); _(window).unbind(mouseup + '.jts_liquid_box_events_' + boxID); }); }); //IF ON MOBILE if (onMobile) { let MIN_VY = 5; _('.' + 'jts_liquid_box_touch_scroll_' + boxID).bind(mousedown + '.jts_liquid_box_events_' + boxID, function (e) { let currentY; let previousY; let vY; let dVY = 0;//this for keep vY value for slow down scroll when touch end; previousY = e.originalEvent.touches[0].clientY; currentY = previousY; _(window).bind(mousemove + '.jts_liquid_box_events_' + boxID, function (e) { e.preventDefault(); currentY = e.originalEvent.touches[0].clientY; vY = currentY - previousY; previousY = currentY; dVY = vY === 0 ? dVY : vY; scrollWithTouch(vY); }).bind(mouseup + '.jts_liquid_box_events_' + boxID, function (e) { _(window).unbind(mousemove + '.jts_liquid_box_events_' + boxID); _(window).unbind(mouseup + '.jts_liquid_box_events_' + boxID); if (Math.abs(dVY) > MIN_VY) { slowSlideFromTouch(dVY); } }); }); } } function setMarkerHeight() { let containerHeight = _(container).outerHeight(); let sliderHeight = _(slidingBox).outerHeight(); let height = Math.round(containerHeight * (containerHeight / sliderHeight)); let display = 'block'; if (sliderHeight < containerHeight) { display = 'none'; } let css = { 'height': height, 'display': display }; _(scrollMarker).css(css); } function setMarkerY(containerHeight, sliderHeight, y) { y = y * (containerHeight / sliderHeight); _(scrollMarker).css('top', y); } function setSize(e) { setMarkerHeight(); if (size) { setSliderYFromResize(e); } if (!size) { size = true; } } function slowSlideFromTouch(vY) { //let FRICTION = 0.92; let startVY = vY; inSliding = true; jTS.jAnimate(1000,slowSlide,{ timing_function : 'linear', reverse : true }); //slowSlide(); function slowSlide(progress) { if (Math.abs(vY) > 0.2) { vY = startVY * progress; scrollWithTouch(vY); //vY *= FRICTION; //setTimeout(slowSlide,16); } else { vY = 0; inSliding = false; } } } function setSliderYFromResize(e) { let containerWidth = _(container).outerWidth(); let containerHeight = _(container).outerHeight(); let containerParentWidth = _(container).offsetPs().outerWidth(); let containerParentHeight = _(container).offsetPs().outerHeight(); let sliderHeight = _(slidingBox).outerHeight(); let boxY = currentY * (sliderHeight / previousSlidingBoxHeight); if (sliderHeight < containerHeight) { boxY = 0; } if (boxY > 0) { boxY = 0; } else if (!(sliderHeight < containerHeight) && boxY < containerHeight - sliderHeight) { boxY = containerHeight - sliderHeight; } if (alreadyLiquid && e.type !== jTS.built_in_events.jLIQUID_BOX_RESIZE) { let x = previousContainerX * (containerParentWidth / previousParentWidth); let y = previousContainerY * (containerParentHeight / previousParentHeight); let posCss = { 'left': x, 'top': y }; previousContainerX = x; previousContainerY = y; _(container).css(posCss); } previousSlidingBoxHeight = sliderHeight; previousContainerWidth = containerWidth; previousContainerHeight = containerHeight; previousParentWidth = containerParentWidth; previousParentHeight = containerParentHeight; currentY = boxY; setMarkerY(containerHeight, sliderHeight, -boxY); _(slidingBox).css('top', boxY); } return this; }; /** * * @param configuration {Object} * @return {void} */ jTS.fn.shell = /*void*/function (/*Object literal*/configuration) { const t = this; if(t.length === 0){ return null; } let HANDLE_SIZE = 10; let OL_LEFT_GAP = 45; let V_GAP = 10; let SCROLL_X_EASING = 0.3; let SCROLL_Y_EASING = 18; let color = configuration && configuration.color ? configuration.color : '#5acc06'; let bColor = configuration && configuration.background_color ? configuration.background_color : '#101010'; let runColor = configuration && configuration.run_color ? configuration.run_color : '#2b2b2b'; let filterFunction = configuration && configuration.filter_function ? configuration.filter_function : function (par) { return par; }; let shellID = new Date().getTime() + "_" + Math.round(Math.random() * 1000) ; let tShell = t[0]; let shellWidth = _(tShell).outerWidth(); let shellHeight = _(tShell).outerHeight(); let olPreviousX = 0; let olPreviousY = 0; let rightBound = shellWidth; let xHandleReset = false; let yHandleReset = false; let focused = true; let currentLi = null; let currentVal = ['']; let grid = [[]]; let colIndex = -1; let rowIndex = 0; _(tShell).css({ 'background-color' : bColor, 'overflow' : 'hidden', 'position' : _(tShell).css('position') === 'static' || _(tShell).css('position') === 'relative' ? 'relative' : 'absolute' }).addClass('jts_shell_element'); let ol = document.createElement('div'); let li = document.createElement('div'); let blink = document.createElement('div'); let gap = document.createElement('div'); let run = document.createElement('div'); let vHandle = document.createElement('div'); let oHandle = document.createElement('div'); let style = "<style id='jts_shell_style_" + shellID +"' type='text/css'>" + "#jts_shell_ol_" + shellID + "{list-style:none;border:none;counter-reset:jts_shell_number;position:absolute;padding-top:10px;width:auto;}" + "#jts_shell_ol_" + shellID + " div.li{counter-increment:jts_shell_number;font-size:15px;font-family:Verdana;position:relative;border-left:solid 1px " + color + ";padding-left:5px;left:45px;}" + "#jts_shell_ol_" + shellID + " div.li::before{display:block;content:counter(jts_shell_number);color:" + color + ";width:39px;text-align:right;left:-45px;position:absolute;}" + "#jts_shell_ol_" + shellID + " div.li span.fake{color:transparent;display:inline;position:relative;}" + "#jts_shell_ol_" + shellID + " div.li div{position:relative;height:18px;width:auto;color:" + color + ";display:inline;}" + "#jts_shell_blink_" + shellID + "{border-left:1px solid " + color + ";animation-duration:0.5s;animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:linear;animation-name:jts_blink;}" + "#jts_shell_run_" + shellID + "{position:absolute;width:50px;height:50px;border-radius:2px;background-color:" + runColor + ";color:" + color + ";cursor:pointer;font-size:23px;text-align:center;border:solid 2px " + color + ";padding-top:10px;z-index:2;}" + "@keyframes jts_blink{0%{opacity:1;}50%{opacity:1;}51%{opacity:0;}100%{opacity:0;}}" + "</style>"; _(ol).attr('id', 'jts_shell_ol_' + shellID).addClass('jts_shell_element'); _(li).addClass('jts_shell_element li'); _(blink).attr('id', 'jts_shell_blink_' + shellID).addClass('jts_shell_element'); _(gap).attr('id', 'jts_shell_gap_' + shellID).addClass('jts_shell_element').html('gap'); _(run).attr('id', 'jts_shell_run_' + shellID).addClass('jts_shell_element ts-font-helvetica').html('run'); _(vHandle).attr('id', 'jts_vh_' + shellID).addClass('jts_shell_element').css({ 'height': 0, 'width': HANDLE_SIZE, 'top': 0,'left':shellWidth - HANDLE_SIZE}); _(oHandle).attr('id', 'jts_oh_' + shellID).addClass('jts_shell_element').css({ 'height': HANDLE_SIZE, 'width': 0, 'left': 0 ,'top':shellHeight - HANDLE_SIZE}); _([vHandle, oHandle]).css({ 'position' : 'absolute', 'background-color' : color, 'border-radius' : 2, 'z-index' : 3, 'cursor' : 'pointer', 'display' : 'none', 'opacity' : 0.5, 'box-shadow' : '0px 0px 3px 3px rgba(255,255,255,0.5)' }); _(blink).css({ 'z-index' : 10, 'width' : 'auto', 'height' : 20 }); _(gap).css({ 'width' : 35, 'opacity' : 0, 'position' : 'relative' }); _(run).css({ 'top' : shellHeight - 50, 'left': shellWidth - 50 }); _('head').append(style); _(ol).append(li); _(blink).append(gap); _(li).append(blink); _(tShell).append(ol); _(tShell).append([run,vHandle,oHandle]); currentLi = li; setListeners(); function executeCode() { let val = ''; for (let i = 0; i < currentVal.length; i++) { val += currentVal[i] + (i === currentVal.length - 1 ? '' : '\n'); } try { eval(filterFunction(String(val))); } catch (e) { console.log('code-error @jTSShell'); } } function getRootN() { let e_parent = tShell; let r_parent = e_parent; while (e_parent) { e_parent = _(e_parent).offsetPs()[0]; if (e_parent) { r_parent = e_parent; } } if (r_parent.nodeName.toLowerCase() !== '#document') { _(window).unbind('.jts_shell_events_' + shellID); _(tShell).unbind('.jts_shell_events_' + shellID); _(tShell).off(jTS.built_in_events.jSHELL_RESIZE); _(oHandle).unbind('mousedown'); _(vHandle).unbind('mousedown'); _(run).unbind('click'); /*WARNING this is hardcoded WARNING*/ delete jTS.flow.listeners['mousemove-jts_shell_events_' + shellID]; return false; } else { return true; } } function insertText(e) { e.preventDefault(); let posCode = getPosCode(); switch (e.keyCode) { case 8: back(posCode); break; case 13: enter(posCode); break; case 35: gotoEndLine(); break; case 36: gotoStartLine(); break; case 37: left(posCode); break; case 38: up(posCode); break; case 39: right(posCode); break; case 40: down(posCode); break; default: insert(); break; } function getPosCode() { let nodes = currentLi.children; let code = null; if (colIndex === -1 && nodes.length === 1) { code = 1; } else if (colIndex === -1 && nodes.length > 1) { code = 2; } else if (colIndex !== -1 && nodes[nodes.length - 1] !== blink) { code = 3; } else if (colIndex !== -1 && nodes[nodes.length - 1] === blink) { code = 4; } return code; } function back(code) { switch (code) { case 1: backUp(); break; case 2: backUnite(); break; case 3: case 4: disposeOne(); break; } } function enter(code) { switch (code) { case 2: addLiUp(); break; case 3: splitLi(); break; case 1: case 4: addLiDown(); break; } _(ol).css('left', 0); } function left(code) { switch (code) { case 1: case 2: moveUp(); break; case 3: case 4: moveLeft(); break; } } function up(code) { moveUp(); } function right(code) { switch (code) { case 2: case 3: moveRight(); break; case 1: case 4: moveDown(); break; } } function down(code) { moveDown(); } function insert() { if (e.originalEvent.key.length > 1) { return; } if (xHandleReset) { resetXHandle(); } if (yHandleReset) { resetYHandle(); } _(blink).css('position', 'absolute'); let canvas = document.createElement('div'); let opacity = e.keyCode === 32 ? 0 : 1; canvas.innerHTML = e.keyCode === 32 ? 'ff' : e.originalEvent.key; _(canvas).addClass('jts_shell_element').css('opacity', opacity); _(currentLi).before(canvas, blink); colIndex += 1; grid[rowIndex].splice(colIndex,0,canvas); currentVal[rowIndex] = jTS.jStringSplice(currentVal[rowIndex],colIndex,e.originalEvent.key); scrollRight(); setHandleX(); }//OK //sub functions function backUp() { if (yHandleReset) { resetYHandle(); } if (rowIndex === 0) { return; } rowIndex -= 1; currentLi = document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex]; _(currentLi.children[currentLi.children.length - 1]).dispose(); _(currentLi).append(blink); colIndex = grid[rowIndex].length - 1; _(document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex + 1]).dispose(); grid.splice(rowIndex + 1, 1); currentVal.splice(rowIndex + 1, 1); let pos = grid[rowIndex].length === 0 ? 'relative' : 'absolute'; _(blink).css('position', pos); setOl(); scrollUp(); setHandleX(); setHandleY(); }//OK function backUnite(){ if (yHandleReset) { resetYHandle(); } if (rowIndex === 0) { return; } rowIndex -= 1; colIndex = grid[rowIndex].length - 1; grid[rowIndex] = grid[rowIndex].concat(grid[rowIndex + 1]); currentLi = document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex]; _(currentLi.children[currentLi.children.length - 1]).dispose(); _(currentLi).append(blink); _(currentLi).append(grid[rowIndex + 1], blink); grid.splice(rowIndex + 1, 1); _(document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex + 1]).dispose(); currentVal[rowIndex] = currentVal[rowIndex] + currentVal[rowIndex + 1]; currentVal.splice(rowIndex + 1, 1); setOl(); scrollUp(); setHandleX(); setHandleY(); }//OK function disposeOne() { if (xHandleReset) { resetXHandle(); } if (yHandleReset) { resetYHandle(); } _(grid[rowIndex][colIndex]).dispose(); grid[rowIndex].splice(colIndex,1); currentVal[rowIndex] = jTS.jStringSplice(currentVal[rowIndex],colIndex, 1); colIndex -= 1; let pos = colIndex === -1 && grid[rowIndex].length === 0 ? 'relative' : 'absolute'; _(blink).css('position', pos); scrollLeft(); setHandleX(); }//OK function addLiDown() { if (yHandleReset) { resetYHandle(); } let span = "<span class='fake jts_shell_element'>fake</fake>"; let nLi = document.createElement('div'); _(currentLi).append(span); _(ol).append(nLi, currentLi); currentLi = nLi; rowIndex += 1; colIndex = -1; _(currentLi).append(blink).addClass('jts_shell_element li'); grid.splice(rowIndex, 0, []); currentVal.splice(rowIndex, 0, ''); _(blink).css('position', 'relative'); resetOl(); scrollDown(); setHandleX(); setHandleY(); }//OK function addLiUp() { if (yHandleReset) { resetYHandle(); } let span = "<span class='fake jts_shell_element'>fake</fake>"; let nLi = document.createElement('div'); _(currentLi).append(span); _(ol).before(nLi, currentLi); currentLi = nLi; colIndex = -1; _(currentLi).append(blink).addClass('jts_shell_element li'); grid.splice(rowIndex, 0, []); currentVal.splice(rowIndex, 0, ''); _(blink).css('position', 'relative') resetOl(); scrollUp(); setHandleX(); setHandleY(); }//OK function splitLi() { if (yHandleReset) { resetYHandle(); } let span = "<span class='fake jts_shell_element'>fake</fake>"; let nLi = document.createElement('div'); let rightContent = []; let leftContent = []; for (let i = 0; i <= colIndex; i++){ rightContent.push(grid[rowIndex][i]); } for (let l = colIndex + 1 ; l < grid[rowIndex].length ; l++) { leftContent.push(grid[rowIndex][l]); } _(currentLi).html(''); _(currentLi).append(rightContent).append(span); _(nLi).append(leftContent); _(ol).append(nLi, currentLi); currentLi = nLi; _(currentLi).before(blink).addClass('jts_shell_element li'); grid[rowIndex] = rightContent; grid.splice(rowIndex + 1, 0, leftContent); let rightVal = currentVal[rowIndex].substr(0,colIndex + 1); let leftVal = currentVal[rowIndex].substr(colIndex + 1); currentVal[rowIndex] = rightVal; currentVal.splice(rowIndex + 1, 0, leftVal); colIndex = -1; rowIndex += 1; resetOl(); scrollDown(); setHandleX(); setHandleY(); }//OK function moveUp() { if (yHandleReset) { resetYHandle(); } if (rowIndex === 0) { return; } let span = "<span class='fake jts_shell_element'>fake</fake>"; _(currentLi).append(span); rowIndex -= 1; currentLi = document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex]; _(currentLi.children[currentLi.children.length - 1]).dispose(); colIndex = grid[rowIndex].length - 1; _(currentLi).append(blink); let pos = grid[rowIndex].length === 0 ? 'relative' : 'absolute'; _(blink).css('position', pos); setOl(); scrollUp(); setHandleX(); setHandleY(); }//OK function moveLeft() { if (xHandleReset) { resetXHandle(); } if (yHandleReset) { resetYHandle(); } _(currentLi).before(blink, grid[rowIndex][colIndex]); colIndex -= 1; scrollLeft(); setHandleX(); }//OK function moveDown() { if (yHandleReset) { resetYHandle(); } if(rowIndex + 1 === grid.length){ return; } let span = "<span class='fake jts_shell_element'>fake</fake>"; _(currentLi).append(span); rowIndex += 1; currentLi = document.querySelector('#jts_shell_ol_' + shellID).children[rowIndex]; _(currentLi.children[currentLi.children.length - 1]).dispose(); colIndex = - 1; _(currentLi).before(blink); let pos = grid[rowIndex].length === 0 ? 'relative' : 'absolute'; _(blink).css('position', pos); resetOl(); scrollDown(); setHandleX(); setHandleY(); }//OK function moveRight() { if (xHandleReset) { resetXHandle(); } if (yHandleReset) { resetYHandle(); } _(currentLi).append(blink, grid[rowIndex][colIndex + 1]); colIndex += 1; scrollRight(); setHandleX(); }//OK function gotoEndLine(){ if (yHandleReset) { resetYHandle(); } _(currentLi).append(blink); colIndex = grid[rowIndex].length - 1; setOl(); setHandleX(); }//OK function gotoStartLine() { if (yHandleReset) { resetYHandle(); } _(currentLi).before(blink); colIndex = -1; resetOl(); setHandleX(); }//OK } function moveHandleX(vX) { let width = _(oHandle).outerWidth(); let x = _(oHandle).localCoordinates().left; x += vX; if (x < 0) { x = 0 } else if(x + width > shellWidth){ x = shellWidth - width; } _(oHandle).css('left',x); setOlPositionX(x); } function moveHandleY(vY) { let height = _(vHandle).outerHeight(); let y = _(vHandle).localCoordinates().top; y += vY; if (y < 0) { y = 0 } else if (y + height > shellHeight) { y = shellHeight - height; } _(vHandle).css('top', y); setOlPositionY(y); } function resizeDealerZ(){ shellWidth = _(tShell).outerWidth(); shellHeight = _(tShell).outerHeight(); _(run).css({ 'top': shellHeight - 50, 'left': shellWidth - 50, }); _(oHandle).css('top', shellHeight - HANDLE_SIZE); _(vHandle).css('left', shellWidth - HANDLE_SIZE); _(ol).css({ 'left': 0, 'top' : 0 }); rightBound = shellWidth; setHandleX(); setHandleY(); xHandleReset = true; yHandleReset = true; } function resetOl() { rightBound = shellWidth; _(ol).css('left', 0); } function resetXHandle() { xHandleReset = false; setOl(); } function resetYHandle() { yHandleReset = false; let liOffset = _(currentLi).localCoordinates().top; let targetPos = V_GAP; let olHeight = _(ol).outerHeight(); let olOffset = -(liOffset - targetPos); if (olOffset + olHeight + V_GAP < shellHeight) { olOffset = -((olHeight - shellHeight) + V_GAP); } if (olOffset > 0) { olOffset = 0; } _(ol).css('top', olOffset); setHandleY(); } function scrollDown() { let liPos = _(currentLi).localCoordinates().top; let olOffset = _(ol).localCoordinates().top; if ((liPos + SCROLL_Y_EASING) - Math.abs(olOffset) > shellHeight) { olOffset = -(liPos - (shellHeight - V_GAP - SCROLL_Y_EASING)); _(ol).css('top', olOffset); } } function scrollLeft() { let blinkPos = _(blink).localCoordinates().left; let olLeft = _(ol).localCoordinates().left; let olWidth = _(ol).outerWidth(); if (blinkPos - Math.abs(olLeft + OL_LEFT_GAP) < OL_LEFT_GAP) { let gap = shellWidth * SCROLL_X_EASING; olLeft += gap; rightBound -= gap; _(ol).css('left', olLeft); if (olLeft > 0) { resetOl(); } } if (olWidth + OL_LEFT_GAP < shellWidth) { resetOl(); } } function scrollRight() { let blinkPos = _(blink).localCoordinates().left; if (blinkPos + OL_LEFT_GAP > rightBound) { let gap = shellWidth * SCROLL_X_EASING; let olLeft = _(ol).localCoordinates().left - gap; rightBound += gap; _(ol).css('left', olLeft); } } function scrollUp() { let liPos = _(currentLi).localCoordinates().top; let olOffset = _(ol).localCoordinates().top; let olHeight = _(ol).outerHeight(); if ( liPos - Math.abs(olOffset) <= 0) { olOffset = -(liPos - V_GAP); _(ol).css('top', olOffset); } if (olOffset + olHeight + V_GAP < shellHeight) { olOffset = -(olHeight - (shellHeight - V_GAP)); if (olOffset > 0) { olOffset = 0; } _(ol).css('top', olOffset); } } function setHandleX() { let olWidth = _(ol).outerWidth() + OL_LEFT_GAP; let olOffset = _(ol).localCoordinates().left; if (olWidth > shellWidth) { let totalWidth = olWidth + (shellWidth * SCROLL_X_EASING); let handleWidth = shellWidth * (shellWidth / totalWidth); let handlePos = Math.abs(olOffset) * (shellWidth / totalWidth); _(oHandle).css({ 'display' : 'block', 'left' : handlePos, 'width' : handleWidth }); } else { _(oHandle).css('display', 'none'); } } function setHandleY() { let olHeight = _(ol).outerHeight() + V_GAP; if (olHeight > shellHeight) { let olOffset = Math.abs(_(ol).localCoordinates().top); let handleHeight = shellHeight * (shellHeight / olHeight); let handlePos = olOffset * (shellHeight / olHeight); _(vHandle).css({ 'display' : 'block', 'top' : handlePos, 'height' : handleHeight }); } else { _(vHandle).css('display', 'none'); } } function setListeners() { _(window).bind('keydown.jts_shell_events_' + shellID, insertText); _(tShell).bind('click.jts_shell_events_' + shellID, function (e) { if (!focused) { focused = true; _(window).bind('keydown.jts_shell_events_' + shellID, insertText); } _(blink).css({'visibility':'visible'}); }); _(window).bind('click.jts_shell_events_' + shellID, function (e) { if (!getRootN()) { return; } if (!_(e.target).hasClass('jts_shell_element')) { focused = false; _(blink).css({ 'visibility': 'hidden'}); _(window).unbind('keydown.jts_shell_events_' + shellID); } }); _(window).bind('resize.jts_shell_events_' + shellID, function () { if (!getRootN()) { return; } resizeDealerZ(); }); _('.jts_shell_element').bind('mousemove.jts_shell_events_' + shellID, function (e) { e.preventDefault(); }); _(oHandle).bind('mousedown.jts_shell_events_' + shellID, function (e) { let vX, cX, pX; pX = jTS.jMobile() ? e.originalEvent.touches[0].clientX : e.screenX; _(window).bind('mousemove.jts_shell_ohandle', function (e) { e.preventDefault(); cX = jTS.jMobile() ? e.originalEvent.touches[0].clientX : e.screenX; vX = cX - pX; pX = cX; xHandleReset = true; moveHandleX(vX); }); _(window).bind('mouseup.jts_shell_ohandle', function (e) { _(window).unbind('.jts_shell_ohandle'); }); }); _(vHandle).bind('mousedown.jts_shell_events_' + shellID, function (e) { let vY, cY, pY; pY = jTS.jMobile() ? e.originalEvent.touches[0].clientY : e.screenY; _(window).bind('mousemove.jts_shell_vhandle', function (e) { e.preventDefault(); cY = jTS.jMobile() ? e.originalEvent.touches[0].clientY : e.screenY; vY = cY - pY; pY = cY; yHandleReset = true; moveHandleY(vY); }); _(window).bind('mouseup.jts_shell_vhandle', function (e) { _(window).unbind('.jts_shell_vhandle'); }); }); _(run).bind('click', function () { executeCode(); }); _(tShell).on(jTS.built_in_events.jSHELL_RESIZE, function () { resizeDealerZ(); }); } function setOl() { let blinkPos = _(blink).localCoordinates().left + OL_LEFT_GAP; if (blinkPos <= shellWidth) { resetOl(); } else { rightBound = blinkPos + (shellWidth * SCROLL_X_EASING); let olOffset = blinkPos - (shellWidth * (1 - SCROLL_X_EASING)); _(ol).css('left', -olOffset); } } function setOlPositionX(x) { let totalWidth = _(ol).outerWidth() + OL_LEFT_GAP + (shellWidth * SCROLL_X_EASING); let olOffset = x * (totalWidth /shellWidth); _(ol).css('left', -olOffset); olPreviousX = -olOffset; } function setOlPositionY(y) { let olHeight = _(ol).outerHeight() + V_GAP; let olOffset = y * (olHeight / shellHeight); _(ol).css('top', -olOffset); olPreviousY = -olOffset; } }; /** * * @param configuration {Object} * @return {jTS} */ jTS.fn.worldMap =/*jTS*/ function(/*Object literal*/configuration){ class ViewingTransformer { /** * Initialize the transformer. * @param {int} maxScale - Maximum map scale * @param {int} minScale - Minimum map scale * @param {Element} svg - An svg element from which matrices can be created. */ constructor(minScale , maxScale , svg) { this.minimumScale = minScale || 1; this.maximumScale = maxScale || 20; this.lowerScale = Math.floor(this.minimumScale * 100) / 100; this.svg = svg || document.createElementNS('http://www.w3.org/2000/svg', 'svg'); // This is the viewing transformation matrix, which starts at identity. this.vtm = this.createSVGMatrix(); } /** * Helper method to create a new SVGMatrix instance. */ createSVGMatrix() { return this.svg.createSVGMatrix(); } /** * Scale the vtm. * @param {Number} scaleX - The amount to scale in the x direction. * @param {Number} scaleY - The amount to scale in the y direction. * @param {Object} origin - The origin point at which the scale should be centered. */ scale(scaleX, scaleY , origin) { let possibleVtm = this.createSVGMatrix().translate(origin.x, origin.y).scale(scaleX, scaleY).translate(-origin.x, -origin.y).multiply(this.vtm); if(possibleVtm.a < this.minimumScale || possibleVtm.d < this.minimumScale){ origin.x = 0; origin.y = 0; scaleX = this.minimumScale; scaleY = this.minimumScale; this.vtm = this.createSVGMatrix(); }else if(possibleVtm.a > this.maximumScale || possibleVtm.d > this.maximumScale){ return this.vtm; } // Order is important -- read this from the bottom to the top. // 1) Post multiply onto the current matrix. // 2) Translate such that the origin is at (0, 0). // 3) Scale by the provided factors at the origin. // 4) Put the origin back where it was. this.vtm = this.createSVGMatrix() .translate(origin.x, origin.y) .scale(scaleX, scaleY) .translate(-origin.x, -origin.y) .multiply(this.vtm); return this.vtm; } setZoomAndPosition(scaleX, scaleY , origin,translate){ this.vtm = this.createSVGMatrix() .translate(origin.x, origin.y) .scale(scaleX, scaleY) .translate(-translate.x, -translate.y) .multiply(this.vtm); return this.vtm; } translateSvg(vX,vY,boundaries){ let oldScaleX = this.vtm.a; let oldScaleY = this.vtm.d; if(Math.floor(oldScaleX * 100) / 100 === this.lowerScale || Math.floor(oldScaleY * 100) / 100 === this.lowerScale){ return this.vtm; } this.vtm = this.createSVGMatrix() .translate(this.vtm.e + vX, this.vtm.f + vY); this.vtm.a = oldScaleX; this.vtm.d = oldScaleY; if(this.vtm.e > 0){ this.vtm.e = 0; } if(this.vtm.e + boundaries.x < boundaries.xe){ this.vtm.e = boundaries.xe - boundaries.x; } if(this.vtm.f > 0){ this.vtm.f = 0; } if(this.vtm.f + boundaries.y < boundaries.ye){ this.vtm.f = boundaries.ye - boundaries.y; } return this.vtm; } } let t = this; let resizeID = null; let mousedown = jTS.jMobile() ? 'touchstart' : 'mousedown'; let mouseup = jTS.jMobile() ? 'touchend' : 'mouseup'; let mousemove = jTS.jMobile() ? 'touchmove' : 'mousemove'; let overMap = false; let zoomPosAndOrigin = []; addStyle(); t.load(configuration.map_url,function(content,index,element){ activateMap(index,element); }); function activateMap(index,element){ addLabel(); activate(); function activate(){ if(!_(element).attr('id')){ _(element).attr('id','jts_world_map_' + configuration.ID + '_' + i); } _(element).attr('data-id',`${configuration.ID}-${index}`); if(configuration.styleClass){ _(element).addClass(configuration.styleClass); } _(element).css({ overflow : 'hidden' }); zoomPosAndOrigin[index] = { zoom : 0, x : 0, y: 0 }; initializeElement(element); addListeners(); } function addLabel(){ let label = _(`<div class="world-map-label ts-font-helvetica" data-id="${configuration.ID}-${index}"></div>`); _('body').append(label); } function addListeners(){ if(index === 0){ _(window).bind('resize.world_map_events_' + configuration.ID,function(){ clearTimeout(resizeID); resizeID = setTimeout(function () { t.each(function(i,e){ disposeElement(e); initializeElement(e); }); },1500); }); _(window).on(jTS.built_in_events.jEXTERNAL_RESIZE + '.world_map_events_' + configuration.ID,function(e){ resizeID = setTimeout(function () { t.each(function(i,e){ disposeElement(e); initializeElement(e); }); },1500); }); } } function disposeElement(e) { _('#' + _(e).attr('id') + ' svg path').unbind('.world_map_events'); _(e).unbind('.world_map_events'); _('#' + _(e).attr('id') + '_plus').unbind('.world_map_events'); _('#' + _(e).attr('id') + '_minus').unbind('.world_map_events'); _('.world-map-controls').dispose(); _(e).off(jTS.built_in_events.jWORLD_MAP_SET_ZOOM_AND_POSITION); } function globalToLocal(e,x,y){ let parent = e; while(parent){ x -= parent.offsetLeft; y -= parent.offsetTop; parent = parent.offsetParent; } return {x:x,y:y}; } function initializeElement(element){ let minimumScale = 1; let maximumScale = configuration.maxScale ? configuration.maxScale : 20; let transform = false; let svg = document.querySelector('#' + _(element).attr('id') + ' svg'); let g = document.querySelector('#' + _(element).attr('id') + ' svg g'); let viewingTransformer = null; g.transform.baseVal.appendItem(g.transform.baseVal.createSVGTransformFromMatrix(svg.createSVGMatrix())); setSize(); attachListeners(); function addControls(){ let controls = '<div class="world-map-controls ' + (configuration.overrideControlsClass ? configuration.overrideControlsClass : '') + (jTS.jMobile() ? ' controls-visible' : '') + '" id="' + _(element).attr('id') + '_controls' + '">' + '<div class="minus ts-grid-fixed" id="' + _(element).attr('id') + '_minus' + '"><i class="fa fa-minus"></i></div>' + '<div class="plus ts-grid-fixed" id="' + _(element).attr('id') + '_plus' + '"><i class="fa fa-plus"></i></div>' + '</div>'; _(element).append(controls); } function attachListeners(){ _('#' + _(element).attr('id') + ' svg path').bind('mouseover.world_map_events',function(e){ let name = _(this).attr('data-name'); let flag = configuration.flags_url + '/' + _(this).attr('data-flag'); let dataID = _(element).attr('data-id'); overMap = true; if(configuration.showLabel !== false){ _(`.world-map-label[data-id="${dataID}"]`).html('<div class="span ts-grid-fixed">' + name + '</div><div class="img ts-grid-fixed"><img alt="img" src="' + flag + '"></div>'); _(`.world-map-label[data-id="${dataID}"]`).css('opacity',1); } }).bind('mouseout.world_map_events',function (e) { overMap = false; if(configuration.showLabel !== false){ let dataID = _(element).attr('data-id'); _(`.world-map-label[data-id="${dataID}"]`).css('opacity',0); } }); _(element).bind('mousewheel DOMMouseScroll MozMousePixelScroll.world_map_events',function(e){ e.preventDefault(); // The zoom direction (in or out). let dir = e.originalEvent.deltaY < 0 ? 1 : -1; // How much to zoom, maintaining aspect ratio. let scaleX = 1 + .1 * dir; let scaleY = scaleX * svg.height.baseVal.value / svg.width.baseVal.value; let coordinates = globalToLocal(element,e.globalX,e.globalY); // The mouse coordinates. let origin = { x: coordinates.x, y: coordinates.y }; // Get the new matrix. let mat = viewingTransformer.scale(scaleX, scaleY, origin); // Set the matrix on the group. g.transform.baseVal.getItem(0).setMatrix(mat); }); _('#' + _(element).attr('id') + '_minus').bind(mousedown + '.world_map_events',function(e){ transform = true; transformSvg(0.9); }).bind(mouseup + '.world_map_events',function(e){ transform = false; }); _('#' + _(element).attr('id') + '_plus').bind(mousedown + '.world_map_events',function(e){ transform = true; transformSvg(1.1); }).bind(mouseup + '.world_map_events',function(e){ transform = false; }); _(element).bind(mousedown + '.world_map_events',function(e){ let pointerX = jTS.jMobile() ? e.originalEvent.touches[0].clientX : e.globalX; let pointerY = jTS.jMobile() ? e.originalEvent.touches[0].clientY : e.globalY; let previousX = pointerX; let previousY = pointerY; let vX = 0; let vY = 0; if(!_(e.target).hasClass('minus') && !_(e.target).hasClass('plus')){ _(element).addClass('world-draggable'); _(window).bind(mousemove + '.world_drag',function (e) { pointerX = jTS.jMobile() ? e.originalEvent.touches[0].clientX : e.globalX; pointerY = jTS.jMobile() ? e.originalEvent.touches[0].clientY : e.globalY; vX = pointerX - previousX; vY = pointerY - previousY; previousX = pointerX; previousY = pointerY; panSvg(vX,vY); }).bind(mouseup + '.world_drag',function (e) { _(element).removeClass('world-draggable'); _(window).unbind('.world_drag'); }); } }).bind('mouseover.world_map_events',function (e) { _('#' + _(element).attr('id') + '_controls').attr('active',true); }).bind('mouseout.world_map_events',function (e) { _('#' + _(element).attr('id') + '_controls').attr('active',false); }); _(element).bind(mousemove + '.world_map_events_' + + configuration.ID,function(e){ if(overMap && configuration.showLabel !== false){ let dataID = _(element).attr('data-id'); _(`.world-map-label[data-id="${dataID}"]`).css({ top : e.screenY, left : e.screenX, }); } }); _(element).on(jTS.built_in_events.jWORLD_MAP_SET_ZOOM_AND_POSITION,function(e){ if(e.emitter[0] === element){ setZoomAndPosition(e.data); } }); _(element).emits(jTS.built_in_events.jWORLD_MAP_LOADED); } function panSvg(vX,vY) { let boundaries = { x : _(g).outerWidth(), y : _(g).outerHeight(), xe : _(element).outerWidth(), ye : _(element).outerHeight() }; let mat = viewingTransformer.translateSvg(vX,vY,boundaries); g.transform.baseVal.getItem(0).setMatrix(mat); } function resetElement(){ viewingTransformer = new ViewingTransformer(minimumScale,maximumScale); let origin = { x: 0, y: 0 }; let mat = viewingTransformer.scale(minimumScale,minimumScale, origin); g.transform.baseVal.getItem(0).setMatrix(mat); if(zoomPosAndOrigin[index].zoom !== 0){ setZoomAndPosition(zoomPosAndOrigin[index]); } addControls(); } function setSize(){ let WIDTH_REF = 725; let HEIGHT_REF = 360; let SCALE_REF = 0.8; let width = _(element).outerWidth(); let height = width * (HEIGHT_REF / WIDTH_REF); minimumScale = SCALE_REF * (width / WIDTH_REF); _('#' + _(element).attr('id') + ' svg').attr({ 'width' : width, 'height' : height, }); resetElement(); } function setZoomAndPosition(data) { const WIDTH_REF = 725; const HEIGHT_REF = 360; let scaleX = data.zoom > maximumScale ? maximumScale : data.zoom; let scaleY = scaleX * svg.height.baseVal.value / svg.width.baseVal.value; let translateX = (data.x * (svg.width.baseVal.value / WIDTH_REF)) - (svg.width.baseVal.value * 0.5); let translateY = (data.y * (svg.height.baseVal.value / HEIGHT_REF)) - (svg.height.baseVal.value * 0.5); let origin = { x : svg.width.baseVal.value * 0.5, y : svg.height.baseVal.value * 0.5 }; let translate = { x : translateX + (svg.width.baseVal.value * 0.5), y : translateY + (svg.height.baseVal.value * 0.5) }; viewingTransformer = new ViewingTransformer(minimumScale,maximumScale); let resetMat = viewingTransformer.scale(minimumScale,minimumScale,{x : 0 , y : 0}); g.transform.baseVal.getItem(0).setMatrix(resetMat); let mat = viewingTransformer.setZoomAndPosition(scaleX, scaleY,origin,translate); g.transform.baseVal.getItem(0).setMatrix(mat); zoomPosAndOrigin[index] = data; } function transformSvg(scale){ if(transform){ let scaleX = scale; let scaleY = scaleX * svg.height.baseVal.value / svg.width.baseVal.value; let origin = { x: svg.width.baseVal.value * 0.5, y: svg.height.baseVal.value * 0.5 }; let mat = viewingTransformer.scale(scaleX, scaleY, origin); g.transform.baseVal.getItem(0).setMatrix(mat); setTimeout(function(){ transformSvg(scale); },16); } } } } function addStyle(){ let zIndex = configuration.label_index || 100; let backGroundColor = configuration.label_background || '#0d0d0d'; let color = configuration.label_color || '#f9f9f9'; let borderRadius = configuration.label_radius || '5px'; if(_('#world-map-style').length === 0){ let style = '<style type="text/css" id="world-map-style">' + '.world-map-label{position: fixed;z-index: ' + zIndex + ';padding: 5px 20px;height: 50px; white-space: nowrap;background-color: ' + backGroundColor + ';opacity: 0;transition: opacity 0.5s ease-out;pointer-events: none;border-radius: ' + borderRadius + ';transform: translateX(-50%) translateY(-65px);}' + '.world-map-label div.span{padding:10px 0 0 0;height:40px;font-size: 15px;font-weight:600;color: ' + color + '}' + '.world-map-label div.img{overflow: hidden;width: 40px;height: 40px;margin-left: 10px;border-radius: 50%;position: relative;}' + '.world-map-label div.img img{position: absolute;width: 100%;height: 100%;object-fit: cover;}' + '.world-map-label:after{content: "";border: solid 15px transparent;border-top-color: #0d0d0d;position: absolute;bottom:-28px;left: calc(50% - 15px)}' + '.world-map-controls{position: absolute;z-index: 1;top: 10px; left: 10px;opacity: 0;transition: opacity 0.5s ease-out 1s;width: 70px;height: 30px;}' + '.world-map-controls[active]{opacity: 1;}' + '.world-map-controls .minus{width: 30px;height: 30px;border-radius: 50%;background-color: rgba(255,255,255,0.5);color:#0d0d0d;text-align: center;font-size: 18px;margin-right: 10px;cursor: pointer;padding: 5px 0 0 0;}' + '.world-map-controls .plus{width: 30px;height: 30px;border-radius: 50%;background-color: rgba(255,255,255,0.5);color:#0d0d0d;text-align: center;font-size: 18px;cursor: pointer;padding: 5px 0 0 0;}' + '.controls-visible{opacity: 1!important;}' + '.world-draggable{cursor: grabbing!important;}' + '</style>'; _('head').append(style); } } return t; }; /** * * @param zoomSize {int} * @param configuration {Object} * @return {jTS} */ jTS.fn.zoom = /*jTS*/function (/*int*/zoomSize , /*Object literal*/configuration) { const t = this; let BORDER = 'solid 1px ' + (configuration && configuration.border_color ? configuration.border_color : '#efefef'); let SIDE_HIGHLIGHTED = configuration && configuration.highlight_color ? '0px 0px 8px 0px ' + configuration.highlight_color : '0px 0px 8px 0px rgba(255,137,0,1)'; let UNDER_BAR_HEIGHT = 55; let IS_CLICK = 130; let BORDER_GAP = 15; let CANVAS_SIZE = 2024; let SQUARE_SIZE = zoomSize || 180; let BUTTON_SIZE = 512; let RESIZE_DELAY = 50; let sideImages = []; let sideImgElements = []; let imagesInfo = []; let srcDB = []; let zoomID = new Date().getTime() + "_" + Math.floor(Math.random() * 500); let incrementalIndex = -1; t.each(function (i, e) { if (e.tagName.toLowerCase() === 'img') { if (srcDB.indexOf(e.src) === -1) { incrementalIndex++; pushImage(incrementalIndex , e); } _(e).bind('click.jts_zoom_events_' + zoomID, function (event) { addZoom(e, event); }).css('cursor', 'pointer'); } function pushImage(i, e) { let imgC = document.createElement('div'); let imgI = new Image(); _(imgI).css({ 'width': '100%', 'height': 'auto', 'position': 'relative' }).attr({ 'alt': 'side_img', 'src': e.src, 'id': 'jts_zoom_side_img_' + i, 'index_ref': i }).addClass('jts_zoom_side_img'); _(imgC).css({ 'border': BORDER, 'height': 'auto', 'margin-bottom': 5, 'cursor': 'pointer' }).attr('id', 'jts_zoom_side_container_' + i).addClass('col-pp-12 jts_zoom_side_img_container').append(imgI); srcDB.push(e.src); sideImages.push(imgC); sideImgElements.push(imgI); storeImgInfo(i, e); } function storeImgInfo(i, e) { let info = {}; let name = e.src.split('/'); name = name[name.length - 1]; info.name = name; imagesInfo.push(info); if (_(e).attr('info_address')) { getInfo(_(e).attr('info_address')); }else if(_(e).attr('zoom_data')){ let zoomInfo = JSON.parse(_(e).attr('zoom_data')); for (let n in zoomInfo) { if(zoomInfo.hasOwnProperty(n)){ imagesInfo[i][n] = zoomInfo[n]; } } } else { setInfo(); } function getInfo(address) { jTS.jJSON(address, function (d) { for (let n in d) { if(d.hasOwnProperty(n)){ imagesInfo[i][n] = d[n]; } } }, function (e) { setInfo(); }); } function setInfo() { jTS.jRequest(e.src, { 'success': function (d) { let b = new Blob([d]); imagesInfo[i].size = b.size; } }); } } }); function addZoom(e, event) { let imageIndex = srcDB.indexOf(e.src); let onMobile = jTS.jMobile(); let container = document.createElement('div'); let innerContainer = document.createElement('div'); let rowUp = document.createElement('div'); let rowDown = document.createElement('div'); let sideBar = document.createElement('div'); let containerLeftOuterBox = document.createElement('div'); let containerRightOuterBox = document.createElement('div'); let containerLeft = document.createElement('div'); let containerRight = document.createElement('div'); let square = document.createElement('div'); let imageInfo = document.createElement('div'); let imageCanvas = document.createElement('canvas'); let brush = imageCanvas.getContext('2d'); let dpr = 5; let underBar = document.createElement('div'); let titleText = document.createElement('div'); let previousButton = document.createElement('div'); let nextButton = document.createElement('div'); let disposeButton = document.createElement('div'); let mousedown = onMobile ? 'touchstart' : 'mousedown'; let mousemove = onMobile ? 'touchmove' : 'mousemove'; let mouseup = onMobile ? 'touchend' : 'mouseup'; let mouseover = onMobile ? 'touchstart' : 'mouseover'; let mouseout = onMobile ? 'touchend' : 'mouseout'; let startMT = 0; let endMT = 0; let leftIMG = new Image(); _(container).css({ 'background-color': configuration && configuration.overlay_color ? configuration.overlay_color : 'rgba(0,0,0,0.6)', 'position': 'fixed', 'top': 0, 'left': 0, 'z-index': 100 }); _(innerContainer).css({ 'background-color': 'rgb(255,255,255)', 'position': 'absolute', 'border-radius': configuration && (configuration.main_radius || configuration.main_radius === 0) ? configuration.main_radius : 5, 'height': 'auto', 'padding': 15, 'box-shadow' : configuration && configuration.main_shadow ? configuration.main_shadow : '2px 2px 10px 0px rgba(0,0,0,0.6)' }); _([rowUp, rowDown]).addClass('row'); _(sideBar).css({ 'border': BORDER, 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.main_radius : 5, }).addClass('ts-hide-pp col-pl-1'); _(containerLeft).css({ 'border': BORDER, 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.sub_radius : 5, 'box-shadow' : configuration && configuration.sub_shadow ? configuration.sub_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)' }).addClass('col-pp-12'); _(containerRight).css({ 'border': BORDER, 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.sub_radius : 5, 'box-shadow' : configuration && configuration.sub_shadow ? configuration.sub_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)' }).addClass('col-pp-12'); _(containerLeftOuterBox).css({ 'margin-bottom': 15, 'overflow' : 'visible' }).addClass('col-pp-12 col-pl-5h ts-hpd-5').append(containerLeft); _(containerRightOuterBox).css({ 'margin-bottom': 15, 'overflow' : 'visible' }).addClass('col-pp-12 col-pl-5h ts-hpd-5').append(containerRight); _(square).css({ 'background-color': configuration && configuration.square_color ? configuration.square_color : 'rgba(255,137,0,0.3)', 'visibility': 'hidden', 'width': SQUARE_SIZE, 'height': SQUARE_SIZE, 'position': 'absolute', 'z-index': 10 }).attr({ 'id': 'jts_zoom_square' }); _(underBar).css({ 'height': UNDER_BAR_HEIGHT, 'overflow': 'visible' }).addClass('col-pp-12'); _(leftIMG).css({ 'position': 'absolute', 'border': BORDER }).attr({ 'alt': 'left_img', 'src': srcDB[imageIndex] }).addClass('jts_zoom_left_img'); imageCanvas.width = CANVAS_SIZE; imageCanvas.height = CANVAS_SIZE; previousButton.width = BUTTON_SIZE; previousButton.height = BUTTON_SIZE; nextButton.width = BUTTON_SIZE; nextButton.height = BUTTON_SIZE; disposeButton.width = BUTTON_SIZE; disposeButton.height = BUTTON_SIZE; _(imageCanvas).css({ 'width': '100%', 'height': '100%', 'position': 'absolute', 'top': 0, 'left': 0, 'display': 'none', 'z-index': 1 }).addClass('jts_zoom_canvas'); _(imageInfo).css({ 'width': '100%', 'height': '100%', 'position': 'absolute', 'top': 0, 'left': 0, 'padding': Math.floor(BORDER_GAP * 0.5), 'z-index': 0 }).addClass('jts_zoom_info'); _(titleText).css({ 'height': '100%', 'margin-right': 10, 'margin-left': 10, 'padding': 7, 'font-size': 30 }).addClass('ts-hide-pp col-pl-6 col-tab-7').addClass(configuration && configuration.font_class ? configuration.font_class : 'ts-font-helvetica' ); _(previousButton).css({ 'width': UNDER_BAR_HEIGHT, 'height': '100%', 'margin-right': 10, 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.main_radius : 5, 'box-shadow' : configuration && configuration.sub_shadow ? configuration.sub_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'cursor': 'pointer', 'background-color' : configuration && configuration.buttons_background ? configuration.buttons_background : '#ebebeb', 'color' : configuration && configuration.buttons_color ? configuration.buttons_color : '#000000', 'text-align' : 'center', 'font-size' : 30, 'padding' : '13px 0px 0px 0px' }).addClass('ts-grid-fixed'); _(nextButton).css({ 'width': UNDER_BAR_HEIGHT, 'height': '100%', 'margin-right': 10, 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.main_radius : 5, 'box-shadow' : configuration && configuration.sub_shadow ? configuration.sub_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'cursor': 'pointer', 'background-color' : configuration && configuration.buttons_background ? configuration.buttons_background : '#ebebeb', 'color' : configuration && configuration.buttons_color ? configuration.buttons_color : '#000000', 'text-align' : 'center', 'font-size' : 30, 'padding' : '13px 0px 0px 0px' }).addClass('ts-grid-fixed'); _(disposeButton).css({ 'width': UNDER_BAR_HEIGHT, 'height': '100%', 'border-radius': configuration && (configuration.sub_radius || configuration.sub_radius === 0) ? configuration.main_radius : 5, 'box-shadow' : configuration && configuration.sub_shadow ? configuration.sub_shadow : '2px 2px 5px 0px rgba(0,0,0,0.3)', 'cursor': 'pointer', 'background-color' : configuration && configuration.dispose_background ? configuration.dispose_background : '#f12f0a', 'color' : configuration && configuration.dispose_color ? configuration.dispose_color : '#f1f1f1', 'text-align' : 'center', 'font-size' : 30, 'padding' : '13px 0px 0px 0px' }).addClass('ts-grid-fixed ts-grid-right'); _(containerLeft).append([leftIMG, square]); _(containerRight).append([imageInfo, imageCanvas]); _(rowUp).append([sideBar, containerLeftOuterBox, containerRightOuterBox]); _(underBar).append([previousButton, nextButton, titleText, disposeButton]); _(rowDown).append(underBar); _(innerContainer).append([rowUp, rowDown]); _(container).append(innerContainer); _('body').append(container); setSize(); setListeners(); _(sideBar).append(sideImages).scrollingLiquidBox(false,{ 'padding': 5, 'scroll_marker_background ': configuration && configuration.scroll_color ? configuration.scroll_color : 'rgba(165,165,165,0.5)', 'scroll_marker_width': 10 }); setAddedListeners(); loadInfo(); drawButtons(); function canvasDraw(x, y, z) { let mX = x - leftIMG.offsetLeft; let mY = y - leftIMG.offsetTop; let width = _(leftIMG).outerWidth(); let height = _(leftIMG).outerHeight(); let oW = sideImgElements[imageIndex].naturalWidth || sideImgElements[imageIndex].width; let oH = sideImgElements[imageIndex].naturalHeight || sideImgElements[imageIndex].height; let cropX = mX * (oW / width); let cropY = mY * (oH / height); let cropW = z * (oW / width); let cropH = z * (oH / height); _(imageCanvas).css('display', 'block'); /* CANVAS RULE : the crop pixels are stretched to CANVAS.width and CANVAS.height , after stretched to CANVAS css width and height */ brush.fillStyle = '#ffffff'; brush.clearRect(0, 0, imageCanvas.width, imageCanvas.height); brush.fillRect(0, 0, imageCanvas.width, imageCanvas.height); brush.drawImage(sideImgElements[imageIndex], cropX, cropY, cropW, cropH, 0, 0, imageCanvas.width, imageCanvas.height); } function displayInfo(info) { let index = 0; let box = document.createElement('div'); _(box).css({ 'position': 'relative', 'width': '100%', 'height': '100%', 'border': BORDER }).attr('id', 'jts_zoom_info_' + zoomID); let table = document.createElement('table'); table.cellSpacing = 0; table.cellPadding = 5; for (let n in info) { if(info.hasOwnProperty(n)){ let tr = document.createElement('tr'); let tdLeft = document.createElement('td'); let tdCenter = document.createElement('td'); let tdRight = document.createElement('td'); let value = String(info[n]); _(tdLeft).html(n).css({ 'vertical-align': 'top', 'font-size': 23 }).addClass(configuration && configuration.font_class ? configuration.font_class : 'ts-font-helvetica'); _(tdCenter).html(':').css({ 'vertical-align': 'top', 'font-size': 21 }); _(tdRight).html(value).css({ 'vertical-align': 'top', 'font-size': 16, 'font-style': 'italic', 'padding-top': 9, 'width': '100%' }); _(tr).append([tdLeft, tdCenter, tdRight]).css({ 'background-color': index % 2 == 0 ? '#f1f1f1' : '#e1e1e1' }); _(table).append(tr); index++; } } _(table).css({ 'border': 'none', }).addClass('ts-font-helvetica'); _(box).append(table); _(imageInfo).html(box); _('#jts_zoom_info_' + zoomID).scrollingLiquidBox(false,{ 'scroll_marker_background': configuration && configuration.scroll_color ? configuration.scroll_color : 'rgba(165,165,165,0.5)', 'scroll_marker_width' : 10 }); _(titleText).html(String(info.name)); } function dispose() { _(window).unbind('.jts_zoom_events_' + zoomID); _('.jts_zoom_side_img').unbind('.jts_zoom_events_' + zoomID); _(leftIMG).unbind('.jts_zoom_events_' + zoomID); _(square).unbind('.jts_zoom_events_' + zoomID); _(previousButton).unbind('.jts_zoom_events_' + zoomID); _(nextButton).unbind('.jts_zoom_events_' + zoomID); _(disposeButton).unbind('.jts_zoom_events_' + zoomID); _('.jts_zoom_side_img_container').css('box-shadow', 'none'); _(container).dispose(); } function drawButtons() { _('#jts_zoom_side_container_' + imageIndex).css('box-shadow', SIDE_HIGHLIGHTED); _(previousButton).html('').append('<i class="fa fa-step-backward"></i>'); _(nextButton).html('').append('<i class="fa fa-step-forward"></i>'); _(disposeButton).html('').append('<i class="fa fa-times-circle"></i>'); } function getInnerWidth(w) { let MARKER = [0, 415, 737, 1025, 1981, 10000]; let SIZE = [w - 65, w - 40, w - 40, w - 100, w - 200]; for (let i = 0 ; i < MARKER.length - 1 ; i++) { if (w >= MARKER[i] && w < MARKER[i + 1]) { return SIZE[i]; } } } function getSquarePos(e) { let data = {}; let x = onMobile ? e.touches[0].clientX : e.screenX; let y = onMobile ? e.touches[0].clientY : e.screenY; let container = e.target.offsetParent; while (container) { x -= container.offsetLeft; y -= container.offsetTop; container = container.offsetParent; } data.x = x; data.y = y; return data; } function gotoNextImage() { let nIndex = imageIndex; for (let i = nIndex + 1 ; i < sideImages.length ; i++) { if (sideImages[i]) { nIndex = i; break; } } if (nIndex === imageIndex) { return; } setNextImage(nIndex); setLeftIMG(); loadInfo(); } function gotoPreviousImage() { let nIndex = imageIndex; for (let i = nIndex - 1 ; i >= 0 ; i--) { if (sideImages[i]) { nIndex = i; break; } } if (nIndex === imageIndex) { return; } setNextImage(nIndex); setLeftIMG(); loadInfo(); } function loadInfo() { displayInfo(imagesInfo[imageIndex]); } function setAddedListeners() { _('.jts_zoom_side_img').bind(mousedown + '.jts_zoom_events_' + zoomID, function (e) { startMT = e.time; }); _('.jts_zoom_side_img').bind(mouseup + '.jts_zoom_events_' + zoomID, function (e) { endMT = e.time; if (endMT - startMT <= IS_CLICK) { setNextImage(parseInt(_(e.target).attr('index_ref'))); setLeftIMG(); loadInfo(); } }); _(leftIMG).bind(mouseover + '.jts_zoom_events_' + zoomID, function (e) { _(square).css('visibility', 'visible'); setSquarePos(e); _(window).bind(mouseout + '.jts_zoom_events_' + zoomID, function (e) { if (e.relatedTarget !== leftIMG && e.relatedTarget !== square) { _(window).unbind(mouseout + '.jts_zoom_events_' + zoomID); _(square).css('visibility', 'hidden'); _(imageCanvas).css('display', 'none'); } }); }); _([leftIMG, square]).bind(mousemove + '.jts_zoom_events_' + zoomID, function (e) { if (e.target === leftIMG || e.target === square) { e.preventDefault(); setSquarePos(e); } }); _(previousButton).bind('click.jts_zoom_events_' + zoomID, function (e) { gotoPreviousImage(); }); _(nextButton).bind('click.jts_zoom_events_' + zoomID, function (e) { gotoNextImage(); }); _(disposeButton).bind('click.jts_zoom_events_' + zoomID, function (e) { dispose(); }); } function setLeftIMG() { let containerW = _(containerLeft).outerWidth(); let containerH = _(containerLeft).outerHeight(); let oW = sideImgElements[imageIndex].naturalWidth || sideImgElements[imageIndex].width; let oH = sideImgElements[imageIndex].naturalHeight || sideImgElements[imageIndex].height; let data = getSizeData(containerW - BORDER_GAP, containerH - BORDER_GAP); _(leftIMG).css(data); let squareSize = data.width < SQUARE_SIZE || data.height < SQUARE_SIZE ? (data.width > data.height ? data.height : data.width) : SQUARE_SIZE; _(square).css({ 'width': squareSize, 'height': squareSize }); function getSizeData(width, height) { let data = {}; let w, h; if (oW > oH) { getHeight(width); } else { getWidth(height); } if (w > oW && h > oH) { w = oW; h = oH; } data.width = Math.round(w); data.height = Math.round(h); data.left = Math.floor((containerW * 0.5) - (w * 0.5)); data.top = Math.floor((containerH * 0.5) - (h * 0.5)); function getHeight(val) { w = val; h = oH * (w / oW); if (h > height) { getHeight(val - 1); } } function getWidth(val) { h = val; w = oW * (h / oH); if (w > width) { getWidth(val - 1); } } return data; } } function setListeners() { _(window).bind('resize.jts_zoom_events_' + zoomID, function () { setSize(); }); } function setNextImage(nIndex) { _('#jts_zoom_side_container_' + imageIndex).css('box-shadow', 'none'); imageIndex = nIndex; _('#jts_zoom_side_container_' + imageIndex).css('box-shadow', SIDE_HIGHLIGHTED); _(leftIMG).attr('src', srcDB[imageIndex]); } function setSize() { let w = _(window).width(); let h = _(window).height(); _(container).css({ 'width': w, 'height': h }); let innerW = getInnerWidth(w); _(innerContainer).css({ 'width': innerW, 'left': (w * 0.5) - (innerW * 0.5) }); _([sideBar, containerLeft, containerRight]).css('height', _(containerLeft).outerWidth()); setLeftIMG(); imageCanvas.width = _(containerRight).outerWidth() * dpr; imageCanvas.height = _(containerRight).outerHeight() * dpr; let innerY = (h * 0.5) - (_(innerContainer).outerHeight() * 0.5); _(innerContainer).css('top', innerY); /*this should solve side handle issues*/ setTimeout(function () { _(window).emits(jTS.built_in_events.jLIQUID_BOX_RESIZE); }, RESIZE_DELAY); } function setSquarePos(e) { let squarePos = getSquarePos(e); let squareSize = _(square).outerWidth(); let x = squarePos.x - (squareSize * 0.5); let y = squarePos.y - (squareSize * 0.5); let leftBound = leftIMG.offsetLeft; let rightBound = leftBound + _(leftIMG).outerWidth(); let topBound = leftIMG.offsetTop; let bottomBound = topBound + _(leftIMG).outerHeight(); x = x < leftBound ? leftBound : (x + squareSize > rightBound ? rightBound - squareSize : x); y = y < topBound ? topBound : (y + squareSize > bottomBound ? bottomBound - squareSize : y); _(square).css({ 'left': x, 'top': y }); canvasDraw(x, y, squareSize); } } return this; }; /*END TOOLS PACKAGE*/ /*TRAVERSING PACKAGE*/ /** * * @param callback {Function} * @return {jTS} */ jTS.fn.each = /*jTS Object*/ function (/*Function*/ callback) { const t = this; loop(0); function loop(index) { if (index < t.length) { callback(index, t[index]); loop(index + 1); } } return this; }; /** * * @return {jTS} */ jTS.fn.even = /*jTS*/function () { const t = this; let e = []; t.each(filter); function filter(index, element) { if ((index + 1) % 2 === 0) { e.push(element); } } return _(e); }; /** * * @return {Object} */ jTS.fn.elementGlobalPosition = /*Object literal*/function(){ let parent = this; let x = 0; let y = 0; while(parent[0] !== document && parent[0] !== window){ if(!parent.hasClass('row')){ x += parent[0].offsetLeft + parseInt(parent.css('border-left-width')); y += parent[0].offsetTop + parseInt(parent.css('border-top-width')); } parent = parent.offsetPs(); } return {x : x , y : y}; }; /** * * @param x {int} * @param y {int} * @return {Object} */ jTS.fn.globalToLocalPoint =/*Object literal*/ function(/*int*/x,/*int*/y){ let parent = this; while(parent[0] !== document && parent[0] !== window ){ if(!parent.hasClass('row')){ x -= parent[0].offsetLeft; y -= parent[0].offsetTop; } parent = parent.offsetPs(); } return { x : x , y : y}; }; /** * * @return {jTS} */ jTS.fn.odd = /*jTS*/function () { const t = this; let e = []; t.each(filter); function filter(index, element) { if ((index + 1) % 2 !== 0) { e.push(element); } } return _(e); }; /** * * @return {jTS} */ jTS.fn.offsetPs = /*jTS*/function () { const t = this; let jTSObject = []; t.each(function (i, e) { let flag = false; let parent = e === document.querySelector('body') ? document.querySelector('html') : e.parentNode; if (parent == null) { flag = true; } for (let h = 0 ; h < jTSObject.length; h++) { if (jTSObject[h] === parent) { flag = true; break; } } if (!flag) { jTSObject.push(parent); } }); return _(jTSObject); }; /*END TRAVERSING PACKAGE*/ /*HELPERS SECTION*/ jTS.boolean = { "value_attribute": [ 'active', 'async', /*'autocomplete',*/ 'autofocus', 'autoplay', 'checked', 'compact', 'contenteditable', 'controls', 'default', 'defer', 'disabled', 'enabled', 'expanded', 'formNoValidate', 'frameborder', 'hidden', 'indeterminate', 'ismap', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'readonly', 'required', 'reversed', 'scoped', 'scrolling', 'seamless', 'selected', 'sortable', 'spellcheck', 'translate' ] }; jTS.built_in_events = { 'jANIMATE_PAUSE' : 'jAnimate_pause', 'jANIMATE_RESUME' : 'jAnimate_resume', 'jCOLOR_PICKER_UPDATED' : 'jColor_picker_updated', 'jCROPPER_DONE' : 'jCropper_done', 'jCROPPER_ONLY_CLOSED' : 'jCropper_only_closed', 'jEXTERNAL_RESIZE' : 'jExternal_resize', 'jLIQUID_BOX_RESIZE' : 'jLiquid_box_resize', 'jMASONRY_READY' : 'jMasonry_ready', 'jMASONRY_RESIZE' : 'jMasonry_resize', 'jPAGINATION_FILTER_SORT_ITEMS' : 'jPagination_filter_sort_items', 'jPAGINATION_PAGE_CHANGE' : 'jPagination_page_change', 'jPAGINATION_UPDATE_ITEMS' : 'jPagination_update_items', 'jPARTICLES_FX_READY' : 'jParticles_fx_ready', 'jREQUEST_END_EVENT' : 'jRequest_end_event', 'jREQUEST_PROGRESS_EVENT' : 'jRequest_progress_event', 'jREQUEST_START_EVENT' : 'jRequest_start_event', 'jSHELL_RESIZE' : 'jShell_resize', 'jSHOWCASE_ANIMATION_START' : 'jShowcase_animation_start', 'jSHOWCASE_ANIMATION_END' : 'jShowcase_animation_end', 'jSHOWCASE_CONTROLS_PRESSED' : 'jShowcase_controls_pressed', 'jSHOWCASE_READY' : 'jShowcase_ready', 'jTOUCH_SCROLL_STEP' : 'jTouch_scroll_step', 'jWORLD_MAP_LOADED' : 'jWorld_map_loaded', 'jWORLD_MAP_SET_ZOOM_AND_POSITION' : 'jWorld_map_set_position' }; jTS.cssMap = { 'align-content': 'stretch', 'align-items': 'stretch', 'align-self': 'auto', 'all': 'none', 'animation': 'composed', 'animation-delay': '0s', 'animation-direction': 'normal', 'animation-duration': '0s', 'animation-fill-mode': 'none', 'animation-iteration-count': '1', 'animation-name': 'none', 'animation-play-state': 'running', 'animation-timing-function': 'ease', 'backface-visibility': 'visible', 'background': 'composed', 'background-attachment': 'scroll', 'background-blend-mode': 'normal', 'background-clip': 'border-box', 'background-color': 'rgba(255,255,255,0)', 'background-image': 'none', 'background-origin': 'padding-box', 'background-position': '0% 0%', 'background-repeat': 'repeat', 'background-size': 'auto', 'border': 'composed', 'border-bottom': 'composed', 'border-bottom-color': 'rgb(255,255,255)', 'border-bottom-left-radius': '0px', 'border-bottom-right-radius': '0px', 'border-bottom-style': 'none', 'border-bottom-width': '0px', 'border-collapse': 'separate', 'border-color': 'rgb(255,255,255)', 'border-image': 'none', 'border-image-outset': '0', 'border-image-repeat': 'stretch', 'border-smage-slice': '100%', 'border-smage-source': 'none', 'border-image-width': '1', 'border-left': 'composed', 'border-left-color': 'rgb(255,255,255)', 'border-left-style': 'none', 'border-left-width': '0px', 'border-radius': '0px', 'border-right': 'composed', 'border-right-color': 'rgb(255,255,255)', 'border-right-style': 'none', 'border-right-width': '0px', 'border-spacing': '2px', 'border-style': 'none', 'border-top': 'composed', 'border-top-color': 'rgb(255,255,255)', 'border-top-left-radius': '0px', 'border-top-right-radius': '0px', 'border-top-style': 'none', 'border-top-width': '0px', 'border-width': '0px', 'box-decoration-break': 'slice', 'box-shadow': 'none', 'box-sizing': 'content-box', 'caption-side': 'top', 'caret-color': 'auto', 'clear': 'none', 'clip': 'auto', 'color': 'auto', 'column-count': 'auto', 'column-fill': 'balance', 'column-gap': 'normal', 'column-rule': 'composed', 'column-rule-color': 'rgb(255,255,255)', 'column-rule-style': 'none', 'column-rule-width': '0px', 'column-span': 'none', 'column-width': 'auto', 'columns': 'auto auto', 'content': 'normal', 'counter-increment': 'none', 'counter-reset': 'none', 'cursor': 'auto', 'direction': 'ltr', 'display': 'auto', 'empty-cells': 'show', 'filter': 'none', 'flex': 'composed', 'flex-basis': 'auto', 'flex-direction': 'row', 'flex-flow': 'row nowrap', 'flex-grow': '1', 'flex-shrink': '1', 'flax-wrap': 'nowrap', 'float': 'none', 'font': 'composed', 'font-family': 'auto', 'font-kerning': 'auto', 'font-size': 'medium', 'font-size-adjust': 'none', 'font-stretch': 'normal', 'font-style': 'normal', 'font-variant': 'normal', 'font-weight': 'normal', 'grid': 'composed', 'grid-area': 'composed', 'grid-auto-columns': 'auto', 'grid-auto-flow': 'row', 'grid-auto-rows': 'auto', 'grid-column': 'composed', 'grid-column-end': 'auto', 'grid-column-gap': '0', 'grid-column-start': 'auto', 'grid-gap': 'composed', 'grid-row': 'composed', 'grid-row-end': 'auto', 'grid-row-gap': '0', 'grid-row-start': 'auto', 'grid-template': 'composed', 'grid-template-areas': 'none', 'grid-template-columns': 'none', 'grid-template-rows': 'none', 'hanging-puntuaction': 'none', 'justify-content': 'flex-start', 'letter-spacing': 'normal', 'line-height': 'normal', 'line-style': 'composed', 'line-style-image': 'none', 'line-style-position': 'outside', 'line-style-type': 'disc', 'margin-bottom': '0px', 'margin-left': '0px', 'margin-right': '0px', 'margin-top': '0px', 'max-height': 'none', 'max-width': 'none', 'min-height': 'none', 'min-width': 'none', 'object-fit': 'fill', 'opacity': '1', 'order': '0', 'otuline': 'composed', 'outline-color': 'invert', 'outline-offset': '0', 'outline-style': 'none', 'outline-width': '0px', 'overflow': 'visible', 'overflow-x': 'visible', 'overflow-y': 'visible', 'padding-bottom': '0px', 'padding-left': '0px', 'padding-right': '0px', 'padding-top': '0px', 'page-break-after': 'auto', 'page-break-before': 'auto', 'page-break-inside': 'auto', 'perspective': 'none', 'perspective-origin': '50% 50%', 'pointer-events': 'auto', 'position': 'static', 'quotes': 'none', 'resize': 'none', 'tab-size': '8', 'table-layout': 'auto', 'text-align': 'left', 'text-align-last': 'auto', 'text-decoration': 'composed', 'text-decoration-color': 'rgb(255,255,255)', 'text-decoration-line': 'none', 'text-decoration-style': 'solid', 'text-indent': '0', 'text-justify': 'auto', 'text-overflow': 'clip', 'text-shadow': 'none', 'text-transform': 'none', 'transform': 'none', 'transform-origin': '50% 50% 0', 'transform-style': 'flat', 'transition': 'composed', 'transition-delay': '0s', 'transition-duration': '0s', 'transition-property': 'all', 'transition-timing-function': 'ease', 'unicode-bidi': 'normal', 'user-select': 'auto', 'vertical-align': 'baseline', 'visibility': 'visible', 'white-space': 'normal', 'word-break': 'normal', 'word-spacing': 'normal', 'word-wrap': 'normal', 'z-index': 'auto' }; jTS.flow = { "clearFlow": function () { for (let n in jTS.flow.listeners) { if(jTS.flow.listeners.hasOwnProperty(n)){ if (jTS.flow.listeners[n].length === 0) { delete jTS.flow.listeners[n]; } } } }, "events" : {}, "Event" : function (e, listener, data) { let t = this; this.changedTouches = e.changedTouches; this.ctrlKey = e.ctrlKey; this.currentTarget = listener.element; this.data = data; this.elementSetIndex = listener.index; this.globalX = e.pageX; this.globalY = e.pageY; this.keyCode = e.keyCode; this.localX = e.offsetX; this.localY = e.offsetY; this.originalEvent = e; this.relatedTarget = e.relatedTarget; this.screenX = e.clientX || e.x; this.screenY = e.clientY || e.y; this.shiftKey = e.shiftKey; this.target = e.target; this.time = new Date().getTime(); this.type = e.type; this.touches = e.touches; this.preventDefault = function () { e.preventDefault(); }; this.stopImmediatePropagation = function () { e.stopImmediatePropagation(); e.immediatePropS = true; }; this.stopPropagation = function () { e.stopPropagation(); e.propagationStopped = true; e.propagationSO = listener.element; }; this.isDefaultPrevented = function () { return e.defaultPrevented; }; this.isImmediatePropagationStopped = function () { return e.immediatePropS; }; this.isPropagationStopped = function () { return e.propagationStopped; }; if (e.type === 'touchstart') { if (e.touches[0]) { t.globalX = e.touches[0].pageX; t.globalY = e.touches[0].pageY; t.screenX = e.touches[0].clientX; t.screenY = e.touches[0].clientY; let localCoordinates = _(t.target).globalToLocalPoint(t.globalX,t.globalY); t.localX = localCoordinates.x; t.localY = localCoordinates.y; } }else if(e.type === 'touchmove'){ if (e.touches[0]) { t.globalX = e.touches[0].pageX; t.globalY = e.touches[0].pageY; t.screenX = e.touches[0].clientX; t.screenY = e.touches[0].clientY; let localCoordinates = _(t.target).globalToLocalPoint(t.globalX,t.globalY); t.localX = localCoordinates.x; t.localY = localCoordinates.y; } }else if(e.type === 'touchend'){ if (e.changedTouches[0]) { t.globalX = e.changedTouches[0].pageX; t.globalY = e.changedTouches[0].pageY; t.screenX = e.changedTouches[0].clientX; t.screenY = e.changedTouches[0].clientY; let localCoordinates = _(t.target).globalToLocalPoint(t.globalX,t.globalY); t.localX = localCoordinates.x; t.localY = localCoordinates.y; } } }, "listeners" : {}, "stackIndex": {} }; jTS.jFlow = { "jListeners": [], "jEvent": function (type, emitter, currentTarget, data) { let t = this; this.type = type; this.emitter = emitter; this.currentTarget = currentTarget; this.data = data ? data : {}; }, "jStackIndex": 0, "unbindIndex": 0 }; jTS.originalStyles = []; /*END HELPERS SECTION*/
24.16764
320
0.490079
12fcaeee45e5d7729af97a6018f6c39107e37b3e
2,474
dart
Dart
lib/views/tweet_emotion_view.dart
tsukko/my-emotion-flutter
18678e81546dbedf3c144c695903da518ebd62e7
[ "BSD-3-Clause" ]
null
null
null
lib/views/tweet_emotion_view.dart
tsukko/my-emotion-flutter
18678e81546dbedf3c144c695903da518ebd62e7
[ "BSD-3-Clause" ]
null
null
null
lib/views/tweet_emotion_view.dart
tsukko/my-emotion-flutter
18678e81546dbedf3c144c695903da518ebd62e7
[ "BSD-3-Clause" ]
null
null
null
import 'package:flutter/material.dart'; import '../models/my_tweet.dart'; import '../util/environment.dart'; import '../util/my_twitter_api.dart'; import '../util/sentiment_analysis.dart'; import '../util/shared_preferences_util.dart'; // ツイート文から感情分析した結果を一覧表示する画面 class TweetEmotionView extends StatefulWidget { @override _TweetEmotionViewState createState() => _TweetEmotionViewState(); } // ここを参考にする // https://qiita.com/ysato5654/items/22681aba209168f53a53 class _TweetEmotionViewState extends State<TweetEmotionView> { String _userName = ''; List<MyTweet> tweetDataList; Future<void> _readUserName() async { _userName = await SharedPreferencesUtil().getDefaultUserName(); setState(() {}); } Future<void> _sentimentAnalysis(MyTweet tweet) async { String res = await SentimentAnalysis().sentimentAnalysis(tweet.tweet); setState(() { tweet.updateSentiment(res); print("tweet sentiment: $res"); }); } Future<void> _getTweet() async { List<MyTweet> list = await MyTwitterApi().getTweet(_userName); setState(() { tweetDataList = list; list.asMap().forEach((index, tweet) => _sentimentAnalysis(tweet)); }); } @override void initState() { super.initState(); _readUserName(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(envTitle('Tweet Sentiment Analysis')), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(_userName), RaisedButton( child: new Text('Get latest tweet'), onPressed: _getTweet, ), const Divider(height: 4.0, thickness: 2.0), Expanded(child: _docList()), ], ), ); } Widget _docList() { return tweetDataList == null ? Container() : ListView.builder( itemCount: tweetDataList.length, itemBuilder: (context, index) { final item = tweetDataList[index]; return Column( children: <Widget>[ ListTile( trailing: Text(item.sentiment), title: Text(item.tweet), subtitle: Text(item.time), onTap: () {}, ), const Divider(height: 4.0, thickness: 1.0), ], ); }, ); } }
27.186813
74
0.588521
1cd83fefc7dda090afa7510dd3e4404b18142298
48,348
css
CSS
stylesheets/application.css
splendeo/ohwr-theme
a91b9a7562ae7d80744f6c876ae604fdfde971be
[ "MIT" ]
1
2016-03-24T10:04:00.000Z
2016-03-24T10:04:00.000Z
stylesheets/application.css
splendeo/ohwr-theme
a91b9a7562ae7d80744f6c876ae604fdfde971be
[ "MIT" ]
null
null
null
stylesheets/application.css
splendeo/ohwr-theme
a91b9a7562ae7d80744f6c876ae604fdfde971be
[ "MIT" ]
null
null
null
/* Fonts */ @import url(http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400|PT+Sans+Narrow:regular,bold); html { overflow-y:scroll; } body { font-family: Arial, Verdana, sans-serif; font-size: 12px; color: #505050; margin: 0 100px 100px 100px; padding: 0; min-width: 900px; background: #d7d7d7 url(../images/background.png); } /* * Headings */ h1, h2 { font-family: 'PT Sans Narrow', 'HelveticaNeue-CondensedBold', 'Helvetica Neue', Helvetica, Arial, Verdana, sans-serif; text-transform: uppercase; } .wiki h1, .wiki h2 { text-transform: none; } h3, h4, h5 { font-family: 'HelveticaNeue-CondensedBold', 'Helvetica Neue', Helvetica, Arial, Verdana, sans-serif; font-weight: normal; } h1 { font-size: 30px; } h2 { font-size: 25px; } h3 { font-size: 17px; } h4 { font-size: 15px; } h5 { font-size: 12px; } h1 a:hover, h2 a:hover, h3 a:hover, h4 a:hover, h5 a:hover { text-decoration: none; } /* * Links */ a, a:link, a:visited { color: #003264; text-decoration: none; font-weight: bold; } a:hover, a:active { text-decoration: underline; } a img{ border: 0; } a.issue.closed, a.issue.closed:link, a.issue.closed:visited { color: #999; text-decoration: line-through; } .external { background-position: 0% 60%; background-repeat: no-repeat; padding-left: 12px; background-image: url(../images/external.png); } /** * Image links replacements */ .checkbox a img { display: none; } .checkbox a { display: block; padding: 10px 0 0 0; overflow: hidden; background-image: url("../images/iconic/check_12x10.png"); background-repeat: no-repeat; height: 0px !important; height /**/:10px; } .calendar-trigger { display: inline-block; padding: 16px 0 0 0; overflow: hidden; background-image: url("../images/iconic/calendar_16x16.png"); background-repeat: no-repeat; height: 0px !important; height /**/:16px; width: 16px; } /* * Misc types */ .clear:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } /* * Forms/Input fields */ input, select { vertical-align: middle; margin-top: 1px; margin-bottom: 1px; } fieldset { border: 1px solid #e4e4e4; margin:0; } legend { color: #484848; } input[type="text"], input[type="password"], textarea { font-size: 13px; border: 1px solid #dadada; background: #bbbbbb url(../images/input-background.png) 0 top repeat-x; padding: 4px; } input[type="submit"] { font-size: 15px; font-family: 'Yanone Kaffeesatz', Arial, sans-serif; text-shadow: 0px 1px 1px white; text-transform: uppercase; border: 1px solid #bbbbbb; background: #dfdfdf url(../images/button-background.png) 0 top repeat-x; cursor: pointer; padding: 4px 15px; } input[type="text"]:focus, input[type="password"]:focus, input[type="submit"]:focus, textarea:focus { border: 1px solid #222222; background: #f1f1f1; } .required { color: #c50000; } form.tabular input[type="text"], form.tabular input[type="password"] { width: 300px; } form.tabular input[size="10"] { width: 100px; } form.tabular input[size="3"] { width: 100px; } /* * Top-menu */ #top-menu { height:1.8em; font-family: 'Yanone Kaffeesatz', Arial, sans-serif; font-weight: normal; font-size: 16px; padding: 15px 30px 10px 160px; } #top-menu a { color: #7c7c7c; font-weight: normal; } #top-menu a:hover { color: black; text-decoration: none; } #top-menu ul { margin: 0; padding: 0; text-transform: uppercase; } #top-menu li { float:left; list-style-type:none; padding: 0; } #top-menu a { float: left; margin: 0 15px 0 0; } #top-menu #loggedas, #top-menu #account { float: right; color: #bbb; } #top-menu #account a{ margin: 0 0 0 15px; } #top-menu #loggedas a { float: none; margin: 0; } #top-menu .help { position: fixed; float: none; top: 115px; left: 0; color: white; font-size: 1.5em; padding: 3px 18px 5px 18px; background-color: rgba(50,50,50,0.5); background-color: rgb(100,100,100)\9; /* ie8 hack */ * background-color: rgb(100,100,100); /* ie7 hack */ } /***** Layout *****/ #wrapper{ background: white url(../images/white-header-logo.png) 80% -100px no-repeat; box-shadow: 0px 0px 8px rgba(0,0,0,.5); -moz-box-shadow: 0px 0px 8px rgba(0,0,0,.5); -webkit-box-shadow: 0px 0px 8px rgba(0,0,0,.5); } #wrapper2{ background: transparent url(../images/header-logo.png) 25px 10px no-repeat; } #main { margin: 0 20px 10px 20px; overflow: auto; } #content { padding: 0 10px 10px 10px; } /* * Header */ #header { margin: 0; padding: 0 0 0 128px; margin: 0 30px; height: 115px; position: relative; border-bottom: 1px solid #a8a8a8; } #header h1 { color: #b4b4b4; font-size: 37px; font-weight: bold; text-shadow: 1px 1px 1px rgba(0,0,0,.7); text-transform: none; letter-spacing: 0.029em; word-spacing: -0.041em; line-height: 1.1; text-transform: uppercase; margin: 0; } #header h1 a.ancestor, #header h1 a.root { color: #444; font-size: 90%; font-weight: normal; } #quick-search { margin-top: -15px; float:right; font-size: 0.1px; color: transparent; } #quick-search input, #quick-search select { font-size: 11px; } #quick-search a { padding: 20px 0 0 0; overflow: hidden; background: transparent url("../images/iconic/magnifying_glass_alt_16x16.png") 0 3px no-repeat; height: 0px !important; height /**/:16px; width: 16px; display: inline-block; *margin-top: 16px; /* ie7 hack */ } #quick-search a, #quick-search input, #quick-search select { float: left; margin-left: 3px; } /* * Footer */ #footer { border: none; padding: 80px 0 30px 0; background: white url(../images/footer-background.png) center top no-repeat; clear: both; font-size: 0.9em; color: #aaa; text-align:center; } #footer a:hover { text-decoration: none; } /**** Main menu ****/ #main-menu { position: absolute; bottom: 0; left: 0; text-transform: uppercase; background-color: #dbdbdb; padding: 4px 2px 1px 2px; } #main-menu ul { margin: 0; padding: 0; } #main-menu li { float:left; list-style-type:none; background-color: #d7d7d7; border-style: solid; border-color: transparent #e6e6e6 transparent #bebebe; border-width: 0 1px; margin: 0 1px; padding: 0px 0px 0px 0px; } #main-menu li a { display: block; color: #707070; font-family: 'Yanone Kaffeesatz', Arial, sans-serif; font-weight: normal; font-size: 15px; text-shadow: 0px 1px 1px white; margin: 0; padding: 4px 10px 4px 10px; } #main-menu li a.selected { color: #111111; background-color: white; box-shadow: inset 0px 1px 2px rgba(0,0,0,.5); -moz-box-shadow: inset 0px 1px 2px rgba(0,0,0,.5); -webkit-box-shadow: inset 0px 1px 2px rgba(0,0,0,.5); } #main-menu li a:hover, #main-menu li a.selected:hover { background-color: #909090; color: white; text-shadow: 0px -1px 1px black; } /**** Admin menu ****/ #admin-menu ul { margin: 0; padding: 0; } #admin-menu li { margin: 0; padding: 0 0 12px 0; list-style-type:none; } #admin-menu a { background: transparent none 0% 50% no-repeat; padding: 2px 0 3px 22px; } #admin-menu a.projects { background-image: url(../images/iconic/share_16x16.png); } #admin-menu a.users { background-image: url(../images/iconic/user_16x16.png); } #admin-menu a.groups { background-image: url(../images/iconic/group_16x16.png); } #admin-menu a.roles { background-image: url(../images/iconic/key_stroke_16x16.png); } #admin-menu a.trackers { background-image: url(../images/iconic/pin_16x16.png); } #admin-menu a.issue_statuses { background-image: url(../images/iconic/pen_16x16.png); } #admin-menu a.workflows { background-image: url(../images/iconic/spin_16x16.png); } #admin-menu a.custom_fields { background-image: url(../images/iconic/custom_field_16x16.png); } #admin-menu a.enumerations { background-image: url(../images/iconic/enumerations_16x16.png); } #admin-menu a.settings { background-image: url(../images/iconic/cog_alt_16x16.png); } #admin-menu a.plugins { background-image: url(../images/iconic/sun_alt_stroke_16x16.png); } #admin-menu a.info { background-image: url(../images/iconic/question_mark_16x16.png); } #admin-menu a.server_authentication { background-image: url(../images/iconic/key_fill_16x16.png); } #admin-menu a.system-notification { background-image: url(../images/iconic/mail_16x16.png); } /**** Sidebar ****/ #sidebar{ float: right; width: 22%; position: relative; z-index: 9; padding: 0; margin: 0;} * html #sidebar{ width: 22%; } #sidebar h3{ font-size: 14px; margin-top:14px; color: #666; } #sidebar hr{ width: 100%; margin: 0 auto; height: 1px; background: #ccc; border: 0; } * html #sidebar hr{ width: 95%; position: relative; left: -6px; color: #ccc; } #sidebar .contextual { margin-right: 1em; } #main.nosidebar #sidebar{ display: none; } #main.nosidebar #content{ width: auto; border-right: 0; } /**** Content ****/ #content { width: 75%; background-color: #fff; margin: 0px; border-right: 1px solid #ddd; padding: 0px 10px 10px 10px; z-index: 10; } html>body #content { min-height: 600px; } * html body #content { height: 600px; } /* IE */ #login-form table {margin-top:5em; padding:1em; margin-left: auto; margin-right: auto; border: 2px solid #FDBF3B; background-color:#FFEBC1; } #login-form table td {padding: 6px;} #login-form label {font-weight: bold;} #login-form input#username, #login-form input#password { width: 300px; } /***** Tables *****/ table.list { border: 1px solid #e4e4e4; border-collapse: collapse; width: 100%; margin-bottom: 4px; } table.list th { background-color:#EEEEEE; padding: 4px; white-space:nowrap; } table.list td { vertical-align: top; } table.list td.id { width: 2%; text-align: center;} table.list td.checkbox { width: 15px; padding: 0px;} table.list td.buttons { width: 15%; white-space:nowrap; text-align: right; } table.list td.buttons a { padding-right: 0.6em; } table.list caption { text-align: left; padding: 0.5em 0.5em 0.5em 0; } tr.project td.name a { white-space:nowrap; } tr.project.idnt td.name span {background: url(../images/bullet_arrow_right.png) no-repeat 0 50%; padding-left: 16px;} tr.project.idnt-1 td.name {padding-left: 0.5em;} tr.project.idnt-2 td.name {padding-left: 2em;} tr.project.idnt-3 td.name {padding-left: 3.5em;} tr.project.idnt-4 td.name {padding-left: 5em;} tr.project.idnt-5 td.name {padding-left: 6.5em;} tr.project.idnt-6 td.name {padding-left: 8em;} tr.project.idnt-7 td.name {padding-left: 9.5em;} tr.project.idnt-8 td.name {padding-left: 11em;} tr.project.idnt-9 td.name {padding-left: 12.5em;} tr.issue { text-align: center; white-space: nowrap; } tr.issue td.subject, tr.issue td.category, td.assigned_to { white-space: normal; } tr.issue td.subject { text-align: left; } tr.issue td.done_ratio table.progress { margin-left:auto; margin-right: auto;} tr.issue.idnt td.subject a {background: url(../images/bullet_arrow_right.png) no-repeat 0 50%; padding-left: 16px;} tr.issue.idnt-1 td.subject {padding-left: 0.5em;} tr.issue.idnt-2 td.subject {padding-left: 2em;} tr.issue.idnt-3 td.subject {padding-left: 3.5em;} tr.issue.idnt-4 td.subject {padding-left: 5em;} tr.issue.idnt-5 td.subject {padding-left: 6.5em;} tr.issue.idnt-6 td.subject {padding-left: 8em;} tr.issue.idnt-7 td.subject {padding-left: 9.5em;} tr.issue.idnt-8 td.subject {padding-left: 11em;} tr.issue.idnt-9 td.subject {padding-left: 12.5em;} tr.entry { border: 1px solid #f8f8f8; } tr.entry td { white-space: nowrap; } tr.entry td.filename { width: 30%; } tr.entry td.size { text-align: right; font-size: 90%; } tr.entry td.revision, tr.entry td.author { text-align: center; } tr.entry td.age { text-align: right; } tr.entry.file td.filename a { margin-left: 16px; } tr span.expander {background-image: url(../images/bullet_toggle_plus.png); padding-left: 8px; margin-left: 0; cursor: pointer;} tr.open span.expander {background-image: url(../images/bullet_toggle_minus.png);} tr.changeset td.author { text-align: center; width: 15%; } tr.changeset td.committed_on { text-align: center; width: 15%; } table.files tr.file td { text-align: center; } table.files tr.file td.filename { text-align: left; padding-left: 24px; } table.files tr.file td.digest { font-size: 80%; } table.members td.roles, table.memberships td.roles { width: 45%; } tr.message { height: 2.6em; } tr.message td.subject { padding-left: 20px; } tr.message td.created_on { white-space: nowrap; } tr.message td.last_message { font-size: 80%; white-space: nowrap; } tr.message.locked td.subject { background: url(../images/iconic/lock_16x16.png) no-repeat 0 1px; } tr.message.sticky td.subject { background: url(../images/bullet_go.png) no-repeat 0 1px; font-weight: bold; } tr.version.closed, tr.version.closed a { color: #999; } tr.version td.name { padding-left: 20px; } tr.version.shared td.name { background: url(../images/iconic/link16x16.png) no-repeat 0% 70%; } tr.version td.date, tr.version td.status, tr.version td.sharing { text-align: center; } tr.user td { width:13%; } tr.user td.email { width:18%; } tr.user td { white-space: nowrap; } tr.user.locked, tr.user.registered { color: #aaa; } tr.user.locked a, tr.user.registered a { color: #aaa; } tr.wiki-page-version td.updated_on, tr.wiki-page-version td.author {text-align:center;} tr.time-entry { text-align: center; white-space: nowrap; } tr.time-entry td.subject, tr.time-entry td.comments { text-align: left; white-space: normal; } td.hours { text-align: right; font-weight: bold; padding-right: 0.5em; } td.hours .hours-dec { font-size: 0.9em; } table.plugins td { vertical-align: middle; } table.plugins td.configure { text-align: right; padding-right: 1em; } table.plugins span.name { font-weight: bold; display: block; margin-bottom: 6px; } table.plugins span.description { display: block; font-size: 0.9em; } table.plugins span.url { display: block; font-size: 0.9em; } table.list tbody tr.group td { padding: 0.8em 0 0.5em 0.3em; font-weight: bold; border-bottom: 1px solid #ccc; } table.list tbody tr.group span.count { color: #aaa; font-size: 80%; } table.list tbody tr:hover { background-color:#ffffdd; } table.list tbody tr.group:hover { background-color:inherit; } table td {padding:2px;} table p {margin:0;} .odd {background-color:#f6f7f8;} .even {background-color: #fff;} a.sort { padding-right: 16px; background-position: 100% 50%; background-repeat: no-repeat; } a.sort.asc { background-image: url(../images/sort_asc.png); } a.sort.desc { background-image: url(../images/sort_desc.png); } table.attributes { width: 100% } table.attributes th { vertical-align: top; text-align: left; } table.attributes td { vertical-align: top; } table.boards a.board, h3.comments { background: url(../images/iconic/comment_alt1_stroke_16x16.png) no-repeat 0% 50%; padding-left: 20px; } td.center {text-align:center;} h3.version { background: url(../images/package.png) no-repeat 0% 50%; padding-left: 20px; } #watchers ul {margin: 0; padding: 0;} #watchers li {list-style-type:none;margin: 0px 2px 0px 0px; padding: 0px 0px 0px 0px;} #watchers select {width: 95%; display: block;} #watchers a.delete {opacity: 0.4;} #watchers a.delete:hover {opacity: 1;} #watchers img.gravatar {vertical-align: middle;margin: 0 4px 2px 0;} .highlight { background-color: #FCFD8D;} .highlight.token-1 { background-color: #faa;} .highlight.token-2 { background-color: #afa;} .highlight.token-3 { background-color: #aaf;} .box{ padding:6px; margin-bottom: 10px; background-color:#f6f6f6; color:#505050; line-height:1.5em; border: 1px solid #e4e4e4; } div.square { border: 1px solid #999; float: left; margin: .3em .4em 0 .4em; overflow: hidden; width: .6em; height: .6em; } .splitcontentleft{float:left; width:49%;} .splitcontentright{float:right; width:49%;} form {display: inline;} hr { width: 100%; height: 1px; background: #ccc; border: 0;} blockquote { font-style: italic; border-left: 3px solid #e0e0e0; padding-left: 0.6em; margin-left: 2.4em;} blockquote blockquote { margin-left: 0;} acronym { border-bottom: 1px dotted; cursor: help; } textarea.wiki-edit { width: 99%; } li p {margin-top: 0;} div.issue {background:#ffffdd; padding:6px; margin-bottom:6px;border: 1px solid #d7d7d7;} p.breadcrumb { font-size: 0.9em; margin: 4px 0 4px 0;} p.subtitle { font-size: 0.9em; margin: -6px 0 12px 0; font-style: italic; } p.footnote { font-size: 0.9em; margin-top: 0px; margin-bottom: 0px; } div.issue div.subject div div { padding-left: 16px; } div.issue div.subject p {margin: 0; margin-bottom: 0.1em; font-size: 90%; color: #999;} div.issue div.subject>div>p { margin-top: 0.5em; } div.issue div.subject h3 {margin: 0; margin-bottom: 0.1em;} #issue_tree table.issues { border: 0; } #issue_tree td.checkbox {display:none;} fieldset.collapsible { border-width: 1px 0 0 0; font-size: 0.9em; } fieldset.collapsible.borders { border-width: 1px; } fieldset.collapsible.collapsed.borders { border-width: 1px 0 0 0; } fieldset.collapsible legend { padding-left: 16px; background: url(../images/arrow_expanded.png) no-repeat 0% 40%; cursor:pointer; } fieldset.collapsible.collapsed legend { background-image: url(../images/arrow_collapsed.png); } fieldset#date-range p { margin: 2px 0 2px 0; } fieldset#filters table { border-collapse: collapse; } fieldset#filters table td { padding: 0; vertical-align: middle; } fieldset#filters tr.filter { height: 2em; } fieldset#filters td.add-filter { text-align: right; vertical-align: top; } .buttons { font-size: 0.9em; margin-bottom: 1.4em; margin-top: 1em; } div#issue-changesets {float:right; width:45%; margin-left: 1em; margin-bottom: 1em; background: #fff; padding-left: 1em; font-size: 90%;} div#issue-changesets div.changeset { padding: 4px;} div#issue-changesets div.changeset { border-bottom: 1px solid #ddd; } div#issue-changesets p { margin-top: 0; margin-bottom: 1em;} div#activity dl, #search-results { margin-left: 2em; } div#activity dd, #search-results dd { margin-bottom: 1em; padding-left: 18px; font-size: 0.9em; } div#activity dt, #search-results dt { margin-bottom: 0px; padding-left: 20px; line-height: 18px; background-position: 0 50%; background-repeat: no-repeat; } div#activity dt.me .time { border-bottom: 1px solid #999; } div#activity dt .time { color: #777; font-size: 80%; } div#activity dd .description, #search-results dd .description { font-style: italic; } div#activity span.project:after, #search-results span.project:after { content: " -"; } div#activity dd span.description, #search-results dd span.description { display:block; color: #808080; } #search-results dd { margin-bottom: 1em; padding-left: 20px; margin-left:0px; } div#search-results-counts {float:right;} div#search-results-counts ul { margin-top: 0.5em; } div#search-results-counts li { list-style-type:none; float: left; margin-left: 1em; } dt.issue { background-image: url(../images/iconic/ticket_16x16.png); } dt.issue-edit { background-image: url(../images/iconic/ticket_edit_16x16.png); } dt.issue-closed { background-image: url(../images/iconic/ticket_checked_16x16.png); } dt.issue-note { background-image: url(../images/iconic/ticket_note_16x16.png); } dt.changeset { background-image: url(../images/iconic/cog_alt_16x16.png); } dt.news { background-image: url(../images/iconic/headphones_16x16.png); } dt.message { background-image: url(../images/iconic/comment_alt1_stroke_16x16.png); } dt.reply { background-image: url(../images/iconic/chat_alt_stroke_16x16.png); } dt.wiki-page { background-image: url(../images/iconic/pen_16x16.png); } dt.attachment { background-image: url(../images/iconic/attachment_16x16.png); } dt.document { background-image: url(../images/iconic/document_16x16.png); } dt.project { background-image: url(../images/iconic/share_16x16.png); } dt.time-entry { background-image: url(../images/iconic/clock_16x16.png); } #search-results dt.issue.closed { background-image: url(../images/iconic/ticket_checked_16x16.png); } div#roadmap .related-issues { margin-bottom: 1em; } div#roadmap .related-issues td.checkbox { display: none; } div#roadmap .wiki h1:first-child { display: none; } div#roadmap .wiki h1 { font-size: 120%; } div#roadmap .wiki h2 { font-size: 110%; } div#version-summary { float:right; width:380px; margin-left: 16px; margin-bottom: 16px; background-color: #fff; } div#version-summary fieldset { margin-bottom: 1em; } div#version-summary .total-hours { text-align: right; } table#time-report td.hours, table#time-report th.period, table#time-report th.total { text-align: right; padding-right: 0.5em; } table#time-report tbody tr { font-style: italic; color: #777; } table#time-report tbody tr.last-level { font-style: normal; color: #555; } table#time-report tbody tr.total { font-style: normal; font-weight: bold; color: #555; background-color:#EEEEEE; } table#time-report .hours-dec { font-size: 0.9em; } form .attributes { margin-bottom: 8px; } form .attributes p { padding-top: 1px; padding-bottom: 2px; } form .attributes select { min-width: 50%; } ul.projects { margin: 0; padding-left: 1em; } ul.projects.root { margin: 0; padding: 0; } ul.projects ul.projects { border-left: 3px solid #e0e0e0; } ul.projects li.root { list-style-type:none; margin-bottom: 1em; } ul.projects li.child { list-style-type:none; margin-top: 1em;} ul.projects div.root a.project { font-family: "Trebuchet MS", Verdana, sans-serif; font-weight: bold; font-size: 16px; margin: 0 0 10px 0; } .my-project { padding-left: 18px; background: url(../images/iconic/star_16x16.png) no-repeat 0 50%; } #tracker_project_ids ul { margin: 0; padding-left: 1em; } #tracker_project_ids li { list-style-type:none; } ul.properties {padding:0; font-size: 0.9em; color: #777;} ul.properties li {list-style-type:none;} ul.properties li span {font-style:italic;} .total-hours { font-size: 110%; font-weight: bold; } .total-hours span.hours-int { font-size: 120%; } .autoscroll {overflow-x: auto; padding:1px; margin-bottom: 1.2em;} #user_firstname, #user_lastname, #user_mail, #my_account_form select { width: 90%; } #workflow_copy_form select { width: 200px; } .pagination {font-size: 90%} p.pagination {margin-top:8px;} /***** Tabular forms ******/ .tabular p{ margin: 0; padding: 5px 0 8px 0; padding-left: 180px; /*width of left column containing the label elements*/ height: 1%; clear:left; } html>body .tabular p {overflow:hidden;} .tabular label{ font-weight: bold; float: left; text-align: right; margin-left: -180px; /*width of left column*/ width: 175px; /*width of labels. Should be smaller than left column to create some right margin*/ } .tabular label.floating{ font-weight: normal; margin-left: 0px; text-align: left; width: 270px; } .tabular label.block{ font-weight: normal; margin-left: 0px !important; text-align: left; float: none; display: block; width: auto; } .tabular label.inline{ float:none; margin-left: 5px !important; width: auto; } input#time_entry_comments { width: 90%;} input#openid_url { background: url(../images/openid-bg.gif) no-repeat; background-color: #fff; background-position: 0 50%; padding-left: 18px; } #preview fieldset {margin-top: 1em; background: url(../images/draft.png)} .tabular.settings p{ padding-left: 300px; } .tabular.settings label{ margin-left: -300px; width: 295px; } .tabular.settings textarea { width: 99%; } fieldset.settings label { display: block; } .parent { padding-left: 20px; } .required {color: #bb0000;} .summary {font-style: italic;} #attachments {font-size: 1em; } #attachments_fields input[type=text] {margin-left: 8px; } div.attachments { margin-top: 12px; } div.attachments p { margin:4px 0 2px 0; } div.attachments img { vertical-align: middle; } div.attachments span.author { font-size: 0.9em; color: #888; } p.other-formats { text-align: right; font-size:0.9em; color: #666; } .other-formats span + span:before { content: "| "; } a.atom { background: url(../images/iconic/rss_16x16.png) no-repeat 1px 50%; padding: 2px 0px 3px 20px; } /* Project members tab */ div#tab-content-members .splitcontentleft, div#tab-content-memberships .splitcontentleft, div#tab-content-users .splitcontentleft { width: 64% } div#tab-content-members .splitcontentright, div#tab-content-memberships .splitcontentright, div#tab-content-users .splitcontentright { width: 34% } div#tab-content-members fieldset, div#tab-content-memberships fieldset, div#tab-content-users fieldset { padding:1em; margin-bottom: 1em; } div#tab-content-members fieldset legend, div#tab-content-memberships fieldset legend, div#tab-content-users fieldset legend { font-weight: bold; } div#tab-content-members fieldset label, div#tab-content-memberships fieldset label, div#tab-content-users fieldset label { display: block; } div#tab-content-members fieldset div, div#tab-content-users fieldset div { max-height: 400px; overflow:auto; } table.members td.group { padding-left: 20px; background: url(../images/iconic/group_16x16.png) no-repeat 0% 50%; } input#principal_search, input#user_search {width:100%} * html div#tab-content-members fieldset div { height: 450px; } /***** Flash & error messages ****/ #errorExplanation, div.flash, .nodata, .warning { padding: 4px 4px 4px 30px; margin-bottom: 12px; font-size: 1.1em; border: 2px solid; } div.flash {margin-top: 8px;} div.flash.error, #errorExplanation { background: url(../images/iconic/x_alt_16x16.png) 8px 50% no-repeat; background-color: #ffe3e3; border-color: #dd0000; color: #880000; } div.flash.notice { background: url(../images/iconic/info_16x16.png) 8px 5px no-repeat; background-color: #dfffdf; border-color: #9fcf9f; color: #005f00; } div.flash.warning { background: url(../images/iconic/warning_16x16.png) 8px 5px no-repeat; background-color: #FFEBC1; border-color: #FDBF3B; color: #A6750C; text-align: left; } .nodata, .warning { text-align: center; background-color: #FFEBC1; border-color: #FDBF3B; color: #A6750C; } #errorExplanation ul { font-size: 0.9em;} #errorExplanation h2, #errorExplanation p { display: none; } /***** Ajax indicator ******/ #ajax-indicator { position: absolute; /* fixed not supported by IE */ background-color:#eee; border: 1px solid #bbb; top:35%; left:40%; width:20%; font-weight:bold; text-align:center; padding:0.6em; z-index:100; filter:alpha(opacity=50); opacity: 0.5; } html>body #ajax-indicator { position: fixed; } #ajax-indicator span { background-position: 0% 40%; background-repeat: no-repeat; background-image: url(../images/loading.gif); padding-left: 26px; vertical-align: bottom; } /***** Calendar *****/ table.cal {border-collapse: collapse; width: 100%; margin: 0px 0 6px 0;border: 1px solid #d7d7d7;} table.cal thead th {width: 14%; background-color:#EEEEEE; padding: 4px; } table.cal thead th.week-number {width: auto;} table.cal tbody tr {height: 100px;} table.cal td {border: 1px solid #d7d7d7; vertical-align: top; font-size: 0.9em;} table.cal td.week-number { background-color:#EEEEEE; padding: 4px; border:none; font-size: 1em;} table.cal td p.day-num {font-size: 1.1em; text-align:right;} table.cal td.odd p.day-num {color: #bbb;} table.cal td.today {background:#ffffdd;} table.cal td.today p.day-num {font-weight: bold;} table.cal .starting a, p.cal.legend .starting {background: url(../images/bullet_go.png) no-repeat -1px -2px; padding-left:16px;} table.cal .ending a, p.cal.legend .ending {background: url(../images/bullet_end.png) no-repeat -1px -2px; padding-left:16px;} table.cal .starting.ending a, p.cal.legend .starting.ending {background: url(../images/bullet_diamond.png) no-repeat -1px -2px; padding-left:16px;} p.cal.legend span {display:block;} /***** Tooltips ******/ .tooltip{position:relative;z-index:24;} .tooltip:hover{z-index:25;color:#000;} .tooltip span.tip{display: none; text-align:left;} div.tooltip:hover span.tip{ display:block; position:absolute; top:12px; left:24px; width:270px; border:1px solid #555; background-color:#fff; padding: 4px; font-size: 0.8em; color:#505050; } /***** Progress bar *****/ table.progress { border: 1px solid #D7D7D7; border-collapse: collapse; border-spacing: 0pt; empty-cells: show; text-align: center; float:left; margin: 1px 6px 1px 0px; } table.progress td { height: 0.9em; } table.progress td.closed { background: #BAE0BA none repeat scroll 0%; } table.progress td.done { background: #DEF0DE none repeat scroll 0%; } table.progress td.open { background: #FFF none repeat scroll 0%; } p.pourcent {font-size: 80%;} p.progress-info {clear: left; font-style: italic; font-size: 80%;} /***** Tabs *****/ #content .tabs {height: 2.6em; margin-bottom:1.2em; position:relative; overflow:hidden;} #content .tabs ul {margin:0; position:absolute; bottom:0; padding-left:1em; width: 2000px; border-bottom: 1px solid #bbbbbb;} #content .tabs ul li { float:left; list-style-type:none; white-space:nowrap; margin-right:8px; background:#fff; position:relative; margin-bottom:-1px; } #content .tabs ul li a{ display:block; font-size: 0.9em; text-decoration:none; line-height:1.3em; padding:4px 6px 4px 6px; border: 1px solid #ccc; border-bottom: 1px solid #bbbbbb; background-color: #eeeeee; color:#777; font-weight:bold; } #content .tabs ul li a:hover { background-color: #ffffdd; text-decoration:none; } #content .tabs ul li a.selected { background-color: #fff; border: 1px solid #bbbbbb; border-bottom: 1px solid #fff; } #content .tabs ul li a.selected:hover { background-color: #fff; } div.tabs-buttons { position:absolute; right: 0; width: 48px; height: 24px; background: white; bottom: 0; border-bottom: 1px solid #bbbbbb; } button.tab-left, button.tab-right { font-size: 0.9em; cursor: pointer; height:24px; border: 1px solid #ccc; border-bottom: 1px solid #bbbbbb; position:absolute; padding:4px; width: 20px; bottom: -1px; } button.tab-left { right: 20px; background: #eeeeee url(../images/bullet_arrow_left.png) no-repeat 50% 50%; } button.tab-right { right: 0; background: #eeeeee url(../images/bullet_arrow_right.png) no-repeat 50% 50%; } /***** Auto-complete *****/ div.autocomplete { position:absolute; width:400px; margin:0; padding:0; } div.autocomplete ul { list-style-type:none; margin:0; padding:0; } div.autocomplete ul li { list-style-type:none; display:block; margin:-1px 0 0 0; padding:2px; cursor:pointer; font-size: 90%; border: 1px solid #ccc; border-left: 1px solid #ccc; border-right: 1px solid #ccc; background-color:white; } div.autocomplete ul li.selected { background-color: #ffb;} div.autocomplete ul li span.informal { font-size: 80%; color: #aaa; } #parent_issue_candidates ul li {width: 500px;} #related_issue_candidates ul li {width: 500px;} /***** Diff *****/ .diff_out { background: #fcc; } .diff_in { background: #cfc; } /***** Wiki *****/ div.wiki table { border: 1px solid #505050; border-collapse: collapse; margin-bottom: 1em; } div.wiki table, div.wiki td, div.wiki th { border: 1px solid #bbb; padding: 4px; } div.wiki a.new { color: #b73535; } div.wiki pre { margin: 1em 1em 1em 1.6em; padding: 2px 2px 2px 0; background-color: #fafafa; border: 1px solid #dadada; width:auto; overflow-x: auto; overflow-y: hidden; } div.wiki ul.toc { background-color: #ffffdd; border: 1px solid #e4e4e4; padding: 4px; line-height: 1.2em; margin-bottom: 12px; margin-right: 12px; margin-left: 0; display: table } * html div.wiki ul.toc { width: 50%; } /* IE6 doesn't autosize div */ div.wiki ul.toc {font-size: 0.8em;} div.wiki ul.toc.right { float: right; margin-left: 12px; margin-right: 0; width: auto; } div.wiki ul.toc.left { float: left; margin-right: 12px; margin-left: 0; width: auto; } div.wiki ul.toc ul { margin: 0; padding: 0; } div.wiki ul.toc li { list-style-type:none; margin: 0;} div.wiki ul.toc li li { margin-left: 1.5em; } div.wiki ul.toc a { font-weight: normal; text-decoration: none; color: #606060; } div.wiki ul.toc a:hover { color: #c61a1a; text-decoration: underline;} a.wiki-anchor { display: none; margin-left: 6px; text-decoration: none; } a.wiki-anchor:hover { color: #aaa !important; text-decoration: none; } h1:hover a.wiki-anchor, h2:hover a.wiki-anchor, h3:hover a.wiki-anchor { display: inline; color: #ddd; } div.wiki img { vertical-align: middle; } /***** My page layout *****/ .block-receiver { border:1px dashed #c0c0c0; margin-bottom: 20px; padding: 15px 0 15px 0; } .mypage-box { margin:0 0 20px 0; color:#505050; line-height:1.5em; } .handle { cursor: move; } a.close-icon { display:block; margin-top:3px; overflow:hidden; width:12px; height:12px; background-repeat: no-repeat; cursor:pointer; background-image:url('../images/close.png'); } a.close-icon:hover { background-image:url('../images/close_hl.png'); } /***** Gantt chart *****/ .gantt_hdr { position:absolute; top:0; height:16px; border-top: 1px solid #c0c0c0; border-bottom: 1px solid #c0c0c0; border-right: 1px solid #c0c0c0; text-align: center; overflow: hidden; } .gantt_subjects { font-size: 0.8em; } .task { position: absolute; height:8px; font-size:0.8em; color:#888; padding:0; margin:0; line-height:0.8em; white-space:nowrap; } .task.label {width:100%;} .task.label.project, .task.label.version { font-weight: bold; } .task_late { background:#f66 url(../images/task_late.png); border: 1px solid #f66; } .task_done { background:#00c600 url(../images/task_done.png); border: 1px solid #00c600; } .task_todo { background:#aaa url(../images/task_todo.png); border: 1px solid #aaa; } .task_todo.parent { background: #888; border: 1px solid #888; height: 3px;} .task_late.parent, .task_done.parent { height: 3px;} .task.parent.marker.starting { position: absolute; background: url(../images/task_parent_end.png) no-repeat 0 0; width: 8px; height: 16px; margin-left: -4px; left: 0px; top: -1px;} .task.parent.marker.ending { position: absolute; background: url(../images/task_parent_end.png) no-repeat 0 0; width: 8px; height: 16px; margin-left: -4px; right: 0px; top: -1px;} .version.task_late { background:#f66 url(../images/milestone_late.png); border: 1px solid #f66; height: 2px; margin-top: 3px;} .version.task_done { background:#00c600 url(../images/milestone_done.png); border: 1px solid #00c600; height: 2px; margin-top: 3px;} .version.task_todo { background:#fff url(../images/milestone_todo.png); border: 1px solid #fff; height: 2px; margin-top: 3px;} .version.marker { background-image:url(../images/version_marker.png); background-repeat: no-repeat; border: 0; margin-left: -4px; margin-top: 1px; } .project.task_late { background:#f66 url(../images/milestone_late.png); border: 1px solid #f66; height: 2px; margin-top: 3px;} .project.task_done { background:#00c600 url(../images/milestone_done.png); border: 1px solid #00c600; height: 2px; margin-top: 3px;} .project.task_todo { background:#fff url(../images/milestone_todo.png); border: 1px solid #fff; height: 2px; margin-top: 3px;} .project.marker { background-image:url(../images/project_marker.png); background-repeat: no-repeat; border: 0; margin-left: -4px; margin-top: 1px; } .version-behind-schedule a, .issue-behind-schedule a {color: #f66914;} .version-overdue a, .issue-overdue a, .project-overdue a {color: #f00;} /***** Icons *****/ .icon { background-position: 0% 50%; background-repeat: no-repeat; padding-left: 20px; padding-top: 2px; padding-bottom: 3px; } .icon-add { background-image: url(../images/iconic/plus_alt_16x16.png); } .icon-edit { background-image: url(../images/iconic/pen_16x16.png); } .icon-copy { background-image: url(../images/iconic/copy_16x16.png); } .icon-duplicate { background-image: url(../images/iconic/duplicate_16x16.png); } .icon-del { background-image: url(../images/iconic/trash_stroke_16x16.png); } .icon-move { background-image: url(../images/iconic/move_16x16.png); } .icon-save { background-image: url(../images/iconic/save_16x16.png); } .icon-cancel { background-image: url(../images/iconic/x_alt_16x16.png); } .icon-multiple { background-image: url(../images/table_multiple.png); } .icon-folder { background-image: url(../images/iconic/folder_stroke_16x16.png); } .open .icon-folder { background-image: url(../images/iconic/folder_open_16x16.png); } .icon-package { background-image: url(../images/iconic/box_16x16.png); } .icon-user { background-image: url(../images/iconic/user_16x16.png); } .icon-projects { background-image: url(../images/iconic/share_16x16.png); } .icon-help { background-image: url(../images/iconic/question_mark_16x16.png); } .icon-attachment { background-image: url(../images/iconic/attachment_16x16.png); } .icon-history { background-image: url(../images/iconic/movie_16x16.png); } .icon-time { background-image: url(../images/iconic/clock_16x16.png); } .icon-time-add { background-image: url(../images/iconic/clock_add_16x16.png); } .icon-stats { background-image: url(../images/iconic/bars_16x16.png); } .icon-warning { background-image: url(../images/iconic/warning_16x16.png); } .icon-fav { background-image: url(../images/iconic/star_16x16.png); } .icon-fav-off { background-image: url(../images/iconic/star_off_16x16.png); } .icon-reload { background-image: url(../images/iconic/spin_16x16.png); } .icon-lock { background-image: url(../images/iconic/lock_16x16.png); } .icon-unlock { background-image: url(../images/iconic/unlock_16x16.png); } .icon-checked { background-image: url(../images/iconic/check_16x16.png); } .icon-details { background-image: url(../images/iconic/magnifying_glass_alt_16x16.png); } .icon-report { background-image: url(../images/iconic/book_16x16.png); } .icon-comment { background-image: url(../images/iconic/comment_alt1_stroke_16x16.png); } .icon-summary { background-image: url(../images/iconic/bolt_16x16.png); } .icon-server-authentication { background-image: url(../images/iconic/key_fill_16x16.png); } .icon-issue { background-image: url(../images/iconic/ticket_16x16.png); } .icon-zoom-in { background-image: url(../images/iconic/zoom_in_16x16.png); } .icon-zoom-out { background-image: url(../images/iconic/zoom_out_16x16.png); } .icon-file { background-image: url(../images/files/default.png); } .icon-file.text-plain { background-image: url(../images/files/text.png); } .icon-file.text-x-c { background-image: url(../images/files/c.png); } .icon-file.text-x-csharp { background-image: url(../images/files/csharp.png); } .icon-file.text-x-php { background-image: url(../images/files/php.png); } .icon-file.text-x-ruby { background-image: url(../images/files/ruby.png); } .icon-file.text-xml { background-image: url(../images/files/xml.png); } .icon-file.image-gif { background-image: url(../images/files/image.png); } .icon-file.image-jpeg { background-image: url(../images/files/image.png); } .icon-file.image-png { background-image: url(../images/files/image.png); } .icon-file.image-tiff { background-image: url(../images/files/image.png); } .icon-file.application-pdf { background-image: url(../images/files/pdf.png); } .icon-file.application-zip { background-image: url(../images/files/zip.png); } .icon-file.application-x-gzip { background-image: url(../images/files/zip.png); } img.gravatar { padding: 2px; border: solid 1px #d5d5d5; background: #fff; } div.issue img.gravatar { float: right; margin: 0 0 0 1em; padding: 5px; } div.issue table img.gravatar { height: 14px; width: 14px; padding: 2px; float: left; margin: 0 0.5em 0 0; } h2 img.gravatar { padding: 3px; margin: -2px 4px -4px 0; vertical-align: top; } h4 img.gravatar { padding: 3px; margin: -6px 0 -4px 0; vertical-align: top; } td.username img.gravatar { margin: 0 0.5em 0 0; vertical-align: top; } #activity dt img.gravatar { float: left; margin: 0 1em 1em 0; } /* Used on 12px Gravatar img tags without the icon background */ .icon-gravatar { float: left; margin-right: 4px; } #activity dt, .journal { clear: left; } .journal-link { float: right; } h2 img { vertical-align:middle; } .hascontextmenu { cursor: context-menu; } /***** Media print specific styles *****/ @media print { #top-menu, #header, #main-menu, #sidebar, #footer, .contextual, .other-formats { display:none; } #main { background: #fff; } #content { width: 99%; margin: 0; padding: 0; border: 0; background: #fff; overflow: visible !important;} #wiki_add_attachment { display:none; } .hide-when-print { display: none; } } /* * Contextual menu */ .contextual { float:right; white-space: nowrap; line-height:1.4em; font-size:0.9em; *float: none; /* ie7 hack */ } .controller-account #content > .contextual:first-child, .controller-projects #content > .contextual:first-child, .controller-activities #content > .contextual:first-child, .controller-issues #content > .contextual:first-child, .controller-timelog #content > .contextual:first-child, .controller-gantts #content > .contextual:first-child, .controller-calendars #content > .contextual:first-child, .controller-news #content > .contextual:first-child, .controller-documents #content > .contextual:first-child, .controller-files #content > .contextual:first-child, .controller-search #content > .contextual:first-child, .controller-admin #content > .contextual:first-child, .controller-companies #content > .contextual:first-child, .controller-licenses #content > .contextual:first-child, .controller-license_versions #content > .contextual:first-child { padding: 4px 0; margin-top:90px; *margin-top: 0; /* ie7 hack */ background-color: rgba(255,255,255,.8); background-color: white\9; /* ie8 hack */ } .controller-wiki #content > .contextual:first-child { padding: 0; margin: 0; background-color: transparent; } .contextual a, .contextual input, .contextual select { margin: 4px; } .contextual input, .contextual select {font-size:0.9em;} .message .contextual { margin-top: 0; } /* * Home */ .controller-welcome #header { border: none; } .controller-welcome .splitcontentleft { width: 67%; } .controller-welcome .splitcontentright { width: 30%; } .controller-welcome a.wiki-anchor { display: none; } .controller-welcome #projects a, .controller-welcome #welcome, #featured-projects-title { margin: 0 0 10px 0; padding: 0 0 0 5px; display: block; color: white; font-family: 'Yanone Kaffeesatz', Arial, sans-serif; font-weight: normal; font-size: 20px; text-transform: uppercase; background: transparent url(../images/home-featured-projects-title-background.png) 0 0 repeat-x; height: 25px; } #featured-projects-list h4 a { font-weight: normal; } #featured-projects-list .date { font-weight: normal; font-size: 70%; } .controller-welcome #projects { padding: 0; margin-bottom: 30px; margin-top: 0;} .controller-welcome #projects a:hover { text-decoration: none;} .controller-welcome #projects a { background: transparent url(../images/home-projects-banner.png) -15px 0 repeat-x; height: 112px; } .controller-welcome #welcome { background: transparent url(../images/home-welcome-background.png) 0 0 repeat-x; height: 112px; } .controller-welcome .box { border: none; background: none; } #featured-projects-box { border: 1px solid #a8a8a8; background: none; } #featured-projects-list { padding-left: 5px; } #featured-projects-list li { list-style-type: none; } #featured-projects-list h4 { margin: 5px 0 0 0; } #featured-projects-list .date { text-size: 60%; font-weight: bold; } .controller-welcome .news { margin-top: 25px; padding-top: 25px; border-top: 1px solid #a8a8a8; } div.news h3 { background: none; padding: 0; } /* * News box */ .news.box p { margin-top: 0; margin-bottom: 0.5em; } .news.box hr { margin: 1em 0; } /* * Page headers for some specific controllers */ .controller-account #content > h2, .controller-projects #content > h2, .controller-activities #content > h2, .controller-issues #content > h2, .controller-timelog #content > h2, .controller-gantts #content > h2, .controller-calendars #content > h2, .controller-news #content > h2, .controller-documents #content > h2, .controller-files #content > h2, .controller-search #content > h2, .controller-admin #content > h2, .controller-companies #content > h2, .controller-licenses #content > h2, .controller-license_versions #content > h2{ margin: 0 0 10px 0; padding: 0 0 0 5px; display: block; color: white; font-family: 'Yanone Kaffeesatz', Arial, sans-serif; font-weight: normal; font-size: 20px; text-transform: uppercase; height: 112px; background-color: transparent; background-position: -15px 0; background-repeat: repeat-x; background-image: url(../images/projects-header-background.png); } .controller-account #content > h2 { background-image: url(../images/account-header-background.png); } .controller-projects.action-index #content > h2 { background-image: url(../images/projects-index-header-background.png); } .controller-activities #content > h2, .controller-issues #content > h2, .controller-projects.action-settings #content > h2{ background-image: url(../images/activities-header-background.png); } .controller-timelog #content > h2, .controller-gantts #content > h2, .controller-calendars #content > h2{ background-image: url(../images/time-header-background.png); } .controller-news #content > h2, .controller-documents #content > h2, .controller-files #content > h2 { background-image: url(../images/news-header-background.png); } .controller-search #content > h2 { background-image: url(../images/search-header-background.png); } /* * Login */ #login-form table { border: none; background: none; } .controller-account .box { border: none; background: none; width: 800px; margin: auto; } #user_firstname, #user_lastname, #user_mail, #my_account_form select { width: 300px; } .controller-account.action-register form.tabular input[type='submit'] { display: block; width: 130px; margin: 25px auto 50px auto; } .controller-account.action-register form.tabular p { padding: 5px 0 8px 226px; } /* * Projet#index */ .controller-projects.action-index .splitcontentleft { width: 60%; } .controller-projects.action-index .splitcontentright { width: 36%; } .controller-projects.action-index fieldset { padding: 5px 0; } .controller-projects.action-index li.root { border-bottom: 1px solid #a8a8a8; } .controller-projects.action-index #featured-projects-box li.root { border-bottom: none; } .controller-projects.action-index #content p { float: left; } .controller-projects.action-index #content p.other-formats { float: right; } .controller-projects.action-index #content .projects p { float: none; } ul.projects div.root a.project { font-weight: normal; font-family: 'HelveticaNeue-CondensedBold', 'Helvetica Neue', Helvetica, Arial, Verdana, sans-serif; } /* * Project(rest of pages) */ .controller-projects.action-show .issues ul{ margin: 0; padding: 0; } .controller-projects.action-show .issues li{ display: inline; list-style-type: none; margin: 0 15px 0 0; } .controller-projects.action-show .issues p{ display: none; } .controller-projects.action-show .box { border: none; background: none; padding: 0; margin: 30px 0; } .controller-projects.action-show .splitcontentleft, .controller-projects.action-show .splitcontentright { width: auto; float: none; } .controller-projects.action-show .members { background: transparent url(../images/projects-show-members-background.png) 0 32px no-repeat; min-height: 160px; } .controller-projects.action-show .members p { margin-left: 180px; } /* * Custom fields */ .custom_field span { display: none; } i.boolean_true { height: 16px; width: 16px; display: inline-block; background: no-repeat url(../images/iconic/check_16x16.png); } /* * Error explanation */ #content .errorExplanation h2 { font-family: 'PT Sans Narrow', 'HelveticaNeue-CondensedBold', 'Helvetica Neue', Helvetica, Arial, Verdana, sans-serif; font-size: 26px; background: transparent none; color: #707070; margin: 15px 0; padding: 0; font-weight: bold; text-transform: uppercase; height: auto; } .red{ color: red; } .green{ color: green; } .blue{ color: blue; } .yellow{ color: yellow; } .orange{ color: orange; } .fuchsia{ color: fuchsia; } /* staging env is red */ body.environment-staging{ background: #FF3F3F none; } body.environment-staging #main a { color: #CC0000; }
30.236398
181
0.703649
e40140f7532c59dd14479891b6d91e9eaa4c6f4b
700
go
Go
cmd/leaderelection/options.go
rmr-silicom/special-resource-operator
6faf0b12578eafe485b224b5b1d10d21b5d7b764
[ "Apache-2.0" ]
19
2019-09-27T15:43:54.000Z
2021-11-13T13:44:58.000Z
cmd/leaderelection/options.go
rmr-silicom/special-resource-operator
6faf0b12578eafe485b224b5b1d10d21b5d7b764
[ "Apache-2.0" ]
309
2020-01-31T13:21:31.000Z
2022-03-31T10:44:10.000Z
cmd/leaderelection/options.go
rmr-silicom/special-resource-operator
6faf0b12578eafe485b224b5b1d10d21b5d7b764
[ "Apache-2.0" ]
34
2020-11-09T14:26:53.000Z
2022-03-27T17:24:37.000Z
package leaderelection import ( configv1 "github.com/openshift/api/config/v1" "github.com/openshift/library-go/pkg/config/leaderelection" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/manager" ) func ApplyOpenShiftOptions(opts *ctrl.Options) *ctrl.Options { openshiftDefaults := leaderelection.LeaderElectionDefaulting( configv1.LeaderElection{}, "", "") if opts == nil { opts = &manager.Options{} } opts.LeaderElectionID = "b6ae617b.openshift.io" opts.LeaseDuration = &openshiftDefaults.LeaseDuration.Duration opts.RetryPeriod = &openshiftDefaults.RetryPeriod.Duration opts.RenewDeadline = &openshiftDefaults.RenewDeadline.Duration return opts }
25.925926
63
0.778571
58f4905e3a24f749ae6ef365b9877e105b2f08cb
1,465
rs
Rust
src/compression/zip.rs
Narann/exrs
bc3b837ab30ee368382d42b9bc94ad3f50a55554
[ "BSD-3-Clause" ]
69
2020-02-07T04:41:22.000Z
2022-03-18T21:31:16.000Z
src/compression/zip.rs
Narann/exrs
bc3b837ab30ee368382d42b9bc94ad3f50a55554
[ "BSD-3-Clause" ]
108
2020-01-24T00:02:56.000Z
2022-02-09T18:16:48.000Z
src/compression/zip.rs
johannesvollmer/rs-exr
404e2a123fb8191e86067c3d56fc045113d02161
[ "BSD-3-Clause" ]
9
2020-02-08T20:13:26.000Z
2022-02-06T00:18:12.000Z
// see https://github.com/openexr/openexr/blob/master/OpenEXR/IlmImf/ImfCompressor.cpp use super::*; use super::optimize_bytes::*; use std::io; use crate::error::Result; use deflate::write::ZlibEncoder; use inflate::inflate_bytes_zlib; // scanline decompression routine, see https://github.com/openexr/openexr/blob/master/OpenEXR/IlmImf/ImfScanLineInputFile.cpp // 1. Uncompress the data, if necessary (If the line is uncompressed, it's in XDR format, regardless of the compressor's output format.) // 3. Convert one scan line's worth of pixel data back from the machine-independent representation // 4. Fill the frame buffer with pixel data, respective to sampling and whatnot pub fn decompress_bytes(data: Bytes<'_>) -> Result<ByteVec> { let mut decompressed = inflate_bytes_zlib(data) .map_err(|msg| Error::invalid(msg))?; differences_to_samples(&mut decompressed); interleave_byte_blocks(&mut decompressed); Ok(decompressed) } pub fn compress_bytes(packed: Bytes<'_>) -> Result<ByteVec> { let mut packed = Vec::from(packed); // TODO no alloc separate_bytes_fragments(&mut packed); samples_to_differences(&mut packed); { // TODO fine-tune compression options let mut compressor = ZlibEncoder::new( Vec::with_capacity(packed.len()), deflate::Compression::Fast ); io::copy(&mut packed.as_slice(), &mut compressor)?; Ok(compressor.finish()?) } }
33.295455
136
0.705119
96baccb6a4a0a22b3253c74a88f9a535e5fad74f
139
hpp
C++
test/data/comments.hpp
linux-fan-dave/mstch
8a0ac9aa627b0bda5eec568b4e7382eace98feb6
[ "MIT" ]
523
2015-04-24T19:45:54.000Z
2022-03-29T21:19:38.000Z
test/data/comments.hpp
linux-fan-dave/mstch
8a0ac9aa627b0bda5eec568b4e7382eace98feb6
[ "MIT" ]
162
2017-03-11T04:32:32.000Z
2020-12-20T06:45:56.000Z
test/data/comments.hpp
linux-fan-dave/mstch
8a0ac9aa627b0bda5eec568b4e7382eace98feb6
[ "MIT" ]
103
2015-09-03T11:38:20.000Z
2022-03-14T13:13:44.000Z
const mstch::node comments_data = mstch::map{ {"title", mstch::lambda{[]()->mstch::node{return std::string{"A Comedy of Errors"};}}} };
46.333333
90
0.647482
75709c9bc9248decb21393dcdc3587070ddfca30
367
h
C
examples/iOS/01_VisualPiano/Main/ViewController.h
arturocepeda/Modus
849c9ada0e8bf7803db6e1b5c6098ab5898bc430
[ "MIT" ]
2
2015-04-08T21:03:09.000Z
2016-03-20T17:46:31.000Z
examples/iOS/01_VisualPiano/Main/ViewController.h
arturocepeda/Modus
849c9ada0e8bf7803db6e1b5c6098ab5898bc430
[ "MIT" ]
null
null
null
examples/iOS/01_VisualPiano/Main/ViewController.h
arturocepeda/Modus
849c9ada0e8bf7803db6e1b5c6098ab5898bc430
[ "MIT" ]
2
2015-08-18T08:59:07.000Z
2021-04-02T23:03:48.000Z
////////////////////////////////////////////////////////////////// // // Arturo Cepeda Pérez // iOS Game Engine // // Sample application // // --- ViewController.h --- // ////////////////////////////////////////////////////////////////// #import "config.h" #import <UIKit/UIKit.h> #import <GLKit/GLKit.h> @interface ViewController : GLKViewController @end
15.956522
66
0.414169
ac9864c930bb88ab326747bf4ca50fdf7e1f8ddb
6,793
cpp
C++
SPOJ/qtree.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
SPOJ/qtree.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
SPOJ/qtree.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <stack> #include <algorithm> #include <cctype> #include <vector> #include <queue> #include <tr1/unordered_map> #include <cmath> #include <map> #include <bitset> #include <set> #include <iomanip> #include <sstream> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector< ii > vii; ///////////////////////////////UTIL///////////////////////////////// #define CLEAR0(v) memset(v, 0, sizeof(v)) #define CLEAR(v, x) memset(v, x, sizeof(v)) #define COPY(a, b) memcpy(a, b, sizeof(a)) #define CMP(a, b) memcmp(a, b, sizeof(a)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) /////////////////////////////NUMERICAL////////////////////////////// #define INF 0x3f3f3f3f #define EPS 1e-9 #define MOD 1000000007LL #define CHECKFIRST(S) (S & (-S)) //__builtin_popcount(m) //scanf(" %d ", &t); int t, n; vi g[10100], st, a; ii e[10100]; map< ii, int > edge; char str[100]; int chainNo=0, chainHead[10100], chainPos[10100], chainInd[10100], chainSize[10100]; int subsize[10100]; int p[10100], l[10100]; int ac[10100][15]; int s[10100]; void st_build(vi &st, const vi &A, int vertex, int L, int R) { if (L == R){ st[vertex] = L; } else { int nL = 2 * vertex, nR = 2 * vertex + 1; st_build(st, A, nL, L , (L + R) / 2); st_build(st, A, nR, (L + R) / 2 + 1, R ); int lContent = st[nL] , rContent = st[nR]; int lValue = A[lContent], rValue = A[rContent]; st[vertex] = (lValue >= rValue) ? lContent : rContent; } } void st_create(vi &st, const vi &A) { int len = (int)(2*pow(2.0, floor((log((double)A.size())/log(2.0)) + 1))); st.assign(len, 0); st_build(st, A, 1, 0, (int)A.size() - 1); } int st_rmq(vi &st, const vi &A, int vertex, int L, int R, int i, int j) { if (i > R || j < L) return -1; if (L >= i && R <= j) return st[vertex]; int p1 = st_rmq(st, A, 2 * vertex , L , (L+R) / 2, i, j); int p2 = st_rmq(st, A, 2 * vertex + 1, (L+R) / 2 + 1, R , i, j); if (p1 == -1) return p2; if (p2 == -1) return p1; return (A[p1] >= A[p2]) ? p1 : p2; } int st_rmq(vi &st, const vi& A, int i, int j) { if(i > j) return 0; return st_rmq(st, A, 1, 0, (int)A.size() - 1, i, j); } int st_update_point(vi &st, vi &A, int node, int b, int e, int idx, int new_value) { int i = idx, j = idx; if (i > e || j < b) return st[node]; if (b == i && e == j) { A[i] = new_value; return st[node] = b; } int p1, p2; p1 = st_update_point(st, A, 2 * node , b , (b + e) / 2, idx, new_value); p2 = st_update_point(st, A, 2 * node + 1, (b + e) / 2 + 1, e , idx, new_value); return st[node] = (A[p1] >= A[p2]) ? p1 : p2; } int st_update_point(vi &st, vi &A, int idx, int new_value) { return st_update_point(st, A, 1, 0, (int)A.size() - 1, idx, new_value); } void hld(int cur) { if(chainHead[chainNo] == -1) chainHead[chainNo] = cur; chainInd[cur] = chainNo; chainPos[cur] = chainSize[chainNo]; chainSize[chainNo]++; int ind = -1, mai = -1; REP(i, g[cur].size()){ if(g[cur][i] != p[cur] && subsize[g[cur][i]] > mai) { mai = subsize[ g[cur][i] ]; ind = i; } } if(ind >= 0) hld( g[cur][ind] ); REP(i, g[cur].size()){ if(g[cur][i] != p[cur] && i != ind) { chainNo++; hld( g[cur][i] ); } } } int dfs(int v, int P, int L){ if(p[v]) return 0; p[v] = P; l[v] = L; subsize[v] = 1; REP(i, g[v].size()){ subsize[v] += dfs(g[v][i], v, L+1); } return subsize[v]; } void prelca(){ CLEAR0(ac); REPP(i, 1, n+1) ac[i][0] = p[i]; REPP(j, 1, 15) REPP(i, 1, n+1) if(ac[i][j-1]) ac[i][j] = ac[ac[i][j-1]][j-1]; } int lca(int u, int v){ int tmp, log, i; if(l[u] < l[v]) swap(u, v); for (log = 1; 1 << log <= l[u]; log++); log--; for (i = log; i >= 0; i--) if (l[u] - (1 << i) >= l[v]) u = ac[u][i]; if (u == v) return u; for (i = log; i >= 0; i--) if (ac[u][i] && ac[u][i] != ac[v][i]) u = ac[u][i], v = ac[v][i]; return p[u]; } void precmp(){ CLEAR0(p); dfs(1, -1, 0); prelca(); REPP(i, 1, n+1) chainHead[i] = -1; CLEAR0(chainSize); hld(1); chainNo++; s[0] = 0; REPP(i, 1, chainNo) s[i] = s[i-1]+chainSize[i-1]; a.assign(n, 0); REPP(i, 2, n+1){ int ri = s[chainInd[i]]+chainPos[i]; int u = i, v = p[i]; //cout << " VERT " << u << " " << v; if(u > v) swap(u, v); a[ri] = edge[ii(u, v)]; //cout << " peso " << a[ri] << " POSICAO NA ARVORE " << ri << " CHAININD " << chainInd[i] << endl; } st_create(st, a); //REP(i, n) cout << "i " << i << " a[i] " << a[i] << " rmq: " << a[st_rmq(st, a, 0, i)] << endl; } int queryUp(int u, int v){ //cout << " QUERY UP DE " << u << " ATE " << v << endl; int ans = 0; while(chainInd[u] != chainInd[v]){ ans = max(ans, a[st_rmq(st, a, s[chainInd[u]], s[chainInd[u]]+chainPos[u])]); //cout << "VERIFICANDO QUERY DE " << s[chainInd[u]] << " ATE " << s[chainInd[u]] << " Q EH " << a[st_rmq(st, a, s[chainInd[u]], s[chainInd[u]]+chainPos[u])] << endl; u = p[chainHead[chainInd[u]]]; } //cout << "VERIFICANDO QUERY2 DE " << s[chainInd[v]]+chainPos[v]+1 << " ATE " << s[chainInd[u]]+chainPos[u] << " Q EH " << a[st_rmq(st, a, s[chainInd[v]]+chainPos[v]+1, s[chainInd[u]]+chainPos[u])] << endl; return max(ans, a[st_rmq(st, a, s[chainInd[v]]+chainPos[v]+1, s[chainInd[u]]+chainPos[u])]); } int query(int u, int v){ int lc = lca(u, v); return max(queryUp(u, lc), queryUp(v, lc)); } void update(int i, int x){ //cout << "UPDATE " << i << " " << x << endl; int u = e[i].first, v = e[i].second; edge[e[i]] = x; //cout << " ARESTA " << u << " " << v << endl; if(p[u] != v) swap(u, v); //cout << " POSICAO " << s[chainInd[u]]+chainPos[u] << endl; st_update_point(st, a, s[chainInd[u]]+chainPos[u], x); //cout << " QUERY TESTE " << a[st_rmq(st, a, 0, n)] << " " << a[s[chainInd[u]]+chainPos[u]] << endl; } int main(){ scanf(" %d ", &t); while(t--){ scanf(" %d ", &n); edge.clear(); REPP(i, 1, n+1) g[i].clear(); int u, v, w; REPP(i, 1, n){ scanf(" %d %d %d ", &u, &v, &w); if(u > v) swap(u, v); e[i] = ii(u, v); edge[e[i]] = w; g[u].push_back(v); g[v].push_back(u); } precmp(); while(true){ scanf(" %s ", str); if(str[0] == 'D') break; scanf(" %d %d ", &u, &v); if(str[0] == 'Q') printf("%d\n", query(u, v)); else if(str[0] == 'C') update(u, v); } } }
27.613821
208
0.490947
116982baeae6f22655e01306f9809f00c9c6b21a
12,128
html
HTML
application/admin/view/admin/content3.html
RRRMannn/GameStrategy
3c9d9921265aa1ad808f30b1e8b8b279b6816d4c
[ "Apache-2.0" ]
null
null
null
application/admin/view/admin/content3.html
RRRMannn/GameStrategy
3c9d9921265aa1ad808f30b1e8b8b279b6816d4c
[ "Apache-2.0" ]
2
2018-12-22T04:59:33.000Z
2018-12-24T06:05:55.000Z
application/admin/view/admin/content3.html
RRRMannn/GameStrategy
3c9d9921265aa1ad808f30b1e8b8b279b6816d4c
[ "Apache-2.0" ]
2
2018-12-19T14:14:48.000Z
2018-12-19T14:41:27.000Z
<!DOCTYPE html> <html> <head> <!-- 页面meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>咨询管理</title> <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport"> <link rel="stylesheet" href="../../../../public/plugins/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="../../../../public/plugins/adminLTE/css/AdminLTE.css"> <link rel="stylesheet" href="../../../../public/plugins/adminLTE/css/skins/_all-skins.min.css"> <script src="../../../../public/plugins/jQuery/jquery-2.2.3.min.js"></script> <script src="../../../../public/plugins/bootstrap/js/bootstrap.min.js"></script> <script language="javascript" src="../../../../public/ckeditor/ckeditor.js" charset="utf-8"></script> </head> <body class="hold-transition skin-red sidebar-mini" > <!-- .box-body --> <div class="box-header with-border"> <h3 class="box-title">游戏管理 </h3> </div> <div class="box-body"> <!-- 数据表格 --> <div class="table-box"> <!--工具栏--> <div class="pull-left"> <div class="form-group form-inline"> <div class="btn-group"> <button type="button" class="btn btn-default" title="添加" data-toggle="modal" data-target="#editModa3" ><i class="fa fa-file-o"></i> 添加</button> <button type="button" class="btn btn-default" title="刷新" ><i class="fa fa-check"></i> 刷新</button> </div> </div> </div> <div class="pull-right"> <form class="form-inline definewidth m20" action="./content3?type=search" method="post"> <font color="#777777"><strong>游戏名:</strong></font> <input type="text" name="gameName" id="gameName"class="abc input-default" placeholder="" value="">&nbsp;&nbsp; <button type="submit" class="btn btn-default">查询</button> </form> </div> </div> <!--数据列表--> <table id="dataList" class="table table-bordered table-striped table-hover dataTable"> <thead> <tr> <th class="sorting_asc">游戏ID</th> <th class="sorting">游戏名称</th> <th class="sorting">游戏发布时间</th> <th class="sorting">游戏类型</th> <th class="sorting">游戏所在平台</th> <th class="text-center">操作</th> </tr> </thead> <tbody> {volist name='list' id='game'} <tr > <td>{$game.gameID}</td> <td>{$game.gameName}</td> <td>{$game.gameDate}</td> <td>{$game.gameType}</td> <td>{$game.gamePlat}</td> <td class="text-center"> <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal{$game.gameID}" >游戏简介</button> <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModa2{$game.gameID}" >修改</button> <a href="./content3.html?type=delete&gameID={$game.gameID}"><button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#" >删除</button></a> </td> </tr> {/volist} </tbody> </table> <!--数据列表/--> <div class="pagination" style="float: right;"> {$list->render()} </div> </div> <!-- 数据表格 /--> </div> <!-- /.box-body --> <!-- 编辑窗口 --> {volist name = "games" id="game"} <div class="modal fade" id="editModal{$game.gameID}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" > <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">游戏简介</h3> </div> <div class="modal-body"> <table class="table table-bordered table-striped" width="800px"> <tr>{$game.gameInfo} </tr> </table> </div> </div> </div> </div> <div class="modal fade" id="editModa2{$game.gameID}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" > <div class="modal-content" style="width: 1000px;right: 250px;bottom: 150px;"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">修改</h3> </div> <form action="{:url('admin/content3')}?type=change" method="post" id="form{$game.gameID}"> <div class="modal-body"> <table class="table table-bordered table-striped" width="800px"> <tr> <td>游戏ID</td> <td><input type="text" name="gameID" value="{$game.gameID}"></td> </tr> <tr> <td>游戏名称</td> <td><input type="text" name="gameName" value="{$game.gameName}"></td> </tr> <tr> <td>游戏所在平台</td> <td><input type="text" name="gamePlat" value="{$game.gamePlat}"></td> </tr> <tr> <td>游戏类型</td> <td><input type="text" name="gameType" value="{$game.gameType}"></td> </tr> <tr> <td>游戏分类</td> <td> <select name="gameImg"> <option value = 1>主机游戏</option> <option value = 2>单机游戏</option> <option value = 3>网络游戏</option> <option value = 4>手机游戏</option> <option value = 5>主机游戏+单机游戏</option> </select> </td> </tr> <tr> <td>游戏简介</td> <td><textarea name="gameInfo2" style="width:650px;height:200px">{$game.gameInfo}</textarea></td> </tr> </table> </div> <div class="modal-footer"> <button type = "submit" class="btn btn-success" aria-hidden="true">保存</button> <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button> </div> </form> </div> </div> </div> {/volist} <div class="modal fade" id="editModa3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" > <div class="modal-content" style="width: 1000px;right: 250px;bottom: 150px;"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">请输入游戏的相关信息</h3> </div> <form action="{:url('admin/content3')}?type=add" method="post" id="form" enctype = "multipart/form-data"> <div class="modal-body"> <table class="table table-bordered table-striped" width="800px"> <tr> <td>游戏名称</td> <td><input type="text" name="gameName"></td> </tr> <tr> <td>游戏分类</td> <td> <select name="gameImg"> <option value = 1>主机游戏</option> <option value = 2>单机游戏</option> <option value = 3>网络游戏</option> <option value = 4>手机游戏</option> <option value = 5>主机游戏+单机游戏</option> </select> </td> </tr> <tr> <td>游戏所在平台</td> <td><input type="text" name="gamePlat"></td> </tr> <tr> <td>游戏发布时间</td> <td><input type="date" name="gameDate"></td> </tr> <tr> <td>游戏类型</td> <td><input type="text" name="gameType"></td> </tr> <tr> <td>上传游戏图片</td> <td></td> </tr> <tr> <td>0.jpg</td> <td><input type="file" name="img[]"></td> </tr> <tr> <td>1.jpg</td> <td><input type="file" name="img[]"></td> </tr> <tr> <td>2.jpg</td> <td><input type="file" name="img[]"></td> </tr> <tr> <td>3.jpg</td> <td><input type="file" name="img[]"></td> </tr> <tr> <td>4.jpg</td> <td><input type="file" name="img[]"></td> </tr> <tr> <td>游戏简介</td> <td><textarea name="gameInfo1" style="width:650px;height:200px"></textarea></td> </tr> </table> </div> <div class="modal-footer"> <button type = "submit" class="btn btn-success" aria-hidden="true">保存</button> <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button> </div> </form> </div> </div> </div> </body> </html> <script type="text/javascript"> CKEDITOR.replace( 'gameInfo1', { toolbar : [ //加粗 斜体, 下划线 穿过线 下标字 上标字 ['Bold','Italic','Underline','Strike','Subscript','Superscript'], // 数字列表 实体列表 减小缩进 增大缩进 ['NumberedList','BulletedList','-','Outdent','Indent'], //左对 齐 居中对齐 右对齐 两端对齐 ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], //超链接 取消超链接 锚点 ['Link','Unlink','Anchor'], //图片 flash 表格 水平线 表情 特殊字符 分页符 ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'], '/', // 样式 格式 字体 字体大小 ['Styles','Format','Font','FontSize'], //文本颜色 背景颜色 ['TextColor','BGColor'], //全屏 显示区块 ['Maximize', 'ShowBlocks','-'] ],height:350 } ); CKEDITOR.replace( 'gameInfo2', { toolbar : [ //加粗 斜体, 下划线 穿过线 下标字 上标字 ['Bold','Italic','Underline','Strike','Subscript','Superscript'], // 数字列表 实体列表 减小缩进 增大缩进 ['NumberedList','BulletedList','-','Outdent','Indent'], //左对 齐 居中对齐 右对齐 两端对齐 ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], //超链接 取消超链接 锚点 ['Link','Unlink','Anchor'], //图片 flash 表格 水平线 表情 特殊字符 分页符 ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'], '/', // 样式 格式 字体 字体大小 ['Styles','Format','Font','FontSize'], //文本颜色 背景颜色 ['TextColor','BGColor'], //全屏 显示区块 ['Maximize', 'ShowBlocks','-'] ],height:350 } ); </script>
39.763934
201
0.434614
80c832c8ae68b288cf7fc11b2f7dec1136dc60f0
1,385
java
Java
authserver/src/main/java/com/comsysto/dcc/auth/client/CustomClientDetailsService.java
SekibOmazic/spring-oauth2-gateway
fb701b212e1554ea88f445e436d341f539eaed97
[ "MIT" ]
null
null
null
authserver/src/main/java/com/comsysto/dcc/auth/client/CustomClientDetailsService.java
SekibOmazic/spring-oauth2-gateway
fb701b212e1554ea88f445e436d341f539eaed97
[ "MIT" ]
null
null
null
authserver/src/main/java/com/comsysto/dcc/auth/client/CustomClientDetailsService.java
SekibOmazic/spring-oauth2-gateway
fb701b212e1554ea88f445e436d341f539eaed97
[ "MIT" ]
null
null
null
package com.comsysto.dcc.auth.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.ClientRegistrationException; import org.springframework.security.oauth2.provider.client.BaseClientDetails; import org.springframework.stereotype.Service; @Service public class CustomClientDetailsService implements ClientDetailsService { @Autowired private ClientRepository clientRepository; @Override public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException { return mapClientInfo(clientRepository.findOne(clientId)); } private ClientDetails mapClientInfo(Client client) { BaseClientDetails baseClientDetails = new BaseClientDetails(client.getId(), null, client.getScope(), client.getAuthorizedGrantTypes(), "ACTUATOR"); baseClientDetails.setAccessTokenValiditySeconds(1800); // 30min baseClientDetails.setClientSecret(client.getSecret()); // Used to disable CSRF and other "annoying" Stuff when used by R / simple clients baseClientDetails.addAdditionalInformation("serviceAccount", client.isAutoApproveScopes()); return baseClientDetails; } }
39.571429
125
0.788448
905a5dbcf6d40dd8d33a2306f6f8a174d61d4ad4
5,209
kt
Kotlin
stripe/src/test/java/com/stripe/android/paymentsheet/ui/BillingAddressViewTest.kt
blithe-dv/stripe-android
ec4b7553eab234075a1e8fce75fdcecc73635eb2
[ "MIT" ]
1
2020-12-18T14:37:13.000Z
2020-12-18T14:37:13.000Z
stripe/src/test/java/com/stripe/android/paymentsheet/ui/BillingAddressViewTest.kt
blithe-dv/stripe-android
ec4b7553eab234075a1e8fce75fdcecc73635eb2
[ "MIT" ]
null
null
null
stripe/src/test/java/com/stripe/android/paymentsheet/ui/BillingAddressViewTest.kt
blithe-dv/stripe-android
ec4b7553eab234075a1e8fce75fdcecc73635eb2
[ "MIT" ]
null
null
null
package com.stripe.android.paymentsheet.ui import android.content.Context import androidx.core.view.isVisible import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.ApiKeyFixtures import com.stripe.android.PaymentConfiguration import com.stripe.android.model.Address import com.stripe.android.utils.TestUtils.idleLooper import com.stripe.android.view.ActivityScenarioFactory import com.stripe.android.view.Country import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.util.Locale import kotlin.test.BeforeTest import kotlin.test.Test @RunWith(RobolectricTestRunner::class) class BillingAddressViewTest { private val context: Context = ApplicationProvider.getApplicationContext() private val activityScenarioFactory = ActivityScenarioFactory(context) private val billingAddressView: BillingAddressView by lazy { activityScenarioFactory.createView { BillingAddressView(it) } } @BeforeTest fun setup() { PaymentConfiguration.init(context, ApiKeyFixtures.FAKE_PUBLISHABLE_KEY) } @Test fun `default country when locale is US should be United States`() { Locale.setDefault(Locale.US) assertThat( billingAddressView.countryView.text.toString() ).isEqualTo("United States") } @Test fun `changing selectedCountry to country without postal code should hide postal code view`() { billingAddressView.selectedCountry = ZIMBABWE idleLooper() assertThat(billingAddressView.postalCodeLayout.isVisible) .isFalse() } @Test fun `changing selectedCountry to France should show postal code view`() { billingAddressView.selectedCountry = FRANCE idleLooper() assertThat(billingAddressView.postalCodeLayout.isVisible) .isTrue() } @Test fun `changing selectedCountry to US should show postal code view`() { billingAddressView.selectedCountry = USA idleLooper() assertThat(billingAddressView.postalCodeLayout.isVisible) .isTrue() } @Test fun `when selectedCountry is null should show postal code view`() { billingAddressView.selectedCountry = null idleLooper() assertThat(billingAddressView.postalCodeLayout.isVisible) .isTrue() } @Test fun `address with no postal code country and no postal code should return expected value`() { billingAddressView.selectedCountry = ZIMBABWE assertThat(billingAddressView.address.value) .isEqualTo( Address( country = "ZW" ) ) } @Test fun `address with validated postal code country and no postal code should return null`() { billingAddressView.selectedCountry = USA assertThat(billingAddressView.address.value) .isNull() } @Test fun `address with validated postal code country and invalid postal code should return null`() { billingAddressView.selectedCountry = USA billingAddressView.postalCodeView.setText("abc") assertThat(billingAddressView.address.value) .isNull() } @Test fun `address with validated postal code country and valid postal code should return expected value`() { billingAddressView.selectedCountry = USA billingAddressView.postalCodeView.setText("94107") assertThat(billingAddressView.address.value) .isEqualTo( Address( country = "US", postalCode = "94107" ) ) } @Test fun `address with unvalidated postal code country and null postal code should return null`() { billingAddressView.selectedCountry = MEXICO billingAddressView.postalCodeView.setText(" ") assertThat(billingAddressView.address.value) .isNull() } @Test fun `address with unvalidated postal code country and non-empty postal code should return expected value`() { billingAddressView.selectedCountry = MEXICO billingAddressView.postalCodeView.setText("12345") assertThat(billingAddressView.address.value) .isEqualTo( Address( country = "MX", postalCode = "12345" ) ) } @Test fun `changing country should update postalCodeView inputType`() { billingAddressView.selectedCountry = MEXICO assertThat(billingAddressView.postalCodeView.inputType) .isEqualTo(BillingAddressView.PostalCodeConfig.Global.inputType) billingAddressView.selectedCountry = USA assertThat(billingAddressView.postalCodeView.inputType) .isEqualTo(BillingAddressView.PostalCodeConfig.UnitedStates.inputType) } private companion object { private val USA = Country("US", "United States") private val FRANCE = Country("FR", "France") private val ZIMBABWE = Country("ZW", "Zimbabwe") private val MEXICO = Country("MX", "Mexico") } }
34.496689
113
0.676521
2a86d374e828561ae4a606e4e1e994ed919e9259
6,462
java
Java
src/main/java/GoodGenerator/Blocks/TEs/EssentiaHatch.java
iouter/GoodGenerator
b915774cfaaab107fefc63cede3554091a334898
[ "MIT" ]
null
null
null
src/main/java/GoodGenerator/Blocks/TEs/EssentiaHatch.java
iouter/GoodGenerator
b915774cfaaab107fefc63cede3554091a334898
[ "MIT" ]
null
null
null
src/main/java/GoodGenerator/Blocks/TEs/EssentiaHatch.java
iouter/GoodGenerator
b915774cfaaab107fefc63cede3554091a334898
[ "MIT" ]
null
null
null
package GoodGenerator.Blocks.TEs; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import thaumcraft.api.ThaumcraftApiHelper; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.api.aspects.IAspectContainer; import thaumcraft.api.aspects.IEssentiaTransport; import java.util.ArrayList; public class EssentiaHatch extends TileEntity implements IAspectContainer, IEssentiaTransport { public int facing; public boolean isOn; private AspectList current = new AspectList(); @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); this.facing = tagCompound.getInteger("facing"); this.isOn = tagCompound.getBoolean("isOn"); current = new AspectList(); NBTTagList tlist = tagCompound.getTagList("Aspects", 10); for (int j = 0; j < tlist.tagCount(); ++j) { NBTTagCompound rs = tlist.getCompoundTagAt(j); if (rs.hasKey("key")) { current.add(Aspect.getAspect(rs.getString("key")), rs.getInteger("amount")); } } } @Override public void writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); tagCompound.setInteger("facing", this.facing); tagCompound.setBoolean("isOn", this.isOn); NBTTagList tlist = new NBTTagList(); Aspect[] aspectA = current.getAspects(); for (Aspect aspect : aspectA) { if (aspect != null) { NBTTagCompound f = new NBTTagCompound(); f.setString("key", aspect.getTag()); f.setInteger("amount", current.getAmount(aspect)); tlist.appendTag(f); } } tagCompound.setTag("Aspects", tlist); } public final Packet getDescriptionPacket() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 0, nbt); } public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { NBTTagCompound nbt = pkt.func_148857_g(); readFromNBT(nbt); } public void markDirty() { super.markDirty(); if (this.worldObj.isRemote) { return; } this.worldObj.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); } @Override public void updateEntity() { fillfrompipe(); } public void fillfrompipe() { TileEntity[] te = new TileEntity[ForgeDirection.VALID_DIRECTIONS.length]; for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { te[i] = ThaumcraftApiHelper.getConnectableTile(this.worldObj, this.xCoord, this.yCoord, this.zCoord, ForgeDirection.VALID_DIRECTIONS[i]); if (te[i] != null) { IEssentiaTransport pipe = (IEssentiaTransport) te[i]; if (!pipe.canOutputTo(ForgeDirection.VALID_DIRECTIONS[i])) { return; } if ((pipe.getEssentiaType(ForgeDirection.VALID_DIRECTIONS[i]) != null) && (pipe.getSuctionAmount(ForgeDirection.VALID_DIRECTIONS[i]) < getSuctionAmount(ForgeDirection.VALID_DIRECTIONS[i]))) { addToContainer(pipe.getEssentiaType(ForgeDirection.VALID_DIRECTIONS[i]), pipe.takeEssentia(pipe.getEssentiaType(ForgeDirection.VALID_DIRECTIONS[i]), 1, ForgeDirection.VALID_DIRECTIONS[i])); } } } } @Override public AspectList getAspects() { return current; } @Override public void setAspects(AspectList aspectList) { this.current.add(aspectList); } @Override public boolean doesContainerAccept(Aspect aspect) { return true; } @Override public int addToContainer(Aspect aspect, int i) { current.add(aspect, i); return 0; } @Override public boolean takeFromContainer(Aspect aspect, int i) { return false; } @Override public boolean takeFromContainer(AspectList aspectList) { return false; } @Override public boolean doesContainerContainAmount(Aspect aspect, int i) { return current.aspects.containsKey(aspect) && i <= current.getAmount(aspect); } @Override public boolean doesContainerContain(AspectList aspectList) { ArrayList<Boolean> ret = new ArrayList<Boolean>(); for (Aspect a : aspectList.aspects.keySet()) ret.add(current.aspects.containsKey(a)); return !ret.contains(false); } @Override public int containerContains(Aspect aspect) { return current.aspects.containsKey(aspect) ? current.getAmount(aspect) : 0; } @Override public boolean isConnectable(ForgeDirection forgeDirection) { return true; } @Override public boolean canInputFrom(ForgeDirection forgeDirection) { return true; } @Override public boolean canOutputTo(ForgeDirection forgeDirection) { return false; } @Override public void setSuction(Aspect aspect, int i) { } @Override public Aspect getSuctionType(ForgeDirection forgeDirection) { return null; } @Override public int getSuctionAmount(ForgeDirection forgeDirection) { return 256; } @Override public int takeEssentia(Aspect aspect, int i, ForgeDirection forgeDirection) { return 0; } @Override public int addEssentia(Aspect aspect, int i, ForgeDirection forgeDirection) { current.add(aspect, i); return 0; } @Override public Aspect getEssentiaType(ForgeDirection forgeDirection) { return current.getAspects()[0]; } @Override public int getEssentiaAmount(ForgeDirection forgeDirection) { int ret = 0; for (final Aspect A : current.aspects.keySet()) { ret += current.getAmount(A); } return ret; } @Override public int getMinimumSuction() { return Integer.MAX_VALUE; } @Override public boolean renderExtendedTube() { return true; } }
30.196262
209
0.650263
0bade0a813f85f5dc11a97c4d7e70bc69c677f96
1,659
html
HTML
public/form/radio.html
oswaldovaldez1/Warlock-UI
83e0d6e4b6f90d225f0bfda72ad40e602eeb4438
[ "0BSD" ]
null
null
null
public/form/radio.html
oswaldovaldez1/Warlock-UI
83e0d6e4b6f90d225f0bfda72ad40e602eeb4438
[ "0BSD" ]
null
null
null
public/form/radio.html
oswaldovaldez1/Warlock-UI
83e0d6e4b6f90d225f0bfda72ad40e602eeb4438
[ "0BSD" ]
null
null
null
<div class="container"><div class="row"><div class="col-12"><h1>Radio</h1></div><div class="col-6 col-offset-3"><div class="form-group"><div class="radio"><input class="rounded form-control" id="input-radio" type="radio" name="radio-grupo-1"/><label for="input-radio">Input radio</label></div></div><div class="form-group"><div class="radio radio-primary"><input class="rounded form-control" id="input-radio-primary" type="radio" name="radio-grupo-1"/><label for="input-radio-primary">Input radio primary</label></div></div><div class="form-group"><div class="radio radio-secondary"><input class="rounded form-control" id="input-radio-secondary" type="radio" name="radio-grupo-1"/><label for="input-radio-secondary">Input radio secondary</label></div></div><div class="form-group"><div class="radio radio-success"><input class="rounded form-control" id="input-radio-success" type="radio" name="radio-grupo-1"/><label for="input-radio-success">Input radio success</label></div></div><div class="form-group"><div class="radio radio-info"><input class="rounded form-control" id="input-radio-info" type="radio" name="radio-grupo-1"/><label for="input-radio-info">Input radio info</label></div></div><div class="form-group"><div class="radio radio-danger"><input class="rounded form-control" id="input-radio-danger" type="radio" name="radio-grupo-1"/><label for="input-radio-danger">Input radio danger</label></div></div><div class="form-group"><div class="radio radio-warning"><input class="rounded form-control" id="input-radio-warning" type="radio" name="radio-grupo-1"/><label for="input-radio-warning">Input radio warning</label></div></div></div></div></div>
1,659
1,659
0.726341
cab794067fd4e1e228bd49c8975f556fe46480e1
3,095
lua
Lua
node/File.lua
ToxicFrog/EmuFun
27c54d0a99074d59fa8d7f65100c37a35ccaf56b
[ "MIT" ]
null
null
null
node/File.lua
ToxicFrog/EmuFun
27c54d0a99074d59fa8d7f65100c37a35ccaf56b
[ "MIT" ]
null
null
null
node/File.lua
ToxicFrog/EmuFun
27c54d0a99074d59fa8d7f65100c37a35ccaf56b
[ "MIT" ]
null
null
null
local Node = require "node.Node" local File = Node:clone("node.File") File.icon = emufun.images.file function File:__init(...) Node.__init(self, ...) self.attr = self.cache:get(self.name) -- load configuration from disk, if present local cfg = new "Configuration" (self) self:loadConfig() self:configure(cfg) cfg:finalize() end function File:colour() if self.attr.seen then return 0, 192, 255 else return Node.colour(self) end end -- Files named "foo.emufun" are loaded as config files and applied to themselves; -- this lets you write a foo.emufun that shows up as foo and has a custom run -- function. function File:loadConfig() if self.name:match("%.emufun$") then self.config = assert(loadfile(self:path())) end end if love._os == "Windows" then function File:expandcommand(string) return '"' .. string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return '"' .. tostring(self[match](self)) .. '"' else return '"' .. tostring(self[match]) .. '"' end end) .. '"' end else function File:expandcommand(string) local function escape(string) return (string:gsub("'", [['\'']])) end return (string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return "'" .. escape(tostring(self[match](self))) .. "'" else return "'" .. escape(tostring(self[match])) .. "'" end end)) end end function File:run() local function exec(v) if type(v) == "function" then return v(self) elseif type(v) == "string" then local cmd = self:expandcommand(v) log.info("Executing command: %s", cmd) log.debug(" => %s", tostring(os.execute(cmd))) return false elseif type(v) == "table" then local rv for _,command in ipairs(v) do rv = exec(v) end return rv else return new "node.Message" { name = "Error executing commands for " .. self:path(), message = "Unknown command type " .. type(v), parent = self.parent } end end -- the configuration file should define a command to execute -- if not, we fall through to the error if self.execute then local fs = love.window.getFullscreen() window.fullscreen(false) if not self.attr.seen then self.attr.seen = true self.cache:save(true) end local rv = exec(self.execute) or 0 window.fullscreen(fs) return rv end return new "node.Message" { name = "Error!", message = "No configuration available to execute this file", parent = self.parent } end function File:dir() return self.parent:path() end function File:extension() return self.name:match("%.([^%.]+)$") end return File
28.136364
163
0.564782
46b73382b7d63795fbbe1e9e781e6e71eeea4c30
793
dart
Dart
lib/components/form_error.dart
Mehmetates07/Socia_Beta
f47a4df42d3bbaeea8fdde6844d091c0ca300c53
[ "MIT" ]
1
2021-08-22T11:14:03.000Z
2021-08-22T11:14:03.000Z
lib/components/form_error.dart
devmehmetates/Socia_Beta
f47a4df42d3bbaeea8fdde6844d091c0ca300c53
[ "MIT" ]
null
null
null
lib/components/form_error.dart
devmehmetates/Socia_Beta
f47a4df42d3bbaeea8fdde6844d091c0ca300c53
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:socia_new/app/constants.dart'; class FormErrors extends StatelessWidget { const FormErrors({ Key? key, required this.errors, }) : super(key: key); final List<String> errors; @override Widget build(BuildContext context) { return Column( children: List.generate( errors.length, (index) => Padding( padding: const EdgeInsets.only(top: 2.0), child: errorRow(error: errors[index]), ), ), ); } Row errorRow({required String error}) { return Row( children: [ Icon( Icons.error_outline_rounded, color: mainColor, ), SizedBox( width: 10, ), Text(error), ], ); } }
19.825
51
0.563682
fecaf4e923cfcaa304b5d05107d5a11cce5745da
3,672
dart
Dart
packages/mpflutter_sample/lib/pages/route_test_page.dart
aosic/mpflutter
4219538c2ed2420bf6c15c6fa39bc2776493afd1
[ "Apache-2.0" ]
1
2022-03-25T12:30:20.000Z
2022-03-25T12:30:20.000Z
packages/mpflutter_sample/lib/pages/route_test_page.dart
aosic/mpflutter
4219538c2ed2420bf6c15c6fa39bc2776493afd1
[ "Apache-2.0" ]
null
null
null
packages/mpflutter_sample/lib/pages/route_test_page.dart
aosic/mpflutter
4219538c2ed2420bf6c15c6fa39bc2776493afd1
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/widgets.dart'; import 'package:mpcore/mpkit/mpkit.dart'; class RouteTestPage extends StatelessWidget { Widget _renderBlock(Widget child) { return Padding( padding: EdgeInsets.all(12), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Container( color: Colors.white, child: child, ), ), ); } Widget _renderHeader(String title) { return Container( height: 48, padding: EdgeInsets.only(left: 12), child: Align( alignment: Alignment.centerLeft, child: Row( children: [ Expanded( child: Text( title, style: TextStyle(fontSize: 14, color: Colors.black54), ), ), ], ), ), ); } @override Widget build(BuildContext context) { return MPScaffold( name: 'RouteTest', backgroundColor: Color.fromARGB(255, 236, 236, 236), body: ListView( children: [ _renderBlock(Column( children: [ _renderHeader('Tap to pop to previous.'), GestureDetector( onTap: () { Navigator.of(context).pop(); }, child: Container( width: 100, height: 100, color: Colors.pink, ), ), SizedBox(height: 16), ], )), _renderBlock(Column( children: [ _renderHeader('Tap to pushReplacement.'), GestureDetector( onTap: () { Navigator.of(context).pushReplacementNamed('/container'); }, child: Container( width: 100, height: 100, color: Colors.pink, ), ), SizedBox(height: 16), ], )), _renderBlock(Column( children: [ _renderHeader('Tap to push home.'), GestureDetector( onTap: () { Navigator.of(context) .pushNamed('/', arguments: {'second': 'true'}); }, child: Container( width: 100, height: 100, color: Colors.pink, ), ), SizedBox(height: 16), ], )), _renderBlock(Column( children: [ _renderHeader('Tap to pop until home.'), GestureDetector( onTap: () { Navigator.of(context).popUntil((route) => route.isFirst); }, child: Container( width: 100, height: 100, color: Colors.pink, ), ), SizedBox(height: 16), ], )), _renderBlock(Column( children: [ _renderHeader('Tap to pushNamedAndRemoveUntil.'), GestureDetector( onTap: () async { Navigator.of(context).pushNamedAndRemoveUntil( '/container', (route) => false, ); }, child: Container( width: 100, height: 100, color: Colors.pink, ), ), SizedBox(height: 16), ], )), ], ), ); } }
27.402985
75
0.409314
18b9b3f06833374dfabd31ff404a23ffa9b84d08
599
swift
Swift
Sources/XMLCoder/Auxiliaries/Box/SharedBox.swift
thibauddavid/XMLCoder
590feacb7c486769bf0c0a654bd6bcd0e9c34fb9
[ "MIT" ]
3
2021-05-14T14:09:07.000Z
2021-05-16T01:12:01.000Z
Sources/XMLCoder/Auxiliaries/Box/SharedBox.swift
thibauddavid/XMLCoder
590feacb7c486769bf0c0a654bd6bcd0e9c34fb9
[ "MIT" ]
null
null
null
Sources/XMLCoder/Auxiliaries/Box/SharedBox.swift
thibauddavid/XMLCoder
590feacb7c486769bf0c0a654bd6bcd0e9c34fb9
[ "MIT" ]
1
2021-01-21T12:15:31.000Z
2021-01-21T12:15:31.000Z
// // SharedBox.swift // XMLCoder // // Created by Vincent Esche on 12/22/18. // class SharedBox<Unboxed: Box> { private(set) var unboxed: Unboxed init(_ wrapped: Unboxed) { unboxed = wrapped } func withShared<T>(_ body: (inout Unboxed) throws -> T) rethrows -> T { return try body(&unboxed) } } extension SharedBox: Box { var isNull: Bool { return unboxed.isNull } var xmlString: String? { return unboxed.xmlString } } extension SharedBox: SharedBoxProtocol { func unbox() -> Unboxed { return unboxed } }
17.114286
75
0.601002
0f583aa634a04820b9e762f1d6252e3620d86aae
1,049
cpp
C++
tests/expected/bitops.cpp
div72/py2many
60277bc13597bd32d078b88a7390715568115fc6
[ "MIT" ]
345
2021-01-28T17:33:08.000Z
2022-03-25T16:07:56.000Z
tests/expected/bitops.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
291
2021-01-31T13:15:06.000Z
2022-03-23T21:28:49.000Z
tests/expected/bitops.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
23
2021-02-09T17:15:03.000Z
2022-02-03T05:57:44.000Z
#include <cassert> // NOLINT(build/include_order) #include <iostream> // NOLINT(build/include_order) #include <vector> // NOLINT(build/include_order) #include "pycpp/runtime/builtins.h" // NOLINT(build/include_order) #include "pycpp/runtime/sys.h" // NOLINT(build/include_order) inline void main_func() { std::vector<bool> ands = {}; std::vector<bool> ors = {}; std::vector<bool> xors = {}; for (auto a : {false, true}) { for (auto b : {false, true}) { ands.push_back(a & b); ors.push_back(a | b); xors.push_back(a ^ b); } } assert(({ std::vector<bool> __tmp1 = {false, false, false, true}; ands == __tmp1; })); assert(({ std::vector<bool> __tmp2 = {false, true, true, true}; ors == __tmp2; })); assert(({ std::vector<bool> __tmp3 = {false, true, true, false}; xors == __tmp3; })); std::cout << std::string{"OK"}; std::cout << std::endl; } int main(int argc, char** argv) { pycpp::sys::argv = std::vector<std::string>(argv, argv + argc); main_func(); }
26.897436
67
0.593899
aee61af9b09f3ed0fc41f1566d5469f0f22b2258
745
asm
Assembly
oeis/224/A224508.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/224/A224508.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/224/A224508.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A224508: a(n+2) = a(n+1) + a(n) + A*t^n, with A = 1 and t = -2. ; Submitted by Jamie Morken(s3) ; 0,1,2,1,7,0,23,-9,78,-59,275,-296,1003,-1341,3758,-5775,14367,-24176,55727,-99521,218350,-405459,861467,-1641144,3414627,-6615125,13576718,-26592839,54092743,-106717824,215810375,-427778361,861773838,-1713488171,3443252963,-6860169800,13762952347,-27456955821,55025473262,-109870436031,220032944175,-439593305744,879951266207,-1758665295089,3519332482222,-7035425835075,14076092691563,-28143705232344,56301131636883,-112580061950789,225196046396750,-450333968975351,900761984264023,-1801371798396576 mov $2,9 lpb $0 sub $0,1 add $2,$4 mov $1,$2 mov $2,$4 mul $2,2 mov $4,3 sub $4,$2 add $4,$3 add $3,$1 lpe mov $0,$4 div $0,3
39.210526
501
0.727517
716547645425f19edef9378e5be623500f8077a3
1,894
sql
SQL
docs/ddl.sql
DBrittonLinebarger/artgallerymemorymatch
10e294265432ad8925ab73f29d4f08557711c33f
[ "Apache-2.0" ]
null
null
null
docs/ddl.sql
DBrittonLinebarger/artgallerymemorymatch
10e294265432ad8925ab73f29d4f08557711c33f
[ "Apache-2.0" ]
null
null
null
docs/ddl.sql
DBrittonLinebarger/artgallerymemorymatch
10e294265432ad8925ab73f29d4f08557711c33f
[ "Apache-2.0" ]
null
null
null
CREATE TABLE IF NOT EXISTS `Card` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `object_id` INTEGER NOT NULL, `theme_id` INTEGER NOT NULL, `title` TEXT, `object_date` TEXT, `url` TEXT, FOREIGN KEY (`theme_id`) REFERENCES `Theme` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE ); CREATE INDEX `index_Card_object_id` ON `Card` (`object_id`); CREATE INDEX `index_Card_theme_id` ON `Card` (`theme_id`); CREATE INDEX `index_Card_object_date` ON `Card` (`object_date`); CREATE TABLE IF NOT EXISTS `Game` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `player_id` INTEGER NOT NULL, `theme_id` INTEGER NOT NULL, `play_time` INTEGER NOT NULL, `score` INTEGER NOT NULL, `date_started` INTEGER NOT NULL, `date_ended` INTEGER NOT NULL, `timestamp` INTEGER, FOREIGN KEY (`theme_id`) REFERENCES `Theme` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE, FOREIGN KEY (`player_id`) REFERENCES `Player` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE ); CREATE INDEX `index_Game_player_id` ON `Game` (`player_id`); CREATE INDEX `index_Game_theme_id` ON `Game` (`theme_id`); CREATE INDEX `index_Game_play_time` ON `Game` (`play_time`); CREATE INDEX `index_Game_date_started` ON `Game` (`date_started`); CREATE INDEX `index_Game_date_ended` ON `Game` (`date_ended`); CREATE TABLE IF NOT EXISTS `Player` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT ); CREATE TABLE IF NOT EXISTS `Theme` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT ); CREATE UNIQUE INDEX `index_Theme_title` ON `Theme` (`title`);
32.101695
94
0.597149
105c6699a4b3c92a68a06b87b21ff27a50263ce0
72
dart
Dart
lib/Collisions.dart
Grant-Nelson/ThreeDart
e789e495a545ae6142ad3ffd7c9398488ed4c07a
[ "BSD-3-Clause" ]
17
2016-02-27T17:06:55.000Z
2022-03-11T18:27:04.000Z
lib/Collisions.dart
Grant-Nelson/ThreeDart
e789e495a545ae6142ad3ffd7c9398488ed4c07a
[ "BSD-3-Clause" ]
90
2016-09-30T08:01:52.000Z
2020-10-16T21:39:50.000Z
lib/Collisions.dart
Grant-Nelson/ThreeDart
e789e495a545ae6142ad3ffd7c9398488ed4c07a
[ "BSD-3-Clause" ]
11
2016-10-05T04:15:59.000Z
2020-07-14T20:59:29.000Z
library ThreeDart.Collisions; export 'src/Collisions/Collisions.dart';
18
40
0.819444
c7bcf356b8e753a440d4931c93384d834a1544ee
12,519
py
Python
Mutiple_community/Multi_comm2.py
RollingThunderSagnik/Pandemic-Simulator
fbf953a6511eefedb66bd931aa996d623aae9d7d
[ "MIT" ]
1
2020-10-01T03:40:08.000Z
2020-10-01T03:40:08.000Z
Mutiple_community/Multi_comm2.py
RollingThunderSagnik/Pandemic-Simulator
fbf953a6511eefedb66bd931aa996d623aae9d7d
[ "MIT" ]
null
null
null
Mutiple_community/Multi_comm2.py
RollingThunderSagnik/Pandemic-Simulator
fbf953a6511eefedb66bd931aa996d623aae9d7d
[ "MIT" ]
1
2020-10-01T03:23:53.000Z
2020-10-01T03:23:53.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 5 01:57:59 2020 @author: ap """ # PLEASE READ ATTENTION BEFORE EXECUTING import pandas as pd import matplotlib.pyplot as plt import numpy as np import random spread_limit = 10 recovery_prob = 0.70 intial_count = 10 infection_rate = 0.5 population = 1000 landmark = [] landmark_prob = 0.3 landmark_prob_dec_rate = 0.8 lock_ratio = 0.8 lock_decrease_rate = 0.2 lock_increase_rate = 0.1 lock_infected_count = 100 no_of_region = 10 def initialize(): global infected_count,dead_count,recovered_count,infected,pos,infected_count_arr global dead_count_arr,recovered_count_arr,non_infected_count_arr,lock_count,landmark_prob_values,lock_count_arr pos = pd.DataFrame() pos['x'] =[] pos['y'] =[] pos['Quar'] = [] pos['region'] = [] infected = pd.DataFrame() infected['x'] = [] infected['y'] = [] infected['time'] = [] infected['region'] = [] infected_count = intial_count dead_count = 0 recovered_count = 0 lock_count = 0 infected_count_arr = [] dead_count_arr = [] recovered_count_arr = [] non_infected_count_arr = [] landmark_prob_values = [] lock_count_arr = [] for i in range(population): reg = random.randint(0, no_of_region-1) y = random.randint(0, population/10/no_of_region) x = random.randint(0, population/10/no_of_region)+(reg)*(population/10/no_of_region) pos.loc[i]=[x,y,0,reg] # RUN THIS SECTION SO SEE INITIAL DISTRIBUTION #fig = plt.figure(figsize=(no_of_region, 1)) #ax = fig.add_subplot(111) #ax.scatter(pos['x'],pos['y']) #--------------------------------------------- for i in range(10): infected.loc[i]= [pos['x'][i],pos['y'][i],1,pos['region'][i]] pos = pos.iloc[10:] pos = pos.reset_index(drop=True) # set landmarks for each regions for reg in range(no_of_region): y = random.randint(0, population/10/no_of_region) x = random.randint(0, population/10/no_of_region)+(reg)*(population/10/no_of_region) landmark.append([x,y]) def isolation_initiate(): global lock_count for i in range(len(pos['x'])): if(random.random()<lock_ratio): pos.Quar[i]= 1 lock_count = lock_count + 1 def isolation(): global lock_count i = 0 for i in range(len(pos['x'])): t = random.random() if(t<lock_increase_rate): pos.Quar[i] = min(pos.Quar[i]+ random.random(),1) lock_count = lock_count + 1 elif(t <( lock_increase_rate+lock_decrease_rate)): pos.Quar[i] = max(pos.Quar[i]- random.random(),0) lock_count = lock_count - 1 def distance(pos1,pos2): return ((infected['x'][pos2]-pos['x'][pos1])**2)+((infected['y'][pos2]-pos['y'][pos1])**2) def infected_check(pos1): iso = 1- pos['Quar'][pos1] return (random.random()<infection_rate*iso) def region_check(pos1,pos2): if(pos['region'][pos1]==infected['region'][pos2]): return True return False def infect(): global pos,infected_count i = 0 move_around() while(i < len(pos['x'])): for j in range(infected_count): if(i>=len(pos['x'])): break if(region_check(i,j)): if(distance(i,j)< spread_limit): if(infected_check(i)): infected.loc[infected_count]= [pos['x'][i],pos['y'][i],1,pos['region'][i]] infected_count = infected_count + 1 pos = pos.drop(i) pos = pos.reset_index(drop=True) i = i +1 ###################################################EDIT FROM MOVE AROUND####################### def move_around(): global landmark_prob,landmark_prob_values for i in range(len(pos['x'])): if(random.random()<landmark_prob): x,y = landmark[random.randint(0, len(landmark)-1)] pos.loc[i]=[x,y,pos['Quar'][i],pos['region'][i]] else: reg = pos['region'][i] y = random.randint(0, population/10/no_of_region) x = random.randint(0, population/10/no_of_region)+(reg)*(population/10/no_of_region) pos.loc[i]=[x,y,pos['Quar'][i],reg] landmark_prob = landmark_prob* landmark_prob_dec_rate landmark_prob_values.append(landmark_prob) def day(): global infected_count,dead_count,recovered_count,infected,pos,lock_count_arr,lock_count #getting global data isolation() if(infected_count > lock_infected_count): isolation_initiate() infected_count_arr.append(infected_count) non_infected_count_arr.append(len(pos['x'])) dead_count_arr.append(dead_count) recovered_count_arr.append(recovered_count) # increase infected time and remove necessary for i in range(len(infected['time'])): infected['time'][i]= infected['time'][i] +1 if (infected['time'][i]>3): infected = infected.drop(i) removed() # set new loction for all not infected infected = infected.reset_index(drop=True) infected_count = len(infected['time']) infect() lock_count_arr.append(lock_count) def removed(): if(random.random()<recovery_prob): global recovered_count recovered_count = recovered_count + 1 else : global dead_count dead_count = dead_count + 1 def day_call(): initialize() while(infected_count != 0 ): day() #*************************************ATTENTION****************************************************** #PLEASE DON'T EXECUTE THE CODE ALL AT ONCE RUN THE FIRST HALF FIRST AND THE SECOND HALF ONE AT A TIME #*************************************ATTENTION****************************************************** ################################################################################################################################################ # Get plot an data for a virtual environment of a given parameter ################################################################################################################################################ day_call() name = "plot 1" my_file = open(name + ".txt","w") txt = "People are divided into regions. They move around in their own region sometimes to go to captials of other regions helping spread the disease " txt = txt + "People start going to lockdown as the disease spreads. There is a gov. sanctioned lockdown after a ceratin a given infected count. More no of. people tend to disobey with time.\n\n" txt = txt +"Parameters:\n spread_limit = {}\n recovery_prob = {}\n intial_count = {}\n infection_rate = {}\n ".format(spread_limit,recovery_prob,intial_count,infection_rate) txt = txt + "population = {}\n landmark = {}\n landmark_prob = {}\n landmark_prob_dec_rate = {}\n lock_ratio = {}\n ".format(population,landmark,landmark_prob,landmark_prob_dec_rate,lock_ratio) txt = txt + "lock_decrease_rate = {}\n lock_increase_rate = {}\n lock_infected_count = {}\n".format(lock_decrease_rate,lock_increase_rate,lock_infected_count) my_file.write(txt) fig = plt.figure(figsize=(len(dead_count_arr), 5)) ax = fig.add_subplot(111) ax.plot(dead_count_arr,color='blue') ax.plot(non_infected_count_arr,color='orange' ) ax.plot(infected_count_arr,color='red' ) ax.plot(recovered_count_arr,color='green') plt.gca().legend(['Dead', 'non infected','infected', 'recovered'], loc='best') plt.xlabel("Days") plt.ylabel("No. of people") plt.savefig(name+ ".pdf") ax.show() ################################################################################################################################################ # Change in total involved,safe,and days taken with change in spread_limit ################################################################################################################################################ total_involed = [] total_safe = [] days = [] spread_limit_values = [] def spread_limit_change(): global spread_limit spread_limit = 1 for i in range(16): day_call() total_involed.append(recovered_count + dead_count) total_safe.append(population - recovered_count - dead_count) days.append(len(recovered_count_arr)) spread_limit_values.append(spread_limit) spread_limit = spread_limit + 1 spread_limit_change() txt="PEOPLE SPREAD_LIMIT_VARIABLE(1,16) recovery_prob = {} intial_count = {} infection_rate = {} ".format(recovery_prob,intial_count,infection_rate) plt.plot(spread_limit_values,total_involed ,color='blue') plt.plot(spread_limit_values,total_safe,color='orange' ) plt.xlabel("SPREAD_LIMIT_VALUE") plt.ylabel("No. of people") plt.legend(['total_involed', 'total_safe'], loc='best') plt.title( txt) plt.savefig(txt+ ".pdf") plt.show() txt="DAYS SPREAD_LIMIT_VARIABLE(1,16) recovery_prob = {} intial_count = {} infection_rate = {} ".format(recovery_prob,intial_count,infection_rate) plt.plot(spread_limit_values,days) plt.xlabel("SPREAD_LIMIT_VALUE") plt.ylabel("Days") plt.title( txt) plt.savefig(txt+ ".pdf") plt.show() ################################################################################################################################################ # Change in total involved,safe,and days taken with change in intial_count ################################################################################################################################################ total_involed = [] total_safe = [] days = [] intial_count_values = [] def intial_count_change(): global intial_count intial_count = 10 for i in range(16): day_call() total_involed.append(recovered_count + dead_count) total_safe.append(population - recovered_count - dead_count) days.append(len(recovered_count_arr)) intial_count_values.append(intial_count) intial_count = intial_count + 1 intial_count_change() txt="PEOPLE INITIAL_COUNT_VARIABLE(10,25,step = 1) recovery_prob = {} intial_count = {} infection_rate = {} ".format(recovery_prob,intial_count,infection_rate) plt.plot(intial_count_values,total_involed ,color='blue') plt.plot(intial_count_values,total_safe,color='orange' ) plt.xlabel("INITIAL_COUNT_VALUE") plt.ylabel("No. of people") plt.legend(['total_involed', 'total_safe'], loc='best') plt.title( "Description in file name") plt.savefig(txt+ ".pdf") plt.show() txt="DAYS INITIAL_COUNT_VARIABLE(10,40,step = 1) recovery_prob = {} intial_count = {} infection_rate = {} ".format(recovery_prob,intial_count,infection_rate) plt.plot(intial_count_values,days) plt.xlabel("INITIAL_COUNT_VALUE") plt.ylabel("Days") plt.title( "Description in file name") plt.savefig(txt+ ".pdf") plt.show() ################################################################################################################################################ # Change in total involved,safe,and days taken with change in infection_rate ################################################################################################################################################ total_involed = [] total_safe = [] days = [] infection_rate_values = [] def infection_rate_change(): global infection_rate infection_rate = 0.10 for i in range(18): day_call() total_involed.append(recovered_count + dead_count) total_safe.append(population - recovered_count - dead_count) days.append(len(recovered_count_arr)) infection_rate_values.append(infection_rate) infection_rate = infection_rate + 0.05 infection_rate_change() txt="PEOPLE INFECTION_RATE_VARIABLE(0.1,1,step =.05) recovery_prob = {} intial_count = {} spread_limit = {} ".format(recovery_prob,intial_count,spread_limit) plt.plot(infection_rate_values,total_involed ,color='blue') plt.plot(infection_rate_values,total_safe,color='orange' ) plt.xlabel("INFECTION_RATE_VALUE") plt.ylabel("No. of people") plt.legend(['total_involed', 'total_safe'], loc='best') plt.title( "Description in file name") plt.savefig(txt+ ".pdf") plt.show() txt="DAYS INFECTION_RATE_VARIABLE(0.1,1,step =.05) recovery_prob = {} intial_count = {} spread_limit = {} ".format(recovery_prob,intial_count,spread_limit) plt.plot(infection_rate_values,days) plt.xlabel("INFECTION_RATE_VALUE") plt.ylabel("Days") plt.title( "Description in file name") plt.savefig(txt+ ".pdf") plt.show()
37.936364
194
0.595655
0bbb896c1f766d40e02d03530e5012bd42f6b56e
660
py
Python
app/schemas/treatment_type.py
DzhonPetrus/Treatment-Management
6b08c59d2d4e79181bbae4e951b7a5fd2e3162f1
[ "MIT" ]
null
null
null
app/schemas/treatment_type.py
DzhonPetrus/Treatment-Management
6b08c59d2d4e79181bbae4e951b7a5fd2e3162f1
[ "MIT" ]
null
null
null
app/schemas/treatment_type.py
DzhonPetrus/Treatment-Management
6b08c59d2d4e79181bbae4e951b7a5fd2e3162f1
[ "MIT" ]
null
null
null
from datetime import datetime as dt from typing import Optional, List from pydantic import BaseModel from ..utils.schemaHelper import Base, as_form class TreatmentTypeBase(Base): name: str room: str description: str fee: float is_active: Optional[str] = None @as_form class CreateTreatmentType(TreatmentTypeBase): pass class TreatmentType(TreatmentTypeBase): id: str created_at: Optional[dt] = None updated_at: Optional[dt] = None class OutTreatmentTypes(Base): data: List[TreatmentType] error: bool message: str class OutTreatmentType(Base): data: TreatmentType error: bool message: str
19.411765
46
0.721212
998b765752db2440a17a69477c6e5df4f5141242
2,005
lua
Lua
lua/greencode/plugins/rp_custommenu/templates/cl_simple.lua
men232/greencode-framework
b7b3d0bac2523fe189f1f3987d49c9215ee2bcc9
[ "MIT" ]
6
2019-12-01T20:00:51.000Z
2022-02-16T10:42:33.000Z
lua/greencode/plugins/rp_custommenu/templates/cl_simple.lua
men232/greencode-framework
b7b3d0bac2523fe189f1f3987d49c9215ee2bcc9
[ "MIT" ]
null
null
null
lua/greencode/plugins/rp_custommenu/templates/cl_simple.lua
men232/greencode-framework
b7b3d0bac2523fe189f1f3987d49c9215ee2bcc9
[ "MIT" ]
5
2018-08-05T08:02:50.000Z
2021-12-30T03:06:35.000Z
--[[ © 2013 GmodLive private project do not share without permission of its author (Andrew Mensky vk.com/men232). --]] CM_SIMPLE_TMPL = CM_TMPL_CLASS:New{ name = "simple", callback = function( BLOCK, t ) BLOCK:SetTooltip(t.tooltip or false); BLOCK.Title = xlib.makelabel{ parent = BLOCK, x = 60, y = 8, label = t.title or "#Title", font = "Trebuchet22", textcolor = t.color or Color(0,255,0) } //vgui.Create( "DLabel", BLOCK); BLOCK.Title:SetExpensiveShadow(2, Color(0,0,0,255)); if ( t.desc ) then t.desc = string.Replace(t.desc, "\\n", "\n"); end; BLOCK.Desc = xlib.makelabel{ parent = BLOCK, x = 80, y = 33, label = t.desc or "#Desc", textcolor = Color(255,255,255) } BLOCK.Desc:SetExpensiveShadow(2, Color(0,0,0,255)); if ( t.mdl ) then BLOCK.Icon = vgui.Create("SpawnIcon", BLOCK); BLOCK.Icon:SetSize(50, 50); BLOCK.Icon:SetPos(10, 10); BLOCK.Icon:SetModel(Model(t.mdl)); BLOCK.Icon.PaintOver = function() return false; end; BLOCK.Icon.OnCursorEntered = function(...) BLOCK:OnCursorEntered(...); return true; end; BLOCK.Icon.OnCursorExited = function(...) BLOCK:OnCursorExited(...); return true; end; BLOCK.Icon.OnMouseReleased = function(...) BLOCK:OnMouseReleased(...); return true; end; BLOCK.Icon.OnMousePressed = function(...) BLOCK:OnMousePressed(...); return true; end; BLOCK.Icon:SetToolTip(t.title or "#Title"); else BLOCK.Title:SetPos(10,8); BLOCK.Desc:SetPos(10,33); end; if ( t.turn or t.clk2 ) then BLOCK.mBox = vgui.Create("Panel", BLOCK); BLOCK.mBox:SetSize(10, 10); local c = t.turn and Color(45,255,255) or Color(45,255,45); function BLOCK.mBox:Paint() draw.RoundedBox(0, 0, 0, self:GetWide(), self:GetTall(), Color(c.r,c.g,c.b,a)); surface.SetDrawColor( Color(0,0,0,a)); self:DrawOutlinedRect(); end; function BLOCK.mBox:Think() self:SetPos(BLOCK:GetWide()-15, 5); end; end; BLOCK.turnOnH = BLOCK.Desc:GetTall() + 40; return true; end }:Register();
37.12963
186
0.654364
f3e6d27efa7687fce8caebe6b4f58c2b6bb9478b
5,124
cs
C#
src/lib/ControllerState.cs
anewton/minirover
68e80e6569bc9130d40c30a38895186bbea819cc
[ "MIT" ]
1
2020-01-29T00:28:18.000Z
2020-01-29T00:28:18.000Z
src/lib/ControllerState.cs
anewton/minirover
68e80e6569bc9130d40c30a38895186bbea819cc
[ "MIT" ]
null
null
null
src/lib/ControllerState.cs
anewton/minirover
68e80e6569bc9130d40c30a38895186bbea819cc
[ "MIT" ]
null
null
null
using System; using System.Diagnostics; using System.Reflection; using System.Text; using SharpDX.XInput; namespace lib { public class ControllerState { // Threshold for determining exact center joysticks due to innaccuracies in controller data private const int DEADBAND = 2500; public ControllerState(Controller controller) { UpdateControllerState(controller); } public delegate void ControllerStateChangedHandler(object sender, ControllerEventArgs e); public event ControllerStateChangedHandler ControllerStateChanged; public void UpdateControllerState(Controller controller) { try { var state = controller.GetState(); LeftStickX = (Math.Abs((float)state.Gamepad.LeftThumbX) < DEADBAND) ? 0 : (float)state.Gamepad.LeftThumbX / short.MinValue * -100; LeftStickY = (Math.Abs((float)state.Gamepad.LeftThumbY) < DEADBAND) ? 0 : (float)state.Gamepad.LeftThumbY / short.MaxValue * 100; RightStickX = (Math.Abs((float)state.Gamepad.RightThumbX) < DEADBAND) ? 0 : (float)state.Gamepad.RightThumbX / short.MaxValue * 100; RightStickY = (Math.Abs((float)state.Gamepad.RightThumbY) < DEADBAND) ? 0 : (float)state.Gamepad.RightThumbY / short.MaxValue * 100; LeftAxis = string.Format("X: {0} Y: {1}", LeftStickX, LeftStickY); RightAxis = string.Format("X: {0} Y: {1}", RightStickX, RightStickY); Y = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.Y); B = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.B); A = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.A); X = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.X); DPadUp = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadUp); DPadRight = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadRight); DPadDown = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadDown); DPadLeft = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadLeft); LeftShoulder = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.LeftShoulder); RightShoulder = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.RightShoulder); LeftThumb = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.LeftThumb); RightThumb = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.RightThumb); Start = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.Start); Back = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.Back); LeftTrigger = state.Gamepad.LeftTrigger == 255; RightTrigger = state.Gamepad.RightTrigger == 255; var statusString = this.ToString(); if (_lastStatusString != statusString) { _lastStatusString = statusString; Debug.WriteLine(this.ToString()); if (this.ControllerStateChanged != null) { var stateData = $"{LeftStickX}|{LeftStickY}|{RightStickX}|{RightStickY}"; ControllerStateChanged(this, new ControllerEventArgs(stateData)); } } } catch (SharpDX.SharpDXException inputEx) { Debug.WriteLine(inputEx.Message); throw; } } private PropertyInfo[] _PropertyInfos = null; private string _lastStatusString = string.Empty; public override string ToString() { if (_PropertyInfos == null) { _PropertyInfos = this.GetType().GetProperties(); } var sb = new StringBuilder(); foreach (var info in _PropertyInfos) { var value = info.GetValue(this, null) ?? "(null)"; sb.AppendLine(info.Name + ": " + value.ToString()); } return sb.ToString(); } public double LeftStickX { get; set; } public double LeftStickY { get; set; } public double RightStickX { get; set; } public double RightStickY { get; set; } public bool Y { get; set; } public bool B { get; set; } public bool A { get; set; } public bool X { get; set; } public bool DPadUp { get; set; } public bool DPadRight { get; set; } public bool DPadDown { get; set; } public bool DPadLeft { get; set; } public bool LeftShoulder { get; set; } public bool RightShoulder { get; set; } public bool LeftThumb { get; set; } public bool RightThumb { get; set; } public bool Start { get; set; } public bool Back { get; set; } public string LeftAxis { get; set; } public bool LeftTrigger { get; set; } public string RightAxis { get; set; } public bool RightTrigger { get; set; } } }
37.40146
148
0.590359
71fe0d1dad9eeee22e986e53decfabed6ab9b1b4
2,693
cpp
C++
leetcode.051-100/078.subsets/main.cpp
cloudy064/leetcode
b85ec4aed57542247ac4762883bd7fe80b3cfbab
[ "MIT" ]
null
null
null
leetcode.051-100/078.subsets/main.cpp
cloudy064/leetcode
b85ec4aed57542247ac4762883bd7fe80b3cfbab
[ "MIT" ]
null
null
null
leetcode.051-100/078.subsets/main.cpp
cloudy064/leetcode
b85ec4aed57542247ac4762883bd7fe80b3cfbab
[ "MIT" ]
null
null
null
// // Created by cloudy064 on 2019/4/8. // #include "common.h" using namespace std; /// Solution for https://leetcode-cn.com/problems/subsets/ class Solution { public: void pickElement(vector<int>& nums, int skip, int takes, vector<int>& temp, vector<vector<int>>& result) { int size = nums.size(); if (skip + takes > size) return; if (skip + takes == size) { for (int i = skip; i < size; ++i) { temp.push_back(nums[i]); } result.emplace_back(temp); for (int i = skip; i < size; ++i) { temp.pop_back(); } return; } if (takes == 1) { for (int i = skip; i < size; ++i) { temp.push_back(nums[i]); result.emplace_back(temp); temp.pop_back(); } return; } // take current element int num = nums[skip]; temp.push_back(num); pickElement(nums, skip + 1, takes - 1, temp, result); // don't take current element temp.pop_back(); pickElement(nums, skip + 1, takes, temp, result); } vector<vector<int>> subsets(vector<int>& nums) { if (nums.empty()) return { {} }; vector<int> temp; vector<vector<int>> result; result.push_back({}); result.emplace_back(nums); int size = nums.size(); for (int i = 1; i < size; i++) { temp.clear(); pickElement(nums, 0, i, temp, result); } return result; } }; class Test078Solution : public ::testing::Test { public: Solution sln; }; TEST_F(Test078Solution, t1) { vector<vector<int>> expect = { {3}, {1}, {2}, {1,2,3}, {1,3}, {1,2}, {2,3}, {} }; vector<int> nums = { 1,2,3 }; auto result = sln.subsets(nums); sort(expect.begin(), expect.end()); sort(result.begin(), result.end()); EXPECT_EQ(result, expect); } TEST_F(Test078Solution, t2) { vector<vector<int>> expect = { {} }; vector<int> nums = { }; auto result = sln.subsets(nums); sort(expect.begin(), expect.end()); sort(result.begin(), result.end()); EXPECT_EQ(result, expect); } TEST_F(Test078Solution, t3) { vector<vector<int>> expect = { {1}, {} }; vector<int> nums = {1 }; auto result = sln.subsets(nums); sort(expect.begin(), expect.end()); sort(result.begin(), result.end()); EXPECT_EQ(result, expect); } TEST_F(Test078Solution, t4) { vector<vector<int>> expect = { {}, {6}, {5}, {5,6}, {3}, {3,6}, {3,5}, {3,5,6}, {2}, {2,6}, {2,5}, {2,5,6}, {2,3}, {2,3,6}, {2,3,5}, {2,3,5,6}, {1}, {1,6}, {1,5}, {1,5,6}, {1,3}, {1,3,6}, {1,3,5}, {1,3,5,6}, {1,2}, {1,2,6}, {1,2,5}, {1,2,5,6}, {1,2,3}, {1,2,3,6}, {1,2,3,5}, {1,2,3,5,6} }; vector<int> nums = { 1,2,3,5,6 }; auto result = sln.subsets(nums); sort(expect.begin(), expect.end()); sort(result.begin(), result.end()); EXPECT_EQ(result, expect); } GTEST_MAIN
15.748538
107
0.572596
fe34c36f4aff8b98ec75f35a4c778abfae06aaf4
9,451
h
C
wrapper/nim_cpp_wrapper/api/nim_cpp_talkex.h
Mao-Lin-Cooperation/NIM_PC_Demo
f7a6b79bd6945bdf6bdaf46b7190de12ca581119
[ "BSD-2-Clause", "OpenSSL" ]
1
2022-01-17T09:42:37.000Z
2022-01-17T09:42:37.000Z
wrapper/nim_cpp_wrapper/api/nim_cpp_talkex.h
Mao-Lin-Cooperation/NIM_PC_Demo
f7a6b79bd6945bdf6bdaf46b7190de12ca581119
[ "BSD-2-Clause", "OpenSSL" ]
null
null
null
wrapper/nim_cpp_wrapper/api/nim_cpp_talkex.h
Mao-Lin-Cooperation/NIM_PC_Demo
f7a6b79bd6945bdf6bdaf46b7190de12ca581119
[ "BSD-2-Clause", "OpenSSL" ]
null
null
null
/** @file nim_cpp_talkex.h * @brief 收藏、置顶会话、快捷回复、PinMessage、ThreadMessage * @copyright (c) 2015-2020, NetEase Inc. All rights reserved * @date 2020/4/20 */ #ifndef _NIM_SDK_CPP_TALKEX_H_ #define _NIM_SDK_CPP_TALKEX_H_ #include <functional> #include <string> #include "nim_cpp_wrapper/helper/nim_talk_helper.h" #include "nim_cpp_wrapper/helper/nim_talkex_helper_collect.h" #include "nim_cpp_wrapper/helper/nim_talkex_helper_pin_message.h" #include "nim_cpp_wrapper/helper/nim_talkex_helper_quick_comment.h" #include "nim_cpp_wrapper/nim_sdk_cpp_wrapper.h" /** * @namespace nim * @brief namespace nim */ namespace nim { /** @class TalkEx * @brief 聊天功能;主要包括收藏、快捷回复、PinMessage、ThreadMessage、置顶会话 */ class NIM_SDK_CPPWRAPPER_DLL_API TalkEx { public: class NIM_SDK_CPPWRAPPER_DLL_API Collect { public: using AddCollectCallback = std::function<void(int code, const CollectInfo&)>; /**< 添加收藏回调模板 */ using RemoveCollectsCallback = std::function<void(int code, int count)>; /**< 删除收藏回调模板 */ using UpdateCollectCallback = std::function<void(int, const CollectInfo&)>; /**< 更新收藏回调模板 */ using QueryCollectsCallback = std::function<void(int, int, const CollectInfoList&)>; /**< 分页查询回调模板 */ /** @fn static void AddCollect(const CollectInfo& collect_info, const AddCollectCallback& cb) * 添加收藏 * @param[in] collect_info 收藏内容 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void AddCollect(const CollectInfo& collect_info, const AddCollectCallback& cb); /** @fn static void RemoveCollects(const RemoveCollectsParm& collect_list, const RemoveCollectsCallback& cb) * 批量删除收藏 * @param[in] collect_list 要删除的收藏列表 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void RemoveCollects(const RemoveCollectsParm& collect_list, const RemoveCollectsCallback& cb); /** @fn static void UpdateCollectExt(const MatchCollectParm& collect_match_param, const std::string& ext, const UpdateCollectCallback& cb) * 更新收藏扩展字段 * @param[in] collect_match_param 根据收藏的id 与 create time去匹配收藏内容 * @param[in] ext 收藏的扩展字段内容 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void UpdateCollectExt(const MatchCollectParm& collect_match_param, const std::string& ext, const UpdateCollectCallback& cb); /** @fn static void QueryCollectList(const QueryCollectsParm& query_collect_list_param, const QueryCollectsCallback& cb) * 分页查询收藏列表 * @param[in] query_collect_list_param 查询参数 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void QueryCollectList(const QueryCollectsParm& query_collect_list_param, const QueryCollectsCallback& cb); }; class NIM_SDK_CPPWRAPPER_DLL_API QuickComment { public: using AddQuickCommentCallback = std::function<void(int, const QuickCommentInfo&)>; /**< 添加快捷回复回调模板 */ using RemoveQuickCommentCallback = std::function<void(int, const std::string& id)>; /**< 删除快捷回复回调模板 */ using QueryQuickCommentCallback = std::function<void(int, const QueryQuickCommentsResponse&)>; /**< 查询快捷回复回调模板 */ using AddQuickCommentNotifyCallback = std::function<void(const std::string&, NIMSessionType, const std::string&, const QuickCommentInfo&)>; /**<添加快捷回复通知回调*/ using RemoveQuickCommentNotifyCallback = std::function<void(const std::string& session, NIMSessionType type, const std::string& msg_client_id, const std::string& quick_comment_id, const std::string& ext)>; /**< 删除快捷回复通知回调 */ /** @fn void UnregAllCb() * 反注册提供的所有回调 * @return void 无返回值 */ static void UnregAllCb(); /** @fn static void RegAddQuickCommentNotify(const AddQuickCommentNotifyCallback& cb) * 注册添加快捷回复能知 * @param[in] cb 收到通知时的回调函数 * @return void 无返回值 */ static void RegAddQuickCommentNotify(const AddQuickCommentNotifyCallback& cb); /** @fn static void RegRemoveQuickCommentNotify(const RemoveQuickCommentNotifyCallback& cb) * 注册删除快捷回复能知 * @param[in] cb 收到通知时的回调函数 * @return void 无返回值 */ static void RegRemoveQuickCommentNotify(const RemoveQuickCommentNotifyCallback& cb); /** @fn static void AddQuickComment(const IMMessage &msg, const AddQuickCommentCallback& cb) * 添加快捷回复 * @param[in] msg 被回复的消息 * @param[in] info 回复的内容及设置 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void AddQuickComment(const IMMessage& msg, const QuickCommentInfo& info, const AddQuickCommentCallback& cb); /** @fn static void RemoveQuickComment(const IMMessage &msg, const AddQuickCommentCallback& cb) * 添加快捷回复 * @param[in] msg 被回复的消息 * @param[in] info 回复的内容及设置 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void RemoveQuickComment(const IMMessage& msg, const RemoveQuickCommentParam& param, const RemoveQuickCommentCallback& cb); /** @fn void QueryQuickCommentList(const QueryQuickCommentsParam& query_param, const QueryQuickCommentCallback& cb) * 添加快捷回复 * @param[in] query_param 查询参数,一次最多只能查询20条消息的快捷回复 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void QueryQuickCommentList(const QueryQuickCommentsParam& query_param, const QueryQuickCommentCallback& cb); }; class NIM_SDK_CPPWRAPPER_DLL_API PinMsg { public: using PinMessageCallback = std::function<void(int code, const std::string& session, int to_type, const PinMessageInfo&)>; using UnPinMessageCallback = std::function<void(int code, const std::string& session, int to_type, const std::string&)>; using UpdatePinMessageCallback = std::function<void(int code, const std::string& session, int to_type, const PinMessageInfo&)>; using QueryPinMessageCallback = std::function<void(int code, const std::string& session, int to_type, const QueryAllPinMessageResponse&)>; using AddPinMessageNotifyCallback = std::function<void(const std::string& session, int to_type, const PinMessageInfo&)>; using UnPinMessageNotifyCallback = std::function<void(const std::string& session, int to_type, const std::string& id)>; using UpdatePinMessageNotifyCallback = std::function<void(const std::string& session, int to_type, const PinMessageInfo&)>; /** @fn void AddPinMessage(const IMMessage& msg,const PinMessageInfo& pin_info, const PinMessageCallback& cb) * Pin某条消息 * @param[in] msg 要Pin的消息 * @param[in] pin_info Pin的内容 只需赋值 ext参数,其它参数SDK来补充 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void AddPinMessage(const IMMessage& msg, const PinMessageInfo& pin_info, const PinMessageCallback& cb); /** @fn void UnPinMessage(const UnPinMessageParam& unpin_param, const UnPinMessageCallback& cb) * Pin某条消息 * @param[in] modify_param UnPin Message 参数 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void UnPinMessage(const ModifyPinMessageParam& modify_param, const UnPinMessageCallback& cb); /** @fn void UpdatePinMessage(const ModifyPinMessageParam& modify_param, const UpdatePinMessageCallback& cb) * 更新 Pin Message ext字段 * @param[in] modify_param 更新 Pin Message 参数 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void UpdatePinMessage(const ModifyPinMessageParam& modify_param, const UpdatePinMessageCallback& cb); /** @fn void QueryAllPinMessage(const std::string& session,int to_type, const QueryPinMessageCallback& cb) * 查询会话的所有 Pin Message * @param[in] session 会话ID * @param[in] to_type 会话类型 * @param[in] cb 执行结果回调函数 * @return void 无返回值 */ static void QueryAllPinMessage(const std::string& session, int to_type, const QueryPinMessageCallback& cb); /** @fn void UnregAllCb() * 反注册提供的所有回调 * @return void 无返回值 */ static void UnregAllCb(); /** @fn void RegAddPinMessage(const AddPinMessageNotifyCallback& cb) * 注册添加 Pin Message 通知回调 * @param[in] cb 收到通知时的回调函数 * @return void 无返回值 */ static void RegAddPinMessage(const AddPinMessageNotifyCallback& cb); /** @fn void RegUnPinMessage(const UnPinMessageNotifyCallback& cb) * 注册 UnPin Message 通知回调 * @param[in] cb 收到通知时的回调函数 * @return void 无返回值 */ static void RegUnPinMessage(const UnPinMessageNotifyCallback& cb); /** @fn void RegUpdatePinMessage(const UpdatePinMessageNotifyCallback& cb) * 注册 更新Pin Message 通知回调 * @param[in] cb 收到通知时的回调函数 * @return void 无返回值 */ static void RegUpdatePinMessage(const UpdatePinMessageNotifyCallback& cb); }; }; } // namespace nim #endif //_NIM_SDK_CPP_TALKEX_H_
48.466667
146
0.651994
80459fc02c3225223e127ce2cd252ae040f0ed2c
17,862
java
Java
src/main/java/uk/ac/ncl/cs/tongzhou/navigator/RepositoryWalker.java
DnsZhou/online-Java-navigator
9badeb518486ecab46a9db5279ad72757140042f
[ "Apache-2.0" ]
1
2019-04-15T08:53:31.000Z
2019-04-15T08:53:31.000Z
src/main/java/uk/ac/ncl/cs/tongzhou/navigator/RepositoryWalker.java
DnsZhou/online-Java-navigator
9badeb518486ecab46a9db5279ad72757140042f
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/ncl/cs/tongzhou/navigator/RepositoryWalker.java
DnsZhou/online-Java-navigator
9badeb518486ecab46a9db5279ad72757140042f
[ "Apache-2.0" ]
1
2019-05-03T14:52:10.000Z
2019-05-03T14:52:10.000Z
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ncl.cs.tongzhou.navigator; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.javaparser.*; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.PackageDeclaration; import com.github.javaparser.symbolsolver.JavaSymbolSolver; import uk.ac.ncl.cs.tongzhou.navigator.jsonmodel.*; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static uk.ac.ncl.cs.tongzhou.navigator.Util.SLASH; /** * Driver for the parsing and html generation task. */ public class RepositoryWalker { static String TARGET_EXTENSION = "html"; static int allFileAmount = 0; static int existFileAmount = 0; static int errorFileAmount = 0; static List<LinkObject> linkObjectListInCurrentCu; static GavCu currentScanningGavCu; //Switches for TEST use ONLY public static final boolean GENERATE_ID_FOR_ALL = false; public static final boolean DEBUG_MODE = false; public static final boolean GENERATE_PACKAGE_INFO = true; public static final boolean GENERATE_TEST_CASES = false; // TODO change me to an empty dir where the index output will be written public static final String INDEX_PATH = "tmp" + SLASH + "output" + SLASH + "Index"; static final ObjectMapper objectMapper = new ObjectMapper(); // TODO change me to an empty dir where the error output will be written static File outputErrorFileRootDir = new File("tmp" + SLASH + "output" + SLASH + "ErrorDocs"); // TODO change me to an empty dir where the test case output will be written public static File outputTestCaseFileRootDir = new File("tmp" + SLASH + "output" + SLASH + "TestCaseDocs"); static File outputIndexRootDir = new File(INDEX_PATH); // TODO change me to an empty dir where the output will be written public static File outputHtmlRootDir = new File("tmp" + SLASH + "output" + SLASH + TARGET_EXTENSION + "Docs"); // expect ~227021 files. static File outputJsonRootDir = new File("tmp" + SLASH + "output" + SLASH + "JsonDocs"); public static void processRepository() throws Exception { // TODO change me to the location of the repository root File inputRepoRootDir = new File("tmp" + SLASH + "input" + SLASH + "Repository"); // File inputRepoRootDir = new File("tmp" + SLASH + "input" + SLASH + "funcTestRepository"); if (DEBUG_MODE) { System.out.println("Debugging error files in " + outputErrorFileRootDir.toPath()); RepositoryWalker instance = new RepositoryWalker(); instance.processDebugRepository(); } else { //Analysis Repository System.out.println("Analysing repository: " + inputRepoRootDir.getAbsolutePath() + " ... "); allFileAmount = JarFileScanner.countJavaFiles(inputRepoRootDir); System.out.println("Done. " + allFileAmount + " java files found in this repository."); //Parse Repository System.out.println("== Start Parsing Repository =="); RepositoryWalker instance = new RepositoryWalker(); instance.processRepository(inputRepoRootDir, outputHtmlRootDir, outputJsonRootDir); System.out.println("== Parsing Completed.\n" + (allFileAmount - existFileAmount - errorFileAmount) + " file processed."); if (existFileAmount > 0) { System.out.println(existFileAmount + " file already exist. "); } if (errorFileAmount > 0) { System.out.println(errorFileAmount + " file got error during the process. "); } System.out.println("=="); //Index Repository System.out.println("== Start Indexing Repository =="); instance.indexRepository(); System.out.println("== All process finished =="); } } private void processDebugRepository() throws IOException { File debugOutput = new File(outputErrorFileRootDir.getPath(), "DebugResult"); Files.walkFileTree(outputErrorFileRootDir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { if (file.toFile().isFile() && file.toFile().getName().endsWith(".java")) { byte[] inputBytes = Files.readAllBytes(file); processCompilationUnit(inputBytes, debugOutput.toPath(), debugOutput, null, null); } return FileVisitResult.CONTINUE; } }); } private void processRepository(File inputRepoRootDir, File outputHtmlRootDir, File outputJsonRootDir) throws IOException { Files.walkFileTree(inputRepoRootDir.toPath(), new SimpleFileVisitor<Path>() { int processedFileCount = 0; int currentPercentage = 0; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { if (file.toFile().isFile() && file.toFile().getName().endsWith("-sources.jar")) { String relativePath = file.toString() .replace(inputRepoRootDir.getPath(), "") .replace("-sources.jar", ""); File targetDir = new File(outputHtmlRootDir, relativePath); Files.createDirectories(targetDir.toPath()); File targetJsonDir = new File(outputJsonRootDir, relativePath); Files.createDirectories(targetJsonDir.toPath()); /** * To solve the separator problem with regular expression */ String[] pathTokens = relativePath.substring(1).split(SLASH.equals("\\") ? "\\\\" : SLASH); String artifact = pathTokens[pathTokens.length - 3]; String version = pathTokens[pathTokens.length - 2]; String group = relativePath.substring(1).replace(SLASH + artifact + SLASH + version + SLASH + artifact + "-" + version, ""); group = group.replace(SLASH, "."); PackageInfo currentPackageInfo = new PackageInfo(); String gavString = group + ":" + artifact + ":" + version; File packageInfoFile = new File(targetJsonDir, "package.json"); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file.toFile())); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { if (zipEntry.getName().endsWith(".java")) { byte[] inputBytes = zipInputStream.readAllBytes(); String cuPath = zipEntry.getName().replace(".java", ""); String gavCuString = gavString + ":" + cuPath.replace(SLASH, ".").replace("/", "."); File outputFile = new File(targetDir, zipEntry.getName().replace(".java", "." + TARGET_EXTENSION)); File outputJsonFile = new File(targetJsonDir, zipEntry.getName().replace(".java", ".json")); if (!outputFile.exists()) { outputJsonFile.getParentFile().mkdirs(); outputFile.getParentFile().mkdirs(); /*Record current GavCu for Visitor to fetch*/ currentScanningGavCu = new GavCu(gavCuString); byte[] outputBytes = processCompilationUnit(inputBytes, outputFile.toPath(), outputJsonFile, currentPackageInfo, gavCuString); if (outputBytes != null) { Files.write(outputFile.toPath(), outputBytes); } } else { System.out.println("target Html file exists " + file.toFile().getAbsolutePath() + " " + cuPath); existFileAmount++; } printPercentage(); } zipEntry = zipInputStream.getNextEntry(); } zipInputStream.close(); if (GENERATE_PACKAGE_INFO && currentPackageInfo.compilationUnitDecls != null && currentPackageInfo.compilationUnitDecls.length != 0) objectMapper.writeValue(packageInfoFile, currentPackageInfo); } return FileVisitResult.CONTINUE; } private void printPercentage() { this.processedFileCount++; int newPercentage = (processedFileCount * 1000) / allFileAmount; if (newPercentage != this.currentPercentage) { this.currentPercentage = newPercentage; System.out.println((double) newPercentage / 10 + "% " + new Date()); } } }); } private byte[] processCompilationUnit(byte[] inputBytes, Path outputPath, File outputJsonFile, PackageInfo currentPackageInfo, String gavCuString) { // File outputTestCaseFile = new File(outputTestCaseFileRootDir,) byte[] bytesOut; String outputString = null; try { CompilationUnit compilationUnit = parseWithFallback(inputBytes); PackageDeclaration packageDeclaration = compilationUnit.getPackageDeclaration().isPresent() ? compilationUnit.getPackageDeclaration().get() : new PackageDeclaration(); JavaSymbolSolver javaSymbolSolver = new JavaSymbolSolver(new DummyTypeSolver()); javaSymbolSolver.inject(compilationUnit); LinkingVisitor linkingVisitor = new LinkingVisitor(); linkingVisitor.visit(compilationUnit, javaSymbolSolver); linkObjectListInCurrentCu = new ArrayList<>(); switch (TARGET_EXTENSION) { case "html": outputString = StacklessPrinterDriver.print(compilationUnit, new HtmlPrinter()); break; default: outputString = StacklessPrinterDriver.print(compilationUnit, new Printer()); break; } List<String> typeDeclarations = linkingVisitor.getDeclaredTypes(); List<ImportDeclaration> importDeclarations = linkingVisitor.getImportDeclarations(); CompilationUnitDecl compilationUnitDecl = new CompilationUnitDecl(typeDeclarations, importDeclarations, packageDeclaration); objectMapper.writeValue(outputJsonFile, compilationUnitDecl); if (GENERATE_PACKAGE_INFO) { compilationUnitDecl.importDecls = null; currentPackageInfo.add(compilationUnitDecl); } if (GENERATE_TEST_CASES && linkObjectListInCurrentCu != null && !linkObjectListInCurrentCu.isEmpty()) { List<String> gavCuToList = linkObjectListInCurrentCu.stream().map(linkObject -> gavCuString.replace( ":", ",") + "," + linkObject.navFrom + "," + linkObject.navTo) .distinct().collect(Collectors.toList()); File testCaseFile = new File(outputTestCaseFileRootDir, gavCuString .replace(":", "_") + ".csv"); testCaseFile.getParentFile().mkdirs(); Files.write(testCaseFile.toPath(), gavCuToList, StandardCharsets.UTF_8); } bytesOut = outputString.getBytes(StandardCharsets.UTF_8); } catch (Throwable e) { System.out.println("error for " + outputPath.toFile().getAbsolutePath() + " " + e.toString()); errorFileAmount++; try { File outputFile = new File(outputErrorFileRootDir.getAbsolutePath(), outputPath.toString().replace(".html", ".java")); outputFile.getParentFile().mkdirs(); Files.write(outputFile.toPath(), inputBytes); } catch (Exception fe) { System.out.println("ERROR: can not generate the error file to folder: " + fe.toString()); } return null; } return bytesOut; } private CompilationUnit parseWithFallback(byte[] inputBytes) { ParserConfiguration.LanguageLevel[] levels = new ParserConfiguration.LanguageLevel[]{ ParserConfiguration.LanguageLevel.JAVA_11, // fallback to 8 deals with '_' as a var name. ParserConfiguration.LanguageLevel.JAVA_8, // fallback to 1_4 deals with 'enum' as a var name. ParserConfiguration.LanguageLevel.JAVA_1_4 }; CompilationUnit compilationUnit = null; for (int i = 0; i < levels.length && compilationUnit == null; i++) { compilationUnit = tryParseAtLevel(inputBytes, levels[i], false); /** If parsing failed with all version of java, then try parsing with Unicode Escapes*/ if (compilationUnit == null) compilationUnit = tryParseAtLevel(inputBytes, levels[i], true); } return compilationUnit; } private CompilationUnit tryParseAtLevel(byte[] inputBytes, ParserConfiguration.LanguageLevel languageLevel, boolean preprocessUnicodeEscapes) { ParserConfiguration parserConfiguration = new ParserConfiguration(); parserConfiguration.setLanguageLevel(languageLevel); parserConfiguration.setAttributeComments(false); //Solve bug OJN-28 Error while processing Unicode Escaping parserConfiguration.setPreprocessUnicodeEscapes(preprocessUnicodeEscapes); try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputBytes); Provider provider = new StreamProvider(byteArrayInputStream); ParseResult<CompilationUnit> result = new JavaParser(parserConfiguration).parse(ParseStart.COMPILATION_UNIT, provider); if (!result.isSuccessful()) { return null; } else { return result.getResult().get(); } } catch (Exception e) { return null; } } private void indexRepository() throws IOException { //scan all the package.json file in the output/JsonDocs folder and generate index into index/ folder /* Index format: <group>:<artifact>:<version>:<declaration name> eg antlr:antlr:2.7.7.redhat-7:antlr.actions.cpp.ActionLexer */ Files.createDirectories(outputIndexRootDir.toPath()); Files.walkFileTree(outputJsonRootDir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { //Todo: think about whether change it to a special name if (file.toFile().isFile() && file.toFile().getName().equals("package.json")) { String relativePath = file.toString() .replace(outputJsonRootDir.getPath(), "") .replace(SLASH + "package.json", ""); //To solve the separator problem with regular expression String[] pathTokens = relativePath.substring(1).split(SLASH.equals("\\") ? "\\\\" : SLASH); String artifact = pathTokens[pathTokens.length - 3]; String version = pathTokens[pathTokens.length - 2]; String group = relativePath.substring(1) .replace(SLASH + artifact + SLASH + version + SLASH + artifact + "-" + version, ""); group = group.replace(SLASH, "."); PackageInfo currentPackageInfo = objectMapper.readValue(file.toFile(), PackageInfo.class); for (CompilationUnitDecl cuItem : currentPackageInfo.compilationUnitDecls) { for (TypeDecl typeDecl : cuItem.typeDecls) { String typeName = typeDecl.name.substring(typeDecl.name.lastIndexOf(".") + 1, typeDecl.name.length()); String gavCuString = group + ":" + artifact + ":" + version + ":" + typeDecl.name; IndexType.addIndexItem(typeName, gavCuString); } } } return FileVisitResult.CONTINUE; } }); IndexType.generateIndex(); } }
48.275676
158
0.610514
68525ef55b56be9f1349ccde91945c662f9a6b9a
3,803
html
HTML
templates/login.html
Squidtoon99/HacScraper
d085fa18a285d177049f99cb8853778edba767a3
[ "MIT" ]
1
2021-05-12T17:18:23.000Z
2021-05-12T17:18:23.000Z
templates/login.html
Squidtoon99/HacScraper
d085fa18a285d177049f99cb8853778edba767a3
[ "MIT" ]
null
null
null
templates/login.html
Squidtoon99/HacScraper
d085fa18a285d177049f99cb8853778edba767a3
[ "MIT" ]
1
2020-11-08T20:54:25.000Z
2020-11-08T20:54:25.000Z
<!DOCTYPE html> <html lang="en" class="has-background-link-light"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> </head> <body> <div class="hero is-fullheight"> <nav class="navbar is-fixed-top has-background-white" style='box-shadow: 0 0 1em 0 rgba(10,10,10,0.1)'> <div class="navbar-brand"> <a href="/"> <div class="navbar-item has-text-weight-bold has-text-link title is-4">Better HAC</div> </a> </div> <div class="navbar-menu"> <div class="navbar-end"> <div class="navbar-item"> Add User </div> </div> </div> </nav> <div class="hero-body"> <div class="container"> <div class="columns is-centered"> <div class="column is-8"> <form action="/add_user" method="post" class="box"> <label for="name" class="label">Name</label> <div class="control has-icons-left"> <input type="text" class="input" placeholder="Put your name here!" name="name"> <span class="icon is-small is-left"> <i class="fa fa-address-card"></i> </span> </div> <br> <label for="username" class="label">Username</label> <div class="control has-icons-left"> <input type="text" class="input" placeholder="Put your school username here!" name="username"> <span class="icon is-small is-left"> <i class="fa fa-user"></i> </span> </div> <br> <label for="password" class="label">Password</label> <div class="control has-icons-left"> <input type="password" class="input" placeholder="Put your school password here!" name="password"> <span class="icon is-small is-left"> <i class="fa fa-unlock"></i> </span> </div> <br> <label for="url" class="label">URL</label> <div class="control has-icons-left"> <input type="text" class="input" placeholder="Put your HAC url here!" name="url"> <span class="icon is-small is-left"> <i class="fa fa-link"></i> </span> </div> <br> <button type="submit" class="button is-success">Add User!</button> </form> </div> </div> </div> </div> </div> </body> </html>
45.819277
117
0.408625
984806e2afda516e6d3a36f74232024a4a47e11b
67
sql
SQL
hasura/migrations/default/1646843691761_alter_table_public_metadata_drop_column_floor_space/up.sql
tokenocean/demo
025dbbeb0a81403391ade48279d4ffd15e15e241
[ "MIT" ]
null
null
null
hasura/migrations/default/1646843691761_alter_table_public_metadata_drop_column_floor_space/up.sql
tokenocean/demo
025dbbeb0a81403391ade48279d4ffd15e15e241
[ "MIT" ]
null
null
null
hasura/migrations/default/1646843691761_alter_table_public_metadata_drop_column_floor_space/up.sql
tokenocean/demo
025dbbeb0a81403391ade48279d4ffd15e15e241
[ "MIT" ]
1
2022-01-27T04:42:08.000Z
2022-01-27T04:42:08.000Z
alter table "public"."metadata" drop column "floor_space" cascade;
33.5
66
0.776119
4b2f5ff8f77d759caae7765a403488565848c0ee
3,071
html
HTML
ui/fm.html
pathumf89/AAFrecovery
5928185ff1a6cd89c5291061a3415bce15579886
[ "MIT" ]
null
null
null
ui/fm.html
pathumf89/AAFrecovery
5928185ff1a6cd89c5291061a3415bce15579886
[ "MIT" ]
null
null
null
ui/fm.html
pathumf89/AAFrecovery
5928185ff1a6cd89c5291061a3415bce15579886
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <title>Unicorn Admin</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/font-awesome.css" /> <link rel="stylesheet" href="css/colorpicker.css" /> <link rel="stylesheet" href="css/datepicker.css" /> <link rel="stylesheet" href="css/icheck/flat/blue.css" /> <link rel="stylesheet" href="css/select2.css" /> <link rel="stylesheet" href="css/jquery-ui.css" /> <link rel="stylesheet" href="css/unicorn.css" /> <!--[if lt IE 9]> <script type="text/javascript" src="js/respond.min.js"></script> <![endif]--> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-align-justify"></i> </span> <h5>Rest of elements...</h5> </div> <div class="widget-content nopadding"> <form action="#" method="get" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 col-md-3 col-lg-2 control-label">Select input</label> <div class="col-sm-9 col-md-9 col-lg-10"> <select> <option value="CB-20-278">Annual Profit and Loss Form</option> <option value="CB-7789">heading</option> </select> </div> </form> </div> </div> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="fa fa-align-justify"></i> </span> <h5>Rest of elements...</h5> </div> <div class="widget-content nopadding"> <form action="#" method="get" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 col-md-3 col-lg-2 control-label">Select input</label> <div class="col-sm-9 col-md-9 col-lg-10"> <select> <option>First option</option> <option>Second option</option> <option>Third option</option> <option>Fourth option</option> <option>Fifth option</option> <option>Sixth option</option> <option>Seventh option</option> <option>Eighth option</option> </select> </div> </div> <script src="js/jquery.min.js"></script> <script src="js/jquery-ui.custom.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap-colorpicker.js"></script> <script src="js/bootstrap-datepicker.js"></script> <script src="js/jquery.icheck.min.js"></script> <script src="js/select2.min.js"></script> <script src="js/jquery.nicescroll.min.js"></script> <script src="js/unicorn.js"></script> <script src="js/unicorn.form_common.js"></script> </body> </html>
35.298851
86
0.537284
85da0dd802c2218e84fab3a2e01a1160c5dd7083
2,289
asm
Assembly
programs/oeis/154/A154286.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/154/A154286.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/154/A154286.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A154286: a(n) = E(k)*C(n+k,k) = Euler(k)*binomial(n+k,k) for k=4. ; 5,25,75,175,350,630,1050,1650,2475,3575,5005,6825,9100,11900,15300,19380,24225,29925,36575,44275,53130,63250,74750,87750,102375,118755,137025,157325,179800,204600,231880,261800,294525,330225,369075,411255,456950,506350,559650,617050,678755,744975,815925,891825,972900,1059380,1151500,1249500,1353625,1464125,1581255,1705275,1836450,1975050,2121350,2275630,2438175,2609275,2789225,2978325,3176880,3385200,3603600,3832400,4071925,4322505,4584475,4858175,5143950,5442150,5753130,6077250,6414875,6766375,7132125,7512505,7907900,8318700,8745300,9188100,9647505,10123925,10617775,11129475,11659450,12208130,12775950,13363350,13970775,14598675,15247505,15917725,16609800,17324200,18061400,18821880,19606125,20414625,21247875,22106375,22990630,23901150,24838450,25803050,26795475,27816255,28865925,29945025,31054100,32193700,33364380,34566700,35801225,37068525,38369175,39703755,41072850,42477050,43916950,45393150,46906255,48456875,50045625,51673125,53340000,55046880,56794400,58583200,60413925,62287225,64203755,66164175,68169150,70219350,72315450,74458130,76648075,78885975,81172525,83508425,85894380,88331100,90819300,93359700,95953025,98600005,101301375,104057875,106870250,109739250,112665630,115650150,118693575,121796675,124960225,128185005,131471800,134821400,138234600,141712200,145255005,148863825,152539475,156282775,160094550,163975630,167926850,171949050,176043075,180209775,184450005,188764625,193154500,197620500,202163500,206784380,211484025,216263325,221123175,226064475,231088130,236195050,241386150,246662350,252024575,257473755,263010825,268636725,274352400,280158800,286056880,292047600,298131925,304310825,310585275,316956255,323424750,329991750,336658250,343425250,350293755,357264775,364339325,371518425,378803100,386194380,393693300,401300900,409018225,416846325,424786255,432839075,441005850,449287650,457685550,466200630,474833975,483586675,492459825,501454525,510571880,519813000,529179000,538671000,548290125,558037505,567914275,577921575,588060550,598332350,608738130,619279050,629956275,640770975,651724325,662817505,674051700,685428100,696947900,708612300,720422505,732379725,744485175,756740075,769145650,781703130,794413750,807278750,820299375,833476875 add $0,4 bin $0,4 mov $1,$0 mul $1,5
286.125
2,182
0.868502
804b531ce598cb24fcbb1675f4d0de956251cd52
1,012
java
Java
app/src/main/java/com/bozlun/health/android/commdbserver/CommentDataActivity.java
wearheart/BzlHealth
ac1b833474e67ca5e6536d34b7a69e0f878a882b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bozlun/health/android/commdbserver/CommentDataActivity.java
wearheart/BzlHealth
ac1b833474e67ca5e6536d34b7a69e0f878a882b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bozlun/health/android/commdbserver/CommentDataActivity.java
wearheart/BzlHealth
ac1b833474e67ca5e6536d34b7a69e0f878a882b
[ "Apache-2.0" ]
1
2020-02-06T13:43:51.000Z
2020-02-06T13:43:51.000Z
package com.bozlun.health.android.commdbserver; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.bozlun.health.android.R; import com.bozlun.health.android.siswatch.WatchBaseActivity; /** * Created by Admin * Date 2019/3/13 * 用于加载Fragment的activity */ public class CommentDataActivity extends WatchBaseActivity { private FragmentManager fragmentManager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment_data_layout); initViews(); fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.commDataContent,new CommDataFragment()); fragmentTransaction.commit(); } private void initViews() { } }
25.948718
85
0.756917
f3006248928b9920dacecec6fdc7d2e315958690
11,699
ps1
PowerShell
PowerShell/scripts/activeDirectory/privilegedUsersV2.ps1
BanterBoy/Maintenance
21e866a74084a762f269e7af12dd6f3163980dc1
[ "MIT" ]
3
2020-10-29T01:33:16.000Z
2021-11-18T22:09:07.000Z
PowerShell/scripts/activeDirectory/privilegedUsersV2.ps1
BanterBoy/Maintenance
21e866a74084a762f269e7af12dd6f3163980dc1
[ "MIT" ]
null
null
null
PowerShell/scripts/activeDirectory/privilegedUsersV2.ps1
BanterBoy/Maintenance
21e866a74084a762f269e7af12dd6f3163980dc1
[ "MIT" ]
1
2022-02-07T21:33:11.000Z
2022-02-07T21:33:11.000Z
<# Too Many Admins in Your Domain: Expose the Problem(s) and Find a Solution http://blogs.technet.com/b/askpfeplat/archive/2012/07/16/too-many-admins-in-your-domain-expose-the-problem-s-and-find-a-solution-don-t-forget-powershell.aspx http://jeffwouters.nl/index.php/2013/11/powershell-function-to-list-users-in-authorative-groups-in-active-directory/ Too Many Admins in Your Domain: Expose the Problem(s) and Find a Solution. (Don�t forget PowerShell) http://blogs.technet.com/b/askpfeplat/archive/2012/07/16/too-many-admins-in-your-domain-expose-the-problem-s-and-find-a-solution-don-t-forget-powershell.aspx Audit Membership in Privileged Active Directory Groups. A Second Look. http://blogs.technet.com/b/askpfeplat/archive/2013/04/08/audit-membership-in-privileged-active-directory-groups-a-second-look.aspx http://gallery.technet.microsoft.com/scriptcenter/List-Membership-In-bff89703 This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment. THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a nonexclusive, royalty-free right to use and modify the Sample Code and to reproduce and distribute the object code form of the Sample Code, provided that You agree: (i) to not use Our name, logo, or trademarks to market Your software product in which the Sample Code is embedded; (ii) to include a valid copyright notice on Your software product in which the Sample Code is embedded; and (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and against any claims or lawsuits, including attorneys' fees, that arise or result from the use or distribution of the Sample Code. This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm. #> ################## Function to Expand Group Membership ################ function getMemberExpanded { param ($dn) $colOfMembersExpanded = @() $adobject = [adsi]"LDAP://$dn" $colMembers = $adobject.properties.item("member") Foreach ($objMember in $colMembers) { $objMembermod = $objMember.replace("/", "\/") $objAD = [adsi]"LDAP://$objmembermod" $attObjClass = $objAD.properties.item("objectClass") if ($attObjClass -eq "group") { getmemberexpanded $objMember } else { $colOfMembersExpanded += $objMember } } $colOfMembersExpanded } ########################### Function to Calculate Password Age ############## Function getUserAccountAttribs { param($objADUser, $parentGroup) $objADUser = $objADUser.replace("/", "\/") $adsientry = new-object directoryservices.directoryentry("LDAP://$objADUser") $adsisearcher = new-object directoryservices.directorysearcher($adsientry) $adsisearcher.pagesize = 1000 $adsisearcher.searchscope = "base" $colUsers = $adsisearcher.findall() foreach ($objuser in $colUsers) { $dn = $objuser.properties.item("distinguishedname") $sam = $objuser.properties.item("samaccountname") $attObjClass = $objuser.properties.item("objectClass") If ($attObjClass -eq "user") { $description = $objuser.properties.item("description")[0] #$lastlogontimestamp=$objuser.properties.item("lastlogontimestamp") If (($objuser.properties.item("lastlogontimestamp") | Measure-Object).Count -gt 0) { $lastlogontimestamp = $objuser.properties.item("lastlogontimestamp")[0] $lastLogon = [System.DateTime]::FromFileTime($lastlogontimestamp) $lastLogonInDays = ((Get-Date) - $lastLogon).Days if ($lastLogon -match "1/01/1601") { $lastLogon = "Never logged on before" $lastLogonInDays = "N/A" } } else { $lastLogon = "Never logged on before" $lastLogonInDays = "N/A" } $accountexpiration = $objuser.properties.item("accountexpires") $pwdLastSet = $objuser.properties.item("pwdLastSet") if ($pwdLastSet -gt 0) { $pwdLastSet = [datetime]::fromfiletime([int64]::parse($pwdLastSet)) $PasswordAge = ((get-date) - $pwdLastSet).days } Else { $PasswordAge = "<Not Set>" } $uac = $objuser.properties.item("useraccountcontrol") $uac = $uac.item(0) if (($uac -bor 0x0002) -eq $uac) { $disabled = "TRUE" } else { $disabled = "FALSE" } if (($uac -bor 0x10000) -eq $uac) { $passwordneverexpires = "TRUE" } else { $passwordNeverExpires = "FALSE" } } $record = "" | select-object SAM, DN, MemberOf, pwdAge, lastlogon, lastlogonindays, disabled, pWDneverExpires, description $record.SAM = [string]$sam $record.DN = [string]$dn $record.memberOf = [string]$parentGroup $record.pwdAge = $PasswordAge $record.lastlogon = $lastLogon $record.lastlogonindays = $lastLogonInDays $record.disabled = $disabled $record.pWDneverExpires = $passwordNeverExpires $record.description = $description } $record } ####### Function to find all Privileged Groups in the Forest ########## Function getForestPrivGroups { # Privileged Group Membership for the following groups: # - Enterprise Admins - SID: S-1-5-21root domain-519 # - Schema Admins - SID: S-1-5-21root domain-518 # - Domain Admins - SID: S-1-5-21domain-512 # - Cert Publishers - SID: S-1-5-21domain-517 # - Administrators - SID: S-1-5-32-544 # - Account Operators - SID: S-1-5-32-548 # - Server Operators - SID: S-1-5-32-549 # - Backup Operators - SID: S-1-5-32-551 # - Print Operators - SID: S-1-5-32-550 # Reference: http://support.microsoft.com/kb/243330 $colOfDNs = @() $Forest = [System.DirectoryServices.ActiveDirectory.forest]::getcurrentforest() $RootDomain = [string]($forest.rootdomain.name) $forestDomains = $forest.domains $colDomainNames = @() ForEach ($domain in $forestDomains) { $domainname = [string]($domain.name) $colDomainNames += $domainname } $ForestRootDN = FQDN2DN $RootDomain $colDomainDNs = @() ForEach ($domainname in $colDomainNames) { $domainDN = FQDN2DN $domainname $colDomainDNs += $domainDN } $GC = $forest.FindGlobalCatalog() $adobject = [adsi]"GC://$ForestRootDN" $RootDomainSid = New-Object System.Security.Principal.SecurityIdentifier($AdObject.objectSid[0], 0) $RootDomainSid = $RootDomainSid.toString() $colDASids = @() ForEach ($domainDN in $colDomainDNs) { $adobject = [adsi]"GC://$domainDN" $DomainSid = New-Object System.Security.Principal.SecurityIdentifier($AdObject.objectSid[0], 0) $DomainSid = $DomainSid.toString() $daSid = "$DomainSID-512" $colDASids += $daSid $cpSid = "$DomainSID-517" $colDASids += $cpSid } $colPrivGroups = @("S-1-5-32-544"; "S-1-5-32-548"; "S-1-5-32-549"; "S-1-5-32-551"; "S-1-5-32-550"; "$rootDomainSid-519"; "$rootDomainSid-518") $colPrivGroups += $colDASids $searcher = $gc.GetDirectorySearcher() ForEach ($privGroup in $colPrivGroups) { $searcher.filter = "(objectSID=$privGroup)" $Results = $Searcher.FindAll() ForEach ($result in $Results) { $dn = $result.properties.distinguishedname $colOfDNs += $dn } } $colofDNs } ########################## Function to Generate Domain DN from FQDN ######## Function FQDN2DN { Param ($domainFQDN) $colSplit = $domainFQDN.Split(".") $FQDNdepth = $colSplit.length $DomainDN = "" For ($i = 0; $i -lt ($FQDNdepth); $i++) { If ($i -eq ($FQDNdepth - 1)) { $Separator = "" } else { $Separator = "," } [string]$DomainDN += "DC=" + $colSplit[$i] + $Separator } $DomainDN } ########################## MAIN ########################### $forestPrivGroups = GetForestPrivGroups $colAllPrivUsers = @() $MaxUniqueMembers = 25 $MaxPasswordAge = 365 $DetailedConsoleOutput = $False $rootdse = New-Object directoryservices.directoryentry("LDAP://rootdse") Foreach ($privGroup in $forestPrivGroups) { Write-Host "" Write-Host "Enumerating $privGroup.." -foregroundColor yellow $uniqueMembers = @() $colOfMembersExpanded = @() $colofUniqueMembers = @() $members = getmemberexpanded $privGroup If ($members) { $uniqueMembers = $members | sort-object -unique $numberofUnique = $uniqueMembers | Measure-Object | ForEach-Object { $_.Count } Foreach ($uniqueMember in $uniqueMembers) { $objAttribs = getUserAccountAttribs $uniqueMember $privGroup $colOfuniqueMembers += $objAttribs } $colAllPrivUsers += $colOfUniqueMembers } Else { $numberofUnique = 0 } If ($numberofUnique -gt $MaxUniqueMembers) { Write-host "...$privGroup has $numberofUnique unique members" -foregroundColor Red } Else { Write-host "...$privGroup has $numberofUnique unique members" -foregroundColor White } $pwdneverExpiresCount = 0 $pwdAgeCount = 0 ForEach ($user in $colOfuniquemembers) { $i = 0 $userpwdAge = $user.pwdAge $userpwdneverExpires = $user.pWDneverExpires $userSAM = $user.SAM IF ($userpwdneverExpires -eq $True) { $pwdneverExpiresCount ++ $i ++ If ($DetailedConsoleOutput) { Write-host "......$userSAM has a password age of $userpwdage and the password is set to never expire" -foregroundColor Green } } If ($userpwdAge -gt $MaxPasswordAge) { $pwdAgeCount ++ If ($i -gt 0) { If ($DetailedConsoleOutput) { Write-host "......$userSAM has a password age of $userpwdage" -foregroundColor Green } } } } If ($numberofUnique -gt 0) { Write-host "......There are $pwdneverExpiresCount accounts that have the password is set to never expire." -foregroundColor Green Write-host "......There are $pwdAgeCount accounts that have a password age greater than $MaxPasswordAge." -foregroundColor Green } } If ($DetailedConsoleOutput) { write-host "`nComments:" -foregroundColor Yellow write-host " - If a privileged group contains more than $MaxUniqueMembers unique members, it's highlighted in red." -foregroundColor Yellow write-host " - The privileged user is listed if their password is set to never expire." -foregroundColor Yellow write-host " - The privileged user is listed if their password age is greater than $MaxPasswordAge days." -foregroundColor Yellow write-host " - Service accounts should not be privileged users in the domain." -foregroundColor Yellow } $colAllPrivUsers | Export-CSV -notype -path ".\AllPrivUsers.csv" -Delimiter ';' # Remove the quotes (Get-Content ".\AllPrivUsers.csv") | ForEach-Object { $_ -replace '"', "" } | out-file ".\AllPrivUsers.csv" -Force -Encoding ascii
46.059055
168
0.629285
80c8c3310cb89b301a08a4c81c788f31c2b6183b
336
java
Java
spring_base/src/main/java/ioc_di_scope/DiScopePrototype.java
Crisimple/Java
5b2d9bd93b9ab76c1147686ebbadf5f804f3c84e
[ "Apache-2.0" ]
null
null
null
spring_base/src/main/java/ioc_di_scope/DiScopePrototype.java
Crisimple/Java
5b2d9bd93b9ab76c1147686ebbadf5f804f3c84e
[ "Apache-2.0" ]
6
2021-07-06T16:33:56.000Z
2021-07-24T10:40:43.000Z
spring_base/src/main/java/ioc_di_scope/DiScopePrototype.java
Crisimple/Java
5b2d9bd93b9ab76c1147686ebbadf5f804f3c84e
[ "Apache-2.0" ]
null
null
null
package ioc_di_scope; /** * @Author sf * @File DiScopePrototype * @Time 2021-03-27 19:13 * @Description */ public class DiScopePrototype { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } }
12.923077
35
0.666667
843e0910a64a4f81576319dbe498776dc0cbb8a7
4,297
html
HTML
src/app/profil/profil.component.html
benjkap/Desktop-turbo
3cef42a1b86a27892641bb4cacdea3673cfff5b5
[ "MIT" ]
null
null
null
src/app/profil/profil.component.html
benjkap/Desktop-turbo
3cef42a1b86a27892641bb4cacdea3673cfff5b5
[ "MIT" ]
null
null
null
src/app/profil/profil.component.html
benjkap/Desktop-turbo
3cef42a1b86a27892641bb4cacdea3673cfff5b5
[ "MIT" ]
null
null
null
<div class="profil"> <div class="btn-group" id="profilButton"> <button class="btn btn-primary first" title="Profil"> <div id="username" class="text-center font-weight-bolder pl-3 pr-4">{{ ucFirst(user.username) }}</div> <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" fill="currentColor" class="bi bi-person mx-auto mb-1" viewBox="0 0 16 16"> <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z"/> </svg> </button> <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split second" id="dropdownMenuReference" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-reference="parent" data-offset="-10,0"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuReference"> <a id="profile" class="dropdown-item" [routerLink]="['/home']"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house mx-auto mb-1" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M2 13.5V7h1v6.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V7h1v6.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5zm11-11V6l-2-2V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5z"/> <path fill-rule="evenodd" d="M7.293 1.5a1 1 0 0 1 1.414 0l6.647 6.646a.5.5 0 0 1-.708.708L8 2.207 1.354 8.854a.5.5 0 1 1-.708-.708L7.293 1.5z"/> </svg> Home</a> <a id="disconnect" class="dropdown-item" (click)="logout()" > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-left mx-auto mb-1" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M6 12.5a.5.5 0 0 0 .5.5h8a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-8a.5.5 0 0 0-.5.5v2a.5.5 0 0 1-1 0v-2A1.5 1.5 0 0 1 6.5 2h8A1.5 1.5 0 0 1 16 3.5v9a1.5 1.5 0 0 1-1.5 1.5h-8A1.5 1.5 0 0 1 5 12.5v-2a.5.5 0 0 1 1 0v2z"/> <path fill-rule="evenodd" d="M.146 8.354a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L1.707 7.5H10.5a.5.5 0 0 1 0 1H1.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3z"/> </svg> Déconnexion</a> </div> </div> <ul class="list-group mt-5"> <li class="list-group-item d-flex flex-column mt-4"> <div>Nom d'utilisateur: </div> <input type="text" class="form-control bg-light w-50 mt-3 mx-auto" [(ngModel)]="username" (change)="updateUsername(username)" /> </li> <li class="list-group-item d-flex flex-column"> <div>Adresse Mail: </div> <input type="text" class="form-control bg-light w-50 mt-3 mx-auto" [(ngModel)]="email" (change)="updateAdress(email)" /> </li> <li class="list-group-item d-flex flex-column"> <div>Fond d'écran: </div> <input type="text" class="form-control bg-light w-50 mt-3 mx-auto" [(ngModel)]="wallpaper" (change)="updateBackground(wallpaper)" /> </li> </ul> </div> <div class="boutonModificationWidget"> <button type="button" class="btn btn-success mt-3" (click)="activerModificationWidget = true" *ngIf="!activerModificationWidget">Modifier la liste des widgets</button> <button type="button" class="btn btn-success mt-3" (click)="activerModificationWidget = false" *ngIf="activerModificationWidget">Arrêter la modification</button> </div> <div class="selectionWidgets" *ngIf="activerModificationWidget"> <table class="table table-striped"> <thead> <tr> <th scope="col">Nom du widget</th> <th scope="col">Activation</th> </tr> </thead> <tbody> <tr *ngFor="let widget of listeDesWidgets; let o = index"> <th scope="row">{{listeDesWidgets[o].nomWidget}}</th> <td> <button type="button" class="btn btn-danger" *ngIf="listeDesWidgets[o].estActive" (click)="listeDesWidgets[o].estActive = false">On</button> <button type="button" class="btn btn-warning" *ngIf="!listeDesWidgets[o].estActive" (click)="listeDesWidgets[o].estActive = true">Off</button> </td> </tr> </tbody> </table> </div>
60.521127
263
0.617873
c6bbe4250e89d2b4d3e562c3ac157a685f2bdbf9
157
kt
Kotlin
src/main/kotlin/dev/rayzr/gameboi/data/shop/ShopItem.kt
Bronzehail45833/Gameboi
60ebe73996a91892361d2b78a53ebe08959b67c3
[ "MIT" ]
97
2019-06-25T17:08:59.000Z
2022-01-28T01:39:12.000Z
src/main/kotlin/dev/rayzr/gameboi/data/shop/ShopItem.kt
Bronzehail45833/Gameboi
60ebe73996a91892361d2b78a53ebe08959b67c3
[ "MIT" ]
6
2019-06-25T08:56:49.000Z
2021-02-18T15:41:38.000Z
src/main/kotlin/dev/rayzr/gameboi/data/shop/ShopItem.kt
Bronzehail45833/Gameboi
60ebe73996a91892361d2b78a53ebe08959b67c3
[ "MIT" ]
24
2019-07-05T01:37:01.000Z
2021-12-18T18:14:04.000Z
package dev.rayzr.gameboi.data.shop open class ShopItem(val internalName: String, val name: String, val cost: Int, val slot: ItemSlot, val maxQuantity: Int)
52.333333
120
0.783439
5cf30ab9e9ba8e00cab7658a8506d75f9156a9cd
71
lua
Lua
resources/words/fio.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/fio.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/fio.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
return {'fiool','fiona','fiolet','fioole','fiolen','fiooltje','fionas'}
71
71
0.676056
fbaf9064d21231f736f7d85651f5dc05330d004b
822
java
Java
src/main/java/com/ooad/xproject/entity/Permission.java
Carl-Rabbit/xproject_backend
2a98a230bde5d06717ab1b468c35166eb354e258
[ "MIT" ]
2
2020-12-16T16:11:18.000Z
2020-12-19T16:52:22.000Z
web_backend/src/main/java/com/ooad/xproject/entity/Permission.java
Carl-Rabbit/XProject
1bde9c4994fa762251c4c93e1d87e4769d823761
[ "Apache-2.0" ]
null
null
null
web_backend/src/main/java/com/ooad/xproject/entity/Permission.java
Carl-Rabbit/XProject
1bde9c4994fa762251c4c93e1d87e4769d823761
[ "Apache-2.0" ]
null
null
null
package com.ooad.xproject.entity; public class Permission { private Integer pmsId; private String pmsName; private String pmsDesc; private String url; public Integer getPmsId() { return pmsId; } public void setPmsId(Integer pmsId) { this.pmsId = pmsId; } public String getPmsName() { return pmsName; } public void setPmsName(String pmsName) { this.pmsName = pmsName == null ? null : pmsName.trim(); } public String getPmsDesc() { return pmsDesc; } public void setPmsDesc(String pmsDesc) { this.pmsDesc = pmsDesc == null ? null : pmsDesc.trim(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } }
19.116279
63
0.592457
62bb4062a1369d0fbbc13060c92a2e475fa52f16
3,599
html
HTML
generated/en/2018/02/021409.html
tuat-static-syllabus/tuat-static-syllabus.github.io
ad70b206acee2efd03e76744f2d810527f734a6a
[ "MIT" ]
null
null
null
generated/en/2018/02/021409.html
tuat-static-syllabus/tuat-static-syllabus.github.io
ad70b206acee2efd03e76744f2d810527f734a6a
[ "MIT" ]
null
null
null
generated/en/2018/02/021409.html
tuat-static-syllabus/tuat-static-syllabus.github.io
ad70b206acee2efd03e76744f2d810527f734a6a
[ "MIT" ]
null
null
null
--- {"title":"Introduction to Chemical Engineering","permalink":"/en/2018/02/021409.html","layout":"syllabus_details","texts":{"name":"Course title","category":"Course category","requirement":"Requirement","credits":"Credit","department":"Department","grades":"Year","semester":"Semester","course_type":"Course type","course_code":"Course code","instructor":"Instructor(s)","facility_affiliation":"Facility affiliation","office":"Office","email":"Email address","course_description":"Course description","expected_learning":"Expected Learning","course_schedule":"Course schedule","prerequisites":"Prerequisites","texts_and_materials":"Required Text(s) and Materials","references":"References","assessment":"Assessment/Grading","message_from_instructor":"Message from instructor(s)","course_keywords":"Course keywords","office_hours":"Office hours","remarks_1":"Remarks 1","remarks_2":"Remarks 2","related_url":"Related URL","course_language":"Lecture Language","taught_language":"Language Subject","last_update":"Last update","__title":"Introduction to Chemical Engineering"},"contents":{"id":"2018-021409-en","year":2018,"requirement":"","credits":1,"course_code":"021409","email":"","course_description":"History of Chemical Engineering and recent development of Chemical Engineering are investigated by lecture and discussion based on report from students.","expected_learning":"","course_schedule":"1. Background and importance of “Chemical Engineering”\n1.1. History of Chemical Engineering\n(1) Haber-Bosch process (Method of directly synthesizing ammonia from hydrogen and nitrogen)\n(2) Gasoline production process\n1.2. Four important “Pollution-related illnesses” in Japan and the contribution of separation process on the solution of this subjects\n(1) Minamata disease : mercury\n(2) Niigata Minamata disease : mercury\nMercury is highly volatile element, still difficult subjects to separate from flue gas. New production process for NaOH without mercury were developed.\n(3) Itai-itai disease : Cadmium emission, Cd ion in sewer water and dust emission\n(4) Asthma in Yokkaichi : Sulfite gas, Nitrogen oxide and dust, fine particles\nNew Environmental subjects\n\n2. New technology about separation from polluted water and gas\n1) Liquid-liquid extraction, emulsion dispersion (oil in water, water/oil/water)\n2) Adsorption, Zeolite and other adsorbed material (ferrocyanide)\nExample, Fukusima radioactive material Cesium\nEnvironmental standard = 5000 becquerel : the number of atoms / second\n\n3. New concepts for chemical production process engineering,\n/ Closed systems\nSeparation and recycling of unreacted raw feedstock\n/ Zero emission\nl, aggregation and sedimentation etc.\n\n4. Presentation and discussion about \"Chemical Engineering\"\n","prerequisites":"","texts_and_materials":"","assessment":"","message_from_instructor":"","course_keywords":"","office_hours":"Monday afternoon, BASE room 223","remarks_1":"","remarks_2":"","related_url":"","course_language":"Japanese","taught_language":"English","last_update":"4/6/2018 3:21:59 PM","name":{"id":536,"ja":"化学工学序論","en":"Introduction to Chemical Engineering"},"instructor":{"id":509,"ja":"神谷 秀博","en":"KAMIYA Hidehiro"},"present_lang":{"id":2,"lang_name":"English","lang_code":"en"},"grades":{"id":4,"min":1,"max":4},"neutral_department":"Faculty of Engineering","category":"technology speciality courses,ets.","department":"","semester":"Spring","course_type":"Spring","facility_affiliation":"Center for Infectious Disease Epidemiology and Prevention Research","office":"","day_period":"Tue.2","references":""}} ---
1,199.666667
3,591
0.772159
260af80a0679fb9e4b14afdcdd067efc62000ae5
4,211
java
Java
services/iam/src/main/java/com/huaweicloud/sdk/iam/v3/model/AclPolicyResult.java
mathewsreji/huaweicloud-sdk-java-v3
cfa0b14df37c08c56352c129c9cbb7a574a70c79
[ "Apache-2.0" ]
null
null
null
services/iam/src/main/java/com/huaweicloud/sdk/iam/v3/model/AclPolicyResult.java
mathewsreji/huaweicloud-sdk-java-v3
cfa0b14df37c08c56352c129c9cbb7a574a70c79
[ "Apache-2.0" ]
null
null
null
services/iam/src/main/java/com/huaweicloud/sdk/iam/v3/model/AclPolicyResult.java
mathewsreji/huaweicloud-sdk-java-v3
cfa0b14df37c08c56352c129c9cbb7a574a70c79
[ "Apache-2.0" ]
null
null
null
package com.huaweicloud.sdk.iam.v3.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.iam.v3.model.AllowAddressNetmasksResult; import com.huaweicloud.sdk.iam.v3.model.AllowIpRangesResult; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.Objects; /** * */ public class AclPolicyResult { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="allow_address_netmasks") private List<AllowAddressNetmasksResult> allowAddressNetmasks = new ArrayList<>(); @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="allow_ip_ranges") private List<AllowIpRangesResult> allowIpRanges = new ArrayList<>(); public AclPolicyResult withAllowAddressNetmasks(List<AllowAddressNetmasksResult> allowAddressNetmasks) { this.allowAddressNetmasks = allowAddressNetmasks; return this; } public AclPolicyResult addAllowAddressNetmasksItem(AllowAddressNetmasksResult allowAddressNetmasksItem) { this.allowAddressNetmasks.add(allowAddressNetmasksItem); return this; } public AclPolicyResult withAllowAddressNetmasks(Consumer<List<AllowAddressNetmasksResult>> allowAddressNetmasksSetter) { if(this.allowAddressNetmasks == null ){ this.allowAddressNetmasks = new ArrayList<>(); } allowAddressNetmasksSetter.accept(this.allowAddressNetmasks); return this; } /** * 允许访问的IP地址或网段。 * @return allowAddressNetmasks */ public List<AllowAddressNetmasksResult> getAllowAddressNetmasks() { return allowAddressNetmasks; } public void setAllowAddressNetmasks(List<AllowAddressNetmasksResult> allowAddressNetmasks) { this.allowAddressNetmasks = allowAddressNetmasks; } public AclPolicyResult withAllowIpRanges(List<AllowIpRangesResult> allowIpRanges) { this.allowIpRanges = allowIpRanges; return this; } public AclPolicyResult addAllowIpRangesItem(AllowIpRangesResult allowIpRangesItem) { this.allowIpRanges.add(allowIpRangesItem); return this; } public AclPolicyResult withAllowIpRanges(Consumer<List<AllowIpRangesResult>> allowIpRangesSetter) { if(this.allowIpRanges == null ){ this.allowIpRanges = new ArrayList<>(); } allowIpRangesSetter.accept(this.allowIpRanges); return this; } /** * 允许访问的IP地址区间。 * @return allowIpRanges */ public List<AllowIpRangesResult> getAllowIpRanges() { return allowIpRanges; } public void setAllowIpRanges(List<AllowIpRangesResult> allowIpRanges) { this.allowIpRanges = allowIpRanges; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AclPolicyResult aclPolicyResult = (AclPolicyResult) o; return Objects.equals(this.allowAddressNetmasks, aclPolicyResult.allowAddressNetmasks) && Objects.equals(this.allowIpRanges, aclPolicyResult.allowIpRanges); } @Override public int hashCode() { return Objects.hash(allowAddressNetmasks, allowIpRanges); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AclPolicyResult {\n"); sb.append(" allowAddressNetmasks: ").append(toIndentedString(allowAddressNetmasks)).append("\n"); sb.append(" allowIpRanges: ").append(toIndentedString(allowIpRanges)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
31.192593
124
0.687248
240268d4a3dc6abb0723aabce1a194eb7031827b
27
sql
SQL
test/fixtures/query_with_literal_arguments.sql
carwow/olaf
04fa14181e1e49c896e5716f38ecaf411a37b64a
[ "MIT" ]
4
2020-10-22T15:03:51.000Z
2021-02-12T12:44:52.000Z
test/fixtures/query_with_literal_arguments.sql
carwow/olaf
04fa14181e1e49c896e5716f38ecaf411a37b64a
[ "MIT" ]
null
null
null
test/fixtures/query_with_literal_arguments.sql
carwow/olaf
04fa14181e1e49c896e5716f38ecaf411a37b64a
[ "MIT" ]
null
null
null
SELECT 1 FROM :table_name;
13.5
26
0.777778
0f0b6e248aac6dc01cf0791c494e63770596d83f
1,775
cpp
C++
BluetoothImplementations/BlueZ/src/MediaContext.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
1,272
2017-08-17T04:58:05.000Z
2022-03-27T03:28:29.000Z
BluetoothImplementations/BlueZ/src/MediaContext.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
1,948
2017-08-17T03:39:24.000Z
2022-03-30T15:52:41.000Z
BluetoothImplementations/BlueZ/src/MediaContext.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
630
2017-08-17T06:35:59.000Z
2022-03-29T04:04:44.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <gio/gio.h> #include "BlueZ/MediaContext.h" namespace alexaClientSDK { namespace bluetoothImplementations { namespace blueZ { MediaContext::~MediaContext() { if (m_mediaStreamFD != INVALID_FD) { close(m_mediaStreamFD); } if (m_isSBCInitialized) { sbc_finish(&m_sbcContext); } } MediaContext::MediaContext() : m_mediaStreamFD{INVALID_FD}, m_readMTU{0}, m_writeMTU{0}, m_isSBCInitialized{false} { } void MediaContext::setStreamFD(int streamFD) { m_mediaStreamFD = streamFD; } int MediaContext::getStreamFD() { return m_mediaStreamFD; } void MediaContext::setReadMTU(int readMTU) { m_readMTU = readMTU; } int MediaContext::getReadMTU() { return m_readMTU; } void MediaContext::setWriteMTU(int writeMTU) { m_writeMTU = writeMTU; } int MediaContext::getWriteMTU() { return m_writeMTU; } sbc_t* MediaContext::getSBCContextPtr() { return &m_sbcContext; } bool MediaContext::isSBCInitialized() { return m_isSBCInitialized; } void MediaContext::setSBCInitialized(bool initialized) { m_isSBCInitialized = initialized; } } // namespace blueZ } // namespace bluetoothImplementations } // namespace alexaClientSDK
23.666667
116
0.725634
0c5f0e99782d2d6e3ea81f123c8f73f76d979510
753
swift
Swift
GitHubSearch.iOS/GitHubSearch/UI/Main/RootView.swift
teh-nsd/GitHubSearch.iOS
d862fd635e176308b71a4be1ef7d4acc15888684
[ "MIT" ]
null
null
null
GitHubSearch.iOS/GitHubSearch/UI/Main/RootView.swift
teh-nsd/GitHubSearch.iOS
d862fd635e176308b71a4be1ef7d4acc15888684
[ "MIT" ]
null
null
null
GitHubSearch.iOS/GitHubSearch/UI/Main/RootView.swift
teh-nsd/GitHubSearch.iOS
d862fd635e176308b71a4be1ef7d4acc15888684
[ "MIT" ]
1
2021-11-23T08:20:54.000Z
2021-11-23T08:20:54.000Z
// // RootView.swift // GitHubSearch.iOS // // Created by Nikolay Dimitrov on 27.09.21. // import SwiftUI struct RootView: View { @ObservedObject var applicationService: ApplicationService var body: some View { ZStack { switch applicationService.state.content { case .splash: SplashView() .transition(AnyTransition.opacity.animation(.linear)) case .main: RepositoriesView() .environmentObject(applicationService) .environmentObject(applicationService.coreDomainService) } } } }
23.53125
80
0.500664
96949ecef1f22c500b14ef6a557652fcbb870b1b
964
html
HTML
manuscript/page-415/body.html
marvindanig/a-tale-of-two-cities
a7f0d73d45c4c6ce23bc0637fb5342e06b9eaf50
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
manuscript/page-415/body.html
marvindanig/a-tale-of-two-cities
a7f0d73d45c4c6ce23bc0637fb5342e06b9eaf50
[ "BlueOak-1.0.0", "MIT" ]
2
2020-09-06T10:05:57.000Z
2021-05-08T00:06:00.000Z
manuscript/page-415/body.html
marvindanig/a-tale-of-two-cities
a7f0d73d45c4c6ce23bc0637fb5342e06b9eaf50
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><p class="no-indent ">“Extermination.”</p><p>The hungry man repeated, in a rapturous croak, “Magnificent!” and began gnawing another finger.</p><p>“Are you sure,” asked Jacques Two, of Defarge, “that no embarrassment can arise from our manner of keeping the register? Without doubt it is safe, for no one beyond ourselves can decipher it; but shall we always be able to decipher it—or, I ought to say, will she?”</p><p>“Jacques,” returned Defarge, drawing himself up, “if madame my wife undertook to keep the register in her memory alone, she would not lose a word of it—not a syllable of it. Knitted, in her own stitches and her own symbols, it will always be as plain to her as the sun. Confide in Madame Defarge. It would be easier for the weakest poltroon that lives, to erase himself from existence, than to erase one letter of his name or crimes from the knitted register of Madame Defarge.”</p></div> </div>
964
964
0.758299
2547f34ccaffd7a083f95510d9fe3613d43fb6f8
1,815
html
HTML
Desafios/d001/responsivo.html
jonh-dev/html-css-modulo002
99b0dddd2ae3a68a949c36e8f61ea3e4f9d0b206
[ "MIT" ]
null
null
null
Desafios/d001/responsivo.html
jonh-dev/html-css-modulo002
99b0dddd2ae3a68a949c36e8f61ea3e4f9d0b206
[ "MIT" ]
null
null
null
Desafios/d001/responsivo.html
jonh-dev/html-css-modulo002
99b0dddd2ae3a68a949c36e8f61ea3e4f9d0b206
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Teste de Responsividade</title> <style> body{ background-color: gray; } main{ text-align: justify; background-color: white; padding: 20px; border-radius: 10px; margin: auto; max-width: 800px; min-width: 320px; } img{ width: 100%; } </style> </head> <body> <main> <h1>Testando Responsividade</h1> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nobis itaque fugiat ex eos facilis quos maxime, omnis, perspiciatis magnam ipsam vero dolorem sunt voluptates accusantium deleniti quae culpa perferendis iste? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam itaque optio mollitia veritatis dolore perferendis numquam veniam est! Eligendi commodi expedita doloribus a voluptas necessitatibus illum sit minima sequi fuga.</p> <picture> <source media="(max-width:600px)" srcset="imagens/irina-blok-pq.jpg"> <img src="imagens/irina-blok.jpg" alt="Irina Blok"> </picture> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nobis itaque fugiat ex eos facilis quos maxime, omnis, perspiciatis magnam ipsam vero dolorem sunt voluptates accusantium deleniti quae culpa perferendis iste? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam itaque optio mollitia veritatis dolore perferendis numquam veniam est! Eligendi commodi expedita doloribus a voluptas necessitatibus illum sit minima sequi fuga.</p> </main> </body> </html>
45.375
457
0.671074
c071ff46d898fa667b9fbabb76482fecd2247757
2,486
html
HTML
doc/simics-reference-manual-public-all/topic238.html
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
1
2020-06-15T10:41:18.000Z
2020-06-15T10:41:18.000Z
doc/simics-reference-manual-public-all/topic238.html
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
null
null
null
doc/simics-reference-manual-public-all/topic238.html
qiyancos/Simics-3.0.31
9bd52d5abad023ee87a37306382a338abf7885f1
[ "BSD-4-Clause", "FSFAP" ]
3
2020-08-10T10:25:02.000Z
2021-09-12T01:12:09.000Z
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>perfanalyze-client</title> <style>@import url(style.css);</style> </head> <body class="jdocu_main"> <script type="text/javascript"> parent.frames['toc'].d.openTo(1305, true); </script> <a name="label9069"></a><p class="jdocu_navbarp"><span class="jdocu_navbar">VIRTUTECH CONFIDENTIAL&nbsp;&nbsp;&nbsp;&nbsp;<a class="jdocu" href="topic237.html">Previous</a> - <a class="jdocu" href="topic15.html">Up</a> - <a class="jdocu" href="topic239.html">Next</a></span></p> <h3 class="jdocu">perfanalyze-client</h3 class="jdocu"> <a name="label9070"></a><dl class="jdocu_di"> <dt class="jdocu_di"><b>Provided by</b></dt><dd class="jdocu_di"> <a class="jdocu" href="topic14.html#label2754">perfanalyze-client</a></dd> <dt class="jdocu_di"><b>Class Hierarchy</b></dt><dd class="jdocu_di"> <a class="jdocu" href="topic48.html#label4590">conf-object</a> &#8594; <b>perfanalyze-client</b></dd> <dt class="jdocu_di"><b>Interfaces Implemented</b></dt><dd class="jdocu_di"> None</dd> <dt class="jdocu_di_description">Description</dt><dd class="jdocu_di_description"> Internal analysis class. </dd> </dl> <a name="label9071"></a><h4 class="jdocu">Attributes</h4 class="jdocu"> <dl class="jdocu_di"> <dt class="jdocu_di"><b>Attributes inherited from class <a class="jdocu" href="topic48.html#label4590">conf-object</a></b></dt><dd class="jdocu_di"> <i><a class="jdocu" href="topic48.html#label4593">attributes</a></i>, <i><a class="jdocu" href="topic48.html#label4594">classname</a></i>, <i><a class="jdocu" href="topic48.html#label4595">component</a></i>, <i><a class="jdocu" href="topic48.html#label4596">iface</a></i>, <i><a class="jdocu" href="topic48.html#label4597">name</a></i>, <i><a class="jdocu" href="topic48.html#label4598">object_id</a></i>, <i><a class="jdocu" href="topic48.html#label4599">queue</a></i></dd> <dt class="jdocu_di"><b>Attribute List</b></dt><dd class="jdocu_di"> <dl><dt><b><i>memory_usage</i></b></dt><a name="label9072"></a><dd><b>Pseudo</b> <b>class</b> attribute; <b>read-only</b> access; type: <b>unknown type</b>. <p> Internal.</dd></dl> </dd> </dl> <p class="jdocu_navbarp"><span class="jdocu_navbar">VIRTUTECH CONFIDENTIAL&nbsp;&nbsp;&nbsp;&nbsp;<a class="jdocu" href="topic237.html">Previous</a> - <a class="jdocu" href="topic15.html">Up</a> - <a class="jdocu" href="topic239.html">Next</a></span></p> </body> </html>
40.754098
474
0.675382
acccfae2e2118b3b99fbe660b78748ad4f24687e
1,006
cpp
C++
src/Model.cpp
dorchard/nextsimdg
f27de8c97313fbcba4ab6e35c2c5c5e9539d3f5d
[ "Apache-2.0" ]
3
2022-01-13T07:48:19.000Z
2022-01-17T09:19:12.000Z
src/Model.cpp
dorchard/nextsimdg
f27de8c97313fbcba4ab6e35c2c5c5e9539d3f5d
[ "Apache-2.0" ]
51
2021-09-08T10:19:46.000Z
2022-03-31T01:35:48.000Z
src/Model.cpp
dorchard/nextsimdg
f27de8c97313fbcba4ab6e35c2c5c5e9539d3f5d
[ "Apache-2.0" ]
5
2021-12-07T19:15:16.000Z
2022-02-24T13:08:03.000Z
/*! * @file Model.cpp * @date 12 Aug 2021 * @author Tim Spain <timothy.spain@nersc.no> */ #include "Model.hpp" #include "SimpleIterant.hpp" namespace Nextsim { Model::Model( ) { iterant = new SimpleIterant( ); deleteIterant = true; iterator.setIterant(iterant); const int runLength = 5; Iterator::TimePoint now(std::chrono::system_clock::now()); Iterator::Duration dt = std::chrono::seconds(1); Iterator::TimePoint hence = now + runLength * dt; iterator.setStartStopStep(now, hence, dt); } // TODO: add another constructor which takes arguments specifying the // environment and configuration. This will be the location of the // logic with selects the components of the model that will run, // translates I/O details from file configuration to object variable // values, specifies file paths and likely more besides. Model::~Model( ) { if (deleteIterant) delete iterant; } void Model::run( ) { iterator.run(); } } /* namespace Nextsim */
22.355556
69
0.686879
1937a26c5d5a45e9212f535f119d19ceec2f9b66
416
nasm
Assembly
Challenges/ZeroDays 2017/Misc/3 Ward Solutions EAX/code.nasm
victorazzam/stash
c9c9a4c32e5118835d1891fef5b7f27bd3062bb3
[ "MIT" ]
5
2016-12-17T20:11:26.000Z
2020-02-13T08:31:44.000Z
Challenges/ZeroDays 2017/Misc/3 Ward Solutions EAX/code.nasm
victorazzam/stash
c9c9a4c32e5118835d1891fef5b7f27bd3062bb3
[ "MIT" ]
null
null
null
Challenges/ZeroDays 2017/Misc/3 Ward Solutions EAX/code.nasm
victorazzam/stash
c9c9a4c32e5118835d1891fef5b7f27bd3062bb3
[ "MIT" ]
3
2019-04-03T14:41:40.000Z
2020-02-14T19:03:37.000Z
; Compile with --> nasm -f macho code.nasm ; Link with -----> ld -arch i386 -e _start code.o SECTION .text GLOBAL _start GLOBAL L1 GLOBAL L2 GLOBAL L3 _start: MOV ebx,19 MOV ecx,31218 SUB ebx,ecx MOV eax,19211 ADD ebx,eax CMP ebx,eax JL L2 JMP L1 L1: IMUL ebx,eax ADD ebx,eax MOV eax,ebx SUB eax,ecx JMP L3 L2: IMUL ebx,eax SUB ebx,eax MOV eax,ebx ADD eax,ecx L3: INT3 NOP
11.555556
49
0.649038
c0284a30cea7748de26d90b6a3cb5c6583d4a09d
611
swift
Swift
SegmentAdjust/SegmentAdjust/SEGAdjustIntegrationFactory.swift
nodes-ios/segment-adjust
7bd32602bf1385b62f1cd1abf3870e1e92d91dd9
[ "MIT" ]
null
null
null
SegmentAdjust/SegmentAdjust/SEGAdjustIntegrationFactory.swift
nodes-ios/segment-adjust
7bd32602bf1385b62f1cd1abf3870e1e92d91dd9
[ "MIT" ]
null
null
null
SegmentAdjust/SegmentAdjust/SEGAdjustIntegrationFactory.swift
nodes-ios/segment-adjust
7bd32602bf1385b62f1cd1abf3870e1e92d91dd9
[ "MIT" ]
null
null
null
// // SEGAdjustIntegrationFactory.swift // SegmentAdjust // // Created by Todor Brachkov on 30/09/2016. // Copyright © 2016 Nodes. All rights reserved. // import UIKit import Analytics open class SEGAdjustIntegrationFactory: NSObject, SEGIntegrationFactory { static let sharedInstance = SEGAdjustIntegrationFactory() private override init() {} public func create(withSettings settings: [AnyHashable : Any]!, for analytics: SEGAnalytics!) -> SEGIntegration! { return SEGAdjustIntegration(settings) } public func key() -> String { return "Adjust" } }
23.5
118
0.695581
deb167a4e2b88d935263b062e44621184ced34e6
1,212
sql
SQL
misc/sql-scraps/foreign-keys.sql
unison/unison
756c20cb6cb044a1dd929dfb7d14bbc0b4888d69
[ "Apache-2.0" ]
null
null
null
misc/sql-scraps/foreign-keys.sql
unison/unison
756c20cb6cb044a1dd929dfb7d14bbc0b4888d69
[ "Apache-2.0" ]
null
null
null
misc/sql-scraps/foreign-keys.sql
unison/unison
756c20cb6cb044a1dd929dfb7d14bbc0b4888d69
[ "Apache-2.0" ]
null
null
null
create or replace view v_foreign_keys as select FN.nspname as "Fnamespace",FR.relname as "Frelation",FA.attname as "Fcolumn", PN.nspname as "Pnamespace",PR.relname as "Prelation",PA.attname as "Pcolumn", CN.nspname as "Cnamespace",C.conname as "Cname",c.confupdtype || c.confdeltype as "ud" from pg_constraint C join pg_namespace CN on CN.oid=C.connamespace join pg_class FR on FR.oid=C.conrelid join pg_namespace FN on FN.oid=FR.relnamespace join pg_attribute FA on FA.attrelid=C.conrelid and FA.attnum = ANY (C.conkey) join pg_class PR on PR.oid=C.confrelid join pg_namespace PN on PN.oid=PR.relnamespace join pg_attribute PA on PA.attrelid=C.confrelid and PA.attnum = ANY (C.confkey) where C.contype='f'; create or replace view v_foreign_keys_pp as select "Fnamespace"||'.'||"Frelation"||'('||"Fcolumn"||')' as "foreign key", "Cnamespace"||'.'||"Cname" || ' ('||"ud"||')' as "constraint", "Pnamespace"||'.'||"Prelation"||'('||"Pcolumn"||')' as "primary key" from v_foreign_keys; grant select on v_foreign_keys,v_foreign_keys_pp to PUBLIC; comment on view v_foreign_keys is 'foreign key relationships in the database'; comment on view v_foreign_keys_pp is 'pretty print of foreign_keys view';
43.285714
88
0.741749
86f413f1cd2ff2c03c52b9b93ddee7dd723d7f59
12,609
go
Go
expression/generator/time_vec.go
big747386/tidb
c59d2cd8be122466863989b9d5adaa6f7b6fefbb
[ "Apache-2.0" ]
4
2018-12-27T14:38:10.000Z
2019-10-28T15:10:52.000Z
expression/generator/time_vec.go
big747386/tidb
c59d2cd8be122466863989b9d5adaa6f7b6fefbb
[ "Apache-2.0" ]
12
2018-11-29T12:08:20.000Z
2019-10-27T01:48:36.000Z
expression/generator/time_vec.go
big747386/tidb
c59d2cd8be122466863989b9d5adaa6f7b6fefbb
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. // +build ignore package main import ( "bytes" "flag" "go/format" "io/ioutil" "log" "path/filepath" "text/template" . "github.com/pingcap/tidb/expression/generator/helper" ) var addTime = template.Must(template.New("").Parse(`// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. // Code generated by go generate in expression/generator; DO NOT EDIT. package expression import ( "github.com/pingcap/parser/mysql" "github.com/pingcap/parser/terror" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" ) {{ define "SetNull" }}{{if .Output.Fixed}}result.SetNull(i, true){{else}}result.AppendNull(){{end}} // fixed: {{.Output.Fixed }}{{ end }} {{ define "ConvertStringToDuration" }} {{ if ne .SigName "builtinAddStringAndStringSig" }} if !isDuration(arg1) { {{ template "SetNull" . }} continue }{{ end }} sc := b.ctx.GetSessionVars().StmtCtx arg1Duration, err := types.ParseDuration(sc, arg1, {{if eq .Output.TypeName "String"}}getFsp4TimeAddSub{{else}}types.GetFsp{{end}}(arg1)) if err != nil { if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) { sc.AppendWarning(err) {{ template "SetNull" . }} continue } return err } {{ end }} {{ define "strDurationAddDuration" }} var output string if isDuration(arg0) { output, err = strDurationAddDuration(sc, arg0, arg1Duration) if err != nil { if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) { sc.AppendWarning(err) {{ template "SetNull" . }} continue } return err } } else { output, err = strDatetimeAddDuration(sc, arg0, arg1Duration) if err != nil { return err } } {{ end }} {{ range . }} {{ if .AllNull}} func (b *{{.SigName}}) vecEval{{ .Output.TypeName }}(input *chunk.Chunk, result *chunk.Column) error { n := input.NumRows() {{ if .Output.Fixed }} result.Resize{{ .Output.TypeNameInColumn }}(n, true) {{ else }} result.Reserve{{ .Output.TypeNameInColumn }}(n) for i := 0; i < n; i++ { result.AppendNull() } {{ end }} return nil } {{ else }} func (b *{{.SigName}}) vecEval{{ .Output.TypeName }}(input *chunk.Chunk, result *chunk.Column) error { n := input.NumRows() {{ $reuse := (and (eq .TypeA.TypeName .Output.TypeName) .TypeA.Fixed) }} {{ if $reuse }} if err := b.args[0].VecEval{{ .TypeA.TypeName }}(b.ctx, input, result); err != nil { return err } buf0 := result {{ else }} buf0, err := b.bufAllocator.get(types.ET{{.TypeA.ETName}}, n) if err != nil { return err } defer b.bufAllocator.put(buf0) if err := b.args[0].VecEval{{ .TypeA.TypeName }}(b.ctx, input, buf0); err != nil { return err } {{ end }} {{ if eq .SigName "builtinAddStringAndStringSig" }} arg1Type := b.args[1].GetType() if mysql.HasBinaryFlag(arg1Type.Flag) { result.Reserve{{ .Output.TypeNameInColumn }}(n) for i := 0; i < n; i++ { result.AppendNull() } return nil } {{ end }} buf1, err := b.bufAllocator.get(types.ET{{.TypeB.ETName}}, n) if err != nil { return err } defer b.bufAllocator.put(buf1) if err := b.args[1].VecEval{{ .TypeB.TypeName }}(b.ctx, input, buf1); err != nil { return err } {{ if $reuse }} result.MergeNulls(buf1) {{ else if .Output.Fixed}} result.Resize{{ .Output.TypeNameInColumn }}(n, false) result.MergeNulls(buf0, buf1) {{ else }} result.Reserve{{ .Output.TypeNameInColumn}}(n) {{ end }} {{ if .TypeA.Fixed }} arg0s := buf0.{{.TypeA.TypeNameInColumn}}s() {{ end }} {{ if .TypeB.Fixed }} arg1s := buf1.{{.TypeB.TypeNameInColumn}}s() {{ end }} {{ if .Output.Fixed }} resultSlice := result.{{.Output.TypeNameInColumn}}s() {{ end }} for i := 0; i < n; i++ { {{ if .Output.Fixed }} if result.IsNull(i) { continue } {{ else }} if buf0.IsNull(i) || buf1.IsNull(i) { result.AppendNull() continue } {{ end }} // get arg0 & arg1 {{ if .TypeA.Fixed }} arg0 := arg0s[i] {{ else }} arg0 := buf0.Get{{ .TypeA.TypeNameInColumn }}(i) {{ end }} {{ if .TypeB.Fixed }} arg1 := arg1s[i] {{ else }} arg1 := buf1.Get{{ .TypeB.TypeNameInColumn }}(i) {{ end }} // calculate {{ if eq .SigName "builtinAddDatetimeAndDurationSig" }} output, err := arg0.Add(b.ctx.GetSessionVars().StmtCtx, types.Duration{Duration: arg1, Fsp: -1}) if err != nil { return err } {{ else if eq .SigName "builtinAddDatetimeAndStringSig" }} {{ template "ConvertStringToDuration" . }} output, err := arg0.Add(sc, arg1Duration) if err != nil { return err } {{ else if eq .SigName "builtinAddDurationAndDurationSig" }} output, err := types.AddDuration(arg0, arg1) if err != nil { return err } {{ else if eq .SigName "builtinAddDurationAndStringSig" }} {{ template "ConvertStringToDuration" . }} output, err := types.AddDuration(arg0, arg1Duration.Duration) if err != nil { return err } {{ else if eq .SigName "builtinAddStringAndDurationSig" }} sc := b.ctx.GetSessionVars().StmtCtx fsp1 := int8(b.args[1].GetType().Decimal) arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1} {{ template "strDurationAddDuration" . }} {{ else if eq .SigName "builtinAddStringAndStringSig" }} {{ template "ConvertStringToDuration" . }} {{ template "strDurationAddDuration" . }} {{ else if eq .SigName "builtinAddDateAndDurationSig" }} fsp0 := int8(b.args[0].GetType().Decimal) fsp1 := int8(b.args[1].GetType().Decimal) arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1} sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Add(arg1Duration) if err != nil { return err } output := sum.String() {{ else if eq .SigName "builtinAddDateAndStringSig" }} {{ template "ConvertStringToDuration" . }} fsp0 := int8(b.args[0].GetType().Decimal) sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Add(arg1Duration) if err != nil { return err } output := sum.String() {{ end }} // commit result {{ if .Output.Fixed }} resultSlice[i] = output {{ else }} result.Append{{ .Output.TypeNameInColumn }}(output) {{ end }} } return nil } {{ end }}{{/* if .AllNull */}} func (b *{{.SigName}}) vectorized() bool { return true } {{ end }}{{/* range */}} `)) var testFile = template.Must(template.New("").Parse(`// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. // Code generated by go generate in expression/generator; DO NOT EDIT. package expression import ( "testing" . "github.com/pingcap/check" "github.com/pingcap/parser/ast" "github.com/pingcap/parser/mysql" "github.com/pingcap/tidb/types" ) type gener struct { defaultGener } func (g gener) gen() interface{} { result := g.defaultGener.gen() if _, ok := result.(string); ok { dg := &defaultGener{eType: types.ETDuration, nullRation: 0} d := dg.gen().(types.Duration) if int8(d.Duration)%2 == 0 { d.Fsp = 0 } else { d.Fsp = 1 } result = d.String() } return result } {{/* Add more test cases here if we have more functions in this file */}} var vecBuiltin{{.Category}}GeneratedCases = map[string][]vecExprBenchCase{ {{ range .Functions }} ast.{{.FuncName}}: { {{ range .Sigs }} // {{ .SigName }} { retEvalType: types.ET{{ .Output.ETName }}, childrenTypes: []types.EvalType{types.ET{{ .TypeA.ETName }}, types.ET{{ .TypeB.ETName }}}, {{ if ne .FieldTypeA "" }} childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.Type{{.FieldTypeA}}), types.NewFieldType(mysql.Type{{.FieldTypeB}})}, {{ end }} geners: []dataGenerator{ gener{defaultGener{eType: types.ET{{.TypeA.ETName}}, nullRation: 0.2}}, gener{defaultGener{eType: types.ET{{.TypeB.ETName}}, nullRation: 0.2}}, }, }, {{ end }} {{ end }} }, } func (s *testEvaluatorSuite) TestVectorizedBuiltin{{.Category}}EvalOneVecGenerated(c *C) { testVectorizedEvalOneVec(c, vecBuiltin{{.Category}}GeneratedCases) } func (s *testEvaluatorSuite) TestVectorizedBuiltin{{.Category}}FuncGenerated(c *C) { testVectorizedBuiltinFunc(c, vecBuiltin{{.Category}}GeneratedCases) } func BenchmarkVectorizedBuiltin{{.Category}}EvalOneVecGenerated(b *testing.B) { benchmarkVectorizedEvalOneVec(b, vecBuiltin{{.Category}}GeneratedCases) } func BenchmarkVectorizedBuiltin{{.Category}}FuncGenerated(b *testing.B) { benchmarkVectorizedBuiltinFunc(b, vecBuiltin{{.Category}}GeneratedCases) } `)) var addTimeSigsTmpl = []sig{ {SigName: "builtinAddDatetimeAndDurationSig", TypeA: TypeDatetime, TypeB: TypeDuration, Output: TypeDatetime}, {SigName: "builtinAddDatetimeAndStringSig", TypeA: TypeDatetime, TypeB: TypeString, Output: TypeDatetime}, {SigName: "builtinAddDurationAndDurationSig", TypeA: TypeDuration, TypeB: TypeDuration, Output: TypeDuration}, {SigName: "builtinAddDurationAndStringSig", TypeA: TypeDuration, TypeB: TypeString, Output: TypeDuration}, {SigName: "builtinAddStringAndDurationSig", TypeA: TypeString, TypeB: TypeDuration, Output: TypeString}, {SigName: "builtinAddStringAndStringSig", TypeA: TypeString, TypeB: TypeString, Output: TypeString}, {SigName: "builtinAddDateAndDurationSig", TypeA: TypeDuration, TypeB: TypeDuration, Output: TypeString, FieldTypeA: "Date", FieldTypeB: "Duration"}, {SigName: "builtinAddDateAndStringSig", TypeA: TypeDuration, TypeB: TypeString, Output: TypeString, FieldTypeA: "Date", FieldTypeB: "String"}, {SigName: "builtinAddTimeDateTimeNullSig", TypeA: TypeDatetime, TypeB: TypeDatetime, Output: TypeDatetime, AllNull: true}, {SigName: "builtinAddTimeStringNullSig", TypeA: TypeDatetime, TypeB: TypeDatetime, Output: TypeString, AllNull: true, FieldTypeA: "Date", FieldTypeB: "Datetime"}, {SigName: "builtinAddTimeDurationNullSig", TypeA: TypeDuration, TypeB: TypeDatetime, Output: TypeDuration, AllNull: true}, } type sig struct { SigName string TypeA, TypeB, Output TypeContext FieldTypeA, FieldTypeB string // Optional AllNull bool } type function struct { FuncName string Sigs []sig } var tmplVal = struct { Category string Functions []function }{ Category: "Time", Functions: []function{ {FuncName: "AddTime", Sigs: addTimeSigsTmpl}, }, } func generateDotGo(fileName string) error { w := new(bytes.Buffer) err := addTime.Execute(w, addTimeSigsTmpl) if err != nil { return err } data, err := format.Source(w.Bytes()) if err != nil { log.Println("[Warn]", fileName+": gofmt failed", err) data = w.Bytes() // write original data for debugging } return ioutil.WriteFile(fileName, data, 0644) } func generateTestDotGo(fileName string) error { w := new(bytes.Buffer) err := testFile.Execute(w, tmplVal) if err != nil { return err } data, err := format.Source(w.Bytes()) if err != nil { log.Println("[Warn]", fileName+": gofmt failed", err) data = w.Bytes() // write original data for debugging } return ioutil.WriteFile(fileName, data, 0644) } // generateOneFile generate one xxx.go file and the associated xxx_test.go file. func generateOneFile(fileNamePrefix string) (err error) { err = generateDotGo(fileNamePrefix + ".go") if err != nil { return } err = generateTestDotGo(fileNamePrefix + "_test.go") return } func main() { flag.Parse() var err error outputDir := "." err = generateOneFile(filepath.Join(outputDir, "builtin_time_vec_generated")) if err != nil { log.Fatalln("generateOneFile", err) } }
29.950119
163
0.681101
6b674c2db5e2b6700770a997151d254d3cffbde9
1,802
html
HTML
app/admin/cheatlogs/cheatlog.html
Ardakilic/rartracker
61e4bda93914db36015a4885cd36e7150598fd52
[ "WTFPL" ]
1
2021-08-23T14:57:54.000Z
2021-08-23T14:57:54.000Z
app/admin/cheatlogs/cheatlog.html
Dekryptor/rartracker
f37eef55caf45001aed26d4173db019e72feab06
[ "WTFPL" ]
null
null
null
app/admin/cheatlogs/cheatlog.html
Dekryptor/rartracker
f37eef55caf45001aed26d4173db019e72feab06
[ "WTFPL" ]
1
2021-08-23T14:58:27.000Z
2021-08-23T14:58:27.000Z
<div class="text-center"> <h1>Fusklogg</h1> <div ng-hide="logs" class="fa-spinner fa-spin fa-4x fa-fw spinner"></div> <table class="table table-nowrap" ng-show="logs"> <tr> <th style="width: 100px;">Datum</th> <th style="width: 125px;">Användare</th> <th class="text-left">Torrent</th> <th class="text-right" style="width: 90px;">Fart</th> <th class="text-right" style="width: 80px;">Tid</th> <th class="text-right" style="width: 90px;">Uppladdat</th> <th class="text-right" style="width: 90px;">Nedladdat</th> <th class="text-center">IP</th> <th class="text-center" style="width: 75px;">Port</th> <th class="text-center">Klient</th> </tr> <tr ng-repeat="log in logs"> <td>{{ log.added }}</td> <td><user user="log.user"></user> <button class="btn btn-default btn-xs" ng-click="searchUser(log.user.id)"><i class="fa fa-search"></i></button></td> <td class="text-left"><a ui-sref="torrent({id: log.torrentid})">{{ log.name }}</a></td> <td class="text-right" style="background-color: {{ log | cheatColor }};">{{ log.rate | prettysize }}/s</td> <td class="text-right">{{ log.time }} sek</td> <td class="text-right">{{ log.uploaded | prettysize }}</td> <td class="text-right">{{ log.downloaded | prettysize }}</td> <td><a ui-sref="admin-search({ip: log.ip})">{{ log.ip }}</a>:{{ log.port }} </td> <td ng-bind-html="log.connectable | connectable"></td> <td ng-bind-html="log.agent" ng-style="log.agentdiff == 1 && {'background-color': '#f5ffbb'}"></td> </tr> </table> <uib-pagination max-size="10" items-per-page="itemsPerPage" total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" previous-text="Föregående" next-text="Nästa" boundary-links="true" first-text="Första" last-text="Sista"></uib-pagination> </div>
51.485714
257
0.635405
ab2112db8fbd3ac7a72e11e81ef639eefd387c1e
2,460
cs
C#
EF.Essentials/BaseStartup.cs
HeshamMeneisi/GenericCompany.Common
f8d68c6157557ffc7c43adf7111ed4856e644f4d
[ "MIT" ]
null
null
null
EF.Essentials/BaseStartup.cs
HeshamMeneisi/GenericCompany.Common
f8d68c6157557ffc7c43adf7111ed4856e644f4d
[ "MIT" ]
null
null
null
EF.Essentials/BaseStartup.cs
HeshamMeneisi/GenericCompany.Common
f8d68c6157557ffc7c43adf7111ed4856e644f4d
[ "MIT" ]
1
2021-09-30T04:31:30.000Z
2021-09-30T04:31:30.000Z
using System.Text.Json.Serialization; using App.Metrics; using EF.Essentials.StartupExtensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; namespace EF.Essentials { public class BaseStartup { public BaseStartup(IConfiguration configuration) { Configuration = configuration; this.ConfigureSerilog(configuration); } public IConfiguration Configuration { get; } public IHealthChecksBuilder HealthCheckBuilder { get; private set; } // This method gets called by the runtime. Use this method to add services to the container. public virtual void ConfigureServices(IServiceCollection services) { services.AddCorsPolicies(Configuration); services.AddBaseConfiguration(Configuration); var metricsOptions = Configuration.GetSection(nameof(MetricsOptions)).Get<MetricsOptions>(); if (metricsOptions.Enabled) { services.AddMetrics(); } services.ConfigureIdentityServices(); services.AddMvc().AddJsonOptions(options => { var converter = new JsonStringEnumConverter(); options.JsonSerializerOptions.Converters.Add(converter); }); services.ConfigureSwagger(); services.RegisterBaseWorkers(Configuration); HealthCheckBuilder = services.ConfigureHealthChecks(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime) { app.ConfigureGlobalExceptionHandler(); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseCorsPolicy(env); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.AddSwaggerWithUi(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.ConfigureHealthCheckEndpoint(); }); appLifetime.ApplicationStopped.Register(Log.CloseAndFlush); } } }
36.716418
106
0.65122
0559b003e573d0dbf7b3d145bdb876733f9c8155
5,426
html
HTML
comparison.html
yash5OG/Web-Design-Challenge-UCB-Y5
484598e5e052681ea14f54b848fea139773ec95a
[ "MIT" ]
null
null
null
comparison.html
yash5OG/Web-Design-Challenge-UCB-Y5
484598e5e052681ea14f54b848fea139773ec95a
[ "MIT" ]
null
null
null
comparison.html
yash5OG/Web-Design-Challenge-UCB-Y5
484598e5e052681ea14f54b848fea139773ec95a
[ "MIT" ]
null
null
null
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <title>Comparison Page</title> <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/darkly/bootstrap.min.css" rel="stylesheet" > <link rel="stylesheet" type="text/css" href="bootstrap.css"> </head> <body> <!--Navigation Bar--> <div class="navigation"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="index.html">Latitude Home </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!-- Toggling nav links --> <div class="collapse navbar-collapse" id="navbarColor02"> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Visualizations</a> <div class="dropdown-menu"> <a class="dropdown-item" href="temp.html">Max Temperature</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="humidity.html">Humidity</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="clouds.html">Cloudiness</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="wind.html">Wind Speed</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="comparison.html">Comparison</a> </li> <li class="nav-item"> <a class="nav-link" href="data.html">Data</a> </li> </ul> </div> </nav> </div> <!-- Navigation bar ends --> <!-- Start of the Containers --> <div class="container-fluid"> <section class="row"> <!-- Lat vs X summary box --> <!-- <div class="col-lg-7 col-md-12 col-sm-12"> <div class="jumbotron"> <h1 class="display-5"></h1> <hr class="my-3"> <p class="lead">Click for in-depth Analysis </p> </div> </div> --> <!-- Side navigation for Viz --> <div class="col-lg-12 col-md-12 col-sm-12"> <div class="container-fluid"> <div class="jumbotron"> <h1 class="display-5">Comparison: Latitude vs. X</h1> <hr class="my-3"> <p class="lead">Click for in-depth Analysis</p> <div class="row"> <div class="col-md-6 col-sm-6"> <br><a href="temp.html"><img src="./Viz/temp.png" alt="Latitude vs. Max Temperature" title="Latitude vs. Max Temperature" class="img-thumbnail"></a> </div> <div class="col-md-6 col-sm-6"> <br><a href="humidity.html"><img src="./Viz/hum.png" alt="Latitude vs. Humidity" title="Latitude vs. Humidity" class="img-thumbnail"></a> </div> <div class="col-md-6 col-sm-6"> <br><a href="wind.html"><img src="./Viz/ws.png" alt="Latitude vs. Wind Speed" title="Latitude vs. Wind Speed" class="img-thumbnail"></a> </div> <div class="col-md-6 col-sm-6"> <br><a href="clouds.html"><img src="./Viz/cloud.png" alt="Latitude vs. Cloudiness" title="Latitude vs. Cloudiness" class="img-thumbnail"></a> </div> </div> </div> </div> </div> </section> </div> <!-- Start of footer --> <footer> <div class="footer">&copy;Copyright Yash5, Beyond Time</div> </footer> <!-- End of footer --> <!-- <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> --> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script> --> </body> </html>
39.897059
218
0.615186
577373551d3bec032e0f7214ea18d3b50e216fbf
514
go
Go
annotation/go_source_parser_example_test.go
index0h/go-annotation
7276bad4cdf715b20e62787f9a00450abe2acd12
[ "MIT" ]
null
null
null
annotation/go_source_parser_example_test.go
index0h/go-annotation
7276bad4cdf715b20e62787f9a00450abe2acd12
[ "MIT" ]
8
2019-11-21T23:22:16.000Z
2020-04-19T20:29:09.000Z
annotation/go_source_parser_example_test.go
index0h/go-annotation
7276bad4cdf715b20e62787f9a00450abe2acd12
[ "MIT" ]
null
null
null
package annotation import "fmt" func ExampleGoSourceParser_Parse() { fileName := "file.go" content := `// Hello world package main import "fmt" func main() { fmt.Println("Hello world") }` file := NewGoSourceParser(NewJSONAnnotationParser()).Parse(fileName, content) // Clean content to use File rendering file.Content = "" fmt.Println(NewEntityRenderer().Render(file)) // Output: // // Hello world // package main // // import "fmt" // // func main() { // fmt.Println("Hello world") // } }
16.0625
78
0.66537
05dc4f438682dfc1e4ba91365cd2eb0d1067238a
1,251
html
HTML
neat2/index.html
mare-413/mare-413.github.io
783fab42c3cc6a7e9886f3d669d57d499e230ae5
[ "MIT" ]
null
null
null
neat2/index.html
mare-413/mare-413.github.io
783fab42c3cc6a7e9886f3d669d57d499e230ae5
[ "MIT" ]
null
null
null
neat2/index.html
mare-413/mare-413.github.io
783fab42c3cc6a7e9886f3d669d57d499e230ae5
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>NEAT - Snake AI - 2</title> <script src="libraries/p5.js" type="text/javascript"></script> <script src="libraries/p5.dom.js" type="text/javascript"></script> <script src="libraries/p5.sound.js" type="text/javascript"></script> <script src="top14backtrack.js" type="text/javascript"></script> <script src="top36direct.js" type="text/javascript"></script> <script src="libraries/Matrix.js" type="text/javascript"></script> <script src="libraries/NeuralNet.js" type="text/javascript"></script> <script src="libraries/plotly.js" type="text/javascript"></script> <script src="sketch.js" type="text/javascript"></script> <script src="board.js" type="text/javascript"></script> <script src="gs.js" type="text/javascript"></script> <style> body { padding: 0; margin: 0; } canvas { vertical-align: top; } </style> </head> <body style="padding-left: 50px;"> <p id="p1" style="font-family: arial;"></p> <p id="p2" style="font-family: arial;"></p> <button id="b1">Look</button> <button id="b2">Chart</button> <div id="chart1" style="position: absolute;"> </div> </body> </html>
26.617021
72
0.625899
c31a64a1c8d7ff28397d709149326fa0c3c52064
761
asm
Assembly
oeis/145/A145887.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/145/A145887.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/145/A145887.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A145887: Number of excedances in all even permutations of {1,2,...,n} with no fixed points. ; Submitted by Christian Krause ; 0,0,3,6,60,390,3255,29652,300384,3337380,40382595,528644490,7445077068,112248853626,1803999434055,30788257006920,556112892188640,10598857474652712,212565974908314339,4475073155964510510,98675363089017458940,2274232177861164289230,54684946458570723139383,1369501267832032022965596,35664095516459167264732800,964357142765055882838370700,27039090656758682253429706275,785135076848103958766255169522,23582092843901979618657878490444,731858053776268332992830711765890,23443852989299795600203677133574535 add $0,1 mov $2,130472 mul $2,$0 seq $0,3221 ; Number of even permutations of length n with no fixed points. mul $0,$2 div $0,260944
69.181818
500
0.86071
506de1c7059dcf433047bea5faa5551ed90416c4
316
go
Go
internal/httphandler/config.go
marsom/serverbin
65b6f97bc3f4ecd0e3ee66421e5978e286cdb419
[ "Apache-2.0" ]
null
null
null
internal/httphandler/config.go
marsom/serverbin
65b6f97bc3f4ecd0e3ee66421e5978e286cdb419
[ "Apache-2.0" ]
5
2021-12-06T18:09:07.000Z
2022-02-21T18:08:45.000Z
internal/httphandler/config.go
marsom/serverbin
65b6f97bc3f4ecd0e3ee66421e5978e286cdb419
[ "Apache-2.0" ]
null
null
null
package httphandler import ( "net" "net/url" ) type Server struct { MaxRequestBody int64 BaseUrl *url.URL ManagementBaseUrl *url.URL TrustedAddresses []*net.IPNet } type Config struct { Path string Server Server Cookie *Cookie Delay *Delay Slow *Slow Redirect *Redirect }
13.73913
31
0.670886
f5679bd4dd3056e815936763929f17ebc84327a7
351
cpp
C++
2-YellowBelt/week4/Assignment2/FindGreaterElements.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
2-YellowBelt/week4/Assignment2/FindGreaterElements.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
2-YellowBelt/week4/Assignment2/FindGreaterElements.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
#include <vector> #include <set> using namespace std; template <typename T> vector<T> FindGreaterElements(const set<T>& elements, const T& border) { vector <T> result; for (auto it = elements.begin(); it != elements.end(); it++) { if (*it > border) { result.push_back(*it); } } return result; }
20.647059
70
0.57265
8c5cd0b2e5f06623ff30728a7123539eed7630f9
1,445
sql
SQL
solutions/numUniqueFacilities.sql
dianeyeo/StrataScratch
1a4479844094aedd9be9c1968f60dfcc376bd94f
[ "MIT" ]
null
null
null
solutions/numUniqueFacilities.sql
dianeyeo/StrataScratch
1a4479844094aedd9be9c1968f60dfcc376bd94f
[ "MIT" ]
null
null
null
solutions/numUniqueFacilities.sql
dianeyeo/StrataScratch
1a4479844094aedd9be9c1968f60dfcc376bd94f
[ "MIT" ]
null
null
null
/* Number of Unique Facilities and Insepctions per Municipality https://platform.stratascratch.com/coding/9702-number-of-unique-facilities-and-inspections-per-municipality?python= Difficulty: Easy -- Count the number of unique facilities per municipality zip code along with the number of inspections. -- Output the result along with the number of inspections per each municipality zip code. -- Sort the result based on the number of inspections in descending order. Tables: los_angeles_restaurant_health_inspections serial_number varchar activity_date datetime facility_name varchar score int grade varchar service_code int service_description varchar employee_id varchar facility_address varchar facility_city varchar facility_id varchar facility_state varchar facility_zip varchar owner_id varchar owner_name varchar pe_description varchar program_element_pe int program_name varchar program_status varchar record_id varchar */ SELECT COUNT(DISTINCT facility_id) AS numFacilities, facility_zip, COUNT(service_code) AS inspectionCount FROM los_angeles_restaurant_health_inspections GROUP BY facility_zip ORDER BY COUNT(service_code) DESC;
37.051282
115
0.679585
1e900239e69f0a049ac3b27a066ab545251c44aa
3,253
asm
Assembly
NesDev/bin/Release/sdk/music/famitone2/src/demo/sounds.asm
sunneo/NesDev
66653b15bc8fc1f408240e418f17623f61b06225
[ "MIT" ]
null
null
null
NesDev/bin/Release/sdk/music/famitone2/src/demo/sounds.asm
sunneo/NesDev
66653b15bc8fc1f408240e418f17623f61b06225
[ "MIT" ]
null
null
null
NesDev/bin/Release/sdk/music/famitone2/src/demo/sounds.asm
sunneo/NesDev
66653b15bc8fc1f408240e418f17623f61b06225
[ "MIT" ]
null
null
null
;this file for FamiTone2 libary generated by nsf2data tool sounds: .dw @sfx_ntsc_0,@sfx_pal_0 .dw @sfx_ntsc_1,@sfx_pal_1 .dw @sfx_ntsc_2,@sfx_pal_2 .dw @sfx_ntsc_3,@sfx_pal_3 @sfx_ntsc_0: .db $80,$bf,$81,$56,$82,$03,$83,$bf,$84,$a6,$85,$02,$04,$81,$3a,$82 .db $02,$84,$c4,$85,$01,$04,$81,$ab,$82,$01,$84,$52,$04,$81,$1c,$84 .db $e1,$85,$00,$04,$81,$d5,$82,$00,$84,$a9,$04,$80,$b8,$81,$1c,$82 .db $01,$83,$b8,$84,$e1,$04,$81,$d5,$82,$00,$84,$a9,$04,$80,$30,$83 .db $30,$00 @sfx_ntsc_1: .db $89,$3f,$8a,$0d,$01,$8a,$0b,$01,$8a,$09,$01,$8a,$07,$01,$8a,$05 .db $01,$8a,$03,$01,$89,$3e,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$8a .db $0b,$01,$89,$3d,$8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$8a,$03,$01 .db $89,$3c,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$8a,$0b,$01,$89,$3b .db $8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$8a,$03,$01,$89,$3a,$8a,$01 .db $01,$8a,$0f,$01,$8a,$0d,$01,$8a,$0b,$01,$89,$39,$8a,$09,$01,$8a .db $07,$01,$8a,$05,$01,$8a,$03,$01,$89,$38,$8a,$01,$01,$8a,$0f,$01 .db $8a,$0d,$01,$8a,$0b,$01,$89,$37,$8a,$09,$01,$8a,$07,$01,$8a,$05 .db $01,$8a,$03,$01,$89,$36,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$8a .db $0b,$01,$89,$35,$8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$8a,$03,$01 .db $89,$34,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$8a,$0b,$01,$89,$33 .db $8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$8a,$03,$01,$89,$32,$8a,$01 .db $01,$8a,$0f,$01,$8a,$0d,$01,$8a,$0b,$01,$89,$31,$8a,$09,$01,$8a .db $07,$01,$8a,$05,$01,$8a,$03,$01,$8a,$01,$01,$8a,$0f,$01,$8a,$0d .db $01,$89,$30,$00 @sfx_ntsc_2: .db $80,$bf,$81,$d5,$82,$00,$02,$81,$6a,$02,$80,$b4,$04,$80,$b8,$81 .db $d5,$02,$81,$6a,$02,$80,$b2,$04,$80,$30,$00 @sfx_ntsc_3: .db $86,$81,$87,$6a,$88,$00,$01,$87,$70,$01,$87,$6a,$01,$87,$70,$01 .db $87,$6a,$01,$86,$00,$00 @sfx_pal_0: .db $80,$bf,$81,$19,$82,$03,$83,$bf,$84,$75,$85,$02,$04,$81,$11,$82 .db $02,$84,$a4,$85,$01,$03,$81,$8c,$82,$01,$84,$3a,$03,$81,$08,$84 .db $d1,$85,$00,$04,$81,$c6,$82,$00,$84,$9d,$03,$80,$b8,$81,$08,$82 .db $01,$83,$b8,$84,$d1,$03,$81,$c6,$82,$00,$84,$9d,$04,$80,$30,$83 .db $30,$00 @sfx_pal_1: .db $89,$3f,$8a,$0d,$01,$8a,$0b,$01,$8a,$09,$01,$8a,$07,$01,$8a,$05 .db $01,$89,$3e,$8a,$03,$01,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$89 .db $3d,$8a,$0b,$01,$8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$89,$3c,$8a .db $03,$01,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$89,$3b,$8a,$0b,$01 .db $8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$89,$3a,$8a,$03,$01,$8a,$01 .db $01,$8a,$0f,$01,$8a,$0d,$01,$89,$39,$8a,$0b,$01,$8a,$09,$01,$8a .db $07,$01,$8a,$05,$01,$89,$38,$8a,$03,$01,$8a,$01,$01,$8a,$0f,$01 .db $8a,$0d,$01,$89,$37,$8a,$0b,$01,$8a,$09,$01,$8a,$07,$01,$8a,$05 .db $01,$89,$36,$8a,$03,$01,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$89 .db $35,$8a,$0b,$01,$8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$89,$34,$8a .db $03,$01,$8a,$01,$01,$8a,$0f,$01,$8a,$0d,$01,$89,$33,$8a,$0b,$01 .db $8a,$09,$01,$8a,$07,$01,$8a,$05,$01,$89,$32,$8a,$03,$01,$8a,$01 .db $01,$8a,$0f,$01,$8a,$0d,$01,$89,$31,$8a,$0b,$01,$8a,$09,$01,$8a .db $07,$01,$8a,$05,$01,$8a,$03,$01,$8a,$01,$01,$8a,$0f,$01,$89,$30 .db $00 @sfx_pal_2: .db $80,$bf,$81,$c6,$82,$00,$02,$81,$62,$02,$80,$b4,$03,$80,$b8,$81 .db $c6,$02,$81,$62,$01,$80,$b2,$04,$80,$30,$00 @sfx_pal_3: .db $86,$81,$87,$62,$88,$00,$01,$87,$68,$01,$87,$62,$01,$87,$68,$01 .db $87,$62,$01,$86,$00,$00
50.046154
68
0.515524
43a9ab814673d3868217d98e318cac49dd7af2c7
349
go
Go
cmd/commands/version_test.go
ryuyaF/ecs-plugin
4ea2df6e5e979763b7528c3a3b8149c78d40cb58
[ "Apache-2.0" ]
426
2020-07-09T15:53:14.000Z
2020-11-06T01:38:58.000Z
cmd/commands/version_test.go
ryuyaF/ecs-plugin
4ea2df6e5e979763b7528c3a3b8149c78d40cb58
[ "Apache-2.0" ]
106
2020-07-09T19:35:44.000Z
2020-10-06T07:55:29.000Z
cmd/commands/version_test.go
ryuyaF/ecs-plugin
4ea2df6e5e979763b7528c3a3b8149c78d40cb58
[ "Apache-2.0" ]
44
2020-07-09T16:10:32.000Z
2020-10-19T20:35:36.000Z
package commands import ( "bytes" "strings" "testing" "github.com/docker/ecs-plugin/internal" "gotest.tools/v3/assert" ) func TestVersion(t *testing.T) { root := NewRootCmd(nil) var out bytes.Buffer root.SetOut(&out) root.SetArgs([]string{"version"}) root.Execute() assert.Check(t, strings.Contains(out.String(), internal.Version)) }
16.619048
66
0.710602
3cb8cc18b40669f26bf41be18d709a0da40d7701
2,613
dart
Dart
day_02/lib/main.dart
dipakbari4/-30DaysOfFlutter
9c89635c52e4269c8ed4cc32576e96f1ebce4d61
[ "MIT" ]
3
2021-02-12T19:10:07.000Z
2022-01-15T09:28:43.000Z
day_02/lib/main.dart
thiendangit/30DaysOfFlutter-1
9c89635c52e4269c8ed4cc32576e96f1ebce4d61
[ "MIT" ]
null
null
null
day_02/lib/main.dart
thiendangit/30DaysOfFlutter-1
9c89635c52e4269c8ed4cc32576e96f1ebce4d61
[ "MIT" ]
2
2021-07-14T20:10:42.000Z
2022-01-15T09:28:47.000Z
import 'package:flutter/material.dart'; // There's a lots of way to increment and decrement. // I simply used setState method with usage of Snackbar widget void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Day 2 of #30DaysOfFlutter | IncDec'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; final _scaffoldKey = GlobalKey<ScaffoldState>(); void _incrementCounter() { setState(() { _counter++; }); } void _decrementCounter() { setState(() { if (_counter != 0) { _counter--; } else { _scaffoldKey.currentState.showSnackBar( SnackBar( content: const Text("You're reached to the least value"), duration: const Duration(seconds: 1), action: SnackBarAction( label: "DISMISS", onPressed: () {}, textColor: Colors.amber, ), ), ); } }); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'Increment / Decrement integer value:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: Row( // It is not necessary to use only //FloatingActionButton widget here mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( onPressed: _decrementCounter, tooltip: 'Decrement', child: const Icon(Icons.exposure_minus_1), ), const SizedBox( width: 16, ), FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.plus_one), ), ], ), ); } }
24.885714
69
0.566399