text
stringlengths 27
775k
|
---|
function Export-ReportToCSV {
[CmdletBinding()]
param (
[bool] $Report,
[System.Collections.IDictionary] $ReportOptions,
[string] $Extension,
[string] $ReportName,
[Array] $ReportTable
)
if ($Report) {
$ReportFilePath = Set-ReportFileName -ReportOptions $ReportOptions -ReportExtension $Extension -ReportName $ReportName
if ($ReportTable.Count -gt 0) {
$ReportTable | Export-Csv -Encoding Unicode -Path $ReportFilePath
}
return $ReportFilePath
} else {
return ''
}
} |
(cl:in-package :cleavir-stealth-mixins)
;;; The following hack is due to Gilbert Baumann. It allows us to
;;; dynamically mix in classes into a class without the latter being
;;; aware of it.
;; First of all we need to keep track of added mixins, we use a hash
;; table here. Better would be to stick this information to the victim
;; class itself.
(defvar *stealth-mixins* (make-hash-table))
(defmacro class-stealth-mixins (class)
`(gethash ,class *stealth-mixins*))
;; The 'direct-superclasses' argument to ensure-class is a list of
;; either classes or their names. Since we want to avoid duplicates,
;; we need an appropriate equivalence predicate:
(defun class-equalp (c1 c2)
(when (symbolp c1) (setf c1 (find-class c1)))
(when (symbolp c2) (setf c2 (find-class c2)))
(eq c1 c2))
(defmacro define-stealth-mixin (name super-classes victim-class
&rest for-defclass)
"Like DEFCLASS but adds the newly defined class to the super classes
of 'victim-class'."
`(progn
;; First define the class we talk about
(defclass ,name ,super-classes ,@for-defclass)
;; Add the class to the mixins of the victim
(closer-mop:ensure-class
',victim-class
:direct-superclasses (adjoin ',name
(and (find-class ',victim-class nil)
(closer-mop:class-direct-superclasses
(find-class ',victim-class)))
:test #'class-equalp))
;; Register it as a new mixin for the victim class
(pushnew ',name (class-stealth-mixins ',victim-class))
;; When one wants to [re]define the victim class the new mixin
;; should be present too. We do this by 'patching' ensure-class:
(defmethod closer-mop:ensure-class-using-class :around
(class (name (eql ',victim-class))
&rest arguments
&key (direct-superclasses nil direct-superclasses-p)
&allow-other-keys)
(cond (direct-superclasses-p
;; Silently modify the super classes to include our new
;; mixin.
(dolist (k (class-stealth-mixins name))
(pushnew k direct-superclasses
:test #'class-equalp))
(apply #'call-next-method class name
:direct-superclasses direct-superclasses
arguments))
(t
(call-next-method))))
',name))
|
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
; RUN: llc -O0 -mtriple=amdgcn-amd-amdhsa -mcpu=hawaii -verify-machineinstrs < %s | FileCheck -check-prefix=GCN %s
; The first 64 SGPR spills can go to a VGPR, but there isn't a second
; so some spills must be to memory. The last 16 element spill runs out of lanes at the 15th element.
define amdgpu_kernel void @partial_no_vgprs_last_sgpr_spill(i32 addrspace(1)* %out, i32 %in) #1 {
; GCN-LABEL: partial_no_vgprs_last_sgpr_spill:
; GCN: ; %bb.0:
; GCN-NEXT: s_add_u32 s0, s0, s7
; GCN-NEXT: s_addc_u32 s1, s1, 0
; GCN-NEXT: s_load_dword s4, s[4:5], 0x2
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; def s[8:23]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_writelane_b32 v23, s8, 0
; GCN-NEXT: v_writelane_b32 v23, s9, 1
; GCN-NEXT: v_writelane_b32 v23, s10, 2
; GCN-NEXT: v_writelane_b32 v23, s11, 3
; GCN-NEXT: v_writelane_b32 v23, s12, 4
; GCN-NEXT: v_writelane_b32 v23, s13, 5
; GCN-NEXT: v_writelane_b32 v23, s14, 6
; GCN-NEXT: v_writelane_b32 v23, s15, 7
; GCN-NEXT: v_writelane_b32 v23, s16, 8
; GCN-NEXT: v_writelane_b32 v23, s17, 9
; GCN-NEXT: v_writelane_b32 v23, s18, 10
; GCN-NEXT: v_writelane_b32 v23, s19, 11
; GCN-NEXT: v_writelane_b32 v23, s20, 12
; GCN-NEXT: v_writelane_b32 v23, s21, 13
; GCN-NEXT: v_writelane_b32 v23, s22, 14
; GCN-NEXT: v_writelane_b32 v23, s23, 15
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; def s[8:23]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_writelane_b32 v23, s8, 16
; GCN-NEXT: v_writelane_b32 v23, s9, 17
; GCN-NEXT: v_writelane_b32 v23, s10, 18
; GCN-NEXT: v_writelane_b32 v23, s11, 19
; GCN-NEXT: v_writelane_b32 v23, s12, 20
; GCN-NEXT: v_writelane_b32 v23, s13, 21
; GCN-NEXT: v_writelane_b32 v23, s14, 22
; GCN-NEXT: v_writelane_b32 v23, s15, 23
; GCN-NEXT: v_writelane_b32 v23, s16, 24
; GCN-NEXT: v_writelane_b32 v23, s17, 25
; GCN-NEXT: v_writelane_b32 v23, s18, 26
; GCN-NEXT: v_writelane_b32 v23, s19, 27
; GCN-NEXT: v_writelane_b32 v23, s20, 28
; GCN-NEXT: v_writelane_b32 v23, s21, 29
; GCN-NEXT: v_writelane_b32 v23, s22, 30
; GCN-NEXT: v_writelane_b32 v23, s23, 31
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; def s[8:23]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_writelane_b32 v23, s8, 32
; GCN-NEXT: v_writelane_b32 v23, s9, 33
; GCN-NEXT: v_writelane_b32 v23, s10, 34
; GCN-NEXT: v_writelane_b32 v23, s11, 35
; GCN-NEXT: v_writelane_b32 v23, s12, 36
; GCN-NEXT: v_writelane_b32 v23, s13, 37
; GCN-NEXT: v_writelane_b32 v23, s14, 38
; GCN-NEXT: v_writelane_b32 v23, s15, 39
; GCN-NEXT: v_writelane_b32 v23, s16, 40
; GCN-NEXT: v_writelane_b32 v23, s17, 41
; GCN-NEXT: v_writelane_b32 v23, s18, 42
; GCN-NEXT: v_writelane_b32 v23, s19, 43
; GCN-NEXT: v_writelane_b32 v23, s20, 44
; GCN-NEXT: v_writelane_b32 v23, s21, 45
; GCN-NEXT: v_writelane_b32 v23, s22, 46
; GCN-NEXT: v_writelane_b32 v23, s23, 47
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; def s[8:23]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_writelane_b32 v23, s8, 48
; GCN-NEXT: v_writelane_b32 v23, s9, 49
; GCN-NEXT: v_writelane_b32 v23, s10, 50
; GCN-NEXT: v_writelane_b32 v23, s11, 51
; GCN-NEXT: v_writelane_b32 v23, s12, 52
; GCN-NEXT: v_writelane_b32 v23, s13, 53
; GCN-NEXT: v_writelane_b32 v23, s14, 54
; GCN-NEXT: v_writelane_b32 v23, s15, 55
; GCN-NEXT: v_writelane_b32 v23, s16, 56
; GCN-NEXT: v_writelane_b32 v23, s17, 57
; GCN-NEXT: v_writelane_b32 v23, s18, 58
; GCN-NEXT: v_writelane_b32 v23, s19, 59
; GCN-NEXT: v_writelane_b32 v23, s20, 60
; GCN-NEXT: v_writelane_b32 v23, s21, 61
; GCN-NEXT: v_writelane_b32 v23, s22, 62
; GCN-NEXT: v_writelane_b32 v23, s23, 63
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; def s[6:7]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: s_mov_b64 s[8:9], exec
; GCN-NEXT: s_mov_b64 exec, 3
; GCN-NEXT: buffer_store_dword v0, off, s[0:3], 0
; GCN-NEXT: v_writelane_b32 v0, s6, 0
; GCN-NEXT: v_writelane_b32 v0, s7, 1
; GCN-NEXT: buffer_store_dword v0, off, s[0:3], 0 offset:4 ; 4-byte Folded Spill
; GCN-NEXT: buffer_load_dword v0, off, s[0:3], 0
; GCN-NEXT: s_waitcnt vmcnt(0)
; GCN-NEXT: s_mov_b64 exec, s[8:9]
; GCN-NEXT: s_mov_b32 s5, 0
; GCN-NEXT: s_waitcnt lgkmcnt(0)
; GCN-NEXT: s_cmp_lg_u32 s4, s5
; GCN-NEXT: s_cbranch_scc1 BB0_2
; GCN-NEXT: ; %bb.1: ; %bb0
; GCN-NEXT: v_readlane_b32 s4, v23, 0
; GCN-NEXT: v_readlane_b32 s5, v23, 1
; GCN-NEXT: v_readlane_b32 s6, v23, 2
; GCN-NEXT: v_readlane_b32 s7, v23, 3
; GCN-NEXT: v_readlane_b32 s8, v23, 4
; GCN-NEXT: v_readlane_b32 s9, v23, 5
; GCN-NEXT: v_readlane_b32 s10, v23, 6
; GCN-NEXT: v_readlane_b32 s11, v23, 7
; GCN-NEXT: v_readlane_b32 s12, v23, 8
; GCN-NEXT: v_readlane_b32 s13, v23, 9
; GCN-NEXT: v_readlane_b32 s14, v23, 10
; GCN-NEXT: v_readlane_b32 s15, v23, 11
; GCN-NEXT: v_readlane_b32 s16, v23, 12
; GCN-NEXT: v_readlane_b32 s17, v23, 13
; GCN-NEXT: v_readlane_b32 s18, v23, 14
; GCN-NEXT: v_readlane_b32 s19, v23, 15
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; use s[4:19]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_readlane_b32 s4, v23, 16
; GCN-NEXT: v_readlane_b32 s5, v23, 17
; GCN-NEXT: v_readlane_b32 s6, v23, 18
; GCN-NEXT: v_readlane_b32 s7, v23, 19
; GCN-NEXT: v_readlane_b32 s8, v23, 20
; GCN-NEXT: v_readlane_b32 s9, v23, 21
; GCN-NEXT: v_readlane_b32 s10, v23, 22
; GCN-NEXT: v_readlane_b32 s11, v23, 23
; GCN-NEXT: v_readlane_b32 s12, v23, 24
; GCN-NEXT: v_readlane_b32 s13, v23, 25
; GCN-NEXT: v_readlane_b32 s14, v23, 26
; GCN-NEXT: v_readlane_b32 s15, v23, 27
; GCN-NEXT: v_readlane_b32 s16, v23, 28
; GCN-NEXT: v_readlane_b32 s17, v23, 29
; GCN-NEXT: v_readlane_b32 s18, v23, 30
; GCN-NEXT: v_readlane_b32 s19, v23, 31
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; use s[4:19]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_readlane_b32 s4, v23, 32
; GCN-NEXT: v_readlane_b32 s5, v23, 33
; GCN-NEXT: v_readlane_b32 s6, v23, 34
; GCN-NEXT: v_readlane_b32 s7, v23, 35
; GCN-NEXT: v_readlane_b32 s8, v23, 36
; GCN-NEXT: v_readlane_b32 s9, v23, 37
; GCN-NEXT: v_readlane_b32 s10, v23, 38
; GCN-NEXT: v_readlane_b32 s11, v23, 39
; GCN-NEXT: v_readlane_b32 s12, v23, 40
; GCN-NEXT: v_readlane_b32 s13, v23, 41
; GCN-NEXT: v_readlane_b32 s14, v23, 42
; GCN-NEXT: v_readlane_b32 s15, v23, 43
; GCN-NEXT: v_readlane_b32 s16, v23, 44
; GCN-NEXT: v_readlane_b32 s17, v23, 45
; GCN-NEXT: v_readlane_b32 s18, v23, 46
; GCN-NEXT: v_readlane_b32 s19, v23, 47
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; use s[4:19]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: v_readlane_b32 s8, v23, 48
; GCN-NEXT: v_readlane_b32 s9, v23, 49
; GCN-NEXT: v_readlane_b32 s10, v23, 50
; GCN-NEXT: v_readlane_b32 s11, v23, 51
; GCN-NEXT: v_readlane_b32 s12, v23, 52
; GCN-NEXT: v_readlane_b32 s13, v23, 53
; GCN-NEXT: v_readlane_b32 s14, v23, 54
; GCN-NEXT: v_readlane_b32 s15, v23, 55
; GCN-NEXT: v_readlane_b32 s16, v23, 56
; GCN-NEXT: v_readlane_b32 s17, v23, 57
; GCN-NEXT: v_readlane_b32 s18, v23, 58
; GCN-NEXT: v_readlane_b32 s19, v23, 59
; GCN-NEXT: v_readlane_b32 s20, v23, 60
; GCN-NEXT: v_readlane_b32 s21, v23, 61
; GCN-NEXT: v_readlane_b32 s22, v23, 62
; GCN-NEXT: v_readlane_b32 s23, v23, 63
; GCN-NEXT: s_mov_b64 s[6:7], exec
; GCN-NEXT: s_mov_b64 exec, 3
; GCN-NEXT: buffer_store_dword v0, off, s[0:3], 0
; GCN-NEXT: buffer_load_dword v0, off, s[0:3], 0 offset:4 ; 4-byte Folded Reload
; GCN-NEXT: s_waitcnt vmcnt(0)
; GCN-NEXT: v_readlane_b32 s4, v0, 0
; GCN-NEXT: v_readlane_b32 s5, v0, 1
; GCN-NEXT: buffer_load_dword v0, off, s[0:3], 0
; GCN-NEXT: s_waitcnt vmcnt(0)
; GCN-NEXT: s_mov_b64 exec, s[6:7]
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; use s[8:23]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: ;;#ASMSTART
; GCN-NEXT: ; use s[4:5]
; GCN-NEXT: ;;#ASMEND
; GCN-NEXT: BB0_2: ; %ret
; GCN-NEXT: s_endpgm
call void asm sideeffect "", "~{v[0:7]}" () #0
call void asm sideeffect "", "~{v[8:15]}" () #0
call void asm sideeffect "", "~{v[16:19]}"() #0
call void asm sideeffect "", "~{v[20:21]}"() #0
call void asm sideeffect "", "~{v22}"() #0
%wide.sgpr0 = call <16 x i32> asm sideeffect "; def $0", "=s" () #0
%wide.sgpr1 = call <16 x i32> asm sideeffect "; def $0", "=s" () #0
%wide.sgpr2 = call <16 x i32> asm sideeffect "; def $0", "=s" () #0
%wide.sgpr3 = call <16 x i32> asm sideeffect "; def $0", "=s" () #0
%wide.sgpr4 = call <2 x i32> asm sideeffect "; def $0", "=s" () #0
%cmp = icmp eq i32 %in, 0
br i1 %cmp, label %bb0, label %ret
bb0:
call void asm sideeffect "; use $0", "s"(<16 x i32> %wide.sgpr0) #0
call void asm sideeffect "; use $0", "s"(<16 x i32> %wide.sgpr1) #0
call void asm sideeffect "; use $0", "s"(<16 x i32> %wide.sgpr2) #0
call void asm sideeffect "; use $0", "s"(<16 x i32> %wide.sgpr3) #0
call void asm sideeffect "; use $0", "s"(<2 x i32> %wide.sgpr4) #0
br label %ret
ret:
ret void
}
attributes #0 = { nounwind }
attributes #1 = { nounwind "amdgpu-waves-per-eu"="10,10" }
|
class XmlResultConverter {
static toString(results) {
if (Array.isArray(results)) {
switch (results.length) {
case 0:
return null;
case 1:
return results[0].toString();
default:
return this.__wrapCollection(results.map(this.__wrapSingleNode));
}
}
return results.toString();
}
static __wrapSingleNode(node) {
const wrapInResultTag = el => `<result>${el}</result>`;
return node.nodeValue ? wrapInResultTag(node.nodeValue) : node;
}
static __wrapCollection(nodes) {
return `<resultlist>${nodes.join('')}</resultlist>`;
}
}
export default XmlResultConverter;
|
<?php
/**
* Publish a publication
*/
namespace Dvsa\Olcs\Transfer\Command\Publication;
use Dvsa\Olcs\Transfer\Util\Annotation as Transfer;
use Dvsa\Olcs\Transfer\Command\AbstractCommand;
use Dvsa\Olcs\Transfer\FieldType\Traits as FieldType;
/**
* @Transfer\RouteName("backend/publication/link/single")
* @Transfer\Method("PUT")
*/
final class UpdatePublicationLink extends AbstractCommand
{
use FieldType\Identity;
use FieldType\Version;
/**
* @Transfer\Filter({"name":"Laminas\Filter\StringTrim"})
* @Transfer\Validator({"name":"Laminas\Validator\StringLength", "options":{"max":4000}})
* @Transfer\Optional
*/
public $text1;
/**
* @Transfer\Filter({"name":"Laminas\Filter\StringTrim"})
* @Transfer\Validator({"name":"Laminas\Validator\StringLength", "options":{"max":4000}})
* @Transfer\Optional
*/
public $text2;
/**
* @Transfer\Filter({"name":"Laminas\Filter\StringTrim"})
* @Transfer\Validator({"name":"Laminas\Validator\StringLength", "options":{"max":4000}})
* @Transfer\Optional
*/
public $text3;
/**
* @return string
*/
public function getText1()
{
return $this->text1;
}
/**
* @return string
*/
public function getText2()
{
return $this->text2;
}
/**
* @return string
*/
public function getText3()
{
return $this->text3;
}
}
|
import { Column, Entity } from 'typeorm';
import { CustomBaseEntity } from '../core/custom-base.entity';
@Entity({ name: 'profiles', schema: 'public' })
export class ProfileEntity extends CustomBaseEntity {
@Column({
type: 'varchar',
name: 'cover_image_url',
length: 255,
nullable: true,
})
coverImageUrl: string;
@Column({
type: 'varchar',
name: 'profile_image_url',
length: 255,
nullable: true,
})
profileImageUrl: string;
@Column({ type: 'varchar', name: 'title', length: 100, nullable: true })
title: string;
@Column({ type: 'varchar', name: 'description', length: 255, nullable: true })
description: string;
@Column({ type: 'text', name: 'present_address', nullable: true })
presentAddress: string;
@Column({ type: 'text', name: 'permanent_address', nullable: true })
permanentAddress: string;
@Column({ type: 'text', name: 'company_address', nullable: true })
companyAddress: string;
}
|
---
description: Worked out problems from the book
layout: post
title: "HTLCS:LP3 -- Chapter 11 Exercises"
date: "2020-11-12"
---
Below are exercises from chapter 11 of _[How to Think Like a Computer
Scientist: Learning with Python 3](index.html)_. The text in italics comes from
the textbook, and the code (except where it is obviously part of the textbook's
prompt) is my solutions.
# 11.22.5 -- Add items in two lists
_Lists can be used to represent mathematical vectors. In this exercise and
several that follow you will write functions to perform standard operations on
vectors. Create a script named_ `vectors.py` _and write Python code to pass
the tests in each case._
_Write a function_ `add_vectors(u, v)` _that takes two lists of numbers of the
same length, and returns a new list containing the sums of the corresponding
elements of each:_
{% highlight ruby %}
test(add_vectors([1, 1], [1, 1]) == [2, 2])
test(add_vectors([1, 2], [1, 4]) == [2, 6])
test(add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4])
{% endhighlight %}
We can do this like so:
{% highlight ruby %}
def add_vectors(u, v):
"""Add lists.
Takes two lists of numbers of the same length,
and returns a new list containing the sums of the corresponding
elements of each.
"""
new_list = []
for i in range(len(u)):
new_list.append(u[i] + v[i])
return new_list
{% endhighlight %}
# 11.22.6 -- Multiply items in a list by a number
_Write a function_ `scalar_mult(s, v)` _that takes a number,_ `s`, _and a
list,_ `v`, _and returns the [scalar
multiple](https://en.wikipedia.org/wiki/Scalar_multiplication) of_ `v` _by_
`s`.
{% highlight ruby %}
test(scalar_mult(5, [1, 2]) == [5, 10])
test(scalar_mult(3, [1, 0, -1]) == [3, 0, -3])
test(scalar_mult(7, [3, 0, 5, 11, 2]) == [21, 0, 35, 77, 14])
{% endhighlight %}
Solution:
{% highlight ruby %}
def scalar_mult(s, v):
"""Perform scalar multiplication.
Take a number, s, and a list, v, and return the scalar multiple
of v by s.
"""
new_list = []
for x in v:
new_list.append(s * x)
return new_list
{% endhighlight %}
# 11.22.7 -- Dot product
_Write a function_ `dot_product(u, v)` _that takes two lists of numbers of the
same length, and returns the sum of the products of the corresponding elements
of each (the [dot product](https://en.wikipedia.org/wiki/Dot_product))._
{% highlight ruby %}
test(dot_product([1, 1], [1, 1]) == 2)
test(dot_product([1, 2], [1, 4]) == 9)
test(dot_product([1, 2, 1], [1, 4, 3]) == 12)
{% endhighlight %}
Solution:
{% highlight ruby %}
def dot_product(u, v):
"""Return a dot multiple.
Takes two lists of numbers of the same length, and returns the
sum of the products of the corresponding elements of each (the
dot product).
"""
sum = 0
for i in range(len(u)):
sum += u[i] * v[i]
return sum
{% endhighlight %}
11.22.8 -- Cross Product
_Extra challenge for the mathematically inclined: Write a function_
`cross_product(u, v)` _that takes two lists of numbers of length 3 and returns
their cross product. You should write your own tests._
I may not be the most mathematically inclined person out there, but there's a
pretty simple formula out there for cross-products, and it goes like this:

So all we have to do is just, in a very straightforward way, translate that
formula into Python. Solution:
{% highlight ruby %}
def cross_product(u, v):
"""Take two vectors and return their cross-product.
Takes two lists of numbers, each of length three. Returns cross-product
as a similar list."""
a_x = u[0] # Convert names just to make the formula being
a_y = u[1] # used incredibly clear. Think of the underscore _
a_z = u[2] # as making the next letter subscript.
b_x = v[0]
b_y = v[1]
b_z = v[2]
c_x = a_y * b_z - a_z * b_y # Standard formula for cross-products.
c_y = a_z * b_x - a_x * b_z
c_z = a_x * b_y - a_y * b_x
return [c_x, c_y, c_z]
assert(cross_product([2, 3, 4], [5, 6, 7]) == [-3, 6, -3])
{% endhighlight %}
# 11.22.10
_Write a function_ `replace(s, old, new)` _that replaces all occurrences of_ `old` _with_ `new` _in a string_ `s`:
{% highlight ruby %}
test(replace("Mississippi", "i", "I") == "MIssIssIppI")
s = "I love spom! Spom is my favorite food. Spom, spom, yum!"
test(replace(s, "om", "am") ==
"I love spam! Spam is my favorite food. Spam, spam, yum!")
test(replace(s, "o", "a") ==
"I lave spam! Spam is my favarite faad. Spam, spam, yum!")
{% endhighlight %}
_Hint: use the_ `split` _and_ `join` _methods._
Solution:
{% highlight ruby %}
def replace(s, old, new):
"""Replaces all instances of old with new in a string s."""
splitstring = s.split(old)
outputstring = new.join(splitstring)
return outputstring
{% endhighlight %}
That's a relatively explicit way of writing out the solution. Here's a more abbreviated version.
{% highlight ruby %}
def replace(s, old, new):
"""Replaces all instances of old with new in a string s."""
return new.join(s.split(old))
{% endhighlight %}
---
_This page is released under the [GNU Free Documentation
License](http://openbookproject.net/thinkcs/python/english3e/fdl-1.3.html), any
version 1.3 or later produced by the Free Software Foundation. I am grateful to
the authors of the original textbook for releasing it that way: Peter
Wentworth, Jeffrey Elkner, Allen B. Downey, and Chris Meyers._
|
// Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Factory for domain object which holds the list of top answer
* statistics for a particular state.
*/
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed, fakeAsync, flushMicrotasks } from '@angular/core/testing';
import { AnswerStatsObjectFactory } from
'domain/exploration/AnswerStatsObjectFactory';
import { AnswerStatsBackendDict } from
'domain/exploration/visualization-info-object.factory';
import { StateBackendDict } from 'domain/state/StateObjectFactory';
import { RuleObjectFactory } from 'domain/exploration/RuleObjectFactory';
import { StateTopAnswersStats } from
'domain/statistics/state-top-answers-stats-object.factory';
import { StateTopAnswersStatsService } from
'services/state-top-answers-stats.service';
import { StateTopAnswersStatsBackendApiService } from
'services/state-top-answers-stats-backend-api.service';
import { States, StatesObjectFactory } from
'domain/exploration/StatesObjectFactory';
const joC = jasmine.objectContaining;
describe('StateTopAnswersStatsService', () => {
let answerStatsObjectFactory: AnswerStatsObjectFactory;
let ruleObjectFactory: RuleObjectFactory;
let stateTopAnswersStatsBackendApiService:
StateTopAnswersStatsBackendApiService;
let stateTopAnswersStatsService: StateTopAnswersStatsService;
let statesObjectFactory: StatesObjectFactory;
beforeEach(() => {
TestBed.configureTestingModule({imports: [HttpClientTestingModule]});
answerStatsObjectFactory = TestBed.get(AnswerStatsObjectFactory);
ruleObjectFactory = TestBed.get(RuleObjectFactory);
stateTopAnswersStatsBackendApiService = (
TestBed.get(StateTopAnswersStatsBackendApiService));
stateTopAnswersStatsService = TestBed.get(StateTopAnswersStatsService);
statesObjectFactory = TestBed.get(StatesObjectFactory);
});
const expId = '7';
const stateBackendDict: StateBackendDict = {
content: {content_id: 'content', html: 'Say "hello" in Spanish!'},
next_content_id_index: 0,
param_changes: [],
interaction: {
answer_groups: [{
rule_specs: [{
rule_type: 'Contains',
inputs: {x: 'hola'}
}],
outcome: {
dest: 'Me Llamo',
feedback: {content_id: 'feedback_1', html: '¡Buen trabajo!'},
labelled_as_correct: true,
param_changes: [],
refresher_exploration_id: null,
missing_prerequisite_skill_id: null,
},
training_data: null,
tagged_skill_misconception_id: null,
}],
default_outcome: {
dest: 'Hola',
feedback: {content_id: 'default_outcome', html: 'Try again!'},
labelled_as_correct: false,
param_changes: [],
refresher_exploration_id: null,
missing_prerequisite_skill_id: null,
},
hints: [],
id: 'TextInput',
confirmed_unclassified_answers: [],
customization_args: {
placeholder: {
value: {
content_id: 'ca_placeholder_0',
unicode_str: ''
}
},
rows: { value: 1 }
},
solution: null,
},
classifier_model_id: null,
recorded_voiceovers: {
voiceovers_mapping: {
content: {},
default_outcome: {},
feedback_1: {},
},
},
solicit_answer_details: false,
written_translations: {
translations_mapping: {
content: {},
default_outcome: {},
feedback_1: {},
},
},
};
const makeStates = (statesBackendDict = {Hola: stateBackendDict}): States => {
return statesObjectFactory.createFromBackendDict(statesBackendDict);
};
const spyOnBackendApiFetchStatsAsync = (
stateName: string,
answersStatsBackendDicts: AnswerStatsBackendDict[]): jasmine.Spy => {
const answersStats = answersStatsBackendDicts.map(
a => answerStatsObjectFactory.createFromBackendDict(a));
return spyOn(stateTopAnswersStatsBackendApiService, 'fetchStatsAsync')
.and.returnValue(Promise.resolve(new StateTopAnswersStats(
{[stateName]: answersStats}, {[stateName]: 'TextInput'})));
};
it('should not contain any stats before init', () => {
expect(stateTopAnswersStatsService.hasStateStats('Hola')).toBeFalse();
});
it('should identify unaddressed issues', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', [
{answer: 'hola', frequency: 5},
{answer: 'adios', frequency: 3},
{answer: 'ciao', frequency: 1},
]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
const stateStats = stateTopAnswersStatsService.getStateStats('Hola');
expect(stateStats).toContain(joC({answer: 'hola', isAddressed: true}));
expect(stateStats).toContain(joC({answer: 'adios', isAddressed: false}));
expect(stateStats).toContain(joC({answer: 'ciao', isAddressed: false}));
}));
it('should order results by frequency', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', [
{answer: 'hola', frequency: 7},
{answer: 'adios', frequency: 4},
{answer: 'ciao', frequency: 2},
]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.getStateStats('Hola')).toEqual([
joC({answer: 'hola', frequency: 7}),
joC({answer: 'adios', frequency: 4}),
joC({answer: 'ciao', frequency: 2}),
]);
}));
it('should throw when stats for state do not exist', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', [
{answer: 'hola', frequency: 7},
{answer: 'adios', frequency: 4},
{answer: 'ciao', frequency: 2},
]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(() => stateTopAnswersStatsService.getStateStats('Me Llamo'))
.toThrowError('Me Llamo does not exist.');
}));
it('should have stats for state provided by backend', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync(
'Hola', [{answer: 'hola', frequency: 3}]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.hasStateStats('Hola')).toBeTrue();
}));
it('should have stats for state without any answers', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.hasStateStats('Hola')).toBeTrue();
}));
it('should not have stats for state not provided by backend',
fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.hasStateStats('Me Llamo')).toBeFalse();
}));
it('should only returns state names with stats', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.getStateNamesWithStats())
.toEqual(['Hola']);
}));
it('should return empty stats for a newly added state', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(() => stateTopAnswersStatsService.getStateStats('Me Llamo'))
.toThrowError('Me Llamo does not exist.');
stateTopAnswersStatsService.onStateAdded('Me Llamo');
expect(stateTopAnswersStatsService.getStateStats('Me Llamo'))
.toEqual([]);
}));
it('should throw when accessing a deleted state', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
stateTopAnswersStatsService.onStateDeleted('Hola');
flushMicrotasks();
expect(() => stateTopAnswersStatsService.getStateStats('Hola'))
.toThrowError('Hola does not exist.');
}));
it('should respond to changes in state names', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync('Hola', []);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
const oldStats = stateTopAnswersStatsService.getStateStats('Hola');
stateTopAnswersStatsService.onStateRenamed('Hola', 'Bonjour');
expect(stateTopAnswersStatsService.getStateStats('Bonjour'))
.toEqual(oldStats);
expect(() => stateTopAnswersStatsService.getStateStats('Hola'))
.toThrowError('Hola does not exist.');
}));
it('should recognize newly resolved answers', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync(
'Hola', [{answer: 'adios', frequency: 3}]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.getUnresolvedStateStats('Hola'))
.toContain(joC({answer: 'adios'}));
const updatedState = states.getState('Hola');
updatedState.interaction.answerGroups[0].rules.push(
ruleObjectFactory.createNew('Contains', {x: 'adios'}));
stateTopAnswersStatsService.onStateInteractionSaved(updatedState);
expect(stateTopAnswersStatsService.getUnresolvedStateStats('Hola'))
.not.toContain(joC({answer: 'adios'}));
}));
it('should recognize newly unresolved answers', fakeAsync(async() => {
const states = makeStates();
spyOnBackendApiFetchStatsAsync(
'Hola', [{answer: 'hola', frequency: 3}]);
stateTopAnswersStatsService.initAsync(expId, states);
flushMicrotasks();
await stateTopAnswersStatsService.getInitPromise();
expect(stateTopAnswersStatsService.getUnresolvedStateStats('Hola'))
.not.toContain(joC({answer: 'hola'}));
const updatedState = states.getState('Hola');
updatedState.interaction.answerGroups[0].rules = [
ruleObjectFactory.createNew('Contains', {x: 'bonjour'})
];
stateTopAnswersStatsService.onStateInteractionSaved(updatedState);
expect(stateTopAnswersStatsService.getUnresolvedStateStats('Hola'))
.toContain(joC({answer: 'hola'}));
}));
});
|
An operating system (OS) is system software that manages computer hardware,
software resources, and provides common services for computer programs.
**Course**: Operating Systems, [Spring 2013]<br>
**Taught by**: Prof. Banshidhar Majhi
[Spring 2013]: https://github.com/nitrece/semester-6
|
package com.optum.giraffle.tasks
import okhttp3.Request
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction
import java.io.IOException
open class GsqlTokenTask : GsqlTokenAbstract() {
@TaskAction
fun initToken() {
val x = getHttpUrl().newBuilder()
.addQueryParameter("secret", gsqlPluginExtension.authSecret.get())
.build()
val r = Request.Builder()
.url(x)
.build()
client.newCall(r).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
val responseData = response.body.toString()
logger.info("response: {}", responseData)
val tok = tokenMoshiAdapter.fromJson(response.body!!.source())
with(logger) {
info("token: {}", tok!!.token)
info("status code: {}", response.code)
info("message: {}", tok.message)
info("response: {}", tok.toString())
}
when (tok!!.error) {
false -> gsqlPluginExtension.token.set(tok.token)
true -> throw GradleException(tok.message)
}
}
}
}
|
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Admin;
class RegisterRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'user_name' => 'required|unique:users|max:255|isurlsafe',
'user_email' => 'required|unique:users|max:255',
'password' => 'required|confirmed|min:6',
'invcode' => (Admin::InvitesEnabled()) ? 'required|isvalid:invite_codes,code,code_uses,code_expires' : '',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// Only allow logged in users
// return \Auth::check();
// Allows all users in
return true;
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'user_name.isurlsafe' => 'You cannot use /, #, \\, ? or & characters in your username',
'invcode.exists' => 'The invite code is not valid',
];
}
}
|
from .data import get_train_gen
from .data import get_valid_gen
from .data import get_test_gen
from .data import train_set
from .data import valid_set
from .data import test_set
|
#!/bin/bash
set -o nounset
set -o errexit
brew update >/dev/null
FORMULAES=(
aspell
automake
bash
bat
cloc
cmake
coreutils
ctags
diff-so-fancy
exa
fd
fzf
gawk
git
git-extras
gnu-sed
gnupg
htop
hub
imagemagick
jq
mcrypt
mosh
most
neovim
nmap
node
nvm
pandoc
rename
ripgrep
sbt
scala
shellcheck
telnet
thefuck
tig
tmate
tmux
tree
watch
wget
z
)
brew install "${FORMULAES[@]}"
# Install Terminal and text editor fonts
brew tap caskroom/fonts
brew cask install font-fira-code
brew tap homebrew/cask-fonts
brew cask install font-hack-nerd-font
# Install Node CLI tools
brew pin node
npm install -g npm@latest
npm install -g tldr
tldr --update
# Install iTerm scripts
curl -L https://iterm2.com/misc/install_shell_integration_and_utilities.sh | bash
|
<?php
namespace Test;
use PHPUnit\Framework\TestCase;
use Rudl\LibGitDb\RudlGitDbClient;
class ReadObjectsTest extends TestCase
{
public function testReadObjects()
{
$lib = new RudlGitDbClient();
$lib->setEndpointDev("http://cert_issuer1:testtest@localhost");
$objectsList = $lib->listObjects("ssl_certs");
}
} |
using Abp.Application.Services.Dto;
namespace Bloggs.Authors.Dto
{
public class AuthorUserDto:EntityDto<long>
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
}
}
|
"""
Classes from the 'SetupAssistantSupport' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
SASProximityAnisetteDataProvider = _Class("SASProximityAnisetteDataProvider")
SASProximityInformation = _Class("SASProximityInformation")
SASProximitySessionTransport = _Class("SASProximitySessionTransport")
SASProximitySessionSharingTransport = _Class("SASProximitySessionSharingTransport")
SASProximityHandshake = _Class("SASProximityHandshake")
SASProximitySession = _Class("SASProximitySession")
SASLogging = _Class("SASLogging")
SASSystemInformation = _Class("SASSystemInformation")
SASProximityAction = _Class("SASProximityAction")
SASProximityAnisetteRequestAction = _Class("SASProximityAnisetteRequestAction")
SASProximityBackupAction = _Class("SASProximityBackupAction")
SASProximityFinishedAction = _Class("SASProximityFinishedAction")
SASProximityMigrationStartAction = _Class("SASProximityMigrationStartAction")
SASProximityPasscodeValidationAction = _Class("SASProximityPasscodeValidationAction")
SASProximityReadyAction = _Class("SASProximityReadyAction")
SASProximityHandshakeAction = _Class("SASProximityHandshakeAction")
SASProximityCompanionAuthRequestAction = _Class(
"SASProximityCompanionAuthRequestAction"
)
SASProximityInformationAction = _Class("SASProximityInformationAction")
SASProximityMigrationTransferPreparationAction = _Class(
"SASProximityMigrationTransferPreparationAction"
)
|
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (c) 2018 Oracle and/or its affiliates. All Rights Reserved.
TST_MIN_KVER="4.3"
TST_NEEDS_TMPDIR=1
TST_NEEDS_ROOT=1
TST_NEEDS_DRIVERS="mpls_router mpls_iptunnel mpls_gso"
TST_NEEDS_CMDS="sysctl modprobe"
TST_TEST_DATA="icmp tcp udp"
TST_NETLOAD_BINDTODEVICE=
. tst_net.sh
mpls_cleanup()
{
local flush_dev="ip -f mpls route flush dev"
$flush_dev lo > /dev/null 2>&1
tst_rhost_run -c "$flush_dev lo" > /dev/null
[ -n "$rpf_loc" ] && sysctl -q net.ipv4.conf.all.rp_filter=$rpf_loc
[ -n "$rpf_rmt" ] && tst_rhost_run -s -c "sysctl -q net.ipv4.conf.all.rp_filter=$rpf_rmt"
}
mpls_virt_cleanup()
{
ip route del $ip_virt_remote/32 dev ltp_v0 > /dev/null 2>&1
ip route del $ip6_virt_remote/128 dev ltp_v0 > /dev/null 2>&1
tst_rhost_run -c "ip route del $ip_virt_local/32 dev ltp_v0" > /dev/null
tst_rhost_run -c "ip route del $ip6_virt_local/128 dev ltp_v0" > /dev/null
virt_cleanup
mpls_cleanup
}
mpls_setup()
{
local label="$1"
tst_net_run -s "modprobe -a $TST_NEEDS_DRIVERS"
ROD sysctl -q net.mpls.conf.$(tst_iface).input=1
tst_set_sysctl net.mpls.conf.lo.input 1 safe
tst_set_sysctl net.mpls.platform_labels $label safe
rpf_loc="$(sysctl -n net.ipv4.conf.all.rp_filter)"
tst_rhost_run -s -c "sysctl -q net.mpls.conf.$(tst_iface rhost).input=1"
rpf_rmt="$(tst_rhost_run -c 'sysctl -n net.ipv4.conf.all.rp_filter')"
tst_set_sysctl net.ipv4.conf.all.rp_filter 2 safe
}
mpls_setup_tnl()
{
local ip_loc="$1"
local ip_rmt="$2"
local label="$3"
local mask
echo "$ip_loc" | grep -q ':' && mask=128 || mask=32
ROD ip route add $ip_rmt/$mask encap mpls $label dev ltp_v0
ROD ip -f mpls route add $((label + 1)) dev lo
tst_rhost_run -s -c "ip route add $ip_loc/$mask encap mpls $((label + 1)) dev ltp_v0"
tst_rhost_run -s -c "ip -f mpls route add $label dev lo"
}
mpls_virt_setup()
{
mpls_setup 62
virt_lib_setup
tst_res TINFO "test $virt_type with MPLS"
virt_setup "local $(tst_ipaddr) remote $(tst_ipaddr rhost) dev $(tst_iface)" \
"local $(tst_ipaddr rhost) remote $(tst_ipaddr) dev $(tst_iface rhost)"
mpls_setup_tnl $ip_virt_local $ip_virt_remote 60
mpls_setup_tnl $ip6_virt_local $ip6_virt_remote 50
tst_set_sysctl net.mpls.conf.ltp_v0.input 1 safe
}
mpls_virt_test()
{
local type=$2
local max_size=$TST_NET_MAX_PKT
if [ "$type" = "icmp" ]; then
tst_ping $ip_virt_local $ip_virt_remote 10 100 1000 2000 $max_size
tst_ping $ip6_virt_local $ip6_virt_remote 10 100 1000 2000 $max_size
else
tst_netload -S $ip_virt_local -H $ip_virt_remote -T $type -n 10 -N 10
tst_netload -S $ip6_virt_local -H $ip6_virt_remote -T $type -n 10 -N 10
tst_netload -S $ip_virt_local -H $ip_virt_remote -T $type -A $max_size
tst_netload -S $ip6_virt_local -H $ip6_virt_remote -T $type -A $max_size
fi
}
|
#!/bin/bash
LAUNCH_CONFIG_FILE=${1:-/build/config.yaml}
CLUSTER_INFO_FILE=${2:-/build/cluster_info.json}
set -e
LAUNCH_SUCCESS="False"
RETRY_LAUNCH="True"
while [ x"${LAUNCH_SUCCESS}" == x"False" ]; do
dcos-launch create --config-path=${LAUNCH_CONFIG_FILE} --info-path=${CLUSTER_INFO_FILE}
if [ x"$RETRY_LAUNCH" == x"True" ]; then
set +e
else
set -e
fi
dcos-launch wait --info-path=${CLUSTER_INFO_FILE} 2>&1 | tee dcos-launch-wait-output.stdout
# Grep exits with an exit code of 1 if no lines are matched. We thus need to
# disable exit on errors.
set +e
ROLLBACK_FOUND=$(grep -o "Exception: StackStatus changed unexpectedly to: ROLLBACK_IN_PROGRESS" dcos-launch-wait-output.stdout)
if [ -n "${ROLLBACK_FOUND}" ]; then
if [ x"${RETRY_LAUNCH}" == x"False" ]; then
set -e
echo "Cluster launch failed"
exit 1
fi
# TODO: This would be a good place to add some form of alerting!
# We could add a cluster_failure.sh callback, for example.
# We only retry once!
RETRY_LAUNCH="False"
set -e
# We need to wait for the current stack to be deleted
dcos-launch delete --info-path=${CLUSTER_INFO_FILE}
rm -f ${CLUSTER_INFO_FILE}
echo "Cluster creation failed. Retrying after 30 seconds"
sleep 30
else
LAUNCH_SUCCESS="True"
fi
done
set -e
# Print the cluster info.
echo "Printing ${CLUSTER_INFO_FILE}..."
cat ${CLUSTER_INFO_FILE}
|
<?php
namespace App\Http\Controllers;
use App\Tournament;
use Illuminate\Http\Request;
use App\Http\Requests;
class AdminController extends Controller
{
public function lister(Request $request)
{
$this->authorize('admin', Tournament::class, $request->user());
$nowdate = date('Y.m.d.');
$to_approve = Tournament::where('approved', null)->where('deleted_at', null)->get();
$deleted = Tournament::onlyTrashed()->get();
$message = session()->has('message') ? session('message') : '';
return view('admin', compact('user', 'to_approve', 'deleted', 'nowdate', 'message'));
}
public function approve($id, Request $request)
{
$this->authorize('admin', Tournament::class, $request->user());
return $this->approval($id, 1, 'Tournament approved.');
}
public function reject($id, Request $request)
{
$this->authorize('admin', Tournament::class, $request->user());
return $this->approval($id, 0, 'Tournament rejected.');
}
private function approval($id, $outcome, $message)
{
$tournament = Tournament::findorFail($id);
$tournament->approved = $outcome;
$tournament->save();
return back()->with('message', $message);
}
public function restore($id, Request $request)
{
$this->authorize('admin', Tournament::class, $request->user());
Tournament::withTrashed()->where('id', $id)->restore();
return back()->with('message', 'Tournament restored');
}
}
|
// THIS FILE IS GENERATED AUTOMATICALLY AND SHOULD NOT BE EDITED DIRECTLY.
import 'dart:ffi';
/// ------------------------ GL_GREMEDY_string_marker -----------------------
/// @nodoc
Pointer<NativeFunction<Void Function()>>? glad__glStringMarkerGREMEDY;
/// ```c
/// define glStringMarkerGREMEDY GLEW_GET_FUN(__glewStringMarkerGREMEDY)
/// GLEW_FUN_EXPORT PFNGLSTRINGMARKERGREMEDYPROC __glewStringMarkerGREMEDY
/// typedef void (GLAPIENTRY * PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const void *string)
/// ```
void glStringMarkerGREMEDY(int len, Pointer<Void>? string) {
final _glStringMarkerGREMEDY = glad__glStringMarkerGREMEDY!
.cast<NativeFunction<Void Function(Uint32 len, Pointer<Void>? string)>>()
.asFunction<void Function(int len, Pointer<Void>? string)>();
return _glStringMarkerGREMEDY(len, string);
}
/// @nodoc
void gladLoadGLLoader_gremedy_string_marker(Pointer<NativeFunction<Void Function()>> Function(String) load) {
glad__glStringMarkerGREMEDY = load('glStringMarkerGREMEDY');
}
|
RSpec.feature "Case summary details" do
include_context "with an agent"
before do
click_button "Agent Login"
visit support_case_path(support_case)
click_on "Case details"
end
context "when value and support level have been set to nil" do
let(:support_case) { create(:support_case, :opened, value: nil, support_level: nil) }
it "shows hypens" do
within("div#case-details") do
expect(all("dt.govuk-summary-list__key")[0]).to have_text "Source"
expect(all("dd.govuk-summary-list__value")[0]).to have_text "-"
expect(all("dt.govuk-summary-list__key")[1]).to have_text "Case level"
expect(all("dd.govuk-summary-list__value")[1]).to have_text "Not specified"
expect(all("dt.govuk-summary-list__key")[2]).to have_text "Case value"
expect(all("dd.govuk-summary-list__value")[2]).to have_text "Not specified"
end
end
end
context "when value and support levels have been populated" do
let(:support_case) { create(:support_case, :opened, value: 123.32, support_level: "L2", source: :incoming_email) }
it "shows fields with details" do
within("div#case-details") do
expect(all("dt.govuk-summary-list__key")[0]).to have_text "Source"
expect(all("dd.govuk-summary-list__value")[0]).to have_text "Email"
expect(all("dt.govuk-summary-list__key")[1]).to have_text "Case level"
expect(all("dd.govuk-summary-list__value")[1]).to have_text "2 - Specific advice"
expect(all("dt.govuk-summary-list__key")[2]).to have_text "Case value"
expect(all("dd.govuk-summary-list__value")[2]).to have_text "£123.32"
end
end
end
end
|
package com.imangazaliev.materialprefs.storage
import android.content.SharedPreferences
open class DefaultPreferencesStorage(
private val defaultValues: DefaultValuesContainer,
private val preferences: SharedPreferences
) : PreferencesStorage {
override fun putString(key: String, value: String?) {
preferences.edit {
putString(key, value)
}
}
override fun getString(key: String): String? {
return preferences.getString(key, defaultValues.getString(key))
}
override fun putInt(key: String, value: Int) {
preferences.edit {
putInt(key, value)
}
}
override fun getInt(key: String): Int {
return preferences.getInt(key, defaultValues.getInt(key))
}
override fun putLong(key: String, value: Long) {
preferences.edit {
putLong(key, value)
}
}
override fun getLong(key: String): Long {
return preferences.getLong(key, defaultValues.getLong(key))
}
override fun putFloat(key: String, value: Float) {
return preferences.edit {
putFloat(key, value)
}
}
override fun getFloat(key: String): Float {
return preferences.getFloat(key, defaultValues.getFloat(key))
}
override fun putBoolean(key: String, value: Boolean) {
preferences.edit {
putBoolean(key, value)
}
}
override fun getBoolean(key: String): Boolean {
return preferences.getBoolean(key, defaultValues.getBoolean(key))
}
fun SharedPreferences.edit(body: SharedPreferences.Editor.() -> Unit) {
val editor = this.edit()
editor.body()
editor.apply()
}
} |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module PrettyPrinter where
import Data.List ( intercalate )
import CFG
-- Pretty printer interpretation
instance CFGSYM String where
t str = "\"" ++ str ++ "\""
n str = str
opt str = "[" ++ str ++ "]"
rep str = "{" ++ str ++ "}"
cat = intercalate " , "
alt = intercalate " | "
rules = CFG . showRules where
showRules [] = ""
showRules ((n, s) : rs) = n ++ " = " ++ s ++ ";\n" ++ showRules rs
arithStr :: String
arithStr = unCFG arith
|
using Courier.Data;
using Courier.Data.Models;
using Courier.Helpers;
using Microsoft.EntityFrameworkCore;
namespace Courier.Repositories;
public class TokenRepository : ITokenRepository
{
private readonly CourierDbContext _context;
public TokenRepository(CourierDbContext context)
{
_context = context;
}
public Task<List<UserPersonalToken>> GetUserTokens(string userId)
{
return _context.UserPersonalTokens.AsNoTrackingWithIdentityResolution()
.Where(t => t.UserId == userId)
.ToListAsync();
}
public async Task<UserPersonalToken> CreateRandomUserToken(string userId, string description, DateTime? expiresAt)
{
var token = new UserPersonalToken
{
Id = Guid.NewGuid().ToString(),
Token = TokenHelper.GenerateRandomToken("pt"),
Description = description,
UserId = userId,
ExpiresAt = expiresAt
};
await _context.UserPersonalTokens.AddAsync(token);
await _context.SaveChangesAsync();
return token;
}
public async Task UpdateUserToken(UserPersonalToken token)
{
_context.Update(token);
await _context.SaveChangesAsync();
}
public async Task RemoveUserToken(UserPersonalToken token)
{
_context.Remove(token);
await _context.SaveChangesAsync();
}
public async Task<UserPersonalToken?> FindById(string userId, string id)
{
return await _context.UserPersonalTokens.AsNoTrackingWithIdentityResolution()
.Where(t => t.UserId == userId)
.SingleOrDefaultAsync(t => t.Id == id);
}
public async Task<UserPersonalToken?> FindByToken(string token)
{
return await _context.UserPersonalTokens.AsNoTrackingWithIdentityResolution()
.SingleOrDefaultAsync(t => t.Token == token);
}
} |
require 'salus/bugsnag'
module Sarif::OSV
class BaseSarif < Sarif::BaseSarif
include Salus::SalusBugsnag
OSV_URI = "https://osv.dev/list".freeze
SCANNER_NAME = "OSV Scanner".freeze
def initialize(scan_report, repo_path = nil)
super(scan_report, {}, repo_path)
@uri = OSV_URI
@logs = parse_scan_report!
end
def parse_scan_report!
logs = @scan_report.log('')
return [] if logs.strip.empty?
JSON.parse(@scan_report.to_h.dig(:logs))
rescue JSON::ParserError => e
bugsnag_notify(e.message)
[]
end
def parse_issue(issue)
parsed_issue = {
id: issue['ID'],
name: SCANNER_NAME,
level: issue['Severity'],
details: issue['Summary'].to_s,
messageStrings: { "package": { "text": issue['Package'].to_s },
"title": { "text": issue['Summary'].to_s },
"severity": { "text": issue['Severity'].to_s },
"patched_versions": { "text": issue['Patched Version'].to_s },
"vulnerable_versions": {
"text": issue['Vulnerable Version'].to_s
} },
properties: { 'severity': issue['Severity'] },
uri: OSV_URI.to_s,
help_url: issue["Source"].to_s
}
parsed_issue
end
end
end
|
import plugin from 'babel-plugin-macros'
import pluginTester from 'babel-plugin-tester'
import path from 'path'
pluginTester({
plugin,
pluginName: '@molehill-ui/macro',
babelOptions: {
filename: __filename,
presets: [
'@babel/preset-typescript',
['@babel/preset-react', { runtime: 'automatic' }],
'@babel/preset-env',
],
},
filename: __filename,
fixtures: path.join(__dirname, '__fixtures__'),
snapshot: true,
})
|
<?php
namespace Sharif\CalendarBundle\FormData\Date;
use Sharif\CalendarBundle\Entity\Date\SingleDate;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\FormBuilderInterface;
class NullableSingleDateForm extends AbstractType
implements DataTransformerInterface {
private $hasValueLabel;
private $valueLabel;
function __construct($hasValueLabel='hasValue', $valueLabel='value') {
$this->hasValueLabel = $hasValueLabel;
$this->valueLabel = $valueLabel;
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->
add('hasValue', 'checkbox', array('required' => false,
'label' => $this->hasValueLabel))->
add('dateValue', 'single_date', array('label' => $this->valueLabel))->
addModelTransformer($this);
}
/**
* @inheritdoc
*/
public function getName() {
return 'nullable_single_date';
}
/**
* @inheritdoc
*/
public function reverseTransform($value) {
if($value['hasValue']) {
return $value['dateValue'];
} else {
return null;
}
}
/**
* @inheritdoc
*/
public function transform($value) {
if($value == null) {
return array('dateValue' => new SingleDate(), 'hasValue' => false);
} else {
return array('dateValue' => $value, 'hasValue' => true);
}
}
}
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
ParameterExpression Class to enable creating simple expressions of Parameters.
"""
from typing import Callable, Dict, Set, Union
import numbers
import operator
import numpy
from qiskit.circuit.exceptions import CircuitError
try:
import symengine
HAS_SYMENGINE = True
except ImportError:
HAS_SYMENGINE = False
ParameterValueType = Union["ParameterExpression", float]
class ParameterExpression:
"""ParameterExpression class to enable creating expressions of Parameters."""
__slots__ = ["_parameter_symbols", "_parameters", "_symbol_expr", "_names"]
def __init__(self, symbol_map: Dict, expr):
"""Create a new :class:`ParameterExpression`.
Not intended to be called directly, but to be instantiated via operations
on other :class:`Parameter` or :class:`ParameterExpression` objects.
Args:
symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]):
Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol`
serving as their placeholder in expr.
expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.
"""
self._parameter_symbols = symbol_map
self._parameters = set(self._parameter_symbols)
self._symbol_expr = expr
self._names = None
@property
def parameters(self) -> Set:
"""Returns a set of the unbound Parameters in the expression."""
return self._parameters
def conjugate(self) -> "ParameterExpression":
"""Return the conjugate."""
if HAS_SYMENGINE:
conjugated = ParameterExpression(
self._parameter_symbols, symengine.conjugate(self._symbol_expr)
)
else:
conjugated = ParameterExpression(self._parameter_symbols, self._symbol_expr.conjugate())
return conjugated
def assign(self, parameter, value: ParameterValueType) -> "ParameterExpression":
"""
Assign one parameter to a value, which can either be numeric or another parameter
expression.
Args:
parameter (Parameter): A parameter in this expression whose value will be updated.
value: The new value to bind to.
Returns:
A new expression parameterized by any parameters which were not bound by assignment.
"""
if isinstance(value, ParameterExpression):
return self.subs({parameter: value})
return self.bind({parameter: value})
def bind(self, parameter_values: Dict) -> "ParameterExpression":
"""Binds the provided set of parameters to their corresponding values.
Args:
parameter_values: Mapping of Parameter instances to the numeric value to which
they will be bound.
Raises:
CircuitError:
- If parameter_values contains Parameters outside those in self.
- If a non-numeric value is passed in parameter_values.
ZeroDivisionError:
- If binding the provided values requires division by zero.
Returns:
A new expression parameterized by any parameters which were not bound by
parameter_values.
"""
self._raise_if_passed_unknown_parameters(parameter_values.keys())
self._raise_if_passed_nan(parameter_values)
symbol_values = {}
for parameter, value in parameter_values.items():
param_expr = self._parameter_symbols[parameter]
# TODO: Remove after symengine supports single precision floats
# see symengine/symengine.py#351 for more details
if isinstance(value, numpy.floating):
symbol_values[param_expr] = float(value)
else:
symbol_values[param_expr] = value
bound_symbol_expr = self._symbol_expr.subs(symbol_values)
# Don't use sympy.free_symbols to count remaining parameters here.
# sympy will in some cases reduce the expression and remove even
# unbound symbols.
# e.g. (sympy.Symbol('s') * 0).free_symbols == set()
free_parameters = self.parameters - parameter_values.keys()
free_parameter_symbols = {
p: s for p, s in self._parameter_symbols.items() if p in free_parameters
}
if (
hasattr(bound_symbol_expr, "is_infinite") and bound_symbol_expr.is_infinite
) or bound_symbol_expr == float("inf"):
raise ZeroDivisionError(
"Binding provided for expression "
"results in division by zero "
"(Expression: {}, Bindings: {}).".format(self, parameter_values)
)
return ParameterExpression(free_parameter_symbols, bound_symbol_expr)
def subs(self, parameter_map: Dict) -> "ParameterExpression":
"""Returns a new Expression with replacement Parameters.
Args:
parameter_map: Mapping from Parameters in self to the ParameterExpression
instances with which they should be replaced.
Raises:
CircuitError:
- If parameter_map contains Parameters outside those in self.
- If the replacement Parameters in parameter_map would result in
a name conflict in the generated expression.
Returns:
A new expression with the specified parameters replaced.
"""
inbound_parameters = {
p for replacement_expr in parameter_map.values() for p in replacement_expr.parameters
}
self._raise_if_passed_unknown_parameters(parameter_map.keys())
self._raise_if_parameter_names_conflict(inbound_parameters, parameter_map.keys())
if HAS_SYMENGINE:
new_parameter_symbols = {p: symengine.Symbol(p.name) for p in inbound_parameters}
else:
from sympy import Symbol
new_parameter_symbols = {p: Symbol(p.name) for p in inbound_parameters}
# Include existing parameters in self not set to be replaced.
new_parameter_symbols.update(
{p: s for p, s in self._parameter_symbols.items() if p not in parameter_map}
)
# If new_param is an expr, we'll need to construct a matching sympy expr
# but with our sympy symbols instead of theirs.
symbol_map = {
self._parameter_symbols[old_param]: new_param._symbol_expr
for old_param, new_param in parameter_map.items()
}
substituted_symbol_expr = self._symbol_expr.subs(symbol_map)
return ParameterExpression(new_parameter_symbols, substituted_symbol_expr)
def _raise_if_passed_unknown_parameters(self, parameters):
unknown_parameters = parameters - self.parameters
if unknown_parameters:
raise CircuitError(
"Cannot bind Parameters ({}) not present in "
"expression.".format([str(p) for p in unknown_parameters])
)
def _raise_if_passed_nan(self, parameter_values):
nan_parameter_values = {
p: v for p, v in parameter_values.items() if not isinstance(v, numbers.Number)
}
if nan_parameter_values:
raise CircuitError(
"Expression cannot bind non-numeric values ({})".format(nan_parameter_values)
)
def _raise_if_parameter_names_conflict(self, inbound_parameters, outbound_parameters=None):
if outbound_parameters is None:
outbound_parameters = set()
if self._names is None:
self._names = {p.name: p for p in self._parameters}
inbound_names = {p.name: p for p in inbound_parameters}
outbound_names = {p.name: p for p in outbound_parameters}
shared_names = (self._names.keys() - outbound_names.keys()) & inbound_names.keys()
conflicting_names = {
name for name in shared_names if self._names[name] != inbound_names[name]
}
if conflicting_names:
raise CircuitError(
"Name conflict applying operation for parameters: " "{}".format(conflicting_names)
)
def _apply_operation(
self, operation: Callable, other: ParameterValueType, reflected: bool = False
) -> "ParameterExpression":
"""Base method implementing math operations between Parameters and
either a constant or a second ParameterExpression.
Args:
operation: One of operator.{add,sub,mul,truediv}.
other: The second argument to be used with self in operation.
reflected: Optional - The default ordering is "self operator other".
If reflected is True, this is switched to "other operator self".
For use in e.g. __radd__, ...
Raises:
CircuitError:
- If parameter_map contains Parameters outside those in self.
- If the replacement Parameters in parameter_map would result in
a name conflict in the generated expression.
Returns:
A new expression describing the result of the operation.
"""
self_expr = self._symbol_expr
if isinstance(other, ParameterExpression):
self._raise_if_parameter_names_conflict(other._parameter_symbols.keys())
parameter_symbols = {**self._parameter_symbols, **other._parameter_symbols}
other_expr = other._symbol_expr
elif isinstance(other, numbers.Number) and numpy.isfinite(other):
parameter_symbols = self._parameter_symbols.copy()
other_expr = other
else:
return NotImplemented
if reflected:
expr = operation(other_expr, self_expr)
else:
expr = operation(self_expr, other_expr)
return ParameterExpression(parameter_symbols, expr)
def gradient(self, param) -> Union["ParameterExpression", float]:
"""Get the derivative of a parameter expression w.r.t. a specified parameter expression.
Args:
param (Parameter): Parameter w.r.t. which we want to take the derivative
Returns:
ParameterExpression representing the gradient of param_expr w.r.t. param
"""
# Check if the parameter is contained in the parameter expression
if param not in self._parameter_symbols.keys():
# If it is not contained then return 0
return 0.0
# Compute the gradient of the parameter expression w.r.t. param
key = self._parameter_symbols[param]
if HAS_SYMENGINE:
expr_grad = symengine.Derivative(self._symbol_expr, key)
else:
# TODO enable nth derivative
from sympy import Derivative
expr_grad = Derivative(self._symbol_expr, key).doit()
# generate the new dictionary of symbols
# this needs to be done since in the derivative some symbols might disappear (e.g.
# when deriving linear expression)
parameter_symbols = {}
for parameter, symbol in self._parameter_symbols.items():
if symbol in expr_grad.free_symbols:
parameter_symbols[parameter] = symbol
# If the gradient corresponds to a parameter expression then return the new expression.
if len(parameter_symbols) > 0:
return ParameterExpression(parameter_symbols, expr=expr_grad)
# If no free symbols left, return a float corresponding to the gradient.
return float(expr_grad)
def __add__(self, other):
return self._apply_operation(operator.add, other)
def __radd__(self, other):
return self._apply_operation(operator.add, other, reflected=True)
def __sub__(self, other):
return self._apply_operation(operator.sub, other)
def __rsub__(self, other):
return self._apply_operation(operator.sub, other, reflected=True)
def __mul__(self, other):
return self._apply_operation(operator.mul, other)
def __neg__(self):
return self._apply_operation(operator.mul, -1.0)
def __rmul__(self, other):
return self._apply_operation(operator.mul, other, reflected=True)
def __truediv__(self, other):
if other == 0:
raise ZeroDivisionError("Division of a ParameterExpression by zero.")
return self._apply_operation(operator.truediv, other)
def __rtruediv__(self, other):
return self._apply_operation(operator.truediv, other, reflected=True)
def _call(self, ufunc):
return ParameterExpression(self._parameter_symbols, ufunc(self._symbol_expr))
def sin(self):
"""Sine of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.sin)
else:
from sympy import sin as _sin
return self._call(_sin)
def cos(self):
"""Cosine of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.cos)
else:
from sympy import cos as _cos
return self._call(_cos)
def tan(self):
"""Tangent of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.tan)
else:
from sympy import tan as _tan
return self._call(_tan)
def arcsin(self):
"""Arcsin of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.asin)
else:
from sympy import asin as _asin
return self._call(_asin)
def arccos(self):
"""Arccos of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.acos)
else:
from sympy import acos as _acos
return self._call(_acos)
def arctan(self):
"""Arctan of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.atan)
else:
from sympy import atan as _atan
return self._call(_atan)
def exp(self):
"""Exponential of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.exp)
else:
from sympy import exp as _exp
return self._call(_exp)
def log(self):
"""Logarithm of a ParameterExpression"""
if HAS_SYMENGINE:
return self._call(symengine.log)
else:
from sympy import log as _log
return self._call(_log)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, str(self))
def __str__(self):
from sympy import sympify
return str(sympify(self._symbol_expr))
def __float__(self):
if self.parameters:
raise TypeError(
"ParameterExpression with unbound parameters ({}) "
"cannot be cast to a float.".format(self.parameters)
)
return float(self._symbol_expr)
def __complex__(self):
if self.parameters:
raise TypeError(
"ParameterExpression with unbound parameters ({}) "
"cannot be cast to a complex.".format(self.parameters)
)
return complex(self._symbol_expr)
def __int__(self):
if self.parameters:
raise TypeError(
"ParameterExpression with unbound parameters ({}) "
"cannot be cast to an int.".format(self.parameters)
)
return int(self._symbol_expr)
def __hash__(self):
return hash((frozenset(self._parameter_symbols), self._symbol_expr))
def __copy__(self):
return self
def __deepcopy__(self, memo=None):
return self
def __eq__(self, other):
"""Check if this parameter expression is equal to another parameter expression
or a fixed value (only if this is a bound expression).
Args:
other (ParameterExpression or a number):
Parameter expression or numeric constant used for comparison
Returns:
bool: result of the comparison
"""
if isinstance(other, ParameterExpression):
if self.parameters != other.parameters:
return False
if HAS_SYMENGINE:
from sympy import sympify
return sympify(self._symbol_expr).equals(sympify(other._symbol_expr))
else:
return self._symbol_expr.equals(other._symbol_expr)
elif isinstance(other, numbers.Number):
return len(self.parameters) == 0 and complex(self._symbol_expr) == other
return False
def __getstate__(self):
if HAS_SYMENGINE:
from sympy import sympify
symbols = {k: sympify(v) for k, v in self._parameter_symbols.items()}
expr = sympify(self._symbol_expr)
return {"type": "symengine", "symbols": symbols, "expr": expr, "names": self._names}
else:
return {
"type": "sympy",
"symbols": self._parameter_symbols,
"expr": self._symbol_expr,
"names": self._names,
}
def __setstate__(self, state):
if state["type"] == "symengine":
self._symbol_expr = symengine.sympify(state["expr"])
self._parameter_symbols = {k: symengine.sympify(v) for k, v in state["symbols"].items()}
self._parameters = set(self._parameter_symbols)
else:
self._symbol_expr = state["expr"]
self._parameter_symbols = state["symbols"]
self._parameters = set(self._parameter_symbols)
self._names = state["names"]
def is_real(self):
"""Return whether the expression is real"""
if not self._symbol_expr.is_real and self._symbol_expr.is_real is not None:
# Symengine returns false for is_real on the expression if
# there is a imaginary component (even if that component is 0),
# but the parameter will evaluate as real. Check that if the
# expression's is_real attribute returns false that we have a
# non-zero imaginary
if HAS_SYMENGINE:
if self._symbol_expr.imag != 0.0:
return False
else:
return False
return True
|
package co.ledger.wallet.daemon.mappers
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
import co.ledger.core.implicits.NotEnoughFundsException
import co.ledger.wallet.daemon.controllers.responses.ResponseSerializer
import com.twitter.finagle.http.{Request, Response}
import javax.inject.{Inject, Singleton}
@Singleton
class LibCoreExceptionMapper @Inject()(response: ResponseBuilder)
extends ExceptionMapper[NotEnoughFundsException] {
override def toResponse(request: Request, throwable: NotEnoughFundsException): Response = {
ResponseSerializer.serializeBadRequest(
Map("response" -> "Not enough funds"), response)
}
}
|
use fnv::FnvHashMap;
use fnv::FnvHasher;
use std::hash::Hasher;
const INPUT: &str = include_str!("../input/day07.txt");
type BagMap = FnvHashMap<u64, Vec<(u64, u16)>>;
fn hash_str(s: &str) -> u64 {
let mut hasher = FnvHasher::default();
hasher.write(s.as_bytes());
hasher.finish()
}
fn parse() -> BagMap {
let mut bags = BagMap::default();
for line in INPUT.lines() {
let mut tmp = line.split(" bags contain ");
let parent_color = tmp.next().unwrap();
let parent_color_hash = hash_str(parent_color);
let children_str = tmp.next().unwrap();
if children_str.starts_with('n') {
continue; // 'no other bags.'
}
for child_str in children_str.split(", ") {
let first_non_nb = child_str.find(|c: char| !c.is_numeric()).unwrap();
let color_end = child_str.rfind("bag").unwrap();
let nb = child_str[..first_non_nb].parse::<u16>().unwrap();
let color_hash = hash_str(&child_str[first_non_nb + 1..color_end - 1]);
bags.entry(parent_color_hash)
.or_insert_with(Vec::new)
.push((color_hash, nb));
}
}
bags
}
fn contains_bag(bag: u64, color: u64, bag_map: &BagMap) -> bool {
let v = match bag_map.get(&bag) {
Some(v) => v,
None => return false,
};
for (b, _) in v {
if *b == color || contains_bag(*b, color, bag_map) {
return true;
}
}
false
}
fn part1(bags: &BagMap) -> u32 {
let mut sum = 0;
for &k in bags.keys() {
if contains_bag(k, hash_str("shiny gold"), bags) {
sum += 1;
}
}
sum
}
fn part2(bags: &BagMap, parent_bag: u64) -> usize {
let mut count = 1;
let children = match bags.get(&parent_bag) {
Some(v) => v,
None => return count,
};
for (bag, nb) in children {
count += *nb as usize * part2(bags, *bag);
}
count
}
pub fn day07() -> (String, String) {
let bag_map = parse();
(
format!("{}", part1(&bag_map)),
format!("{}", part2(&bag_map, hash_str("shiny gold")) - 1),
)
}
|
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'baseUser.g.dart';
abstract class BaseUser implements Built<BaseUser,BaseUserBuilder>{
static Serializer<BaseUser> get serializer => _$baseUserSerializer;
@nullable
String get uid;
String get username;
@nullable
String get foodie_level;
@nullable
String get photoUrl;
String get foodie_color;
String get primaryLocation;
int get cityId;
String get entityType;
int get entityId;
String get long;
String get lat;
BaseUser._();
factory BaseUser([void Function(BaseUserBuilder) updates]) =_$BaseUser;
} |
-module(alchemical_reduction).
%% alchemical reduction
-export([process1/1, process2/1]).
%% part 1
process1(Session) ->
{ok, Body} = advent_of_code_client:get(5, Session),
reaction1(binary_to_list(string:trim(Body))).
reaction1([H|T]) -> lists:flatlength(reaction1(T, [H])).
reaction1([], L2) -> L2;
reaction1([H|T], []) -> reaction1(T, [H]);
reaction1([H1|T1], [H2|T2] = L2) ->
case abs(H1 - H2) == 32 of
true -> reaction1(T1, T2);
false -> reaction1(T1, [H1|L2])
end.
%% part 2
process2(Session) ->
{ok, Body} = advent_of_code_client:get(5, Session),
reaction2(binary_to_list(string:trim(Body))).
reaction2(List) -> reaction2(List, $A, lists:flatlength(List)).
reaction2(_, 91, Min) -> Min;
reaction2(List, Char, Min) ->
Filtered = lists:filter(fun(C) -> C =/= Char andalso C =/= Char + 32 end, List),
V = reaction1(Filtered),
case V < Min of
true -> reaction2(List, Char + 1, V);
false -> reaction2(List, Char + 1, Min)
end.
|
; RUN: llc -mtriple=amdgcn--amdhsa -mcpu=fiji -amdgpu-spill-sgpr-to-smem=0 -verify-machineinstrs < %s | FileCheck -check-prefix=TOSGPR -check-prefix=ALL %s
; RUN: llc -mtriple=amdgcn--amdhsa -mcpu=fiji -amdgpu-spill-sgpr-to-smem=1 -verify-machineinstrs < %s | FileCheck -check-prefix=TOSMEM -check-prefix=ALL %s
; If spilling to smem, additional registers are used for the resource
; descriptor.
; ALL-LABEL: {{^}}max_12_sgprs:
; FIXME: Should be ablo to skip this copying of the private segment
; buffer because all the SGPR spills are to VGPRs.
; ALL: s_mov_b64 s[10:11], s[2:3]
; ALL: s_mov_b64 s[8:9], s[0:1]
; ALL: SGPRBlocks: 1
; ALL: NumSGPRsForWavesPerEU: 14
define void @max_12_sgprs(i32 addrspace(1)* %out1,
i32 addrspace(1)* %out2,
i32 addrspace(1)* %out3,
i32 addrspace(1)* %out4,
i32 %one, i32 %two, i32 %three, i32 %four) #0 {
store i32 %one, i32 addrspace(1)* %out1
store i32 %two, i32 addrspace(1)* %out2
store i32 %three, i32 addrspace(1)* %out3
store i32 %four, i32 addrspace(1)* %out4
ret void
}
; private resource: 4
; scratch wave offset: 1
; workgroup ids: 3
; dispatch id: 2
; queue ptr: 2
; flat scratch init: 2
; ---------------------
; total: 14
; + reserved vcc = 16
; Because we can't handle re-using the last few input registers as the
; special vcc etc. registers (as well as decide to not use the unused
; features when the number of registers is frozen), this ends up using
; more than expected.
; ALL-LABEL: {{^}}max_12_sgprs_14_input_sgprs:
; TOSGPR: SGPRBlocks: 1
; TOSGPR: NumSGPRsForWavesPerEU: 16
; TOSMEM: s_mov_b64 s[10:11], s[2:3]
; TOSMEM: s_mov_b64 s[8:9], s[0:1]
; TOSMEM: s_mov_b32 s7, s13
; TOSMEM: SGPRBlocks: 1
; TOSMEM: NumSGPRsForWavesPerEU: 16
define void @max_12_sgprs_14_input_sgprs(i32 addrspace(1)* %out1,
i32 addrspace(1)* %out2,
i32 addrspace(1)* %out3,
i32 addrspace(1)* %out4,
i32 %one, i32 %two, i32 %three, i32 %four) #2 {
store volatile i32 0, i32* undef
%x.0 = call i32 @llvm.amdgcn.workgroup.id.x()
store volatile i32 %x.0, i32 addrspace(1)* undef
%x.1 = call i32 @llvm.amdgcn.workgroup.id.y()
store volatile i32 %x.0, i32 addrspace(1)* undef
%x.2 = call i32 @llvm.amdgcn.workgroup.id.z()
store volatile i32 %x.0, i32 addrspace(1)* undef
%x.3 = call i64 @llvm.amdgcn.dispatch.id()
store volatile i64 %x.3, i64 addrspace(1)* undef
%x.4 = call i8 addrspace(2)* @llvm.amdgcn.dispatch.ptr()
store volatile i8 addrspace(2)* %x.4, i8 addrspace(2)* addrspace(1)* undef
%x.5 = call i8 addrspace(2)* @llvm.amdgcn.queue.ptr()
store volatile i8 addrspace(2)* %x.5, i8 addrspace(2)* addrspace(1)* undef
store i32 %one, i32 addrspace(1)* %out1
store i32 %two, i32 addrspace(1)* %out2
store i32 %three, i32 addrspace(1)* %out3
store i32 %four, i32 addrspace(1)* %out4
ret void
}
; The following test is commented out for now; http://llvm.org/PR31230
; XALL-LABEL: max_12_sgprs_12_input_sgprs{{$}}
; ; Make sure copies for input buffer are not clobbered. This requires
; ; swapping the order the registers are copied from what normally
; ; happens.
; XTOSMEM: s_mov_b32 s5, s11
; XTOSMEM: s_add_u32 m0, s5,
; XTOSMEM: s_buffer_store_dword vcc_lo, s[0:3], m0
; XALL: SGPRBlocks: 2
; XALL: NumSGPRsForWavesPerEU: 18
;define void @max_12_sgprs_12_input_sgprs(i32 addrspace(1)* %out1,
; i32 addrspace(1)* %out2,
; i32 addrspace(1)* %out3,
; i32 addrspace(1)* %out4,
; i32 %one, i32 %two, i32 %three, i32 %four) #2 {
; store volatile i32 0, i32* undef
; %x.0 = call i32 @llvm.amdgcn.workgroup.id.x()
; store volatile i32 %x.0, i32 addrspace(1)* undef
; %x.1 = call i32 @llvm.amdgcn.workgroup.id.y()
; store volatile i32 %x.0, i32 addrspace(1)* undef
; %x.2 = call i32 @llvm.amdgcn.workgroup.id.z()
; store volatile i32 %x.0, i32 addrspace(1)* undef
; %x.3 = call i64 @llvm.amdgcn.dispatch.id()
; store volatile i64 %x.3, i64 addrspace(1)* undef
; %x.4 = call i8 addrspace(2)* @llvm.amdgcn.dispatch.ptr()
; store volatile i8 addrspace(2)* %x.4, i8 addrspace(2)* addrspace(1)* undef
;
; store i32 %one, i32 addrspace(1)* %out1
; store i32 %two, i32 addrspace(1)* %out2
; store i32 %three, i32 addrspace(1)* %out3
; store i32 %four, i32 addrspace(1)* %out4
; ret void
;}
declare i32 @llvm.amdgcn.workgroup.id.x() #1
declare i32 @llvm.amdgcn.workgroup.id.y() #1
declare i32 @llvm.amdgcn.workgroup.id.z() #1
declare i64 @llvm.amdgcn.dispatch.id() #1
declare i8 addrspace(2)* @llvm.amdgcn.dispatch.ptr() #1
declare i8 addrspace(2)* @llvm.amdgcn.queue.ptr() #1
attributes #0 = { nounwind "amdgpu-num-sgpr"="14" }
attributes #1 = { nounwind readnone }
attributes #2 = { nounwind "amdgpu-num-sgpr"="12" }
attributes #3 = { nounwind "amdgpu-num-sgpr"="11" }
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class C_Lahan extends CI_Controller {
function __construct(){
parent::__construct();
if ($this->session->userdata('udhmasuk') !="login") {
redirect(base_url("c_signin/signin"));
}
$this->load->model('m_lahan');
$this->load->helper('url');
}
// public function index(){
// echo "ini method index pada controller belajar | cara membuat controller pada codeigniter | MalasNgoding.com";
// }
public function lahan(){
$data['lahan'] = $this->m_lahan->lahan()->result();
$this->load->view('lahan_manajer',$data);
}
public function tambah_lahan(){
$this->load->view('tambah_lahan');
}
function tambah_data_lahan(){
$lokasi = $this->input->post('lokasi');
$no_surat = $this->input->post('no_surat');
$lahan = $this->input->post('lahan');
$data = array(
'lokasi' => $lokasi,
'no_surat' => $no_surat,
'lahan' => $lahan
);
$this->m_lahan->tambah_data_lahan($data,'lahan');
redirect('c_lahan/lahan');
}
function hapus_data_lahan($id_lahan){
$where = array('id_lahan' => $id_lahan );
$this->m_lahan->hapus_data_lahan($where,'lahan');
redirect('c_lahan/lahan');
}
function edit_data_lahan($id_lahan){
$where = array('id_lahan' => $id_lahan );
$data['lahan'] = $this->m_lahan->edit_data_lahan($where,'lahan')->result();
$this->load->view('edit_lahan',$data);
}
function update_data_lahan(){
$id_lahan = $this->input->post('id_lahan');
$lokasi = $this->input->post('lokasi');
$no_surat = $this->input->post('no_surat');
$lahan = $this->input->post('lahan');
$data = array(
'lokasi' => $lokasi,
'no_surat' => $no_surat,
'lahan' => $lahan
);
$where = array(
'id_lahan' => $id_lahan
);
$this->m_lahan->update_data_lahan($where,$data,'lahan');
redirect('c_lahan/lahan');
}
} |
class Product < ApplicationRecord
belongs_to :department
has_many :taggings
has_many :tags, through: :taggings
validates :name, presence: true, uniqueness: true
validates :price, presence: true, numericality: {greater_than_or_equal_to: 0}
validates :units_in_stock, numericality:{greater_than_or_equal_to: 0, allow_nil: true}
validates :weight, numericality:{greater_than_or_equal_to: 0, allow_nil: true}
validates :height, numericality:{greater_than_or_equal_to: 0, allow_nil: true}
validates :length, numericality:{greater_than_or_equal_to: 0, allow_nil: true}
validates :width, numericality:{greater_than_or_equal_to: 0, allow_nil: true}
has_many :order_items, dependent: :destroy
has_many :options, dependent: :destroy
has_many :price_variants, dependent: :destroy
use_farm_slugs
validate :neg_price_variants_cannot_exceed_price
def total_negative_adjustments
neg = self.price_variants.negative.inject(0){ |sum, pv| sum + pv.adjustment }
neg * (-2 + neg)
end
def neg_price_variants_cannot_exceed_price
if self.total_negative_adjustments > self.price.to_f
self.errors.add(:price_variants,
"total negative price variants cannot exceed price")
end
end
end
|
package com.exratione.sdgexample.config
import com.yammer.dropwizard.config.Configuration
import javax.validation.constraints.NotNull
import org.hibernate.validator.constraints.NotEmpty
/**
* Configuration class for the application.
*
* Populated by values from the YAML configuration file passed to Dropwizard
* when the application is launched.
*/
class SdgExampleConfiguration extends Configuration {
@NotEmpty
var contentEncoding: String = _
@NotEmpty
var contentResource: String = _
@NotNull
var contentTrimLength: Int = _
}
|
; RUN: llc -march=amdgcn -mcpu=verde -mattr=+vgpr-spilling -verify-machineinstrs < %s | FileCheck %s
; RUN: llc -march=amdgcn -mcpu=tonga -mattr=-flat-for-global -mattr=+vgpr-spilling -verify-machineinstrs < %s | FileCheck %s
; This used to fail due to a v_add_i32 instruction with an illegal immediate
; operand that was created during Local Stack Slot Allocation. Test case derived
; from https://bugs.freedesktop.org/show_bug.cgi?id=96602
;
; CHECK-LABEL: {{^}}main:
; CHECK-DAG: v_mov_b32_e32 [[K:v[0-9]+]], 0x200
; CHECK-DAG: v_mov_b32_e32 [[ZERO:v[0-9]+]], 0{{$}}
; CHECK-DAG: v_lshlrev_b32_e32 [[BYTES:v[0-9]+]], 2, v0
; CHECK-DAG: v_and_b32_e32 [[CLAMP_IDX:v[0-9]+]], 0x1fc, [[BYTES]]
; TODO: add 0?
; CHECK-DAG: v_or_b32_e32 [[LO_OFF:v[0-9]+]], [[CLAMP_IDX]], [[ZERO]]
; CHECK-DAG: v_or_b32_e32 [[HI_OFF:v[0-9]+]], [[CLAMP_IDX]], [[K]]
; CHECK: buffer_load_dword {{v[0-9]+}}, [[LO_OFF]], {{s\[[0-9]+:[0-9]+\]}}, {{s[0-9]+}} offen
; CHECK: buffer_load_dword {{v[0-9]+}}, [[HI_OFF]], {{s\[[0-9]+:[0-9]+\]}}, {{s[0-9]+}} offen
define amdgpu_ps float @main(i32 %idx) {
main_body:
%v1 = extractelement <81 x float> <float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float 0x3FE41CFEA0000000, float 0xBFE7A693C0000000, float 0xBFEA477C60000000, float 0xBFEBE5DC60000000, float 0xBFEC71C720000000, float 0xBFEBE5DC60000000, float 0xBFEA477C60000000, float 0xBFE7A693C0000000, float 0xBFE41CFEA0000000, float 0x3FDF9B13E0000000, float 0x3FDF9B1380000000, float 0x3FD5C53B80000000, float 0x3FD5C53B00000000, float 0x3FC6326AC0000000, float 0x3FC63269E0000000, float 0xBEE05CEB00000000, float 0xBEE086A320000000, float 0xBFC63269E0000000, float 0xBFC6326AC0000000, float 0xBFD5C53B80000000, float 0xBFD5C53B80000000, float 0xBFDF9B13E0000000, float 0xBFDF9B1460000000, float 0xBFE41CFE80000000, float 0x3FE7A693C0000000, float 0x3FEA477C20000000, float 0x3FEBE5DC40000000, float 0x3FEC71C6E0000000, float 0x3FEBE5DC40000000, float 0x3FEA477C20000000, float 0x3FE7A693C0000000, float 0xBFE41CFE80000000>, i32 %idx
%v2 = extractelement <81 x float> <float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float undef, float 0xBFE41CFEA0000000, float 0xBFDF9B13E0000000, float 0xBFD5C53B80000000, float 0xBFC6326AC0000000, float 0x3EE0789320000000, float 0x3FC6326AC0000000, float 0x3FD5C53B80000000, float 0x3FDF9B13E0000000, float 0x3FE41CFEA0000000, float 0xBFE7A693C0000000, float 0x3FE7A693C0000000, float 0xBFEA477C20000000, float 0x3FEA477C20000000, float 0xBFEBE5DC40000000, float 0x3FEBE5DC40000000, float 0xBFEC71C720000000, float 0x3FEC71C6E0000000, float 0xBFEBE5DC60000000, float 0x3FEBE5DC40000000, float 0xBFEA477C20000000, float 0x3FEA477C20000000, float 0xBFE7A693C0000000, float 0x3FE7A69380000000, float 0xBFE41CFEA0000000, float 0xBFDF9B13E0000000, float 0xBFD5C53B80000000, float 0xBFC6326AC0000000, float 0x3EE0789320000000, float 0x3FC6326AC0000000, float 0x3FD5C53B80000000, float 0x3FDF9B13E0000000, float 0x3FE41CFE80000000>, i32 %idx
%r = fadd float %v1, %v2
ret float %r
}
|
package messages
const MSG_ID_ATTITUDE = 30
type Attitude struct {
TimeBootMs [4]byte /*uint32 < [ms] Timestamp (time since system boot).*/
Roll [4]byte /*float32 < [rad] Roll angle (-pi..+pi)*/
Pitch [4]byte /*float32 < [rad] Pitch angle (-pi..+pi)*/
Yaw [4]byte /*float32 < [rad] Yaw angle (-pi..+pi)*/
Rollspeed [4]byte /*float32 < [rad/s] Roll angular speed*/
Pitchspeed [4]byte /*float32 < [rad/s] Pitch angular speed*/
Yawspeed [4]byte /*float32 < [rad/s] Yaw angular speed*/
}
|
import 'dart:math' show pi;
import 'package:apod_gallery/models/picture_data.dart';
import 'package:apod_gallery/provider/favorites_notifier.dart';
import 'package:apod_gallery/provider/favorites_provider.dart';
import 'package:apod_gallery/screens/picture_details.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Favorites extends ConsumerWidget {
const Favorites({Key? key}) : super(key: key);
List<Widget> createTiles(
BuildContext context,
{List<PictureData> cards = const [],
required FavoritesNotifier notifier}) {
return [
for (final card in cards)
Dismissible(
key: Key(card.url),
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return PictureDetails(picture: card);
}));
},
child: Card(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
child: ListTile(
iconColor: Colors.pinkAccent,
leading: Container(
alignment: Alignment.centerLeft,
width: 100,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
card.url,
),
fit: BoxFit.cover,
),
)),
title: Text(card.title),
subtitle: Text('Taken on ${card.date}'),
trailing: const Icon(
Icons.favorite_rounded,
),
),
),
],
),
),
),
background: Container(
color: Colors.redAccent.shade400,
child: Padding(
padding: const EdgeInsets.only(left: 64.0),
child: Transform(
transform: Matrix4.rotationY(pi),
child: const Icon(
Icons.delete_sweep,
color: Colors.white,
),
),
),
alignment: AlignmentDirectional.centerStart,
),
secondaryBackground: Container(
color: Colors.redAccent.shade400,
child: const Padding(
padding: EdgeInsets.only(right: 32.0),
child: Icon(
Icons.delete_sweep,
color: Colors.white,
),
),
alignment: AlignmentDirectional.centerEnd,
),
onDismissed: (_) {
notifier.removeFavorite(card.title);
},
),
];
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final _favorites = ref.watch(favoritesProvider);
final _notifier = ref.read(favoritesProvider.notifier);
return Scaffold(
appBar: AppBar(
title: const Text('Favorite Pictures of the Day'),
backgroundColor: Colors.pink,
),
body: _favorites.isNotEmpty
? ListView(
children: createTiles(context,
cards: _favorites, notifier: _notifier),
)
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text("You haven't selected any favorite picture yet",
style: TextStyle(fontSize: 16, color: Colors.black54)),
Text(
'😢',
style: TextStyle(fontSize: 40),
),
],
),
));
}
}
|
#!/bin/bash
# setup virtual network default for five hosts named n1 through n5
virsh net-destroy default
virsh net-undefine default
# configure virtual network bridge
cat > /tmp/default.xml <<EOF
<network>
<name>default</name>
<uuid>5329efc7-b33f-4585-86bf-da9f58952024</uuid>
<forward mode='nat'>
<nat>
<port start='1024' end='65535'/>
</nat>
</forward>
<bridge name='virbr0' stp='on' delay='0'/>
<mac address='52:54:00:ba:ea:f4'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.11' end='192.168.122.100'/>
<host mac='00:1E:62:AA:AA:AA' name='n1' ip='192.168.122.11'/>
<host mac='00:1E:62:AA:AA:AB' name='n2' ip='192.168.122.12'/>
<host mac='00:1E:62:AA:AA:AC' name='n3' ip='192.168.122.13'/>
<host mac='00:1E:62:AA:AA:AD' name='n4' ip='192.168.122.14'/>
<host mac='00:1E:62:AA:AA:AE' name='n5' ip='192.168.122.15'/>
</dhcp>
</ip>
</network>
EOF
virsh net-define /tmp/default.xml
if virsh net-list | grep default > /dev/null 2>&1; then
echo "virtual network default already started"
else
echo "starting virtual network default"
virsh net-start default
fi
|
<?php
namespace common\components;
use yii\base\UserException;
class ColumnNotFoundException extends UserException
{
protected $wrongColumnName;
/**
* @return mixed
*/
public function getWrongColumnName()
{
return $this->wrongColumnName;
}
/**
* @param mixed $wrongColumnName
* @return ColumnNotFoundException
*/
public function setWrongColumnName($wrongColumnName)
{
$this->wrongColumnName = $wrongColumnName;
return $this;
}
}
|
package db
import java.sql.Timestamp
import db.ObjectId.Uninitialized
sealed trait DbInitialized[A] {
def value: A
def unsafeToOption: Option[A]
override def toString: String = unsafeToOption match {
case Some(value) => value.toString
case None => "DbInitialized.Uninitialized"
}
}
sealed trait ObjectId extends DbInitialized[ObjectReference]
object ObjectId {
case object Uninitialized extends ObjectId {
override def value: Nothing = sys.error("Tried to access uninitialized ObjectId")
override def unsafeToOption: Option[Nothing] = None
}
private case class RealObjectId(value: ObjectReference) extends ObjectId {
override def unsafeToOption: Option[ObjectReference] = Some(value)
}
def apply(id: ObjectReference): ObjectId = RealObjectId(id)
def unsafeFromOption(option: Option[ObjectReference]): ObjectId = option match {
case Some(id) => ObjectId(id)
case None => Uninitialized
}
}
sealed trait ObjectTimestamp extends DbInitialized[Timestamp]
object ObjectTimestamp {
case object Uninitialized extends ObjectTimestamp {
override def value: Nothing = sys.error("Tried to access uninitialized ObjectTimestamp")
override def unsafeToOption: Option[Nothing] = None
}
private case class RealObjectTimestamp(value: Timestamp) extends ObjectTimestamp {
override def unsafeToOption: Option[Timestamp] = Some(value)
}
def apply(timestamp: Timestamp): ObjectTimestamp = RealObjectTimestamp(timestamp)
def unsafeFromOption(option: Option[Timestamp]): ObjectTimestamp = option match {
case Some(id) => ObjectTimestamp(id)
case None => Uninitialized
}
} |
package io.jenkins.plugins.servicenow.api.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Result extends JsonResponseObject {
@JsonProperty
private Links links;
@JsonProperty
private String status;
@JsonProperty("status_label")
private String statusLabel;
@JsonProperty("status_message")
private String statusMessage;
@JsonProperty("status_detail")
private String statusDetail;
@JsonProperty
private String error;
@JsonProperty("percent_complete")
private Integer percentComplete;
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusLabel() {
return statusLabel;
}
public void setStatusLabel(String statusLabel) {
this.statusLabel = statusLabel;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getStatusDetail() {
return statusDetail;
}
public void setStatusDetail(String statusDetail) {
this.statusDetail = statusDetail;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public Integer getPercentComplete() {
return percentComplete;
}
public void setPercentComplete(Integer percentComplete) {
this.percentComplete = percentComplete;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("\n\t'links':");
if(links != null) {
final LinkObject progress = links.getProgress();
if(progress != null) {
sb.append("\n\t\t'progress':");
toString(sb, progress);
}
final LinkObject source = links.getSource();
if(source != null) {
sb.append("\n\t\t'source':");
toString(sb, source);
}
}
sb.append("\n\t'status': ").append(status);
sb.append("\n\t'statusLabel': ").append(statusLabel);
sb.append("\n\t'statusMessage': ").append(statusMessage);
sb.append("\n\t'statusDetails': ").append(statusDetail);
sb.append("\n\t'error': ").append(error);
sb.append("\n\t'percentComplete': ").append(percentComplete);
return sb.toString();
}
private void toString(final StringBuffer sb, final LinkObject linkObject) {
sb.append("\n\t\t\t'id': ").append(linkObject.getId());
sb.append("\n\t\t\t'url': ").append(linkObject.getUrl());
}
}
|
# frozen_string_literal: true
name 'sumologic-collector'
maintainer 'Sumo Logic'
maintainer_email '[email protected]'
issues_url 'https://github.com/SumoLogic/sumologic-collector-chef-cookbook/issues' if respond_to?(:issues_url)
source_url 'https://github.com/SumoLogic/sumologic-collector-chef-cookbook' if respond_to?(:source_url)
license 'Apache-2.0'
description 'Installs/Configures sumologic-collector'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.2.22'
chef_version '>= 11' if respond_to?(:chef_version)
%w[
debian
ubuntu
centos
redhat
scientific
fedora
amazon
oracle
windows
suse
].each do |os|
supports os
end
|
require 'support/invite_use_case'
require 'support/notifications_service'
describe "Inviting a team member as a super admin", type: :feature do
let(:organisation) { create(:organisation, name: "Gov Org 3") }
let(:super_admin) { create(:user, :super_admin) }
let(:email) { '[email protected]' }
before do
sign_in_user super_admin
visit super_admin_organisation_path(organisation)
click_on 'Add team member'
fill_in 'Email address', with: email
end
include_context 'when using the notifications service'
include_context 'when sending an invite email'
it "will take the user to the organisation when they click 'back to organisation'" do
click_on 'Back to organisation'
expect(page).to have_current_path(super_admin_organisation_path(organisation))
end
it "will display the name of the organisation you want to add a team member to" do
expect(page).to have_content("Invite a team member to #{organisation.name}")
end
it "creates the user when invited" do
expect { click_on 'Send invitation email' }.to change(User, :count).by(1)
end
it "adds the invited user to the correct organisation" do
click_on 'Send invitation email'
user = User.find_by(email: '[email protected]')
expect(user.organisations).to eq([organisation])
end
it "will redirect the user to the organisation page on success" do
click_on 'Send invitation email'
expect(page).to have_current_path(super_admin_organisation_path(organisation))
end
context "without can manage team privileges" do
before do
super_admin.default_membership.update(can_manage_team: false)
end
it "does not show the add team member button" do
expect(page).not_to have_content("Add team member")
end
end
context "without an email address" do
let(:email) { "" }
before do
click_on 'Send invitation email'
end
it "does not send an invite" do
expect(InviteUseCaseSpy.invite_count).to eq(0)
end
it "displays the correct error message" do
expect(page).to have_content("Email can't be blank")
end
context "when retrying with a valid email address" do
let(:email_second_attempt) { "[email protected]" }
before do
fill_in 'Email address', with: email_second_attempt
click_on 'Send invitation email'
end
it "sends an invite" do
expect(InviteUseCaseSpy.invite_count).to eq(1)
end
it "adds the invited user to the correct organisation" do
user = User.find_by(email: '[email protected]')
expect(user.organisations).to eq([organisation])
end
it "will redirect the user to the organisation page on success" do
expect(page).to have_current_path(super_admin_organisation_path(organisation))
end
end
end
end
|
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
class Test():
def setup_method(self, method):
self.driver = webdriver.Firefox()
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_(self):
self.driver.get("https://www.stoloto.ru/")
self.driver.set_window_size(1616, 876)
self.driver.find_element(By.CSS_SELECTOR, ".links > .pseudo").click()
self.driver.find_element(By.ID, "auth_login").click()
self.driver.find_element(By.ID, "auth_login").send_keys("89154482623")
self.driver.find_element(By.ID, "auth_password").click()
self.driver.find_element(By.ID, "auth_password").send_keys("Test2018")
self.driver.find_element(By.CSS_SELECTOR, ".submit_button_container > .pretty_button").click()
self.driver.find_element(By.CSS_SELECTOR, ".bg_7x49 .game_card_about ins").click()
self.driver.execute_script("window.scrollTo(0,306)")
self.driver.find_element(By.CSS_SELECTOR, ".quickies:nth-child(8) .fastfill-rnd").click()
self.driver.find_element(By.NAME, "7x49_cart").click()
element = self.driver.find_element(By.ID, "layout")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
element = self.driver.find_element(By.CSS_SELECTOR, "body")
actions = ActionChains(driver)
actions.move_to_element(element, 0, 0).perform()
self.driver.find_element(By.CSS_SELECTOR, ".medium a").click()
|
package ar.ferman.ddb4k
import ar.ferman.ddb4k.example.data.ExampleData
import ar.ferman.ddb4k.example.data.ExampleTable
import org.assertj.core.api.BDDAssertions.assertThat
import org.junit.jupiter.api.Test
internal class TableDefinitionTest {
@Test
internal fun `create item from value`() {
val tableDef = ExampleTable.createTableDefinition()
val userRanking = ExampleData("ferman", 100).apply {
attString = "example"
attBoolean = true
attInt = 25
attLong = 50L
attFloat = 51.4f
attDouble = 5.999998
attStringList = listOf("d", "a", "b", "c")
}
val item = tableDef.toItem(userRanking)
println(item)
val userRankingFromItem = tableDef.fromItem(item)
println(userRankingFromItem)
assertThat(userRankingFromItem).isEqualTo(ExampleData("ferman", 100).apply {
attString = "example"
attBoolean = true
attInt = 25
attLong = 50L
attFloat = 51.4f
attDouble = 5.999998
attStringList = listOf("d", "a", "b", "c")
})
}
} |
#!/bin/bash
sudo usermod -g nginx -G ec2-user,wheel
# TODO set default file permissions such that nginx can execute
# also on /home and /home/ec2-user!
# TODO add IP to ALLOWED_HOSTS in settings.py
sudo yum install -y gcc libjpeg-devel zlib-devel nginx git
sudo yum install postgresql94 postgresql94-server postgresql94-libs postgresql94-contrib postgresql94-devel
git clone https://github.com/mnieber/shared-goals.git
chmod -R g+w shared-goals/
cd shared-goals
sed s#{{shared_goals}}#`pwd`#g conf/supervisord.conf.template > conf/supervisord.conf
sed s#{{shared_goals}}#`pwd`#g conf/sharedgoals_nginx.conf.template > conf/sharedgoals_nginx.conf
mkdir log
mkdir static
mkdir media
sudo ln -s `pwd`/conf/sharedgoals_nginx.conf /etc/nginx/conf.d/
virtualenv env
source env/bin/activate
pip install --upgrade pip
pip install -r conf/REQUIREMENTS.txt
# TODO set superuser
cd src
python manage.py collectstatic --noinput
# TODO run migrate
exit
|
CREATE TABLE invoices (
id serial primary key,
name varchar(255),
date timestamp
);
INSERT INTO invoices (name, date) VALUES
('a thing', to_timestamp('1/1/2012', 'MM/DD/YYYY') AT TIME ZONE 'UTC'),
('another thing', to_timestamp('10/19/2013', 'MM/DD/YYYY') AT TIME ZONE 'UTC'),
('great', to_timestamp('11/20/2016', 'MM/DD/YYYY') AT TIME ZONE 'UTC');
CREATE TABLE line_items (
id serial primary key,
subtotal real,
discount real,
invoice_id integer default null references "invoices" ("id") on delete cascade
);
WITH invoice AS (
SELECT id FROM invoices WHERE name = 'a thing'
)
INSERT INTO line_items (subtotal, discount, invoice_id) VALUES
(10, 0, (SELECT id FROM invoice)),
(20, 1, (SELECT id FROM invoice)),
(30, 2, (SELECT id FROM invoice)),
(40, 3, (SELECT id FROM invoice)),
(50, 4, (SELECT id FROM invoice)),
(60, 5, (SELECT id FROM invoice)),
(70, 6, (SELECT id FROM invoice)),
(80, 7, (SELECT id FROM invoice)),
(90, 8, (SELECT id FROM invoice)),
(100, 9, (SELECT id FROM invoice));
WITH invoice AS (
SELECT id FROM invoices WHERE name = 'another thing'
)
INSERT INTO line_items (subtotal, discount, invoice_id) VALUES
(10, 0, (SELECT id FROM invoice)),
(20, 1, (SELECT id FROM invoice)),
(30, 2, (SELECT id FROM invoice)),
(40, 3, (SELECT id FROM invoice)),
(50, 4, (SELECT id FROM invoice)),
(60, 5, (SELECT id FROM invoice)),
(70, 6, (SELECT id FROM invoice)),
(80, 7, (SELECT id FROM invoice)),
(90, 8, (SELECT id FROM invoice)),
(100, 9, (SELECT id FROM invoice));
WITH invoice AS (
SELECT id FROM invoices WHERE name = 'great'
)
INSERT INTO line_items (subtotal, discount, invoice_id) VALUES
(10, 0, (SELECT id FROM invoice)),
(20, 1, (SELECT id FROM invoice)),
(30, 2, (SELECT id FROM invoice)),
(40, 3, (SELECT id FROM invoice)),
(50, 4, (SELECT id FROM invoice)),
(60, 5, (SELECT id FROM invoice)),
(70, 6, (SELECT id FROM invoice)),
(80, 7, (SELECT id FROM invoice)),
(90, 8, (SELECT id FROM invoice)),
(100, 9, (SELECT id FROM invoice));
CREATE TABLE nodes (
id serial primary key,
name varchar(255),
val real
);
INSERT INTO nodes (name, val) VALUES
('HELLO', 3),
('Gary busey', -10),
('John Bonham', 10000),
('Mona Lisa', 100),
(NULL, 10);
CREATE TABLE refs (
id serial primary key,
node_id integer not null references "nodes" ("id") on delete cascade,
val real
);
INSERT INTO refs (node_id, val) VALUES
((SELECT id FROM nodes WHERE name = 'HELLO'), 10),
((SELECT id FROM nodes WHERE name = 'Gary busey'), 0),
((SELECT id FROM nodes WHERE name = 'John Bonham'), 0);
CREATE TABLE farouts (
id serial primary key,
ref_id integer default null references "refs" ("id") on delete cascade,
second_ref_id integer default null references "refs" ("id") on delete cascade
);
CREATE TABLE items (
id serial primary key,
name text,
created timestamp,
updated timestamp,
deleted timestamp
);
CREATE TABLE item_details (
id serial primary key,
comment text,
item_id integer default null references "items" ("id") on delete cascade,
deleted_at timestamp
);
CREATE TABLE item_prices (
id serial primary key,
price integer,
item_detail_id integer default null references "item_details" ("id") on delete cascade
);
CREATE TABLE column_tests (
id serial primary key,
b64_json_column text
);
CREATE TABLE ref_column_tests (
id serial primary key,
column_id integer default null references "column_tests" ("id") on delete cascade
);
CREATE TABLE encrypted_column_tests (
id serial primary key,
secret_data text
);
|
namespace Models.NorthwindIB.NH
{
using System;
using System.Collections.Generic;
public partial class InternationalOrder
{
public virtual int OrderID { get; set; }
public virtual string CustomsDescription { get; set; }
public virtual decimal ExciseTax { get; set; }
public virtual int RowVersion { get; set; }
public virtual Order Order { get; set; }
}
}
|
import { google } from 'googleapis';
import Config from './Config';
import Request from './Request';
class GoogleAPI extends Request {
/**
* Get JWT Authorization access token
*
* @returns {Promise<*>}
*/
static async getAuthToken({ credentials = null }) {
const key = await Config.getAll({ credentialsFile: credentials });
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/indexing'],
null,
);
const tokens = await jwtClient.authorize();
if (!tokens.access_token) {
throw new Error('Get Access Token, check your service account json file');
}
return tokens;
}
static async request({
url,
method = 'GET',
body = null,
headersOpt = {},
credentials = null,
}) {
const token = await GoogleAPI.getAuthToken({ credentials });
const headers = {
Authorization: `Bearer ${token.access_token}`,
...headersOpt,
};
const response = await Request.requestInterface({ url, method, body, headersOpt: headers });
if (response === false) {
return response;
}
return response.json();
}
}
export default GoogleAPI;
|
@model string
@{
ViewData["Title"] = "Result";
}
<h2>Result:</h2>
<h3>@Model</h3>
|
using System;
namespace AsyncInn.Models
{
public class ExtensionMethods
{
// Implement a case insensitive string comparison
public static bool CaseInsensitiveContains(string dbString, string searchTerm, StringComparison comparer)
{
return dbString != null && searchTerm != null ? dbString.IndexOf(searchTerm, comparer) >= 0 : false;
}
}
} |
<?php
declare(strict_types=1);
namespace Ziswapp\Funding\Application\Filters;
use Illuminate\Support\Carbon;
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
final class StartDateRangeFilter implements Filter
{
/**
* @psalm-suppress MissingParamType
*/
public function __invoke(Builder $query, $value, string $property): Builder
{
$date = Carbon::parse($value)->startOfDay()->toDateTimeString();
return $query->whereDate($property, '>=', $date);
}
}
|
// Originally generated by the template in CodeDAO
package kotlinadventofcode.`2015`
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import com.github.h0tk3y.betterParse.parser.*
import kotlinadventofcode.Day
import kotlin.math.max
import kotlin.math.min
class `2015-09` : Day {
data class City(val name: String, val distances: Map<City, Int>) {
override fun equals(other: Any?): Boolean = other is City && name == other.name
override fun hashCode(): Int = name.hashCode()
}
fun parse(input: String): Set<City> {
val distancesByCityName: MutableMap<String, MutableMap<City, Int>> = mutableMapOf()
val cities: MutableSet<City> = mutableSetOf()
val grammar = object: Grammar<List<Unit>>() {
val newLine by literalToken("\n")
val to by literalToken(" to ")
val equals by literalToken(" = ")
val digits by regexToken("\\d+")
val name by regexToken("[a-zA-Z]+")
val city by name use {
val city = City(text, distancesByCityName.getOrPut(text) { mutableMapOf() })
cities += city
city
}
val distance by digits use { text.toInt() }
val line by city and -to and city and -equals and distance map { (leftCity, rightCity, distance) ->
fun saveCityMappings(city1: City, city2: City) {
distancesByCityName.getOrPut(city1.name) { mutableMapOf() } += city2 to distance
}
saveCityMappings(leftCity, rightCity)
saveCityMappings(rightCity, leftCity)
}
override val rootParser by separatedTerms(line, newLine)
}
grammar.parseToEnd(input)
return cities
}
override fun runPart1(input: String): String {
return run(input, ::min)
}
fun run(input: String, bestChooser: (Int, Int) -> Int): String {
val cities = parse(input)
val paths: ArrayDeque<List<City>> = ArrayDeque(cities.map { listOf(it) })
var best: Int? = null
while (!paths.isEmpty()) {
val path = paths.removeLast()
if (path.size == cities.size) {
var distance = 0
for (i in 0..path.size - 2) {
distance += path[i].distances[path[i + 1]] ?: throw Exception("City distance missing.")
}
best = best?.let { bestChooser(it, distance) } ?: distance
} else {
path.last().distances
.filterKeys { it !in path }
.forEach { (city, _) -> paths.addLast(path + city) }
}
}
return best.toString()
}
/**
* After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
*/
override fun runPart2(input: String): String {
return run(input, ::max)
}
override val defaultInput = """Tristram to AlphaCentauri = 34
Tristram to Snowdin = 100
Tristram to Tambi = 63
Tristram to Faerun = 108
Tristram to Norrath = 111
Tristram to Straylight = 89
Tristram to Arbre = 132
AlphaCentauri to Snowdin = 4
AlphaCentauri to Tambi = 79
AlphaCentauri to Faerun = 44
AlphaCentauri to Norrath = 147
AlphaCentauri to Straylight = 133
AlphaCentauri to Arbre = 74
Snowdin to Tambi = 105
Snowdin to Faerun = 95
Snowdin to Norrath = 48
Snowdin to Straylight = 88
Snowdin to Arbre = 7
Tambi to Faerun = 68
Tambi to Norrath = 134
Tambi to Straylight = 107
Tambi to Arbre = 40
Faerun to Norrath = 11
Faerun to Straylight = 66
Faerun to Arbre = 144
Norrath to Straylight = 115
Norrath to Arbre = 135
Straylight to Arbre = 127"""
} |
package main
import . "leetcode-go/common/listnode"
var zeroNode = &ListNode{Val: 0}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var (
dummy = &ListNode{Val: 0}
prev = dummy
p1 = l1
p2 = l2
carrier = 0
)
for p1 != p2 {
prev.Next = &ListNode{Val: (p1.Val + p2.Val + carrier) % 10}
prev = prev.Next
if (p1.Val + p2.Val + carrier) >= 10 {
carrier = 1
} else {
carrier = 0
}
if p1 = p1.Next; p1 == nil {
p1 = zeroNode
}
if p2 = p2.Next; p2 == nil {
p2 = zeroNode
}
}
if carrier > 0 {
prev.Next = &ListNode{Val: 1}
}
return dummy.Next
}
|
require 'simplecov'
SimpleCov.start
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "silicium"
require "minitest/autorun"
class Minitest::Test
def assert_equal_as_sets(expected, actual)
assert_equal expected.size, actual.size
expected.each do |elem|
assert_includes actual, elem
end
end
def assert_equal_arrays(expected, actual)
expected.zip(actual).each {|x, y| assert_equal x, y }
end
def assert_equal_arrays_in_delta(expected, actual, delta)
expected.zip(actual).each {|x, y| assert_in_delta x, y, delta}
end
end |
#!/bin/bash
wget http://cvsp.cs.ntua.gr/research/stavis/data/annotations/DIEM.tar.gz
wget http://cvsp.cs.ntua.gr/research/stavis/data/annotations/Coutrot_db1.tar.gz
wget http://cvsp.cs.ntua.gr/research/stavis/data/annotations/Coutrot_db2.tar.gz
tar -xf DIEM.tar.gz
rm DIEM.tar.gz
mv DIEM diem
tar -xf Coutrot_db1.tar.gz
rm Coutrot_db1.tar.gz
mv Coutrot_db1 coutrot1
cd coutrot1
for d in ./*/; do mv -v "$d" "${d/clip/clip_}"; done;
cd ../
tar -xf Coutrot_db2.tar.gz
rm Coutrot_db2.tar.gz
mv Coutrot_db2 coutrot2
cd coutrot2
for d in ./*/; do mv -v "$d" "${d/clip/clip_}"; done;
cd ../
|
---
layout: issue
title: "Implementation"
id: ZF-3665
---
ZF-3665: Implementation
-----------------------
Issue Type: Sub-task Created: 2008-07-17T09:49:52.000+0000 Last Updated: 2008-07-17T09:53:30.000+0000 Status: Resolved Fix version(s):
Reporter: Alexander Veremyev (alexander) Assignee: Alexander Veremyev (alexander) Tags: - Zend\_Search\_Lucene
Related issues:
Attachments:
### Description
### Comments
Posted by Alexander Veremyev (alexander) on 2008-07-17T09:53:25.000+0000
Done
|
package com.lunatech.iamin
import japgolly.scalajs.react.component.Scala
import japgolly.scalajs.react.component.ScalaFn.Component
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.{CtorType, _}
import org.scalajs.dom.html.{Div, LI}
import scala.concurrent.Future
object IaminApp {
case class AppState(items: List[String], user: String)
val component: Scala.Component[Unit, AppState, AppBackend, CtorType.Nullary] = ScalaComponent
.builder[Unit]("Iamin")
.initialState(AppState(Nil, ""))
.renderBackend[AppBackend]
.build
class AppBackend($: BackendScope[Unit, AppState]) {
def onChange(e: ReactEventFromInput): Callback = {
val newValue = e.target.value
$.modState(_.copy(user = newValue))
}
def postUser(name: String): Future[User] = IaminAPI.postUser(name)
def handleSubmit(event: ReactEventFromInput): Callback = {
event.preventDefaultCB >> {
$.modState(state => {
postUser(state.user)
AppState(state.items :+ state.user, "")
})
}
}
def createItem(itemText: String): VdomTagOf[LI] = <.li(itemText)
def render(state: AppState): VdomTagOf[Div] =
<.div(
<.form(^.onSubmit ==> handleSubmit,
<.input(^.onChange ==> onChange, ^.value := state.user),
<.button("Create")
),
UserList(state.items)
)
}
val UserList: Component[List[String], CtorType.Props] = ScalaFnComponent[List[String]] { props =>
def createItem(itemText: String) = <.li(itemText)
<.ul(props.sorted map createItem: _*)
}
}
|
/// _Material_Pixel_Evaluate.sh
/// Don't include!
/// Return final alpha with optionally applied fade out.
#ifdef URHO3D_SOFT_PARTICLES
half GetSoftParticleFade(const half fragmentDepth, const half backgroundDepth)
{
half depthDelta = backgroundDepth - fragmentDepth - cFadeOffsetScale.x;
return clamp(depthDelta * cFadeOffsetScale.y, 0.0, 1.0);
}
#define GetFinalAlpha(surfaceData) \
surfaceData.albedo.a * GetSoftParticleFade(vWorldDepth, surfaceData.backgroundDepth)
#else
#define GetFinalAlpha(surfaceData) surfaceData.albedo.a
#endif
#ifdef URHO3D_IS_LIT
#ifdef URHO3D_AMBIENT_PASS
/// Calculate ambient lighting.
half3 CalculateAmbientLighting(const SurfaceData surfaceData)
{
#ifdef URHO3D_PHYSICAL_MATERIAL
half NoV = abs(dot(surfaceData.normal, surfaceData.eyeVec)) + 1e-5;
#ifdef URHO3D_BLUR_REFLECTION
half3 linearReflectionColor = GammaToLinearSpace(surfaceData.reflectionColor.rgb);
#else
half3 linearReflectionColor = mix(GammaToLinearSpace(surfaceData.reflectionColor.rgb),
cReflectionAverageColor, surfaceData.roughness * surfaceData.roughness);
#endif
half3 diffuseAndSpecularColor = Indirect_PBR(
surfaceData.ambientLighting, linearReflectionColor,
surfaceData.albedo.rgb, surfaceData.specular,
surfaceData.roughness, NoV);
#elif defined(URHO3D_REFLECTION_MAPPING)
half3 diffuseAndSpecularColor = Indirect_SimpleReflection(
surfaceData.ambientLighting, surfaceData.reflectionColor.rgb, surfaceData.albedo.rgb, cMatEnvMapColor.rgb);
#else
half3 diffuseAndSpecularColor = Indirect_Simple(
surfaceData.ambientLighting, surfaceData.albedo.rgb, cMatEnvMapColor.rgb);
#endif
return diffuseAndSpecularColor * surfaceData.occlusion + surfaceData.emission;
}
#endif
/*
#ifdef URHO3D_LIGHT_PASS
/// Return pixel lighting data for forward rendering.
DirectLightData GetForwardDirectLightData(vec3 lightVec, vec3 shapePos, float worldDepth)
{
DirectLightData result;
result.lightVec = NormalizeLightVector(lightVec);
#ifdef URHO3D_LIGHT_CUSTOM_SHAPE
result.lightColor = GetLightColorFromShape(shapePos);
#else
result.lightColor = GetLightColor(result.lightVec.xyz);
#endif
#ifdef URHO3D_HAS_SHADOW
vec4 shadowUV = ShadowCoordToUV(vShadowPos, worldDepth);
result.shadow = FadeShadow(SampleShadowFiltered(shadowUV), worldDepth);
#endif
return result;
}
/// Calculate lighting from per-pixel light source.
half3 CalculateDirectLighting(const SurfaceData surfaceData, vec3 lightVec, vec3 shapePos, float worldDepth)
{
DirectLightData lightData = GetForwardDirectLightData(lightVec, shapePos, worldDepth);
#if defined(URHO3D_PHYSICAL_MATERIAL) || URHO3D_SPECULAR > 0
half3 halfVec = normalize(surfaceData.eyeVec + lightData.lightVec.xyz);
#endif
#if defined(URHO3D_SURFACE_VOLUMETRIC)
half3 lightColor = Direct_Volumetric(lightData.lightColor, surfaceData.albedo.rgb);
#elif defined(URHO3D_PHYSICAL_MATERIAL)
half3 lightColor = Direct_PBR(lightData.lightColor, surfaceData.albedo.rgb,
surfaceData.specular, surfaceData.roughness,
lightData.lightVec.xyz, surfaceData.normal, surfaceData.eyeVec, halfVec);
#elif URHO3D_SPECULAR > 0
half3 lightColor = Direct_SimpleSpecular(lightData.lightColor,
surfaceData.albedo.rgb, surfaceData.specular,
lightData.lightVec.xyz, surfaceData.normal, halfVec, cMatSpecColor.a, cLightColor.a);
#else
half3 lightColor = Direct_Simple(lightData.lightColor,
surfaceData.albedo.rgb, lightData.lightVec.xyz, surfaceData.normal);
#endif
return lightColor * GetDirectLightAttenuation(lightData);
}
#endif
/// Return color with applied lighting, but without fog.
/// Fills all channels of geometry buffer except destination color.
half3 GetFinalColor(const SurfaceData surfaceData, vec3 lightVec, vec3 shapePos, float worldDepth)
{
#ifdef URHO3D_AMBIENT_PASS
half3 finalColor = CalculateAmbientLighting(surfaceData);
#else
half3 finalColor = vec3(0.0);
#endif
#ifdef URHO3D_GBUFFER_PASS
#ifdef URHO3D_PHYSICAL_MATERIAL
half roughness = surfaceData.roughness;
#else
half roughness = 1.0 - cMatSpecColor.a / 255.0;
#endif
gl_FragData[1] = vec4(surfaceData.fogFactor * surfaceData.albedo.rgb, 0.0);
gl_FragData[2] = vec4(surfaceData.fogFactor * surfaceData.specular, roughness);
gl_FragData[3] = vec4(surfaceData.normal * 0.5 + 0.5, 0.0);
#elif defined(URHO3D_LIGHT_PASS)
finalColor += CalculateDirectLighting(surfaceData, lightVec, shapePos, worldDepth);
#endif
return finalColor;
}
#else // URHO3D_IS_LIT
/// Return color with optionally applied reflection, but without fog.
half3 GetFinalColor(const SurfaceData surfaceData)
{
half3 finalColor = surfaceData.albedo.rgb;
#ifdef URHO3D_REFLECTION_MAPPING
finalColor += GammaToLightSpace(cMatEnvMapColor.rgb * surfaceData.reflectionColor.rgb);
#endif
#ifdef URHO3D_GBUFFER_PASS
gl_FragData[1] = vec4(0.0, 0.0, 0.0, 0.0);
gl_FragData[2] = vec4(0.0, 0.0, 0.0, 0.0);
gl_FragData[3] = vec4(0.5, 0.5, 0.5, 0.0);
#endif
return finalColor;
}
*/
#endif // URHO3D_IS_LIT
|
module Feed
( getFeedContent
, Content(..)
, parseFeed
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Text.Feed.Import (parseFeedSource)
import Text.Feed.Query
import Text.Feed.Types
type LByteString = LB.ByteString
type ByteString = B.ByteString
data Content = Content { hash :: ByteString
, content :: Text
} deriving Show
getFeedContent :: Feed -> [Content]
getFeedContent = mapMaybe getContent . getFeedItems
where
getContent :: Item -> Maybe Content
getContent item = Content <$> getId item <*> (T.strip <$> getItemTitle item)
getId = fmap (T.encodeUtf8 . snd) . getItemId
parseFeed :: LByteString -> Maybe Feed
parseFeed = parseFeedSource
|
% P31 (**) Determine whether a given integer number is prime.
% is_prime(P) :- P is a prime number
% (integer) (+)
is_prime(2).
is_prime(3).
is_prime(P) :- integer(P), P > 3, P mod 2 =\= 0, \+ has_factor(P,3).
% has_factor(N,L) :- N has an odd factor F >= L.
% (integer, integer) (+,+)
has_factor(N,L) :- N mod L =:= 0.
has_factor(N,L) :- L * L < N, L2 is L + 2, has_factor(N,L2).
% added by bson
prime_(2).
prime_(N):-
prime_(M),
N is M+1.
prime(N):-
prime_(N),
is_prime(N).
%broken:
%strange(N):-!,goldbach(N). %broken
%strange(N):-N<100,prime(N).
%strange(N):-N>1000,prime(N). |
package models
import play.api.libs.json.{Json, OFormat}
case class Cart(id: Int, products: String, userId: String)
object Cart {
implicit val commentsFormat: OFormat[Cart] = Json.format[Cart]
}
|
package main
import (
"encoding/hex"
"fmt"
"io/ioutil"
"strconv"
"strings"
"testing"
)
type CpuState struct {
A int
X int
Y int
P int
S int
C int
Op uint16
Cyc int
Sl int
}
func TestGoldLog(test *testing.T) {
ProgramCounter = 0xC000
Ram.Init()
cpu.Reset()
ppu.Init()
cpu.P = 0x24
cpu.Accurate = false
if contents, err := ioutil.ReadFile("test_roms/nestest.nes"); err == nil {
if rom, err = LoadRom(contents); err != nil {
test.Error(err.Error())
return
}
}
logfile, err := ioutil.ReadFile("test_roms/nestest.log")
if err != nil {
test.Error(err.Error())
return
}
log := strings.Split(string(logfile), "\n")
sentinel := 250
//sentinel := 5003
for i := 0; i < sentinel; i++ {
op, _ := hex.DecodeString(log[i][:4])
high := op[0]
low := op[1]
r := log[i][48:]
registers := strings.Fields(r)
a, _ := hex.DecodeString(strings.Split(registers[0], ":")[1])
x, _ := hex.DecodeString(strings.Split(registers[1], ":")[1])
y, _ := hex.DecodeString(strings.Split(registers[2], ":")[1])
p, _ := hex.DecodeString(strings.Split(registers[3], ":")[1])
sp, _ := hex.DecodeString(strings.Split(registers[4], ":")[1])
sl, _ := strconv.Atoi(strings.Split(registers[len(registers)-1], ":")[1])
var cyc int
if len(registers[len(registers)-2]) > 2 {
cyc, _ = strconv.Atoi(strings.Split(registers[len(registers)-2], ":")[1])
} else {
cyc, _ = strconv.Atoi(registers[len(registers)-2])
}
fmt.Printf("PC 0x%X -> Cyc: %s\n", ProgramCounter, registers[len(registers)-2])
// CYC is PPU cycle (wraps at 341)
// SL is PPU scanline (wraps at 260)
expectedState := CpuState{
A: int(a[0]),
X: int(x[0]),
Y: int(y[0]),
P: int(p[0]),
S: int(sp[0]),
Op: (uint16(high) << 8) + uint16(low),
Cyc: cyc,
Sl: sl,
}
verifyCpuState(ProgramCounter, &cpu, &ppu, expectedState, test)
cycles := cpu.Step()
// 3 PPU cycles for each CPU cycle
for i := 0; i < 3*cycles; i++ {
ppu.Step()
}
}
}
func verifyCpuState(pc uint16, c *Cpu, p *Ppu, e CpuState, test *testing.T) {
if pc != e.Op {
test.Errorf("PC was 0x%X, expected 0x%X\n", pc, e.Op)
}
if c.A != Word(e.A) {
test.Errorf("PC: 0x%X Register A was 0x%X, was expecting 0x%X\n", pc, c.A, e.A)
}
if c.X != Word(e.X) {
test.Errorf("PC: 0x%X Register X was 0x%X, was expecting 0x%X\n", pc, c.X, e.X)
}
if c.Y != Word(e.Y) {
test.Errorf("PC: 0x%X Register Y was 0x%X, was expecting 0x%X\n", pc, c.Y, e.Y)
}
if c.P != Word(e.P) {
test.Errorf("PC: 0x%X P register was 0x%X, was expecting 0x%X\n", pc, c.P, e.P)
}
if c.StackPointer != Word(e.S) {
test.Errorf("PC: 0x%X Stack pointer was 0x%X, was expecting 0x%X\n", pc, c.StackPointer, e.S)
}
if p.Cycle != e.Cyc {
test.Errorf("PC: 0x%X PPU cycle was %d, was expecting %d\n", pc, p.Cycle, e.Cyc)
}
if p.Scanline != e.Sl {
test.Errorf("PC: 0x%X PPU scanline was %d, was expecting %d\n", pc, p.Scanline, e.Sl)
}
}
|
/*
* Copyright 2017 helloscala.com
*
* 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 helloscala.starter.nosql
import javax.inject.{Inject, Provider, Singleton}
import com.google.inject.AbstractModule
import helloscala.common.{AppLifecycle, Configuration, HSCommons}
import helloscala.nosql.cassandra.CassandraSession
import helloscala.nosql.elasticsearch.ESClient
import helloscala.common.util.InternalConfig
@Singleton
class CassandraSessionProvider @Inject()(val config: Configuration, appLifecycle: AppLifecycle)
extends Provider[CassandraSession] {
private[this] val session = new DefaultCassandraSession(config, appLifecycle)
override def get(): CassandraSession = session
}
@Singleton
class ElasticsearchClientProvider @Inject()(configuration: Configuration, appLifecycle: AppLifecycle)
extends Provider[ESClient] {
private[this] val client = new DefaultESClient(configuration, appLifecycle)
override def get() = client
}
class HSNoSQLModule extends AbstractModule {
private[this] def config = InternalConfig.config
override def configure(): Unit = {
if (config.hasPath(HSCommons.CASSANDRA_PATH) && isEnable(HSCommons.CASSANDRA_PATH + ".enable")) {
bind(classOf[CassandraSession])
.toProvider(classOf[CassandraSessionProvider])
}
if (config.hasPath(HSCommons.ELASTICSEARCH_PATH) && isEnable(HSCommons.ELASTICSEARCH_PATH + ".enable")) {
bind(classOf[ESClient]).toProvider(classOf[ElasticsearchClientProvider])
}
}
private def isEnable(path: String): Boolean = {
if (config.hasPath(path)) config.getBoolean(path) else true
}
}
|
import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_luckin_coffee/components/a_button/index.dart';
import 'package:flutter_luckin_coffee/utils/global.dart';
class OrderListRow extends StatelessWidget {
final int orderStatus;
final String address;
final String goodsName;
final String orderNum;
final String time;
final double price;
final Function onPress;
/// 创建订单列表信息
/// ```
/// @param {int} orderStatus - 订单状态 1: 待付款 2: 已完成 3: 已取消
/// @param {String} address - 地址
/// @param {String} goodsName - 商品名字
/// @param {String} orderNum - 订单号
/// @param {String} time - 订单时间
/// @param {double} price - 价格
/// ```
OrderListRow(this.orderStatus,
{this.address,
this.goodsName,
this.orderNum,
this.time,
this.price,
this.onPress});
/// 文字状态
Widget textStatus() {
var text = '';
var color = rgba(166, 166, 166, 1);
if (orderStatus == 1) {
color = rgba(136, 175, 213, 1);
text = "待付款";
} else if (orderStatus == 2)
text = "已完成";
else if (orderStatus == 3) text = "已取消";
return Text(text, style: TextStyle(fontSize: 12, color: color));
}
/// 按钮状态
List<Widget> buttonStatus(BuildContext context) {
List<Widget> button = [];
var btn1 = Container(
margin: EdgeInsets.only(left: 10),
child: AButton.normal(
child: Text(
'再来一单',
style: TextStyle(fontSize: 12),
),
color: rgba(56, 56, 56, 1),
plain: true,
height: 28,
width: 74,
borderColor: rgba(242, 242, 242, 1),
onPressed: () => {}),
);
var btn2 = Container(
margin: EdgeInsets.only(left: 10),
child: AButton.normal(
child: Text(
'去支付',
style: TextStyle(fontSize: 12),
),
color: rgba(255, 129, 2, 1),
borderColor: rgba(255, 129, 2, 1),
plain: true,
height: 28,
width: 74,
onPressed: () => G.pushNamed('/order_confirm')),
);
var btn3 = Container(
margin: EdgeInsets.only(left: 10),
child: AButton.normal(
child: Text(
'去评价',
style: TextStyle(fontSize: 12),
),
color: rgba(144, 192, 239, 1),
plain: true,
height: 28,
width: 74,
borderColor: rgba(144, 192, 239, 1),
onPressed: () => G.pushNamed('/order_evaluation')),
);
if (orderStatus == 1) {
button.add(btn2);
} else if (orderStatus == 2) {
button.add(btn1);
button.add(btn3);
} else if (orderStatus == 3) {
button.add(btn1);
}
return button;
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => onPress == null ? () {} : onPress(),
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
height: 160,
color: hex('#fff'),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(border: G.borderBottom()),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'外卖订单:$orderNum',
style:
TextStyle(color: rgba(166, 166, 166, 1), fontSize: 12),
),
textStatus()
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'$address...',
style: TextStyle(
color: rgba(56, 56, 56, 1),
fontSize: 15,
fontWeight: FontWeight.bold),
),
Text(
'$time',
style:
TextStyle(fontSize: 12, color: rgba(166, 166, 166, 1)),
)
],
),
),
Row(
children: <Widget>[
Text(
'$goodsName等 共1件商品',
style: TextStyle(
color: rgba(80, 80, 80, 1),
fontSize: 12,
),
),
],
),
Container(
margin: EdgeInsets.only(top: 25),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'¥$price',
style: TextStyle(
color: rgba(56, 56, 56, 1),
fontSize: 14,
fontWeight: FontWeight.bold),
),
Row(children: buttonStatus(context))
],
),
),
],
),
),
);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Stencil.SDK.Models
{
public partial class Order : SDKModel
{
public Order()
{
}
public virtual Guid order_id { get; set; }
public virtual Guid account_id { get; set; }
public virtual Guid? invoice_id { get; set; }
public virtual Guid? payment_id { get; set; }
public virtual Guid? shipment_id { get; set; }
public virtual bool order_paid { get; set; }
public virtual bool order_shipped { get; set; }
public virtual OrderStatus order_status { get; set; }
//<IndexOnly>
public decimal order_total { get; set; }
public DateTime created_utc { get; set; }
public string account_name { get; set; }
public string account_email { get; set; }
public string shipment_address { get; set; }
public string payment_cardtype { get; set; }
public string status { get; set; }
public int lineitem_count { get; set; }
public Product[] products { get; set; }
//</IndexOnly>
}
}
|
#!/bin/bash
# This script is for performing basic directory/file descriptive analysis.
# Upon successful completion there will be a log file summary in each directory (<dir>.log).
cd "$(dirname "$0")" || exit
cd ../data || exit
DIRS=(TCGA-BRCA TCGA-COAD TCGA-GBM TCGA-KIRC TCGA-KIRP TCGA-LUAD TCGA-LUSC TCGA-OV TCGA-READ TCGA-UCEC)
for d in "${DIRS[@]}"; do
cd "$d" || exit; pwd
toWrite=''; fc=0
for f in $(find . -name \*.txt); do # This loop style is generally bad practice, but it is fine here.
((fc += 1))
size="$(wc -lm "$f")"
_file="$(echo "$size" | tr -s ' ' | cut -d ' ' -f 4)"
_line="$(echo "$size" | tr -s ' ' | cut -d ' ' -f 2)"
_byte="$(echo "$size" | tr -s ' ' | cut -d ' ' -f 3)" # Same as character count since this is ASCII.
head="$(head "$f")"; tail="$(tail "$f")"
printf -v printed "FILE: %s\nLINES: %s BYTES/CHARS: %s\n----------HEAD----------\n%s\n----------TAIL\
----------\n%s\n----------------------------------------------------------------------------------------\
------------\n" "$_file" "$_line" "$_byte" "$head" "$tail"
toWrite+=$printed
done
printf -v printed '%d FILES PROCESSED\n' "$fc"
toWrite+=$printed; echo "$toWrite" > "$d".log
cd ..
done
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package atom
import (
"context"
"io"
"io/ioutil"
"net/http"
"github.com/devigned/tab"
)
// CloseRes closes the response (or if it's nil just no-ops)
func CloseRes(ctx context.Context, res *http.Response) {
if res == nil {
return
}
_, _ = io.Copy(ioutil.Discard, res.Body)
if err := res.Body.Close(); err != nil {
tab.For(ctx).Error(err)
}
}
|
# Hello!
---
I am *Fatih* Karakus. This is how I look like;

## Basic info about me
* from Turkey
* 40 years old
* married
* father of two *beautiful* sons
* lives in **Hasselt**
---
You can access my **Github** page from [here](https://github.com/fmkarakus).
|
package uk.gov.dvla.vehicles.presentation.common.models
import org.joda.time.LocalDate
import play.api.data.Forms.mapping
import play.api.libs.json.Json
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.CacheKey
import uk.gov.dvla.vehicles.presentation.common.mappings
import uk.gov.dvla.vehicles.presentation.common.services.DateService
case class DateModel(date: LocalDate)
object DateModel {
implicit val Key = CacheKey[DateModel]("test")
implicit val JsonFormat = Json.format[DateModel]
object Form {
final val DateId = "DateFieldId1"
final def Mapping(implicit dateService: DateService) = mapping(
DateId -> mappings.Date.dateMapping.verifying(mappings.Date.notInTheFuture())
)(DateModel.apply)(DateModel.unapply)
}
}
|
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Czas generowania: 03 Lut 2017, 23:43
-- Wersja serwera: 10.1.16-MariaDB
-- Wersja PHP: 5.6.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Baza danych: `ave`
--
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `albumy`
--
CREATE TABLE `albumy` (
`id` int(11) NOT NULL,
`tytul` varchar(100) COLLATE utf8_polish_ci NOT NULL,
`data` date NOT NULL,
`id_uzytkownika` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `uzytkownicy`
--
CREATE TABLE `uzytkownicy` (
`id` int(11) NOT NULL,
`login` varchar(20) COLLATE utf8_polish_ci NOT NULL,
`hasło` varchar(32) COLLATE utf8_polish_ci NOT NULL,
`email` varchar(128) COLLATE utf8_polish_ci NOT NULL,
`zarejestrowany` date NOT NULL,
`uprawnienia` enum('uzytkownik','moderator','administrator') COLLATE utf8_polish_ci NOT NULL,
`aktywny` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
--
-- Zrzut danych tabeli `uzytkownicy`
--
INSERT INTO `uzytkownicy` (`id`, `login`, `hasło`, `email`, `zarejestrowany`, `uprawnienia`, `aktywny`) VALUES
(1, 'robcio', '883ab664180407bda9659d1ba774802c', '[email protected]', '2016-12-22', 'administrator', 1),
(2, 'robercik', '14b0e4f335a105a131545bf3fa2683ba', '[email protected]', '2017-02-02', 'administrator', 0);
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `zadjecia`
--
CREATE TABLE `zadjecia` (
`id` int(11) NOT NULL,
`tytul` varchar(255) COLLATE utf8_polish_ci NOT NULL,
`id_albumu` int(11) NOT NULL,
`data` date NOT NULL,
`id_uzytkownika` int(11) NOT NULL,
`zaakceptowane` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `zadjecia_komentarze`
--
CREATE TABLE `zadjecia_komentarze` (
`ID` int(11) NOT NULL,
`id_zdjecia` int(11) NOT NULL,
`id_uzytkownika` int(11) NOT NULL,
`data` date NOT NULL,
`komentarz` varchar(11) COLLATE utf8_polish_ci NOT NULL,
`zaakceptowany` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `zadjecia_oceny`
--
CREATE TABLE `zadjecia_oceny` (
`id_zdjecia` int(11) NOT NULL,
`id_uzytkownika` int(11) NOT NULL,
`ocena` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
--
-- Indeksy dla zrzutów tabel
--
--
-- Indexes for table `albumy`
--
ALTER TABLE `albumy`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `uzytkownicy`
--
ALTER TABLE `uzytkownicy`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `zadjecia`
--
ALTER TABLE `zadjecia`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `zadjecia_komentarze`
--
ALTER TABLE `zadjecia_komentarze`
ADD PRIMARY KEY (`ID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT dla tabeli `albumy`
--
ALTER TABLE `albumy`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT dla tabeli `uzytkownicy`
--
ALTER TABLE `uzytkownicy`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT dla tabeli `zadjecia`
--
ALTER TABLE `zadjecia`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT dla tabeli `zadjecia_komentarze`
--
ALTER TABLE `zadjecia_komentarze`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
<?php
/**
* Starter Module
*
* @author PremiumPresta <[email protected]>
* @copyright PremiumPresta
* @license http://creativecommons.org/licenses/by/4.0/ CC BY 4.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class Vuefront extends Module
{
/** @var array Use to store the configuration from database */
public $config_values;
/** @var array submit values of the configuration page */
protected static $config_post_submit_values = array('saveConfig');
public function __construct()
{
$this->name = 'vuefront'; // internal identifier, unique and lowercase
$this->tab = 'front_office_features'; // backend module coresponding category
$this->version = '2.1.1'; // version number for the module
$this->author = 'VueFront'; // module author
$this->need_instance = 0; // load the module when displaying the "Modules" page in backend
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('VueFront'); // public name
$this->description = $this->l('CMS Connect App for PrestaShop'); // public description
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); // confirmation message at uninstall
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->module_key = '1d77752fd71e98268cd50f200cb5f5ce';
}
/**
* Install this module
* @return boolean
*/
public function install()
{
Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'vuefront_url` (
`id_url` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id` INT( 11 ) UNSIGNED NOT NULL,
`type` varchar(64) NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`id_url`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8');
return parent::install() &&
$this->registerAdminTab() && $this->registerAdminAjaxTab();
}
/**
* Uninstall this module
* @return boolean
*/
public function uninstall()
{
return Configuration::deleteByName($this->name) &&
parent::uninstall() &&
$this->deleteAdminTab();
}
/**
* Configuration page
*/
public function getContent()
{
$this->config_values = $this->getConfigValues();
$this->context->smarty->assign(array(
'module' => array(
'class' => get_class($this),
'name' => $this->name,
'displayName' => $this->displayName,
'dir' => $this->_path
)
));
$app = json_decode(
Tools::file_get_contents(
realpath(_PS_MODULE_DIR_.'vuefront/').'/'
. '/views/js/d_vuefront/manifest.json'
),
true
);
$current_chunk = $app['files'];
while (!empty($current_chunk)) {
foreach ($current_chunk['js'] as $value) {
$this->context->controller->addJS(
$this->_path . 'views/js/d_vuefront/' . basename($value),
false
);
}
foreach ($current_chunk['css'] as $value) {
$this->context->controller->addCSS(
$this->_path . 'views/css/admin/' . basename($value)
);
}
$current_chunk = $current_chunk['next'];
}
$this->context->smarty->assign(array(
'catalog' => Tools::getHttpHost(true).
__PS_BASE_URI__.'index.php?controller=graphql&module=vuefront&fc=module',
'blog' => Module::isInstalled('prestablog'),
'baseUrl' => '',
'siteUrl' => Tools::getHttpHost(true).
__PS_BASE_URI__,
'tokenVuefront' => Tools::getAdminTokenLite('AdminVuefrontAjax')
));
return $this->display(__FILE__, 'views/templates/admin/configure.tpl');
}
/**
* Get configuration array from database
* @return array
*/
public function getConfigValues()
{
return json_decode(Configuration::get($this->name), true);
}
public function registerAdminAjaxTab()
{
$tab = new Tab();
$tab->class_name = 'AdminVuefrontAjax';
$tab->module = 'vuefront';
foreach (Language::getLanguages(false) as $lang) {
$tab->name[$lang['id_lang']] = 'Vuefront';
}
$tab->id_parent = -1;
return $tab->save();
}
public function registerAdminTab()
{
$tab = new Tab();
$tab->class_name = 'AdminVuefront';
foreach (Language::getLanguages(false) as $lang) {
$tab->name[$lang['id_lang']] = 'Vuefront';
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminTools');
$tab->module = 'vuefront';
$tab->icon = 'library_books';
return $tab->save();
}
public function deleteAdminTab()
{
foreach (array('AdminVuefront') as $tab_name) {
$id_tab = (int)Tab::getIdFromClassName($tab_name);
if ($id_tab) {
$tab = new Tab($id_tab);
$tab->delete();
}
}
return true;
}
}
|
package com.ximedes.vas.api.async
import com.ximedes.vas.api.*
import com.ximedes.vas.domain.*
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.ContentNegotiation
import io.ktor.http.HttpStatusCode
import io.ktor.jackson.jackson
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.get
import io.ktor.routing.post
import io.ktor.routing.route
import io.ktor.routing.routing
import kotlinx.coroutines.delay
import mu.KotlinLogging
import java.util.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module() {
val logger = KotlinLogging.logger {}
install(ContentNegotiation) {
jackson { }
}
val ledger = AsyncLedger()
routing {
post("/user") {
val msg = call.receive<CreateUserRequest>()
val user = User(UserID(msg.id), msg.email)
ledger.createUser(user)
call.respond(HttpStatusCode.OK)
}
route("/account") {
get("/{userId}") {
val userID = UserID(call.parameters["userId"]!!)
val accounts = ledger.findAccountsByUserID(userID)
call.respond(accounts)
}
post {
val msg = call.receive<CreateAccountRequest>()
val account = Account(UserID(msg.user), AccountID((msg.account)), 0, msg.overdraft, msg.description)
ledger.createAccount(account)
call.respond(HttpStatusCode.OK)
}
}
post("/transfer") {
val msg = call.receive<TransferRequest>()
val id = TransferID(UUID.randomUUID().toString())
val transfer = Transfer(id, AccountID(msg.from), AccountID(msg.to), msg.amount, msg.description)
ledger.transfer(transfer)
call.respond(transfer)
}
post("/reset") {
val reset = call.receive<ResetRequest>()
val capacity = reset.readCapacityUnits?.let { rcu ->
reset.writeCapacityUnits?.let { wcu ->
Pair(rcu, wcu)
}
}
ledger.reset(capacity)
call.respond(HttpStatusCode.OK)
}
get("/sleep") {
val ms = call.request.queryParameters["ms"]?.toLong() ?: defaultSleepMS
delay(ms)
call.respond(HttpStatusCode.OK)
}
}
}
|
# ZooKeeper Installation
Download and extract ZooKeeper using 7-zip from [zookeeper download site](http://zookeeper.apache.org/releases.html)
1. Go to your ZooKeeper config directory. For me its C:\apps\zookeeper\apache-zookeeper-3.5.5-bin\conf
1. Rename file “zoo_sample.cfg” to “zoo.cfg”
1. Open zoo.cfg in any text editor
1. Find and edit dataDir=/tmp/zookeeper to dataDir=C:\apps\zookeeper\apache-zookeeper-3.5.5-bin\data
1. add the following line to the end of the file:
admin.serverPort=8020
1. Add an entry in the System Environment Variables as we did for Java.
* Add ZOOKEEPER_HOME = C:\apps\zookeeper\apache-zookeeper-3.5.5-bin to the System Variables.
* Edit the System Variable named “Path” and add ;%ZOOKEEPER_HOME%\bin;
1. You can change the default Zookeeper port in zoo.cfg file (Default port 2181).
1. Switch to directory:
C:\apps\zookeeper\apache-zookeeper-3.5.5-bin\bin
Run ZooKeeper by opening a new cmd and type zkserver.
[zookeeper admin guide](https://zookeeper.apache.org/doc/r3.5.4-beta/zookeeperAdmin.html#sc_adminserver_config)
[source](https://dzone.com/articles/running-apache-kafka-on-windows-os) |
import {Action, handleActions} from 'redux-actions';
import {SystemSchema} from '../api/types';
import {SystemSchemaFetchedPayload, systemSchemaFetched} from '../action/systemSchemaEvents';
export interface SystemSchemaState {
systemSchema: null|SystemSchema;
}
export const initialState = {
systemSchema: null,
};
export const reducer = handleActions<SystemSchemaState, any>(
{
[systemSchemaFetched.toString()]: (state = initialState, action: Action<SystemSchemaFetchedPayload>) => {
if (!state) {
return state;
}
return {
...state,
systemSchema: action.payload.systemSchema,
};
},
},
initialState,
);
|
import Template from '../models/Template';
export default class TslintConfig implements Template {
private innerTemplate = {
defaultSeverity: 'error',
extends: ['tslint:recommended', 'tslint-react', 'tslint-config-prettier'],
jsRules: {},
rules: {
'arrow-parens': [false],
indent: [true, 'spaces', 2],
'object-literal-sort-keys': [false],
'one-line': [true, 'check-open-space', 'check-whitespace'],
'trailing-comma': [false]
},
rulesDirectory: ['tslint-plugin-prettier']
};
public readonly name: string = 'tslint.json';
public generate(): string {
return JSON.stringify(this.innerTemplate, null, 2);
}
}
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("SavedStateHandleSupport")
package androidx.lifecycle
import android.os.Bundle
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModelProvider.NewInstanceFactory.Companion.VIEW_MODEL_KEY
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryOwner
private const val VIEWMODEL_KEY = "androidx.lifecycle.internal.SavedStateHandlesVM"
private const val SAVED_STATE_KEY = "androidx.lifecycle.internal.SavedStateHandlesProvider"
/**
* Enables the support of [SavedStateHandle] in a component.
*
* After this method, [createSavedStateHandle] can be called on [CreationExtras] containing this
* [SavedStateRegistryOwner] / [ViewModelStoreOwner].
*
* Must be called while component is in `INITIALIZED` or `CREATED` state and before
* a [ViewModel] with [SavedStateHandle] is requested.
*/
@MainThread
fun <T> T.enableSavedStateHandles()
where T : SavedStateRegistryOwner, T : ViewModelStoreOwner {
val currentState = lifecycle.currentState
require(
currentState == Lifecycle.State.INITIALIZED || currentState == Lifecycle.State.CREATED
)
// Add the SavedStateProvider used to save SavedStateHandles
// if we haven't already registered the provider
if (savedStateRegistry.getSavedStateProvider(SAVED_STATE_KEY) == null) {
val provider = SavedStateHandlesProvider(savedStateRegistry, this)
savedStateRegistry.registerSavedStateProvider(SAVED_STATE_KEY, provider)
lifecycle.addObserver(SavedStateHandleAttacher(provider))
}
}
private fun createSavedStateHandle(
savedStateRegistryOwner: SavedStateRegistryOwner,
viewModelStoreOwner: ViewModelStoreOwner,
key: String,
defaultArgs: Bundle?
): SavedStateHandle {
val provider = savedStateRegistryOwner.savedStateHandlesProvider
val viewModel = viewModelStoreOwner.savedStateHandlesVM
// If we already have a reference to a previously created SavedStateHandle
// for a given key stored in our ViewModel, use that. Otherwise, create
// a new SavedStateHandle, providing it any restored state we might have saved
return viewModel.handles[key] ?: SavedStateHandle.createHandle(
provider.consumeRestoredStateForKey(key), defaultArgs
).also { viewModel.handles[key] = it }
}
/**
* Creates `SavedStateHandle` that can be used in your ViewModels
*
* This function requires [enableSavedStateHandles] call during the component
* initialization. Latest versions of androidx components like `ComponentActivity`, `Fragment`,
* `NavBackStackEntry` makes this call automatically.
*
* This [CreationExtras] must contain [SAVED_STATE_REGISTRY_OWNER_KEY],
* [VIEW_MODEL_STORE_OWNER_KEY] and [VIEW_MODEL_KEY].
*
* @throws IllegalArgumentException if this `CreationExtras` are missing required keys:
* `ViewModelStoreOwnerKey`, `SavedStateRegistryOwnerKey`, `VIEW_MODEL_KEY`
*/
@MainThread
public fun CreationExtras.createSavedStateHandle(): SavedStateHandle {
val savedStateRegistryOwner = this[SAVED_STATE_REGISTRY_OWNER_KEY]
?: throw IllegalArgumentException(
"CreationExtras must have a value by `SAVED_STATE_REGISTRY_OWNER_KEY`"
)
val viewModelStateRegistryOwner = this[VIEW_MODEL_STORE_OWNER_KEY]
?: throw IllegalArgumentException(
"CreationExtras must have a value by `VIEW_MODEL_STORE_OWNER_KEY`"
)
val defaultArgs = this[DEFAULT_ARGS_KEY]
val key = this[VIEW_MODEL_KEY] ?: throw IllegalArgumentException(
"CreationExtras must have a value by `VIEW_MODEL_KEY`"
)
return createSavedStateHandle(
savedStateRegistryOwner, viewModelStateRegistryOwner, key, defaultArgs
)
}
internal val ViewModelStoreOwner.savedStateHandlesVM: SavedStateHandlesVM
get() = ViewModelProvider(this, viewModelFactory {
initializer { SavedStateHandlesVM() }
})[VIEWMODEL_KEY, SavedStateHandlesVM::class.java]
internal val SavedStateRegistryOwner.savedStateHandlesProvider: SavedStateHandlesProvider
get() = savedStateRegistry.getSavedStateProvider(SAVED_STATE_KEY) as? SavedStateHandlesProvider
?: throw IllegalStateException("enableSavedStateHandles() wasn't called " +
"prior to createSavedStateHandle() call")
internal class SavedStateHandlesVM : ViewModel() {
val handles = mutableMapOf<String, SavedStateHandle>()
}
/**
* This single SavedStateProvider is responsible for saving the state of every
* SavedStateHandle associated with the SavedState/ViewModel pair.
*/
internal class SavedStateHandlesProvider(
private val savedStateRegistry: SavedStateRegistry,
viewModelStoreOwner: ViewModelStoreOwner
) : SavedStateRegistry.SavedStateProvider {
private var restored = false
private var restoredState: Bundle? = null
private val viewModel by lazy {
viewModelStoreOwner.savedStateHandlesVM
}
override fun saveState(): Bundle {
return Bundle().apply {
// Ensure that even if ViewModels aren't recreated after process death and recreation
// that we keep their state until they are recreated
if (restoredState != null) {
putAll(restoredState)
}
// But if we do have ViewModels, prefer their state over what we may
// have restored
viewModel.handles.forEach { (key, handle) ->
val savedState = handle.savedStateProvider().saveState()
if (savedState != Bundle.EMPTY) {
putBundle(key, savedState)
}
}
}.also {
// After we've saved the state, allow restoring a second time
restored = false
}
}
/**
* Restore the state from the SavedStateRegistry if it hasn't already been restored.
*/
fun performRestore() {
if (!restored) {
restoredState = savedStateRegistry.consumeRestoredStateForKey(SAVED_STATE_KEY)
restored = true
// Grab a reference to the ViewModel for later usage when we saveState()
// This ensures that even if saveState() is called after the Lifecycle is
// DESTROYED, we can still save the state
viewModel
}
}
/**
* Restore the state associated with a particular SavedStateHandle, identified by its [key]
*/
fun consumeRestoredStateForKey(key: String): Bundle? {
performRestore()
return restoredState?.getBundle(key).also {
restoredState?.remove(key)
if (restoredState?.isEmpty == true) {
restoredState = null
}
}
}
}
// it reconnects existent SavedStateHandles to SavedStateRegistryOwner when it is recreated
internal class SavedStateHandleAttacher(
private val provider: SavedStateHandlesProvider
) : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
check(event == Lifecycle.Event.ON_CREATE) {
"Next event must be ON_CREATE, it was $event"
}
source.lifecycle.removeObserver(this)
// onRecreated() is called after the Lifecycle reaches CREATED, so we
// eagerly restore the state as part of this call to ensure it consumed
// even if no ViewModels are actually created during this cycle of the Lifecycle
provider.performRestore()
}
}
/**
* A key for [SavedStateRegistryOwner] that corresponds to [ViewModelStoreOwner]
* of a [ViewModel] that is being created.
*/
@JvmField
val SAVED_STATE_REGISTRY_OWNER_KEY = object : CreationExtras.Key<SavedStateRegistryOwner> {}
/**
* A key for [ViewModelStoreOwner] that is an owner of a [ViewModel] that is being created.
*/
@JvmField
val VIEW_MODEL_STORE_OWNER_KEY = object : CreationExtras.Key<ViewModelStoreOwner> {}
/**
* A key for default arguments that should be passed to [SavedStateHandle] if needed.
*/
@JvmField
val DEFAULT_ARGS_KEY = object : CreationExtras.Key<Bundle> {}
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:valid_attributes) do
{
first_name: "Asafaa",
last_name: "Daevidoov",
email: "[email protected]",
password: "password123",
password_confirmation: "password123"
}
end
let(:password_not_matching_confirmation) { valid_attributes.merge(password_confirmation: "password1234") }
let(:password_too_short) { valid_attributes.merge(password: "1234") }
let(:missing_email) { valid_attributes.except(:email) }
it "is valid when expected" do
expect(User.new(valid_attributes)).to be_valid
end
it "is invalid when password_confirmation and password do not match" do
expect(User.new(password_not_matching_confirmation)).to be_invalid
end
it "is invalid when password is too short" do
expect(User.new(password_too_short)).to be_invalid
end
it "is invalid without email" do
expect(User.new(missing_email)).to be_invalid
end
end
|
use strict;
use warnings;
use Getopt::Long;
my $bedgenes = 'Hw2.maker_genes_only.bed';
my $bedwindows = 'Hw2.maker_genes_only.5windows.bed';
GetOptions("g|gene|genes:s" => \$bedgenes,
'w|window|windows:s' => \$bedwindows,
);
open(my $in => $bedgenes) || die $!;
my %genes;
while(<$in>) {
my ($chr,$start,$end,$name,$score,$strand) = split;
$genes{$name} = $strand;
}
open($in => $bedwindows) || die $!;
my %windows;
while(<$in>) {
my ($chr,$start,$end,$w) = split;
my $gene;
if( $w =~ /(\S+)_(\d+)$/ ) {
$gene = $1;
} else {
$gene= $w;
# die"expected window num at end of gene name";
}
push @{$windows{$chr}->{$gene}}, [$start,$end];
}
for my $chr ( sort keys %windows ) {
for my $gene ( sort keys %{$windows{$chr}} ) {
my @windows = @{$windows{$chr}->{$gene}};
if ( $genes{$gene} eq '-' ) {
@windows = reverse @windows; # flip the order if
}
my $i = 1;
for my $window ( @windows ) {
print join("\t", $chr, @$window, sprintf("%s_%d",$gene,$i++),'.',$genes{$gene}),"\n";
}
}
}
|
module Api
module V1
class Verifications < Grape::API
version 'v1'
format :json
content_type :json, 'application/json'
prefix :api
params do
requires :campaign_list, type: Array[Hash], desc: 'list of campaigns'
end
desc 'Creates Verification and returns a list of reports or empty list'
post :verify do
Verification.create!(campaign_list: params[:campaign_list]).perform!
end
add_swagger_documentation(
api_version: 'v1',
hide_documentation_path: true,
info: {
title: 'AdMatcher',
description: 'Simple solution to verify ads'
}
)
end
end
end
|
package me.obsilabor.prismarin.module.modules
import me.obsilabor.prismarin.minecraft.gui.`super`.SuperMenu
import me.obsilabor.prismarin.module.AbstractModule
import me.obsilabor.prismarin.module.Module
import me.obsilabor.prismarin.module.SystemIntegrated
import me.obsilabor.prismarin.setting.Setting
import me.obsilabor.prismarin.theme.Theme
import me.obsilabor.prismarin.theme.ThemeManager
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper
import net.minecraft.client.option.KeyBinding
import net.minecraft.client.util.InputUtil
import org.lwjgl.glfw.GLFW
@SystemIntegrated
@Module(
name = "Prismarin",
description = "Provider for core mod settings"
)
object SettingsProvider : AbstractModule() {
private var keyBinding: KeyBinding? = null
val selectedTheme: Theme
get() = getSetting("theme")
fun setting(key: String): Setting<*> {
return getRawSetting(key)
}
override fun init() {
addThemeSetting("theme", "Theme", ThemeManager.LIGHT)
if(!isEnabled()) {
toggle()
}
keyBinding = KeyBindingHelper.registerKeyBinding(
KeyBinding(
"Open Super Menu",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_RIGHT_SHIFT,
"Prismarin"
)
)
ClientTickEvents.END_CLIENT_TICK.register(ClientTickEvents.EndTick {
while (keyBinding?.wasPressed() == true) {
it.setScreen(SuperMenu())
}
})
}
override fun onSettingsChanged() {
ThemeManager.currentTheme = selectedTheme
}
override fun toggle() {
if(!isEnabled()) {
isEnabled = true
onEnable()
}
}
} |
package json
import (
"encoding"
"io"
"reflect"
"strconv"
"sync"
"unsafe"
)
type Delim rune
func (d Delim) String() string {
return string(d)
}
type decoder interface {
decode([]byte, int64, unsafe.Pointer) (int64, error)
decodeStream(*stream, unsafe.Pointer) error
}
type Decoder struct {
s *stream
disallowUnknownFields bool
structTypeToDecoder map[uintptr]decoder
}
type decoderMap struct {
sync.Map
}
func (m *decoderMap) get(k uintptr) decoder {
if v, ok := m.Load(k); ok {
return v.(decoder)
}
return nil
}
func (m *decoderMap) set(k uintptr, dec decoder) {
m.Store(k, dec)
}
var (
cachedDecoder decoderMap
unmarshalJSONType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
unmarshalTextType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
)
func init() {
cachedDecoder = decoderMap{}
}
const (
nul = '\000'
)
// NewDecoder returns a new decoder that reads from r.
//
// The decoder introduces its own buffering and may
// read data from r beyond the JSON values requested.
func NewDecoder(r io.Reader) *Decoder {
s := newStream(r)
return &Decoder{
s: s,
}
}
// Buffered returns a reader of the data remaining in the Decoder's
// buffer. The reader is valid until the next call to Decode.
func (d *Decoder) Buffered() io.Reader {
return d.s.buffered()
}
func (d *Decoder) validateType(typ *rtype, p uintptr) error {
if typ.Kind() != reflect.Ptr || p == 0 {
return &InvalidUnmarshalError{Type: rtype2type(typ)}
}
return nil
}
func (d *Decoder) decode(src []byte, header *interfaceHeader) error {
typ := header.typ
typeptr := uintptr(unsafe.Pointer(typ))
// noescape trick for header.typ ( reflect.*rtype )
copiedType := *(**rtype)(unsafe.Pointer(&typeptr))
ptr := uintptr(header.ptr)
if err := d.validateType(copiedType, ptr); err != nil {
return err
}
dec := cachedDecoder.get(typeptr)
if dec == nil {
d.structTypeToDecoder = map[uintptr]decoder{}
compiledDec, err := d.compileHead(copiedType)
if err != nil {
return err
}
cachedDecoder.set(typeptr, compiledDec)
dec = compiledDec
}
if _, err := dec.decode(src, 0, header.ptr); err != nil {
return err
}
return nil
}
func (d *Decoder) decodeForUnmarshal(src []byte, v interface{}) error {
header := (*interfaceHeader)(unsafe.Pointer(&v))
header.typ.escape()
return d.decode(src, header)
}
func (d *Decoder) decodeForUnmarshalNoEscape(src []byte, v interface{}) error {
header := (*interfaceHeader)(unsafe.Pointer(&v))
return d.decode(src, header)
}
func (d *Decoder) prepareForDecode() error {
s := d.s
for {
switch s.char() {
case ' ', '\t', '\r', '\n':
s.cursor++
continue
case ',', ':':
s.cursor++
return nil
case nul:
if s.read() {
continue
}
return io.EOF
}
break
}
return nil
}
// Decode reads the next JSON-encoded value from its
// input and stores it in the value pointed to by v.
//
// See the documentation for Unmarshal for details about
// the conversion of JSON into a Go value.
func (d *Decoder) Decode(v interface{}) error {
header := (*interfaceHeader)(unsafe.Pointer(&v))
typ := header.typ
ptr := uintptr(header.ptr)
typeptr := uintptr(unsafe.Pointer(typ))
// noescape trick for header.typ ( reflect.*rtype )
copiedType := *(**rtype)(unsafe.Pointer(&typeptr))
if err := d.validateType(copiedType, ptr); err != nil {
return err
}
dec := cachedDecoder.get(typeptr)
if dec == nil {
d.structTypeToDecoder = map[uintptr]decoder{}
compiledDec, err := d.compileHead(typ)
if err != nil {
return err
}
cachedDecoder.set(typeptr, compiledDec)
dec = compiledDec
}
if err := d.prepareForDecode(); err != nil {
return err
}
s := d.s
if err := dec.decodeStream(s, header.ptr); err != nil {
return err
}
return nil
}
func (d *Decoder) More() bool {
s := d.s
for {
switch s.char() {
case ' ', '\n', '\r', '\t':
s.cursor++
continue
case '}', ']':
return false
case nul:
if s.read() {
continue
}
return false
}
break
}
return true
}
func (d *Decoder) Token() (Token, error) {
s := d.s
for {
c := s.char()
switch c {
case ' ', '\n', '\r', '\t':
s.cursor++
case '{', '[', ']', '}':
s.cursor++
return Delim(c), nil
case ',', ':':
s.cursor++
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
bytes := floatBytes(s)
s := *(*string)(unsafe.Pointer(&bytes))
f64, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
return f64, nil
case '"':
bytes, err := stringBytes(s)
if err != nil {
return nil, err
}
return string(bytes), nil
case 't':
if err := trueBytes(s); err != nil {
return nil, err
}
return true, nil
case 'f':
if err := falseBytes(s); err != nil {
return nil, err
}
return false, nil
case 'n':
if err := nullBytes(s); err != nil {
return nil, err
}
return nil, nil
case nul:
if s.read() {
continue
}
return nil, io.EOF
default:
return nil, errInvalidCharacter(s.char(), "token", s.totalOffset())
}
}
return nil, io.EOF
}
// DisallowUnknownFields causes the Decoder to return an error when the destination
// is a struct and the input contains object keys which do not match any
// non-ignored, exported fields in the destination.
func (d *Decoder) DisallowUnknownFields() {
d.s.disallowUnknownFields = true
}
func (d *Decoder) InputOffset() int64 {
return d.s.totalOffset()
}
// UseNumber causes the Decoder to unmarshal a number into an interface{} as a
// Number instead of as a float64.
func (d *Decoder) UseNumber() {
d.s.useNumber = true
}
|
package streaming_transmit
import (
"sync"
"sync/atomic"
)
type pendingRequest struct {
dst []byte // dst to copy response to
err error // error while waiting for response
wg sync.WaitGroup // signals the caller that the response has been received
}
type PendingRequestPool struct {
sp sync.Pool
m *PoolMetrics
}
func (p *PendingRequestPool) acquire(dst []byte) *pendingRequest {
v := p.sp.Get()
if v == nil {
v = &pendingRequest{}
atomic.AddUint32(&p.m.na, uint32(1))
} else {
atomic.AddUint32(&p.m.nr, uint32(1))
}
pr := v.(*pendingRequest)
pr.dst = dst
return pr
}
func (p *PendingRequestPool) release(pr *pendingRequest) {
pr.dst = nil
pr.err = nil
p.sp.Put(pr)
atomic.AddUint32(&p.m.np, uint32(1))
}
|
package ginutil
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestGetOrigin(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", nil)
c.Request.Host = "test.localhost"
assert.Equal(t, "http://test.localhost", GetOrigin(c))
c.Request.Header.Set("X-Forwarded-Proto", "https")
c.Request.Header.Set("X-Forwarded-Host", "abc.localhost")
assert.Equal(t, "https://abc.localhost", GetOrigin(c))
}
|
# enjoy-env
A library which can get the browser environment information of the visitors for you.
一个获取用户浏览容器信息的库。
## 安装
```bash
npm i enjoy-env
```
引入类库:
```javascript
import enjoyEnv from 'enjoy-env';
```
## API
### libVersion
获得当前类库的版本号
### dpr
获得设备的设备像素比(devicePixelRatio)
## app
判别用户是在何种Native APP容器中访问当前页面
app.name - 表示在哪个APP中
app.isUnknown - true,不知道在哪个app中(未检测出来);false,表示检测出来在某个APP中
app.isWeibo - 检测到在微博中
app.isWechat - 检测到在微信中
## system
获取用户设备的操作系统信息,返回信息格式如下
```
{
name: '', //系统名称
version: '' //系统版本号
}
```
## browser
获取用户设备的浏览器信息,返回信息格式如下
```
{
name: '', //浏览器名称
version: '' //浏览器版本号
}
```
|
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.choreo.connect.enforcer.tracing;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.context.Context;
import org.wso2.choreo.connect.enforcer.constants.Constants;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Span utility class
*/
public class Utils {
private static boolean isTracingEnabled = false;
/**
* Initialize a span with parent context. Used to link the enforcer traces under
* router's trace context.
*
* @param spanName the name of the span
* @param context parent trace context
* @param tracer a tracer instance
* @return a TracingSpan object
*/
public static TracingSpan startSpan(String spanName, Context context, TracingTracer tracer) {
if (context == null) {
return startSpan(spanName, tracer);
}
Span cs = tracer.getTracingTracer().spanBuilder(spanName)
.setParent(context)
.setSpanKind(SpanKind.SERVER)
.startSpan();
return new TracingSpan(cs);
}
/**
* Start the tracing span
*
* @param spanName the name of the span
* @param tracer io.opentelemetry.api.trace.Span
* @return a TracingSpan object
*/
public static TracingSpan startSpan(String spanName, TracingTracer tracer) {
Span span = tracer.getTracingTracer().spanBuilder(spanName).startSpan();
return new TracingSpan(span);
}
/**
* Set tag to the span
*
* @param span the span tag is to be set
* @param key key
* @param value value
*/
public static void setTag(TracingSpan span, String key, String value) {
Span sp = span.getSpan();
if (sp != null) {
sp.setAttribute(key, value);
}
}
/**
* Finish the span
*
* @param span span that is to be finished
*/
public static void finishSpan(TracingSpan span) {
Span sp = span.getSpan();
if (sp != null) {
sp.end();
}
}
public static void setTracingEnabled(boolean isTracingEnabled) {
Utils.isTracingEnabled = isTracingEnabled;
}
public static boolean tracingEnabled() {
return isTracingEnabled;
}
public static TracingTracer getGlobalTracer() {
return new TracingTracer(TracerFactory.getInstance().getTracer());
}
public static String replaceEnvRegex(String value) {
Matcher m = Pattern.compile("\\$env\\{(.*?)\\}").matcher(value);
if (value.contains(Constants.ENV_PREFIX)) {
while (m.find()) {
String envName = value.substring(m.start() + 5, m.end() - 1);
if (System.getenv(envName) != null) {
value = value.replace(value.substring(m.start(), m.end()), System.getenv(envName));
}
}
}
return value;
}
}
|
package flow_test
import(
"io"
"fmt"
"github.com/hyper-ml/hyperml/server/pkg/flow"
"testing"
)
func Test_LogStream(t *testing.T) {
flow_id := "9d9f19754e714d2fbad352c05a33ecba"
pk := flow.NewDefaultPodKeeper(nil, nil)
ro, err := pk.LogStream(flow_id)
if err != nil {
t.Fatalf("error: %s", err)
}
var n int
p := make([]byte, 4)
for {
n, err = ro.Read(p)
fmt.Println("n: ", n, err)
if err != nil {
if (err == io.EOF && n == 0 ){
break
}
fmt.Println("error reading Io: ", err)
}
fmt.Println(string(p[:n]))
// subscribe to kube log
// watch for done
}
} |
/* eslint-disable import/no-extraneous-dependencies */
const tape = require('tape');
const utils = require('./utilities');
const tokensModule = require('../tokens');
tape.test('tokens', (test) => {
test.test('getUserFromToken', (getUserFromTokenTest) => {
getUserFromTokenTest.test('with invalid token', (invalidTokenTest) => {
process.env.JWT_SECRET = 'secret';
process.env.TOKEN_SIGNATURE_ALGORITHM = 'HS256';
const testFn = () => tokensModule.getUserFromToken('invalid token');
invalidTokenTest.throws(testFn, 'throws an exception');
invalidTokenTest.end();
});
getUserFromTokenTest.test('with valid token', (validTokenTest) => {
validTokenTest.test('with invalid secret', (invalidSecretTest) => {
process.env.JWT_SECRET = 'invalid secret';
process.env.TOKEN_SIGNATURE_ALGORITHM = 'HS256';
const testFn = () => tokensModule.getUserFromToken(utils.validAuthorizationToken);
invalidSecretTest.throws(testFn, 'throws an exception');
invalidSecretTest.end();
});
validTokenTest.test('with valid secret', (validSecretTest) => {
process.env.JWT_SECRET = 'secret';
process.env.TOKEN_SIGNATURE_ALGORITHM = 'HS256';
const user = tokensModule.getUserFromToken(utils.validAuthorizationToken);
validSecretTest.deepEqual(user, utils.validAuthorizationObject, 'resolves the correct object');
validSecretTest.end();
});
validTokenTest.end();
});
getUserFromTokenTest.end();
});
test.test('createTokenFromUser', (createTokenFromUser) => {
process.env.JWT_SECRET = 'secret';
process.env.TOKEN_SIGNATURE_ALGORITHM = 'HS256';
process.env.TOKEN_EXPIRE_TIME = '2h';
const token = tokensModule.createTokenFromUser(utils.validAuthorizationObject);
createTokenFromUser.ok(token, 'returns a token');
createTokenFromUser.ok(/[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+/.test(token), 'token has valid structure');
// We can't test the actual value of the token because it
// will have an iat based on the timestampe when the token
// was created. The only way to test the value of the
// token would be to decrypt it and then check the parts
// we expect (e.g., validAuthorizationObject).
createTokenFromUser.end();
});
test.end();
});
|
package com.marcohc.terminator.sample.feature.detail
import com.marcohc.terminator.sample.data.model.User
import com.marcohc.terminator.sample.data.repositories.ConnectionManager
import com.marcohc.terminator.sample.data.repositories.UserRepository
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Completable
import io.reactivex.internal.operators.single.SingleJust
import io.reactivex.schedulers.Schedulers
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
internal class GetUserByIdUseCaseTest {
@Mock
lateinit var connectionManager: ConnectionManager
@Mock
private lateinit var userRepository: UserRepository
private lateinit var useCase: GetVenueByIdUseCase
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
useCase = GetVenueByIdUseCase(
connectionManager,
userRepository,
Schedulers.trampoline()
)
}
@Test
fun `given connection when use case executes then return items`() {
val city = "Madrid"
val item = User()
whenever(connectionManager.isConnected()).thenReturn(true)
whenever(userRepository.getByIdFromLocal(city)).thenReturn(SingleJust(item))
whenever(userRepository.getByIdFromNetwork(city)).thenReturn(SingleJust(item))
whenever(userRepository.save(item)).thenReturn(Completable.complete())
useCase.execute(city).test().assertValue { it == item }
}
@Test
fun `given connection when use case executes then save items`() {
val city = "Madrid"
val item = User()
whenever(connectionManager.isConnected()).thenReturn(true)
whenever(userRepository.getByIdFromNetwork(city)).thenReturn(SingleJust(item))
whenever(userRepository.getByIdFromLocal(city)).thenReturn(SingleJust(item))
useCase.execute(city).test()
verify(userRepository).save(item)
}
@Test
fun `given no connection when use case executes then return local items`() {
val city = "Madrid"
val item = User()
whenever(connectionManager.isConnected()).thenReturn(false)
whenever(userRepository.getByIdFromLocal(city)).thenReturn(SingleJust(item))
useCase.execute(city).test().assertValue { it == item }
}
}
|
use common::err;
//a black box for encryption
pub struct Cipher {
key: Vec<u8>,
mode: aes::Mode
}
impl Cipher {
fn new(data: &Vec<u8>, mode: aes::Mode) -> Result<Self, err::Error> {
Ok(CipherBox {
key: try!(key::random(mode.blocksize)),
data: data.clone(),
mode: mode
})
}
fn encrypt(&self, data: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
aes::encrypt(&data, &self.key, &self.mode)
}
fn decrypt(&self, data: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
aes::decrypt(&data, &self.key, &self.mode)
}
}
|
// Copyright (c) 2020.
// ALL Rights reserved.
// @Description def.go
// @Author moxiao
// @Date 2020/11/21 18:19
package baidu
type MGAi struct {
AppId string
AppKey string
AppSecurity string
Cuid string
}
|
export class AddressModel {
id?: number;
street_name: string;
street_number: number;
unit_number: number;
city: string;
province: string;
postal_code: string;
country: string;
}
|
import React from 'react'
import { View, Linking } from 'react-native'
import { WebView, WebViewNavigation } from 'react-native-webview'
import Logic, { State, Event, Props } from './logic'
import { StatefulUIElement } from 'src/ui/types'
import ActionBar from '../../components/action-bar'
import ReaderWebView from '../../components/web-view'
import ErrorView from '../../components/error-view'
import styles from './styles'
import LoadingBalls from 'src/ui/components/loading-balls'
import { RemoteFnName } from 'src/features/reader/utils/remote-functions'
import { Message as WebViewMessage, Anchor } from 'src/content-script/types'
export default class Reader extends StatefulUIElement<Props, State, Event> {
constructor(props: Props) {
super(props, new Logic(props))
}
private scrollTimeout: number = 0
private webView!: WebView
componentWillUnmount() {
super.componentWillUnmount()
clearTimeout(this.scrollTimeout)
}
private constructJsRemoteFnCall = (
fnName: RemoteFnName,
arg?: any,
): string => {
const serializedArg = JSON.stringify(arg)
return !arg
? `window['remoteFnEvents'].emit('${fnName}'); true;`
: `window['remoteFnEvents'].emit('${fnName}', ${serializedArg}); true;`
}
private runFnInWebView = (fnName: RemoteFnName, arg?: any) =>
this.webView.injectJavaScript(this.constructJsRemoteFnCall(fnName, arg))
private handleWebViewMessageReceived = (serialized: string) => {
let message: WebViewMessage
try {
message = JSON.parse(serialized)
} catch (err) {
throw new Error(
`Received malformed message from WebView: ${serialized}`,
)
}
switch (message.type) {
case 'selection':
return this.processEvent('setTextSelection', {
text: message.payload,
})
case 'highlight':
return this.processEvent('createHighlight', {
anchor: message.payload,
renderHighlight: h =>
this.runFnInWebView('renderHighlight', h),
})
case 'annotation':
return this.processEvent('createAnnotation', {
anchor: message.payload,
renderHighlight: h =>
this.runFnInWebView('renderHighlight', h),
})
case 'highlightClicked':
return this.processEvent('editHighlight', {
highlightUrl: message.payload,
})
default:
console.warn(
'Unsupported message received from WebView:',
message,
)
}
}
private handleNavStateChange = (event: WebViewNavigation) => {
switch (event.navigationType) {
case 'click':
return this.handleOpenLinksInBrowser(event.url)
case 'backforward':
case 'formresubmit':
case 'formsubmit':
case 'reload':
return this.webView.stopLoading()
default:
}
}
private handleOpenLinksInBrowser(url: string) {
if (Logic.formUrl(url) === this.state.url) {
return
}
this.webView.stopLoading()
return Linking.openURL(url)
}
private generateInitialJSToInject() {
const renderHighlightsCall = this.constructJsRemoteFnCall(
'renderHighlights',
this.state.highlights,
)
// TODO: We only need to inject `this.state.contentScriptSource` if full webpage mode -
// else we include it with the HTML we pass to the WebView for rendering.
return `${this.state.contentScriptSource}; ${renderHighlightsCall}`
}
private renderLoading = () => (
<View style={[styles.webView, styles.webViewLoader]}>
<LoadingBalls />
</View>
)
private renderWebView() {
if (this.state.loadState === 'running') {
return this.renderLoading()
}
if (this.state.error) {
return (
<ErrorView
url={this.state.url}
message={this.state.error.message}
alreadyReported={this.state.isErrorReported}
className={[styles.webView, styles.container]}
onErrorReport={() => this.processEvent('reportError', null)}
/>
)
}
return (
<ReaderWebView
url={this.state.url}
setRef={ref => (this.webView = ref)}
className={styles.webView}
onMessage={this.handleWebViewMessageReceived}
htmlSource={this.state.htmlSource!}
injectedJavaScript={this.generateInitialJSToInject()}
onNavigationStateChange={this.handleNavStateChange}
startInLoadingState
renderLoading={this.renderLoading}
// This flag needs to be set to afford text selection on iOS.
// https://github.com/react-native-community/react-native-webview/issues/1275
allowsLinkPreview
/>
)
}
render() {
return (
<View style={styles.container}>
{this.renderWebView()}
<ActionBar
className={styles.actionBar}
isErrorView={this.state.error != null}
{...this.state}
onBackBtnPress={() => this.processEvent('goBack', null)}
onHighlightBtnPress={() =>
this.runFnInWebView('createHighlight')
}
onAnnotateBtnPress={() =>
this.runFnInWebView('createAnnotation')
}
onBookmarkBtnPress={() =>
this.processEvent('toggleBookmark', null)
}
onListBtnPress={() =>
this.processEvent('navToPageEditor', {
mode: 'collections',
})
}
onCommentBtnPress={() =>
this.processEvent('navToPageEditor', { mode: 'notes' })
}
onTagBtnPress={() =>
this.processEvent('navToPageEditor', { mode: 'tags' })
}
/>
</View>
)
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/password_bubble_experiment.h"
#include <ostream>
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/testing_pref_service.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/sync/base/model_type.h"
#include "components/sync/driver/test_sync_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace password_bubble_experiment {
namespace {
enum class CustomPassphraseState { NONE, SET };
} // namespace
class PasswordManagerPasswordBubbleExperimentTest : public testing::Test {
public:
PasswordManagerPasswordBubbleExperimentTest() {
RegisterPrefs(pref_service_.registry());
signin::IdentityManager::RegisterProfilePrefs(pref_service_.registry());
}
PrefService* prefs() { return &pref_service_; }
syncer::TestSyncService* sync_service() { return &fake_sync_service_; }
protected:
void SetupFakeSyncServiceForTestCase(syncer::ModelType type,
CustomPassphraseState passphrase_state) {
sync_service()->SetPreferredDataTypes({type});
sync_service()->SetActiveDataTypes({type});
sync_service()->SetIsUsingSecondaryPassphrase(passphrase_state ==
CustomPassphraseState::SET);
}
private:
syncer::TestSyncService fake_sync_service_;
TestingPrefServiceSimple pref_service_;
};
TEST_F(PasswordManagerPasswordBubbleExperimentTest,
ShouldShowChromeSignInPasswordPromo) {
// By default the promo is off.
EXPECT_FALSE(ShouldShowChromeSignInPasswordPromo(prefs(), nullptr));
constexpr struct {
bool account_storage_enabled;
bool was_already_clicked;
bool is_sync_allowed;
bool is_first_setup_complete;
bool is_signin_allowed;
int current_shown_count;
bool result;
} kTestData[] = {
{false, false, true, false, true, 0, true},
{true, false, true, false, true, 0, false},
{false, false, true, false, true, 5, false},
{false, true, true, false, true, 0, false},
{false, true, true, false, true, 10, false},
{false, false, false, false, true, 0, false},
{false, false, true, true, true, 0, false},
{false, false, true, false, false, 0, false},
};
for (const auto& test_case : kTestData) {
SCOPED_TRACE(testing::Message("#test_case = ") << (&test_case - kTestData));
base::test::ScopedFeatureList account_storage_feature;
account_storage_feature.InitWithFeatureState(
password_manager::features::kEnablePasswordsAccountStorage,
test_case.account_storage_enabled);
prefs()->SetBoolean(password_manager::prefs::kWasSignInPasswordPromoClicked,
test_case.was_already_clicked);
prefs()->SetInteger(
password_manager::prefs::kNumberSignInPasswordPromoShown,
test_case.current_shown_count);
sync_service()->SetDisableReasons(
test_case.is_sync_allowed
? syncer::SyncService::DisableReasonSet()
: syncer::SyncService::DISABLE_REASON_PLATFORM_OVERRIDE);
sync_service()->SetFirstSetupComplete(test_case.is_first_setup_complete);
sync_service()->SetTransportState(
test_case.is_first_setup_complete
? syncer::SyncService::TransportState::ACTIVE
: syncer::SyncService::TransportState::
PENDING_DESIRED_CONFIGURATION);
prefs()->SetBoolean(prefs::kSigninAllowed, test_case.is_signin_allowed);
#if defined(OS_CHROMEOS)
EXPECT_FALSE(ShouldShowChromeSignInPasswordPromo(prefs(), sync_service()));
#else
EXPECT_EQ(test_case.result,
ShouldShowChromeSignInPasswordPromo(prefs(), sync_service()));
#endif
}
}
#if !defined(OS_CHROMEOS)
TEST_F(PasswordManagerPasswordBubbleExperimentTest, ReviveSignInPasswordPromo) {
// If kEnablePasswordsAccountStorage is enabled, then the password manager
// bubble never shows Sync promos, so this test doesn't apply.
if (base::FeatureList::IsEnabled(
password_manager::features::kEnablePasswordsAccountStorage)) {
return;
}
sync_service()->SetDisableReasons(syncer::SyncService::DisableReasonSet());
sync_service()->SetFirstSetupComplete(false);
sync_service()->SetTransportState(
syncer::SyncService::TransportState::PENDING_DESIRED_CONFIGURATION);
prefs()->SetBoolean(password_manager::prefs::kWasSignInPasswordPromoClicked,
true);
prefs()->SetInteger(password_manager::prefs::kNumberSignInPasswordPromoShown,
10);
// The state is to be reset.
EXPECT_TRUE(ShouldShowChromeSignInPasswordPromo(prefs(), sync_service()));
}
#endif
TEST_F(PasswordManagerPasswordBubbleExperimentTest, IsSmartLockUser) {
constexpr struct {
syncer::ModelType type;
CustomPassphraseState passphrase_state;
bool expected_sync_user;
} kTestData[] = {
{syncer::ModelType::BOOKMARKS, CustomPassphraseState::NONE, false},
{syncer::ModelType::BOOKMARKS, CustomPassphraseState::SET, false},
{syncer::ModelType::PASSWORDS, CustomPassphraseState::NONE, true},
{syncer::ModelType::PASSWORDS, CustomPassphraseState::SET, true},
};
for (const auto& test_case : kTestData) {
SCOPED_TRACE(testing::Message("#test_case = ") << (&test_case - kTestData));
SetupFakeSyncServiceForTestCase(test_case.type, test_case.passphrase_state);
EXPECT_EQ(test_case.expected_sync_user, IsSmartLockUser(sync_service()));
}
}
} // namespace password_bubble_experiment
|
# TODO: Need to fix naming conflict with the other playwright gem. Bundler is getting confused.
module Playwright
class Cli < Play
class Publish < Play
attr_reader :directories
NO_PLAY_NAME_MSG = "What play would you like to publish?".freeze
NO_GIT_REMOTE_MSG = "You need to set a git remote to publish!".freeze
set_service_url "http://localhost:3000"
set_service_resource "plays"
map_params :play_name
validate proc { !params.play_name },
NO_PLAY_NAME_MSG
validate proc { !github_url },
NO_GIT_REMOTE_MSG
def before_validation
@directories = DirectoryBuilder.new(params.play_name)
end
def run
service.post(
name: name,
github_clone_ssh_url: github_url
).success do |resp, status|
puts "#{params.play_name.capitalize} published successfully!"
end.failure do |resp, status|
puts "Publishing #{params.play_name} failed!"
end
end
def name
@name ||= params.play_name || File.basename(Dir.pwd)
end
def github_url
@github_url ||= git_remotes['origin']
end
def git_remotes
`cd #{directories.play_body_filepath} && git remote -v`.split("\n").map do |remote|
remote.gsub(" (fetch)", '')
.gsub(" (push)", '')
.split("\t")
end.to_h
end
end
end
end |
const $body = document.body
const $scr = document.scrollingElement || document.documentElement
let scrollTop: number
const helpers = {
afterOpen() {
scrollTop = $scr.scrollTop // 获取页面滚动距离
const { style } = $body
style.position = 'fixed' // 添加样式会回到顶部(fixed布局)
style.width = '100%'
style.top = `${-scrollTop}px` // 设置对应位置
},
beforeClose() {
const { style } = $body
style.position = '' // 去掉样式,又会回到顶部
style.width = ''
style.top = ''
// scrollTop lost after set position:fixed, restore it back.
$scr.scrollTop = scrollTop // 滚回对应位置
},
}
export default helpers
|
//go:build !no_udp_backend && !no_backends
// +build !no_udp_backend,!no_backends
package backends
import (
"context"
"fmt"
"net"
"sync"
"time"
"github.com/ansible/receptor/pkg/logger"
"github.com/ansible/receptor/pkg/netceptor"
"github.com/ansible/receptor/pkg/utils"
"github.com/ghjm/cmdline"
)
// UDPMaxPacketLen is the maximum size of a message that can be sent over UDP.
const UDPMaxPacketLen = 65507
// UDPDialer implements Backend for outbound UDP.
type UDPDialer struct {
address string
redial bool
}
// NewUDPDialer instantiates a new UDPDialer backend.
func NewUDPDialer(address string, redial bool) (*UDPDialer, error) {
_, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return nil, err
}
nd := UDPDialer{
address: address,
redial: redial,
}
return &nd, nil
}
// Start runs the given session function over this backend service.
func (b *UDPDialer) Start(ctx context.Context, wg *sync.WaitGroup) (chan netceptor.BackendSession, error) {
return dialerSession(ctx, wg, b.redial, 5*time.Second,
func(closeChan chan struct{}) (netceptor.BackendSession, error) {
dialer := net.Dialer{}
conn, err := dialer.DialContext(ctx, "udp", b.address)
if err != nil {
return nil, err
}
udpconn, ok := conn.(*net.UDPConn)
if !ok {
return nil, fmt.Errorf("DialContext returned a non-UDP connection")
}
ns := &UDPDialerSession{
conn: udpconn,
closeChan: closeChan,
closeChanCloser: sync.Once{},
}
return ns, nil
})
}
// UDPDialerSession implements BackendSession for UDPDialer.
type UDPDialerSession struct {
conn *net.UDPConn
closeChan chan struct{}
closeChanCloser sync.Once
}
// Send sends data over the session.
func (ns *UDPDialerSession) Send(data []byte) error {
if len(data) > UDPMaxPacketLen {
return fmt.Errorf("data too large")
}
n, err := ns.conn.Write(data)
if err != nil {
return err
}
if n != len(data) {
return fmt.Errorf("partial data sent")
}
return nil
}
// Recv receives data via the session.
func (ns *UDPDialerSession) Recv(timeout time.Duration) ([]byte, error) {
err := ns.conn.SetReadDeadline(time.Now().Add(timeout))
if err != nil {
return nil, err
}
buf := make([]byte, utils.NormalBufferSize)
n, err := ns.conn.Read(buf)
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
return nil, netceptor.ErrTimeout
}
if err != nil {
return nil, err
}
return buf[:n], nil
}
// Close closes the session.
func (ns *UDPDialerSession) Close() error {
if ns.closeChan != nil {
ns.closeChanCloser.Do(func() {
close(ns.closeChan)
ns.closeChan = nil
})
}
return ns.conn.Close()
}
// UDPListener implements Backend for inbound UDP.
type UDPListener struct {
laddr *net.UDPAddr
conn *net.UDPConn
sessChan chan *UDPListenerSession
sessRegLock sync.RWMutex
sessionRegistry map[string]*UDPListenerSession
}
// NewUDPListener instantiates a new UDPListener backend.
func NewUDPListener(address string) (*UDPListener, error) {
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return nil, err
}
uc, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, err
}
ul := UDPListener{
laddr: addr,
conn: uc,
sessChan: make(chan *UDPListenerSession),
sessRegLock: sync.RWMutex{},
sessionRegistry: make(map[string]*UDPListenerSession),
}
return &ul, nil
}
// LocalAddr returns the local address the listener is listening on.
func (b *UDPListener) LocalAddr() net.Addr {
if b.conn == nil {
return nil
}
return b.conn.LocalAddr()
}
// Start runs the given session function over the UDPListener backend.
func (b *UDPListener) Start(ctx context.Context, wg *sync.WaitGroup) (chan netceptor.BackendSession, error) {
sessChan := make(chan netceptor.BackendSession)
wg.Add(1)
go func() {
defer wg.Done()
buf := make([]byte, utils.NormalBufferSize)
for {
select {
case <-ctx.Done():
_ = b.conn.Close()
return
default:
}
err := b.conn.SetReadDeadline(time.Now().Add(1 * time.Second))
if err != nil {
logger.Error("Error setting UDP timeout: %s\n", err)
return
}
n, addr, err := b.conn.ReadFromUDP(buf)
if ne, ok := err.(net.Error); ok && ne.Timeout() {
continue
}
if err != nil {
logger.Error("UDP read error: %s\n", err)
return
}
data := make([]byte, n)
copy(data, buf)
addrStr := addr.String()
b.sessRegLock.RLock()
sess, ok := b.sessionRegistry[addrStr]
b.sessRegLock.RUnlock()
if !ok {
b.sessRegLock.Lock()
sess = &UDPListenerSession{
li: b,
raddr: addr,
recvChan: make(chan []byte),
}
b.sessionRegistry[addrStr] = sess
b.sessRegLock.Unlock()
select {
case <-ctx.Done():
_ = b.conn.Close()
return
case sessChan <- sess:
}
}
select {
case <-ctx.Done():
_ = b.conn.Close()
return
case sess.recvChan <- data:
}
}
}()
if b.conn != nil {
logger.Debug("Listening on UDP %s\n", b.LocalAddr().String())
}
return sessChan, nil
}
// UDPListenerSession implements BackendSession for UDPListener.
type UDPListenerSession struct {
li *UDPListener
raddr *net.UDPAddr
recvChan chan []byte
}
// Send sends data over the session.
func (ns *UDPListenerSession) Send(data []byte) error {
n, err := ns.li.conn.WriteToUDP(data, ns.raddr)
if err != nil {
return err
} else if n != len(data) {
return fmt.Errorf("partial data sent")
}
return nil
}
// Recv receives data from the session.
func (ns *UDPListenerSession) Recv(timeout time.Duration) ([]byte, error) {
select {
case data := <-ns.recvChan:
return data, nil
case <-time.After(timeout):
return nil, netceptor.ErrTimeout
}
}
// Close closes the session.
func (ns *UDPListenerSession) Close() error {
ns.li.sessRegLock.Lock()
defer ns.li.sessRegLock.Unlock()
delete(ns.li.sessionRegistry, ns.raddr.String())
return nil
}
// **************************************************************************
// Command line
// **************************************************************************
// udpListenerCfg is the cmdline configuration object for a UDP listener.
type udpListenerCfg struct {
BindAddr string `description:"Local address to bind to" default:"0.0.0.0"`
Port int `description:"Local UDP port to listen on" barevalue:"yes" required:"yes"`
Cost float64 `description:"Connection cost (weight)" default:"1.0"`
NodeCost map[string]float64 `description:"Per-node costs"`
AllowedPeers []string `description:"Peer node IDs to allow via this connection"`
}
// Prepare verifies the parameters are correct.
func (cfg udpListenerCfg) Prepare() error {
if cfg.Cost <= 0.0 {
return fmt.Errorf("connection cost must be positive")
}
for node, cost := range cfg.NodeCost {
if cost <= 0.0 {
return fmt.Errorf("connection cost must be positive for %s", node)
}
}
return nil
}
// Run runs the action.
func (cfg udpListenerCfg) Run() error {
address := fmt.Sprintf("%s:%d", cfg.BindAddr, cfg.Port)
b, err := NewUDPListener(address)
if err != nil {
logger.Error("Error creating listener %s: %s\n", address, err)
return err
}
err = netceptor.MainInstance.AddBackend(b,
netceptor.BackendConnectionCost(cfg.Cost),
netceptor.BackendNodeCost(cfg.NodeCost),
netceptor.BackendAllowedPeers(cfg.AllowedPeers))
if err != nil {
logger.Error("Error creating backend for %s: %s\n", address, err)
return err
}
return nil
}
// udpDialerCfg is the cmdline configuration object for a UDP listener.
type udpDialerCfg struct {
Address string `description:"Host:Port to connect to" barevalue:"yes" required:"yes"`
Redial bool `description:"Keep redialing on lost connection" default:"true"`
Cost float64 `description:"Connection cost (weight)" default:"1.0"`
AllowedPeers []string `description:"Peer node IDs to allow via this connection"`
}
// Prepare verifies the parameters are correct.
func (cfg udpDialerCfg) Prepare() error {
if cfg.Cost <= 0.0 {
return fmt.Errorf("connection cost must be positive")
}
return nil
}
// Run runs the action.
func (cfg udpDialerCfg) Run() error {
logger.Debug("Running UDP peer connection %s\n", cfg.Address)
b, err := NewUDPDialer(cfg.Address, cfg.Redial)
if err != nil {
logger.Error("Error creating peer %s: %s\n", cfg.Address, err)
return err
}
err = netceptor.MainInstance.AddBackend(b,
netceptor.BackendConnectionCost(cfg.Cost),
netceptor.BackendAllowedPeers(cfg.AllowedPeers))
if err != nil {
logger.Error("Error creating backend for %s: %s\n", cfg.Address, err)
return err
}
return nil
}
func (cfg udpDialerCfg) PreReload() error {
return cfg.Prepare()
}
func (cfg udpListenerCfg) PreReload() error {
return cfg.Prepare()
}
func (cfg udpDialerCfg) Reload() error {
return cfg.Run()
}
func (cfg udpListenerCfg) Reload() error {
return cfg.Run()
}
func init() {
cmdline.RegisterConfigTypeForApp("receptor-backends",
"UDP-listener", "Run a backend listener on a UDP port", udpListenerCfg{}, cmdline.Section(backendSection))
cmdline.RegisterConfigTypeForApp("receptor-backends",
"UDP-peer", "Make an outbound backend connection to a UDP peer", udpDialerCfg{}, cmdline.Section(backendSection))
}
|
drop table if exists prg.delta_new;
create unlogged table prg.delta_new as
select
pa.lokalnyid,
pa.teryt_msc,
pa.teryt_simc,
coalesce(pa.osm_ulica, pa.teryt_ulica) teryt_ulica,
pa.teryt_ulic,
pa.numerporzadkowy nr,
pa.pna,
pa.gml geom,
pa.nr nr_standaryzowany
from prg.pa_hashed prg
join prg.pa using (lokalnyid)
left join osm_hashed osm
on (prg.hash = osm.hash and st_dwithin(prg.geom, osm.geom, 150))
where osm.hash is null
;
create index if not exists delta_gis_new on prg.delta_new using gist (geom);
cluster prg.delta_new using delta_gis_new;
create index if not exists delta_lokalnyid_new on prg.delta_new using btree (lokalnyid);
analyze prg.delta_new;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.