content
stringlengths 10
4.9M
|
---|
<filename>tests/test_reader.py
import mmap
from pathlib import Path
from par2.packets import Packet
from par2.reader import Par2FileReader, DDPacketPointer
from .conftest import in_sample_dir, SAMPLES_PATH, factory_packet_header
def test_reader_empty_bytes():
""" Make sure it at least works with bytes """
reader = Par2FileReader(b'')
assert len(reader) == 0
def test_reader_par2_file_str(in_sample_dir):
reader = Par2FileReader("testfile.txt.par2")
assert isinstance(reader._read_buffer, mmap.mmap), "File should be memmapped"
assert reader._packet_offsets == [], "File should not be parsed immediately"
assert reader._readable_and_seekable is True, "File should support regular file operations"
assert len(reader) == 4, "Parser should have found the packets. Found offsets: {}".format(reader._packet_offsets)
assert reader._packet_offsets == [0, 92, 224, 724], "Offsets should always be here"
def test_reader_par2_file_str_mmap_closed(in_sample_dir):
""" Similar to above, but this time simulating a mmap being closed """
reader = Par2FileReader("testfile.txt.par2")
assert isinstance(reader._read_buffer, mmap.mmap), "File should be memmapped"
reader._read_buffer.close()
assert len(reader) == 4, "Parser should have found the packets. Found offsets: {}".format(reader._packet_offsets)
assert reader._packet_offsets == [0, 92, 224, 724], "Offsets should always be here"
def test_reader_par2_file_path(in_sample_dir):
""" Similar to above, but just checking input type """
reader = Par2FileReader(SAMPLES_PATH.joinpath("testfile.txt.par2"))
assert len(reader) == 4, "Parser should have found the packets. Found offsets: {}".format(reader._packet_offsets)
def test_reader_par2_open_file(in_sample_dir):
""" Similar to above, but just checking input type """
file = Path("testfile.txt.par2").open('rb')
reader = Par2FileReader(file)
assert len(reader) == 4, "Parser should have found the packets. Found offsets: {}".format(reader._packet_offsets)
def test_pointer_set():
""" Make sure two identical pointers properly de-duplicate """
header = factory_packet_header()
reader0 = Par2FileReader(b'')
reader1 = Par2FileReader(b'')
pointer0 = DDPacketPointer(header, reader0, 0)
pointer1 = DDPacketPointer(header, reader1, 1)
assert pointer0 == pointer1
assert hash(pointer0) == hash(pointer1)
assert len({pointer0, pointer1}) == 1
def test_get_pointers(in_sample_dir):
""" Test getting packet pointers, and that they work """
reader = Par2FileReader("testfile.txt.par2")
pointers = reader.get_pointers()
assert isinstance(pointers, set)
assert len(pointers) == 4
for pointer in pointers:
assert pointer.header.set_id.hex() == "be22b3624317366207908eb8aed92827"
packet = pointer.get()
assert isinstance(packet, Packet)
|
PARIS — French voters face a stark choice on May 7 between retreating into isolationism or taking the lead in shaping a European defense policy to respond to Islamic terrorism, an unstable neighborhood, a resurgent Russia, an uncertain America and a rising China.
France prizes its strategic autonomy but can no longer afford to go it alone as a pocket superpower. That means the two options represented by the finalists in the presidential election — independent centrist Emmanuel Macron and anti-EU nationalist Marine Le Pen — represent a crucial fork in the road when it comes to France's defense and foreign policy.
Macron, the front-runner and most pro-European of the 11 first round contenders, advocates closer European defense integration compatible with NATO as part of a strengthened EU and eurozone. Le Pen wants to pull France out of NATO's military wing, restore border controls, abandon the euro and call a referendum on France’s EU membership, raise protectionist trade barriers and pursue a strictly national defense policy.
If Macron wins, he has a historic opportunity to lead Europe in defense provided he eschews traditional French arrogance toward smaller EU countries and embraces a more comprehensive approach to security that combines "hard security" with diplomacy, development aid, open trade and institution building. He will also need to jettison a half-baked campaign promise to restore a one-month compulsory military service period for all young French people, which would be costly and yield no extra military capability.
The 39-year-old political novice may also have to face down resistance in the high command, political establishment and defense industries to closer EU cooperation on defense policy, arms production and military technology.
France’s security horizon has darkened in the wake of a spate of terrorist attacks on French soil and threats to French citizens and interests abroad.
Over the last decade, France’s political clout in Europe has declined relative to Germany's due to its economic stagnation. In that time, Paris has also engaged in more overseas military operations than any other EU country, including conflicts in Libya, Mali and Syria, NATO and U.N. missions, and numerous covert commando actions. And its armed forces have taken on an expanded role in domestic security in the wake of the 2015 terrorist attacks in Paris.
The "cheese-eating surrender monkeys" — derided by U.S. neo-conservatives after Paris opposed the 2003 invasion of Iraq — have become "the frogs of war," an uninhibited interventionist force and go-to partner for the United States in Africa and the Middle East.
Britain's impending departure from the European Union will soon leave France as the only major military power in the 27-nation union with a U.N. Security Council seat, a nuclear deterrent, NATO membership, battle-hardened forces configured for expeditionary warfare and a full-spectrum defense industry, sustained partly by booming arms exports.
But France’s military activism has taken its toll, over-stretching the armed forces and their equipment, and prompting critical questions about strategic priorities. Paris is also feeling the pressure for greater defense spending and more military and armaments cooperation with European allies and NATO partners.
The next occupant of the Élysée Palace will inherit tough security choices and limited resources.
On top of long-term risks related to climate change, migration and the instability of an incomplete eurozone, France’s security horizon has darkened in the wake of a spate of terrorist attacks on French soil — most recently on Paris’ Champs-Élysées last week — and threats to French citizens and interests abroad inspired by jihadi groups with bases in Syria, Iraq, Libya and the Sahel.
The advent of an "America first" U.S. president has cast doubt on the U.S.' strategic guarantee for Europe and on its historic support for the EU and for open trade, raising the possibility that Europe will be left in the lurch when it counts.
Brexit, meanwhile, has thrown the future of France’s most important bilateral defense partnership in Europe into uncertainty. Even as both countries have vowed to continue cooperation, whether the U.K. will stick to its commitments remains to be seen. And Russian President Vladimir Putin's annexation of Crimea, destabilization of Ukraine, military buildup and provocations, and suspected use of cyberattacks to undermine Western democracies also loom large.
Due to both geography and demography, the most urgent threat in French eyes is overwhelmingly seen as the nexus between radicalized, poorly integrated young Muslims in France, mostly of immigrant background, and the rise of jihadi groups in the Middle East and Africa.
For Paris, the priority will be to build up intelligence, cybersecurity, specialized internal security units and rapidly deployable combined arms special forces rather than large conventional armed forces.
But France's ambition to remain a global power also dictates continued investment in naval forces, satellites and the nuclear deterrent, on which there is a virtual national consensus among parties, aside from the far left.
The next president has four main options to address these challenges.
The cavalier seul (lone ranger) model would see France do as much as it can on its own, militarily and industrially. It would try to retain a full-spectrum technological and industrial capacity since most European partners don't share its strategic priorities or appetite for expeditionary warfare. But with a defense budget of €32.7 billion or 1.79 percent of GDP, excluding pensions, it’s unlikely the country can afford to go it alone.
Alternatively, France could give top priority to creating an EU defense capability that takes action where NATO chooses not to engage. French support for a permanent structured defense cooperation in an EU framework could finally give the idea — which would include a European defense fund and operating out of a joint EU headquarters — lift-off, but could be difficult to sell to an increasingly Euroskeptic public in France and Europe more widely.
A variation on this option is European bilateralism, whereby France gives priority to bilateral or trilateral defense cooperation with major European partners outside the EU framework. It would build military and industrial ties with key allies such as Britain, Germany, Italy, Spain and if possible Poland, maximizing French power and leverage while avoiding EU procedural obstacles and bureaucracy.
The often-floated idea of building up a “European pillar” of NATO might avoid duplicating military headquarters and staff and has the benefit of relying on a trusted framework with common standards that binds the U.S. to European security — but given enduring Gaullist resentment of U.S. hegemony, Paris is unlikely to go for it.
Le Pen has made clear she aims for option No. 1 — going it alone. She wants to jettison NATO, unravel the EU and seek closer strategic cooperation with Russia. She vows to raise defense spending to 2 percent of GDP immediately and to 3 percent by the end of her term. But it is not remotely clear how she would find the extra money, especially given the likely damage her isolationist economic policies would have on the French economy.
Macron may not have a free hand in parliament and will likely face heavy opposition to giving EU institutions a greater role.
Macron has pledged to raise defense spending gradually to 2 percent of GDP by 2025, a slower rate of increase than experts say is required. He advocates deeper European defense cooperation to supplement NATO's role and share the financial burden. But he may not have a free hand in parliament and will likely face heavy opposition to giving EU institutions a greater role in an area traditionally core to national sovereignty.
If elected, he should give priority to developing a long-term defense program with Germany, open to other partners including Britain if it wishes, with a timetable for key capability improvements such as more airlift, air-to-air refueling planes and reconnaissance drones, and a commitment to developing future systems such as fighter planes and aircraft carriers jointly in Europe.
Such an effort will require strategic patience and will only work if it is part of a grand bargain with Berlin to strengthen the eurozone and implement long-overdue economic reforms. Macron should be wary of overpromising on EU defense integration and risk under-delivering on an issue that is key to citizens’ safety — and strikes at the core of voters’ identity at a time when they feel under threat.
Paul Taylor writes POLITICO's Europe at Large.
This article is based on a report "Crunch Time — France and the future of European defense," published by the Friends of Europe think tank on April 25. |
package prompt
import (
"errors"
"fmt"
"io/ioutil"
)
func PromptName() string {
return TrimmedLine("Vault name")
}
func GivenOrPromptName(namePrefix string) string {
if namePrefix == "" {
return PromptName()
}
return namePrefix
}
func GivenOrPromptPassword(passwordFile string) (string, error) {
if passwordFile != "" {
return readPasswordFile(passwordFile)
}
return Password("<PASSWORD>"), nil
}
func GivenOrPromptConfirmedPassword(passwordFile string) (string, error) {
if passwordFile != "" {
return readPasswordFile(passwordFile)
}
p := Password("<PASSWORD>")
c := Password("<PASSWORD>")
if p != c {
return "", errors.New("password mismatch")
}
return p, nil
}
func readPasswordFile(passwordFile string) (string, error) {
password, err := ioutil.ReadFile(passwordFile)
if err != nil {
return "", fmt.Errorf("could not read from password file %s: %s", passwordFile, err)
}
return string(password), nil
}
|
/* Accel framework public API for discovering current engine capabilities. */
uint64_t
spdk_accel_get_capabilities(struct spdk_io_channel *ch)
{
struct accel_io_channel *accel_ch = spdk_io_channel_get_ctx(ch);
return accel_ch->engine->capabilities;
} |
// Get the optionally base64 encoded values
@JsonIgnore
public byte[] parseSignature() {
if (this.getSignature().equals("")) {
return Base64.decode(this.getSignature64());
}
return this.getSignature().getBytes(RAW_BYTE_CHARSET);
} |
<reponame>toshism/AmIThere<gh_stars>1-10
package main
import (
"fmt"
"time"
"gocv.io/x/gocv"
)
func capture_image(img *gocv.Mat) {
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
fmt.Println(err)
panic(err)
}
defer webcam.Close()
webcam.Read(img)
}
func am_i_there(img *gocv.Mat) bool {
classifier := gocv.NewCascadeClassifier()
defer classifier.Close()
classifier.Load("/home/tosh/bin/haarcascade_profileface.xml")
rects := classifier.DetectMultiScale(*img)
if len(rects) > 0 {
return true
} else {
return false
}
}
func main() {
img := gocv.NewMat()
defer img.Close()
am_there := "no"
for i := 0; i <= 5; i++ {
capture_image(&img)
if am_i_there(&img) {
am_there = "yes"
break
}
time.Sleep(5 * time.Second)
}
fmt.Print(am_there)
}
|
package main
import (
"flag"
"fmt"
"os"
"strings"
"github.com/fatih/color"
"github.com/syllabix/versioner/commit"
"github.com/syllabix/versioner/tag"
)
func fail(err error) {
color.Red("%+v", err)
os.Exit(1)
}
func scopePrinter(latest, path string) {
args := flag.Args()
v := "HEAD"
n := len(args)
if n > 0 {
v = args[n-1]
}
if v == "HEAD" {
msgs, err := commit.MessagesInRange("HEAD", latest, path)
if err != nil {
fail(err)
}
printScopes(msgs)
} else {
msgs := commitsForVersion(v, path)
printScopes(msgs)
}
}
func commitsForVersion(v, path string) []commit.Message {
prior, err := tag.GetVersionPriorTo(v)
if err != nil {
color.Red("%+v", err)
os.Exit(1)
}
msgs, err := commit.MessagesInRange(v, prior, path)
if err != nil {
color.Red("%+v", err)
os.Exit(1)
}
return msgs
}
func printScopes(msgs []commit.Message) {
scopes := map[string]struct{}{}
var builder strings.Builder
for _, m := range msgs {
if len(m.Scope) < 1 {
continue
}
_, printed := scopes[m.Scope]
if !printed {
builder.WriteString(m.Scope + " ")
}
scopes[m.Scope] = struct{}{}
}
fmt.Println(builder.String())
}
|
package models;
import db.DatabaseRule;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
public class AnimalTest {
@Rule
public DatabaseRule databaseRule = new DatabaseRule();
private Animal newAnimal() {
return new Animal("Lion","Good", "Young");
}
private Animal newAnimal2() {
return new Animal("Wolf","Healthy", "Adult");
}
@Test
public void animal_instantiatesCorrectly_true(){
Animal animal = newAnimal();
assertTrue(animal instanceof Animal);
}
@Test
public void getName_returnAnimalsName(){
Animal animal = newAnimal();
assertEquals("Lion", animal.getName());
}
@Test
public void getHealth_returnAnimalsHealth(){
Animal animal = newAnimal();
assertEquals("Good", animal.getHealth());
}
@Test
public void getAge_returnAnimalsAge(){
Animal animal = newAnimal();
assertEquals("Young", animal.getAge());
}
@Test
public void getStatus_returnAnimalsStatus(){
Animal animal = newAnimal();
assertEquals("Not Endangered", Animal.getDatabaseType());
}
@Test
public void saveAnimal_savedToDb_int(){
Animal animal = newAnimal();
Animal animal1 = newAnimal2();
animal.saveAnimal();
animal1.saveAnimal();
int one = animal.getId();
int two = Animal.getAnimals().get(0).getId();
assertEquals(one, two);
}
@Test
public void find_locateNormalAnimal_Name(){
Animal animal = newAnimal();
animal.saveAnimal();
Animal animal1 = Animal.find(animal.getId());
assertEquals(animal,animal1);
}
} |
// Restores previously saved cursor position, character attribute (graphic rendition),
// character set, and origin mode selection.
// If none were saved, the cursor moves to home position.
void
CEscapeHandler::
escapeDECRC()
{
restoreCursor();
} |
<gh_stars>1-10
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as msRest from "@azure/ms-rest-js";
/**
* Input to create KB.
*/
export interface CreateKbInputDTO {
/**
* List of QNA to be added to the index. Ids are generated by the service and should be omitted.
*/
qnaList?: QnADTO[];
/**
* List of URLs to be added to knowledgebase.
*/
urls?: string[];
/**
* List of files to be added to knowledgebase.
*/
files?: FileDTO[];
}
/**
* An instance of CreateKbInputDTO for add operation
*/
export interface UpdateKbOperationDTOAdd extends CreateKbInputDTO {
}
/**
* PATCH body schema of Delete Operation in UpdateKb
*/
export interface DeleteKbContentsDTO {
/**
* List of Qna Ids to be deleted
*/
ids?: number[];
/**
* List of sources to be deleted from knowledgebase.
*/
sources?: string[];
}
/**
* An instance of DeleteKbContentsDTO for delete Operation
*/
export interface UpdateKbOperationDTODelete extends DeleteKbContentsDTO {
}
/**
* PATCH body schema for Update operation in Update Kb
*/
export interface UpdateKbContentsDTO {
/**
* Friendly name for the knowledgebase.
*/
name?: string;
/**
* List of Q-A (UpdateQnaDTO) to be added to the knowledgebase.
*/
qnaList?: UpdateQnaDTO[];
/**
* List of existing URLs to be refreshed. The content will be extracted again and re-indexed.
*/
urls?: string[];
}
/**
* An instance of UpdateKbContentsDTO for Update Operation
*/
export interface UpdateKbOperationDTOUpdate extends UpdateKbContentsDTO {
}
/**
* Contains list of QnAs to be updated
*/
export interface UpdateKbOperationDTO {
/**
* An instance of CreateKbInputDTO for add operation
*/
add?: UpdateKbOperationDTOAdd;
/**
* An instance of DeleteKbContentsDTO for delete Operation
*/
deleteProperty?: UpdateKbOperationDTODelete;
/**
* An instance of UpdateKbContentsDTO for Update Operation
*/
update?: UpdateKbOperationDTOUpdate;
}
/**
* PATCH Body schema for Update Kb which contains list of questions to be added and deleted
*/
export interface UpdateQuestionsDTO {
/**
* List of questions to be added
*/
add?: string[];
/**
* List of questions to be deleted.
*/
deleteProperty?: string[];
}
/**
* List of questions associated with the answer.
*/
export interface UpdateQnaDTOQuestions extends UpdateQuestionsDTO {
}
/**
* PATCH Body schema to represent list of Metadata to be updated
*/
export interface UpdateMetadataDTO {
/**
* List of Metadata associated with answer to be deleted
*/
deleteProperty?: MetadataDTO[];
/**
* List of metadata associated with answer to be added
*/
add?: MetadataDTO[];
}
/**
* List of metadata associated with the answer to be updated
*/
export interface UpdateQnaDTOMetadata extends UpdateMetadataDTO {
}
/**
* Update Body schema to represent context to be updated
*/
export interface UpdateContextDTO {
/**
* List of prompts associated with qna to be deleted
*/
promptsToDelete?: number[];
/**
* List of prompts to be added to the qna.
*/
promptsToAdd?: PromptDTO[];
/**
* To mark if a prompt is relevant only with a previous question or not.
* true - Do not include this QnA as search result for queries without context
* false - ignores context and includes this QnA in search result
*/
isContextOnly?: boolean;
}
/**
* Context associated with Qna to be updated.
*/
export interface UpdateQnaDTOContext extends UpdateContextDTO {
}
/**
* PATCH Body schema for Update Qna List
*/
export interface UpdateQnaDTO {
/**
* Unique id for the Q-A
*/
id?: number;
/**
* Answer text
*/
answer?: string;
/**
* Source from which Q-A was indexed. eg.
* https://docs.microsoft.com/en-us/azure/cognitive-services/QnAMaker/FAQs
*/
source?: string;
/**
* List of questions associated with the answer.
*/
questions?: UpdateQnaDTOQuestions;
/**
* List of metadata associated with the answer to be updated
*/
metadata?: UpdateQnaDTOMetadata;
/**
* Context associated with Qna to be updated.
*/
context?: UpdateQnaDTOContext;
}
/**
* Name - value pair of metadata.
*/
export interface MetadataDTO {
/**
* Metadata name.
*/
name: string;
/**
* Metadata value.
*/
value: string;
}
/**
* Q-A object.
*/
export interface QnADTO {
/**
* Unique id for the Q-A.
*/
id?: number;
/**
* Answer text
*/
answer: string;
/**
* Source from which Q-A was indexed. eg.
* https://docs.microsoft.com/en-us/azure/cognitive-services/QnAMaker/FAQs
*/
source?: string;
/**
* List of questions associated with the answer.
*/
questions: string[];
/**
* List of metadata associated with the answer.
*/
metadata?: MetadataDTO[];
/**
* Context of a QnA
*/
context?: QnADTOContext;
}
/**
* QnADTO - Either QnaId or QnADTO needs to be present in a PromptDTO object
*/
export interface PromptDTOQna extends QnADTO {
}
/**
* Prompt for an answer.
*/
export interface PromptDTO {
/**
* Index of the prompt - used in ordering of the prompts
*/
displayOrder?: number;
/**
* Qna id corresponding to the prompt - if QnaId is present, QnADTO object is ignored.
*/
qnaId?: number;
/**
* QnADTO - Either QnaId or QnADTO needs to be present in a PromptDTO object
*/
qna?: PromptDTOQna;
/**
* Text displayed to represent a follow up question prompt
*/
displayText?: string;
}
/**
* Context associated with Qna.
*/
export interface ContextDTO {
/**
* To mark if a prompt is relevant only with a previous question or not.
* true - Do not include this QnA as search result for queries without context
* false - ignores context and includes this QnA in search result
*/
isContextOnly?: boolean;
/**
* List of prompts associated with the answer.
*/
prompts?: PromptDTO[];
}
/**
* Context of a QnA
*/
export interface QnADTOContext extends ContextDTO {
}
/**
* DTO to hold details of uploaded files.
*/
export interface FileDTO {
/**
* File name. Supported file types are ".tsv", ".pdf", ".txt", ".docx", ".xlsx".
*/
fileName: string;
/**
* Public URI of the file.
*/
fileUri: string;
}
/**
* List of QnADTO
*/
export interface QnADocumentsDTO {
/**
* List of answers.
*/
qnaDocuments?: QnADTO[];
}
/**
* Post body schema for CreateKb operation.
*/
export interface CreateKbDTO {
/**
* Friendly name for the knowledgebase.
*/
name: string;
/**
* List of Q-A (QnADTO) to be added to the knowledgebase. Q-A Ids are assigned by the service and
* should be omitted.
*/
qnaList?: QnADTO[];
/**
* List of URLs to be used for extracting Q-A.
*/
urls?: string[];
/**
* List of files from which to Extract Q-A.
*/
files?: FileDTO[];
}
/**
* Post body schema for Replace KB operation.
*/
export interface ReplaceKbDTO {
/**
* List of Q-A (QnADTO) to be added to the knowledgebase. Q-A Ids are assigned by the service and
* should be omitted.
*/
qnAList: QnADTO[];
}
/**
* The error object. As per Microsoft One API guidelines -
* https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.
*/
export interface ErrorModel {
/**
* One of a server-defined set of error codes. Possible values include: 'BadArgument',
* 'Forbidden', 'NotFound', 'KbNotFound', 'Unauthorized', 'Unspecified', 'EndpointKeysError',
* 'QuotaExceeded', 'QnaRuntimeError', 'SKULimitExceeded', 'OperationNotFound', 'ServiceError',
* 'ValidationFailure', 'ExtractionFailure'
*/
code: ErrorCodeType;
/**
* A human-readable representation of the error.
*/
message?: string;
/**
* The target of the error.
*/
target?: string;
/**
* An array of details about specific errors that led to this reported error.
*/
details?: ErrorModel[];
/**
* An object containing more specific information than the current object about the error.
*/
innerError?: InnerErrorModel;
}
/**
* The error object.
*/
export interface ErrorResponseError extends ErrorModel {
}
/**
* Error response. As per Microsoft One API guidelines -
* https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.
*/
export interface ErrorResponse {
/**
* The error object.
*/
error?: ErrorResponseError;
}
/**
* An object containing more specific information about the error. As per Microsoft One API
* guidelines -
* https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.
*/
export interface InnerErrorModel {
/**
* A more specific error code than was provided by the containing error.
*/
code?: string;
/**
* An object containing more specific information than the current object about the error.
*/
innerError?: InnerErrorModel;
}
/**
* Record to track long running operation.
*/
export interface Operation {
/**
* Operation state. Possible values include: 'Failed', 'NotStarted', 'Running', 'Succeeded'
*/
operationState?: OperationStateType;
/**
* Timestamp when the operation was created.
*/
createdTimestamp?: string;
/**
* Timestamp when the current state was entered.
*/
lastActionTimestamp?: string;
/**
* Relative URI to the target resource location for completed resources.
*/
resourceLocation?: string;
/**
* User Id
*/
userId?: string;
/**
* Operation Id.
*/
operationId?: string;
/**
* Error details in case of failures.
*/
errorResponse?: ErrorResponse;
}
/**
* Response schema for CreateKb operation.
*/
export interface KnowledgebaseDTO {
/**
* Unique id that identifies a knowledgebase.
*/
id?: string;
/**
* URL host name at which the knowledgebase is hosted.
*/
hostName?: string;
/**
* Time stamp at which the knowledgebase was last accessed (UTC).
*/
lastAccessedTimestamp?: string;
/**
* Time stamp at which the knowledgebase was last modified (UTC).
*/
lastChangedTimestamp?: string;
/**
* Time stamp at which the knowledgebase was last published (UTC).
*/
lastPublishedTimestamp?: string;
/**
* Friendly name of the knowledgebase.
*/
name?: string;
/**
* User who created / owns the knowledgebase.
*/
userId?: string;
/**
* URL sources from which Q-A were extracted and added to the knowledgebase.
*/
urls?: string[];
/**
* Custom sources from which Q-A were extracted or explicitly added to the knowledgebase.
*/
sources?: string[];
}
/**
* Collection of knowledgebases owned by a user.
*/
export interface KnowledgebasesDTO {
/**
* Collection of knowledgebase records.
*/
knowledgebases?: KnowledgebaseDTO[];
}
/**
* Collection of words that are synonyms.
*/
export interface AlterationsDTO {
/**
* Words that are synonymous with each other.
*/
alterations: string[];
}
/**
* Collection of word alterations.
*/
export interface WordAlterationsDTO {
/**
* Collection of word alterations.
*/
wordAlterations: AlterationsDTO[];
}
/**
* Schema for EndpointKeys generate/refresh operations.
*/
export interface EndpointKeysDTO {
/**
* Primary Access Key.
*/
primaryEndpointKey?: string;
/**
* Secondary Access Key.
*/
secondaryEndpointKey?: string;
/**
* Current version of runtime.
*/
installedVersion?: string;
/**
* Latest version of runtime.
*/
lastStableVersion?: string;
}
/**
* Defines headers for GetDetails operation.
*/
export interface OperationsGetDetailsHeaders {
/**
* Indicates how long the client should wait before sending a follow up request. The header will
* be present only if the operation is running or has not started yet.
*/
retryAfter: number;
}
/**
* Defines headers for Update operation.
*/
export interface KnowledgebaseUpdateHeaders {
/**
* Relative URI to the target location of the asynchronous operation. Client should poll this
* resource to get status of the operation.
*/
location: string;
}
/**
* Defines values for KnowledgebaseEnvironmentType.
* Possible values include: 'Prod', 'Test'
* @readonly
* @enum {string}
*/
export type KnowledgebaseEnvironmentType = 'Prod' | 'Test';
/**
* Defines values for ErrorCodeType.
* Possible values include: 'BadArgument', 'Forbidden', 'NotFound', 'KbNotFound', 'Unauthorized',
* 'Unspecified', 'EndpointKeysError', 'QuotaExceeded', 'QnaRuntimeError', 'SKULimitExceeded',
* 'OperationNotFound', 'ServiceError', 'ValidationFailure', 'ExtractionFailure'
* @readonly
* @enum {string}
*/
export type ErrorCodeType = 'BadArgument' | 'Forbidden' | 'NotFound' | 'KbNotFound' | 'Unauthorized' | 'Unspecified' | 'EndpointKeysError' | 'QuotaExceeded' | 'QnaRuntimeError' | 'SKULimitExceeded' | 'OperationNotFound' | 'ServiceError' | 'ValidationFailure' | 'ExtractionFailure';
/**
* Defines values for OperationStateType.
* Possible values include: 'Failed', 'NotStarted', 'Running', 'Succeeded'
* @readonly
* @enum {string}
*/
export type OperationStateType = 'Failed' | 'NotStarted' | 'Running' | 'Succeeded';
/**
* Defines values for EnvironmentType.
* Possible values include: 'Prod', 'Test'
* @readonly
* @enum {string}
*/
export type EnvironmentType = 'Prod' | 'Test';
/**
* Contains response data for the getKeys operation.
*/
export type EndpointKeysGetKeysResponse = EndpointKeysDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EndpointKeysDTO;
};
};
/**
* Contains response data for the refreshKeys operation.
*/
export type EndpointKeysRefreshKeysResponse = EndpointKeysDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EndpointKeysDTO;
};
};
/**
* Contains response data for the get operation.
*/
export type AlterationsGetResponse = WordAlterationsDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: WordAlterationsDTO;
};
};
/**
* Contains response data for the listAll operation.
*/
export type KnowledgebaseListAllResponse = KnowledgebasesDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: KnowledgebasesDTO;
};
};
/**
* Contains response data for the getDetails operation.
*/
export type KnowledgebaseGetDetailsResponse = KnowledgebaseDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: KnowledgebaseDTO;
};
};
/**
* Contains response data for the update operation.
*/
export type KnowledgebaseUpdateResponse = Operation & KnowledgebaseUpdateHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: KnowledgebaseUpdateHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Operation;
};
};
/**
* Contains response data for the create operation.
*/
export type KnowledgebaseCreateResponse = Operation & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Operation;
};
};
/**
* Contains response data for the download operation.
*/
export type KnowledgebaseDownloadResponse = QnADocumentsDTO & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: QnADocumentsDTO;
};
};
/**
* Contains response data for the getDetails operation.
*/
export type OperationsGetDetailsResponse = Operation & OperationsGetDetailsHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: OperationsGetDetailsHeaders;
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Operation;
};
};
|
#include<stdio.h>
int main()
{
short int a,b,c,no1=0;
scanf("%hd%hd%hd",&a,&b,&c);
if(a==1)
no1++;
if(b==1)
no1++;
if(c==1)
no1++;
if(no1==3)
printf("3\n");
else if(no1==2)
{
if(b!=1)
printf("%d\n",b+2);
else
printf("%d\n",2*((a==1)?c:a));
}
else if(no1==1)
{
if(b!=1)
printf("%d\n",(b+1)*((a==1)?c:a));
else
printf("%d\n",a*c+(a>c?a:c));
}
else
printf("%d\n",a*b*c);
return 0;
} |
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package model
import (
"github.com/clivern/walrus/core/driver"
)
// Backup type
type Backup struct {
db driver.Database
}
// NewBackupStore creates a new instance
func NewBackupStore(db driver.Database) *Backup {
result := new(Backup)
result.db = db
return result
}
|
<filename>src/main/java/trainer/NullStopWatch.java
package trainer;
/**
* A null object pattern implementation for <tt>SimpleTimerInterface</tt>.
*
* @author <NAME>
*
*/
public class NullStopWatch implements SimpleTimerInterface {
/**
* Does nothing.
*/
@Override
public void start() {}
/**
* Does nothing.
*/
@Override
public void stop() {}
}
|
Comparison of the Application of Different Fluoride Supplements on Enamel Demineralization Adjacent to Orthodontic Brackets: An In Vitro Study
Background: White spot lesion is considered as one of the main problems in the orthodontic treatment. Brackets used in fixed orthodontic treatment create an environment that provides enamel demineralization. Objectives: Theobjectiveof thecurrentstudywastoperformaninvitrostudytocomparedifferentapplicationsof fluoridesupple-mentsonenameldemineralizationadjacenttoorthodonticbracketsandfinallytounderstandthebestsupplementtorecommend the patients. Methods: One hundred and twenty extracted caries-free human premolar teeth were randomly assigned into six groups: group 1: Controlgroup,group2: Fluoridetoothpaste,group3: Fluoridetoothpaste/mouthrinse,group4: Fluoridetoothpaste/vanish,group 5: Fluoridetoothpaste/gelandgroup6: Fluoridetoothpaste/foam. Afterbondingthebracketstotheteeth,thefluoridesupplements were applied based on each group above, except the control group. Then all the specimens were cycled for 30 days in demineralization solution for 8 hours a day, rinsed, placed in artificial saliva for 4 hours a day, brushed (except the control group), and put back to artificial saliva for 12 hours. DIAGNOdent laser fluorescence was used to quantify the demineralization changes. Results: Significantdifferencesexistedbetweenallfluoride-containinggroupsandcontrolgroup. Analysesof theresultsshoweda significantdifferencebetweencontrolgroupandtherest5treatmentgroups(P< 0.001). Othersignificantdifferenceswerebetween groups 2/5, 3/5, 2/4 and 5/6 (P < 0.05). There was no significant difference among the other groups (P > 0.05). Conclusions: Accordingtotheresults,allfluoridesupplementscouldbeusedduringorthodontictreatmenttodecreasetheenamel demineralization. It has been illustrated that fluoride-containing toothpaste and mouth rinse is better than no fluoride treatment but is not effective as well as fluoride gel and varnish.
Background
White spot lesions represent superficial dissolving of enamel of the tooth. Enamel demineralization is the primary stage of tooth decay (1,2). Fixed orthodontic appliances using brackets are one of the reasons of enamel demineralization because the brackets are closely attached to tooth surface and these attachments prevent achieving adequate oral hygiene (3). Enamel demineralization occurs at low pH when the enamel crystals are dissolved by organic acids such as lactic and acetic acid which are produced by plaque and biofilm. The acidogenic bacteria of biofilm can transform fermentable carbohydrates to organic acids (4,5). The buccal surface of teeth is usually the region of bonding of fixed orthodontic appliances and due to inadequate cleansing of this area, it is more sensitive to enamel demineralization (5).
The prevalence of enamel demineralization during orthodontic therapy has been reported about 50% and can be developed only one month after the beginning of the treatment (6)(7)(8).
quantitative comparable data and can detect the mineral loss of enamel before the cavity formation (9).
Enamel demineralization is early decay but can be reversible and fluoride can decrease the white spot lesions (10)(11)(12).
There are some various forms of fluoride now a days.
Objectives
Therefore, the aim of this study was to compare different fluoride therapies including fluoride-containing toothpaste, mouth rinse, varnish, gel and foam during an in vitro study and to find the most effective treatment to recommend the patients.
Methods
In this study 120 extracted caries-free human premolar teeth, which had been extracted for orthodontic reasons were randomly collected from the Department of Oral Surgery, Tabriz Faculty of Dentistry, Iran. The research was reviewed by the Ethics in Research Committee of Medical University of Tabriz, Iran. The collected teeth were kept in 0.1% thymol solution at room temperature. Soft tissue remnants and debris were removed from teeth and they were randomly divided into different 6 groups, of 20 each. Group 1: Control group; without treatment, group 2: Fluoride-containing toothpaste group (Oral-B pro-expert enamel protected toothpaste, Oral-B, USA), group 3: Fluoride-containing toothpaste/mouth rinse group (Oral-B pro-expert multi protection alcohol free mouthwash 0.05% Sodium Fluoride, Oral-B, USA), group 4: Fluoride-containing toothpaste/vanish group (5% Sodium Fluoride Varnish Fluorilaq™, Pascal, USA), group 5: Fluoride-containing toothpaste/gel group (pH7 ® Neutral 2% Sodium Fluoride Fluoride Gel, Pascal, USA) and group 6: Fluoride-containing toothpaste/foam group (PUFF ® , 2.0 % Neutral Sodium Fluoride Non-Aerosol Foam, Pascal, USA). Randomly assignment of the teeth to the groups was performed by using random list numbers. Before bracket bonding, the roots of the teeth from CEJ to apex were mounted in cubes made of self cure polymethyl metaacrilate acrylic resin (PMMA) (Acropars Self-cure, Marlik, Medical Co, Iran) and then were polished with rubber cup and fluoride-free prophylactic paste, then were rinsed and were dried with air. All of the surfaces of teeth except the place of the bracket were covered by a tape. The standard edgewise bracket, slot 0.022 inches for premolars (American Orthodontics, USA) was bonded to the center of buccal surface, 3 mm gingivally from buccal cusp tip. The window on buccal surface was etched with 37% acid phosphoric gel (Dia-Etch, DiaDent, Korea) for 30 seconds and then rinsed and dried. The light cure resin bonding composite (Transbond XT, 3M Unitec, USA) was used for bonding, cured with light cure device (D-Lux, DiaDent, Korea). The intensity of light 1600 mw/cm 2 , its wavelength 450 nm for 10 second. The tape was then removed. The enamel fluorescence was determined beneath the bracket base on gingival surface by DIAGNOdent (KaVo, Germany) prior to fluoride treatments (fluorescence value1: FV1). The teeth were kept in artificial saliva for 16 hours at room temperature. After that the teeth were removed, rinsed, and fluoride supplements were applied based on each group above, except for the control group. The artificial saliva contained of different materials listed in Table 1. Applying fluoride toothpaste involved twice daily brushing for 2 minutes finished by swishing of toothpaste and water for 30 seconds (13). Daily use of 0.05% sodium fluoride mouth rinse in accompany with fluoride toothpaste was the most recommended fluoride regimen by orthodontists (14). Fluoride varnish was applied around brackets with the aid of brush applicators during orthodontic treatment (15). For applying fluoride gel and foam, trays were filled about 1/2 to 1/3 with gel and fully with foam and fluoride therapy came about in 4 minutes (16,17).
Teeth were rinsed again after treatment and put in to the demineralization solution (acetic acid 50 mM, NaH 2 PO 4 , 2H 2 O 2.2 mM, CaCl 2 2.2 mM, KOH 1 M) which has been described by ten Cate and Duijsters, pH 5.0, for 8 hours at room temperature (18).
All of them except the control group were brushed by orthodontic brush (Oral-B orthodontic brush, Oral-B, USA) and fluoride-containing toothpaste (Oral-B proexpert enamel protected toothpaste, Oral-B, USA). The teeth were put back to artificial saliva for 12 hours until the next fluoride therapy. These procedures were repeated every day for 30 days.
The enamel fluorescence was determined after treatment by DIAGNOdent and fluorescence value2 (FV2) was recorded for each tooth of the 6 different groups. The technicians were blind for different groups in this procedure.
∆FV (FV2-FV1) was recorded for each tooth of 6 groups. The mean and standard deviation of ∆FV were calculated for each group (Table 2).
Statistical Analysis
According to Kolmogorov-Smirnov test, the hypothesis of normality of data was rejected. Therefore, One-way ANOVA analysis could not be used in this case. Since P value of levene's test was less than 0.001 and it was concluded that the variance of fluorescence value was not homogeneous in the six groups, therefore non parametric evaluation test (Kruskal Valis) was selected to analysis data pre and post fluoride treatment and the data was analyzed by Mann-Whitney test to compare between groups. The P value < 0.05 was considered as significant difference between heterogeneous groups by SPSS software (version 19).
Results
As the mean and standard deviation of ∆FV for each group has been listed in Table 2, the highest mean was for control group (14.64) and the lowest mean was for fluoridecontaining toothpaste/gel group (group 5 = 4.10).
Discussion
In spite of many improvements in orthodontic techniques, enamel demineralization is still one of the most important challenges of orthodontic therapy. Fixed appliances in orthodontic treatment can increase the incidence of white spot lesions from 73% to 95% (1,19). In another study the prevalence of enamel demineralization before orthodontic therapy was 32% and after that was 74%, 10% of them with cavity (20). According to the study, after demineralization-remineralization cycle ( There are some different mechanisms for enamel demineralization reduction by fluoride therapy in oral cavity; fluoride ions adsorb on the surface of enamel crystals and make a barrier for organic acid dissolving of enamel crystals, therefore, fluoride inhibits enamel demineralization. Fluoride also inhibits the bacterial enzymes which produce organic acids (12,21). Fluoride induces the enamel remineralization by settlement of the Calcium and Phosphate ions of saliva (4,22).
According to the results, fluoride containing toothpaste was significantly better than control group but there was also significant difference between fluoride containing toothpaste group and fluoride containing foam, varnish and gel (P < 0.05). This difference might be caused by these complicated cumulative components of calcium phosphate and fluoride ions of these products. Fluoride containing foam, varnish and gel can be saturated on teeth and lead to enamel demineralization suppression.
In an in vitro study that demineralization had been created by lactate and acetate buffer. The enamel demineralization had been reduced by fluoride treatment which was analyzed by energy dispersive X-ray (23).
Fluorides containing mouthrinse and toothpaste have been recommended by many orthodontists to reduce enamel demineralization during orthodontic therapy. In this research, enamel demineralization was decreased by Iran J Ortho. 2019; 14(1):e64157. fluoride containing mouthrinse and toothpaste but there was no significant difference between fluoride containing mouthrinse and toothpaste group and fluoride containing toothpaste group (P > 0.05). Similar result was observed in Geiger et al. study which they found no significant difference between fluoride containing mouthrinse and toothpaste against WSL in orthodontic patients (24).
Fluoride varnish was effective on enamel demineralization reduction, remineralization improvement and caries cure (remission) closed to orthodontic brackets (15,25,26) as well as some similar studies on orthodontic patients (27)(28)(29). According to the results, fluoride varnish was significantly better than control groups (P < 0.05). Fluoride varnish had significantly decreased interproximal enamel demineralization which had been assessed by scanning electron microscopy (SEM) and energy dispersive X-ray (EDS) in an in vitro study (P < 0.05) (30). In an in situ observation of enamel demineralization by SEM and EDS, titanium tetrafluoride varnish could significantly decrease enamel demineralization (P < 0.05) (31). Fluoride varnish has a sticky potential on teeth, therefore calcium fluoride precipitate as a source of fluoride ions for low pH plaques.
Combination of fluoride containing mouthrinse, varnish and gel was more effective on enamel demineralization decreasing in comparison with separate usage of these products (32). In this research, fluoride varnish and toothpaste group was significantly more effective on enamel demineralization reduction than fluoride containing toothpaste group (P < 0.05) but there was no significant difference among fluoride varnish with fluoride gel and foam groups (P > 0.05). Fluoride gel was significantly better than fluoride containing mouth rinse (P < 0.05). Different density of fluoride gel and mouth rinse and duration of treatment could have caused this difference.
In this study, not only fluoride gel and foam were significantly different with control group (P < 0.05) but also fluoride gel was significantly better than fluoride foam in enamel demineralization reduction (P < 0.05). It could be result of low density and high solubility of foam (17). Therefore, this substance was rinsed easily from dental surface.
In some similar studies fluoride gel affected on enamel demineralization reduction (16,33,34). Fluoride gel and foam was observed effective on remineralization improvement (35).
There were some difficulties during this research, that one of the most important one, was finding suitable premolar teeth for the study which was time consuming. Although, there are some new techniques such as quantitative light fluorescent (QLF) and scanning electron microscopy (SEM) with energy dispersive X-ray (EDS) analysis that can compensate to DIAGNOdent for assessment of enamel demineralization but such equipment didn't exist in Tabriz Faculty of Dentistry, Iran. 4 Iran J Ortho. 2019; 14(1):e64157.
Conclusions
There are some different factors that can cause enamel demineralization in a patient during orthodontic therapy such as diet, oral hygiene, saliva (its flow rate and pH) and microbial factors (4,22,36). In Iran, there is no information of enamel demineralization prevalence during orthodontic therapies but it is proposed that the prevalence is more than the developed countries. According to the results, it is recommended that one of the most effective fluoride supplements -fluoride gel, fluoride varnish and fluoride foam is used as a routine procedure during orthodontic therapy. The final goal of this in vitro study was to find the best solution for the enamel demineralization during orthodontic therapy for patients but it is recommended that it will be completed by an in vivo study to compare the results because the intervals of the fluoride applications are different in real condition. It is also recommended that prior to orthodontic treatment, the susceptibility of the patient is assessed then the most effective fluoride therapy is selected. |
/*
* Creates a new gang by logging on a session to each segDB involved.
*
* elog ERROR or return a non-NULL gang.
*/
Gang *
AllocateGang(PxDispatcherState *ds, GangType type, List *segments)
{
MemoryContext oldContext;
SegmentType segmentType;
Gang *newGang = NULL;
int i;
ELOG_DISPATCHER_DEBUG("AllocateGang begin.");
if (px_role != PX_ROLE_QC)
{
elog(FATAL, "dispatch process called with role %d", px_role);
}
if (segments == NIL)
return NULL;
Assert(px_DispatcherContext);
oldContext = MemoryContextSwitchTo(px_DispatcherContext);
if (type == GANGTYPE_PRIMARY_WRITER)
segmentType = SEGMENTTYPE_EXPLICT_WRITER;
else if (ds->isExtendedQuery)
segmentType = SEGMENTTYPE_EXPLICT_READER;
else
segmentType = SEGMENTTYPE_ANY;
newGang = pxgang_createGang(segments, segmentType);
newGang->allocated = true;
newGang->type = type;
ds->allocatedGangs = lcons(newGang, ds->allocatedGangs);
ds->largestGangSize = Max(ds->largestGangSize, newGang->size);
ELOG_DISPATCHER_DEBUG("AllocateGang end.");
if (type == GANGTYPE_PRIMARY_WRITER)
{
for (i = 0; i < newGang->size; i++)
pxconn_setPXIdentifier(newGang->db_descriptors[i], -1);
}
MemoryContextSwitchTo(oldContext);
return newGang;
} |
<filename>src/com/github/pedron98/bean/LoginUsuarioBean.java
package com.github.pedron98.bean;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.github.pedron98.dao.UsuarioDAO;
import com.github.pedron98.model.Usuario;
@Named
@ViewScoped
public class LoginUsuarioBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Usuario usuario;
@Inject
private UsuarioDAO usuarioDAO;
private String emailUsuario;
public String getEmailUsuario() {
return emailUsuario;
}
public void setEmailUsuario(String emailUsuario) {
this.emailUsuario = emailUsuario;
}
public Usuario getUsuario() {
return usuario;
}
public String login() {
try {
usuario = usuarioDAO.findUsuarioByEmail(emailUsuario);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", usuario);
return "dashboardUsuario?faces-redirect=true";
}
catch(Exception ex) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, ex.getMessage(), ""));
return null;
}
}
}
|
<filename>src/AnimeTable.tsx
import React from "react";
import {addDays, compareAsc, compareDesc, endOfDay, format, startOfDay} from "date-fns";
import LocalizationProvider from "@mui/lab/LocalizationProvider";
import DateAdapter from "@mui/lab/AdapterDateFns";
import jaLocale from "date-fns/locale/ja";
import EditIcon from '@mui/icons-material/Edit';
import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import FormControl from '@mui/material/FormControl';
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import TextField from "@mui/material/TextField";
import {DatePicker} from "@mui/lab";
import "./AnimeTable.css";
import {encode} from "base64-arraybuffer";
export type AllAnimeInfo = Record<string, AnimeInfo>
interface AnimeInfo {
name: string,
start: Date,
first: number,
intervalDays: number,
watched: Set<number>,
}
interface SingleAnimeProps {
number: number,
available: Date,
animeInfo: AnimeInfo,
updateAnimeInfo: (update: Partial<AnimeInfo>) => void,
watched: boolean,
markWatched: (watched: boolean) => void,
delete: () => void,
}
interface SingleAnimeNumber {
type: 'anime',
id: string,
index: number,
available: Date,
info: AnimeInfo,
watched: boolean
}
interface TodayDividerMarker {
type: 'today-marker',
available: Date,
}
interface AnimeTableState {
showAll: boolean,
}
interface AnimeTableProps {
info: AllAnimeInfo,
setInfo: (updater: (old: Readonly<AllAnimeInfo>) => AllAnimeInfo) => void,
}
class AnimeTable extends React.Component<AnimeTableProps, AnimeTableState> {
constructor(props: AnimeTableProps) {
super(props);
this.state = {
showAll: false,
}
}
deleteAnime(id: string) {
this.props.setInfo((old) => {
const newObj = Object.assign({} as AllAnimeInfo, old);
delete newObj[id];
return newObj;
});
}
updateAnimeInfo(id: string, info: Partial<AnimeInfo>) {
this.props.setInfo((old) => {
if (old[id] == null) return old
return {
...old,
[id]: Object.assign(old[id], info),
}
});
}
markWatched(id: string, number: number, watched: boolean) {
this.props.setInfo((old) => {
if (old[id] == null) return old
const animeInfo = old[id];
const alreadyWatched = animeInfo.watched.has(number);
if (watched === alreadyWatched) return old
if (watched)
animeInfo.watched.add(number)
else
animeInfo.watched.delete(number)
return {
...old,
[id]: animeInfo,
}
});
}
static sortAnime(array: { available: Date }[]) {
array.sort((a, b) => compareDesc(a.available, b.available));
}
computeAnimeNumbers(): Record<string, SingleAnimeNumber[]> {
const today = endOfDay(new Date());
const anime = this.props.info;
const result: Record<string, SingleAnimeNumber[]> = Object.create(null)
function computeAvailableDate(index: number, info: AnimeInfo): Date {
return addDays(info.start, index * info.intervalDays);
}
for (let [id, info] of Object.entries(anime)) {
const map = new Map<number, SingleAnimeNumber>();
const theDayNextWillBeReleased = addDays(today, info.intervalDays);
for (const index of info.watched) {
map.set(index, {
id, index, info,
type: "anime",
available: computeAvailableDate(index, info),
watched: true
})
}
const array: SingleAnimeNumber[] = Array.from(map.values());
for (let index = 0; ; index++) {
const available = computeAvailableDate(index, info)
if (index !== 0 && compareAsc(available, theDayNextWillBeReleased) > 0) break;
if (map.has(index)) continue;
array.push({
id, index, info, available,
type: "anime",
watched: false,
})
}
AnimeTable.sortAnime(array);
result[id] = array;
}
return result
}
// AnimeNumbers which one of:
// not watched
// the latest
// the next
// will be returned
computeNotWatchedAnime(): (SingleAnimeNumber | TodayDividerMarker)[] {
const allNumbers = this.computeAnimeNumbers();
const shown: (SingleAnimeNumber | TodayDividerMarker)[] = [];
for (let numbers of Object.values(allNumbers)) {
for (const animeNumber of numbers) {
if (!animeNumber.watched) {
shown.push(animeNumber)
}
}
if (numbers[0]?.watched) shown.push(numbers[0])
if (numbers[1]?.watched) shown.push(numbers[1])
}
shown.push(AnimeTable.todayAnimeMarker());
AnimeTable.sortAnime(shown);
return shown
}
computeAllAnime(): (SingleAnimeNumber | TodayDividerMarker)[] {
const allNumbers = this.computeAnimeNumbers();
const shown: (SingleAnimeNumber | TodayDividerMarker)[] = Object.values(allNumbers).flatMap(it => it);
shown.push(AnimeTable.todayAnimeMarker());
AnimeTable.sortAnime(shown);
return shown
}
private static todayAnimeMarker(): TodayDividerMarker {
const today = endOfDay(new Date());
return {
type: 'today-marker',
available: today,
}
}
addNewAnime() {
// util: random id gen
this.props.setInfo((old) => {
let id: string
do id = randomStr()
while (old[id] != null);
return {
...old,
[id]: {
name: `アニメ${Object.keys(old).length + 1}`,
start: startOfDay(new Date()),
first: 1,
intervalDays: 7,
watched: new Set(),
},
}
});
function randomStr(): string {
return encode(crypto.getRandomValues(new Uint8Array(9)).buffer)
}
}
render() {
console.log(this.props.info);
const allAnimeNumbers = this.state.showAll
? this.computeAllAnime()
: this.computeNotWatchedAnime();
return <>
<LocalizationProvider dateAdapter={DateAdapter} locale={jaLocale}>
<div className={"AnimeTable"}>
<FormControlLabel
control={<Switch
checked={this.state.showAll}
onChange={(_, all) => this.setState({showAll: all})}
/>}
label={"すべて表示"}
/>
<Table size={"small"}>
<TableHead>
<TableRow>
<TableCell/>
<TableCell>アニメ</TableCell>
<TableCell>話数</TableCell>
<TableCell>放送日</TableCell>
<TableCell>視聴済み</TableCell>
</TableRow>
</TableHead>
<TableBody>
{allAnimeNumbers.map(animeNumber => {
if (animeNumber.type === 'today-marker') {
return <TodayDivider key={`today-marker`}/>;
} else {
return <SingleAnime
key={`${animeNumber.id}-${animeNumber.index}`}
number={animeNumber.index + animeNumber.info.first}
available={animeNumber.available}
animeInfo={animeNumber.info}
updateAnimeInfo={this.updateAnimeInfo.bind(this, animeNumber.id)}
watched={animeNumber.watched}
markWatched={this.markWatched.bind(this, animeNumber.id, animeNumber.index)}
delete={this.deleteAnime.bind(this, animeNumber.id)}
/>;
}
})}
</TableBody>
</Table>
<Button onClick={this.addNewAnime.bind(this)}>+</Button>
</div>
</LocalizationProvider>
</>
}
}
function TodayDivider() {
return <TableRow>
<TableCell colSpan={7}>
<div className={"TodayMarker"}>
今日
</div>
</TableCell>
</TableRow>
}
function SingleAnime(props: SingleAnimeProps) {
const [open, setOpen] = React.useState(false);
const [deleteDialog, setDeleteDialog] = React.useState(false);
return <TableRow>
<TableCell className={"EditButton"}>
<Button
className={"MinWidth"}
onClick={() => setOpen(true)}
>
<EditIcon/>
</Button>
</TableCell>
<TableCell>{props.animeInfo.name}</TableCell>
<TableCell>{props.number}話</TableCell>
<TableCell>{format(props.available, "yyyy/MM/dd")}</TableCell>
<TableCell>
<FormControlLabel control={<Checkbox
checked={props.watched}
onChange={(e) => props.markWatched(e.target.checked)}
/>} label={"視聴済み"}/>
</TableCell>
<Dialog open={open}>
<DialogTitle>Edit {props.animeInfo.name}</DialogTitle>
<DialogContent>
<FormControl
sx={{'& > :not(style)': { m: 1, width: '25ch' }}}
>
<TextField
size={"small"}
fullWidth
label={"名前"}
value={props.animeInfo.name}
onChange={(e) =>
props.updateAnimeInfo({name: e.target.value})}
/>
<DatePicker
onChange={(start) => props.updateAnimeInfo({start: start!})}
mask={"____/__/__"}
value={props.animeInfo.start}
renderInput={(params) => <TextField
{...params}
size={"small"}
fullWidth
label={"初回放送日"}
/>}
/>
<TextField
size={"small"}
fullWidth
label={"初回"}
value={props.animeInfo.first}
onChange={(e) =>
props.updateAnimeInfo({first: Number(e.target.value)})}
inputProps={{
inputMode: "numeric",
pattern: "[0-9]*"
}}
/>
<TextField
size={"small"}
fullWidth
label={"隔日"}
value={props.animeInfo.intervalDays}
onChange={(e) =>
props.updateAnimeInfo({intervalDays: Number(e.target.value)})}
inputProps={{
inputMode: "numeric",
pattern: "[0-9]*"
}}
/>
</FormControl>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialog(true)}>
削除
</Button>
<Button onClick={() => setOpen(false)}>
閉じる
</Button>
<Dialog open={deleteDialog}>
<DialogTitle>{props.animeInfo.name}を削除しますか?</DialogTitle>
<DialogActions>
<Button onClick={() => props.delete()}>
削除
</Button>
<Button onClick={() => setOpen(false)}>
キャンセル
</Button>
</DialogActions>
</Dialog>
</DialogActions>
</Dialog>
</TableRow>
}
export default AnimeTable;
|
It seems almost heretical to say it, but could it be that Liverpool's captain Steven Gerrard is not the solution but the problem?
When Steven Gerrard came off the bench against Newcastle United on 30 December and transformed a 1-1 draw into a 3-1 win, the assumption was that, with their talisman back after an ankle injury, Liverpool would kick on. That win took them to fifth and with Chelsea and Arsenal faltering, Newcastle seemingly beginning to feel the effects of their comparatively slender squad and Tottenham being Tottenham, a challenge for Champions League qualification, perhaps even third place, seemed probable.
Liverpool have won only two of their 13 league games since then. Going into Tuesday's game against Blackburn Rovers they lie eighth, level on points with Fulham and Norwich City, the two sides below them, and risk finishing outside the top eight for the first time since they returned to the top flight in 1962. They need 15 points from the six games that remain to avoid their worst points tally in a 20-team Premier League (in 2005, a failure that was mitigated by their European Cup win that year).
A Carling Cup and possible FA Cup, of course, provide some mitigation – and it is actually slightly depressing that league position apparently means so much more than trophies – but it is still reasonable to ask what on earth has gone wrong since the turn of the year. Take a cohesive team, add Gerrard, and the result has been a shambles.
It seems almost heretical to say it, but could it be that Gerrard is not the solution but the problem; that, fine player though he is, he has destroyed the balance of the side? When Gerrard has not started this season, Liverpool have won 48% of games played; when he has started, that drops to 9%.
In the 11 games Gerrard has started, Liverpool have scored an average of 1.00 goal per game while conceding 1.36; without him it is goals for 1.24, goals against 0.90. They have taken 1.67 points per game without him, just 0.73 with. Project that over a season: without Gerrard, Liverpool would get 63 points, which last season would have seen them finish fifth; with Gerrard, they would get 28, certain relegation form.
Those figures include six games in which Gerrard has come off the bench. In two of those, against Everton away in October and against Newcastle, he helped turn draws into wins. In the other four, the result has remained unchanged, although Manchester City did increase a 2-0 lead to 3-0.
It was apparent even under Rafael Benítez that Gerrard was at his best when he could be let off the leash, when the situation was so desperate that he could be released from responsibility and told simply to swash buckles and storm barns all over the pitch – as he did against Olympiakos in December 2004, against Milan in the 2005 European Cup final and against West Ham in the FA Cup final the following year. In that regard, he fitted perfectly the Roy of the Rovers template and, as Scott Murray argued in The Blizzard (a piece reproduced here), there has been no figure so pernicious in English football history as Roy Race.
"While little schemers from Italy dreamt of becoming fantasistas, conducting their team-mates to victory from the centre of the park, while South American youths honed their skills and picked up a few street-smarts in the dusty favelas, hoping to put it all together in a gambeta," he wrote, "thanks to Roy Race, English children spent their formative years sat on their arses being taught a very strange lesson: it doesn't really matter what you do for 89 minutes because a superhero will turn up eventually, welt the ball into the net, and you can all go home with your cups and medals.
"Such was the sermon preached from the Melchester pulpit. In the big games, Rovers were perfectly happy to wing it, knowing Racey would amble along to the rescue at some point. As a result, nobody would bother preparing for anything. More often than not, Melchester would yawn on to the pitch, and end up a goal or two down not long after kick-off. A Race-inspired comeback was nearly always on the cards."
Nobody ever mentions it but in terms of control, Liverpool's best performance in their 2004-05 run in the Champions League was the 0-0 draw at Juventus, where Gerrard was absent and Liverpool's midfield comprised Xabi Alonso, Igor Biscan and Antonio Núñez.
Gerrard's penchant for Hollywood passes and his tactical indiscipline are well-known, but the Opta statistics present a more nuanced picture. Shots on target and shots to goal are virtually unchanged with and without Gerrard while possession (55.22% to 56.50%) and pass completion (80.79% to 81.06%) improve marginally with him in the side.
Cross completion drops from 21.21% to 15.19% when Gerrard comes into the side, while the number of tackles won falls from 75.49% to 71.90%. That latter figure perhaps hints at what he does in terms of disrupting the shape of the midfield. That said, the injury to Lucas Leiva who, remarkably, has still made more tackles than anybody else in the Liverpool squad this season despite having been injured since November, partly accounts for that fall-off and has clearly been a significant factor in Liverpool's stumble.
But what is really telling is the impact Gerrard has on other players. All six of Charlie Adam's assists and both his goals have come when Gerrard has not started. Jordan Henderson's tackle success rate drops from 92.59% when Gerrard does not start to only 63.64% when he does. Jay Spearing wins 60.71% of duels when Gerrard does not start; only 54.76% when he does. When Gerrard is there, they have to adjust to different roles and, so far, that seems to have had a detrimental effect.
The phenomenon of a big player dwarfing those around him, particularly when, as in the case of Henderson and Adam, they are low on confidence, is well-known. The tendency, understandably, is to give the ball to the star, to try to feed him at every opportunity: Cesc Fábregas described it happening at Arsenal in Thierry Henry's last full season, while an overreliance on Samuel Eto'o has clearly hampered Cameroon. Gerrard offers an excuse, an easy way for his team-mates to dodge responsibility.
It is not that he is a bad player, far from it – and Lucas's absence is almost certainly a bigger reason for Liverpool's slide than Gerrard's return – but it could be that his impact is detrimental. That is the problem with building up individuals in football: no matter how gifted he is, it is never just about one man. |
def _validate_workflow(self, stage):
if stage == 'add_source':
if self.validation['add_widget']:
raise WorkflowOrderError('New sources cannot be added after `add_widget` has been called.')
if self.validation['prepare_plot']:
raise WorkflowOrderError('New sources cannot be added after `prepare_plot` has been called.')
if self.validation['add_layer']:
raise WorkflowOrderError('New sources cannot be added after `add_layer` has been called.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.')
if stage == 'add_widget':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before adding a widget.')
if self.validation['prepare_plot']:
raise WorkflowOrderError('New widgets cannot be added after `prepare_plot` has been called.')
if self.validation['add_layer']:
raise WorkflowOrderError('New widgets cannot be added after `add_layer` has been called.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.')
if stage == 'prepare_plot':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before calling `prepare_plot`.')
if self.validation['add_layer']:
raise WorkflowOrderError('Plot cannot be prepared after `add_layer` has been called.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.')
if stage == 'add_layer':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before adding a layer.')
if not self.validation['prepare_plot']:
raise WorkflowOrderError('New layers cannot be added after `prepare_plot` has been called.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.')
if stage == 'render_plot':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before rendering the plot.')
if not self.validation['prepare_plot']:
raise WorkflowOrderError('Method `prepare_plot` must be called before rendering the plot.')
if not self.validation['add_layer']:
raise WorkflowOrderError('Method `add_layer` must be called before rendering the plot.')
if stage == 'add_path':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before adding a path.')
if not self.validation['prepare_plot']:
raise WorkflowOrderError('Method `prepare_plot` must be called before adding a path.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.')
if self.validation['add_widget']:
raise WorkflowOrderError('Plot contains widgets, which are not compatible with paths.')
if stage == 'add_data_table':
if not self.validation['add_source']:
raise WorkflowOrderError('Method `add_source` must be called before adding a data table.')
if not self.validation['prepare_plot']:
raise WorkflowOrderError('Method `prepare_plot` must be called before adding a data table.')
if self.validation['render_plot']:
raise WorkflowOrderError('Method `render_plot` has already been called. Start new workflow.') |
// Copyright 2016 Esption
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ops::Deref;
use std::sync::{Mutex, MutexGuard, RwLock as StdRwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError};
pub struct RoMutex<T> {
m: Mutex<T>
}
pub struct RoMutexGuard<'a, T: 'a> {
g: MutexGuard<'a, T>
}
impl<'a, T> Deref for RoMutexGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
&self.g
}
}
impl<T> RoMutex<T> {
#[inline]
pub fn new(t: T) -> Self {
RoMutex { m: Mutex::new(t) }
}
#[inline]
pub fn from(mutex: Mutex<T>) -> Self {
RoMutex { m: mutex }
}
#[inline]
pub fn read<'a>(&'a self) -> RoMutexGuard<'a, T> {
RoMutexGuard { g: self.m.lock().unwrap_or_else(|e| e.into_inner()) }
}
#[inline]
pub fn try_read<'a>(&'a self) -> Option<RoMutexGuard<'a, T>> {
match self.m.try_lock() {
Ok(val) => Some(RoMutexGuard { g: val }),
Err(err) => match err {
TryLockError::Poisoned(p) => Some(RoMutexGuard { g: p.into_inner() }),
_ => None
}
}
}
}
/// The main reason this RwMutex exists is to wrap poison errors.
/// It's not very useful besides that.
pub struct RwMutex<T> {
m: Mutex<T>
}
impl<T> RwMutex<T> {
#[inline]
pub fn new(t: T) -> Self {
RwMutex { m: Mutex::new(t) }
}
#[inline]
pub fn from(mutex: Mutex<T>) -> Self {
RwMutex { m: mutex }
}
#[inline]
pub fn lock(&self) -> MutexGuard<T> {
self.m.lock().unwrap_or_else(|e| e.into_inner())
}
#[inline]
pub fn try_lock(&self) -> Option<MutexGuard<T>> {
match self.m.try_lock() {
Ok(val) => Some(val),
Err(err) => match err {
TryLockError::Poisoned(p) => Some(p.into_inner()),
_ => None
}
}
}
}
pub struct RoLock<T> {
rwl: StdRwLock<T>
}
impl<T> RoLock<T> {
#[inline]
pub fn new(t: T) -> Self {
RoLock { rwl: StdRwLock::new(t) }
}
#[inline]
pub fn from(rwl: StdRwLock<T>) -> Self {
RoLock { rwl: rwl }
}
#[inline]
pub fn read(&self) -> RwLockReadGuard<T> {
self.rwl.read().unwrap_or_else(|e| e.into_inner())
}
#[inline]
pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
match self.rwl.try_read() {
Ok(val) => Some(val),
Err(err) => match err {
TryLockError::Poisoned(p) => Some(p.into_inner()),
_ => None
}
}
}
}
/// The main reason this RwLock exists is to wrap poison errors.
/// It's not very useful besides that.
pub struct RwLock<T> {
rwl: StdRwLock<T>
}
impl<T> RwLock<T> {
#[inline]
pub fn new(t: T) -> Self {
RwLock { rwl: StdRwLock::new(t) }
}
#[inline]
pub fn from(rwl: StdRwLock<T>) -> Self {
RwLock { rwl: rwl }
}
#[inline]
pub fn read(&self) -> RwLockReadGuard<T> {
self.rwl.read().unwrap_or_else(|e| e.into_inner())
}
#[inline]
pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
match self.rwl.try_read() {
Ok(val) => Some(val),
Err(err) => match err {
TryLockError::Poisoned(p) => Some(p.into_inner()),
_ => None
}
}
}
#[inline]
pub fn write(&self) -> RwLockWriteGuard<T> {
self.rwl.write().unwrap_or_else(|e| e.into_inner())
}
#[inline]
pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
match self.rwl.try_write() {
Ok(val) => Some(val),
Err(err) => match err {
TryLockError::Poisoned(p) => Some(p.into_inner()),
_ => None
}
}
}
}
|
//---------------------------------------------------------------------------//
// Check that the threshold energy can be returned
FRENSIE_UNIT_TEST( MomentPreservingElasticPositronatomicReaction, getThresholdEnergy )
{
FRENSIE_CHECK_EQUAL( mp_elastic_reaction->getThresholdEnergy(),
1.000000000000E-05 );
} |
A Monitoring System for the Safety of Building Structure Based on Semantic Technology
The development of the internet of things provides the basis for monitoring systems used in the building structure monitoring area, and this makes it possible to collect data for the safety of different kinds of building structure. A series of intelligent services can be provided according to these data. This paper proposes a monitoring system for the safety of building structure based on semantic technology. In this system, various sensors which are connected via cable or wireless way, are used to monitor the different parameters of building structure. The semantic data can be obtained and represented in RDF to describe the sensor data, and can provide the application background for users. LarKC, a platform for scalable semantic data processing, is used for semantic querying over the data. Based on this uniform representation of data and semantic processing, intelligent services can be provided by the effective data analysis. This provides the possibility to integrate all of the monitoring systems for the safety of building structure in urban computing. |
def run_data_forecast(self, **kwargs):
request = {
"processinginstructioninfo": {},
"taskInfo": {
"task": {
"taskType": 1,
"initiatedFrom": 2,
"taskFlags": {
"disabled": False
}
},
"appGroup": {},
"subTasks": [
{
"subTaskOperation": 1,
"subTask": {
"subTaskName": "",
"subTaskType": 1,
"operationType": 4004
},
"options": {
"adminOpts": {
"reportOption": {
"showHiddenStoragePolicies": False,
"showGlobalStoragePolicies": False,
"storagePolicyCopyList": [
{
"storagePolicyName": self.storage_policy_name
}
],
"mediaInfoReport": {
"mediaLocIn": True,
"mediaLocOut": True
},
"commonOpt": {
"dateFormat": "mm/dd/yyyy",
"overrideDateTimeFormat": 0,
"reportType": 7738,
"summaryOnly": False,
"reportCustomName": "",
"timeFormat": "hh:mm:ss am/pm",
"onCS": True,
"locale": {
"country": "English",
"language": "UnitedStates",
"localeName": kwargs.get("localeName", "en-us")
},
"outputFormat": {
"outputType": 1,
"isNetworkDrive": False
}
},
"computerSelectionList": {
"includeAll": True
},
"jobSummaryReport": {
"subclientFilter": False
},
"dataRetentionForecastReport": {
"pruneData": True,
"retainedBeyondBasicRet": False,
"forecastDays": 0,
"unPrunableData": True,
"sortByOption": 2
},
"agentList": [
{
"type": 0,
"flags": {
"include": True
}
}
]
}
}
}
}
]
}
}
forecast = self._commcell_object._services['CREATE_TASK']
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', forecast, request)
if flag:
if response.json():
if "jobIds" in response.json():
return Job(self._commcell_object, response.json()['jobIds'][0])
elif "errorCode" in response.json():
error_message = response.json()['errorMessage']
o_str = 'Failed to Run Data Forecast\nError: "{0}"'.format(error_message)
raise SDKException('Storage', '102', o_str)
else:
raise SDKException('Storage', '108')
else:
raise SDKException('Response', '102')
else:
response_string = self._commcell_object._update_response_(response.text)
raise SDKException('Response', '101', response_string) |
////////////////////////////////////////////////////////////////////
// Function: EggNameUniquifier::generate_name
// Access: Public, Virtual
// Description: Generates a new name for the given node when its
// existing name clashes with some other node. This
// function will be called repeatedly, if necessary,
// until it returns a name that actually is unique.
//
// The category is the string returned by
// get_category(), and index is a uniquely-generated
// number that may be useful for synthesizing the name.
////////////////////////////////////////////////////////////////////
string EggNameUniquifier::
generate_name(EggNode *node, const string &category, int index) {
string name = filter_name(node);
ostringstream str;
if (name.empty()) {
str << category << index;
} else {
str << name << "." << category << index;
}
return str.str();
} |
package api
import (
"encoding/json"
"log"
"net/http"
)
// Response implements the standard JSON response payload structure.
type Response struct {
Status string `json:"status"`
Error *ResponseError `json:"error,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
}
// ResponseError implements the standard Error response structure.
type ResponseError struct {
Code int `json:"code"`
Message string `json:"message"`
Details []string `json:"details"`
}
func (e ResponseError) Error() string {
j, err := json.Marshal(e)
if err != nil {
return "ResponseError: " + err.Error()
}
return string(j)
}
// Fail ends an unsuccessful JSON response with the stardard failure format.
func Fail(w http.ResponseWriter, status, errCode int, details ...string) {
msg, ok := frErrMap[errCode]
if !ok {
errCode = status
msg = http.StatusText(status)
}
r := &Response{
Status: StatusFail,
Error: &ResponseError{
Code: errCode,
Message: msg,
Details: details,
},
}
j, err := json.Marshal(r)
if err != nil {
http.Error(
w,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(j)
if err != nil {
log.Printf("couldn't write response: %v", err)
}
}
// Send sends a successful JSON response using the standard success format.
func Send(w http.ResponseWriter, status int, result interface{}) {
rj, err := json.Marshal(result)
if err != nil {
http.Error(
w,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
return
}
r := &Response{
Status: StatusOK,
Result: rj,
}
j, err := json.Marshal(r)
if err != nil {
http.Error(
w,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(j)
if err != nil {
log.Printf("couldn't write response: %v", err)
}
}
// ResponseStatus constants.
const (
StatusOK = "ok"
StatusFail = "nok"
)
// ErrCodes map response body error codes to standard error status messages.
const (
ErrCodeAuto = 0
ErrCodeParameterMismatch = 1
ErrCodeHMACInvalid = 2
ErrCodeOperationNotAllowed = 3
ErrCodeInvalidUserCredentials = 4
ErrCodeInternalServiceError = 666
ErrCodeServiceUnavailable = 667
)
var frErrMap = map[int]string{
ErrCodeParameterMismatch: "Parameter Mismatch",
ErrCodeHMACInvalid: "HMAC is invalid",
ErrCodeOperationNotAllowed: "Operation is not allowed",
ErrCodeInvalidUserCredentials: "Invalid user credentials",
ErrCodeInternalServiceError: "Internal Server Error",
ErrCodeServiceUnavailable: "Service Unavailable",
}
|
/**
* Crea una imagen mediante un vector de estado y la guarda en el directorio
* raiz de nuestro proyecto.
*
* @param EstadoVector //Double[]
* @param name //String
*/
public static void graficarEstado(Double[] EstadoVector, String name) {
try {
DefaultCategoryDataset ds = new DefaultCategoryDataset();
for (int i = 0; i < EstadoVector.length; i++) {
ds.addValue(EstadoVector[i], "Vertice" + Integer.toString(i), "");
}
JFreeChart jf = ChartFactory.createBarChart3D("Estado", "Vertices", "Probabilidad", ds, PlotOrientation.VERTICAL, true, true, true);
ChartFrame f = new ChartFrame("Estados", jf);
f.setSize(1000, 600);
f.setLocationRelativeTo(null);
f.setVisible(false);
ChartUtilities.saveChartAsPNG(new File(name + ".png"), jf, 1000, 600, null);
} catch (Exception e) {
System.out.println("error" + e);
}
} |
/**
* Release references held by this object to allow objects to be
* garbage-collected.
*/
private void clear() {
setValues(null,
null,
null,
null,
null,
null,
null,
null,
null,
null, hreadName
null,
0,
0
);
} |
import React from 'react'
import styled from 'styled-components'
import Link from 'gatsby-link'
import {
flexbox,
space,
layout,
compose,
variant,
position,
SpaceProps,
LayoutProps,
FlexboxProps,
} from 'styled-system'
import Image from 'gatsby-image'
import { colors } from '../../theme/colors'
import { mediaQueries } from '../../theme/mediaQueries'
import { CardProps, CardImageProps, CardContentProps } from './Card.types'
const StyledCardImage = styled(Image)<{ fixed: any }>`
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-height: 100%;
min-width: 100%;
`
const CardImageOverflow = styled.div`
overflow: hidden;
position: relative;
${mediaQueries.md} {
padding-top: 68%;
}
`
const CardImageWrapper = styled.div`
transition: transform 0.15s ease-out;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
`
export const CardImage: React.FC<CardImageProps> = ({ image, ...props }) => (
<CardImageOverflow>
<CardImageWrapper>
<StyledCardImage fixed={image} {...props} />
</CardImageWrapper>
</CardImageOverflow>
)
export const CardTitle = styled.h3`
margin: 0 0 0.5em 0;
font-size: 1.25rem;
line-height: 1.25;
${mediaQueries.md} {
font-size: 1.5rem;
}
${mediaQueries.mdMax} {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
/* Multi-line ellipsis, only works in webkit browsers */
@supports (-webkit-line-clamp: 2) {
overflow: hidden;
text-overflow: ellipsis;
white-space: initial;
/* stylelint-disable */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
/* stylelint-enable */
}
}
`
export const CardContent = styled.div<CardContentProps>`
background-color: ${colors.white};
color: ${colors.darkGrey};
display: flex;
flex-direction: column;
flex-grow: 1;
font-size: 0.875rem;
line-height: 1.3;
padding: 20px;
${compose(space, layout, position)}
`
export const CardFooter = styled.div<SpaceProps & LayoutProps & FlexboxProps>`
display: flex;
margin-top: auto;
${compose(space, layout, flexbox)}
`
export const Card = styled(Link)<CardProps>`
width: 100%;
display: flex;
overflow: hidden;
text-decoration: none;
&:hover,
&:focus {
${CardImageWrapper} {
transform: scale(1.08);
}
}
${variant({
variants: {
column: {
flexDirection: 'column',
[CardImageOverflow]: {
flexBasis: 'auto',
},
[CardContent]: {
minHeight: 0,
flexBasis: 'auto',
flexGrow: 1,
margin: 0,
},
},
row: {
flexDirection: 'row',
[CardImageOverflow]: {
flexBasis: '50%',
},
[CardContent]: {
minHeight: '200px',
flexBasis: 'calc(50% + 60px)',
margin: '25px 0 25px -60px',
zIndex: '1',
},
},
},
})}
`
Card.defaultProps = {
variant: 'column',
}
|
<reponame>seidlr/ipyvuetify
from traitlets import Unicode, List, Dict
from ipywidgets import DOMWidget
from ipywidgets.widgets.widget import widget_serialization
class Events(object):
def __init__(self, **kwargs):
self.on_msg(self._handle_event)
self.events = [item[4:] for item in dir(self) if item.startswith("vue_")]
def _handle_event(self, _, content, buffers):
event = content.get("event", "")
data = content.get("data", {})
getattr(self, 'vue_' + event)(data)
class VuetifyTemplate(DOMWidget, Events):
_model_name = Unicode('VuetifyTemplateModel').tag(sync=True)
_view_name = Unicode('VuetifyTemplateView').tag(sync=True)
_view_module = Unicode('jupyter-vuetify').tag(sync=True)
_model_module = Unicode('jupyter-vuetify').tag(sync=True)
_view_module_version = Unicode('0.1.0').tag(sync=True)
_model_module_version = Unicode('0.1.0').tag(sync=True)
template = Unicode(None, allow_none=True).tag(sync=True)
events = List(Unicode(), default_value=None, allow_none=True).tag(sync=True)
components = Dict(default_value=None, allow_none=True).tag(sync=True, **widget_serialization)
__all__ = ['VuetifyTemplate']
|
<reponame>digideskio/kbfs
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"testing"
"github.com/keybase/client/go/libkb"
keybase1 "github.com/keybase/client/go/protocol"
"github.com/keybase/go-framed-msgpack-rpc"
"golang.org/x/crypto/nacl/box"
"golang.org/x/net/context"
)
type FakeCryptoClient struct {
Local *CryptoLocal
readyChan chan<- struct{}
goChan <-chan struct{}
}
func NewFakeCryptoClient(config Config, signingKey SigningKey,
cryptPrivateKey CryptPrivateKey,
readyChan chan<- struct{},
goChan <-chan struct{}) *FakeCryptoClient {
return &FakeCryptoClient{
Local: NewCryptoLocal(config, signingKey, cryptPrivateKey),
readyChan: readyChan,
goChan: goChan,
}
}
func (fc FakeCryptoClient) maybeWaitOnChannel(ctx context.Context) error {
if fc.readyChan == nil {
return nil
}
// say we're ready, and wait for a signal to proceed or a
// cancellation.
fc.readyChan <- struct{}{}
select {
case <-fc.goChan:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (fc FakeCryptoClient) Call(ctx context.Context, s string, args interface{}, res interface{}) error {
switch s {
case "keybase.1.crypto.signED25519":
if err := fc.maybeWaitOnChannel(ctx); err != nil {
return err
}
arg := args.([]interface{})[0].(keybase1.SignED25519Arg)
sigInfo, err := fc.Local.Sign(context.Background(), arg.Msg)
if err != nil {
return err
}
sigRes := res.(*keybase1.ED25519SignatureInfo)
// Normally, we'd have to validate all the parameters
// in sigInfo, but since this is used in tests only,
// there's no need.
var ed25519Signature keybase1.ED25519Signature
copy(ed25519Signature[:], sigInfo.Signature)
publicKey :=
libkb.KIDToNaclSigningKeyPublic(sigInfo.VerifyingKey.kid.ToBytes())
*sigRes = keybase1.ED25519SignatureInfo{
Sig: ed25519Signature,
PublicKey: keybase1.ED25519PublicKey(*publicKey),
}
return nil
case "keybase.1.crypto.unboxBytes32":
if err := fc.maybeWaitOnChannel(ctx); err != nil {
return err
}
arg := args.([]interface{})[0].(keybase1.UnboxBytes32Arg)
publicKey := MakeTLFEphemeralPublicKey(arg.PeersPublicKey)
encryptedClientHalf := EncryptedTLFCryptKeyClientHalf{
Version: EncryptionSecretbox,
EncryptedData: arg.EncryptedBytes32[:],
Nonce: arg.Nonce[:],
}
clientHalf, err := fc.Local.DecryptTLFCryptKeyClientHalf(
context.Background(), publicKey, encryptedClientHalf)
if err != nil {
return err
}
res := res.(*keybase1.Bytes32)
*res = clientHalf.data
return nil
case "keybase.1.crypto.unboxBytes32Any":
if err := fc.maybeWaitOnChannel(ctx); err != nil {
return err
}
arg := args.([]interface{})[0].(keybase1.UnboxBytes32AnyArg)
keys := make([]EncryptedTLFCryptKeyClientAndEphemeral, 0, len(arg.Bundles))
for _, k := range arg.Bundles {
ePublicKey := MakeTLFEphemeralPublicKey(k.PublicKey)
encryptedClientHalf := EncryptedTLFCryptKeyClientHalf{
Version: EncryptionSecretbox,
EncryptedData: make([]byte, len(k.Ciphertext)),
Nonce: make([]byte, len(k.Nonce)),
}
copy(encryptedClientHalf.EncryptedData, k.Ciphertext[:])
copy(encryptedClientHalf.Nonce, k.Nonce[:])
keys = append(keys, EncryptedTLFCryptKeyClientAndEphemeral{
EPubKey: ePublicKey,
ClientHalf: encryptedClientHalf,
PubKey: MakeCryptPublicKey(k.Kid),
})
}
clientHalf, index, err := fc.Local.DecryptTLFCryptKeyClientHalfAny(
context.Background(), keys, arg.PromptPaper)
if err != nil {
return err
}
res := res.(*keybase1.UnboxAnyRes)
res.Plaintext = clientHalf.data
res.Index = index
res.Kid = keys[index].PubKey.kidContainer.kid
return nil
default:
return fmt.Errorf("Unknown call: %s %v %v", s, args, res)
}
}
func (fc FakeCryptoClient) Notify(_ context.Context, s string, args interface{}) error {
return fmt.Errorf("Unknown notify: %s %v", s, args)
}
func testCryptoClientConfig(t *testing.T) Config {
config := &ConfigLocal{codec: NewCodecMsgpack()}
setTestLogger(config, t)
return config
}
// Test that signing a message and then verifying it works.
func TestCryptoClientSignAndVerify(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
msg := []byte("message")
sigInfo, err := c.Sign(context.Background(), msg)
if err != nil {
t.Fatal(err)
}
err = c.Verify(msg, sigInfo)
if err != nil {
t.Error(err)
}
}
// Test that canceling a signing RPC returns the correct error
func TestCryptoClientSignCanceled(t *testing.T) {
config := testCryptoClientConfig(t)
serverConn, conn := rpc.MakeConnectionForTest(t)
c := newCryptoClientWithClient(config, conn.GetClient())
f := func(ctx context.Context) error {
msg := []byte("message")
_, err := c.Sign(ctx, msg)
return err
}
testRPCWithCanceledContext(t, serverConn, f)
}
// Test that decrypting an TLF crypt key client half encrypted with
// box.Seal works.
func TestCryptoClientDecryptTLFCryptKeyClientHalfBoxSeal(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
var nonce [24]byte
err = cryptoRandRead(nonce[:])
if err != nil {
t.Fatal(err)
}
keypair, err := libkb.ImportKeypairFromKID(cryptPrivateKey.getPublicKey().kid)
if err != nil {
t.Fatal(err)
}
dhKeyPair, ok := keypair.(libkb.NaclDHKeyPair)
if !ok {
t.Fatal(libkb.KeyCannotEncryptError{})
}
encryptedData := box.Seal(nil, clientHalf.data[:], &nonce, (*[32]byte)(&dhKeyPair.Public), (*[32]byte)(&ephPrivateKey.data))
encryptedClientHalf := EncryptedTLFCryptKeyClientHalf{
Version: EncryptionSecretbox,
Nonce: nonce[:],
EncryptedData: encryptedData,
}
decryptedClientHalf, err := c.DecryptTLFCryptKeyClientHalf(
context.Background(), ephPublicKey, encryptedClientHalf)
if err != nil {
t.Fatal(err)
}
if clientHalf != decryptedClientHalf {
t.Error("clientHalf != decryptedClientHalf")
}
}
// Test that decrypting a TLF crypt key client half encrypted with the
// default method (currently nacl/box) works.
func TestCryptoClientDecryptEncryptedTLFCryptKeyClientHalf(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
// See crypto_common_test.go for tests that this actually
// performs encryption.
encryptedClientHalf, err := c.EncryptTLFCryptKeyClientHalf(ephPrivateKey, cryptPrivateKey.getPublicKey(), clientHalf)
if err != nil {
t.Fatal(err)
}
if encryptedClientHalf.Version != EncryptionSecretbox {
t.Fatalf("Unexpected encryption version %d", encryptedClientHalf.Version)
}
decryptedClientHalf, err := c.DecryptTLFCryptKeyClientHalf(
context.Background(), ephPublicKey, encryptedClientHalf)
if err != nil {
t.Fatal(err)
}
if clientHalf != decryptedClientHalf {
t.Error("clientHalf != decryptedClientHalf")
}
}
// Test that attempting to decrypt an empty set of client keys fails.
func TestCryptoClientDecryptEmptyEncryptedTLFCryptKeyClientHalfAny(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
keys := make([]EncryptedTLFCryptKeyClientAndEphemeral, 0, 0)
_, _, err := c.DecryptTLFCryptKeyClientHalfAny(
context.Background(), keys, false)
if _, ok := err.(NoKeysError); !ok {
t.Fatalf("expected NoKeysError. Actual error: %v", err)
}
}
// Test that when decrypting set of client keys, the first working one
// is used to decrypt.
func TestCryptoClientDecryptEncryptedTLFCryptKeyClientHalfAny(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
keys := make([]EncryptedTLFCryptKeyClientAndEphemeral, 0, 4)
clientHalves := make([]TLFCryptKeyClientHalf, 0, 4)
for i := 0; i < 4; i++ {
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
// See crypto_common_test.go for tests that this actually
// performs encryption.
encryptedClientHalf, err := c.EncryptTLFCryptKeyClientHalf(ephPrivateKey, cryptPrivateKey.getPublicKey(), clientHalf)
if err != nil {
t.Fatal(err)
}
if encryptedClientHalf.Version != EncryptionSecretbox {
t.Fatalf("Unexpected encryption version %d", encryptedClientHalf.Version)
}
keys = append(keys, EncryptedTLFCryptKeyClientAndEphemeral{
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalf,
EPubKey: ephPublicKey,
})
clientHalves = append(clientHalves, clientHalf)
}
decryptedClientHalf, index, err := c.DecryptTLFCryptKeyClientHalfAny(
context.Background(), keys, false)
if err != nil {
t.Fatal(err)
}
if index != 0 {
t.Errorf("expected first key to work. Actual key index: %d", index)
}
if clientHalves[0] != decryptedClientHalf {
t.Error("clientHalf != decryptedClientHalf")
}
}
// Test various failure cases for DecryptTLFCryptKeyClientHalfAny and that
// if a working key is present, the decryption succeeds.
func TestCryptoClientDecryptTLFCryptKeyClientHalfAnyFailures(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
encryptedClientHalf, err := c.EncryptTLFCryptKeyClientHalf(ephPrivateKey, cryptPrivateKey.getPublicKey(), clientHalf)
if err != nil {
t.Fatal(err)
}
// Wrong version.
encryptedClientHalfWrongVersion := encryptedClientHalf
encryptedClientHalfWrongVersion.Version++
// Wrong sizes.
encryptedClientHalfWrongSize := encryptedClientHalf
encryptedClientHalfWrongSize.EncryptedData = encryptedClientHalfWrongSize.EncryptedData[:len(encryptedClientHalfWrongSize.EncryptedData)-1]
encryptedClientHalfWrongNonceSize := encryptedClientHalf
encryptedClientHalfWrongNonceSize.Nonce = encryptedClientHalfWrongNonceSize.Nonce[:len(encryptedClientHalfWrongNonceSize.Nonce)-1]
// Corrupt key.
ephPublicKeyCorrupt := ephPublicKey
ephPublicKeyCorrupt.data[0] = ^ephPublicKeyCorrupt.data[0]
// Corrupt data.
encryptedClientHalfCorruptData := encryptedClientHalf
encryptedClientHalfCorruptData.EncryptedData = make([]byte, len(encryptedClientHalf.EncryptedData))
copy(encryptedClientHalfCorruptData.EncryptedData, encryptedClientHalf.EncryptedData)
encryptedClientHalfCorruptData.EncryptedData[0] = ^encryptedClientHalfCorruptData.EncryptedData[0]
keys := []EncryptedTLFCryptKeyClientAndEphemeral{
{
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalfWrongVersion,
EPubKey: ephPublicKey,
}, {
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalfWrongSize,
EPubKey: ephPublicKey,
}, {
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalfWrongNonceSize,
EPubKey: ephPublicKey,
}, {
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalf,
EPubKey: ephPublicKeyCorrupt,
}, {
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalfCorruptData,
EPubKey: ephPublicKey,
}, {
PubKey: cryptPrivateKey.getPublicKey(),
ClientHalf: encryptedClientHalf,
EPubKey: ephPublicKey,
},
}
_, index, err := c.DecryptTLFCryptKeyClientHalfAny(
context.Background(), keys, false)
if err != nil {
t.Fatal(err)
}
if index != len(keys)-1 {
t.Errorf("expected last key to work. Actual key index: %d", index)
}
}
// Test various failure cases for DecryptTLFCryptKeyClientHalf.
func TestCryptoClientDecryptTLFCryptKeyClientHalfFailures(t *testing.T) {
signingKey := MakeFakeSigningKeyOrBust("client sign")
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
fc := NewFakeCryptoClient(config, signingKey, cryptPrivateKey, nil, nil)
c := newCryptoClientWithClient(config, fc)
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
encryptedClientHalf, err := c.EncryptTLFCryptKeyClientHalf(ephPrivateKey, cryptPrivateKey.getPublicKey(), clientHalf)
if err != nil {
t.Fatal(err)
}
var expectedErr error
// Wrong version.
encryptedClientHalfWrongVersion := encryptedClientHalf
encryptedClientHalfWrongVersion.Version++
expectedErr = UnknownEncryptionVer{encryptedClientHalfWrongVersion.Version}
ctx := context.Background()
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKey,
encryptedClientHalfWrongVersion)
if err != expectedErr {
t.Errorf("Expected %v, got %v", expectedErr, err)
}
// Wrong sizes.
encryptedClientHalfWrongSize := encryptedClientHalf
encryptedClientHalfWrongSize.EncryptedData = encryptedClientHalfWrongSize.EncryptedData[:len(encryptedClientHalfWrongSize.EncryptedData)-1]
expectedErr = libkb.DecryptionError{}
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKey,
encryptedClientHalfWrongSize)
if err != expectedErr {
t.Errorf("Expected %v, got %v", expectedErr, err)
}
encryptedClientHalfWrongNonceSize := encryptedClientHalf
encryptedClientHalfWrongNonceSize.Nonce = encryptedClientHalfWrongNonceSize.Nonce[:len(encryptedClientHalfWrongNonceSize.Nonce)-1]
expectedErr = InvalidNonceError{encryptedClientHalfWrongNonceSize.Nonce}
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKey,
encryptedClientHalfWrongNonceSize)
if err.Error() != expectedErr.Error() {
t.Errorf("Expected %v, got %v", expectedErr, err)
}
// Corrupt key.
ephPublicKeyCorrupt := ephPublicKey
ephPublicKeyCorrupt.data[0] = ^ephPublicKeyCorrupt.data[0]
expectedErr = libkb.DecryptionError{}
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKeyCorrupt,
encryptedClientHalf)
if err != expectedErr {
t.Errorf("Expected %v, got %v", expectedErr, err)
}
// Corrupt data.
encryptedClientHalfCorruptData := encryptedClientHalf
encryptedClientHalfCorruptData.EncryptedData[0] = ^encryptedClientHalfCorruptData.EncryptedData[0]
expectedErr = libkb.DecryptionError{}
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKey,
encryptedClientHalfCorruptData)
if err != expectedErr {
t.Errorf("Expected %v, got %v", expectedErr, err)
}
}
// Test that canceling a signing RPC returns the correct error
func TestCryptoClientDecryptTLFCryptKeyClientHalfCanceled(t *testing.T) {
cryptPrivateKey := MakeFakeCryptPrivateKeyOrBust("client crypt private")
config := testCryptoClientConfig(t)
serverConn, conn := rpc.MakeConnectionForTest(t)
c := newCryptoClientWithClient(config, conn.GetClient())
_, _, ephPublicKey, ephPrivateKey, cryptKey, err := c.MakeRandomTLFKeys()
if err != nil {
t.Fatal(err)
}
serverHalf, err := c.MakeRandomTLFCryptKeyServerHalf()
if err != nil {
t.Fatal(err)
}
clientHalf, err := c.MaskTLFCryptKey(serverHalf, cryptKey)
if err != nil {
t.Fatal(err)
}
encryptedClientHalf, err := c.EncryptTLFCryptKeyClientHalf(ephPrivateKey, cryptPrivateKey.getPublicKey(), clientHalf)
if err != nil {
t.Fatal(err)
}
f := func(ctx context.Context) error {
_, err = c.DecryptTLFCryptKeyClientHalf(ctx, ephPublicKey,
encryptedClientHalf)
return err
}
testRPCWithCanceledContext(t, serverConn, f)
}
|
<filename>safe-indexer-ts/src/ethers/parser/transfers.ts
import { ethers } from "ethers";
import { EventDecoder } from ".";
import { Event, TransferTx, EtherDetails, TransferDetails } from "../../types";
import { erc20Interface, erc20OldInterface, erc721Interface, etherReceivedTopic, safeInterface, transferTopic, } from "../constants";
export class TransferDecoder implements EventDecoder {
provider: ethers.providers.Provider;
useFallbackDecoding: boolean;
constructor(provider: ethers.providers.Provider, useFallbackDecoding?: boolean) {
this.provider = provider;
this.useFallbackDecoding = useFallbackDecoding || true;
}
async decodeTokenTransfer(safe: string, event: Event): Promise<TransferTx | undefined> {
const id = "transfer_" + event.transactionHash + "_" + event.eventId
const block = await this.provider.getBlock(event.blockHash)
let type: string = ""
let eventInterface
if (event.topics.length === 4) {
eventInterface = erc721Interface
type = "ERC721"
} else if (event.topics.length === 3) {
eventInterface = erc20Interface
type = "ERC20"
} else if (event.topics.length === 2) {
eventInterface = erc20OldInterface
type = "ERC20"
} else {
return undefined
}
const eventParams = eventInterface.decodeEventLog("Transfer", event.data, event.topics)
let details: TransferDetails
if (type === "ERC20") {
details = {
type: "ERC20",
tokenAddress: event.address,
value: eventParams.amount.toString()
}
} else {
details = {
type: "ERC721",
tokenAddress: event.address,
tokenId: eventParams.tokenId.toString()
}
}
return {
type: "transfer",
id,
block: block.number,
txHash: event.transactionHash,
timestamp: block.timestamp,
sender: eventParams.from,
receipient: eventParams.to,
direction: (eventParams.to.toLowerCase() === safe.toLowerCase() ? "INCOMING" : "OUTGOING"),
details
}
}
async decodeEtherTransfer(safe: string, event: Event): Promise<TransferTx | undefined> {
const id = "transfer_" + event.transactionHash + "_" + event.eventId
const block = await this.provider.getBlock(event.blockHash)
const eventParams = safeInterface.decodeEventLog("SafeReceived", event.data, event.topics)
let details: EtherDetails = {
type: "ETHER",
value: eventParams.value.toString()
}
const transferMeta: any = {
type: "transfer",
id,
sender: eventParams.sender,
receipient: safe,
direction: "INCOMING",
timestamp: block.timestamp,
txHash: event.transactionHash,
details
}
return transferMeta
}
async decode(event: Event, subEvents?: Event[], detailEvent?: Event): Promise<TransferTx | undefined> {
switch (event.topics[0]) {
case transferTopic: {
if (subEvents && subEvents.length > 0) console.error("Sub logs for transfer entry!", event, subEvents)
if (!event.account) return undefined
return await this.decodeTokenTransfer(event.account, event)
}
case etherReceivedTopic: {
if (subEvents && subEvents.length > 0) console.error("Sub logs for transfer entry!", event, subEvents)
return await this.decodeEtherTransfer(event.address, event)
}
default: {
return undefined
}
}
}
} |
// commandUsage display the usage for a specific command.
func commandUsage(method interface{}) {
usage, err := dcrjson.MethodUsageText(method)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to obtain command usage:", err)
return
}
fmt.Fprintln(os.Stderr, "Usage:")
fmt.Fprintf(os.Stderr, " %s\n", usage)
} |
<filename>cmd/syncthing/gui.go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"runtime"
"sync"
"time"
"code.google.com/p/go.crypto/bcrypt"
"github.com/codegangsta/martini"
)
type guiError struct {
Time time.Time
Error string
}
var (
configInSync = true
guiErrors = []guiError{}
guiErrorsMut sync.Mutex
static = embeddedStatic()
staticFunc = static.(func(http.ResponseWriter, *http.Request, *log.Logger))
)
const (
unchangedPassword = <PASSWORD>--"
)
func startGUI(cfg GUIConfiguration, m *Model) error {
l, err := net.Listen("tcp", cfg.Address)
if err != nil {
return err
}
router := martini.NewRouter()
router.Get("/", getRoot)
router.Get("/rest/version", restGetVersion)
router.Get("/rest/model", restGetModel)
router.Get("/rest/connections", restGetConnections)
router.Get("/rest/config", restGetConfig)
router.Get("/rest/config/sync", restGetConfigInSync)
router.Get("/rest/system", restGetSystem)
router.Get("/rest/errors", restGetErrors)
router.Post("/rest/config", restPostConfig)
router.Post("/rest/restart", restPostRestart)
router.Post("/rest/reset", restPostReset)
router.Post("/rest/shutdown", restPostShutdown)
router.Post("/rest/error", restPostError)
router.Post("/rest/error/clear", restClearErrors)
mr := martini.New()
if len(cfg.User) > 0 && len(cfg.Password) > 0 {
mr.Use(basic(cfg.User, cfg.Password))
}
mr.Use(static)
mr.Use(martini.Recovery())
mr.Use(restMiddleware)
mr.Action(router.Handle)
mr.Map(m)
go http.Serve(l, mr)
return nil
}
func getRoot(w http.ResponseWriter, r *http.Request) {
r.URL.Path = "/index.html"
staticFunc(w, r, nil)
}
func restMiddleware(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) >= 6 && r.URL.Path[:6] == "/rest/" {
w.Header().Set("Cache-Control", "no-cache")
}
}
func restGetVersion() string {
return Version
}
func restGetModel(m *Model, w http.ResponseWriter, r *http.Request) {
var qs = r.URL.Query()
var repo = qs.Get("repo")
var res = make(map[string]interface{})
for _, cr := range cfg.Repositories {
if cr.ID == repo {
res["invalid"] = cr.Invalid
break
}
}
globalFiles, globalDeleted, globalBytes := m.GlobalSize(repo)
res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes
localFiles, localDeleted, localBytes := m.LocalSize(repo)
res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes
needFiles, needBytes := m.NeedSize(repo)
res["needFiles"], res["needBytes"] = needFiles, needBytes
res["inSyncFiles"], res["inSyncBytes"] = globalFiles-needFiles, globalBytes-needBytes
res["state"] = m.State(repo)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
func restGetConnections(m *Model, w http.ResponseWriter) {
var res = m.ConnectionStats()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
func restGetConfig(w http.ResponseWriter) {
encCfg := cfg
if encCfg.GUI.Password != "" {
encCfg.GUI.Password = <PASSWORD>
}
json.NewEncoder(w).Encode(encCfg)
}
func restPostConfig(req *http.Request) {
var prevPassHash = cfg.GUI.Password
err := json.NewDecoder(req.Body).Decode(&cfg)
if err != nil {
warnln(err)
} else {
if cfg.GUI.Password == "" {
// Leave it empty
} else if cfg.GUI.Password != <PASSWORD> {
hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
if err != nil {
warnln(err)
} else {
cfg.GUI.Password = string(hash)
}
} else {
cfg.GUI.Password = <PASSWORD>
}
saveConfig()
configInSync = false
}
}
func restGetConfigInSync(w http.ResponseWriter) {
json.NewEncoder(w).Encode(map[string]bool{"configInSync": configInSync})
}
func restPostRestart(w http.ResponseWriter) {
flushResponse(`{"ok": "restarting"}`, w)
go restart()
}
func restPostReset(w http.ResponseWriter) {
flushResponse(`{"ok": "resetting repos"}`, w)
resetRepositories()
go restart()
}
func restPostShutdown(w http.ResponseWriter) {
flushResponse(`{"ok": "shutting down"}`, w)
go shutdown()
}
func flushResponse(s string, w http.ResponseWriter) {
w.Write([]byte(s + "\n"))
f := w.(http.Flusher)
f.Flush()
}
var cpuUsagePercent [10]float64 // The last ten seconds
var cpuUsageLock sync.RWMutex
func restGetSystem(w http.ResponseWriter) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
res := make(map[string]interface{})
res["myID"] = myID
res["goroutines"] = runtime.NumGoroutine()
res["alloc"] = m.Alloc
res["sys"] = m.Sys
if cfg.Options.GlobalAnnEnabled && discoverer != nil {
res["extAnnounceOK"] = discoverer.ExtAnnounceOK()
}
cpuUsageLock.RLock()
var cpusum float64
for _, p := range cpuUsagePercent {
cpusum += p
}
cpuUsageLock.RUnlock()
res["cpuPercent"] = cpusum / 10
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
func restGetErrors(w http.ResponseWriter) {
guiErrorsMut.Lock()
json.NewEncoder(w).Encode(guiErrors)
guiErrorsMut.Unlock()
}
func restPostError(req *http.Request) {
bs, _ := ioutil.ReadAll(req.Body)
req.Body.Close()
showGuiError(string(bs))
}
func restClearErrors() {
guiErrorsMut.Lock()
guiErrors = nil
guiErrorsMut.Unlock()
}
func showGuiError(err string) {
guiErrorsMut.Lock()
guiErrors = append(guiErrors, guiError{time.Now(), err})
if len(guiErrors) > 5 {
guiErrors = guiErrors[len(guiErrors)-5:]
}
guiErrorsMut.Unlock()
}
func basic(username string, passhash string) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
error := func() {
time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
http.Error(res, "Not Authorized", http.StatusUnauthorized)
}
hdr := req.Header.Get("Authorization")
if len(hdr) < len("Basic ") || hdr[:6] != "Basic " {
error()
return
}
hdr = hdr[6:]
bs, err := base64.StdEncoding.DecodeString(hdr)
if err != nil {
error()
return
}
fields := bytes.SplitN(bs, []byte(":"), 2)
if len(fields) != 2 {
error()
return
}
if string(fields[0]) != username {
error()
return
}
if err := bcrypt.CompareHashAndPassword([]byte(passhash), fields[1]); err != nil {
error()
return
}
}
}
|
def calc_cosine_similarity(word):
return similarity |
The next ‘Adventures in infrastructure design’ webinar is currently being planned and I am very honoured to have had such as good response.
We had over 40 live attendees on the last webinar and received a lot of requests for the recording and future topics.
The next webinar will cover some of these requests in more detail.
Presented by several VCDX certified presenters / Mentors and experienced professionals.
This session will be covering
“The VCDX submission, last minute changes / checklists”
Timed just before the next VCDX submission in June, you will also have a chance to get some last minute advice from people who have been through the journey themselves (We are not panelists and have no knowledge of the official scoring method).
We have also got some recent VCDX experience discussions planned too.
Date : 6th June 2017
Time : 23:30 pm UK (about 1 hour )
Please register your interest using this sign up link.
Real time discussion is valued so please attend if you can.
See you there |
WATER QUALITY EVALUATION OF SMALL SCALE DESALINATION PLANTS IN THE GAZA STRIP, PALESTINE
The Gaza Strip is a highly populated, small area in which the groundwater is the main water source. During the last few decades, groundwater quality has deteriorated to a limit that the municipal tap water became brackish and unsuitable for human consumption in most parts of the Strip. To overcome this serious situation, the reverse osmosis (RO) technology is used to replace the tap water or to improve its quality. Several private Palestinian water investing companies established a small-scale reverse osmosis (RO) desalination plants to cover the shortage of good quality of drinking water in the whole Gaza Strip. The purpose of this paper is to investigate the chemical and bacteriological water qualities of different small scale of (RO) desalination companies in the Gaza Strip. The results of the chemical and bacteriological parameters were compared with the World Health Organization (WHO) standards. It was concluded that all chemical analyses of RO produced water are within the allowable WHO limits. Bact... |
/**
* Validates: a {@link GtfsStop} is within a distance threshold for a trip shape.
*
* <p>Generated notice: {@link StartAndEndDateOutOfOrderNotice}.
*/
@GtfsValidator
public class StopTooFarFromTripShapeValidator extends FileValidator {
@Inject GtfsStopTimeTableContainer stopTimeTable;
@Inject GtfsTripTableContainer tripTable;
@Inject GtfsShapeTableContainer shapeTable;
@Inject GtfsStopTableContainer stopTable;
@Override
public void validate(NoticeContainer noticeContainer) {
List<StopTooFarFromTripShapeNotice> notices = new ArrayList<>();
// Cache for previously tested shape_id and stop_id pairs - we don't need to test them more than
// once
final Set<String> testedCache = new HashSet<>();
stopTimeTable
.byTripIdMap()
.forEach(
(tripId, tripStopTimes) -> {
GtfsTrip trip = tripTable.byTripId(tripId);
if (trip == null || !trip.hasShapeId()) {
// No shape for this trip - skip to the next trip
return;
}
// Check for possible errors for this combination of stop times and shape points for
// this trip_id
List<StopTooFarFromTripShapeNotice> noticesForTrip =
GeospatialUtil.checkStopsWithinTripShape(
trip,
stopTimeTable.byTripId(tripId),
shapeTable.byShapeId(trip.shapeId()),
stopTable,
testedCache);
notices.addAll(noticesForTrip);
});
notices.forEach(noticeContainer::addValidationNotice);
}
} |
/*
* API function to set the number to be partitioned
*/
void partition_function_iterator__init(
const int _entire_size)
{
if (set_array != NULL)
{
free(set_array);
}
if (sum_array != NULL)
{
free(sum_array);
}
if (_entire_size < 1)
{
has_next = false;
return;
}
has_next = true;
entire_size = _entire_size;
set_array = malloc((_entire_size + 1) * sizeof(int));
for (int i = 0; i < _entire_size; ++i)
{
set_array[i] = 0;
}
sum_array = malloc(_entire_size * sizeof(int));
} |
<gh_stars>1-10
#![doc = include_str!("../Readme.md")]
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
// XXX: REMOVEME: Get rid of these defs in the next breaking revision of abibool.
// They're too winapi specific. See other "XXX: REMOVEME: " comments for thoughts.
use i32 as BOOL; // use winapi::shared::minwindef::BOOL;
use u8 as BOOLEAN; // use winapi::shared::minwindef::BOOLEAN;
/// 8-bit boolean type that's ABI-compatible with Win32's [BOOLEAN].
///
/// 99% of the time, you should prefer [bool] in your interfaces and simply convert between types.
/// However, some windows APIs take [BOOLEAN] arrays, or contain structures with [BOOLEAN]s.
/// [bool8] can be used in these cases to avoid the need for internal allocations or conversions for mere ABI conversions.
///
/// `0` is `false`y, all other bit patterns are `true`thy.
///
/// [BOOLEAN]: https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types#BOOLEAN
#[allow(non_camel_case_types)] // Okay, `bool8` is kind of a weird type name I agree... warranted in this case though IMO
#[derive(Clone, Copy)]
#[repr(transparent)] pub struct bool8(BOOLEAN);
pub use bool8 as b8;
impl bool8 {
/// bool8(`0`)
pub const FALSE : bool8 = bool8(0);
/// bool8(`1`)
pub const TRUE : bool8 = bool8(1);
pub fn from(value: impl Into<Self>) -> Self { value.into() }
}
/// 32-bit boolean type that's ABI-compatible with Win32's [BOOL].
///
/// 99% of the time, you should prefer [bool] in your interfaces and simply convert between types.
/// However, some windows APIs take [BOOL] arrays, or contain structures with [BOOL]s.
/// [bool32] can be used in these cases to avoid the need for internal allocations or conversions for mere ABI conversions.
///
/// `0` is `false`y, all other bit patterns are `true`thy.
///
/// [BOOL]: https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types#BOOL
#[allow(non_camel_case_types)] // Okay, `bool32` is kind of a weird type name I agree... warranted in this case though IMO
#[derive(Clone, Copy)]
#[repr(transparent)] pub struct bool32(BOOL);
pub use bool32 as b32;
impl bool32 {
/// bool32(`0`)
pub const FALSE : bool32 = bool32(0);
/// bool32(`1`)
pub const TRUE : bool32 = bool32(1);
pub fn from(value: impl Into<Self>) -> Self { value.into() }
}
impl AsRef<bool> for bool8 { fn as_ref(&self) -> &bool { if bool::from(*self) { &true } else { &false } } }
impl AsRef<bool> for bool32 { fn as_ref(&self) -> &bool { if bool::from(*self) { &true } else { &false } } }
impl Borrow<bool> for bool8 { fn borrow(&self) -> &bool { if bool::from(*self) { &true } else { &false } } }
impl Borrow<bool> for bool32 { fn borrow(&self) -> &bool { if bool::from(*self) { &true } else { &false } } }
// DON'T IMPLEMENT:
// impl Borrow<BOOLEAN> for bool8 { ... }
// impl Borrow<BOOL > for bool32 { ... }
// "In particular Eq, Ord and Hash must be equivalent for borrowed and owned values" (https://doc.rust-lang.org/std/borrow/trait.Borrow.html)
// We've gone to pains to make bool32 behave very much like bool, with `true` acting like a single value, even when the internal BOOL might be another truthy value like `-1`.
// XXX: REMOVEME: Too winapi specific, prone to misuse. Main intent here is FFI interop.
// Replace with `as_[mut_]_ptr` type constrained to matching-size integer types?
impl Deref for bool8 { type Target = BOOLEAN; fn deref(&self) -> &Self::Target { &self.0 } }
impl Deref for bool32 { type Target = BOOL; fn deref(&self) -> &Self::Target { &self.0 } }
impl DerefMut for bool8 { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
impl DerefMut for bool32 { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
impl Default for bool8 { fn default() -> Self { Self::FALSE } }
impl Default for bool32 { fn default() -> Self { Self::FALSE } }
impl Debug for bool8 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Debug ::fmt(&bool::from(*self), f) } }
impl Debug for bool32 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Debug ::fmt(&bool::from(*self), f) } }
impl Display for bool8 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Display::fmt(&bool::from(*self), f) } }
impl Display for bool32 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Display::fmt(&bool::from(*self), f) } }
impl From<bool > for bool8 { fn from(value: bool ) -> Self { Self(value as _) } }
impl From<bool > for bool32 { fn from(value: bool ) -> Self { Self(value as _) } }
impl From<BOOLEAN> for bool8 { fn from(value: BOOLEAN) -> Self { Self(value) } } // XXX: REMOVEME: replace with `{u,i}8`?
impl From<BOOL > for bool32 { fn from(value: BOOL ) -> Self { Self(value) } } // XXX: REMOVEME: replace with `{u,i}32`?
impl From<bool8 > for BOOLEAN { fn from(value: bool8 ) -> Self { value.0 } } // XXX: REMOVEME: replace with `{u,i}8`?
impl From<bool32 > for BOOL { fn from(value: bool32 ) -> Self { value.0 } } // XXX: REMOVEME: replace with `{u,i}32`?
impl From<bool8 > for bool { fn from(value: bool8 ) -> Self { value.0 != 0 } }
impl From<bool32 > for bool { fn from(value: bool32 ) -> Self { value.0 != 0 } }
impl From<&BOOLEAN> for &bool8 { fn from(value: &BOOLEAN) -> Self { unsafe { std::mem::transmute(value) } } } // XXX: REMOVEME: replace with `{u,i}8`?
impl From<&BOOL > for &bool32 { fn from(value: &BOOL ) -> Self { unsafe { std::mem::transmute(value) } } } // XXX: REMOVEME: replace with `{u,i}32`?
impl From<&bool8 > for &BOOLEAN { fn from(value: &bool8 ) -> Self { unsafe { std::mem::transmute(value) } } } // XXX: REMOVEME: replace with `{u,i}8`?
impl From<&bool32 > for &BOOL { fn from(value: &bool32 ) -> Self { unsafe { std::mem::transmute(value) } } } // XXX: REMOVEME: replace with `{u,i}32`?
// slices are always foreign, so we can't implement these - transmute yourself I guess
// impl From<&[BOOLEAN]> for &[bool8 ] { fn from(value: &[BOOLEAN]) -> Self { unsafe { std::mem::transmute(value) } } }
// impl From<&[BOOL ]> for &[bool32 ] { fn from(value: &[BOOL ]) -> Self { unsafe { std::mem::transmute(value) } } }
// impl From<&[bool8 ]> for &[BOOLEAN] { fn from(value: &[bool8 ]) -> Self { unsafe { std::mem::transmute(value) } } }
// impl From<&[bool32 ]> for &[BOOL ] { fn from(value: &[bool32 ]) -> Self { unsafe { std::mem::transmute(value) } } }
// All comparisons, hashes, etc. are based on truthiness, not the underlying bit patterns!
impl Eq for bool8 {}
impl Eq for bool32 {}
impl PartialEq<bool8 > for bool8 { fn eq(&self, other: &bool8 ) -> bool { bool::from(*self) == bool::from(*other) } }
impl PartialEq<bool32> for bool32 { fn eq(&self, other: &bool32) -> bool { bool::from(*self) == bool::from(*other) } }
impl PartialEq<bool8 > for bool32 { fn eq(&self, other: &bool8 ) -> bool { bool::from(*self) == bool::from(*other) } }
impl PartialEq<bool32> for bool8 { fn eq(&self, other: &bool32) -> bool { bool::from(*self) == bool::from(*other) } }
impl PartialEq<bool > for bool8 { fn eq(&self, other: &bool ) -> bool { bool::from(*self) == *other } }
impl PartialEq<bool > for bool32 { fn eq(&self, other: &bool ) -> bool { bool::from(*self) == *other } }
impl PartialEq<bool8 > for bool { fn eq(&self, other: &bool8 ) -> bool { bool::from(*other) == *self } }
impl PartialEq<bool32> for bool { fn eq(&self, other: &bool32) -> bool { bool::from(*other) == *self } }
impl PartialOrd<bool8 > for bool8 { fn partial_cmp(&self, other: &bool8 ) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), &bool::from(*other)) } }
impl PartialOrd<bool32> for bool32 { fn partial_cmp(&self, other: &bool32) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), &bool::from(*other)) } }
impl PartialOrd<bool8 > for bool32 { fn partial_cmp(&self, other: &bool8 ) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), &bool::from(*other)) } }
impl PartialOrd<bool32> for bool8 { fn partial_cmp(&self, other: &bool32) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), &bool::from(*other)) } }
impl PartialOrd<bool > for bool8 { fn partial_cmp(&self, other: &bool ) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), other) } }
impl PartialOrd<bool > for bool32 { fn partial_cmp(&self, other: &bool ) -> Option<Ordering> { PartialOrd::partial_cmp(&bool::from(*self), other) } }
impl PartialOrd<bool8 > for bool { fn partial_cmp(&self, other: &bool8 ) -> Option<Ordering> { PartialOrd::partial_cmp(self, &bool::from(*other)) } }
impl PartialOrd<bool32> for bool { fn partial_cmp(&self, other: &bool32) -> Option<Ordering> { PartialOrd::partial_cmp(self, &bool::from(*other)) } }
impl Ord for bool8 { fn cmp(&self, other: &bool8 ) -> Ordering { Ord::cmp(&bool::from(*self), &bool::from(*other)) } }
impl Ord for bool32 { fn cmp(&self, other: &bool32) -> Ordering { Ord::cmp(&bool::from(*self), &bool::from(*other)) } }
impl Hash for bool8 { fn hash<H: Hasher>(&self, state: &mut H) { bool::from(*self).hash(state) } }
impl Hash for bool32 { fn hash<H: Hasher>(&self, state: &mut H) { bool::from(*self).hash(state) } }
#[cfg(feature = "bytemuck")] mod _bytemuck {
use super::*;
unsafe impl bytemuck::Pod for bool8 {}
unsafe impl bytemuck::Pod for bool32 {}
unsafe impl bytemuck::Zeroable for bool8 {}
unsafe impl bytemuck::Zeroable for bool32 {}
}
|
def save_token(self, access_token):
access_token_id = self.execute(self.create_access_token_query,
access_token.client_id,
access_token.grant_type,
access_token.token,
access_token.expires_at,
access_token.refresh_token,
access_token.refresh_expires_at,
access_token.user_id)
for key, value in list(access_token.data.items()):
self.execute(self.create_data_query, key, value,
access_token_id)
for scope in access_token.scopes:
self.execute(self.create_scope_query, scope, access_token_id)
return True |
<gh_stars>0
package com.macroyau.thingspeakandroid.demo;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SetChoiceActivity extends AppCompatActivity {
private ImageView alertButtonSopot;
private ImageView alertButtonTatry;
private ImageView alertButtonWarszawa;
private ImageView alertButtonParyz;
private ImageView alertButtonLondyn;
private ImageView alertButtonRio;
private TextView alertTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_choice);
alertTextView = (TextView) findViewById(R.id.alert);
alertButtonSopot = (ImageView) findViewById(R.id.sopot_img);
alertButtonTatry = (ImageView) findViewById(R.id.tatry_img);
alertButtonWarszawa = (ImageView) findViewById(R.id.waraszawa_img);
alertButtonParyz = (ImageView) findViewById(R.id.paryz_img);
alertButtonLondyn = (ImageView) findViewById(R.id.londyn_img);
alertButtonRio = (ImageView) findViewById(R.id.rio_img);
alertButtonSopot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
alertButtonTatry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
alertButtonWarszawa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
alertButtonParyz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
alertButtonLondyn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
alertButtonRio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SetChoiceActivity.this);
builder.setTitle("Brak zestawu czujników");
builder.setMessage("Nie wykryto żadnego zestawu czujników. Pozdłącz zestaw do aplikacji ThingSpeak.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertTextView.setVisibility(View.VISIBLE);
}
});
builder.show();
}
});
}
public void poznan(View view) {
Intent intent = new Intent(SetChoiceActivity.this, PoznanActivity.class);
startActivity(intent);
}
public void inowroclaw(View view) {
Intent intent = new Intent(SetChoiceActivity.this, InowroclawActivity.class);
startActivity(intent);
}
}
|
// +build wasm
package jspubsub
import (
"context"
"fmt"
"github.com/quorumcontrol/tupelo-go-sdk/gossip/client/pubsubinterfaces"
"syscall/js"
"github.com/quorumcontrol/tupelo-go-sdk/wasm/helpers"
pb "github.com/libp2p/go-libp2p-pubsub/pb"
)
type BridgedSubscription struct {
pubsubinterfaces.Subscription
pubsub *PubSubBridge
jsFunc js.Func
topic string
ch chan pubsubinterfaces.Message
}
func newBridgedSubscription(topic string) *BridgedSubscription {
return &BridgedSubscription{
topic: topic,
ch: make(chan pubsubinterfaces.Message),
}
}
func (bs *BridgedSubscription) Next(ctx context.Context) (pubsubinterfaces.Message, error) {
done := ctx.Done()
select {
case <-done:
return nil, fmt.Errorf("context done")
case msg := <-bs.ch:
return msg, nil
}
}
func (bs *BridgedSubscription) Cancel() {
go bs.pubsub.jspubsub.Call("unsubscribe", js.ValueOf(bs.topic), bs.jsFunc)
bs.jsFunc.Release()
}
func (bs *BridgedSubscription) QueueJS(msg js.Value) {
// js looks like:
// {
// from: 'QmSWBdQGuX8Uregx8Q<KEY>',
// data: <Buffer 68 69>,
// seqno: <Buffer fe 54 4a ad 49 b4 94 5d 09 98 ad 0e ad 70 43 33 4c fc 4f a5>,
// topicIDs: [ 'test' ]
// }
pubsubMsg := &pb.Message{
From: []byte(msg.Get("from").String()),
Seqno: helpers.JsBufferToBytes(msg.Get("seqno")),
Data: helpers.JsBufferToBytes(msg.Get("data")),
TopicIDs: helpers.JsStringArrayToStringSlice(msg.Get("topicIDs")),
}
bs.ch <- pubsubMsg
}
|
// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { AppModule } from "./app/app.module";
import * as app from "tns-core-modules/application";
import * as appSettings from "tns-core-modules/application-settings";
appSettings.setString("WECHAT_APP_ID", "wxd930ea5d5a258f4f"); // We will set wechat APP ID as global here so that we can use that from anywhere :)
if (app.ios) {
const setupAppDeligate = require('./app/getappdelegate.ios').setupAppDeligate;
setupAppDeligate();
}
platformNativeScriptDynamic().bootstrapModule(AppModule);
|
<gh_stars>0
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2019 Google Inc. http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "LoadDeformed.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h"
#include "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btSoftBody.h"
#include "BulletSoftBody/btSoftBodyHelpers.h"
#include "BulletSoftBody/btDeformableBodySolver.h"
#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "../CommonInterfaces/CommonParameterInterface.h"
#include <stdio.h> //printf debugging
#include "../CommonInterfaces/CommonDeformableBodyBase.h"
#include "../Utils/b3ResourcePath.h"
#include "../Utils/b3BulletDefaultFileIO.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string.h>
struct CustomSoftBodyHelper : public btSoftBodyHelpers
{
static std::string loadDeformableState(btAlignedObjectArray<btVector3>& qs, btAlignedObjectArray<btVector3>& vs, const char* filename, CommonFileIOInterface* fileIO);
};
static inline bool isSpace(const char c)
{
return (c == ' ') || (c == '\t');
}
static inline bool isNewLine(const char c)
{
return (c == '\r') || (c == '\n') || (c == '\0');
}
static inline float parseFloat(const char*& token)
{
token += strspn(token, " \t");
float f = (float)atof(token);
token += strcspn(token, " \t\r");
return f;
}
static inline void parseFloat3(
float& x, float& y, float& z,
const char*& token)
{
x = parseFloat(token);
y = parseFloat(token);
z = parseFloat(token);
}
std::string CustomSoftBodyHelper::loadDeformableState(btAlignedObjectArray<btVector3>& qs, btAlignedObjectArray<btVector3>& vs, const char* filename, CommonFileIOInterface* fileIO)
{
{
qs.clear();
vs.clear();
std::string tmp = filename;
std::stringstream err;
#ifdef USE_STREAM
std::ifstream ifs(filename);
if (!ifs)
{
err << "Cannot open file [" << filename << "]" << std::endl;
return err.str();
}
#else
int fileHandle = fileIO->fileOpen(filename, "r");
if (fileHandle < 0)
{
err << "Cannot open file [" << filename << "]" << std::endl;
return err.str();
}
#endif
std::string name;
int maxchars = 8192; // Alloc enough size.
std::vector<char> buf(maxchars); // Alloc enough size.
std::string linebuf;
linebuf.reserve(maxchars);
#ifdef USE_STREAM
while (ifs.peek() != -1)
#else
char* line = 0;
do
#endif
{
linebuf.resize(0);
#ifdef USE_STREAM
safeGetline(ifs, linebuf);
#else
char tmpBuf[1024];
line = fileIO->readLine(fileHandle, tmpBuf, 1024);
if (line)
{
linebuf = line;
}
#endif
// Trim newline '\r\n' or '\r'
if (linebuf.size() > 0)
{
if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0)
{
if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty())
{
continue;
}
// Skip leading space.
const char* token = linebuf.c_str();
token += strspn(token, " \t");
btAssert(token);
if (token[0] == '\0') continue; // empty line
if (token[0] == '#') continue; // comment line
// q
if (token[0] == 'q' && isSpace((token[1])))
{
token += 2;
float x, y, z;
parseFloat3(x, y, z, token);
qs.push_back(btVector3(x, y, z));
continue;
}
// v
if (token[0] == 'v' && isSpace((token[1])))
{
token += 3;
float x, y, z;
parseFloat3(x, y, z, token);
vs.push_back(btVector3(x, y, z));
continue;
}
// Ignore unknown command.
}
#ifndef USE_STREAM
while (line)
;
#endif
if (fileHandle >= 0)
{
fileIO->fileClose(fileHandle);
}
return err.str();
}
}
class LoadDeformed : public CommonDeformableBodyBase
{
int steps;
btSoftBody* psb;
char filename;
int reset_frame;
float sim_time;
public:
LoadDeformed(struct GUIHelperInterface* helper)
: CommonDeformableBodyBase(helper)
{
steps = 0;
psb = nullptr;
reset_frame = 0;
sim_time = 0;
}
virtual ~LoadDeformed()
{
}
void initPhysics();
void exitPhysics();
void resetCamera()
{
float dist = 2;
float pitch = -45;
float yaw = 100;
float targetPos[3] = {0, 0, 0};
m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
}
void stepSimulation(float deltaTime)
{
steps++;
sim_time += deltaTime;
//// int seconds = 1/deltaTime;
if (0)
{
// if (reset_frame==0 && steps<100){
//// printf("steps %d, seconds %d, steps/seconds %d\n", steps,seconds,steps/seconds);
char filename[100];
sprintf(filename, "%s_%d_%d.txt", "states", reset_frame, steps);
btSoftBodyHelpers::writeState(filename, psb);
}
if (sim_time + reset_frame * 0.05 >= 5) exit(0);
float internalTimeStep = 1. / 240.f;
// float internalTimeStep = 0.1f;
m_dynamicsWorld->stepSimulation(deltaTime, deltaTime / internalTimeStep, internalTimeStep);
}
void addCloth(const btVector3& origin);
virtual void renderScene()
{
CommonDeformableBodyBase::renderScene();
btDeformableMultiBodyDynamicsWorld* deformableWorld = getDeformableDynamicsWorld();
for (int i = 0; i < deformableWorld->getSoftBodyArray().size(); i++)
{
btSoftBody* psb = (btSoftBody*)deformableWorld->getSoftBodyArray()[i];
{
btSoftBodyHelpers::DrawFrame(psb, deformableWorld->getDebugDrawer());
btSoftBodyHelpers::Draw(psb, deformableWorld->getDebugDrawer(), deformableWorld->getDrawFlags());
}
}
}
};
void LoadDeformed::initPhysics()
{
m_guiHelper->setUpAxis(1);
///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
m_broadphase = new btDbvtBroadphase();
btDeformableBodySolver* deformableBodySolver = new btDeformableBodySolver();
btDeformableMultiBodyConstraintSolver* sol = new btDeformableMultiBodyConstraintSolver();
sol->setDeformableSolver(deformableBodySolver);
m_solver = sol;
m_dynamicsWorld = new btDeformableMultiBodyDynamicsWorld(m_dispatcher, m_broadphase, sol, m_collisionConfiguration, deformableBodySolver);
btVector3 gravity = btVector3(0, -9.8, 0);
m_dynamicsWorld->setGravity(gravity);
getDeformableDynamicsWorld()->getWorldInfo().m_gravity = gravity;
getDeformableDynamicsWorld()->getWorldInfo().m_sparsesdf.setDefaultVoxelsz(0.25);
m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
{
///create a ground
btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(150.), btScalar(2.5), btScalar(150.)));
groundShape->setMargin(0.02);
m_collisionShapes.push_back(groundShape);
btTransform groundTransform;
groundTransform.setIdentity();
groundTransform.setOrigin(btVector3(0, -3.5, 0));
groundTransform.setRotation(btQuaternion(btVector3(1, 0, 0), SIMD_PI * 0));
btScalar mass(0.);
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0, 0, 0);
if (isDynamic)
groundShape->calculateLocalInertia(mass, localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
body->setFriction(4);
//add the ground to the dynamics world
m_dynamicsWorld->addRigidBody(body);
}
addCloth(btVector3(0, 1, 0));
getDeformableDynamicsWorld()->setImplicit(false);
getDeformableDynamicsWorld()->setLineSearch(false);
m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
}
void LoadDeformed::addCloth(const btVector3& origin)
// create a piece of cloth
{
const btScalar s = 0.6;
const btScalar h = 0;
psb = btSoftBodyHelpers::CreatePatch(getDeformableDynamicsWorld()->getWorldInfo(), btVector3(-s, h, -2 * s),
btVector3(+s, h, -2 * s),
btVector3(-s, h, +2 * s),
btVector3(+s, h, +2 * s),
15, 30,
0, true, 0.0);
psb->getCollisionShape()->setMargin(0.02);
psb->generateBendingConstraints(2);
psb->setTotalMass(.5);
psb->m_cfg.kKHR = 1; // collision hardness with kinematic objects
psb->m_cfg.kCHR = 1; // collision hardness with rigid body
psb->m_cfg.kDF = 0.1;
psb->rotate(btQuaternion(0, SIMD_PI / 2, 0));
btTransform clothTransform;
clothTransform.setIdentity();
clothTransform.setOrigin(btVector3(0, 0.2, 0) + origin);
psb->transform(clothTransform);
b3BulletDefaultFileIO fileio;
char absolute_path[1024];
char filename[100];
sprintf(filename, "/Users/fuchuyuan/Documents/mybullet/build_cmake/examples/ExampleBrowser/states_0_%d.txt", reset_frame);
fileio.findResourcePath(filename, absolute_path, 1024);
btAlignedObjectArray<btVector3> qs;
btAlignedObjectArray<btVector3> vs;
CustomSoftBodyHelper::loadDeformableState(qs, vs, absolute_path, &fileio);
if (reset_frame > 0)
psb->updateState(qs, vs);
psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD;
psb->m_cfg.collisions |= btSoftBody::fCollision::SDF_MDF;
psb->m_cfg.collisions |= btSoftBody::fCollision::SDF_RDF;
// psb->m_cfg.collisions |= btSoftBody::fCollision::SDF_RDN;
psb->setCollisionFlags(0);
psb->setCacheBarycenter(true);
getDeformableDynamicsWorld()->addSoftBody(psb);
psb->setSelfCollision(false);
btDeformableMassSpringForce* mass_spring = new btDeformableMassSpringForce(2, 0.2, true);
psb->setSpringStiffness(4);
getDeformableDynamicsWorld()->addForce(psb, mass_spring);
m_forces.push_back(mass_spring);
btVector3 gravity = btVector3(0, -9.8, 0);
btDeformableGravityForce* gravity_force = new btDeformableGravityForce(gravity);
getDeformableDynamicsWorld()->addForce(psb, gravity_force);
// getDeformableDynamicsWorld()->setUseProjection(true);
m_forces.push_back(gravity_force);
}
void LoadDeformed::exitPhysics()
{
//cleanup in the reverse order of creation/initialization
removePickingConstraint();
//remove the rigidbodies from the dynamics world and delete them
int i;
for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_dynamicsWorld->removeCollisionObject(obj);
delete obj;
}
// delete forces
for (int j = 0; j < m_forces.size(); j++)
{
btDeformableLagrangianForce* force = m_forces[j];
delete force;
}
m_forces.clear();
//delete collision shapes
for (int j = 0; j < m_collisionShapes.size(); j++)
{
btCollisionShape* shape = m_collisionShapes[j];
delete shape;
}
m_collisionShapes.clear();
delete m_dynamicsWorld;
delete m_solver;
delete m_broadphase;
delete m_dispatcher;
delete m_collisionConfiguration;
}
class CommonExampleInterface* LoadDeformedCreateFunc(struct CommonExampleOptions& options)
{
return new LoadDeformed(options.m_guiHelper);
}
|
<reponame>fochoao/cpython<filename>Lib/site-packages/hackedit/app/main_window.py
"""
This module contains the main window implementation.
The main window is a windows with a set of preset objects (tab widget, file
system tree view) that is extended by plugins.
"""
import json
import traceback
import logging
import os
try:
import psutil
except ImportError:
psutil = None # optional dependency.
from PyQt5 import QtCore, QtGui, QtPrintSupport, QtWidgets
from pyqode.core import modes, panels
from pyqode.core.api import TextHelper, ColorScheme, CodeEdit
from pyqode.core.widgets import EncodingsContextMenu, MenuRecentFiles
from pyqode.core.widgets import GenericCodeEdit, TextCodeEdit
from hackedit.app import settings
from hackedit.app.project import ProjectExplorer
from hackedit.api import system, shortcuts, special_icons
from hackedit.api.events import Event, WARNING, ExceptionEvent
from hackedit.api.project import load_user_config, save_user_config
from hackedit.api.widgets import ClickableLabel, FileIconProvider
from hackedit.app import common, events, generic_pyqode_server
from hackedit.app.dialogs.preferences import DlgPreferences
from hackedit.app.docks import DockWidgetsManager
from hackedit.app.forms import main_window_ui
from hackedit.app.tasks import TaskManagerWidget
def _logger():
return logging.getLogger(__name__)
#: The editor page, which contains our splittable tab widget
PAGE_EDITOR = 0
#: Index of the page shown when no editor is open (show explanations about
#: how to open files in the IDE)
PAGE_EXPLANATIONS = 1
GenericCodeEdit.DEFAULT_SERVER = generic_pyqode_server.__file__
TextCodeEdit.DEFAULT_SERVER = generic_pyqode_server.__file__
class MainWindow(QtWidgets.QMainWindow):
#: Signal emitted when window has been closed.
closed = QtCore.pyqtSignal(QtWidgets.QMainWindow)
current_tab_changed = QtCore.pyqtSignal(QtWidgets.QWidget)
editor_created = QtCore.pyqtSignal(QtWidgets.QWidget)
editor_detached = QtCore.pyqtSignal(QtWidgets.QWidget, QtWidgets.QWidget)
editor_loaded = QtCore.pyqtSignal(QtWidgets.QWidget)
project_added = QtCore.pyqtSignal(str)
current_project_changed = QtCore.pyqtSignal(str)
project_files_available = QtCore.pyqtSignal()
about_to_open_tab = QtCore.pyqtSignal(str)
document_saved = QtCore.pyqtSignal(str, str)
state_restored = QtCore.pyqtSignal()
file_renamed = QtCore.pyqtSignal(str, str)
file_deleted = QtCore.pyqtSignal(str)
@property
def task_manager(self):
"""
Gets the task manager instance.
:return: hackedit.app.tasks.TaskManager
"""
return self.task_manager_widget.task_manager
@property
def current_tab(self):
"""
Gets the current tab (widget).
:param self: parent window.
:return: QWidget
"""
return self._current_tab
@property
def projects(self):
"""
Gets the list of open projects.
Remember that when you open a single file, the IDE actually opens the
parent folder instead and open the file in a new tab.
:return: list of str
"""
return self._open_projects
@property
def current_project(self):
"""
Gets the current project/file path.
:return: str
"""
return self._current_folder
@current_project.setter
def current_project(self, value):
self._current_folder = value
@property
def tab_widget(self):
"""
Gets a reference to the main tab widget.
:return: pyqode.core.widgets.SplittableCodeEditTabWidget
"""
return self._ui.tabs
@property
def ui(self):
return self._ui
def __init__(self, app, path, workspace):
"""
:param app: reference to the application instance
:param path: main path (linked paths will be open automatically).
"""
super().__init__()
self.setAcceptDrops(True)
self._docks_to_restore = []
self._toolbars = []
self._open_projects = []
self._current_tab = None
#: Reference to the application instance.
self.app = app
self.app.active_window = self
#: List of plugins added to the window
self.plugins = []
#: Workspace definition
self.workspace = workspace
#: Dock widgets manager
self._dock_manager = None
#: List of dock widget currently displayed
self._dock_widgets = []
#: User interface definition
self._ui = main_window_ui.Ui_MainWindow()
self._ui.setupUi(self)
self._ui.stackedWidget.setCurrentIndex(1)
if not QtGui.QIcon.hasThemeIcon('application-exit'):
self._ui.action_quit.setIcon(QtGui.QIcon.fromTheme('window-close'))
self.addActions(self._ui.mnu_file.actions())
self.addActions(self._ui.mnu_edit.actions())
self.addActions(self._ui.mnu_help.actions())
self.addActions(self._ui.mnu_view.actions())
self.setWindowIcon(QtGui.QIcon.fromTheme(
'hackedit', QtGui.QIcon(':/icons/hackedit_128.png')))
self._setup_actions()
#: Menus map
self._menus = {
'File': self._ui.mnu_file,
'Edit': self._ui.mnu_edit,
'View': self._ui.mnu_view,
'Tools': self._ui.menuTools,
'?': self._ui.mnu_help
}
self._menus_list = [
self.ui.mnu_file,
self._ui.mnu_edit,
self._ui.menuTools,
self._ui.mnu_view,
self._ui.mnu_help
]
# setup application menu button
menu_button = QtWidgets.QToolButton(self)
menu_button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
menu_button.setIcon(special_icons.app_menu())
menu_button.setToolTip('Application menu')
self.menu_button = menu_button
self._update_menu_button()
# setup recent files menu
self._mnu_recents = MenuRecentFiles(
self._ui.mnu_file,
recent_files_manager=self.app.get_recent_files_manager(),
clear_icon=QtGui.QIcon.fromTheme('edit-clear'),
icon_provider=FileIconProvider())
self._mnu_recents.setTitle('Recents')
self._mnu_recents.menuAction().setIcon(
QtGui.QIcon.fromTheme('document-open-recent'))
self._ui.mnu_file.insertMenu(self._ui.mnu_file.actions()[3],
self._mnu_recents)
self._current_folder = ''
self._dock_manager = DockWidgetsManager(self)
self._connect_slots()
self.update_mnu_view()
self.task_manager_widget = TaskManagerWidget(self)
self.add_statusbar_widget(self.task_manager_widget)
self._setup_status_bar_widgets()
self.notifications = events.Manager(self)
self.open_folder(path)
self.project_explorer = ProjectExplorer(self)
self.project_explorer.activate()
self.project_explorer.apply_preferences()
self._update_mem_label_timer = QtCore.QTimer()
self._update_mem_label_timer.setInterval(500)
self._update_mem_label_timer.timeout.connect(self._update_mem_label)
self._update_mem_label_timer.start()
self._update_mem_label()
def setup_menu_toolbar(self):
empty = QtWidgets.QWidget()
empty.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Preferred)
self.toolbar_menu = QtWidgets.QToolBar(self)
self.toolbar_menu.setObjectName('toolBarAppMenu')
self.toolbar_menu.setMovable(False)
self.toolbar_menu.addWidget(empty)
self.toolbar_menu.addWidget(self.menu_button)
self.addToolBar(self.toolbar_menu)
self._update_menu_visibility()
def __repr__(self):
return 'MainWindow(path=%r)' % self.projects
# -------------------------------------------------------------------------
# Public API
# -------------------------------------------------------------------------
def open_folder(self, path):
"""
Adds a path to the window.
:param path: path to add: file or directory
"""
if path in self.projects or not os.path.exists(path):
# already open
return
_logger().debug('open folder: %r', path)
self._open_projects.append(path)
self.project_added.emit(path)
self._current_folder = path
linked_paths = self._get_linked_paths()
if len(self.projects) > 1:
# save the additional paths in project configs, that way
# they will be open together next time.
linked_paths.append(path)
self._save_linked_paths(linked_paths)
else:
# read possible linked paths and open them
for pth in linked_paths:
self.open_folder(pth)
self._save_linked_paths(linked_paths)
self.on_current_tab_changed(None)
hackedit_path = os.path.join(path, '.hackedit')
try:
os.makedirs(hackedit_path)
except FileExistsError:
_logger().debug('failed to create .hackedit folder at %r, '
'directory already exits', path)
def remove_folder(self, path):
try:
self._open_projects.remove(path)
except ValueError:
_logger().warn('failed to remove folder %r', path)
def get_menu(self, menu_name):
"""
Gets a top level menu.
The menu is implicitly created if it did not exist.
:param self: window to get a QMenu from
:param menu_name: Name of the menu to retrieve.
:return: QtWidgets.QMenu
"""
try:
return self._menus[menu_name.replace('&', '')]
except KeyError:
# create a new menu.
_logger().debug('creating menu %r on %r', menu_name, self)
mnu = QtWidgets.QMenu(menu_name, self.menuBar())
self.menuBar().insertMenu(self._menus['Tools'].menuAction(), mnu)
self._menus[menu_name.replace('&', '')] = mnu
tools_menu = self._menus['Tools']
i = self._menus_list.index(tools_menu)
self._menus_list.insert(i, mnu)
self._update_menu_button()
return mnu
def get_toolbar(self, name, title):
"""
Gets a toolbar.
The toolbar is implicitly created if it did not exist.
:param name: Name of the toolbar
:param title: Title of the toolbar (used when creating the toobar).
:return: QToolBar
"""
children = self.findChildren(QtWidgets.QToolBar, name)
if children:
toolbar = children[0]
else:
toolbar = QtWidgets.QToolBar(title)
toolbar.setObjectName(name)
self.addToolBar(toolbar)
return toolbar
def add_dock_widget(self, widget, title, icon, area, special):
"""
Add a dock widget to the window.
You pass a widget that is automatically wrapped into a QDockWidget.
:param self: window where the dock widget must be added
:param widget: the widget to dock (QWidget, not a QDockWidget)
:param title: dock widget title
:param icon: dock widget icon. Default is None
:param area: dock widget area. Default is bottom area
:param no_button: True to avoid showing a button. Default is False
:return The dock widget instance that was added to the window.
"""
_logger().debug('adding dock widget %r to %r', title, self)
class DockWidget(QtWidgets.QDockWidget):
"""
Forces focus on the child widget when the dock is shown.
"""
def showEvent(self, ev):
super().showEvent(ev)
self.widget().setFocus()
if area is None:
area = QtCore.Qt.BottomDockWidgetArea
if system.PLASMA_DESKTOP:
title = title.replace('&', '')
title = title[:-1] + '&' + title[-1]
dock = DockWidget(title, self)
dock.setShortcutEnabled(False)
dock.setObjectName('dock%s' % title)
dock.setWidget(widget)
if icon:
dock.setWindowIcon(icon)
dock.setShortcutEnabled(0, False)
self.addDockWidget(area, dock, special=special)
return dock
def get_dock_widget(self, title):
"""
Returns the dock widget whose windowTitle match `title`.
:param self: parent window.
:param title: title of the dock widget to get.
:return: QDockWidget
"""
for dock in self._dock_widgets:
if dock.windowTitle().replace('&', '') == title:
return dock
return None
def get_project_treeview(self):
"""
Gets the project treeview.
:return: pyqode.core.widgets.FileSystemTreeView
"""
return self.project_explorer.view
def open_file(self, path, line=None, column=0):
"""
Opens a new tab in the window (and optionally goes to the
specified line).
:param path: path to open
:param line: line to go to (optional).
:param line: column to go to (optional).
"""
if path is None:
return
path = os.path.normpath(path)
if not os.path.exists(path) or os.path.isdir(path):
return None
self.about_to_open_tab.emit(path)
color_scheme = settings.color_scheme()
try:
tab = self._ui.tabs.open_document(
path, encoding=settings.default_encoding(),
replace_tabs_by_spaces=settings.convert_tabs(),
clean_trailing_whitespaces=settings.
clean_trailing_whitespaces(),
safe_save=settings.safe_save(),
restore_cursor_position=settings.restore_cursor(),
preferred_eol=settings.eol_convention(),
autodetect_eol=settings.autodetect_eol(),
show_whitespaces=settings.show_whitespaces(),
color_scheme=color_scheme)
except Exception as e:
tab = None
tb = traceback.format_exc()
_logger().exception('failed to open file')
self.notifications.add(ExceptionEvent(
_('Failed to open file: %s') % path,
_('An unhandled exception occured while opening file: %r') % e,
e, tb=tb), show_balloon=False)
else:
_logger().debug('document opened: %s', path)
try:
tab.remove_action(tab.action_goto_line)
except AttributeError:
_logger().debug('cannot remove action goto line from editor '
'%r, not a CodeEdit', tab)
else:
assert isinstance(tab, CodeEdit)
tab.add_action(self.project_explorer.action_goto_line)
try:
mode = tab.modes.get('FileWatcherMode')
except (KeyError, AttributeError):
_logger().debug('no file watcher on widget %r', tab)
else:
# enable filewatcher autoreload
mode.auto_reload = True
if line is not None:
QtWidgets.qApp.processEvents()
try:
TextHelper(tab).goto_line(line, column)
except AttributeError:
_logger().debug('failed to go to line %d in %r' % (
line, tab.file.path))
return tab
def add_statusbar_widget(self, widget, with_separator=True, first=False):
"""
Add a widget to the status bar.
The associated widget action is set on the widget as "toolbar_action"
:param widget: widget to add
:param with_separator: true to add a separator before the widget
:param first: True to add the widget at the beggining of the bar
instead of the end.
:return: the associated widget action (use it for show/hide).
"""
action = self._dock_manager.add_bottom_widget(
widget, with_separator, first)
widget.toolbar_action = action
return action
def get_plugin_instance(self, plugin_class):
"""
Returns the plugin instance that match a given plugin class.
:param self: parent window
:param plugin_class: Plugin class
"""
for p in self.plugins:
if isinstance(p, plugin_class):
return p
return None
def save_current(self):
"""
Saves the current tab.
"""
try:
self._ui.tabs.save_current()
except Exception as e:
self.notifications.add(Event(
_('Failed to save file'), str(e), level=WARNING),
show_balloon=False)
def save_current_as(self):
"""
Saves the current tab as.
"""
try:
self._ui.tabs.save_current_as()
except Exception as e:
self.notifications.add(Event(
_('Failed to save file'), str(e), level=WARNING),
show_balloon=False)
else:
self.update_title()
def save_all(self):
"""
Saves all open tabs
"""
try:
self._ui.tabs.save_all()
except Exception as e:
self.notifications.add(Event(
_('Failed to save file'), str(e), level=WARNING),
show_balloon=False)
def update_mnu_recents(self):
"""
Updates the recent files menu
"""
self._mnu_recents.update_actions()
def update_mnu_view(self):
"""
Updates the list of window show in the view menu.
"""
self._ui.mnu_windows.clear()
self.window_group = QtWidgets.QActionGroup(self._ui.mnu_windows)
open_windows = self.app.get_open_windows()
_logger().debug('updating mnu_view: %r', open_windows)
for w in open_windows:
a = self._ui.mnu_windows.addAction(w.windowTitle())
assert isinstance(a, QtWidgets.QAction)
a.setCheckable(True)
a.setChecked(w == self)
self.window_group.addAction(a)
a.setData(w)
self.window_group.triggered.connect(self._on_window_action_triggered)
def update_title(self):
"""
Update the window title based on the project name and the
current editor:
PROJ_NAME - [current file path]
"""
tab = self.current_tab
if tab:
# prj mode
root_path = self.current_project
root = os.path.split(root_path)[1]
fpath = tab.file.path
self.setWindowTitle('%s - [%s]' % (root, fpath))
else:
root_path = self.current_project
root = os.path.split(root_path)[1]
self.setWindowTitle('%s' % (root))
def restore_state(self, pth=None):
"""
Restore the window state (geometry and state).
If settings.restore_session is True, it restore open files.
"""
ret_val = False
if pth is None:
pth = self.projects[0]
key = '%s_' % pth.replace('\\', '_').replace('/', '_')
geometry = QtCore.QSettings().value('_window/geometry_' + key)
if geometry:
ret_val = True
self.setGeometry(geometry)
_logger().debug('restoreGeometry: OK')
self.restoreState(QtCore.QSettings().value(
'_window/state_' + key, b''))
_logger().debug('restoreState: OK')
if not self._ui.menuTools.actions():
self._ui.menubar.removeAction(self._ui.menuTools.menuAction())
self._files_to_restore = QtCore.QSettings().value(
'_session/files_' + key, [])
self._restore_index = int(QtCore.QSettings().value(
'_session/index_' + key, 0))
QtWidgets.qApp.processEvents()
if settings.restore_session():
_logger().debug('restoring session')
while self._files_to_restore:
_logger().debug('restoring file')
self._restore_file()
_logger().debug('file restored')
QtWidgets.qApp.processEvents()
if self.notifications.has_errors() or \
self.notifications.has_warnings():
self.notifications.show()
self.state_restored.emit()
QtWidgets.qApp.processEvents()
return ret_val
def apply_preferences(self):
"""
Applies the preferences stored in QSettings.
This method will apply preferences on each editor and on each
plugin.
"""
self.project_explorer.apply_preferences()
self._dock_manager.update_style()
self._apply_shortcuts()
for toolbar in self._toolbars:
s = settings.toolbar_icon_size()
toolbar.setIconSize(QtCore.QSize(s, s))
for editor in self.tab_widget.widgets():
try:
self._apply_editor_preferences(editor)
except AttributeError:
# not a CodeEdit
_logger().debug('failed to apply preferences on editor %r',
editor)
for plugin in self.plugins:
plugin.apply_preferences()
if settings.widescreen_layout():
self.setCorner(
QtCore.Qt.TopLeftCorner, QtCore.Qt.LeftDockWidgetArea)
self.setCorner(
QtCore.Qt.TopRightCorner, QtCore.Qt.RightDockWidgetArea)
self.setCorner(
QtCore.Qt.BottomLeftCorner, QtCore.Qt.LeftDockWidgetArea)
self.setCorner(
QtCore.Qt.BottomRightCorner, QtCore.Qt.RightDockWidgetArea)
else:
self.setCorner(
QtCore.Qt.TopLeftCorner, QtCore.Qt.LeftDockWidgetArea)
self.setCorner(
QtCore.Qt.TopRightCorner, QtCore.Qt.RightDockWidgetArea)
self.setCorner(
QtCore.Qt.BottomLeftCorner, QtCore.Qt.BottomDockWidgetArea)
self.setCorner(
QtCore.Qt.BottomRightCorner, QtCore.Qt.BottomDockWidgetArea)
# -------------------------------------------------------------------------
# Private API (+ overridden methods)
# -------------------------------------------------------------------------
@staticmethod
def dragEnterEvent(event):
mime = event.mimeData()
if mime is None or not mime.hasUrls():
return
event.accept()
def dropEvent(self, event):
mime = event.mimeData()
if mime is None or not mime.hasUrls():
return
for url in mime.urls():
path = url.path()
if system.WINDOWS and path.startswith('/'):
path = path[1:]
if os.path.isfile(path):
# open a new editor
self.open_file(path)
else:
# open a new window
self.app.open_path(path)
@staticmethod
def createPopupMenu():
# prevent the window to create its standard popup. That menu
# is already visible in View->Tools menu.
return None
def addDockWidget(self, area, dock, orientation=None, special=False):
self._dock_manager.add_dock_widget(dock, area, special)
if orientation:
super().addDockWidget(area, dock, orientation)
else:
super().addDockWidget(area, dock)
self._dock_widgets.append(dock)
def removeDockWidget(self, dock):
if dock is None:
return
super().removeDockWidget(dock)
self._dock_manager.remove_dock_widget(dock)
self._dock_widgets.remove(dock)
def addToolBar(self, *args):
for arg in args:
if isinstance(arg, QtWidgets.QToolBar):
size = settings.toolbar_icon_size()
arg.setIconSize(QtCore.QSize(size, size))
self._toolbars.append(arg)
break
super().addToolBar(*args)
def closeEvent(self, event):
if self._ui:
_logger().debug('close event')
if self.app.window_count == 1 and settings.confirm_app_exit():
answer = QtWidgets.QMessageBox.question(
self, _('Confirm exit'),
_('Are you sure you want to exit HackEdit?'),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.Yes)
if answer == QtWidgets.QMessageBox.No:
event.ignore()
return
current_index, files = self.get_session_info()
self.save_state(current_index, files)
accept = self._close_documents(event)
event.setAccepted(accept)
if event.isAccepted():
for plugin in self.plugins:
try:
plugin.close()
except AttributeError:
_logger().debug('plugin %r has not attribute close',
plugin)
finally:
plugin.window = None
self.plugins.clear()
self.closed.emit(self)
self._ui = None
self.task_manager.terminate()
self.notifications.close()
self.notifications = None
self.task_manager_widget.close()
self._dock_manager.window = None
self.project_explorer.close()
if self.app.last_window == self:
self.app.last_window = None
self.app = None
self.setParent(None)
def event(self, e):
if e.type() == QtCore.QEvent.WindowActivate and self.app:
self.app.active_window = self
return super().event(e)
def showEvent(self, ev):
super().showEvent(ev)
if self.task_manager.count:
self.task_manager_widget.show()
@staticmethod
def _setup_dark_editor(editor):
try:
panel = editor.panels.get('FoldingPanel')
except KeyError:
_logger().debug('no FoldingPanel on widget %r', editor)
else:
if settings.dark_theme():
panel.native_look = False
try:
mode = editor.modes.get('OccurrencesHighlighterMode')
except KeyError:
_logger().debug('no OccurrencesHighlighterMode on widget %r',
editor)
else:
mode.background = QtGui.QColor('#344134')
mode.foregound = None
try:
mode = editor.modes.get('SymbolMatcherMode')
except KeyError:
_logger().debug('no SymbolMatcherMode on widget %r', editor)
else:
mode.match_background = QtGui.QColor('#344134')
mode.match_foreground = QtGui.QColor('yellow')
@staticmethod
def _setup_native_editor(editor):
try:
panel = editor.panels.get('FoldingPanel')
except KeyError:
_logger().debug('no FoldingPanel on widget %r', editor)
else:
panel.native_look = True
try:
mode = editor.modes.get('OccurrencesHighlighterMode')
except KeyError:
_logger().debug('no OccurrencesHighlighterMode on widget %r',
editor)
else:
mode.background = QtGui.QColor('#CCFFCC')
mode.foregound = None
try:
mode = editor.modes.get('SymbolMatcherMode')
except KeyError:
_logger().debug('no SymbolMatcherMode on widget %r', editor)
else:
mode.match_background = QtGui.QColor('#CCFFCC')
mode.match_foreground = QtGui.QColor('red')
def get_session_info(self):
widgets = self._ui.tabs.widgets()
files = []
current_index = 0
for i, w in enumerate(widgets):
try:
# widget that have this attribute set won't be restored when
# restoring session
w.dont_remember
except AttributeError:
try:
path = w.file.path
except AttributeError:
_logger().debug('widget %r has not attribute file.path', w)
else:
files.append(path)
if path == self._ui.tabs.current_widget().file.path:
current_index = i
else:
continue
return current_index, files
def _close_documents(self, event=None):
if event is None:
event = QtGui.QCloseEvent()
event.setAccepted(True)
self._ui.tabs.closeEvent(event)
accept = event.isAccepted()
for dock in self._dock_widgets:
dock.widget().closeEvent(event)
if not event.isAccepted():
accept = False
return accept
def save_state(self, current_index, files):
if self._docks_to_restore:
self._restore_children()
pth = self.projects[0]
key = '%s_' % pth.replace('\\', '_').replace('/', '_')
QtCore.QSettings().setValue('_session/files_' + key, files)
QtCore.QSettings().setValue('_session/index_' + key, int(current_index))
QtCore.QSettings().setValue('_window/state_' + key, self.saveState())
QtCore.QSettings().setValue('_window/geometry_' + key, self.geometry())
def _restore_file(self):
path = self._files_to_restore.pop(0)
self.open_file(path)
self._ui.tabs.main_tab_widget.setCurrentIndex(self._restore_index)
def _setup_status_bar_widgets(self):
if psutil:
self.lbl_memory = QtWidgets.QLabel()
self.lbl_memory.setText('0 MiB')
self.lbl_cursor = ClickableLabel()
self.lbl_cursor.setText('1:1', False)
self.lbl_cursor.setAlignment(
QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.lbl_cursor.clicked.connect(self._on_label_cursor_clicked)
self.lbl_encoding = ClickableLabel()
self.lbl_encoding.setText(_('n/a'), False)
self.lbl_encoding.setAlignment(
QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.lbl_encoding.clicked.connect(self._on_label_encodings_clicked)
def setup_status_bar(self):
self.add_statusbar_widget(self.lbl_cursor)
self.add_statusbar_widget(self.lbl_encoding)
if psutil:
self.add_statusbar_widget(self.lbl_memory)
def _connect_slots(self):
self._ui.tabs.editor_created.connect(self.editor_created.emit)
self._ui.tabs.document_opened.connect(self.editor_loaded.emit)
self._ui.tabs.document_saved.connect(self.document_saved.emit)
self._ui.tabs.editor_created.connect(self._apply_editor_preferences)
self._ui.action_new.triggered.connect(self._on_new_triggered)
self._ui.action_help.triggered.connect(self._show_not_implemented_msg)
self._ui.action_check_for_update.triggered.connect(
self._show_not_implemented_msg)
self._ui.tabs.current_changed.connect(self.on_current_tab_changed)
self._ui.action_close.triggered.connect(self.close)
self._ui.action_quit.triggered.connect(QtWidgets.qApp.closeAllWindows)
self._ui.action_save.triggered.connect(self.save_current)
self._ui.action_save_as.triggered.connect(self.save_current_as)
self._ui.action_save_all.triggered.connect(self.save_all)
self._ui.tabs.last_tab_closed.connect(self._on_last_tab_closed)
self._ui.action_report_bug.triggered.connect(self._report_bug)
self._ui.action_about.triggered.connect(self._show_about)
self._ui.action_check_for_update.triggered.connect(
self._check_for_update)
self._ui.action_preferences.triggered.connect(self._edit_preferences)
self._mnu_recents.open_requested.connect(
self._on_open_recent_requested)
self._ui.tabs.tab_detached.connect(self._on_tab_detached)
self._ui.tabs.tab_detached.connect(self.editor_detached.emit)
self._ui.a_print.triggered.connect(self._print)
def _show_not_implemented_msg(self):
common.not_implemented_action(self)
def _on_label_cursor_clicked(self):
if self.current_tab:
self.project_explorer.action_goto_line.triggered.emit()
def _on_label_encodings_clicked(self):
if self.current_tab:
mnu = EncodingsContextMenu(parent=self.current_tab)
self.current_tab.remove_menu(mnu)
mnu.reload_requested.connect(self._update_encoding_label)
mnu.exec_(self.lbl_encoding.mapToGlobal(QtCore.QPoint(0, 0)))
def _update_encoding_label(self, encoding):
from pyqode.core.api import ENCODINGS_MAP
try:
self.lbl_encoding.setText(ENCODINGS_MAP[encoding][0], False)
except KeyError:
self.lbl_encoding.setText(encoding, False)
def _setup_actions(self):
self._ui.action_about.setMenuRole(QtWidgets.QAction.AboutRole)
self._ui.action_preferences.setMenuRole(
QtWidgets.QAction.PreferencesRole)
self._ui.action_quit.setMenuRole(QtWidgets.QAction.QuitRole)
self._ui.action_check_for_update.setMenuRole(
QtWidgets.QAction.ApplicationSpecificRole)
def _get_linked_paths(self):
data = load_user_config(self.projects[0])
try:
linked_paths = data['linked_paths']
except KeyError:
return []
else:
ret_val = []
for p in linked_paths:
if os.path.exists(p):
ret_val.append(p)
return ret_val
def _save_linked_paths(self, linked_paths):
data = load_user_config(self.projects[0])
data['linked_paths'] = linked_paths
try:
save_user_config(self.projects[0], data)
except PermissionError:
_logger().warn('failed to save linked paths, permission error')
def _on_window_action_triggered(self, action):
_logger().debug('window action triggered')
self.app.active_window = action.data()
def _on_last_tab_closed(self):
_logger().debug('last tab closed')
self.on_current_tab_changed(None)
def _on_open_recent_requested(self, path):
_logger().debug('open recent requested')
self.app.open_path(path, sender=self)
# Private slots
def _on_new_triggered(self):
common.create_new(self.app, self, self.current_project)
@QtCore.pyqtSlot(QtWidgets.QWidget)
def on_current_tab_changed(self, tab):
self._current_tab = tab
_logger().debug('current tab changed: %r', tab)
self.current_tab_changed.emit(tab)
if tab:
self._ui.menuActive_editor.clear()
self._ui.menuActive_editor.addActions(
[a for a in tab.actions() if not hasattr(
a, 'dont_show_in_edit_menu')])
self._ui.menuActive_editor.addSeparator()
try:
for m in tab.menus():
self._ui.menuActive_editor.addMenu(m)
except AttributeError:
# not a code edit
_logger().debug('failed to add editor menus to Edit -> Active '
'editor, not a CodeEdit instance')
self._ui.stackedWidget.setCurrentIndex(PAGE_EDITOR)
try:
self._update_cursor_label()
tab.cursorPositionChanged.connect(
self._update_cursor_label, QtCore.Qt.UniqueConnection)
except TypeError:
# already connected
_logger().debug('failed to connect to cursorPositionChanged '
'signal, already connected')
except AttributeError:
# not a code editor widget
self.lbl_cursor.setText('n/a', False)
try:
self._update_encoding_label(tab.file.encoding)
except AttributeError:
self.lbl_encoding.setText('n/a', False)
else:
if self._ui:
self._ui.menuActive_editor.clear()
self._ui.stackedWidget.setCurrentIndex(PAGE_EXPLANATIONS)
try:
self.lbl_encoding.setText('n/a', False)
self.lbl_cursor.setText('n/a', False)
except AttributeError:
_logger().debug('failed to reset cursor infos labels, '
'widget deleted (window is closing...)')
@QtCore.pyqtSlot()
def on_action_open_triggered(self):
""" Opens a project directory"""
common.open_folder(self, self.app)
@QtCore.pyqtSlot()
def on_action_open_file_triggered(self):
"""
Opens a file.
"""
path, _filter = QtWidgets.QFileDialog.getOpenFileName(
self, _('Open file'), settings.last_open_dir())
if path:
settings.set_last_open_dir(os.path.dirname(path))
self.open_file(path)
@QtCore.pyqtSlot()
def on_a_fullscreen_triggered(self):
state = self._ui.a_fullscreen.isChecked()
if state:
self.showFullScreen()
else:
self.showNormal()
@QtCore.pyqtSlot()
def on_a_menu_triggered(self):
state = self._ui.a_menu.isChecked()
settings.set_show_menu(state)
self._update_menu_visibility()
@QtCore.pyqtSlot()
def _report_bug(self):
common.report_bug(self)
@QtCore.pyqtSlot()
def _show_about(self):
common.show_about(self)
@QtCore.pyqtSlot()
def _check_for_update(self):
common.check_for_update(self)
def _restore_children(self):
for dock in self._docks_to_restore:
dock.show()
self._docks_to_restore[:] = []
for tb in self._toolbars:
if self.toolBarArea(tb) == QtCore.Qt.TopToolBarArea:
tb.show()
def _hide_children(self):
for dock in self._dock_manager.dock_widgets():
if dock.isVisible():
self._docks_to_restore.append(dock)
dock.hide()
for tb in self._toolbars:
if self.toolBarArea(tb) == QtCore.Qt.TopToolBarArea:
tb.hide()
def _edit_preferences(self):
DlgPreferences.edit_preferences(self, self.app)
def _apply_editor_plugin_preferences(self, editor):
for plugin in self.app.plugin_manager.editor_plugins:
if plugin.get_editor_class() == editor.__class__:
try:
plugin.apply_specific_preferences(editor)
except Exception:
_logger().exception('failed to apply specific preferences')
finally:
break
def _apply_shortcuts(self):
# File
self._ui.action_new.setShortcut(shortcuts.get(
'New', _('New'), 'Ctrl+N'))
self._ui.action_open.setShortcut(shortcuts.get(
'Open directory', _('Open directory'), 'Ctrl+O'))
self._ui.action_save.setShortcut(shortcuts.get(
'Save', _('Save'), 'Ctrl+S'))
self._ui.action_save_as.setShortcut(shortcuts.get(
'Save as', _('Save as'), 'Ctrl+Shift+S'))
self._ui.action_save_all.setShortcut(shortcuts.get(
'Save all', _('Save all'), 'Ctrl+Alt+S'))
self._ui.action_open_file.setShortcut(shortcuts.get(
'Open file', _('Open file'), 'Ctrl+Shift+O'))
self._ui.action_close.setShortcut(shortcuts.get(
'Close window', _('Close window'), 'Ctrl+Shift+Q'))
self._ui.action_quit.setShortcut(shortcuts.get(
'Quit', _('Quit'), 'Ctrl+Q'))
# Edit
self._ui.action_preferences.setShortcut(shortcuts.get(
'Preferences', _('Preferences'), 'Ctrl+,'))
for editor in self.tab_widget.widgets(True):
if not isinstance(editor, CodeEdit):
continue
self._apply_editor_shortcuts(editor)
# View
self._ui.a_fullscreen.setShortcut(shortcuts.get(
'Toggle fullscreen', _('Toggle fullscreen'), 'Ctrl+F11'))
self._ui.a_menu.setShortcut(shortcuts.get(
'Toggle menu', _('Toggle menu'), 'Ctrl+M'))
@staticmethod
def _apply_editor_shortcuts(editor):
editor.action_undo.setShortcut(shortcuts.get(
'Undo', _('Undo'), 'Ctrl+Z'))
editor.action_redo.setShortcut(shortcuts.get(
'Redo', _('Redo'), 'Ctrl+Y'))
editor.action_copy.setShortcut(shortcuts.get(
'Copy', _('Copy'), 'Ctrl+C'))
editor.action_cut.setShortcut(shortcuts.get(
'Cut', _('Cut'), 'Ctrl+X'))
editor.action_paste.setShortcut(shortcuts.get(
'Paste', _('Paste'), 'Ctrl+V'))
editor.action_duplicate_line.setShortcut(shortcuts.get(
'Duplicate line', _('Duplicate line'), 'Ctrl+D'))
editor.action_goto_line.setShortcut(shortcuts.get(
'Goto line', _('Goto line'), 'Ctrl+G'))
try:
p = editor.panels.get('SearchAndReplacePanel')
except KeyError:
_logger().debug('no SearchAndReplacePanel on widget %r', editor)
else:
p.actionSearch.setShortcut(shortcuts.get(
'Find', _('Find'), 'Ctrl+F'))
p.actionActionSearchAndReplace.setShortcut(
shortcuts.get('Replace', _('Replace'), 'Ctrl+H'))
p.actionFindNext.setShortcut(shortcuts.get(
'Find next', _('Find next'), 'F3'))
p.actionFindPrevious.setShortcut(shortcuts.get(
'Find previous', _('Find previous'), 'Shift+F3'))
try:
p = editor.panels.get('FoldingPanel')
except KeyError:
_logger().debug('no FoldingPanel on widget %r', editor)
else:
p.action_collapse.setShortcut(shortcuts.get(
'Folding: collapse', _('Folding: collapse'), 'Shift+-'))
p.action_expand.setShortcut(shortcuts.get(
'Folding: expand', _('Folding: expand'), 'Shift++'))
p.action_collapse_all.setShortcut(shortcuts.get(
'Folding: collapse all', _('Folding: collapse all'),
'Ctrl+Shift+-'))
p.action_expand_all.setShortcut(shortcuts.get(
'Folding: expand all', _('Folding: expand all'),
'Ctrl+Shift++'))
try:
m = editor.modes.get('ExtendedSelectionMode')
except KeyError:
_logger().debug('no ExtendedSelectionMode on widget %r', editor)
else:
m.action_select_word.setShortcut(shortcuts.get(
'Select word', _('Select word'), 'Ctrl+Alt+J'))
m.action_select_extended_word.setShortcut(shortcuts.get(
'Select extended word', _('Select extended word'),
'Ctrl+Shift+J'))
m.action_select_matched.setShortcut(shortcuts.get(
'Matched select', _('Matched select'), 'Ctrl+E'))
m.action_select_line.setShortcut(shortcuts.get(
'Select line', _('Select line'), 'Ctrl+Shift+L'))
try:
m = editor.modes.get('CaseConverterMode')
except KeyError:
_logger().debug('no CaseConverterMode on widget %r', editor)
else:
m.action_to_lower.setShortcut(shortcuts.get(
'Convert to lower case', _('Convert to lower case'), 'Ctrl+U'))
m.action_to_upper.setShortcut(shortcuts.get(
'Convert to UPPER CASE', _('Convert to UPPER CASE'),
'Ctrl+Shift+U'))
def _on_tab_detached(self, _, tab):
self._apply_editor_preferences(tab)
def _print(self):
printer = QtPrintSupport.QPrinter()
try:
document = self.current_tab.document()
has_selection = self.current_tab.textCursor().hasSelection()
except AttributeError:
# not a code editor
return
dialog = QtPrintSupport.QPrintDialog(printer, self)
dialog.setOption(dialog.PrintSelection, has_selection)
dialog.setWindowTitle(_('Print current editor'))
if dialog.exec_() == dialog.Accepted:
document.print(printer)
def _apply_editor_preferences(self, editor, set_color_scheme=True):
if not isinstance(editor, CodeEdit):
return
editor.show_whitespaces = settings.show_whitespaces()
if set_color_scheme:
editor.syntax_highlighter.color_scheme = ColorScheme(
settings.color_scheme())
editor.font_size = settings.editor_font_size()
editor.font_name = settings.editor_font()
if settings.dark_theme() or settings.is_dark_color_scheme():
self._setup_dark_editor(editor)
else:
self._setup_native_editor(editor)
editor.tab_length = settings.tab_length()
editor.use_spaces_instead_of_tabs = \
settings.use_spaces_instead_of_tabs()
editor.setCenterOnScroll(settings.center_on_scroll())
editor.file.replace_tabs_by_spaces = settings.convert_tabs()
editor.file.safe_save = settings.safe_save()
editor.file.clean_trailing_whitespaces = \
settings.clean_trailing_whitespaces()
editor.file.restore_cursor = settings.restore_cursor()
editor.file.preferred_eol = settings.eol_convention()
editor.file.autodetect_eol = settings.autodetect_eol()
editor.setLineWrapMode(
editor.WidgetWidth if settings.text_wrapping() else
editor.NoWrap)
try:
mode = editor.modes.get(modes.RightMarginMode)
except KeyError:
_logger().debug('no RightMarginMode on widget %r', editor)
else:
if 'cobol' not in editor.__class__.__name__.lower():
mode.position = settings.margin_position()
mode.enabled = settings.right_margin()
try:
mode = editor.modes.get(modes.CodeCompletionMode)
except KeyError:
_logger().debug('no CodeCompletionMode on widget %r', editor)
else:
mode.filter_mode = settings.cc_filter_mode()
mode.trigger_length = settings.cc_trigger_len()
mode.case_sensitive = settings.cc_case_sensitive()
mode.show_tooltips = settings.cc_show_tooltips()
try:
mode = editor.modes.get(modes.CaretLineHighlighterMode)
except KeyError:
_logger().debug('no CaretLineHighlighterMode on widget %r', editor)
else:
mode.enabled = settings.highlight_caret_line()
try:
mode = editor.modes.get(modes.SymbolMatcherMode)
except KeyError:
_logger().debug('no SymbolMatcherMode on widget %r', editor)
else:
mode.enabled = settings.highlight_parentheses()
try:
mode = editor.modes.get(modes.SmartBackSpaceMode)
except KeyError:
_logger().debug('no SmartBackSpaceMode on widget %r', editor)
else:
mode.enabled = settings.backspace_unindents()
# those modes are typically subclasses
available_modes = editor.modes.keys()
for name in available_modes:
if 'autocomplete' in name.lower():
mode = editor.modes.get(name)
mode.enabled = settings.auto_complete()
break
for name in available_modes:
if 'autoindent' in name.lower():
mode = editor.modes.get(name)
mode.enabled = settings.auto_indent()
break
try:
panel = editor.panels.get(panels.LineNumberPanel)
except KeyError:
_logger().debug('no LineNumberPanel on widget %r', editor)
else:
panel.setVisible(settings.show_line_numbers_panel())
try:
panel = editor.panels.get(panels.CheckerPanel)
except KeyError:
_logger().debug('no CheckerPanel on widget %r', editor)
else:
panel.setVisible(settings.show_errors_panel())
try:
panel = editor.panels.get(panels.GlobalCheckerPanel)
except KeyError:
_logger().debug('no GlobalCheckerPanel on widget %r', editor)
else:
panel.setVisible(settings.show_global_panel())
try:
panel = editor.panels.get(panels.FoldingPanel)
except KeyError:
_logger().debug('no FoldingPanel on widget %r', editor)
else:
panel.highlight_caret_scope = settings.highlight_caret_scope()
panel.setVisible(settings.show_folding_panel())
self._apply_editor_shortcuts(editor)
self._apply_editor_plugin_preferences(editor)
def _update_cursor_label(self):
try:
l, c = TextHelper(self.current_tab).cursor_position()
self.lbl_cursor.setText('%d:%d' % (l+1, c+1), False)
except (AttributeError, TypeError):
try:
l, c = self.current_tab.cursor_position
self.lbl_cursor.setText('%d:%d' % (l+1, c+1), False)
except AttributeError:
self.lbl_cursor.setText('n/a', False)
def _update_mem_label(self):
if psutil:
process = psutil.Process(os.getpid())
mem = int(process.memory_info().rss) / 1024 / 1024
self.lbl_memory.setText('%.3f MiB' % mem)
self._update_mem_label_timer.start()
def _update_menu_visibility(self):
self.ui.a_menu.setChecked(settings.show_menu())
self.ui.menubar.setVisible(settings.show_menu())
self.toolbar_menu.setVisible(not settings.show_menu())
def _update_menu_button(self):
for a in self.menu_button.actions():
self.menu_button.removeAction(a)
for menu in self._menus_list:
self.menu_button.addAction(menu.menuAction())
|
Facilitatory role of serotonin (5-HT) in the control of thyrotropin releasing hormone/thyrotropin (TRH/TSH) secretion in rats.
In order to investigate the role of serotonin in the regulation of thyrotropin (TSH) secretion, control and propylthiouracil (PTU)-treated male Wistar rats weighing approximately 250 g were subjected to ip injections of methysergide (MET, 10 micrograms/100 g body weight), a serotonergic receptor blocker, and killed 60 min later by decapitation. Serum and pituitary concentrations of TSH were measured by radioimmunoassay. An addition, the pituitary release of TSH was estimated in an in vitro system in which pituitary glands were incubated with hypothalamic extracts. MET treatment led to a decrease in pituitary (94.12 +/- 18.55 vs 199.30 +/- 31.47 micrograms/mg, N = 20), and serum (1.95 +/- 0.92 vs 4.26 +/- 1.40 ng/ml, N = 20) TSH concentration (P < 0.001) and also to a decreased in vitro pituitary response to control hypothalamic extracts (55 +/- 8 vs 78 +/- 7%, N = 5, P < 0.005). In addition, hypothalamic extracts of MET-treated rats significantly facilitated in vitro pituitary TSH secretion, suggesting an enhanced hypothalamic thyrotropin releasing hormone (TRH) activity (347 +/- 62 vs 78 +/- 7%, N = 5, P < 0.001). These results suggest that serotonin participates in the physiological control of TRH/TSH secretion, probably by increasing TRH production/secretion, and/or by facilitating the pituitary TSH response to TRH. |
def Center(self):
if not self.comPort:
self.G.printf("EDTracker: can't Center(); " +
"no comPort defined")
return
try:
from System.IO.Ports import SerialPort
serial = SerialPort(self.comPort, 57600)
serial.Open()
serial.Write('R')
serial.Close()
self.G.dbg('ED', "EDTracker.Center() succeeded")
except Exception as e:
self.G.printf("EDTracker.Center() failed: %s", str(e)) |
def run_val_loop(self, visuals, rnd_seed, all_metrics=False):
print("epoch {}: validation loop".format(self.epoch))
torch.manual_seed(rnd_seed)
np.random.seed(rnd_seed)
torch.cuda.manual_seed(rnd_seed)
device = self.device
self.model = self.model.eval()
disp_frac_vec = np.array(range(11))
disp_val = disp_frac_vec[0]
disp_counter = 0
if all_metrics:
metrics = {"mse": [], "ssim": [], "nmse": [], "psnr": []}
with torch.no_grad():
val_loss = 0
counter = 0
for i, val_batch in enumerate(self.val_loader):
val_target, val_dat = (
val_batch["target"].to(device),
val_batch["dat"].to(device),
)
val_est = self.model(val_dat)
val_loss = (
val_loss * counter + self.loss_fn(val_est, val_target).item()
) / (counter + 1)
counter = counter + 1
if all_metrics:
for ind in range(val_target.shape[0]):
nptarget = val_target[ind].cpu().numpy()
if nptarget.shape[0] > 1:
nptarget = np.sqrt(nptarget[0] ** 2 + nptarget[1] ** 2)
else:
nptarget = nptarget[0]
npest = val_est[ind].cpu().numpy()
if npest.shape[0] > 1:
npest = np.sqrt(npest[0] ** 2 + npest[1] ** 2)
else:
npest = npest[0]
metrics["mse"].append(MetricEval.mse(nptarget, npest))
metrics["ssim"].append(MetricEval.ssim(nptarget, npest))
metrics["nmse"].append(MetricEval.nmse(nptarget, npest))
metrics["psnr"].append(MetricEval.psnr(nptarget, npest))
if (i / len(self.val_loader)) >= (disp_val / 10):
print(
"validation loop progress: {:.0f}%".format(
100 * (i + 1) / len(self.val_loader)
)
)
disp_counter += 1
disp_val = disp_frac_vec[disp_counter]
print("validation loop finished")
dispind = 0
if val_target.shape[1] > 1:
tmp = np.squeeze(
val_target[dispind, ...].cpu().detach().float().numpy()
)
visuals["val_target"] = np.expand_dims(
np.sqrt(tmp[0, ...] ** 2 + tmp[1, ...] ** 2), 0
)
else:
visuals["val_target"] = np.absolute(
val_target[dispind, ...].cpu().detach().numpy()
)
if val_dat.shape[1] > 1:
tmp = np.squeeze(val_dat[dispind, ...].cpu().detach().float().numpy())
visuals["val_dat"] = np.expand_dims(
np.sqrt(tmp[0, ...] ** 2 + tmp[1, ...] ** 2), 0
)
else:
visuals["val_dat"] = np.absolute(
val_dat[dispind, ...].cpu().detach().numpy()
)
if val_est.shape[1] > 1:
tmp = np.squeeze(val_est[dispind, ...].cpu().detach().float().numpy())
visuals["val_est"] = np.expand_dims(
np.sqrt(tmp[0, ...] ** 2 + tmp[1, ...] ** 2), 0
)
else:
visuals["val_est"] = np.absolute(
val_est[dispind, ...].cpu().detach().float().numpy()
)
if all_metrics:
mse = np.array(metrics["mse"])
mse = mse[~np.isnan(mse)]
mse = mse[~np.isinf(mse)]
nmse = np.array(metrics["nmse"])
nmse = nmse[~np.isnan(nmse)]
nmse = nmse[~np.isinf(nmse)]
ssim = np.array(metrics["ssim"])
ssim = ssim[~np.isnan(ssim)]
ssim = ssim[~np.isinf(ssim)]
psnr = np.array(metrics["psnr"])
psnr = psnr[~np.isnan(psnr)]
psnr = psnr[~np.isinf(psnr)]
metrics["mse"] = mse
metrics["nmse"] = nmse
metrics["ssim"] = ssim
metrics["psnr"] = psnr
return metrics, visuals
else:
return val_loss, visuals |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class PublicadosManager(models.Manager):
def get_queryset(self):
return super(PublicadosManager, self).\
get_queryset().filter(status='publicado')
class Post(models.Model):
STATUS_CHOICES = (
('rascunho', 'Rascunho'),
('publicado', 'Publicado')
)
objects = models.Manager()
publicados = PublicadosManager()
titulo = models.CharField(max_length=255)
slug = models.SlugField(max_length=100)
corpo = models.TextField()
autor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='meublog_posts')
data_publicacao = models.DateTimeField(default=timezone.now)
data_criacao = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='rascunho')
class Meta:
ordering = ('-data_publicacao', )
verbose_name = "Post"
verbose_name_plural = "Posts"
def __str__(self):
return self.titulo
class Comentario(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
nome = models.CharField('Nome', max_length=50)
email = models.EmailField('E-mail')
corpo = models.TextField('Comentario')
data_criacao = models.DateTimeField('Data da criacao', auto_now_add=True)
ativo = models.BooleanField('Ativo', default=False)
class Meta:
verbose_name = 'Comentario'
verbose_name_plural = 'Comentarios'
def __str__(self):
return 'Comentario de: ' + self.nome |
def _parseMessage(self, content):
if 'ms' not in content:
return
for m in content['ms']:
try:
if m['type'] in ['m_messaging', 'messaging']:
if m['event'] in ['deliver']:
mid = m['message']['mid']
message=m['message']['body']
fbid = m['message']['sender_fbid']
name = m['message']['sender_name']
attachs = m['message']['attachments']
image = None
for attach in attachs:
if attach['attach_type'] == 'photo':
image = [attach['name'], attach['hires_url']]
elif attach['mercury']['attach_type'] == 'share':
image = [attach['mercury']['share']['title'], attach['mercury']['share']['media']['image']]
self.on_message(mid, fbid, name, message, image)
elif m['type'] in ['typ']:
self.on_typing(m["from"])
elif m['type'] in ['m_read_receipt']:
self.on_read(m['realtime_viewer_fbid'], m['reader'], m['time'])
elif m['type'] in ['inbox']:
viewer = m['realtime_viewer_fbid']
unseen = m['unseen']
unread = m['unread']
other_unseen = m['other_unseen']
other_unread = m['other_unread']
timestamp = m['seen_timestamp']
self.on_inbox(viewer, unseen, unread, other_unseen, other_unread, timestamp)
elif m['type'] in ['qprimer']:
self.on_qprimer(m['made'])
else:
print(m)
except Exception as e:
self.on_message_error(e, m) |
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:52:32 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/CarPlaySupport.framework/CarPlaySupport
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <CarPlaySupport/CarPlaySupport-Structs.h>
#import <UIKitCore/UIView.h>
@class CPTrip, UILabel, CPSHidingLabel, NSString, CPTravelEstimates, CPSRouteEstimatesView;
@interface CPSRouteOverviewView : UIView {
CPTrip* _representedTrip;
UILabel* _destinationName;
CPSHidingLabel* _destinationAddress;
CPSHidingLabel* _routeNoteLabel;
NSString* _routeNote;
CPTravelEstimates* _currentTravelEstimates;
CPSRouteEstimatesView* _estimatesView;
}
@property (nonatomic,readonly) CPTrip * representedTrip; //@synthesize representedTrip=_representedTrip - In the implementation block
@property (nonatomic,readonly) UILabel * destinationName; //@synthesize destinationName=_destinationName - In the implementation block
@property (nonatomic,readonly) CPSHidingLabel * destinationAddress; //@synthesize destinationAddress=_destinationAddress - In the implementation block
@property (nonatomic,readonly) CPSHidingLabel * routeNoteLabel; //@synthesize routeNoteLabel=_routeNoteLabel - In the implementation block
@property (nonatomic,copy) NSString * routeNote; //@synthesize routeNote=_routeNote - In the implementation block
@property (nonatomic,retain) CPTravelEstimates * currentTravelEstimates; //@synthesize currentTravelEstimates=_currentTravelEstimates - In the implementation block
@property (nonatomic,readonly) CPSRouteEstimatesView * estimatesView; //@synthesize estimatesView=_estimatesView - In the implementation block
+(id)_multilineLabel;
+(id)_nameForMapItem:(id)arg1 ;
+(void)_applyBoldText:(id)arg1 fontSize:(double)arg2 color:(id)arg3 toLabel:(id)arg4 ;
+(id)_shortenedAddressForAddress:(id)arg1 ;
+(void)_applyText:(id)arg1 fontSize:(double)arg2 color:(id)arg3 toLabel:(id)arg4 ;
-(UILabel *)destinationName;
-(CPSHidingLabel *)destinationAddress;
-(CPSHidingLabel *)routeNoteLabel;
-(CPTrip *)representedTrip;
-(CPSRouteEstimatesView *)estimatesView;
-(void)setRepresentedTrip:(CPTrip *)arg1 ;
-(void)setRouteNote:(NSString *)arg1 ;
-(void)setCurrentTravelEstimates:(CPTravelEstimates *)arg1 ;
-(NSString *)routeNote;
-(CPTravelEstimates *)currentTravelEstimates;
-(id)initWithFrame:(CGRect)arg1 ;
@end
|
/**
* @author gregperlinli
* @Description get times
*/
public class GetTime {
private static final int MIDNIGHT = 0 , NOON = 12, SUNSET = 18, TONIGHT = 20;
public static String getMorAftEveNig() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH");
String str = sdf.format(date);
int time = Integer.parseInt(str);
if ( time >= MIDNIGHT && time < NOON ) {
return "morning";
} else if ( time >= NOON && time < SUNSET ) {
return "afternoon";
} else if ( time >= SUNSET && time < TONIGHT ) {
return "evening";
} else {
return "night";
}
}
} |
NBC News launched the latest in a series of failed attempts to link Dr. Sebastian Gorka — the philosemitic, pro-Israel deputy foreign policy adviser to President Donald Trump — to the neo-Nazi far-right on Saturday.
As with all such previous attempts, NBC found nothing to prove any extremist ideas or views on the part of Dr. Gorka. And as with all such previous slanders, NBC relied on fraud — this time, in the form of the phony “Anne Frank Center.”
The full name of the bogus front organization is the “Anne Frank Center for Mutual Respect” — an ironic title, given that it is a full-throated Democratic Party attack machine that shows no respect for anyone else whatsover.
The self-described “civil rights activist” who leads it, Steven Goldstein, is an LGBT activist who has beclowned himself on cable news over the past few months in his efforts to tarnish President Trump as the second coming of Adolf Hitler.
Breitbart Jerusalem editor Aaron Klein exposed Goldstein and his organization in February. Goldstein is no Holocaust expert: he is merely an ardent Hillary Clinton supporter who found a ready audience for his political schtick among a gullible press corps eager for ammunition in their war against the White House. He has no qualms about exploiting the name and memory of Anne Frank for his purely partisan purposes. It is Holocaust desecration, if not outright denial.
Among many embarrassing moments for Goldstein and the Anne Frank Center, none was worse than last month’s revelation that the barrage of antisemitic bomb threats against Jewish Community Centers had been carried out by a black liberal journalist and a Jewish teenager in Israel. Rather than apologize for vomiting forth false accusations of hatred against the White House, Goldstein, reacting to the news, still managed to blame the Trump administration.
And yet it is the Anne Frank Center to which NBC News, lacking any other proof for its baseless claims, turned for help in condemning Gorka.
Goldstein’s operation did not disappoint: “How many ducks in the Trump White House must walk, talk and quack Anti-Semitically before our country wakes up and sees the greater problem?” the Center said in a statement to NBC. Never mind that all such accusations are entirely without merit: Goldstein & Co. repeat the lies.
The rest of the NBC News report was devoted to collecting statements from Hungarian villagers who claim to recall Gorka’s father’s membership in, and Gorka’s sympathy for, a version of the Vitezi Rend order that was anticommunist and had nothing to do with the Second World War organization of the same name.
NBC News was forced to admit that after sending investigative journalists halfway around the world, it was “unable to confirm” Gorka’s membership.
Cue the Anne Frank Center, there to add its emotive name and bilious innuendo to the heap of false accusations.
Yet as Bruce Abramson and Jeff Ballabon noted at the Jerusalem Post last month, the Gorka family protected Jews during the Second World War. Gorka senior went on to fight Soviet communism — which, notably, suppressed the Jewish faith and encouraged anti-Israel fanaticism. For that, he was awarded, in exile, the Vitezi Rend medal his son wore in tribute.
Dr. Gorka, a former Breitbart News editor, worked for this company for years — under the management of Jews, alongside many Jewish colleagues, and with favorable views toward the Jewish community and the Jewish state. It is clear that liberal media outlets like NBC and left-wing fronts like the bogus “Anne Frank Center” are just attacking him as a way to undermine Trump.
Their partisanship is obvious; they could, at least, make the fraud a little less obvious.
Joel B. Pollak is Senior Editor-at-Large at Breitbart News. He was named one of the “most influential” people in news media in 2016. His new book, How Trump Won: The Inside Story of a Revolution, is available from Regnery. Follow him on Twitter at @joelpollak. |
def process_contact_mtx(contact_mtx, gappy_idxs_a, constant_idxs_a,
gappy_idxs_b, constant_idxs_b):
contact_mtx = np.delete(contact_mtx, gappy_idxs_a, axis=0)
contact_mtx = np.delete(contact_mtx, constant_idxs_a, axis=0)
contact_mtx = np.delete(contact_mtx, gappy_idxs_b, axis=1)
contact_mtx = np.delete(contact_mtx, constant_idxs_b, axis=1)
return contact_mtx |
<gh_stars>0
package com.liumapp.blog.thread.threadpool.service;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author liumapp
* @file RejectedExecutionHandlerImpl.java
* @email <EMAIL>
* @homepage http://www.liumapp.com
* @date 4/27/18
*/
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + " is rejected");
}
}
|
/**
* format(packet 0xFE) ch dd [ddddcdcdddc] c - id h - sub id
*
* d - manor id d - size
* [ d - Object id d - crop id d - seed level c d - reward 1 id c d - reward 2
* id d - manor d - buy residual d - buy price d - reward ]
*
* @author l3x
*/
public class ExShowSellCropList extends L2GameServerPacket
{
private static final String _S__FE_21_EXSHOWSELLCROPLIST = "[S] FE:2c ExShowSellCropList";
private int _manorId = 1;
private final FastMap<Integer, L2ItemInstance> _cropsItems;
private final FastMap<Integer, CropProcure> _castleCrops;
public ExShowSellCropList(L2PcInstance player, int manorId, List<CropProcure> crops)
{
_manorId = manorId;
_castleCrops = new FastMap<Integer, CropProcure>();
_cropsItems = new FastMap<Integer, L2ItemInstance>();
FastList<Integer> allCrops = L2Manor.getInstance().getAllCrops();
for (int cropId : allCrops)
{
L2ItemInstance item = player.getInventory().getItemByItemId(cropId);
if (item != null)
{
_cropsItems.put(cropId, item);
}
}
for (CropProcure crop : crops)
{
if (_cropsItems.containsKey(crop.getId()) && crop.getAmount() > 0)
{
_castleCrops.put(crop.getId(), crop);
}
}
}
@Override
public void runImpl()
{
// no long running
}
@Override
public void writeImpl()
{
writeC(0xFE);
writeH(0x2c);
writeD(_manorId); // manor id
writeD(_cropsItems.size()); // size
for (L2ItemInstance item : _cropsItems.values())
{
writeD(item.getObjectId()); // Object id
writeD(item.getItemId()); // crop id
writeD(L2Manor.getInstance().getSeedLevelByCrop(item.getItemId())); // seed level
writeC(1);
writeD(L2Manor.getInstance().getRewardItem(item.getItemId(), 1)); // reward 1 id
writeC(1);
writeD(L2Manor.getInstance().getRewardItem(item.getItemId(), 2)); // reward 2 id
if (_castleCrops.containsKey(item.getItemId()))
{
CropProcure crop = _castleCrops.get(item.getItemId());
writeD(_manorId); // manor
writeQ(crop.getAmount()); // buy residual
writeQ(crop.getPrice()); // buy price
writeC(crop.getReward()); // reward
}
else
{
writeD(0xFFFFFFFF); // manor
writeQ(0); // buy residual
writeQ(0); // buy price
writeC(0); // reward
}
writeQ(item.getCount()); // my crops
}
}
@Override
public String getType()
{
return _S__FE_21_EXSHOWSELLCROPLIST;
}
} |
Like Dracula or Jason Voorhees or any other monster too profitable to stay dead forever, the horror anthology film always rises from the grave. It was probably 1945’s Dead Of Night that first popularized these loose assemblages of campfire tales. In the decades since, the genre has repeatedly come back into vogue: in the ’70s, with the EC Comics inspired portmanteau flicks of Amicus Productions; in the ’80s, when the craze overlapped with a boom in horror-anthology television shows like Tales From The Darkside and Monsters; and again this decade, when the success of V/H/S and The ABCs Of Death has inspired a new wave of cinematic short-story collections. The enduring popularity of the horror omnibus isn’t difficult to grasp: These films reward short attention spans, and often combine the talents (and marquee appeal) of multiple directors and stars. Plus, they offer multiple scary movies for the price of one.
If the horror anthology film has a weakness, the equivalent of a wooden stake or an overbearing (and decapitated) mother, it’s that they are almost always, by their very nature, uneven. Whether one director is in charge or the stories have been divvied up among a group, the result is still usually a mixed bag—a couple highlights, sharing runtime with some major lowlights. And even the best horror anthologies usually have at least one minor misfire, one chance for Stephen King to throw on some overalls. If only there was a way to separate the wheat from the chaff, the treats from the tricks, the candy from the meteor shit.
With Halloween right around the corner, The A.V. Club has done just that. Going back as far as Dead Of Night, we’ve assembled an unranked guide to the best individual segments from horror anthology films—a kind of greatest-hits mixtape of scary shorts, culled from a variety of omnibus projects. Only one entry per film was allowed, meaning that we had some agonizing choices to make when looking at some of the more consistent anthologies. And while we couldn’t actually put these disparate selections together into an easily playable playlist (damn copyright laws!), consider these our enthusiastic suggestions for those looking to construct their own super-sized bootleg anthology film.
One of Italy’s finer mid-century anthologies from horror maestro Mario Bava, this trilogy of tales kicks off with a simple, Twilight Zone-esque story of revenge and lies (complete with a Rod Serling-style introduction from Boris Karloff). A woman comes home at night only to begin receiving threatening phone calls, promising she’ll be dead by the morning. That’s all there is to it; she worries, she gets scared, she eventually calls a friend to come help out, and the killer’s “calling the police is useless, I’m too close” deters that option. Instead of snappy dialogue or top-shelf acting, the menace and tone come through in Bava’s striking color schemes, his ’60s-cool jazz soundtrack alternating with more traditional pulsing horror orchestration, all to create an indelible atmospheric chiller. It’s giallo without the gore, perfect for those with a more sensitive stomach. [Alex McLevy]
“The Crate,” Creepshow (1982)
Advertisement
“The Crate,” the second-to-last segment of 1982’s Creepshow, has all the elements for a successful EC Comics story. We’ve got the arrogant asshole in need of comeuppance (Adrienne Barbeau as an obnoxious, verbally abusive professor’s wife), the put-upon target of the asshole’s wrath (Hal Holbrook as her meek husband), and the supernaturally charged solution that will inevitably turn out to be worse than the problem itself (that would be the thing in the crate). Colorful, funny in a mean-spirited sort of way, and arguably the scariest segment of the film as a whole, “The Crate” is the epitome of everything that makes George Romero and Stephen King’s affectionate ode to the scary stories of their youth so much fun. [Katie Rife]
“The Black Cat,” Tales Of Terror (1962)
By 1962, Roger Corman and Vincent Price were on their fourth Edgar Allen Poe adaptation. So they decided to mix things up a bit by making Tales Of Terror, an anthology film combining three Poe stories (four, really) into one movie. Two of the segments reflect Corman’s admitted weariness with the material, but the middle segment, “The Black Cat,” turns a hybrid of Poe’s stories “The Black Cat” and “The Cask Of Amontillado” into a winking romp through the campy side of Gothic horror. Peter Lorre stars as Montresor, a barfly who challenges snobby sommelier Fortunato Luchresi (Vincent Price) to a battle of the palates that escalates into a deadly rivalry. Their initial face off, where Price primly exaggerates the fastidious routine of professional wine tasters as Lorre throws back whole glasses in one gulp, is a comedic delight, with two professional movie villains having a great time poking fun at their onscreen reputations. [Katie Rife]
One doesn’t usually look to horror anthologies for great acting; premise tends to be the real star, overshadowing whatever the cast can wring out of one-dimensional characters and severely abbreviated runtimes. But in “Quitters, Inc.,” the first of the three Stephen King vignettes that make up 1985’s Cat’s Eye, James Woods earns his top billing. Adapted by King from one of his own short stories, the segment casts Woods as a longtime chain-smoker who goes to the title agency for help in breaking his habit, only to discover the company’s rather unorthodox methods, which include nonstop surveillance and some extreme penalties for falling off the wagon. It’s a dementedly inspired conceit, but it wouldn’t work half as well without Woods’ miniature master class in anxiety, disbelief, and withdrawal—the way he spends most of his screen time mentally weighing the consequence of taking a puff against how damn good it might taste. Of course, for modern audiences, there’s a new satisfaction in seeing this particular actor, now fond of blowing a different kind of smoke, suffer for his sins and our enjoyment. [A.A. Dowd]
Advertisement
While the entirety of Michael Dougherty’s time-hopping anthology of stories unfolding over the course of one Halloween night succeeds at evoking the spirit of old-school campfire tales, the last segment best captures the macabre sense of All-Hallows’-Eve fun. Brian Cox stars as the resident old grouch of a small neighborhood, scaring away trick-or-treating kids by dressing up his dog as a monster, then pocketing the sugary treats they drop as they run in terror. Soon, he’s visited by Sam, a little being wearing a grinning burlap mask and footie pajamas, who teaches the cantankerous grinch that the rules of Halloween aren’t to be taken lightly. Set entirely within the old’s man dusty house, it’s a classic home-alone scary story that earns its scares the old-fashioned way: through ghoulishly entertaining slow-build frights, until it hits a practical effects-assisted conclusion that will leave you smiling as wide as the mysterious Sam’s mask. [Alex McLevy]
“It’s A Good Life,” Twilight Zone: The Movie (1983)
“Kick The Can,” Steven Spielberg’s dreadful contribution to Twilight Zone: The Movie, argues that there’s a mischievous kid lurking inside every adult. As if to prove the point, Joe Dante unleashes his own anarchic inner child in the vastly superior segment that follows. Based, like most of the film’s stories, on an old Twilight Zone episode, “It’s A Good Life” strands a schoolteacher (Kathleen Quinlan) among the terrorized surrogate family of a 10-year-old boy with the ability to reshape reality to his whims. Dante amps up the dark comedy of this domestic hostage situation—the grownups nervously scramble to placate their preadolescent ruler—while also unleashing some truly incredible special effects. Who is this enfant terrible but a stand-in for the director himself, using his powers to drop live-action people into cartoons, drag cartoon monsters into the live-action world, and subject everyone to his personal obsessions? Dante’s diabolical imagination ends up salvaging the whole project; after two duds, his entry is as darkly exciting as a hideous rabbit yanked from a top hat. (Incidentally, George Miller’s film-closing remake of “Nightmare At 20,000 Feet” is also superb.) [A.A. Dowd]
“Blind Alleys,” Tales From The Crypt (1972)
The portmanteau specialists at Hammer House Of Horror rival Amicus Productions had fully developed their signature style by 1972’s Tales From The Crypt. Although the film kicked off the wave of EC Comics adaptations that would eventually bring us the HBO series of the same name, only two of the film’s five segments are actually based on issues of the Tales From The Crypt comic book. The final segment in the film, “Blind Alleys,” is one of those. It’s a very mannered, very British take on EC’s ironic morality tales, starring Nigel Patrick as Major William Rogers, a military man who takes over a home for the blind populated mostly by the elderly and infirm. Rogers’ leadership style is to cruelly freeze and starve his charges while he lives in luxury; the residents’ eventual revenge takes a sadistically inventive approach to torture that presages much later films like Saw and Hostel. [Katie Rife]
Advertisement
There was a time when “Amelia” was considered one of the scariest half hours ever conceived for television. It snuck up on viewers, putting a razor-edged punctuation mark on Trilogy Of Terror, an ABC movie-of-the-week directed by Dark Shadows creator Dan Curtis and featuring Karen Black in four different roles. After two forgettable psychological horror scenarios, along comes a Richard Matheson corker about a terrified wallflower (Black, in a one-woman show that got her typecast in genre roles going forward) fighting for her life against the screaming, pointy toothed Zuni fetish doll she brings home to her high-rise apartment. Many of the killer-doll movies that followed (including, especially, the Puppet Master series) owe a debt to this intense, single-location battle royale. And if “Amelia” no longer looks, after Tales From The Crypt and American Horror Story and The X-Files, like the height of TV terror, it still carries a big lesson on the power of sequencing: End with a big enough bang, and your middling anthology film may become a cult favorite too. [A.A. Dowd]
“The Woman Of The Snow,” Kwaidan (1964)
Masaki Kobayashi’s classic Japanese horror anthology Kwaidan is a deliberately paced, theatrically staged movie that has more in common with traditional kabuki theater than contemporary horror films. Throughout the film, Kobayashi uses folkloric archetypes to create slow, creeping psychological horror, and the relationship between humans and the supernatural is at its most intimate in the chilling “The Woman Of The Snow.” With a palette of icy blues and a sharp, piercing soundtrack, Kobayashi evokes the eerie stillness of a forest blanketed with snow to tell a slow-burn tale of revenge, as a young woodcutter spared from death by hypothermia promises to never reveal his encounter with the beautiful, otherworldly woman who saved his life. Ten years later, he tells his beloved wife the tale… [Katie Rife]
The Japanese folktale that inspired “The Woman Of The Snow” gets a modern update in “Lover’s Vow,” the fourth and final chapter in 1990’s Tales From The Darkside: The Movie. Written by Beetlejuice’s Michael McDowell and with monster-movie luminaries like Robert Kurtzman, Greg Nicotero, Howard Berger, and Dick Smith on special effects, “Lover’s Vow” puts a grittier, more adult spin on the normally kitschy horror subgenre of EC Comics adaptations. James Remar stars as Preston, a bohemian artist whose life is spared by a gargoyle after he stumbles upon the creature eviscerating drunks in an alley one night. That same night, he meets Carola (Rae Dawn Chong), the woman who will eventually become his wife. Like the hapless woodcutter in Kobayashi’s tale, Preston can’t help but reveal his secret to his lover and best friend, although the consequences here are significantly more grotesque. [Katie Rife]
Advertisement
Second time was the charm for the V/H/S series. Though part two jettisoned much of the stylistic variety of its predecessor, it also ran with what worked best about the original, offering four relentless found-footage freak-outs. The best of the bunch—and, by extension, of this whole franchise—is “Safe Haven,” in which a team of documentary filmmakers make the very unwise decision to infiltrate a Heaven’s Gate-style commune. What happens inside plays to every rational and irrational fear audiences might have about hermetic cults, as a vague sense of growing unease eventually explodes into total batshit chaos. Co-director Gareth Evans also made the ruthlessly violent new action classic The Raid, and here he simply truncates and genre-twists that film’s strategy of constantly escalating intensity. It’s a half-hour roller coaster of horror, frazzling your nerves on the way up, then stealing your breath during the long, nightmarish drop. [A.A. Dowd]
The more real or plausible a horror story feels in the telling, the more effective it usually is at scaring the viewer. So consider it a high compliment indeed that the final segment of Fear(s) Of The Dark, an animated French anthology of scary stories, manages to unnerve so powerfully, despite being little more than a bluntly effective series of simply rendered black-and-white illustrations. Indeed, for the majority of Richard McGuire’s tale of a man seeking respite from a blizzard inside a (seemingly) abandoned house, the entire screen in engulfed in black, the rare moments of illumination provided only by his striking a match, stoking a fire, or lighting a candle. Those fleeting instances reveal little more than what’s a couple of feet in front of the man, and as he explores the house, our own claustrophobia increases, walls and corridors appearing and disappearing from the faint light with his movements. It’s near-silent, and by the time the tale hits its dark conclusion, this starkly drawn story has also animated a potent sense of unease. [Alex McLevy]
Japan’s insanely prolific (and prolifically insane) Takashi Miike has made a lot of movies—maybe as many as 100, if the campaign behind the upcoming Blade Of The Immortal is to be believed. In that vast body of work, “Box” is a haunting highpoint: a kind of ghost story told in whispers and flashes. Though it’s either the first or last chapter of a uniformly excellent Asian omnibus project called Three…Extremes (the order was shuffled for the American release), there’s nothing especially extreme about this story of a former circus performer tormented by the specter or her deceased twin sister. In place of grotesque gore, like the kind featured in some of his features, Miike offers striking, disquieting imagery: a circus tent on fire, a tree standing lonely in a snowy pasture, someone buried alive in plastic. Building to a surprising twist ending, “Box” comingles dreams, memories, and emotional trauma into a phantom of pure atmosphere. And did we mention it’s scary as hell? [A.A. Dowd]
“The Ventriloquist’s Dummy,” Dead Of Night (1945)
Advertisement
Ealing Studios tapped four notable directors for one of the finest and most influential of all horror anthologies. A group of people at a country home recount a number of uncanny or supernatural stories to one another. And while nearly all of them are successful and memorable—from the morbid to the darkly comic—the final stand-alone segment, “The Ventriloquist’s Dummy,” is the most resonant. An iconic use of the haunted-doll trope, this Alberto Cavalcanti-directed tale of a ventriloquist and his seemingly sentient (and malevolent) dummy has stood as a touchstone of the subgenre—everything from the Anthony Hopkins-starring Magic to recent offerings like Annabelle owe the British horror sequence a debt. Martin Scorsese has placed it among his best horror films of all time; the dastardly dummy, Hugo, is a big reason why. [Alex McLevy] |
s=input()
n=len(s)
flag=0
for i in range(0,n) :
x=s[i]
j=i
while j<=n-1 and x==s[j] :
j=j+1
length=j-i
if length>=7 :
flag=1
break
if flag==0 :
print("NO")
elif flag==1 :
print("YES")
|
<reponame>spacycoder/cosmosdb-go-sdk
package cosmos
// Coordinate = [lon, lat]
type Coordinate [2]float64
type Coordinates []Coordinate
type Geometry interface {
GeoType() string
}
// LineString struct defines a line string
type LineString struct {
Type string `json:"type"`
Coordinates Coordinates `json:"coordinates"`
}
// NewLineString creates a new LineString struct.
func NewLineString(coords ...Coordinate) *LineString {
line := &LineString{Type: "LineString", Coordinates: coords}
return line
}
// AddPoint is a helper method for adding point to a LineString
func (l *LineString) AddPoint(lon, lat float64) {
l.Coordinates = append(l.Coordinates, Coordinate{lon, lat})
}
func (l *LineString) Coords() *Coordinates {
return &l.Coordinates
}
func (l *LineString) GeoType() string {
return l.Type
}
type Polygon struct {
Type string `json:"type"`
Coordinates []Coordinates `json:"coordinates"`
}
// NewPolygon creates a new Polygon struct.
func NewPolygon(coords ...Coordinates) *Polygon {
polygon := &Polygon{Type: "Polygon", Coordinates: coords}
return polygon
}
func (p *Polygon) Coords() []Coordinates {
return p.Coordinates
}
func (p *Polygon) GeoType() string {
return p.Type
}
type Point struct {
Type string `json:"type"`
Coordinates Coordinate `json:"coordinates"`
}
// NewPoint creates a new point struct and returns it.
func NewPoint(coords Coordinate) *Point {
line := &Point{Type: "Point", Coordinates: coords}
return line
}
func (p *Point) Coords() *Coordinate {
return &p.Coordinates
}
func (p *Point) GeoType() string {
return p.Type
}
|
// DbInit returns a connection to bhlindex database.
func DbInit() (*sql.DB, error) {
var db *sql.DB
var err error
env := EnvVars()
params := fmt.Sprintf("postgres://%s@%s/%s?sslmode=disable",
env.DbUser, env.DbHost, env.Db)
db, err = sql.Open("postgres", params)
return db, err
} |
<gh_stars>0
package main
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil {
return head
}
var preHead = &ListNode{Next: head}
var p, q = preHead, head
var toRemove = -101
for q != nil {
if q.Val == toRemove {
p.Next = q.Next
q = p.Next
continue
}
if q.Next == nil {
break
}
if q.Val == q.Next.Val {
toRemove = q.Val
p.Next = q.Next
q = p.Next
continue
}
p = p.Next
q = q.Next
}
return preHead.Next
}
|
/**
* Collectors (terminal operations).
*/
private static void collectorsDemo(Stream<String> s) {
} |
The chronic wound pain experience: a conceptual model.
Chronic wound pain is experienced to a greater or lesser degree with most types of chronic wounds, yet research to date on this subject has been extremely limited. This article presents an empirically and inductively derived model, including a theoretical definition of the chronic wound pain experience (CWPE) and its subcomponents (noncyclic acute wound pain, cyclic acute wound pain and chronic wound pain). The model relates the CWPE to the nursing process and to nursing diagnoses and proposes intervention schemes to optimize patient outcomes. Avenues for future research are delineated. |
Are these emergency department performance data real?
We have recently demonstrated that the distribution of total time spent by patients in emergency departments (EDs) in England shows a peak immediately prior to the current Department of Health target of 4 hours. We aimed to investigate whether this suggested that performance data were being manipulated. We collected data from 117 EDs, and 616 067 patient episodes were included in the analysis. Evidence of manipulation of performance data appears to be present in a small proportion of episodes, but because of the numbers involved, it could equate to over 50 000 episodes per year in EDs in England. |
<gh_stars>0
package com.github.ivan909020.freelancehunt.sdk.objects.entities;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.ivan909020.freelancehunt.sdk.objects.models.*;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import static com.github.ivan909020.freelancehunt.sdk.client.ObjectMapperConfig.DATE_PATTERN;
import static com.github.ivan909020.freelancehunt.sdk.client.ObjectMapperConfig.DATE_TIME_PATTERN;
public class UserDetails {
@JsonProperty("id")
private Long id;
@JsonProperty("type")
private EntityType type;
@JsonProperty("attributes")
private Attributes attributes;
public UserDetails() {
}
public Long getId() {
return id;
}
public EntityType getType() {
return type;
}
public Attributes getAttributes() {
return attributes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDetails that = (UserDetails) o;
return Objects.equals(id, that.id) &&
type == that.type &&
Objects.equals(attributes, that.attributes);
}
@Override
public int hashCode() {
return Objects.hash(id, type, attributes);
}
@Override
public String toString() {
return "UserDetails{" +
"id=" + id +
", type=" + type +
", attributes=" + attributes +
'}';
}
public static class Attributes {
@JsonProperty("login")
private String login;
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
@JsonProperty("avatar")
private Avatar avatar;
@JsonProperty("birth_date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_PATTERN)
private LocalDate birthDate;
@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_TIME_PATTERN)
private ZonedDateTime createdAt;
@JsonProperty("cv")
private String cv;
@JsonProperty("cv_html")
private String cvHtml;
@JsonProperty("rating")
private Integer rating;
@JsonProperty("ratingPosition")
private Integer ratingPosition;
@JsonProperty("arbitrages")
private Integer arbitrages;
@JsonProperty("positive_reviews")
private Integer positiveReviews;
@JsonProperty("negative_reviews")
private Integer negativeReviews;
@JsonProperty("plus_ends_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_TIME_PATTERN)
private ZonedDateTime plusEndsAt;
@JsonProperty("is_plus_active")
private Boolean isPlusActive;
@JsonProperty("is_online")
private Boolean isOnline;
@JsonProperty("visited_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_TIME_PATTERN)
private ZonedDateTime visitedAt;
@JsonProperty("location")
private Location location;
@JsonProperty("verification")
private Verification verification;
@JsonProperty("contacts")
private Contacts contacts;
@JsonProperty("status")
private Status status;
@JsonProperty("skills")
private List<Skill> skills;
public Attributes() {
}
public String getLogin() {
return login;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Avatar getAvatar() {
return avatar;
}
public LocalDate getBirthDate() {
return birthDate;
}
public ZonedDateTime getCreatedAt() {
return createdAt;
}
public String getCv() {
return cv;
}
public String getCvHtml() {
return cvHtml;
}
public Integer getRating() {
return rating;
}
public Integer getRatingPosition() {
return ratingPosition;
}
public Integer getArbitrages() {
return arbitrages;
}
public Integer getPositiveReviews() {
return positiveReviews;
}
public Integer getNegativeReviews() {
return negativeReviews;
}
public ZonedDateTime getPlusEndsAt() {
return plusEndsAt;
}
public Boolean getPlusActive() {
return isPlusActive;
}
public Boolean getOnline() {
return isOnline;
}
public ZonedDateTime getVisitedAt() {
return visitedAt;
}
public Location getLocation() {
return location;
}
public Verification getVerification() {
return verification;
}
public Contacts getContacts() {
return contacts;
}
public Status getStatus() {
return status;
}
public List<Skill> getSkills() {
return skills;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attributes that = (Attributes) o;
return Objects.equals(login, that.login) &&
Objects.equals(firstName, that.firstName) &&
Objects.equals(lastName, that.lastName) &&
Objects.equals(avatar, that.avatar) &&
Objects.equals(birthDate, that.birthDate) &&
Objects.equals(createdAt, that.createdAt) &&
Objects.equals(cv, that.cv) &&
Objects.equals(cvHtml, that.cvHtml) &&
Objects.equals(rating, that.rating) &&
Objects.equals(ratingPosition, that.ratingPosition) &&
Objects.equals(arbitrages, that.arbitrages) &&
Objects.equals(positiveReviews, that.positiveReviews) &&
Objects.equals(negativeReviews, that.negativeReviews) &&
Objects.equals(plusEndsAt, that.plusEndsAt) &&
Objects.equals(isPlusActive, that.isPlusActive) &&
Objects.equals(isOnline, that.isOnline) &&
Objects.equals(visitedAt, that.visitedAt) &&
Objects.equals(location, that.location) &&
Objects.equals(verification, that.verification) &&
Objects.equals(contacts, that.contacts) &&
Objects.equals(status, that.status) &&
Objects.equals(skills, that.skills);
}
@Override
public int hashCode() {
return Objects.hash(login, firstName, lastName, avatar, birthDate, createdAt, cv, cvHtml, rating, ratingPosition, arbitrages, positiveReviews, negativeReviews, plusEndsAt, isPlusActive, isOnline, visitedAt, location, verification, contacts, status, skills);
}
@Override
public String toString() {
return "Attributes{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", avatar=" + avatar +
", birthDate=" + birthDate +
", createdAt=" + createdAt +
", cv='" + cv + '\'' +
", cvHtml='" + cvHtml + '\'' +
", rating=" + rating +
", ratingPosition=" + ratingPosition +
", arbitrages=" + arbitrages +
", positiveReviews=" + positiveReviews +
", negativeReviews=" + negativeReviews +
", plusEndsAt=" + plusEndsAt +
", isPlusActive=" + isPlusActive +
", isOnline=" + isOnline +
", visitedAt=" + visitedAt +
", location=" + location +
", verification=" + verification +
", contacts=" + contacts +
", status=" + status +
", skills=" + skills +
'}';
}
}
}
|
import java.util.*;
public class Sol
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int n,m,a,b;
double z;
n=sc.nextInt();
m=sc.nextInt();
if(n>m || n==m)
{
z=Math.sqrt(n);
a=(int)z;
b=n-(a*a);
}
else
{
z=Math.sqrt(m);
b=(int)z;
a=m-(b*b);
}
System.err.println("a: "+a+"\nb: "+b);
int x=(a*a)+b;
int y=(b*b)+a;
if(x==n && y==m)
{
if((y==n && x==m) &&(a!=b))
System.out.println(2);
else
System.out.println(1);
}
else
System.out.println(0);
}
}
|
/* * * * * * * * * * * * * * * * * * * * *
**
** Copyright 2012 <NAME>
**
** 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.
**
** * * * * * * * * * * * * * * * * * * */
#ifndef _SCENARIO_CHANGE_PASSWORD
#define _SCENARIO_CHANGE_PASSWORD
#pragma once
#include "field_state_pair.h"
#include "field_initializor.h"
enum CHANGE_PASSWORD_FIELD_ID
{
CPFI_OTP_LOGO = 0,
CPFI_OTP_LARGE_TEXT = 1,
CPFI_OTP_SMALL_TEXT = 2,
CPFI_OTP_PASS_OLD = 3,
CPFI_OTP_PASS_NEW_1 = 4,
CPFI_OTP_PASS_NEW_2 = 5,
CPFI_OTP_SUBMIT_BUTTON = 6,
CPFI_NUM_FIELDS = 7,
};
static const FIELD_INITIALIZOR s_rgScenarioChangePasswordFieldInitializors[] =
{
{ FIT_NONE, NULL },
{ FIT_VALUE_OR_LOGIN_TEXT, L"" },
{ FIT_VALUE_OR_LOCKED_TEXT, L"" },
{ FIT_USERNAME_AND_DOMAIN, L"" },
{ FIT_VALUE, L"" },
{ FIT_VALUE, L"" },
{ FIT_VALUE, L"Submit" },
};
// These two arrays are seperate because a credential provider might
// want to set up a credential with various combinations of field state pairs
// and field descriptors.
// The field state value indicates whether the field is displayed
// in the selected tile, the deselected tile, or both.
// The Field interactive state indicates when
static const FIELD_STATE_PAIR s_rgScenarioChangePasswordFieldStatePairs[] =
{
{ CPFS_DISPLAY_IN_BOTH, CPFIS_NONE }, // CPFI_OTP_LOGO
{ CPFS_DISPLAY_IN_BOTH, CPFIS_NONE }, // CPFI_OTP_LARGE_TEXT
{ CPFS_HIDDEN, CPFIS_NONE }, // CPFI_OTP_SMALL_TEXT
{ CPFS_DISPLAY_IN_SELECTED_TILE, CPFIS_FOCUSED }, // CPFI_OTP_PASS_OLD
{ CPFS_DISPLAY_IN_SELECTED_TILE, CPFIS_NONE }, // CPFI_OTP_PASS_NEW_1
{ CPFS_DISPLAY_IN_SELECTED_TILE, CPFIS_NONE }, // CPFI_OTP_PASS_NEW_2
{ CPFS_DISPLAY_IN_SELECTED_TILE, CPFIS_NONE }, // CPFI_OTP_SUBMIT_BUTTON
};
// Field descriptors for unlock and logon.
// The first field is the index of the field.
// The second is the type of the field.
// The third is the name of the field, NOT the value which will appear in the field.
static const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR s_rgScenarioChangePasswordCredProvFieldDescriptors[] =
{
{ CPFI_OTP_LOGO, CPFT_TILE_IMAGE, L"Logo" },
{ CPFI_OTP_LARGE_TEXT, CPFT_LARGE_TEXT, L"LargeText" },
{ CPFI_OTP_SMALL_TEXT, CPFT_SMALL_TEXT, L"SmallText" },
{ CPFI_OTP_PASS_OLD, CPFT_PASSWORD_TEXT, L"<PASSWORD>" },
{ CPFI_OTP_PASS_NEW_1, CPFT_PASSWORD_TEXT, L"<PASSWORD>" },
{ CPFI_OTP_PASS_NEW_2, CPFT_PASSWORD_TEXT, L"<PASSWORD>" },
{ CPFI_OTP_SUBMIT_BUTTON, CPFT_SUBMIT_BUTTON, L"Submit" },
};
#endif
|
//Classe per effettuare il download delle opere
public void Download()
{
Stage secondStage = new Stage();
btdownload.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event)
{
for (int i=0;i <list.size();i++)
{
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Image");
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image", "*.jpg"));
File file = fileChooser.showSaveDialog(secondStage);
if (file != null) {
try {
ImageIO.write(SwingFXUtils.fromFXImage(list.get(i), null), "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
} |
/**
* this method checks if the given Url matches the Url of the given Website Entity specified by
* username and websiteName
*/
void checkExpectedDB(String username, String websiteName, String webAddress) {
Url expected = getWebsite(username, websiteName, webAddress);
assertNotNull(expected);
assertEquals(expected.username, username);
assertEquals(expected.websiteName, websiteName);
assertEquals(expected.webAddress, webAddress);
} |
Lumbar Spinal Stenosis in a Patient With Diffuse Idiopathic Skeletal Hypertrophy Syndrome
Lumbar spinal stenosis is associated with a variety of conditions, including dysplastic narrowing of the spine, lumbar spondylosis, Paget's disease, and achondroplastic dwarfism. No case of lumbar stenosis associated with diffuse idiopathic skeletal hyperostosis (DISH) previously has been described. It would appear that this case could represent either another manifestation of DISH characterized by involvement of the ligamentum flavum or coincidental association with lumbar spondylosis. In either case, physicians treating spinal and skeletal diseases should be aware of potential neurologic complications requiring surgical decompression due to narrowing of the spinal canal in this unusual disorder. |
/**
* Removes action from this.untrainedActions if present.
* @param action (HashSet<Action>)
*/
public void removeUntrainedAction(Action action){
if(this.untrainedActions.contains(action)){
this.untrainedActions.remove(action);
}
} |
For six months starting in late 2014, web series Whatever, Linda creators Hannah Cheesman and Mackenzie Donaldson chronicled their careers as young, female producers in the ever-shifting film/TV/digital landscape for The Globe and Mail. With their first feature film, The Definites, having premiered at the Cucalorus Festival in Wilmington, N.C., this past week, The Globe checked back in with the producing partners over e-mail.
In one of your first columns, you chronicled shooting scenes guerrilla-style at Art Basel in Miami. Was shooting the rest of The Definites in Toronto as exciting?
Hannah Cheesman: "Exciting" is one way of putting it. I kid. It was such an unusual project, because what we shot in Miami and brought back home with us, we then tore apart upon return to Toronto, rebroke the storyline and rewrote the script.
Story continues below advertisement
Mackenzie Donaldson: I would describe the Toronto leg of shooting, which was three separate shoots over 1 1/2 years, as more exciting than Miami. First, because after Miami, it was beyond pleasurable to be fully prepped and prepared with a fulsome crew and plan to execute in the old-fashioned indie way. And secondly, because of what our amazing crew pulled off including finding missing wardrobe pieces on Bunz (we traded broccoli for a matching American apparel shirt that was missing from Miami) and not just matching winter Toronto for hot Miami but also then spring Toronto for winter Toronto.
What's your elevator pitch of The Definites? (And do people even pitch in elevators any more?)
HC: A woman leaves her husband-to-be and instead weds her own wild desire when she flies away to a libidinous, party-filled weekend at Art Basel Miami.
There, she collides with her estranged sister, as they try to navigate and reconcile with the untimely death of their mother.
MD: I don't know if we pitch in elevators any more, but a 30-second pitch is still as important as ever to sell your film. If you don't have someone interested in the first 10 seconds you've probably lost them.
You've already sold the film to Mongrel and TMN in Canada. How did that come about?
HC: Mackenzie and I both brought two key elements to the table in order to procure this deal. For my part, I'd met one of the heads at Mongrel first at a TIFF karaoke night, then at Cannes. He's a smart business mind with a great eye for film, and when we finally had a cut of the film that we were proud of, I reached out to him.
Story continues below advertisement
MD: And I have a great relationship through my work on Orphan Black with executives at Bell Media, so as soon we had a screener I sent it their way to see if it might fit with their channel TMN. It did and they continue to be amazing supporters of the project and of both Hannah and I.
The Definites co-director/producer Hannah Cheesman and co-director/producer Mackenzie Donaldson. Handout
After Cucalorus, The Definites headed to the Key West Film Festival and the Whistler Film Festival – and it's also at the Bahamas International Film Festival in December. Is your life as glamorous as it sounds?
HC: I know it's cliché to bring up the starving-artist trope, but to say my life is any less precarious than that would be a misrepresentation. I wouldn't call that glamorous. Almost every aspect of the festivals we go to are paid for out of pocket. I joke that filmmaking is an expensive hobby, but there's truth there.
MD: I'm still debating whether or not I will fork out the money to get to BIFF. I really want one of us to represent the film at our international premiere, but like Hannah said, going would be completely out of pocket for us so I have to look at my bank account. The business is an odd combination of glamour and poverty.
Whatever happened to Whatever, Linda – the "internet odyssey" we had a sneak peek of on The Globe's site back in 2014? I thought it was becoming a full series.
HC: Linda has indeed been (and continues to be) an odyssey. We were in development with behemoth Hollywood producer Mark Gordon and had a deal set up with BBC America. This summer, that fell through. We are still working with Graeme Manson, who is on board to executive produce, and have another pending deal with a new network – but wait for that announcement in early 2018.
Story continues below advertisement
MD: Oh, the ups and downs. Linda is our first-born baby and she definitely is in her teens. The project has new momentum after a hard summer, but I've actually never been more excited about the future for Linda.
Can you each update me on some of your individual projects?
HC: The last year has been a really exciting one for me. I wrote for Workin' Moms (season 2), a new kids live-action show about a time-travelling ballerina called Find Me in Paris and am in the development room for a half-hour comedy project with CBC and Project 10 Productions.
MD: We wrapped the final season of Orphan Black in March, which was like saying goodbye to my extended family of five years. I started my own production company in April and through that company, I'm working on a slate of TV and film projects. My company is working on its first development deal with a network right now and is producing its first feature documentary, Citizen Bio, for Showtime.
And are you still teaming up to create work together?
HC: Indeed we are! At Cucalorus, we will also be premiering a short we made (me director-writer; Mack producing) called Emmy. It stars Amanda Brugel and we made it together last year. Also, we have a digital show in development with CBC's digital arm, called Did.
Your column for us was often explicitly about working as young women in a male-dominated industry. Have you felt anything shift since we last checked in with you?
HC: If we look at the stats collected by organizations like the Geena Davis Institute, no. But I think there is undeniably a fomenting of awareness and a rallying around the glaring inequities and biases of this industry. The fact that Telefilm has committed gender parity in its project funding could in fact mean real change, real shifts.
MD: There's a lot of buzz around change and equality in the business, especially with the whole Harvey/Hoffman/Spacey news. And there are new opportunities and funds being designed to help facilitate that equality, so I hope we see real change in the stats in the coming years. Because when you look at those numbers today, it doesn't look good for equality or change, but I have hope.
The interview has been edited and condensed. |
def std(self, p):
return self.var(p)**(1/2) |
<reponame>nicford/databases-group8
import { Injectable } from '@nestjs/common';
import { Message } from '@group8/api-interfaces';
@Injectable()
export class AppService {
getData(): Message {
return { message: 'Welcome to api!' };
}
}
|
const HTTP_REGEX = "^https?:";
const WS_REGEX = "^wss?:";
function getUrlProtocol(url: string): string | undefined {
const matches = url.match(new RegExp(/^\w+:/, "gi"));
if (!matches || !matches.length) return;
return matches[0];
}
function matchRegexProtocol(url: string, regex: string): boolean {
const protocol = getUrlProtocol(url);
if (typeof protocol === "undefined") return false;
return new RegExp(regex).test(protocol);
}
export function isHttpUrl(url: string): boolean {
return matchRegexProtocol(url, HTTP_REGEX);
}
export function isWsUrl(url: string): boolean {
return matchRegexProtocol(url, WS_REGEX);
}
export function isLocalhostUrl(url: string): boolean {
return new RegExp("wss?://localhost(:d{2,5})?").test(url);
}
|
<reponame>SSSDNSY/go
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflect
import (
"internal/goarch"
"sync"
"unsafe"
)
// MakeRO returns a copy of v with the read-only flag set.
func MakeRO(v Value) Value {
v.flag |= flagStickyRO
return v
}
// IsRO reports whether v's read-only flag is set.
func IsRO(v Value) bool {
return v.flag&flagStickyRO != 0
}
var CallGC = &callGC
// FuncLayout calls funcLayout and returns a subset of the results for testing.
//
// Bitmaps like stack, gc, inReg, and outReg are expanded such that each bit
// takes up one byte, so that writing out test cases is a little clearer.
// If ptrs is false, gc will be nil.
func FuncLayout(t Type, rcvr Type) (frametype Type, argSize, retOffset uintptr, stack, gc, inReg, outReg []byte, ptrs bool) {
var ft *rtype
var abid abiDesc
if rcvr != nil {
ft, _, abid = funcLayout((*funcType)(unsafe.Pointer(t.(*rtype))), rcvr.(*rtype))
} else {
ft, _, abid = funcLayout((*funcType)(unsafe.Pointer(t.(*rtype))), nil)
}
// Extract size information.
argSize = abid.stackCallArgsSize
retOffset = abid.retOffset
frametype = ft
// Expand stack pointer bitmap into byte-map.
for i := uint32(0); i < abid.stackPtrs.n; i++ {
stack = append(stack, abid.stackPtrs.data[i/8]>>(i%8)&1)
}
// Expand register pointer bitmaps into byte-maps.
bool2byte := func(b bool) byte {
if b {
return 1
}
return 0
}
for i := 0; i < intArgRegs; i++ {
inReg = append(inReg, bool2byte(abid.inRegPtrs.Get(i)))
outReg = append(outReg, bool2byte(abid.outRegPtrs.Get(i)))
}
if ft.kind&kindGCProg != 0 {
panic("can't handle gc programs")
}
// Expand frame type's GC bitmap into byte-map.
ptrs = ft.ptrdata != 0
if ptrs {
nptrs := ft.ptrdata / goarch.PtrSize
gcdata := ft.gcSlice(0, (nptrs+7)/8)
for i := uintptr(0); i < nptrs; i++ {
gc = append(gc, gcdata[i/8]>>(i%8)&1)
}
}
return
}
func TypeLinks() []string {
var r []string
sections, offset := typelinks()
for i, offs := range offset {
rodata := sections[i]
for _, off := range offs {
typ := (*rtype)(resolveTypeOff(unsafe.Pointer(rodata), off))
r = append(r, typ.String())
}
}
return r
}
var GCBits = gcbits
func gcbits(interface{}) []byte // provided by runtime
func MapBucketOf(x, y Type) Type {
return bucketOf(x.(*rtype), y.(*rtype))
}
func CachedBucketOf(m Type) Type {
t := m.(*rtype)
if Kind(t.kind&kindMask) != Map {
panic("not map")
}
tt := (*mapType)(unsafe.Pointer(t))
return tt.bucket
}
type EmbedWithUnexpMeth struct{}
func (EmbedWithUnexpMeth) f() {}
type pinUnexpMeth interface {
f()
}
var pinUnexpMethI = pinUnexpMeth(EmbedWithUnexpMeth{})
func FirstMethodNameBytes(t Type) *byte {
_ = pinUnexpMethI
ut := t.uncommon()
if ut == nil {
panic("type has no methods")
}
m := ut.methods()[0]
mname := t.(*rtype).nameOff(m.name)
if *mname.data(0, "name flag field")&(1<<2) == 0 {
panic("method name does not have pkgPath *string")
}
return mname.bytes
}
type OtherPkgFields struct {
OtherExported int
otherUnexported int
}
func IsExported(t Type) bool {
typ := t.(*rtype)
n := typ.nameOff(typ.str)
return n.isExported()
}
func ResolveReflectName(s string) {
resolveReflectName(newName(s, "", false))
}
type Buffer struct {
buf []byte
}
func clearLayoutCache() {
layoutCache = sync.Map{}
}
func SetArgRegs(ints, floats int, floatSize uintptr) (oldInts, oldFloats int, oldFloatSize uintptr) {
oldInts = intArgRegs
oldFloats = floatArgRegs
oldFloatSize = floatRegSize
intArgRegs = ints
floatArgRegs = floats
floatRegSize = floatSize
clearLayoutCache()
return
}
var MethodValueCallCodePtr = methodValueCallCodePtr
|
TransLink says a one-hour breakdown in service during the Friday afternoon rush hour was caused by commuters leaving the train and walking on the guideway.
A TransLink official told CBC News that a car stalled and stopped between the Scott Road and Gateway stations in Surrey shortly after 5 p.m. PT Friday.
But within minutes of the train stopping, some passengers broke open the emergency door release and began exiting the train on to the track which carries a 600-volt charge and could have caused an electrocution, according to TransLink
For safety reasons, TransLink said in a statement that it was forced to completely shutdown power on the section of the line between Scott Road and Gateway stations and the SkyTrain official had to escort people to the station. Some commuters are in the habit of forcing open SkyTrain doors and taking to the guideway but TransLink says the practise is not only risky, it usually leads to far longer delays in service. (Twitter) "What should have been a seven-to-ten minute delay ended up being almost an hour as more than 100 passengers placed themselves at risk by walking on the gateway."
TransLink said the actions of the passengers who walked onto the track caused thousands of commuters to be further delayed.
Passengers from a second train also forced open the doors and entered the track.
Passengers leave a SkyTrain car for a walk on the guideway during one of the recent system shut-downs. TransLink says passengers risk electrocution from 600 volts of current. Cutting power when this happens also leads to longer delays. (Twitter) "All available personnel from Transit Police, Transit Security and Transit Supervisors were immediately deployed to assist," said TransLink. TransLink has threatened to issue $115 fines to passengers prying open doors and lay charges of mischief for repeat offenders. It's the third major shutdown of SkyTrain during commute times in the last two months.
In July, two system-wide SkyTrain shutdowns within five days of each other left thousands of commuters fuming after they were given no information when communications systems failed.
The shutdown affected only the Expo/Millennium Line. The Canada Line was not affected. |
<gh_stars>1000+
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Original Work: MIT License, Copyright (c) [2015-2020] all contributors
* https://github.com/marianobarrios/tls-channel
*/
package com.mongodb.internal.connection.tlschannel;
import com.mongodb.internal.connection.tlschannel.util.DirectBufferDeallocator;
import java.nio.ByteBuffer;
/**
* Allocator that creates direct buffers. The {@link #free(ByteBuffer)} method, if called,
* deallocates the buffer immediately, without having to wait for GC (and the finalizer) to run.
* Calling {@link #free(ByteBuffer)} is actually optional, but should result in reduced memory
* consumption.
*
* <p>Direct buffers are generally preferred for using with I/O, to avoid an extra user-space copy,
* or to reduce garbage collection overhead.
*/
public class DirectBufferAllocator implements BufferAllocator {
private final DirectBufferDeallocator deallocator = new DirectBufferDeallocator();
@Override
public ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
@Override
public void free(ByteBuffer buffer) {
// do not wait for GC (and finalizer) to run
deallocator.deallocate(buffer);
}
}
|
import { useQuery, useResult } from '@vue/apollo-composable';
import { struct } from 'superstruct';
import * as T from './typings';
export const useReadOne = <C extends T.Cfg, Vo = C['ObC']['Po'], Dto = C['ObC']['Po']>(p: T.UseReadOneP<C, Vo, Dto>): T.UseReadOneR<Vo> => {
const { fallback = null, fields, id, rp } = p;
const { error, loading, result } = useQuery<T.Dict<Dto>>(rp.O.readOne({ fields }), { where: { id } });
const item: T.Api.R<T.Maybe<Vo>> = useResult<T.Dict<Dto>, T.Maybe<Vo>, T.Maybe<Vo>>(result, fallback, getFromData(p));
return { error, item, loading };
};
const getFromData = <C extends T.Cfg, Vo, Dto>(p: T.UseReadOneP<C, Vo, Dto>) => (data: T.Dict<Dto>): T.Maybe<Vo> => {
try {
return getValue({ ...p, data });
} catch (error) {
return manageError({ ...p, error });
}
};
const getValue = <C extends T.Cfg, Vo, Dto>(p: { data: T.Dict<Dto> } & T.UseReadOneP<C, Vo, Dto>): T.Maybe<Vo> => {
const { data, debug = false, fallback = null, id, rp, update = (dto) => (dto as unknown) as Vo, validation } = p;
const dto = data[rp.L.readOne];
if (debug) console.log(rp.L.readOne, 'with id', id, 'gets dto', dto);
const value = dto ? update(validation ? struct(validation)(dto) : dto) : fallback;
if (debug) console.log(rp.L.readOne, 'with id', id, 'returns item', value);
return value;
};
const manageError = <C extends T.Cfg, Vo, Dto>(p: { error: Error } & T.UseReadOneP<C, Vo, Dto>): null => {
const { debug = false, error, id, rp } = p;
if (debug) console.error(rp.L.readOne, 'with id', id, 'errored :', error);
return null;
};
|
<gh_stars>1-10
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { sortBy } from 'lodash';
type SortField =
| 'name'
| 'status'
| 'health'
| 'primary'
| 'replica'
| 'documents'
| 'size'
| 'primary_size'
| 'data_stream';
type Unit = 'kb' | 'mb' | 'gb' | 'tb' | 'pb';
const unitMagnitude = {
kb: 1,
mb: 2,
gb: 3,
tb: 4,
pb: 5,
};
const stringSort = (fieldName: SortField) => (item: { [key: string]: any }) => {
return item[fieldName];
};
const numericSort = (fieldName: SortField) => (item: { [key: string]: any }) => +item[fieldName];
const byteSort = (fieldName: SortField) => (item: { [key: string]: any }) => {
const rawValue = item[fieldName];
// raw value can be missing if index is closed
if (!rawValue) {
return 0;
}
const matchResult = rawValue.match(/(.*)([kmgtp]b)/);
if (!matchResult) {
return 0;
}
const [, number, unit]: [string, string, Unit] = matchResult;
return +number * Math.pow(1024, unitMagnitude[unit]);
};
const sorters = {
name: stringSort('name'),
status: stringSort('status'),
health: stringSort('health'),
primary: numericSort('primary'),
replica: numericSort('replica'),
documents: numericSort('documents'),
size: byteSort('size'),
primary_size: byteSort('primary_size'),
data_stream: stringSort('data_stream'),
};
export const sortTable = (array = [], sortField: SortField, isSortAscending: boolean) => {
const sorted = sortBy(array, sorters[sortField]);
return isSortAscending ? sorted : sorted.reverse();
};
|
/*
* Copyright <NAME> <EMAIL>
*
* 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 io.github.ma1uta.matrix.client;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.github.ma1uta.matrix.client.model.content.ContentUri;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.MediaType;
class ContentAsyncMethodsTest extends MockServer {
@Test
void upload() throws Exception {
wireMockServer.stubFor(post(urlPathMatching("/_matrix/media/r0/upload"))
.withHeader("Content-Type", equalTo(MediaType.TEXT_PLAIN))
.withHeader("Authorization", equalTo("Bearer " + ACCESS_TOKEN))
.withQueryParam("filename", equalTo("content.txt"))
.willReturn(okJson("{\"content_uri\":\"mxc://example.com/AQwafuaFswefuhsfAFAgsw\"}")
)
);
try (InputStream inputStream = getClass().getResourceAsStream("/content.txt")) {
getMatrixClient().getConnectionInfo().setAccessToken(ACCESS_TOKEN);
String uri = getMatrixClient().contentAsync().upload(inputStream, "content.txt", "text/plain").thenApply(ContentUri::getContentUri)
.get(1000, TimeUnit.MILLISECONDS);
assertEquals("mxc://example.com/AQwafuaFswefuhsfAFAgsw", uri);
}
}
}
|
/// If edns is_none, this will create a new default Edns.
pub fn edns_mut(&mut self) -> &mut Edns {
if self.edns.is_none() {
self.edns = Some(Edns::new());
}
self.edns.as_mut().unwrap()
} |
/**
* @author Matthew Stevenson <www.mechio.org>
*/
public class Activator implements BundleActivator {
private static final Logger theLogger = LoggerFactory.getLogger(Activator.class);
@Override
public void start(BundleContext context) throws Exception {
theLogger.info("AnimationControl Activation Begin.");
InterpolatorDirectory.instance().setContext(context);
InterpolatorDirectory.registerFactory(context, new CSplineInterpolatorFactory());
theLogger.info("CSplineInterpolatorFactory Service Registered Successfully.");
InterpolatorDirectory.registerFactory(context, new LinearInterpolatorFactory());
theLogger.info("LinearInterpolatorFactory Service Registered Successfully.");
InterpolatorDirectory.registerFactory(context, new BezierInterpolatorFactory());
theLogger.info("BezierInterpolatorFactory Service Registered Successfully.");
theLogger.info("AnimationControl Activation Complete.");
}
@Override
public void stop(BundleContext context) throws Exception {
}
} |
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.asset.management.client.editors.conf;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.google.gwt.core.client.GWT;
import org.guvnor.asset.management.client.i18n.Constants;
import org.guvnor.asset.management.model.ProjectStructureModel;
import org.guvnor.asset.management.service.AssetManagementService;
import org.guvnor.asset.management.service.ProjectStructureService;
import org.guvnor.structure.repositories.Repository;
import org.guvnor.structure.repositories.RepositoryService;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.mvp.UberView;
import org.uberfire.client.workbench.events.BeforeClosePlaceEvent;
import org.uberfire.client.workbench.widgets.common.ErrorPopup;
import org.uberfire.lifecycle.OnOpen;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.mvp.PlaceRequest;
@Dependent
@WorkbenchScreen(identifier = "Repository Configuration")
public class RepositoryConfigurationPresenter {
private Constants constants = GWT.create(Constants.class);
public interface RepositoryConfigurationView extends UberView<RepositoryConfigurationPresenter> {
void displayNotification(String text);
ListBox getChooseRepositoryBox();
Button getConfigureButton();
TextBox getReleaseBranchText();
TextBox getDevBranchText();
TextBox getCurrentVersionText();
TextBox getVersionText();
}
@Inject
RepositoryConfigurationView view;
@Inject
Caller<AssetManagementService> assetManagementServices;
@Inject
Caller<RepositoryService> repositoryServices;
@Inject
Caller<ProjectStructureService> projectStructureServices;
@Inject
private Event<BeforeClosePlaceEvent> closePlaceEvent;
private PlaceRequest place;
@Inject
private PlaceManager placeManager;
private List<Repository> repositories;
@OnStartup
public void onStartup(final PlaceRequest place) {
this.place = place;
}
@WorkbenchPartTitle
public String getTitle() {
return constants.Repository_Configuration();
}
@WorkbenchPartView
public UberView<RepositoryConfigurationPresenter> getView() {
return view;
}
public RepositoryConfigurationPresenter() {
}
@PostConstruct
public void init() {
}
public void loadRepositoryProjectStructure(String value) {
if(!value.equals(constants.Select_Repository())){
for(Repository r : repositories){
if((r.getAlias()).equals(value)){
projectStructureServices.call(new RemoteCallback<ProjectStructureModel>() {
@Override
public void callback(ProjectStructureModel model) {
if(model != null && model.getPOM() != null){
// don't include snapshot for branch names
view.getCurrentVersionText().setText(model.getPOM().getGav().getVersion().replace("-SNAPSHOT", ""));
view.getVersionText().setText(model.getPOM().getGav().getVersion().replace("-SNAPSHOT", ""));
}else{
view.getCurrentVersionText().setText(constants.No_Project_Structure_Available());
view.getVersionText().setText("1.0.0");
}
}
}).load(r);
return;
}
}
}
}
public void loadRepositories() {
repositoryServices.call(new RemoteCallback<List<Repository>>() {
@Override
public void callback(final List<Repository> repositoriesResults) {
repositories = repositoriesResults;
view.getChooseRepositoryBox().addItem(constants.Select_Repository());
for (Repository r : repositories) {
view.getChooseRepositoryBox().addItem(r.getAlias(), r.getAlias());
}
}
}).getRepositories();
}
public void configureRepository(String repository, String sourceBranch, String devBranch, String releaseBranch, String version) {
assetManagementServices.call(new RemoteCallback<Long>() {
@Override
public void callback(Long taskId) {
view.displayNotification("Repository Configuration Started!");
}
}, new ErrorCallback<Message>() {
@Override
public boolean error(Message message, Throwable throwable) {
ErrorPopup.showMessage("Unexpected error encountered : " + throwable.getMessage());
return true;
}
}).configureRepository(repository, sourceBranch, devBranch, releaseBranch, version);
}
@OnOpen
public void onOpen() {
view.getChooseRepositoryBox().setFocus(true);
}
}
|
/**
* Set memory mapping to the default value based on OS properties
*
* @return this instance
*/
@NotNull
public FileStoreBuilder withDefaultMemoryMapping() {
this.memoryMapping = MEMORY_MAPPING_DEFAULT;
return this;
} |
Outside the National Anticorruption Directorate in downtown Bucharest, more than a dozen reporters and cameramen stand around chatting. It’s a weekday afternoon, and they know it’s only a matter of time before the next high-profile Romanian shows up to face charges of corruption.
Even a few years ago, Romania's powerful and well-connected were able to line their own pockets with impunity, earning the country deserved notoriety as one of Europe's most graft-ridden nations.
But today, in a perfect storm of external pressure from the European Union and internal public anger, Romania's crackdown on corruption is almost routine. With an independent and tenacious special prosecutor's office driving the effort, the country is making dramatic strides in holding elites just as accountable as the common man.
Major progress
Romania has long been considered one of the most graft-ridden countries in Europe, ranking last among European Union member states on Transparency International’s 2014 Corruption Perception Index (tied with Greece, Italy, and Bulgaria).
Yet as part of the country’s ascension into the EU, which they joined in 2007 along with neighboring Bulgaria, Romania – where graft reaches to all levels of society – was required to clean up its act.
“It started because we had the right mix of external pressure from the European Commission and internal pressure from the population,” says Laura Stefan, an anticorruption expert and a former director in the Romanian Ministry of Justice.
Yet, she adds: “When this started, there was no trust in the state. A lot of people were skeptical, and it took a long time and a lot of strong cases to convince people.”
In 2003, the country established the National Anticorruption Directorate (DNA), a specialized prosecutor's office tasked with fighting corruption and graft. Initially the DNA targeted lower-level figures, but within a few years it was aiming far higher, and the number of people convicted of high-level graft of more than 10,000 euros ($11,300) has risen accordingly.
Last year 1,138 individuals, including politicians, businessmen, judges, and prosecutors, were convicted of corruption in Romania, up from 155 in 2006. This included 24 mayors, five members of parliament, two ex-ministers, and a former prime minister, not to mention seven judges and 13 prosecutors. Those convicted include politicians of all stripes, irrespective of party lines.
High-profile targets
This year the headlines have continued to pile up. Last week Monica Iacob Ridzi, a former sports and youth minister, was sentenced to five years in prison for abuse of power and corruption. A few days earlier, a former transportation minister was also jailed, sentenced to two years for taking bribes while in office, including getting a house built for his mother free of charge.
These days Romanian news channels are fixated on the rapid fall from grace of Elena Udrea, a glamorous MP, former tourism minister, and recent presidential candidate (she finished fourth) who was arrested in mid-February on charges of money laundering, influence peddling, and taking bribes. Pundits had a field day when Ms. Udrea asked for permission to refurbish and decorate the cell she was being held in under preventive arrest.
Some 7 percent of politicians elected in 2012 have been convicted or are currently under investigation for corruption, according to estimates. The DNA’s conviction success rate is over 90 percent.
The DNA’s biggest conviction to date has been that of former Prime Minister Adrian Nastase (2000-2004), who was sentenced to four years behind bars in January 2014 for bribery and blackmail.
“Right now it is ugly, but it is a sign of progress, it shows willingness,” says Cristian Ghinea, director of the Romanian Center for European Policies, a Bucharest-based think tank.
Push back
This progress, however, has not come without a backlash.
DNA’s chief prosecutor, Laura Codruta Kovesi, has had her personal life regularly attacked in the media, particularly by news organizations owned or linked with some of the powerful men who have been targeted by DNA investigations. Last year she sued one television station for libel after it accused her of taking bribes.
Yet these public accusations seem to have had little impact on the popularity of the DNA or of Ms. Kovesi herself; in fact, some have suggested that the organization is now Romania’s fourth-most-trusted institution, behind only the church, Army, and security services.
In a statement released last month to coincide with the EU’s latest report on corruption, Frans Timmermans, vice president of the European Commission wrote that: “Romania is on the right course and needs to stick to it. Tackling corruption remains the biggest challenge and the biggest priority.”
Any remaining concerns hinge on the actions of parliament, which has previously tried to curtail the scope of investigations.
While politicians have at least publicly supported the DNA’s anticorruption drive, there have been attempts in parliament to shield elected officials from investigation and prosecution.
In December 2013, on a day dubbed Black Tuesday,the parliament passed a draft law that would have granted immunity to elected officials. The international community reacted strongly, as did many Romanians who took to the streets in protest, and the measures were later struck down.
No longer untouchable
Last November, just days after an anticorruption candidate won Romania’s latest presidential election, lawmakers were once again called to vote on a controversial amnesty bill. This one would have opened the way to releasing any inmate serving up to six years in prison for non-violent crimes – which would have included most of those serving time for corruption.
This time the vote was almost unanimously against the bill.
If there were clear-cut signs that no one is now safe from investigation, it has been in recent weeks, as first Udrea, the former presidential candidate, was arrested, and then Iulian Hertanu, the brother-in-law of Romania’s Prime Minister Victor Ponta, was detained. Mr. Hertanu was allegedly involved in embezzling funds worth around 1.75 million euros.
Get the Monitor Stories you care about delivered to your inbox. By signing up, you agree to our Privacy Policy
“The area of untouchables has gotten smaller and smaller with time,” says Ms. Stefan, the anticorruption expert.
“People are seeing for the first time, if you steal you go to jail, no matter who you are. This is the way it should be, but we need to keep the momentum.” |
import sys
import time
import struct
import statistics
from task.helper import get_data
from util.util import TcpClient, timestamp
def main():
model_name = sys.argv[1]
batch_size = int(sys.argv[2])
model_name_list = model_name.split(';')
print('List: ' + str(model_name_list))
latency_list = []
for cur_model in model_name_list:
timestamp('client', 'before_request')
data = get_data(cur_model, batch_size)
# Connect
client = TcpClient('localhost', 12345)
timestamp('client', 'after_connect')
time_1 = time.time()
# Serialize data
task_name = cur_model + '_inference'
task_name_b = task_name.encode()
task_name_length = len(task_name_b)
task_name_length_b = struct.pack('I', task_name_length)
data_b = data.numpy().tobytes()
length = len(data_b)
length_b = struct.pack('I', length)
timestamp('client', 'after_serialization')
print("N: " + task_name + ". CurM: " + cur_model)
# Send Data
client.send(task_name_length_b)
client.send(task_name_b)
client.send(length_b)
client.send(data_b)
timestamp('client', 'after_send')
# Get reply
reply_b = client.recv(4)
reply = reply_b.decode()
if reply == 'FAIL':
timestamp('client', 'FAIL')
break
timestamp('client', 'after_reply')
time_2 = time.time()
model_name_length = 0
model_name_length_b = struct.pack('I', model_name_length)
client.send(model_name_length_b)
timestamp('client', 'close_training_connection')
timestamp('**********', '**********')
latency = (time_2 - time_1) * 1000
latency_list.append(latency)
print("Inference request on machine X using model " + cur_model + " (" + str(batch_size) + " batchsize) completed for: " + str(latency) + "ms. ")
#time.sleep(2)
if __name__ == '__main__':
main() |
Saturday Night Live has been home to over a hundred cast members throughout the past 38 years. In our column Saturday Night’s Children, we present the history, talent, and best sketches of one SNL cast member every other week for your viewing, learning, and laughing pleasure.
Now that Jimmy Fallon has taken over The Tonight Show, Seth Meyers – whose last SNL episode was just over two weeks ago – is poised to take over for him on Late Night. The post-SNL path to success usually isn’t that simple for veterans of the show, or as Lorne Michaels put it: “You’re a star on SNL. That does not automatically mean you’ll be a star in everything else you touch.” Though he’s best remembered as the suited-up straight man behind the Update desk for eight seasons, Meyers spent half a decade as a regular cast member, where he played an array of drunken Irishmen, reality show hosts, Red Sox fans, Dell dudes, and frat boys.
Born in New Hampshire, Meyers got his start in comedy while attending Chicago’s Northwestern University for film, where he pledged Phi Gamma Delta and later joined the improv troupe Mee-Ow. Like his younger brother Josh, Seth continued with the Chicago improv scene after graduation, performing at the ImprovOlympic as well as Boom Chicago’s Amsterdam troupe overseas. It was there that Meyers collaborated with Boom Chicago member Jill Benjamin and developed a two-person dating-themed comedy show (dubbed an “improvised love affair”) called “Pick-ups and Hiccups,” which the pair debuted back in Chicago at The Live Bait then toured in Edinburgh, London, and even Singapore. The show caught the attention of SNL producers at the 2000 Chicago Improv Festival, and Meyers was hired as a featured player for the start of the 27th season the following year.
Like Amy Poehler, Meyers had the dubious fortune of joining the cast just two and a half weeks after 9/11. He made his first appearance in the Will Ferrell “Patriotic Shorts” sketch and soon found recurring roles with Jimmy Fallon (as DJ Jonathan Feinstein in “Jarret’s Room” and William Fitzpatrick on “Top O’ The Morning”) and Poehler, with whom he exhibited a winning chemistry. They teamed up for the British gossip show “Spy Glass” and played the inexplicably still-married couple Dan and Sally Needler. While mostly supporting or straight-man roles in sketches, Meyers also had a few starring characters of his own like the zinger-loving David Clinger, the shocked “Pranksters” host Zach Ricky, and Nerod, the heard-it-all receptionist at the “Appalachian Emergency Room.” He also impersonated over 30 celebrities during his 13 years on the show including Michael Caine, Carrot Top, Anderson Cooper, John Kerry, and Prince Charles. (Check out a videolist of Meyers’s best sketches here.)
Following Tina Fey’s departure in 2006, Meyers was promoted to co-head writer and joined Poehler at the Weekend Update desk (he had auditioned to co-anchor opposite Fey back in 2004 but lost out to Poehler). The chemistry Poehler and Meyers had developed since their shared baptism-by-fire newbie days paid off in recurring bits like “Really!?! with Seth and Amy” and their willingness to entertain a barrage of Update guest usuals helped make the current news segment the only reason many viewers tuned in, from Fred Armisen’s blind New Jersey governor David Paterson to Bill Hader’s nightclub hopping favorite Stefon, who married Meyers during Hader’s final episode in May 2013. Where Tina and Amy rocked the segment during its lone female-dominated era, Amy and Seth shared a similar buddy-buddy rapport, and Meyers made the perfect foil for Amy’s beamy delivery, often playing the straight man while Poehler provided silly outbursts and the occasional musical performance like her famous Sarah Palin rap.
With a total of 154 episodes, Meyers holds the record as the longest running anchor in Weekend Update history, and his work as head writer helped nurture The Lonely Island’s Digital Shorts and guide the show through the 2008 presidential election. Meyers is also credited for writing the Girls promo parody for host Tina Fey, the Lincoln-focused Louie spoof for Louis C.K., and all of Fey’s lines during her brief return to SNL as Sarah Palin in the late 2000s. Alongside SNL producer Michael Shoemaker, Meyers also created the superhero-themed animated half-hour web series The Awesomes produced by Lorne Michaels’s Broadway Video and available on Hulu. The series features a ton of SNL voice talent including Bill Hader, Paula Pell, Taran Killam, Bobby Moynihan, and producer Steve Higgins.
When it was announced last year that Jimmy Fallon would be succeeding Jay Leno as host of The Tonight Show and returning the show to its original NYC home – a move that made Lorne Michaels the head of both NBC late night shows – Meyers was speculated as the frontrunner to take over Late Night. NBC confirmed the news in May, noting Meyers as “one of the brightest, most insightful comedy writers and performers of his generation.” While we’ll have to wait a few more days to see Meyers in action at the Late Night desk, his best SNL moments often came from helping his cast mates shine brighter or bouncing back from a flop Weekend Update joke with charm and style, which will no doubt serve him well in his new gig. “His comedy brain is certainly something that will be missed, but his heart, also,” cast mate Will Forte told Huffington Post earlier this month. “There’s this energy that he brings and a positivity that is such a wonderful thing to have.” That’s still no proof that Meyers will excel beyond the SNL bubble, but considering his willingness to share the spotlight and high reputation among his SNL collaborators, it seems like a sure bet that he will. |
<reponame>nullcodeexecutor/rural
package org.rural.render;
import org.rural.ui.Model;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by yuantao on 2014/8/10.
*/
public interface View {
void render(String view, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, ServletException;
}
|
/**
* Creates Imagekit CDN URL
* @param url - URL which need to be CDNified
* @param height - Height of the image
* @param width - Width of the image
* @returns cdn url of the passed URL
*/
export function imagekitURL(
url: string | undefined | null,
height: string | number = '',
width: string | number = ''
): string {
return `https://ik.imagekit.io/devparty/tr:w-${height},h-${width}/${url}`
}
|
American breed of domestic chicken
Barred hen
Plymouth Rock egg
The Plymouth Rock is an American breed of domestic chicken. It was first seen in Massachusetts in the nineteenth century, and for much of the early twentieth century was the most popular chicken breed in the United States. It is a dual-purpose breed, raised both for its meat and for its brown eggs. It is resistant to cold, easy to manage, and a good sitter.[2][6]:68
History [ edit ]
The Plymouth Rock was first shown in Boston in 1849, but was then not seen for another twenty years.[2] In 1869, in Worcester, Massachusetts, one D.A. Upham cross-bred some Black Java hens with a cock with barred plumage and a single comb; he selectively bred for barred plumage and clean (featherless) legs.[6]:68 His birds were shown in Worcester in 1869; the modern Plymouth Rock is thought to derive from them.[2] Other people have been associated with the development of the Plymouth Rock, as have other chicken breeds including the Brahma, the Cochin (both white and buff), the Dominique, and the White-faced Black Spanish.[2]
The Plymouth Rock was added to the Standard of Excellence of the American Poultry Association in 1874.[2] The barred plumage pattern was the original one; other colors were later added.[2]
Because of its many good qualities – tasty meat, good egg production, resistance to cold, early feathering, easy management, good sitting – the Plymouth Rock became the most widespread chicken breed in the United States until the time of World War II.[2] With the advent of industrial chicken farming, it was much used in the development of broiler hybrids, but began to fall in popularity as a domestic fowl.[6]:68
The Plymouth Rock is listed by the Livestock Conservancy as "recovering", meaning that there are at least 2500 new registrations per year. Worldwide, numbers for the Plymouth Rock are reported at almost 33,000;[7] about 24,000 are reported for the Barred Plymouth Rock,[8] and over 970,000 for the White variety.[9]
Characteristics [ edit ]
The Plymouth Rock has a single comb with five points; the comb, wattles and ear-lobes are bright red. The legs are yellow and unfeathered. The beak is yellow or horn-colored.[6]:69
In the United States, seven color varieties of the Plymouth Rock are recognized: Barred, Blue, Buff, Columbian, Partridge, Silver-penciled and White.[3] Ten plumage varieties are listed by the Entente Européenne d’Aviculture et de Cuniculture, of which five – Barred, Black, Buff, Columbian and White – are recognized by the Poultry Club of Great Britain.[4] In Australia, the Barred variant is split into two separate colors, Dark Barred and Light Barred.[10]
Use [ edit ]
The Plymouth Rock is a dual-purpose breed, and is kept both for its meat and for its large brown eggs, of which it lays about 200 per year.[2] |
def process_process_image(img_info):
from datetime import datetime
import time
from image import b64_to_image
from image import image_to_b64
logging.info("Starting process for processing {} to user {}"
.format(img_info["filename"], img_info["username"]))
keys = ["username", "filename", "image"]
for key in keys:
status = validate_input(key, img_info[key])
if status["code"] != 200:
return status
_, status = validate_user(img_info["username"])
if status["code"] != 200:
return status
orig_img = b64_to_image(img_info["image"])
img = orig_img
procs = ["Original", "Histogram Equalization", "Contrast Stretching",
"Log Compression", "Reverse Video"]
t1 = time.time()
processes = list(img_info["proc_step"])
if len(processes) == 5:
for ind, proc in enumerate(processes):
if proc == '1':
try:
logging.info(procs[ind])
proc_img = run_image_processing(img, procs[ind])
img = proc_img
except:
status = {"code": 404,
"msg": "Processing method not defined"}
logging.warning("{} was unable to be {} processed."
.format(img_info["filename"],
procs[ind]))
return status
elif proc == '0':
pass
else:
status = {"code": 404,
"msg": "Processing method not defined"}
else:
status = {"code": 400,
"msg": "Too many processing methods defined"}
t2 = time.time()
img_info["proc_image"] = image_to_b64(img)
logging.info("Storing processing time")
img_info["proc_time"] = t2-t1
img_info["size"] = get_img_size(img_info["image"])
img_info["proc_size"] = get_img_size(img_info["proc_image"])
logging.info("Providing a timestamp")
img_info["timestamp"] = datetime.now()
upload_processed_image(img_info)
return status |
/*
* Copyright © 2018 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.internal.app;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import io.cdap.cdap.api.artifact.ArtifactScope;
import io.cdap.cdap.api.macro.InvalidMacroException;
import io.cdap.cdap.api.macro.MacroEvaluator;
import io.cdap.cdap.api.macro.MacroParserOptions;
import io.cdap.cdap.api.plugin.Plugin;
import io.cdap.cdap.api.plugin.PluginClass;
import io.cdap.cdap.api.plugin.PluginConfigurer;
import io.cdap.cdap.api.plugin.PluginProperties;
import io.cdap.cdap.api.plugin.PluginSelector;
import io.cdap.cdap.internal.app.runtime.artifact.ArtifactDescriptor;
import io.cdap.cdap.internal.app.runtime.artifact.PluginFinder;
import io.cdap.cdap.internal.app.runtime.plugin.FindPluginHelper;
import io.cdap.cdap.internal.app.runtime.plugin.MacroParser;
import io.cdap.cdap.internal.app.runtime.plugin.PluginClassLoader;
import io.cdap.cdap.internal.app.runtime.plugin.PluginInstantiator;
import io.cdap.cdap.internal.app.runtime.plugin.PluginNotExistsException;
import io.cdap.cdap.internal.lang.CallerClassSecurityManager;
import io.cdap.cdap.proto.id.ArtifactId;
import io.cdap.cdap.proto.id.NamespaceId;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Abstract base implementation of {@link PluginConfigurer}.
*/
public class DefaultPluginConfigurer implements PluginConfigurer {
private final ArtifactId artifactId;
private final NamespaceId pluginNamespaceId;
private final PluginInstantiator pluginInstantiator;
private final PluginFinder pluginFinder;
private final Map<String, PluginWithLocation> plugins;
public DefaultPluginConfigurer(ArtifactId artifactId, NamespaceId pluginNamespaceId,
PluginInstantiator pluginInstantiator, PluginFinder pluginFinder) {
this.artifactId = artifactId;
this.pluginNamespaceId = pluginNamespaceId;
this.pluginInstantiator = pluginInstantiator;
this.pluginFinder = pluginFinder;
this.plugins = new HashMap<>();
}
public PluginInstantiator getPluginInstantiator() {
return pluginInstantiator;
}
public Map<String, PluginWithLocation> getPlugins() {
return Collections.unmodifiableMap(plugins);
}
@Nullable
@Override
public final <T> T usePlugin(String pluginType, String pluginName, String pluginId,
PluginProperties properties, PluginSelector selector) {
try {
Plugin plugin = addPlugin(pluginType, pluginName, pluginId, properties, selector);
return pluginInstantiator.newInstance(plugin);
} catch (PluginNotExistsException | IOException e) {
return null;
} catch (ClassNotFoundException e) {
// Shouldn't happen
throw Throwables.propagate(e);
}
}
@Nullable
@Override
public final <T> Class<T> usePluginClass(String pluginType, String pluginName, String pluginId,
PluginProperties properties, PluginSelector selector) {
try {
Plugin plugin = addPlugin(pluginType, pluginName, pluginId, properties, selector);
return pluginInstantiator.loadClass(plugin);
} catch (PluginNotExistsException | IOException e) {
return null;
} catch (ClassNotFoundException e) {
// Shouldn't happen
throw Throwables.propagate(e);
}
}
@Override
public Map<String, String> evaluateMacros(Map<String, String> properties, MacroEvaluator evaluator,
MacroParserOptions options) throws InvalidMacroException {
MacroParser macroParser = new MacroParser(evaluator, options);
Map<String, String> evaluated = new HashMap<>();
properties.forEach((key, val) -> evaluated.put(key, macroParser.parse(val)));
return evaluated;
}
private Plugin addPlugin(String pluginType, String pluginName, String pluginId,
PluginProperties properties, PluginSelector selector) throws PluginNotExistsException {
PluginWithLocation existing = plugins.get(pluginId);
if (existing != null) {
throw new IllegalArgumentException(String.format("Plugin of type %s, name %s was already added as id %s.",
existing.getPlugin().getPluginClass().getType(),
existing.getPlugin().getPluginClass().getName(), pluginId));
}
final Class[] callerClasses = CallerClassSecurityManager.getCallerClasses();
if (callerClasses.length < 3) {
// This shouldn't happen as there should be someone calling this method.
throw new IllegalStateException("Invalid call stack.");
}
Set<ArtifactId> parents = new LinkedHashSet<>();
// go through the call stack to get the parent plugins. This is to support plugins of plugins.
// for example, suppose appX uses pluginY, which uses pluginZ. When we try to use pluginZ, we need to first
// check if pluginZ extends pluginY. If it does not, we then check if it extends appX.
// 0 is the CallerClassSecurityManager, 1 is this class, hence 2 is the actual caller
for (int i = 2; i < callerClasses.length; i++) {
ClassLoader classloader = callerClasses[i].getClassLoader();
if (classloader instanceof PluginClassLoader) {
// if this is the first time we've seen this plugin artifact, it must be a new plugin parent.
io.cdap.cdap.api.artifact.ArtifactId pluginCallerArtifactId = ((PluginClassLoader) classloader).getArtifactId();
parents.add((pluginCallerArtifactId.getScope() == ArtifactScope.SYSTEM ? NamespaceId.SYSTEM : pluginNamespaceId)
.artifact(pluginCallerArtifactId.getName(), pluginCallerArtifactId.getVersion().getVersion()));
}
}
PluginNotExistsException exception = null;
for (ArtifactId parentId : Iterables.concat(parents, Collections.singleton(artifactId))) {
try {
Map.Entry<ArtifactDescriptor, PluginClass> pluginEntry = pluginFinder.findPlugin(pluginNamespaceId, parentId,
pluginType, pluginName,
selector);
Plugin plugin = FindPluginHelper.getPlugin(Iterables.transform(parents, ArtifactId::toApiArtifactId),
pluginEntry, properties, pluginInstantiator);
plugins.put(pluginId, new PluginWithLocation(plugin, pluginEntry.getKey().getLocation()));
return plugin;
} catch (PluginNotExistsException e) {
// ignore this in case the plugin extends something higher up in the call stack.
// For example, suppose the app uses pluginA, which uses pluginB. However, pluginB is a plugin that
// has the app as its parent and not pluginA as its parent. In this case, we want to keep going up the call
// stack until we get to the app as the parent, which would be able to find plugin B.
exception = e;
}
}
throw exception == null ? new PluginNotExistsException(pluginNamespaceId, pluginType, pluginName) : exception;
}
}
|
/* ---------- empty prototype function for copy and expand ---------- */
static wchar_t ocr0_XXX(ocr0_shared_t *sdata){
struct box *box1=sdata->box1;
pix *bp=sdata->bp;
int i,j,d,x,y,i0,i1,i2,i3,hchar=sdata->hchar,gchar=sdata->gchar,
x0=box1->x0,x1=box1->x1,y0=box1->y0,y1=box1->y1,cs=sdata->cs;
int dx=x1-x0+1,dy=y1-y0+1,
ac,ad;
return box1->c;
} |
def _save_plus_one_hub_module_v1(path):
def plus_one():
x = tf.compat.v1.placeholder(dtype=tf.float32, name="x")
y = x + 1
hub.add_signature(inputs=x, outputs=y)
spec = hub.create_module_spec(plus_one)
_export_module_spec_with_init_weights(spec, path) |
<gh_stars>1-10
import React from 'react'
import { useTranslation } from 'react-i18next'
import { SceneData, SceneMetadata } from '@xrengine/common/src/interfaces/SceneInterface'
import { useAuthState } from '../../../user/services/AuthService'
import ConfirmModel from '../../common/ConfirmModel'
import TableComponent from '../../common/Table'
import { sceneColumns, SceneProps, SceneViewModel } from '../../common/variables/scene'
import { SCENE_PAGE_LIMIT, SceneService, useSceneState } from '../../services/SceneService'
import { useStyles } from '../../styles/ui'
import ViewScene from './ViewScene'
const SceneTable = (props: SceneProps) => {
// const classes = useStyles()
// const authState = useAuthState()
// const user = authState.user
// const { t } = useTranslation()
// const scene = useSceneState()
// const sceneData = scene?.scenes
// const sceneCount = scene?.total
// const [singleScene, setSingleScene] = React.useState<SceneMetadata>(null!)
// const [open, setOpen] = React.useState(false)
// const [sceneName, setSceneName] = React.useState<string | JSX.Element>('')
// const [popConfirmOpen, setPopConfirmOpen] = React.useState(false)
// const [sceneId, setSceneId] = React.useState('')
// const [page, setPage] = React.useState(0)
// const [rowsPerPage, setRowsPerPage] = React.useState(SCENE_PAGE_LIMIT)
// React.useEffect(() => {
// if (user.id.value && scene.updateNeeded.value) {
// SceneService.fetchAdminScenes()
// }
// }, [user, scene.updateNeeded.value])
// const handlePageChange = (event: unknown, newPage: number) => {
// const incDec = page < newPage ? 'increment' : 'decrement'
// SceneService.fetchAdminScenes(incDec)
// setPage(newPage)
// }
// const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// setRowsPerPage(+event.target.value)
// setPage(0)
// }
// const handleClose = (open: boolean) => {
// setOpen(open)
// }
// const handleViewScene = (id: string) => {
// const scene = sceneData?.value.find((sc) => sc.id === id)
// if (scene !== undefined) {
// setSingleScene(scene)
// setOpen(true)
// }
// }
// const handleCloseModel = () => {
// setPopConfirmOpen(false)
// }
// const submitRemoveLocation = async () => {
// await SceneService.deleteScene(sceneId)
// setPopConfirmOpen(false)
// }
// const createData = (
// id: string,
// name: string | JSX.Element,
// type: string | JSX.Element,
// description: string | JSX.Element,
// entity: number | JSX.Element,
// version: string | JSX.Element
// ): SceneViewModel => {
// return {
// id,
// name,
// description,
// type,
// entity,
// version,
// action: (
// <>
// <a href="#h" className={classes.actionStyle}>
// <span className={classes.spanWhite} onClick={() => handleViewScene(id)}>
// {t('admin:components.index.view')}
// </span>
// </a>
// <a
// href="#h"
// className={classes.actionStyle}
// onClick={() => {
// setPopConfirmOpen(true)
// setSceneId(id)
// setSceneName(name)
// }}
// >
// <span className={classes.spanDange}>{t('admin:components.index.delete')}</span>
// </a>
// </>
// )
// }
// }
// const rows = sceneData?.value.map((el) => {
// return createData(
// el.id!,
// el.name || <span className={classes.spanNone}>{t('admin:components.index.none')}</span>,
// el.type || <span className={classes.spanNone}>{t('admin:components.index.none')}</span>,
// el.description || <span className={classes.spanNone}>{t('admin:components.index.none')}</span>,
// el.entities?.length || <span className={classes.spanNone}>{t('admin:components.index.none')}</span>,
// el.version || <span className={classes.spanNone}>{t('admin:components.index.none')}</span>
// )
// })
// return (
// <React.Fragment>
// <TableComponent
// rows={rows}
// column={sceneColumns}
// page={page}
// rowsPerPage={rowsPerPage}
// count={sceneCount?.value}
// handlePageChange={handlePageChange}
// handleRowsPerPageChange={handleRowsPerPageChange}
// />
// <ConfirmModel
// popConfirmOpen={popConfirmOpen}
// handleCloseModel={handleCloseModel}
// submit={submitRemoveLocation}
// name={sceneName}
// label={'scene'}
// />
// {singleScene && <ViewScene adminScene={singleScene} viewModal={open} closeViewModal={handleClose} />}
// </React.Fragment>
// )
}
export default SceneTable
|
n=int(input())
l=list(input())
z=[]
for i in range(n):
x,y=map(str,input().split("->"))
z.append(x)
z.append(y)
z1=list(set(z))
z2=[]
for i in range(len(z1)):
z2.append(z.count(z1[i]))
for i in range(len(z2)):
if z2[i]%2==1:
print("contest")
break
else:
print("home") |
<reponame>rokjoana/kiya<filename>generate.go
package kiya
import (
"bytes"
"crypto/rand"
"math/big"
)
// default set contains characters that do not required URL encoding
// the kiya configuration can override this set per profile.
const defaultSecreteCharSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-~"
// GenerateSecret composes a random secrets using runes from a give set.
func GenerateSecret(length int, runes []rune) (string, error) {
if len(runes) == 0 {
runes = []rune(defaultSecreteCharSet)
}
var buffer bytes.Buffer
for i := 0; i < length; i++ {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(runes))))
if err != nil {
return "", err
}
buffer.WriteRune(runes[n.Int64()])
}
return buffer.String(), nil
}
|
// New creates a new Client instance
func New(httpClient http.Client, baseUrl string) Client {
return &client{
httpClient: httpClient,
baseUrl: baseUrl,
}
} |
Removing long-term errors from the AVHRR observation based on Normalized Difference Vegetation Index (NDVI)
This paper investigates Normalized Difference Vegetation Index (NDVI) stability in the NOAA/NESDIS Global Vegetation Index (GVI) data during 1982-2003. Advanced Very High Resolution Radiometer (AVHRR) weekly data for the five NOAA afternoon satellites for the China dataset is studied, for it includes a wide variety of different ecosystems represented globally. It was found that data for the years 1988, 1992, 1993, 1994, 1995 and 2000 are not stable enough compared to other years because of satellite orbit drift, and AVHRR sensor degradation. It is assumed that data from NOAA-7 (1982, 1983), NOAA-9 (1985, 1986), NOAA-11 (1989, 1990), NOAA-14 (1996, 1997), and NOAA-16 (2001, 2002) to be standard because these satellite's equator crossing time fall within 1330 and 1500, and hence maximizing the value of coefficients. The crux of the proposed correction procedure consists of dividing standard year's data sets into two subsets. The subset 1 (standard data correction sets) is used for correcting unstable years and then corrected data for this years compared with the standard data in the subset 2 (standard data validation sets). In this paper, we apply empirical distribution function (EDF) to correct this deficiency of data for the affected years. We normalize or correct NDVI data by the method of EDF compared with the standard. Using these normalized values, we estimate new NDVI time series which provides NDVI data for these years that match in subset 2 that is used for data validation. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.