content
stringlengths 10
4.9M
|
---|
package com.company.MidExam.E02;
import java.math.BigDecimal;
import java.util.*;
public class P03Numbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbersArr = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
double total = 0;
for (int i = 0; i < numbersArr.length; i++) {
int currentNumber = numbersArr[i];
total = total + currentNumber;
}
//10 20 30 40 50
double average = total / numbersArr.length;
List<BigDecimal> topNumbers = new ArrayList<>();
for (int i = 0; i < numbersArr.length; i++) {
int currentNum = numbersArr[i];
if (currentNum > average) {
topNumbers.add(BigDecimal.valueOf(currentNum));
}
}
Collections.sort(topNumbers);
Collections.reverse(topNumbers);
if (topNumbers.size() > 5) {
for (int i = 0; i < 5; i++) {
System.out.print(topNumbers.get(i) + " ");
}
} else if (topNumbers.isEmpty()) {
System.out.println("No");
} else {
System.out.println(topNumbers.toString().replaceAll("[\\[\\],]", ""));
}
}
}
|
import styled from "styled-components";
export const CardSearch = styled.div`
width: 282px;
height: auto;
left: 0px;
top: 100px;
margin-top: 20px;
background: #29274B;
box-shadow: 0px 0px 30px rgba(0, 0, 0, 0.5);
border-radius: 10px;
@media only screen and (max-width: 600px) {
width: 100%;
display: inline-block;
}
`;
export const HeaderSearch = styled.div`
display: flex;
flex-direction: row;
place-content: space-between;
padding: 20px;
`;
export const TitleSearch = styled.div`
font-family: SF Pro Display;
font-style: normal;
font-weight: 600;
font-size: 16px;
line-height: 20px;
`;
export const IconDown = styled.div`
width: 25px;
height: 20px;
margin-right: 10px;
background-image: url("/images/icon-down.png");
background-repeat: no-repeat;
background-position: center;
`;
export const TextWithoutResults = styled.div`
font-family: SF Pro Display;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 24px;
padding-bottom: 20px;
`;
export const BodySearch = styled.div`
width: 100%;
font-family: SF Pro Display;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 24px;
padding: 0px 20px 20px 20px;
`;
export const TextCheckbox = styled.div`
font-family: SF Pro Display;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 24px;
padding-left: 28px;
`;
export const CheckboxContainer = styled.div`
flex-direction: row;
`; |
<gh_stars>1-10
package string_memset
import (
unsafe "unsafe"
libc "github.com/goplus/libc"
testing "testing"
)
var buf_cgo1 [400]int8
var buf2_cgo2 [400]int8
var pmemset_cgo3 func(unsafe.Pointer, int32, uint64) unsafe.Pointer
func aligned_cgo4(p unsafe.Pointer) *int8 {
return (*int8)(unsafe.Pointer(uintptr((uint64(uintptr(p)) + uint64(63)) & uint64(18446744073709551552))))
}
func test_align_cgo5(align int32, len int32) {
var s *int8 = (*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(aligned_cgo4(unsafe.Pointer((*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1))))+uintptr(int32(64)))))))) + uintptr(align)))
var want *int8 = (*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(aligned_cgo4(unsafe.Pointer((*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf2_cgo2))))+uintptr(int32(64)))))))) + uintptr(align)))
var p *int8
var i int32
if int64(len+int32(64)) > int64(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1))))+uintptr(int32(400))))))-uintptr(unsafe.Pointer(s))) || int64(len+int32(64)) > int64(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf2_cgo2))))+uintptr(int32(400))))))-uintptr(unsafe.Pointer(want))) {
libc.Abort()
}
for i = int32(0); i < int32(400); i++ {
*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1)))) + uintptr(i))) = func() (_cgo_ret int8) {
_cgo_addr := &*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf2_cgo2)))) + uintptr(i)))
*_cgo_addr = int8(' ')
return *_cgo_addr
}()
}
for i = int32(0); i < len; i++ {
*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(want)) + uintptr(i))) = int8('#')
}
p = (*int8)(pmemset_cgo3(unsafe.Pointer(s), '#', uint64(len)))
if uintptr(unsafe.Pointer(p)) != uintptr(unsafe.Pointer(s)) {
t_printf((*int8)(unsafe.Pointer(&[63]int8{'s', 'r', 'c', '/', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', 'a', 'l', '/', 's', 't', 'r', 'i', 'n', 'g', '_', 'm', 'e', 'm', 's', 'e', 't', '.', 'c', ':', '3', '2', ':', ' ', 'm', 'e', 'm', 's', 'e', 't', '(', '%', 'p', ',', '.', '.', '.', ')', ' ', 'r', 'e', 't', 'u', 'r', 'n', 'e', 'd', ' ', '%', 'p', '\n', '\x00'})), s, p)
}
for i = -64; i < len+int32(64); i++ {
if int32(*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(s)) + uintptr(i)))) != int32(*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(want)) + uintptr(i)))) {
t_printf((*int8)(unsafe.Pointer(&[79]int8{'s', 'r', 'c', '/', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', 'a', 'l', '/', 's', 't', 'r', 'i', 'n', 'g', '_', 'm', 'e', 'm', 's', 'e', 't', '.', 'c', ':', '3', '5', ':', ' ', 'm', 'e', 'm', 's', 'e', 't', '(', 'a', 'l', 'i', 'g', 'n', ' ', '%', 'd', ',', ' ', '\'', '#', '\'', ',', ' ', '%', 'd', ')', ' ', 'f', 'a', 'i', 'l', 'e', 'd', ' ', 'a', 't', ' ', 'p', 'o', 's', ' ', '%', 'd', '\n', '\x00'})), align, len, i)
t_printf((*int8)(unsafe.Pointer(&[14]int8{'g', 'o', 't', ' ', ':', ' ', '\'', '%', '.', '*', 's', '\'', '\n', '\x00'})), len+int32(128), (*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(s))-uintptr(int32(64)))))
t_printf((*int8)(unsafe.Pointer(&[14]int8{'w', 'a', 'n', 't', ':', ' ', '\'', '%', '.', '*', 's', '\'', '\n', '\x00'})), len+int32(128), (*int8)(unsafe.Pointer(uintptr(unsafe.Pointer(want))-uintptr(int32(64)))))
break
}
}
}
func test_value_cgo6(c int32) {
var i int32
pmemset_cgo3(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1))), c, uint64(10))
for i = int32(0); i < int32(10); i++ {
if int32(uint8(*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1)))) + uintptr(i))))) != int32(uint8(c)) {
t_printf((*int8)(unsafe.Pointer(&[62]int8{'s', 'r', 'c', '/', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', 'a', 'l', '/', 's', 't', 'r', 'i', 'n', 'g', '_', 'm', 'e', 'm', 's', 'e', 't', '.', 'c', ':', '4', '9', ':', ' ', 'm', 'e', 'm', 's', 'e', 't', '(', '%', 'd', ')', ' ', 'f', 'a', 'i', 'l', 'e', 'd', ':', ' ', 'g', 'o', 't', ' ', '%', 'd', '\n', '\x00'})), c, int32(*(*int8)(unsafe.Pointer(uintptr(unsafe.Pointer((*int8)(unsafe.Pointer(&buf_cgo1)))) + uintptr(i)))))
break
}
}
}
func _cgo_main() int32 {
var i int32
var j int32
pmemset_cgo3 = libc.Memset
for i = int32(0); i < int32(16); i++ {
for j = int32(0); j < int32(200); j++ {
test_align_cgo5(i, j)
}
}
test_value_cgo6('c')
test_value_cgo6(int32(0))
test_value_cgo6(-1)
test_value_cgo6(-5)
test_value_cgo6(int32(171))
return t_status
}
func TestMain(t *testing.T) {
if _cgo_ret := _cgo_main(); _cgo_ret != 0 {
t.Fatal("exit status", _cgo_ret)
}
}
|
<filename>spring/interfacesDAO/AdminDAOInterface.java
package ttps.spring.interfacesDAO;
import ttps.spring.model.Admin;
public interface AdminDAOInterface extends GenericDAOInterface<Admin> {
public Admin recuperarAdmin(Long id);
} |
import Hooks from 'burdy/src/shared/features/hooks';
import asyncMiddleware from 'burdy/src/server/middleware/async.middleware';
import Tag from 'burdy/src/server/models/tag.model';
import { getEnhancedRepository } from 'burdy/src/server/common/orm-helpers';
import Post from 'burdy/src/server/models/post.model';
import { compilePost, publishedQuery } from 'burdy/src/server/common/post.utility';
Hooks.addAction('api/init', async (app) => {
app.get('/categories', asyncMiddleware(async (req, res) => {
const tagsRepository = getEnhancedRepository(Tag);
const qb = tagsRepository.createQueryBuilder('tag')
.leftJoinAndSelect('tag.parent', 'parent')
.where('parent.slug = :slug', {slug: 'category'})
const categories = await qb.getMany();
res.send(categories);
}));
app.get('/blogs', asyncMiddleware(async (req, res) => {
const {tags} = req.query as any;
const postRepository = getEnhancedRepository(Post);
const countQb = postRepository.createQueryBuilder('post_count')
.leftJoinAndSelect('post_count.contentType', 'contentType')
.leftJoinAndSelect('post_count.tags', 'tags')
.leftJoinAndSelect('tags.parent', 'tags.parent')
.where('post_count.type = :type', {type: 'post'})
.andWhere('contentType.name = :name', {name: 'blogs'})
if (tags?.length > 0) {
countQb.andWhere('tags.slugPath IN(:...tags)', {tags})
}
publishedQuery(countQb, 'post_count' as any);
const qb = postRepository.createQueryBuilder('post')
.leftJoinAndSelect('post.contentType', 'contentType')
.leftJoinAndSelect('post.author', 'author')
.leftJoinAndSelect('post.meta', 'meta')
.leftJoinAndSelect('post.tags', 'tags')
.leftJoinAndSelect('tags.parent', 'tags.parent')
.where('post.type = :type', {type: 'post'})
.andWhere('contentType.name = :name', {name: 'blogs'})
publishedQuery(qb);
if (tags?.length > 0) {
qb.andWhere('tags.slugPath IN(:...tags)', {tags})
}
qb.addOrderBy('post.updatedAt', 'DESC');
const [posts, count] = await Promise.all([
qb.getMany(),
countQb.getCount()
]);
const compiledPosts = await Promise.all(posts.map(post => compilePost(post)));
res.send({
count,
data: compiledPosts
});
}));
app.get('/blogs/:slug', asyncMiddleware(async (req, res) => {
const postRepository = getEnhancedRepository(Post);
const qb = postRepository.createQueryBuilder('post')
.leftJoinAndSelect('post.contentType', 'contentType')
.leftJoinAndSelect('post.author', 'author')
.leftJoinAndSelect('post.meta', 'meta')
.leftJoinAndSelect('post.tags', 'tags')
.leftJoinAndSelect('tags.parent', 'tags.parent')
.where('post.slug = :slug', {slug: req.params.slug})
.andWhere('post.type = :type', {type: 'post'})
.andWhere('contentType.name = :name', {name: 'blogs'})
publishedQuery(qb);
const post = await qb.getOne();
const compiled = await compilePost(post);
res.send(compiled);
}));
app.get('/uncompiled/:slug', asyncMiddleware(async (req, res) => {
const postRepository = getEnhancedRepository(Post);
const qb = postRepository.createQueryBuilder('post')
.leftJoinAndSelect('post.contentType', 'contentType')
.leftJoinAndSelect('post.author', 'author')
.leftJoinAndSelect('post.meta', 'meta')
.leftJoinAndSelect('post.tags', 'tags')
.leftJoinAndSelect('tags.parent', 'tags.parent')
.where('post.slug = :slug', {slug: req.params.slug})
.andWhere('post.type = :type', {type: 'post'})
.andWhere('contentType.name = :name', {name: 'blogs'})
publishedQuery(qb);
const post = await qb.getOne();
res.send(post);
}))
})
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DaffProductModule } from '@daffodil/product';
import { DaffLoadingIconModule } from '@daffodil/design';
import { ProductGridModule } from '../product-grid/product-grid.module';
import { BestSellersComponent } from './best-sellers.component';
@NgModule({
imports: [
CommonModule,
DaffLoadingIconModule,
ProductGridModule,
DaffProductModule
],
declarations: [
BestSellersComponent
],
exports: [
BestSellersComponent
]
})
export class BestSellersModule { }
|
<gh_stars>0
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'cabinets': reverse('api_v1:hardware:cabinet-list', request=request, format=format),
'cabinet-assignments': reverse('api_v1:hardware:cabinetassignment-list', request=request, format=format),
'datacenters': reverse('api_v1:hardware:datacenter-list', request=request, format=format),
'network': reverse('api_v1:hardware:networkdevice-list', request=request, format=format),
'pdus': reverse('api_v1:hardware:powerdistributionunit-list', request=request, format=format),
'port-assignments': reverse('api_v1:hardware:portassignment-list', request=request, format=format),
'servers': reverse('api_v1:hardware:server-list', request=request, format=format),
})
|
For Whom the Bell Trolls: Troll Behaviour in the Twitter Brexit Debate
In a review into automated and malicious activity Twitter released a list of accounts that they believed were connected to state sponsored manipulation of the 2016 American Election. This list details 2,752 accounts Twitter believed to be controlled by Russian operatives. In the absence of a similar list of operatives active within the debate on the 2016 UK referendum on membership of the European Union (Brexit) we investigated the behaviour of the same American Election focused accounts in the production of content related to the UK-EU referendum. We found that within our dataset we had Brexit-related content from 419 of these accounts, leading to 3,485 identified tweets gathered between the 29th August 2015 and 3rd October 2017. The behaviour of the accounts altered radically on the day of the referendum, shifting from generalised disruptive tweeting to retweeting each other in order to amplify content produced by other troll accounts. We also demonstrate that, while these accounts are, in general, designed to resemble American citizens, accounts created in 2016 often contained German locations and terms in the user profiles.
Introduction
Trolls are internet users who attempt to manipulate opinion by spreading rumours, speculation and false information (Mihaylov, Georgiev, and Nakov 2015). Twitter identified 2,752 troll accounts they claim are likely run by the Internet Research Agency (IRA), a Russian company that was identified as tweeting about the US 2016 elections. 1 2 We have been collecting tweets on the topic of the UK-EU 'Brexit' referendum since August 2015. In our dataset we have 3,485 tweets from 419 troll accounts that were collected between the 29th August 2015 and 3rd October 2017. These tweets were about the Brexit vote and topics that were expected to influence the vote, such as the EU, refugees and migrants. In total, we have collected over 70 million Brexit-related tweets; 3,485 is therefore a tiny proportion of the overall number but does indicate that these trolls, who tweeted about the US elections, were also active in the Brexit debate.
1 https://democrats-intelligence.house.gov/ uploadedfiles/exhibit_b.pdf 2 Twitter released a further 1,062 accounts on the 19th January 2018, these are not included in this study As a consequence of our ethical procedure and following legal advice we are unable to disclose or share usernames, the usernames of retweeted users (unless they are verified users) or any full tweets. We utilise this information in our analysis but it remains confidential. Access to any images or videos contained in these tweets is no longer possible as these have been removed from the Twitter website. Our findings, utilising the tweet text and metadata from derived and aggregated data allow us to provide important insights into the behaviour of these Twitter trolls and the types of content that their tweets contain.
Senate Testimony
On October 31st 2017 Sean Edgett, a legal representative of Twitter, presented evidence to the United States Senate Judiciary Subcommittee on Crime and Terrorism. 3 His report provided details of 36,746 accounts that automatically generated election content (referred to as 'bots'). He also provided details of 2,752 accounts that were linked to the IRA, a Russian company thought to be involved in the creation of online propaganda. He stated that these 2,752 accounts were identified using information obtained by Twitter from third-party sources. These 2,752 accounts also produced automated content, but approximately 53% of the content associated with these accounts was produced by humans (referred to as 'trolls').
Twitter studied tweets from 1st September 2016 to 15th November 2016. Not all of the content posted by these accounts during the time period studied was about the US election (only approximately 9%) and over 47% of the content was automated. In written testimony these accounts were described as being 'Russian election-focused efforts'. 2 The troll accounts posed as news outlets, activists, and politically engaged Americans. Edgett's testimony describes the troll behaviour as: contacting prominent individuals through mentions, organising political events and abusive behaviour and harassment. All 2,752 accounts have been suspended and the information posted by them is therefore no longer available through Twitter.
As part of a review of 'Fake News' the British Member of Parliament, Damian Collins, who is the Chair of the Digital, Culture, Media and Sports Select Committee asked that the UK parliament be provided with 'a list of accounts linked to the Internet Research Agency and any other Russian linked accounts that it has removed and examples of any posts from these accounts that are linked to the United Kingdom'. 4 Twitter responded with six tweets from Russia Today. In the absence of a specific officially-published list, detailing accounts from the IRA that were active in the Brexit debate, we investigate whether any of the accounts known to be active on the 2016 US Election also produced content related to Brexit.
Tweets and Retweets
In the report given by Twitter to the Senate committee 2 it is stated that, of the tweets studied from the 1st September 2016 to the 15th November 2016, 1% were US election related. Of these 1% of election related tweets, 0.74% were Russian linked and had been detected by Twitter either as automation or spam. In its report to Senate, Twitter only considers original Tweets; all retweets are excluded.
The report indicates that Twitter identified 131,000 tweets from the accounts identified in the IRA list. Of these 9% were about the American Election (11,790). The total number of tweets annotated by Twitter as Election Related was 189 million which means that 0.006% of Election related content was created by the IRA trolls.
We analysed our longitudinal Brexit-related data set for evidence of activity from the 2,752 IRA linked troll accounts identified to Senate by Twitter. We confirmed that these accounts were creating Brexit related content. In total we found 3,485 tweets from the IRA linked accounts, representing 0.005% of the total data we collected.
The 0.005% figure for Brexit as opposed to 0.006% figure for the US Election indicates that there is a lower level of activity in our set of trolls discussing Brexit. Possible causal factors include: • that trolls, created to target the US election, are less active on the Brexit topic; • trolls are more active at certain points, the lower level activity seen here could be a factor of the longitudinal nature of our data set. We gathered and analysed data from a period of over two years whilst Twitter presented an analysis of data from 1st September 2016 until 15th November 2016; • that there are other trolls that are more active in the Brexit debate but they are not on this list. This 0.005% figure includes retweets and drops to 0.002% when these are excluded. In our troll dataset 57.59% of data are retweets.
Our analysis of this longitudinal dataset allows us to present a study of the changes in activity and troll behaviour over time and in response to external events. In particular, we note a change in retweeting behaviour on the 23rd June 2016, the day of the UK-EU referendum vote. On this day we captured 1,059,888 tweets in total. Out of this total, 389 of these tweets were from troll accounts (0.037%): nearly an eight-fold (7.4) increase in the relative number of tweets that came from trolls. The vast majority of tweets captured on this day were retweets, something the headline value of 0.74% in the US Twitter report would fail to identify. In fact, only eleven tweets were original tweets. If we were to calculate troll activity excluding retweets, we find that on this day 0.001% of original data are from trolls. Conducting the calculation in this way would indicate a decrease in troll activity rather than an increase. This highlights that, although the trolls were more active on the day of the Brexit referendum vote, there was a change in their behaviour and they produced more retweets and less original content. We must therefore consider this when we evaluate the 0.74% value given by Twitter.
Brexit Data Collection
We have been collecting Twitter data on the UK-EU referendum (Brexit) since August 2015. These data have enabled us to study discussions leading up the referendum and the consequential reaction to the decision of the UK to leave the European Union. Data were gathered through the Twitter API based on a selection of relevant hashtags chosen by a panel of academic experts. The set of hashtags grew periodically to reflect the evolving conversation. The dataset currently contains over seventy million tweets (Llewellyn and Cram 2017;Llewellyn, Cram, and Favero 2016).
The terms of service of the Twitter Developer Agreement ask that all Tweets are 'deleted within 24 hours after a request to do so by Twitter'. 5 We have an automated method in place that removes all tweets as requested. Therefore, it is possible tweets relevant to this study have been deleted.
This data is collected and archived to allow us to study the ongoing discussion and opinions regarding Brexit. The user accounts of the trolls identified by Twitter have now been deleted and are not available from Twitter directly. Archived copies of tweets are now the only way we can conduct academic research into troll activity in the Brexit discussion. We know that we are likely only to have a proportion of the content produced by the trolls. In this paper we can only analyse what we have found and remain aware that this data is probably a sub-sample of what was originally produced.
The selection of hashtags used to gather data ensured that we gathered both tweets that related to the Brexit vote directly and also to topics that were expected by experts to influence opinions on Brexit. When researching whether the troll accounts were active in the Brexit discussions we decided to split the data into tweets that were directly about Brexit and those that contained other Brexit related topics. We annotated tweets we had gathered from the troll accounts on the basis of whether they were directly about Brexit or not. The annotators were asked to be conservative and only to include tweets in the Brexit set if they were absolutely certain they were directly about Brexit. We found that 1,357 were directly about Brexit, 2,109 were not and 19 were difficult to decide. This gave us 38.94% of the tweets that were directly about Brexit. Henceforth we will call these sets 'Brexit Tweets' and 'Related Tweets'. The 19 undecided tweets were excluded from the study. All of the tweets were annotated by a single coder. We double coded a sample (100) of the tweets to validate consistency and measure inter-annotator agreement, producing a kappa score of 0.80 indicative of very high agreement. These tweets contained multi-lingual content: English, German and Italian. Both annotators were fluent in all of these languages.
Related Work
Automatic generation of Twitter content is common-place. Bessi and Ferrara (2016) found that one fifth of the Twitter conversation about the 2016 US Elections was not generated by humans. 'Bot' accounts are set up to automatically retweet and aggregate content from other sources or to create automatically generated text. 'Influence bots' were described in the DARPA Twitter Bot Challenge as bots designed to influence discussion on social media sites (Subrahmanian et al. 2016). Much of this content has no malicious intent, but some is designed to mislead or influence other users with misinformation and spam.
Social media companies are not required to fact check information. Catchiness and repeatability can lead to widespread dissemination of content whether it is true or not (Ratkiewicz et al. 2011). Bots are often used as a method for repeating information and making it appear that the information is popular .
As bots have become more advanced, they are able to interact with other bots and humans in a conversational type way making them more believable and increasing their social networks . Automatically extracting information from real users and from the wider internet allows the automatic generation of life-like user profile information creating complex and believable sock puppet personas .
Automated accounts can be used to produce large amounts of content on single issues, where many accounts become active and tweet on the same topic at once forming a 'bot legion' (Chu et al. 2012a). Ratkiewicz et al (2011) describe how nine fake users tweeted 929 times in 138 minutes in a 2009 Massachusetts election. This type of activity is intended to start a cascade of information-spreading with nonautomated accounts reproducing the content. Messages are also more likely to be believed if they are seen from multiple sources (Ratkiewicz et al. 2011) as it creates a wallpaper effect where information is seen so often it becomes background noise and is assumed to be true.
As shown by Bessi and Ferrara (2016) much of this automatically generated content can be automatically detected and extensive work has been conducted in this area, including the DARPA challenge. Systems have been created that are based on social network information, crowd sourcing and machine learning Davis et al. 2016).
The 2,752 Twitter accounts detailed in the Senate list are not automated accounts but 'cyborgs' which are at least partially operated by humans (Chu et al. 2012b). These are harder to detect than bots as they have the behaviour patterns of both bots and humans.
Astro-turfing describes the use of bots, cyborgs or sock puppets to emulate the personas of individuals involved in grass root political movements (Ratkiewicz et al. 2011). This activity is intended to foster a sense of group identity amongst individuals that share certain traits. These traits help other users identify with them and make them more likely to be sympathetic towards their opinions. The more often human users are exposed to content the more likely they are to align with the perspectives being shared (Del Vicario et al. 2016).
Astro-turf cyborgs commonly combine political information with more general human content. Keller et al (2017) found that cyborg trolls were used in astro-turfing by the South Korean secret service in the 2012 elections. They observed specific behaviour patterns: having many accounts tweet the same tweet at the same time to influence trending topics, having an agent cut and paste roughly the same content into many accounts, and a consistent time pattern for the activity in the accounts. They found that human troll accounts often act in similar and repetitive ways, as the individuals trolls are following central instructions. Howard and Kollanyi (2016), in a study of tweets collected between 5th and the 12th June 2016 in the UK-EU referendum, found that bots played a 'small but strategic role in the referendum conversations' but that not all accounts were completely automated. Bastos and Mercea (2017) found a network of 13,493 bots that tweeted on the UK-EU referendum but disappeared after the ballot, concluding that these accounts were involved in the amplification of human created content.
User Information
The list provided by Twitter to the US Senate contained 2,752 accounts that were thought to contain troll activity. Within our full data set we found tweets from 419 of these accounts. We had more than one tweet from 66.83% accounts. In the Brexit Tweets set we had tweets from 267 accounts. We found more than one tweet from 56.68% of those accounts indicating that most accounts did engage with the Brexit topic multiple times.
As seen in Table 1 there is a high overlap between the most frequent tweeters in each set. The accounts tweeted both about Brexit and related topics. We have most tweets from account a, an account that tweets in English and mostly retweets rather than producing original content.
We examined the information from the user metadata as extracted from the troll tweets. This user metadata is either generated automatically or added by the account holder. The information can change over time and/or be altered by the user; for example the number of followers is an automated value that can vary but the user profile location field can be added by the account holder. Information that is added by the user can indicate the role of the account. If we assume that the accounts are all created by the Internet Research Agency, an account could be created to look like an American individual with a particular political opinion and this can be expressed through the information added in fields such as location and user description. Account creation date is an automatic field and can not be changed. As can be seen in Figure 1 most of the accounts were created in 2013 and 2014 after the 2012 US Election but well before both the 2016 US Election and the UK-EU Brexit Referendum. There are more accounts created in 2016, the year of the US Election (and the Brexit vote), than in either 2015 or 2017. Of the forty-four accounts created in 2016 thirty-eight were created after the UK Brexit referendum but before the US election, all but one of these within a very tight window of ten days between 4th and 13th of July.
To further determine who the accounts were intended to represent we analysed the user description field in the tweet metadata. We counted the occurrences of terms by the year of account creation, and we removed very common english and german words. A user can change the text in this field at anytime but we did not find any evidence of changes in the data we collected. The full list of terms can be seen in Table 2. Many of the accounts do not have any terms at all in the user description field. The counts in Table 2 are small but do indicate a pattern. In 2013-2015 the accounts contained description terms that indicate American, conservative, patriotic personas, suggesting that the accounts were designed to influence American events. But in 2016 many of the terms are German, mag (like), glaube (I believe), uern (likely a shortening ofäußern which translates as express). Therefore, the accounts created in 2016 may not have been designed to tweet about the US election but something more European based instead.
When we looked at the user descriptions of the forty-four accounts created in 2016 we found twelve of the accounts created in July 2016 had German language descriptions (of the rest one was in English, one was mixed German and English, two only contained hashtags, and the rest were empty). For comparison, in 2015, sixteen were in English, three in German and four were empty.
This German language use in accounts created after the 2016 Brexit vote suggests that the trolls were using the result of the vote to push an agenda related to Germany, perhaps anticipating the German elections in 2017.
We confirmed the change in location by checking by hand the location fields of tweets in the Brexit set. We did not see any evidence in our data set that these fields had been changed over time but this is possible. We found 154 were in some way based in the USA, sixteen in Europe and three in Russia (94 had no location information). The sixteen European accounts were made up of seven German accounts, five Italian accounts, three from the UK and one from Belgium. To give a better idea of the types of locations described we give the term counts from the location field in Table 3. We can see that the European based accounts were created in 2016 and later. This location information suggests that most of the accounts on the list submitted by Twitter to US Senate were indeed designed to look like they are from the USA. The agenda they were designed to follow was also related to the USA, but those created in and after 2016 had a different agenda.
Some of the accounts have many followers and therefore a high potential to reach other Twitter users. We used the maximum number of followers when we had multiple tweets from an account. Of the 267 that have tweeted about Brexit: 122 accounts have more than 1,000 followers, sixteen accounts have over 10,000 and one account has over 100,000. The median number of followers is 875. As we cannot tell from this dataset how many of the trolls follow each other, this high median number should be treated with caution.
Tweet Information
The hashtags that are used by the troll accounts indicate the different topics discussed in both the Brexit Tweet and the Related Tweet sets. Table 4 shows the top hashtags in each set. In the Brexit Tweet set the hashtags used are related to Brexit, Britain, and the EU. In the top ten we also find hashtags relating to Chancellor Merkel, #merkel, and #merkelmussbleiben (which translates as #merkelmuststay). The trolls are directly discussing Brexit but also using wider hashtags for example referring to the role of the German In the Related Tweet set we can see that the trolls use hashtags about the EU, #eu; about refugees, #refugeeswelcome, #flchtlinge (which translates as #refugee) and #refugee. We see mentions of the German Chancellor, #merkel and the President of Turkey #erdogan, we also see reference to Germany, #deutschland and Turkey #trke. We also see that tweets that were classified as not directly about Brexit are still being tagged with the #brexit hashtag.
The way that the hashtags are being used in the wider Brexit related set suggests that the trolls have an agenda that related to Germany and Turkey and were using the Brexit topic to push this agenda and the issue of migration. The last elections in Germany were held on the 24th September 2017, and in Turkey there was a constitutional referendum held on the 16th April 2017.
Tweets, Retweets and Verified Users
We wanted to look at how the trolls behaved when directly discussing Brexit. We found that the Brexit Tweet subset contains a higher percentage of retweets and those retweets are less likely to be retweets of verified users and more likely to originally come from other trolls than the wider set.
The total number of tweets that we gathered was 3,485; of these, 2,007 are retweets (57.59%). Within the Brexit Tweet subset of 1,357 tweets 989 were retweets (72.88%). In the full set there are 775 tweets that were originally created by verified users (38.61%) and then retweeted by trolls. In the Brexit Tweet subset 321 tweets are originally from verified users (subsequently forming 32% of retweets). Out of the 104 accounts retweeted in the Brexit Tweets set 57 (54.81%) were only ever retweeted once. The most frequently retweeted verified users are presented in Table 5. We can see that the top retweets come from news outlets, the EU Council and the EU Comission.
We also find that trolls retweet trolls. In the total set there are 443 retweets (22.07%) from 34 different trolls (17 of these trolls were only in the set as retweets). In the Brexit Tweets set 345 are retweets (34.88%) from 25 other trolls (10 only ever as retweets). In the Brexit Tweet subset one specific troll has been retweeted 186 times by the other trolls, which means that 5.33% of all data gathered originated from a single account.
When we look at the Brexit Tweet set and split the data into original content and retweets from the troll accounts we Sputnik is a global wire, radio and digital news service. We exist to tell the stories that are not being told. tagesschau tagesschau 6 The news of the ARD nachdem 32 eu 62 eu 30 european 54 fr 25 uk 41 may 21 doorstep 35 gibt 21 council 35 merkel 21 la 28 negativen 20 deal 26 frau 20 vote 24 folgen 20 britain 24 neue 19 special 22 can see a difference in the language used. We removed all of the hashtags, as these were the most frequent terms and masked other term usage. Very common english and a german words were also removed. If we look at Table 6 we can see that original content tends to contain german words whereas retweeted content tends to contain english terms.
Tweet Dates
Overall there were very few tweets per day from the troll accounts. The number of tweets per day follows a similar pattern in both the Brexit Tweet and the Related Tweet sets. We can see in Figure 2 that there are several spikes of activity for the Brexit Tweets dataset. In Table 7 we show the dates, volumes, whether the tweet was original content or a retweet and what was happening in the news that may have triggered the content. We found that the spikes in content production are related to particular events such as the referendum vote itself or the UK Prime Minister May meeting German Chancellor Merkel. We can see that there is a differ- ence in troll behaviour on two dates that exhibit higher tweet volumes. On the 23rd June 2016 there is a large increase in volume of tweets produced but these are almost entirely retweets (97.73%). In contrast, on the 21st July 2016 there was a considerably larger proportion of original content produced: only 26.56% are retweets. There is also a conspicuous spike on the 19th February 2016. On a closer inspection of the data from this day, we found that all the tweets come from a single troll account.
The Day of the Brexit Referendum
The largest number of troll tweets was collected on the day of the referendum, the 23rd of June 2016. We collected 400 in total of which 398 were directly about Brexit. On this day out of the 398 Brexit Tweets only nine tweets (and eleven tweets out of the 400 total) consisted of original content, the rest being retweets. 97.73% of tweets on the day of the referendum were retweets. The trolls were therefore focused entirely on Brexit but they were retweeting rather than producing original content. None of the tweets on the day of the UK's EU referendum were retweets of verified users. This is a radical change of behaviour. Out of the 387 retweets 279 were retweets of other trolls from the list isssued to Senate by Twitter (72.10%). These tweets originate from only 11 troll accounts, and 186 were retweets originating from a single troll account. These 186 tweets exhibit a very similar homogeneity in style, content and format (text in italics altered from original): @USER #brexitornot #britaininout #brexitinout #euref https://t.co/VARIOUS In Figure 3 we see the frequency of tweets grouped by hour across the day of the referendum. This reveals that the vast majority of tweets were sent between 2pm and 4pm. There were no tweets after 4pm although the referendum polls did not close until 10pm. The nine tweets consisting of original content were tweeted early in the day, while only two original tweets were tweeted after 2pm (at 2pm and 2.45pm).
Amplification Behaviour
A social media amplifier is defined as a user that shares ideas and opinions (Tinati et al. 2012). In this context we will use the term amplifier to classify an account which, as far as we can see from the data we have collected, only ever retweets.
Overall there was very different pattern of behaviour exhibited by the trolls on the 23rd June, with a greater propensity to retweet, particularly sharing more information from other trolls. Overall in our set we have a large number of trolls who are amplifiers. To judge if their behaviour changed on the referendum polling day we analysed troll accounts which sent tweets on both the 23rd June and other days. In the Brexit Tweets set we have tweets from 248 troll accounts, of which 38 of them were active on the 23rd June 2016. Of those accounts, 19 (50%) also appear on other days. This could suggest that the other 19 troll accounts only tweeted about Brexit on the 23rd June or it could just mean we did not catch them in our dataset.
There were only nine tweets that were not retweets on the 23rd June. Those original content tweets all came from accounts that tweeted on other days as well. In this data set the accounts that only tweeted on the 23rd June 2016 were amplifiers. Thirteen of the accounts acted as amplifiers on the 23rd June and twelve in the wider time period. As we do not have all of the tweets produced by all trolls we cannot establish a definitive pattern but this suggests that, while some accounts may simply be amplifiers, content producers can also switch their behaviour to amplification if required. Users may be more likely to be one or another but these behaviour patterns can change. On the day of the referendum vote we found that all of the IRA troll accounts were more likely to be involved in amplification behaviour.
Sentiment and Stance
We annotated the 1,357 Brexit Tweets for both stance and sentiment. The annotator was asked to rate the stance of the Pro-Leave Pro-Remain tweets as either pro-leaving the EU, pro-remaining in the EU or neutral/neither. For sentiment the tweets were annotated as containing positive, negative or neutral sentiment. The majority of tweets were both neutral in stance (78.78%) and neutral in sentiment (64.41%), although this may be a consequence of the lack of available image or video context. In general the tweets had a stronger pro-leave stance (14.96%) than pro-remain (6.26%). The split of sentiment was fairly equal with a positive sentiment (18.35%) being very slightly higher than negative sentiment (17.24%). The pro-leave stance was consistently higher throughout the time period as shown in Figure 4. The sentiment scores do change over time as can be seen in Figure 5. In particular there was a spike of positive sentiment tweets on the 21st July 2016. As previously stated this was a spike in volume that occurred on the day that UK Prime Minister May met German Chancellor Merkel. A high percentage of these (73.44%) were not retweets and the tweets were in German. The content driving this change in sentiment direction revolves around Chancellor Merkel, describing her as a strong person that will handle the Brexit issue well. The trolls discuss new possibilities and options after Brexit and that Frankfurt will be soon in a stronger position. A few trolls also talk about the EU accession of Turkey and that Merkel does not want any negotiations if Turkey re-introduces the death penalty.
User Accounts Released 19th Jan 2017
On the 19th January 2017 Twitter released a statement saying that they were adding a further 1,062 accounts associated with the Internet Research Agency. We have yet to see these account usernames.
Discussion
The Internet Research Agency accounts identified by Twitter were active in the Brexit debate. These tweets were slightly more likely to be pro-leave than pro-remain. These accounts were not designed to look like either proleave or pro-remain grassroots individuals. It is likely they were designed to be active in the American and perhaps latterly in the German Elections. This raises two questions: do accounts designed by the Internet Research Agency to look like grassroots Brexit groups exist? and why were the American and German sock-puppets tweeting about Brexit?
The answer to the first question is unknown. To the second question, it could be either be that these tweets are background noise designed to make the accounts look either more human or more politically aware, or that the topic of Brexit was used to promote another agenda such as instability and disruption.
We also observe the high-level retweeting of verified users again possibly to create the illusion of a politically active human.
We observe 'bot legion' behaviour on the 23rd June 2016. Many retweets that contain very similar content were tweeted over a short time frame. It is likely that these were produced automatically or exhibit the cut and paste behaviour seen in the South Korean Election. It looks like these American and German persona had been instructed to tweet on the Brexit topic en masse.
There are other spikes in data production that were not produced by mass retweet events. We see on the 21st July there was a high level of positive original content produced that wass related to Merkel and Brexit, certainly pointing towards the use of Brexit as a supporting issue.
The longitudinal nature of the data collection technique that we use offers the opportunity to investigate behavioural changes and adaptation. If we had studied these data from the 23rd June 2016 in isolation then the cyborg troll accounts would have simply resembled bot accounts. In order to successfuly identify the cyborg accounts we need to systematically look for changes in behaviour over time. |
package de.mygrades;
import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;
import de.mygrades.database.DatabaseHelper;
import de.mygrades.database.dao.DaoMaster;
import de.mygrades.database.dao.DaoSession;
import de.mygrades.main.alarm.ScrapeAlarmManager;
/**
* MyGradesApplication to hold the DaoSession in application scope.
*/
public class MyGradesApplication extends Application {
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
// set preferences default values
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
SQLiteOpenHelper helper = new DatabaseHelper(this, "mygrades.db", null);
DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
// check if alarm for automatic scraping is set
ScrapeAlarmManager scrapeAlarmManager = new ScrapeAlarmManager(this);
scrapeAlarmManager.setAlarmFromPrefs(false, false);
}
public DaoSession getDaoSession() {
return daoSession;
}
}
|
Whether you are in the web hosting business, or run a few web sites on a VPS yourself, chances are you want to display visitor statistics such as top visitors, requested files (dynamic or static), used bandwidth, client browsers, and referring sites, and so forth.
GoAccess is a command-line log analyzer and interactive viewer for Apache or Nginx web server. With this tool, you will not only be able to browse the data mentioned earlier, but also parse the web server logs to dig for further data as well - and all of this within a terminal window in real time. Since as of today most web servers use either a Debian derivative or a Red Hat based distribution as the underlying operating system, I will show you how to install and use GoAccess in Debian and CentOS.
Installing GoAccess on Linux
In Debian, Ubuntu and derivatives, run the following command to install GoAccess:
# aptitude install goaccess
In CentOS, you'll need to enable the EPEL repository and then:
# yum install goaccess
In Fedora, simply use yum command:
# yum install goaccess
If you want to install GoAccess from the source to enable further options (such as GeoIP location), install required dependencies for your operating system, and then follow these steps:
# wget http://tar.goaccess.io/goaccess-0.8.5.tar.gz
# tar -xzvf goaccess-0.8.5.tar.gz
# cd goaccess-0.8.5/
# ./configure --enable-geoip
# make
# make install
That will install version 0.8.5, but you can always verify what is the latest version in the Downloads page of the project's web site.
Since GoAccess does not require any further configurations, once it's installed you are ready to go.
Running GoAccess
To start using GoAccess, just run it against your Apache access log.
For Debian and derivatives:
# goaccess -f /var/log/apache2/access.log
For Red Hat based distros:
# goaccess -f /var/log/httpd/access_log
When you first launch GoAccess, you will be presented with the following screen to choose the date and log format. As explained, you can toggle between options using the spacebar and proceed with F10. As for the date and log formats, you may want to refer to the Apache documentation if you need to refresh your memory.
In this case, Choose Common Log Format (CLF):
and then press F10. You will be presented with the statistics screen. For the sake of brevity, only the header, which shows the summary of the log file, is shown in the next image:
Browsing Web Server Statistics with GoAccess
As you scroll down the page with the down arrow, you will find the following sections, sorted by requests. The order of the categories presented here may vary depending on your distribution or your preferred installation method (from repositories or from source):
1. Unique visitors per day (HTTP requests having the same IP, same date and same agent are considered an unique visit)
2. Requested files (Pages-URL)
3. Requested static files (e.g., .png, .js, etc)
4. Referrers URLs (the URLs where each request came from)
5. HTTP 404 Not Found response code
6. Operating Systems
7. Browsers
8. Hosts (client IPs)
9. HTTP status codes
10. Top referring sites
11. Top keyphrases used on Google's search engine
If you also want to inspect the archived logs, you can pipe them to GoAccess as follows.
For Debian and derivatives:
# zcat -f /var/log/apache2/access.log* | goaccess
For Red Hat based distributions:
# cat /var/log/httpd/access* | goaccess
Should you need a more detailed report of any of the above (1 through 11), press the desired section number and then O (uppercase o) to bring up what is called the Detailed View. The following image shows the output of 5-O (press 5, then press O):
To display GeoIP location information, open the Detail View in the Hosts section, as explained earlier, and you will see the location of the client IPs that performed requests to your web server:
If your system has not been very busy lately, some of the above sections will not show a great deal of information, but that situation can change as more and more requests are made to your web server.
Saving Reports for Offline Analysis
There will be times when you don't want to inspect your system's stats in real time, but save it to a file for offline analysis or printing. To generate an HTML report, simply redirect the output of the GoAccess commands mentioned earlier to an HTML file. Then just point your web browser to the file to open it.
# zcat -f /var/log/apache2/access.log* | goaccess > /var/www/webserverstats.html
Once the report is displayed, you will need to click on the Expand link to show the detail view on each category:
As we have discussed throughout this article, GoAccess is an invaluable tool that will provide you, as a system administrator, with HTTP statistics in a visual report on the fly. Although GoAccess by default presents its results to the standard output, you can also save them to JSON, HTML, or CSV files. This converts GoAccess in an incredibly useful tool to monitor and display statistics of a web server. |
The Saskatchewan government passed legislation Wednesday that would allow it sell up to 49 per cent of the province's Crown corporations.
Bill 40 creates a legal definition of privatization that allows the partial sale of a Crown without requiring a vote of support from the people of the province.
Up to 49 per cent of each Crown, such as SaskTel and SaskPower, could be up for grabs to private shareholders, without technically being "privatized."
Opposition leader Trent Wotherspoon spoke in the Legislative Assembly on Wednesday, calling the bill an "incredible betrayal of Saskatchewan people by the Premier and the Sask. Party."
SGEU President Bob Bymoen said he's concerned about the future of the province's Crowns.
"Decade after decade, our Crowns have served Saskatchewan people well," Bymoen. "They're the reason we have some of the lowest utility rates in Canada, and reliable service in remote and rural areas."
"The Sask. Party wants to sacrifice those advantages for a one-time windfall, to dig themselves out of the financial mess they created — and they don't want to let Saskatchewan people tell them otherwise." |
// Define a class, but leave its key function undefined.
class C
{
public:
C() : c(1) { }
virtual void set();
virtual void clear();
int c;
} |
<reponame>afgoulart/react-analytics
import {
EventArgs,
GaOptions,
InitializeOptions,
Tracker,
TrackerNames,
FieldsObject,
TimingArgs,
Plugin,
TestModeAPI,
OutboundLinkArgs,
OutboundLinkProps,
} from 'react-ga';
export type ReactGAType = {
EventArgs: EventArgs;
GaOptions: GaOptions;
InitializeOptions: InitializeOptions;
Tracker: Tracker;
TrackerNames: TrackerNames;
FieldsObject: FieldsObject;
TimingArgs: TimingArgs;
Plugin: Plugin;
TestModeAPI: TestModeAPI;
OutboundLinkArgs: OutboundLinkArgs;
OutboundLinkProps: OutboundLinkProps;
initialize(trackingCode: string, options?: InitializeOptions): void;
initialize(trackers: Tracker[], options?: InitializeOptions): void;
addTrackers(trackingCode: string): void;
addTrackers(trackers: Tracker[]): void;
ga(): (...args: any[]) => void;
ga(...args: any[]): void;
resetCalls(): void;
set(fieldsObject: FieldsObject, trackerNames?: TrackerNames): void;
send(fieldsObject: FieldsObject, trackerNames?: TrackerNames): void;
pageview(path: string, trackerNames?: TrackerNames, title?: string): void;
modalview(name: string, trackerNames?: TrackerNames): void;
timing(args: TimingArgs, trackerNames?: TrackerNames): void;
event(args: EventArgs, trackerNames?: TrackerNames): void;
exception(fieldsObject: FieldsObject, trackerNames?: TrackerNames): void;
plugin: Plugin;
testModeAPI: TestModeAPI;
outboundLink(args: OutboundLinkArgs, hitCallback: () => void, trackerNames?: TrackerNames): void;
OutboundLink: React.ComponentClass<OutboundLinkProps & React.HTMLProps<HTMLAnchorElement>>;
};
export interface AnalyticsTrackerInfoProps {
trackerName: string;
trackerId: string;
}
export interface AnalyticsContextProps {
config: any;
reactGA: ReactGAType;
trackerInfo: AnalyticsTrackerInfo;
options?: AnalyticsInitilizeOptions;
}
export interface AnalyticsProviderProps {
config: any;
trackerInfo: AnalyticsTrackerInfo;
options?: AnalyticsInitilizeOptions;
}
export type AnalyticsTrackerInfo = string | Tracker[];
export type AnalyticsInitilizeOptions = InitializeOptions;
export interface AnalyticsProps {
reactGA?: ReactGAType;
children?: any;
ref?: React.RefObject<{}>;
}
|
/*
* Copyright (c) 2019 <NAME>
*
* This file is part of http-ece, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
package httpece
import (
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"log"
)
var debug = debugT(false)
type debugT bool
func (d debugT) dumpBinary(base string, data []byte) {
if d {
log.Printf("%12s [%4d]: %s\n", base, len(data), base64.StdEncoding.EncodeToString(data))
}
}
func parseOptions(mode mode, opts []Option) *options {
opt := &options{
mode: mode,
curve: elliptic.P256(),
encoding: AES128GCM,
rs: sizeRecordDefault,
keyLabel: curveAlgorithm,
}
for _, o := range opts {
o(opt)
}
return opt
}
func uint16ToBytes(i int) []byte {
x := make([]byte, 2)
binary.BigEndian.PutUint16(x, uint16(i))
return x
}
func uint32ToBytes(i int) []byte {
x := make([]byte, 4)
binary.BigEndian.PutUint32(x, uint32(i))
return x
}
func generateNonce(baseNonce []byte, counter int) []byte {
x := make([]byte, nonceLen)
binary.BigEndian.PutUint32(x[8:], uint32(counter))
xor12(x, baseNonce, x)
return x
}
func xor12(dst []byte, a []byte, b []byte) {
_ = dst[11]
_ = a[11]
_ = b[11]
dst[0] = a[0] ^ b[0]
dst[1] = a[1] ^ b[1]
dst[2] = a[2] ^ b[2]
dst[3] = a[3] ^ b[3]
dst[4] = a[4] ^ b[4]
dst[5] = a[5] ^ b[5]
dst[6] = a[6] ^ b[6]
dst[7] = a[7] ^ b[7]
dst[8] = a[8] ^ b[8]
dst[9] = a[9] ^ b[9]
dst[10] = a[10] ^ b[10]
dst[11] = a[11] ^ b[11]
}
func resultsJoin(s [][]byte) []byte {
if len(s) == 1 {
return s[0]
}
n := 0
for _, v := range s {
n += len(v)
}
b := make([]byte, n)
o := 0
for _, v := range s {
o += copy(b[o:], v)
}
return b
}
func randomSalt() ([]byte, error) {
salt := make([]byte, keyLen)
if _, err := rand.Read(salt); err != nil {
return nil, err
}
return salt, nil
}
|
<gh_stars>1-10
#pragma once
#include <stdint.h>
struct RI_t{
volatile uint32_t ICR;
volatile uint32_t ASCR1;
volatile uint32_t ASCR2;
volatile uint32_t HYSCR[4];
volatile uint32_t ASMR1;
volatile uint32_t CMR1;
volatile uint32_t CIRC1;
volatile uint32_t ASMR2;
volatile uint32_t CMR2;
volatile uint32_t CICR2;
volatile uint32_t ASMR3;
volatile uint32_t CMR3;
volatile uint32_t CICR3;
volatile uint32_t ASMR4;
volatile uint32_t CMR4;
volatile uint32_t CICR4;
volatile uint32_t ASMR5;
volatile uint32_t CMR5;
volatile uint32_t CICR5;
};
#if defined(STM32L1)
static RI_t &RI = *(RI_t *)(0x40007C00 + 4);
#endif
|
<reponame>weclaw1/learn_opengl<filename>src/utils/input.rs<gh_stars>1-10
const MIN_PITCH: f32 = -89.0;
const MAX_PITCH: f32 = 89.0;
pub struct Input {
up: bool,
down: bool,
left: bool,
right: bool,
close: bool,
yaw: f32,
pitch: f32,
fov: f32,
}
impl Input {
pub fn new() -> Self {
Input {
up: false,
down: false,
left: false,
right: false,
close: false,
yaw: -90.0,
pitch: 0.0,
fov: 45.0,
}
}
pub fn up(&self) -> bool {
self.up
}
pub fn set_up(&mut self, pressed: bool) {
self.up = pressed;
}
pub fn down(&self) -> bool {
self.down
}
pub fn set_down(&mut self, pressed: bool) {
self.down = pressed;
}
pub fn left(&self) -> bool {
self.left
}
pub fn set_left(&mut self, pressed: bool) {
self.left = pressed;
}
pub fn right(&self) -> bool {
self.right
}
pub fn set_right(&mut self, pressed: bool) {
self.right = pressed;
}
pub fn close(&self) -> bool {
self.close
}
pub fn set_close(&mut self, pressed: bool) {
self.close = pressed;
}
pub fn yaw(&self) -> f32 {
self.yaw
}
pub fn set_yaw(&mut self, value: f32) {
self.yaw = value;
}
pub fn pitch(&self) -> f32 {
self.pitch
}
pub fn set_pitch(&mut self, value: f32) {
if value < MIN_PITCH {
self.pitch = MIN_PITCH;
} else if value > MAX_PITCH {
self.pitch = MAX_PITCH;
} else {
self.pitch = value;
}
}
pub fn fov(&self) -> f32 {
self.fov
}
pub fn set_fov(&mut self, value: f32) {
self.fov = value;
}
} |
This article is about the American author. For other people with the same name, see Michael Talbot (disambiguation)
Michael Coleman Talbot (September 29, 1953 – May 27, 1992)[1] was an American author of several books highlighting parallels between ancient mysticism and quantum mechanics, and espousing a theoretical model of reality that suggests the physical universe is akin to a hologram based on the research and conclusions of David Bohm and Karl H. Pribram.[2] According to Talbot ESP, telepathy, and other paranormal phenomena are a product of this holographic model of reality.[3]
Early life [ edit ]
Talbot was born in Grand Rapids, Michigan, on September 29, 1953.
Career [ edit ]
He was originally a fiction and science fiction author.[1][4] He also contributed articles to The Village Voice and other publications.[4]
Talbot attempted to incorporate spirituality, religion and science to shed light on profound questions.[5] His non-fiction books include Mysticism And The New Physics, Beyond The Quantum, and The Holographic Universe (freely available at the Internet Archive).
Personal life and death [ edit ]
Although Talbot is not known to have made it much of a political issue, he was openly gay, living with a boyfriend.[6] In 1992, Talbot died of lymphocytic leukemia at age 38.[1][4]
Bibliography [ edit ]
Novels
The Delicate Dependency , 1982 (reprinted in 2014 by Valancourt Books), ISBN 1941147240
, 1982 (reprinted in 2014 by Valancourt Books), ISBN 1941147240 The Bog , 1986 (reprinted in 2015 by Valancourt Books)
, 1986 (reprinted in 2015 by Valancourt Books) Night Things, 1988 (reprinted in 2015 by Valancourt Books)
Non-fiction
Mysticism And The New Physics , ISBN 0-14-019328-6, 1980 (rev. 1992)
, ISBN 0-14-019328-6, 1980 (rev. 1992) Beyond The Quantum , ISBN 0-553-34480-3, 1986 [7] [8]
, ISBN 0-553-34480-3, 1986 Your Past Lives - A Reincarnation Handbook , 1987, ISBN 0517563010
, 1987, ISBN 0517563010 The Holographic Universe, ISBN 0-06-092258-3, 1991[9]
See also [ edit ] |
/**
* Store payload objects that come from web submissions until they are retrieved by SUBMISSION_TOKEN value
*/
public class WebSubmissionPlace extends ServiceProviderPlace implements emissary.place.AgentsNotSupportedPlace {
/** The hash of stored documents */
protected final Map<String, List<IBaseDataObject>> map = new HashMap<String, List<IBaseDataObject>>();
/** Matching output types will have data available */
protected List<String> outputTypes;
/** Matchine view names will have view data available */
protected List<String> viewTypes;
/**
* Create and register with all defaults
*/
public WebSubmissionPlace() throws IOException {
super();
configure();
}
/**
* Create and register
*/
public WebSubmissionPlace(String configInfo, String dir, String placeLoc) throws IOException {
super(configInfo, dir, placeLoc);
configure();
}
/**
* Create for test
*/
public WebSubmissionPlace(String configInfo) throws IOException {
super(configInfo, "WebSubmissionPlace.www.example.com:8001");
configure();
}
/**
* Configure our stuff
*/
protected void configure() {
outputTypes = configG.findEntries("OUTPUT_DATA_TYPE", ".*");
viewTypes = configG.findEntries("OUTPUT_VIEW_TYPE", ".*");
}
/**
* Consume the data object list
*/
@Override
public List<IBaseDataObject> agentProcessHeavyDuty(List<IBaseDataObject> payloadList) {
// Nuke the form that got us here
for (IBaseDataObject payload : payloadList) {
nukeMyProxies(payload);
}
// Sort the list of records
Collections.sort(payloadList, new emissary.util.ShortNameComparator());
// Grab the submission token
String token = payloadList.get(0).getStringParameter(DocumentAction.SUBMISSION_TOKEN);
// Store the payload
if (token != null) {
synchronized (map) {
logger.debug("Storing family tree payload " + token + " (" + payloadList.size() + ")");
List<IBaseDataObject> clones = new ArrayList<IBaseDataObject>();
for (IBaseDataObject d : payloadList) {
try {
clones.add(d.clone());
} catch (CloneNotSupportedException ex) {
logger.warn("Cannot clone payload", ex);
clones.add(d);
}
}
map.put(token, clones);
}
}
return Collections.emptyList();
}
/**
* Take something from the store, if found removed from map
*
* @param token the web submission token
* @return the stored family tree or null
*/
public List<IBaseDataObject> take(String token) {
List<IBaseDataObject> list = null;
synchronized (map) {
list = map.remove(token);
}
// Clear out unwanted data
if (list != null) {
for (IBaseDataObject d : list) {
// Test current forms and file type
if (!matchesAny(d.getAllCurrentForms(), outputTypes) && !matchesAny(d.getFileType(), outputTypes)) {
logger.debug("Clearing data " + d.getAllCurrentForms() + ", " + d.getFileType());
d.setData(null);
}
// Test alternate views
for (String avname : d.getAlternateViewNames()) {
if (!matchesAny(avname, viewTypes)) {
logger.debug("Clearing alt view " + avname);
d.addAlternateView(avname, null);
}
}
}
}
return list;
}
/**
* Match against all
*/
private boolean matchesAny(List<String> forms, List<String> patterns) {
for (String f : forms) {
if (f == null) {
continue;
}
for (String p : patterns) {
if (f.matches(p)) {
logger.debug("Pattern match " + f + " with " + p);
return true;
}
logger.debug("Pattern no-match " + f + " with " + p);
}
}
return false;
}
/**
* Match against all
*/
private boolean matchesAny(String form, List<String> patterns) {
if (form == null) {
return false;
}
for (String p : patterns) {
if (form.matches(p)) {
logger.debug("Pattern match " + form + " with " + p);
return true;
}
logger.debug("Pattern no-match " + form + " with " + p);
}
return false;
}
/**
* List the keys in the map
*/
public synchronized List<String> keys() {
return new ArrayList<String>(map.keySet());
}
/**
* Test run
*/
public static void main(String[] argv) {
mainRunner(WebSubmissionPlace.class.getName(), argv);
}
} |
MIAMI — Josh Richardson is the Heat’s new $42 million man. But will he be the Heat’s new starter this season?
We answer that question and more in the latest installment of the Heat mailbag. If you weren’t able to ask a question this time, send your questions for future mailbags via Twitter (@Anthony_Chiang and @tomdangelo44).
@ifotomedia: I think Josh Richardson could end up as a starter. Do you agree?
Anthony Chiang: I know it’s been said so many times that people don’t really believe it anymore. But … it doesn’t matter who starts on this Heat team. Really. With Erik Spoelstra, it’s all about rotations and combinations that work together. Yes, Richardson has a chance to start at small forward over Rodney McGruder and Justise Winslow. But if he’s not in the starting lineup, he’s still going to get at least 20 minutes of playing time per game. Josh has looked impressive and healthy this preseason, with his best performance coming Saturday against the Magic. He finished with 19 points, four assists and four steals. And the performance came with Josh playing multiple roles, initiating offense with Goran Dragic out and playing off the ball. It’s that skill set that could keep him out of the Heat’s starting lineup this season. Some believe Richardson’s versatility at 6-foot-6 and 200 pounds is better suited for the bench, where he can enter games in different roles based on foul trouble and matchups. He’s received minutes at point guard, shooting guard and small forward over the first two seasons of his NBA career, and can defend all three positions. So, yes, Josh does have a chance to start this season. But there’s also a chance the Heat decide to use him as a weapon off their bench. Just know that Josh is going to play significant minutes whether he starts or not. That’s what matters.
@Aj3th: Why hasn’t Bam Adebayo played that many minutes this preseason?
Anthony Chiang: Because Erik Spoelstra is still trying to find a rotation that will work when the regular season begins in one week. 10 Heat players have averaged 15 minutes of playing time or more through three preseason games, and they are the 10 players who are expected to have a consistent role this season — Josh Richardson, Kelly Olynyk, Dion Waiters, James Johnson, Rodney McGruder, Justise Winslow, Hassan Whiteside, Wayne Ellington, Goran Dragic and Tyler Johnson. This shows you that Spoelstra is still experimenting with his rotation to find the lineups that work best. And this means rookie Bam Adebayo probably won’t be in the rotation right away. As a power forward/center, Bam is behind Hassan, Kelly, James and Justise at those spots. Spoelstra has relied on those four to play most of the minutes to start the preseason. If this continues into the regular season, this isn’t necessarily a bad thing for Bam. The Heat have been pleased with his progress and believe he can help the team, even as a rookie. But the more time Bam has to work on his game and learn from his teammates and coaches before playing a key role, the better for him and the Heat. Remember, Bam just turned 20 on July 18.
[3 takeaways: Josh Richardson, Dion Waiters, Hassan Whiteside stand out in Heat loss to Magic]
[Heat forward Jordan Mickey knows the long road between Portland, Maine, and Boston]
[Miami Heat guard Dion Waiters says peace of mind played big part in being able to focus on getting ready for season]
[Want more Heat news sent directly to your Facebook feed? Make sure to like our Heat Facebook page] |
/**
* @file
* @author __AUTHOR_NAME__ <<EMAIL>>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_CAMERAS_SCENE2D_SYSTEMS_FADE_HPP
#define ZEN_CAMERAS_SCENE2D_SYSTEMS_FADE_HPP
#include <functional>
#include <SDL2/SDL_types.h>
#include "../../../ecs/entity.hpp"
#include "../../../scene/scene.fwd.hpp"
namespace Zen {
class MultiPipeline;
/**
* Fades the Camera to or from the given color over the duration specified.
*
* @since 0.0.0
*
* @param camera The camera to run the effect on.
* @param direction The direction of the fade. `true` = fade out (transparent to
* color), `false` = fade in (color to transparent)
* @param duration The duration of the effect in milliseconds.
* @param red The amount to fade the red channel towards. A value between 0 and 255.
* @param green The amount to fade the green channel towards. A value between 0 and
* 255.
* @param blue The amount to fade the blue channel towards. A value between 0 and
* 255.
* @param force Force the effect to start immediately, even if already running.
* @param callback - This callback will be invoked every frame for the duration of
* the effect.
* It is sent two arguments: A reference to the camera and a progress amount
* between 0 and 1 indicating how complete the effect is.
*/
void StartFade (Entity camera, bool direction = true, int duration = 1000,
int red = 0, int green = 0, int blue = 0, bool force = false,
std::function<void(Entity, double)> callback = nullptr);
/**
* The main update loop for this effect. Called automatically by the camera manager.
*
* @since 0.0.0
*
* @param time The current timestamp since the start of SDL.
* @param delta The delta time, in ms, elapsed since the last frame.
*/
void UpdateFade (Entity camera, Uint32 time, Uint32 delta);
/**
* Called internally by the renderer.
*
* @since 0.0.0
*
* @return `true` if the effect drew to the renderer, otherwise `false`.
*/
bool PostRenderFade (Entity camera, MultiPipeline& pipeline);
/**
* Called internally when the effect completes.
*
* @since 0.0.0
*/
void CompleteFade (Entity camera);
/**
* Resets this camera effect.
* If it was previously running, it stops instantly without calling its onComplete
* callback or emitting an event.
*
* @since 0.0.0
*/
void ResetFade (Entity camera);
bool IsFadeRunning (Entity camera);
bool IsFadeComplete (Entity camera);
} // namespace Zen
#endif
|
Building A More Decentralized Internet: It's Happening Faster Than People Realize
from the you-bet-we-can dept
More than three years ago, I wrote a post predicting that "the revolution will be distributed." In talking about a variety of attacks (mainly on Wikileaks), I pointed out that these were only going to inspire more and more interest in building an internet that is not nearly as centralized, but actually much more decentralized and distributed -- and that those defending the status quo still don't realize what an astoundingly big impact this will have. Soon after, we noted that the real battle lines for the future will be about distributed and open systems against centralized and closed systems. Movement in this arena has certainly been slow, but it's continued to move forward. The Snowden leaks of the past year have really only accelerated the process -- and interest in these kinds of projects.Over at the New Yorker, they have a pretty good status update on "the mission to decentralize the internet," though, unlike a big centralized project, that "mission" is done in a decentralized and open manner as well. The short summary might lead some to dismiss this whole trajectory -- as many of the initial attempts have failed to gain much traction. But that would be a huge mistake. One of the things that you will see, if you study the history of innovation, is that this is exactly how it always happens. The early projects may have some minor successes here and there, but are littered with failures. But thething about a rapidly changing world where people are doing things in a decentralized and open way is that each of those failures only contributes to the knowledge for future projects, in which more and more people are testing more and more things, getting closer to hitting that point in the "innovator's dilemma" curve, where the new systems actually serve people's needsthan the old way.It often feels like these new systems suck at first, and it's easy to dismiss them as not being real competition for the established ways of doing things -- but the rapid rate of improvement, and the almost underground nature of many of these advancements means that when they suddenly catch on, they'll catch on quickly, and the folks who previously dismissed them as not being viable won't know what hit them. In fact, I've seen a few much more ambitious projects than what Joshua Kopstein discusses in his article, which suggests we're already well on our way to creating much more distributed systems that will make many of the debates we have today about the internet, internet governance, surveillance, copyright and much, much more totally obsolete. It's an issue I'm planning to explore in much more detail in 2014, so stay tuned...
Filed Under: damage, decentralized internet, privacy |
/**
* Represents a range of versions that a particular broker supports for some feature.
*/
public class SupportedVersionRange {
private final short minVersion;
private final short maxVersion;
/**
* Raises an exception unless the following conditions are met:
* 1 <= minVersion <= maxVersion.
*
* @param minVersion The minimum version value.
* @param maxVersion The maximum version value.
*
* @throws IllegalArgumentException Raised when the condition described above is not met.
*/
SupportedVersionRange(final short minVersion, final short maxVersion) {
if (minVersion < 1 || maxVersion < 1 || maxVersion < minVersion) {
throw new IllegalArgumentException(
String.format(
"Expected 1 <= minVersion <= maxVersion but received minVersion:%d, maxVersion:%d.",
minVersion,
maxVersion));
}
this.minVersion = minVersion;
this.maxVersion = maxVersion;
}
public short minVersion() {
return minVersion;
}
public short maxVersion() {
return maxVersion;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
final SupportedVersionRange that = (SupportedVersionRange) other;
return this.minVersion == that.minVersion && this.maxVersion == that.maxVersion;
}
@Override
public int hashCode() {
return Objects.hash(minVersion, maxVersion);
}
@Override
public String toString() {
return String.format("SupportedVersionRange[min_version:%d, max_version:%d]", minVersion, maxVersion);
}
} |
An umanned rocket lit up the night sky over Florida like a larger-than-life roman candle Thursday night (March 12), carrying a four satellites on a mission to seek an explosive phenomenon in Earth's magnetic field.
The United Launch Alliance Atlas V rocket blasted off from a launch pad here at Cape Canaveral Air Force Station at 10:44 p.m. (0244 p.m. GMT March 13), sending NASA's four Magnetospheric Multiscale satellites (MMS) on their way to hunt for magnetic reconnection events in Earth's magnetic field. NASA captured spectacular video of the nighttime MMS satellite launch.
NASA launch manager Omar Baez said it was a "picture perfect" launch for the Atlas V and the four MMS satellites. "Everybody is cheering and it appears that all four are where they need to be," Baez said after the launch. [See more launch photos for NASA's Magnetospheric Multiscale Mission]
Roughly 3,850 people were expected to watch the launch from the Kennedy Space Center campus and the Banana Creek, NASA Causeway as the Atlas V streaked into the clear, windy night sky over Florida.
The Atlas V was carrying four satellites that comprise the Magnetospheric Multiscale mission, or MMS, which will orbit together through the Earth's magnetic field. The $1.1 billion MMS mission will study a phenomenon known as magnetic reconnection, the key driver of what is known as space weather, which includes solar flares and coronal mass ejections, as well as geomagnetic storms and the auroras at the north and south poles. These events can damage human-made satellites and create electric surges in power grids on the ground.
John Durelli, an MMS scientist at the NASA Goddard Space Flight Center, said "the whole MMS team" came to Florida to watch the launch, many of them with their families. When asked how he was feeling about the launch, Durelli said he and his colleagues were using the phrase, "euphora-terror."
"Some people have been [working on MMS] for 10 years, so it's been a long time in development," Durelli said. "You have this combined feeling: you can't believe it's finally happening, but also, 'Oh my god! What if something goes wrong!'"
MMS is the only space experiment dedicated solely to studying magnetic reconnection. This process occurs when magnetic field lines break and reconnect in the presence of plasma. The magnetic fields release huge amounts of energy that can accelerate the plasma to nearly the speed of light. The four MMS satellites were built and tested at NASA's Goddard Space Flight Center in Greenbelt, Maryland. Multiple institutions and universities contributed to the science and instrumentation on the MMS satellites.
It is not yet known how the energy from magnetic field lines is transformed into heat and kinetic energy during magnetic reconnection, the mission scientists say. The four MMS satellites will fly in a pyramid shape, which will allow them to take data on magnetic reconnection events in three dimensions. The satellites will observe these extreme events all the way down to the level of electrons — a resolution 100 times higher than previous experiments that have observed this phenomenon, according to MMS scientists.
Get the Monitor Stories you care about delivered to your inbox. By signing up, you agree to our Privacy Policy
Follow Calla Cofield @callacofield.Follow us @Spacedotcom, Facebook and Google+. Original article on Space.com.
Copyright 2015 SPACE.com, a Purch company. All rights reserved. This material may not be published, broadcast, rewritten or redistributed. |
// Then creates a wrapper function that forces a request to run through a your gauntlet of middleware
// functions before finally executing the intent/request handler you're registering.
func (m Middleware) Then(handler HandlerFunc) HandlerFunc {
for i := len(m) - 1; i >= 0; i-- {
mw := m[i]
if mw == nil {
continue
}
next := handler
handler = func(ctx context.Context, request Request) (Response, error) {
return mw(ctx, request, next)
}
}
return handler
} |
def convert_strehl(sr1,lambda1,lambda2):
return np.power(sr1,(lambda1/lambda2)**2) |
use utils::InputType;
use std::collections::HashSet;
fn main() {
let xss = read_input(InputType::Input);
println!("Day09 part a = {}", part_a(&xss)); // 591
println!("Day09 part b = {}", part_b(&xss)); // 1113424
}
fn part_a(xss: &Vec<Vec<u32>>) -> usize {
let res = get_low_spots(&xss).iter().fold(0, |acc, (r, c)| acc + 1 + xss[*r][*c] as usize);
res
}
fn part_b(xss: &Vec<Vec<u32>>) -> usize {
let low_spots = get_low_spots(&xss);
let mut in_basin = HashSet::new();
let mut basins: Vec<usize> = low_spots.iter()
.map(|(r, c)| count_basin(&mut in_basin, xss, *r, *c))
.collect();
basins.sort_by(|a, b| b.cmp(a));
basins.iter().take(3).fold(1, |acc, v| acc * v)
}
fn get_low_spots(m: &Vec<Vec<u32>>) -> Vec<(usize, usize)> {
let mut ys = Vec::new();
let rows = m.len() - 2;
let cols = m[0].len() - 2;
for r in 1..=rows {
for c in 1..=cols {
if is_low_spot(m, r, c) {
ys.push((r, c));
}
}
}
ys
}
fn is_low_spot(m: &Vec<Vec<u32>>, r: usize, c: usize) -> bool {
if r < 1 || r > m.len() - 2 || c < 1 || c > m[0].len() - 2 {
return false;
}
let v = m[r][c];
v < m[r - 1][c] // up
&& v < m[r + 1][c] // down
&& v < m[r][c - 1] // left
&& v < m[r][c + 1] // right
}
fn count_basin(in_basin: &mut HashSet<(usize, usize)>, m: &Vec<Vec<u32>>, r: usize, c: usize) -> usize {
let mut count = 1;
in_basin.insert((r, c));
if m[r - 1][c] != 9 && !in_basin.contains(&(r - 1, c)) {
in_basin.insert((r - 1, c));
count += count_basin(in_basin, m, r - 1, c);
}
if m[r + 1][c] != 9 && !in_basin.contains(&(r + 1, c)) {
in_basin.insert((r + 1, c));
count += count_basin(in_basin, m, r + 1, c);
}
if m[r][c - 1] != 9 && !in_basin.contains(&(r, c - 1)) {
in_basin.insert((r, c - 1));
count += count_basin(in_basin, m, r, c - 1);
}
if m[r][c + 1] != 9 && !in_basin.contains(&(r, c + 1)) {
in_basin.insert((r, c + 1));
count += count_basin(in_basin, m, r, c + 1);
}
count
}
fn read_input(input_type: InputType) -> Vec<Vec<u32>> {
let data = {
match input_type {
InputType::Sample => include_str!("sample.txt"),
InputType::Input => include_str!("input.txt"),
}
};
let mut xss: Vec<Vec<u32>> = data
.lines()
.map(|s| s.chars()
.map(|ch| ch.to_digit(10).unwrap())
.collect())
.collect();
// pad matrix with zeros
for xs in &mut xss {
xs.insert(0, 9);
xs.push(9)
}
let cols = xss.first().unwrap().len();
let zeros = vec![9; cols];
xss.insert(0, zeros.clone());
xss.push(zeros.clone());
xss
}
#[cfg(test)]
mod tests {
use crate::{read_input, part_a, part_b};
use utils::InputType;
#[test]
fn test_part_a() {
let xss = read_input(InputType::Sample);
assert_eq!(15, part_a(&xss));
}
#[test]
fn test_part_b() {
let xss = read_input(InputType::Sample);
for xs in &xss {
println!("{:?}", xs);
}
assert_eq!(1134, part_b(&xss));
}
} |
/* Parse a string of the form attr=value,attr=value,attr=value */
bool
keychain_query_parse_string(CFMutableDictionaryRef q, CFStringRef s) {
bool inkey = true;
bool escaped = false;
bool error = false;
CFStringRef key = NULL;
CFMutableStringRef str = CFStringCreateMutable(0, 0);
CFRange rng = { .location = 0, .length = CFStringGetLength(s) };
CFCharacterSetRef cs_key = CFCharacterSetCreateWithCharactersInString(0, CFSTR("=\\"));
CFCharacterSetRef cs_value = CFCharacterSetCreateWithCharactersInString(0, CFSTR(",\\"));
while (rng.length) {
CFRange r;
CFStringRef sub;
bool complete = false;
if (escaped) {
r.location = rng.location;
r.length = 1;
sub = CFStringCreateWithSubstring(0, s, r);
escaped = false;
} else if (CFStringFindCharacterFromSet(s, inkey ? cs_key : cs_value, rng, 0, &r)) {
if (CFStringGetCharacterAtIndex(s, r.location) == '\\') {
escaped = true;
} else {
complete = true;
}
CFIndex next = r.location + 1;
r.length = r.location - rng.location;
r.location = rng.location;
sub = CFStringCreateWithSubstring(0, s, r);
rng.length -= next - rng.location;
rng.location = next;
} else {
sub = CFStringCreateWithSubstring(0, s, rng);
rng.location += rng.length;
rng.length = 0;
complete = true;
}
CFStringAppend(str, sub);
CFRelease(sub);
if (complete) {
CFStringRef value = CFStringCreateCopy(0, str);
CFStringReplaceAll(str, CFSTR(""));
if (inkey) {
key = value;
} else {
if(key && CFStringCompare(key, kSecAttrAccessControl, kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
SecAccessControlRef sac = keychain_query_parse_sac(value);
if(sac) {
CFDictionarySetValue(q, key, sac);
} else {
fprintf(stderr, "SecItemCopyMatching returned unexpected results:");
error = true;
}
} else {
CFDictionarySetValue(q, key, value);
}
CFReleaseNull(value);
CFReleaseNull(key);
}
inkey = !inkey;
}
if(error)
break;
}
if (key) {
CFDictionarySetValue(q, key, kCFBooleanTrue);
CFReleaseNull(key);
}
CFRelease(str);
CFRelease(cs_key);
CFRelease(cs_value);
return error == false;
} |
/**
* @author Yusuke Ikeda
*/
public class HttpResponseTest {
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
@Test
public void file_html() throws Exception {
File tmpFile = new File(tmpDir.getRoot(), "test.html");
Files.write(tmpFile.toPath(), "hello!!".getBytes("UTF-8"), StandardOpenOption.CREATE);
HttpResponse response = new HttpResponse(HttpStatus.OK);
response.setBody(tmpFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.writeTo(out);
String actual = out.toString("UTF-8");
assertThat(actual, is(
"HTTP/1.1 200 OK" + CRLF +
"Content-Type: text/html" + CRLF +
CRLF +
"hello!!"
));
}
@Test
public void basic() throws Exception {
HttpResponse response = new HttpResponse(HttpStatus.OK);
response.addHeader("Content-Type", ContentType.TEXT_HTML);
response.setBody("<h1>Hello World!!</h1>");
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.writeTo(out);
String actual = out.toString("UTF-8");
assertThat(actual, is(
"HTTP/1.1 200 OK" + CRLF +
"Content-Type: text/html" + CRLF +
CRLF +
"<h1>Hello World!!</h1>"
));
}
} |
/**
* a proxy class that helps classes to communicate internally without exposing the unnecessary API
*
* @param <S> the Outer Object type
* @param <T> the stored item type
*/
abstract class Proxy<S, T> {
/**
* access the Outer Object of this {@link Proxy}
*
* @return the Outer Object
*/
abstract S owner();
/**
* copy the Outer Object with a different item in it
*
* @return a new instance of the Outer Object
*/
S copy(T item) {
return copy(item, getConfiguration());
}
/**
* copy an instance of the outer Object
*
* @param item the new item for the new copy
* @return a new copy of the outer Object
*/
abstract S copy(T item, InternalConfiguration configuration);
/**
* get the {@link InternalConfiguration} associated with the outer Object
*
* @return the {@link InternalConfiguration} for the outer Object
*/
abstract InternalConfiguration getConfiguration();
/**
* get the current item in the current Object
*
* @return the item stored in the outer Object
*/
abstract T getItem();
} |
def quit_alternate_screen(self):
if self._in_alternate_screen:
stdout = HANDLE(self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE))
self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
self._winapi(windll.kernel32.CloseHandle, self.hconsole)
self.hconsole = stdout
self._in_alternate_screen = False |
<gh_stars>10-100
/* YUV->RGB conversion for Raspberry Pi camera, because fast video
port doesn't currently support raw RGB capture, only YUV.
python-dev required to build.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source development by purchasing
products from Adafruit, thanks!
Written by <NAME> / Paint Your Dragon for Adafruit Industries.
BSD license, all text above must be included in any redistribution. */
#include <python2.7/Python.h>
static PyObject *convert(PyObject *self, PyObject *args) {
Py_buffer inBuf, outBuf;
short row, col, r, g, b, w, h, rd, gd, bd;
unsigned char *rgbPtr, *yPtr, y;
signed char *uPtr, *vPtr, u, v;
if(!PyArg_ParseTuple(args, "s*s*hh", &inBuf, &outBuf, &w, &h))
return NULL;
if(w & 31) w += 32 - (w & 31); // Round up width to multiple of 32
if(h & 15) h += 16 - (h & 15); // Round up height to multiple of 16
rgbPtr = outBuf.buf;
yPtr = inBuf.buf;
uPtr = (signed char *)&yPtr[w * h];
vPtr = &uPtr[(w * h) >> 2];
w >>= 1; // 2 columns processed per iteration
for(row=0; row<h; row++) {
for(col=0; col<w; col++) {
// U, V (and RGB deltas) updated on even columns
u = uPtr[col] - 128;
v = vPtr[col] - 128;
rd = (359 * v) >> 8;
gd = ((183 * v) + (88 * u)) >> 8;
bd = (454 * u) >> 8;
// Even column
y = *yPtr++;
r = y + rd;
g = y - gd;
b = y + bd;
*rgbPtr++ = (r > 255) ? 255 : (r < 0) ? 0 : r;
*rgbPtr++ = (g > 255) ? 255 : (g < 0) ? 0 : g;
*rgbPtr++ = (b > 255) ? 255 : (b < 0) ? 0 : b;
// Odd column
y = *yPtr++;
r = y + rd;
g = y - gd;
b = y + bd;
*rgbPtr++ = (r > 255) ? 255 : (r < 0) ? 0 : r;
*rgbPtr++ = (g > 255) ? 255 : (g < 0) ? 0 : g;
*rgbPtr++ = (b > 255) ? 255 : (b < 0) ? 0 : b;
}
if(row & 1) {
uPtr += w;
vPtr += w;
}
}
PyBuffer_Release(&inBuf);
PyBuffer_Release(&outBuf);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef yuv2rgb_methods[] = {
{"convert", convert, METH_VARARGS},
{NULL,NULL}
};
PyMODINIT_FUNC inityuv2rgb(void) {
(void)Py_InitModule("yuv2rgb", yuv2rgb_methods);
}
|
<reponame>zixia/node-clone-class<gh_stars>1-10
#!/usr/bin/env -S node --no-warnings --loader ts-node/esm
/**
* Wechaty - https://github.com/chatie/wechaty
*
* @copyright 2016-2018 <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.
*
*/
import { test } from 'tstest'
import { FixtureClass } from '../tests/fixtures/fixture-class.js'
import { cloneClass } from './clone-class.js'
test('cloneClass smoke testing', async t => {
const EXPECTED_NUMBER1 = 1
const EXPECTED_NUMBER2 = 2
const NewClass1 = cloneClass(FixtureClass)
const NewClass2 = cloneClass(FixtureClass)
t.ok(NewClass1.prototype instanceof FixtureClass, 'should extend right')
t.not(NewClass1, NewClass2, 'NewClass1 should different with NewClass2')
t.not(NewClass1, FixtureClass, 'NewClass1 should different with FixtureClass')
NewClass1.staticMethod(EXPECTED_NUMBER1)
t.equal(NewClass1.staticNumber, EXPECTED_NUMBER1, 'should set static number to EXPECTED_NUMBER1')
NewClass2.staticMethod(EXPECTED_NUMBER2)
t.equal(NewClass2.staticNumber, EXPECTED_NUMBER2, 'should set static number to EXPECTED_NUMBER2')
const nc1 = new NewClass1(EXPECTED_NUMBER1, EXPECTED_NUMBER2)
const nc2 = new NewClass2(EXPECTED_NUMBER1, EXPECTED_NUMBER2)
t.ok(nc1 instanceof FixtureClass, 'nc1 should instanceof FixtureClass')
t.ok(nc1 instanceof NewClass1, 'nc1 should instanceof NewClass1')
t.equal(nc1.sum(), EXPECTED_NUMBER1 + EXPECTED_NUMBER1 + EXPECTED_NUMBER2, 'should sum right for 1 + 1 + 2')
t.equal(nc2.sum(), EXPECTED_NUMBER2 + EXPECTED_NUMBER1 + EXPECTED_NUMBER2, 'should sum right for 2 + 1 + 2')
})
test('cloneClass return NewClass with Original Name', async t => {
const NewClass = cloneClass(FixtureClass)
t.equal(NewClass.name, FixtureClass.name, 'should clone the same name for Class')
})
test('throw error when lowercase static property initilized with defination', async t => {
class Test {
public static n = { mof: 42 }
}
t.throws(() => cloneClass(Test), 'should throw when the static property initialized with a object in defination')
})
test('permit static property start with a captial letter to be initilized with defination', async t => {
class Test {
public static Data = { mof: 42 }
}
t.doesNotThrow(() => cloneClass(Test), 'should not throw when the static property start with a captial letter that initialized with a object in defination')
})
|
// ExistsAddresses is the concurrency safe, exported function that returns
// whether or not each address in a slice of addresses has been seen before.
func (idx *ExistsAddrIndex) ExistsAddresses(addrs []dcrutil.Address) ([]bool, error) {
exists := make([]bool, len(addrs))
addrKeys := make([][addrKeySize]byte, len(addrs))
for i := range addrKeys {
var err error
addrKeys[i], err = addrToKey(addrs[i], idx.chainParams)
if err != nil {
return nil, err
}
}
err := idx.db.View(func(dbTx database.Tx) error {
for i := range addrKeys {
meta := dbTx.Metadata()
existsAddrIndex := meta.Bucket(existsAddrIndexKey)
exists[i] = existsAddrIndex.Get(addrKeys[i][:]) != nil
}
return nil
})
if err != nil {
return nil, err
}
idx.unconfirmedLock.RLock()
for i := range addrKeys {
if !exists[i] {
_, exists[i] = idx.mpExistsAddr[addrKeys[i]]
}
}
idx.unconfirmedLock.RUnlock()
return exists, nil
} |
/**
* Returns a list of activities that are part of this application, skipping
* those from included libraries and *this* activity.
*/
public ArrayList<ExampleEntry> listActivities(Context context) {
ArrayList<ExampleEntry> result = new ArrayList<>();
try {
final String packageName = context.getPackageName();
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
for(ActivityInfo activityInfo : info.activities) {
parseExample(activityInfo, result);
}
return result;
} catch (Exception e) {
throw new IllegalStateException("failed to get list of activities", e);
}
} |
/*
* write a region of pages back to the server
*/
static int afs_writepages_region(struct address_space *mapping,
struct writeback_control *wbc,
loff_t start, loff_t end, loff_t *_next)
{
struct folio *folio;
struct page *head_page;
ssize_t ret;
int n, skips = 0;
_enter("%llx,%llx,", start, end);
do {
pgoff_t index = start / PAGE_SIZE;
n = find_get_pages_range_tag(mapping, &index, end / PAGE_SIZE,
PAGECACHE_TAG_DIRTY, 1, &head_page);
if (!n)
break;
folio = page_folio(head_page);
start = folio_pos(folio);
_debug("wback %lx", folio_index(folio));
if (wbc->sync_mode != WB_SYNC_NONE) {
ret = folio_lock_killable(folio);
if (ret < 0) {
folio_put(folio);
return ret;
}
} else {
if (!folio_trylock(folio)) {
folio_put(folio);
return 0;
}
}
if (folio_mapping(folio) != mapping ||
!folio_test_dirty(folio)) {
start += folio_size(folio);
folio_unlock(folio);
folio_put(folio);
continue;
}
if (folio_test_writeback(folio) ||
folio_test_fscache(folio)) {
folio_unlock(folio);
if (wbc->sync_mode != WB_SYNC_NONE) {
folio_wait_writeback(folio);
#ifdef CONFIG_AFS_FSCACHE
folio_wait_fscache(folio);
#endif
} else {
start += folio_size(folio);
}
folio_put(folio);
if (wbc->sync_mode == WB_SYNC_NONE) {
if (skips >= 5 || need_resched())
break;
skips++;
}
continue;
}
if (!folio_clear_dirty_for_io(folio))
BUG();
ret = afs_write_back_from_locked_folio(mapping, wbc, folio, start, end);
folio_put(folio);
if (ret < 0) {
_leave(" = %zd", ret);
return ret;
}
start += ret;
cond_resched();
} while (wbc->nr_to_write > 0);
*_next = start;
_leave(" = 0 [%llx]", *_next);
return 0;
} |
// DialogGetDialogsByOffsetDate
// dialog.getDialogsByOffsetDate user_id:long exclude_pinned:Bool offset_date:int limit:int = Vector<DialogExt>;
func (c *DialogCore) DialogGetDialogsByOffsetDate(in *dialog.TLDialogGetDialogsByOffsetDate) (*dialog.Vector_DialogExt, error) {
c.Logger.Errorf("dialog.getDialogsByOffsetDate - error: method DialogGetDialogsByOffsetDate not impl")
return nil, mtproto.ErrMethodNotImpl
} |
<reponame>dreadw8/test-task<filename>src/app/modules/categories/categories.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CqrsModule } from '@nestjs/cqrs';
import { CategoryEntity } from './entity';
import { FindCategoryBySlugQueryHandler } from './queries';
import { CategoryResolver } from './resolvers';
import { CategoriesAPI } from './api';
@Module({
imports: [
CqrsModule,
TypeOrmModule.forFeature([CategoryEntity]),
],
providers: [
CategoryResolver,
FindCategoryBySlugQueryHandler,
CategoriesAPI,
],
exports: [CategoriesAPI]
})
export class CategoriesModule {}
|
// putBucketRequest wrapper creates a new putBucket request
func (a apiV1) putBucketRequest(bucket, acl, location string) (*request, error) {
var r *request
var err error
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
HTTPPath: "/" + bucket,
}
var createBucketConfigBuffer *bytes.Reader
switch {
case location != "":
createBucketConfig := new(createBucketConfiguration)
createBucketConfig.Location = location
var createBucketConfigBytes []byte
switch {
case a.config.AcceptType == "application/xml":
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
case a.config.AcceptType == "application/json":
createBucketConfigBytes, err = json.Marshal(createBucketConfig)
default:
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
}
if err != nil {
return nil, err
}
createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
}
switch {
case createBucketConfigBuffer == nil:
r, err = newRequest(op, a.config, nil)
if err != nil {
return nil, err
}
default:
r, err = newRequest(op, a.config, createBucketConfigBuffer)
if err != nil {
return nil, err
}
r.req.ContentLength = int64(createBucketConfigBuffer.Len())
}
switch {
case acl != "":
r.Set("x-amz-acl", acl)
default:
r.Set("x-amz-acl", "private")
}
return r, nil
} |
def reglob(path: str, exp: str, invert: bool = False) -> List[str]:
m = re.compile(exp)
if invert is False:
res = [f for f in os.listdir(path) if m.match(f)]
else:
res = [f for f in os.listdir(path) if not m.match(f)]
res = [os.path.join(path, x) for x in res]
return res |
// GetAssetsFromBatch - get a group of assets
func (contract *FixedAssetContract) GetAssetsFromBatch(ctx utils.Context, batch []string) (*[]*assets.FixedAsset, error) {
fmt.Println("Entering getAssetsFromBatch")
retArr := make([]*assets.FixedAsset, len(batch))
for idx, uuid := range batch {
bytes, err := ctx.GetStub().GetState(uuid)
if err != nil {
return nil, err
}
fixedAsset := assets.FixedAsset{}
err = json.Unmarshal(bytes, &fixedAsset)
if err != nil {
return nil, err
}
retArr[idx] = &fixedAsset
}
return &retArr, nil
} |
/**
* @author Biju Joseph
*/
@CaaersUseCases({CREATE_PARTICIPANT})
public class ParticipantTest extends CaaersNoSecurityTestCase {
private Participant participant;
@Override
protected void setUp() throws Exception {
super.setUp();
participant = new Participant();
}
public void testGetStudies() throws Exception {
Study study1 = Fixtures.createStudy("S1");
study1.setId(1);
Fixtures.assignParticipant(participant, study1, Fixtures.SITE);
Study study2 = Fixtures.createStudy("S2");
study2.setId(2);
Fixtures.assignParticipant(participant, study2, Fixtures.SITE);
Study study3 = Fixtures.createStudy("S3");
study3.setId(3);
Fixtures.assignParticipant(participant, study3, Fixtures.SITE);
List<Study> actual = participant.getStudies();
assertEquals("Wrong number of studies found", 3, actual.size());
assertEquals("Wrong first study", "S1", actual.get(0).getShortTitle());
assertEquals("Wrong second study", "S2", actual.get(1).getShortTitle());
assertEquals("Wrong third study", "S3", actual.get(2).getShortTitle());
}
public void testCheckStudiesCanNotBeAssignedOnSameSiteAgain() throws Exception {
Fixtures.assignParticipant(participant, Fixtures.createStudy("S1"), Fixtures.SITE, 1);
Fixtures.assignParticipant(participant, Fixtures.createStudy("S2"), Fixtures.SITE, 1);
Fixtures.assignParticipant(participant, Fixtures.createStudy("S3"), Fixtures.SITE, 2);
List<Study> actual = participant.getStudies();
assertEquals("Wrong number of studies found", 2, actual.size());
}
} |
Assam Floods: Why Forgotten Assam not getting desired attention from Modi Govt?
Feature
oi-Reetu
By Reetu
After flash floods ravaged Jammu & Kashmir, in the worst ever natural disaster in last six decades, the North Eastern states of Assam and Meghalaya are the latest to witness the same tragedy triggered by incessant rain. But, it seems both the Centre and state governments did not plan things in advance to deal with a situation like this.
Although relief and rescue teams were sent to the affected areas but had the government bodies been proactive in their approach, precious lives could have been saved. It seems that the government perhaps focused heavily on the relief and rescue operations in Kashmir but forgot to plan things beforehand to tackle situation in North East, where such problems occur every year.
Current flood situation in North East
Heavy rains in Goalpara district coupled with that in neighbouring Garo Hills of Meghalaya was causing the deluge to be intensified in the district.
At least 10 people have died in the landslide and several villages in Goalpara, Dhubri, Lakhimpur and Kamrup (Rural) district, besides Guwahati inundated by water.
A child was killed in a landslide in Dhubri district's Hatsingimari, while one person was electrocuted in Guwahati where a body floating on river Bharalu was also recovered, state government officials said.
In Goalpara district, the army and State Disaster Response Force (SDRF) were assisting the district administration in rescuing the over 50,000 people marooned in 100 villages due to the deluge in Krishnai, Dudhnoi and Bolbola areas, district Deputy Commissioner (DC) Preetam Saikia said.
The NH-37 was overrun by the flood waters that were flowing above the tin roofed and thatch houses in many areas in Goalpara. Brahmaputra, the Assam's Sorrow, has swelled and started flooding its embankments.
Polls in J&K and no polls in Assam that's why ignorance?
The way Central government handled the flood situation in the state of Jammu & Kashmir is laudable but things are not happening in the North eastern area at the same pace. What is the probable reason for slow rescue and relief operation in the Eastern state? Was J&K given a special attention just because the state will be witnessing assembly polls and the BJP smells an opportunity in bagging a considerably good number of seats from the valley state?
People are also feeling that because there are no such elections in the near future in the North Eastern states, that is why these regions are not being highlighted the way things were in the case of J&K floods.
Step-motherly behaviour with Assam?
People in Assam have been saying in the past that Governments' have always given step-motherly treatment to the state.
A report in the Assam Tribune said, "Accusing the BJP-led NDA of turning a blind eye to Assam's pressing problems, public activist Prof Deven Dutta today said that life-and-death issues such as illegal cross-border migration, recurring floods and erosion, stagnant agriculture, etc., were continued to be ignored by the new dispensation in the same manner as was done by the preceding Congress-led UPA regime."
"There is very little to differentiate between Prime Minister Narendra Modi and UPA chairperson and Congress president Sonia Gandhi when it comes to addressing the burning issues of Assam. Similarly, Home Minister Rajnath Singh, Water Resources Minister Uma Bharati and Agriculture Minister Radhamohan Singh have also made it clear that Assam's genuine interests are never a priority for them," Prof Dutta was quoted as saying in the daily.
Floods in Assam is "nothing new", still why no action so far?
"Flood condition is nothing new to Assam. I have been dealing with floods in Assam since 1970 onwards," Union minister for Development of North Eastern Region (DoNER) Vijay Kumar Singh had once said.
But the question is if it is really not a new thing then why has nothing concrete been done so far to prevent such so called natural calamities, which in reality are man made.
Why not a serious thought on silting of Brahmaputra so far?
Experts have been saying that silting of Brahmaputra is a big problem and is also a reason of these floods, but the governments so far have not given a serious thought on this over the years. In forgotten Assam, floods inundate hundreds of villages and many precious lives are lost, but still no steps are taken.
Floods displace lakhs of people every year in this forgotten part of the country, but despite the fact nothing has been so far to prevent it. The Modi Government was applauded for the relief and rescue operations it ordered for J&K lets hope that the people of Assam and neighbouring areas, marooned by floods, heap praises for the government. |
With VMworld 2015 around the corner I thought this would be a great time to announce our latest version of the VMware Certified Professional – DCV study guide. A few years back, Jason Langer (blog / twitter) and I teamed up with Veeam Software and released the VMware Certified Professional 5 – DCV study guide, which you can find here. We have again teamed up with Veeam and I’m happy to announce the availability of The Unofficial Official VMware Certififed Professional 6 -DCV Study Guide. There is a chance that there will be printed copies (free of course) available at the Veeam booth at VMworld, so if you prefer hard copied study material and don’t want to use 163 pieces of your own paper, be sure to stop by their booth and grab a copy.
Hope to see you at VMworld! |
// There is nothing in a caterpillar that tells you its going to be a butterfly --------------------- !
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long int
#define pi pair<int,int>
#define pii pair<ll,pi>
#define f first
#define mp make_pair
#define mod 1000000007
#define s second
#define pb push_back
ll c[111][111];
int main(){
int n,m;
cin >> n >> m;
rep(i,n)
rep(j,m)
cin >> c[i][j];
ll ans=0;
rep(i,n){
ll h=INT_MAX;
rep(j,m){
h=min(h,c[i][j]);
}
ans=max(ans,h);
}
cout<<ans;
}
|
n=input()
a=[int(x) for x in raw_input().split()]
m=input()
for i in xrange(m):
y,x=map(int,raw_input().split())
l=x-1
r=a[y-1]-x
if y==1:
a[0]=0
if len(a)>1:
a[1]+=r
elif y==n:
a[-2]+=l
a[-1]=0
else:
a[y-2]+=l
a[y]+=r
a[y-1]=0
for ans in a:
print ans |
/**
* Facilitates the extraction of AAC samples from elementary audio files formatted as AAC with ADTS
* headers.
*/
public class AdtsExtractor extends HlsExtractor {
private static final int MAX_PACKET_SIZE = 200;
private final long firstSampleTimestamp;
private final ParsableByteArray packetBuffer;
private final AdtsReader adtsReader;
// Accessed only by the loading thread.
private boolean firstPacket;
// Accessed by both the loading and consuming threads.
private volatile boolean prepared;
public AdtsExtractor(boolean shouldSpliceIn, long firstSampleTimestamp, BufferPool bufferPool) {
super(shouldSpliceIn);
this.firstSampleTimestamp = firstSampleTimestamp;
packetBuffer = new ParsableByteArray(MAX_PACKET_SIZE);
adtsReader = new AdtsReader(bufferPool);
firstPacket = true;
}
@Override
public int getTrackCount() {
Assertions.checkState(prepared);
return 1;
}
@Override
public MediaFormat getFormat(int track) {
Assertions.checkState(prepared);
return adtsReader.getMediaFormat();
}
@Override
public boolean isPrepared() {
return prepared;
}
@Override
public void release() {
adtsReader.release();
}
@Override
public long getLargestSampleTimestamp() {
return adtsReader.getLargestParsedTimestampUs();
}
@Override
public boolean getSample(int track, SampleHolder holder) {
Assertions.checkState(prepared);
Assertions.checkState(track == 0);
return adtsReader.getSample(holder);
}
@Override
public void discardUntil(int track, long timeUs) {
Assertions.checkState(prepared);
Assertions.checkState(track == 0);
adtsReader.discardUntil(timeUs);
}
@Override
public boolean hasSamples(int track) {
Assertions.checkState(prepared);
Assertions.checkState(track == 0);
return !adtsReader.isEmpty();
}
@Override
public int read(DataSource dataSource) throws IOException {
int bytesRead = dataSource.read(packetBuffer.data, 0, MAX_PACKET_SIZE);
if (bytesRead == -1) {
return -1;
}
packetBuffer.setPosition(0);
packetBuffer.setLimit(bytesRead);
// TODO: Make it possible for adtsReader to consume the dataSource directly, so that it becomes
// unnecessary to copy the data through packetBuffer.
adtsReader.consume(packetBuffer, firstSampleTimestamp, firstPacket);
firstPacket = false;
if (!prepared) {
prepared = adtsReader.hasMediaFormat();
}
return bytesRead;
}
@Override
protected SampleQueue getSampleQueue(int track) {
Assertions.checkState(track == 0);
return adtsReader;
}
} |
// FetchEvents returns all events for a calendar in a slice
func (cal Calendar) FetchEvents() ([]Event, error) {
var events []Event
err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte(cal)).Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
var event Event
err := json.Unmarshal(v, &event)
if err != nil {
return err
}
events = append(events, event)
}
return nil
})
return events, err
} |
// return null if the media type can not be recognized.
private static OdfDocument loadDocumentFromTemplate(OdfMediaType odfMediaType) throws Exception {
final Resource documentTemplate;
switch (odfMediaType) {
case TEXT:
case TEXT_TEMPLATE:
case TEXT_MASTER:
case TEXT_WEB:
documentTemplate = OdfTextDocument.EMPTY_TEXT_DOCUMENT_RESOURCE;
break;
case SPREADSHEET:
case SPREADSHEET_TEMPLATE:
documentTemplate = OdfSpreadsheetDocument.EMPTY_SPREADSHEET_DOCUMENT_RESOURCE;
break;
case PRESENTATION:
case PRESENTATION_TEMPLATE:
documentTemplate = OdfPresentationDocument.EMPTY_PRESENTATION_DOCUMENT_RESOURCE;
break;
case GRAPHICS:
case GRAPHICS_TEMPLATE:
documentTemplate = OdfGraphicsDocument.EMPTY_GRAPHICS_DOCUMENT_RESOURCE;
break;
case CHART:
case CHART_TEMPLATE:
documentTemplate = OdfChartDocument.EMPTY_CHART_DOCUMENT_RESOURCE;
break;
case IMAGE:
case IMAGE_TEMPLATE:
documentTemplate = OdfImageDocument.EMPTY_IMAGE_DOCUMENT_RESOURCE;
break;
default:
documentTemplate = null;
throw new IllegalArgumentException(
"Given mediaType '" + odfMediaType.mMediaType + "' is not yet supported!");
}
return loadTemplate(documentTemplate, odfMediaType);
} |
<filename>vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go
// +build !go1.7
package tlsconfig
import (
"crypto/x509"
"github.com/Sirupsen/logrus"
)
// SystemCertPool returns an new empty cert pool,
// accessing system cert pool is supported in go 1.7
func SystemCertPool() (*x509.CertPool, error) {
logrus.Warn("Unable to use system certificate pool: requires building with go 1.7 or later")
return x509.NewCertPool(), nil
}
|
/* Code decompiled incorrectly, please refer to instructions dump. */
public final int M(T r17, byte[] r18, int r19, int r20, int r21, int r22, int r23, int r24, long r25, int r27, long r28, b.l.a.c.f.e.jm r30) {
/*
r16 = this;
r0 = r16
r1 = r17
r3 = r18
r4 = r19
r5 = r20
r2 = r21
r6 = r23
r8 = r24
r9 = r28
r7 = r30
sun.misc.Unsafe r11 = f2986q
java.lang.Object r12 = r11.getObject(r1, r9)
b.l.a.c.f.e.i r12 = (b.l.a.c.f.e.i) r12
boolean r13 = r12.a()
if (r13 != 0) goto L_0x0033
int r13 = r12.size()
if (r13 != 0) goto L_0x002b
r13 = 10
goto L_0x002c
L_0x002b:
int r13 = r13 + r13
L_0x002c:
b.l.a.c.f.e.i r12 = r12.h(r13)
r11.putObject(r1, r9, r12)
L_0x0033:
r9 = 5
r10 = 2
r11 = 1
r13 = 0
switch(r27) {
case 18: goto L_0x0391;
case 19: goto L_0x0348;
case 20: goto L_0x0310;
case 21: goto L_0x0310;
case 22: goto L_0x02f5;
case 23: goto L_0x02b6;
case 24: goto L_0x0275;
case 25: goto L_0x0221;
case 26: goto L_0x0176;
case 27: goto L_0x015b;
case 28: goto L_0x010e;
case 29: goto L_0x02f5;
case 30: goto L_0x00d8;
case 31: goto L_0x0275;
case 32: goto L_0x02b6;
case 33: goto L_0x0098;
case 34: goto L_0x0058;
case 35: goto L_0x0391;
case 36: goto L_0x0348;
case 37: goto L_0x0310;
case 38: goto L_0x0310;
case 39: goto L_0x02f5;
case 40: goto L_0x02b6;
case 41: goto L_0x0275;
case 42: goto L_0x0221;
case 43: goto L_0x02f5;
case 44: goto L_0x00d8;
case 45: goto L_0x0275;
case 46: goto L_0x02b6;
case 47: goto L_0x0098;
case 48: goto L_0x0058;
default: goto L_0x003b;
}
L_0x003b:
r1 = 3
if (r6 != r1) goto L_0x03f9
b.l.a.c.f.e.o0 r1 = r0.P(r8)
r6 = r2 & -8
r6 = r6 | 4
r22 = r1
r23 = r18
r24 = r19
r25 = r20
r26 = r6
r27 = r30
int r4 = b.l.a.c.b.a.A2(r22, r23, r24, r25, r26, r27)
goto L_0x03d7
L_0x0058:
if (r6 != r10) goto L_0x007c
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x0063:
if (r1 >= r2) goto L_0x0073
int r1 = b.l.a.c.b.a.R1(r3, r1, r7)
long r4 = r7.f3100b
long r4 = b.l.a.c.f.e.vm.o(r4)
r12.l(r4)
goto L_0x0063
L_0x0073:
if (r1 != r2) goto L_0x0077
goto L_0x03fa
L_0x0077:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x007c:
if (r6 != 0) goto L_0x03f9
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
L_0x0080:
int r1 = b.l.a.c.b.a.R1(r3, r4, r7)
long r8 = r7.f3100b
long r8 = b.l.a.c.f.e.vm.o(r8)
r12.l(r8)
if (r1 >= r5) goto L_0x0097
int r4 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x0080
L_0x0097:
return r1
L_0x0098:
if (r6 != r10) goto L_0x00bc
b.l.a.c.f.e.f r12 = (b.l.a.c.f.e.f) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x00a3:
if (r1 >= r2) goto L_0x00b3
int r1 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r4 = r7.a
int r4 = b.l.a.c.f.e.vm.n(r4)
r12.l(r4)
goto L_0x00a3
L_0x00b3:
if (r1 != r2) goto L_0x00b7
goto L_0x03fa
L_0x00b7:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x00bc:
if (r6 != 0) goto L_0x03f9
b.l.a.c.f.e.f r12 = (b.l.a.c.f.e.f) r12
L_0x00c0:
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
int r4 = b.l.a.c.f.e.vm.n(r4)
r12.l(r4)
if (r1 >= r5) goto L_0x00d7
int r4 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x00c0
L_0x00d7:
return r1
L_0x00d8:
if (r6 != r10) goto L_0x00df
int r2 = b.l.a.c.b.a.E2(r3, r4, r12, r7)
goto L_0x00f0
L_0x00df:
if (r6 != 0) goto L_0x03f9
r2 = r21
r3 = r18
r4 = r19
r5 = r20
r6 = r12
r7 = r30
int r2 = b.l.a.c.b.a.C2(r2, r3, r4, r5, r6, r7)
L_0x00f0:
b.l.a.c.f.e.e r1 = (b.l.a.c.f.e.e) r1
b.l.a.c.f.e.d1 r3 = r1.zzc
b.l.a.c.f.e.d1 r4 = b.l.a.c.f.e.d1.f
if (r3 != r4) goto L_0x00f9
r3 = 0
L_0x00f9:
b.l.a.c.f.e.h r4 = r0.R(r8)
b.l.a.c.f.e.c1<?, ?> r5 = r0.f2995m
r6 = r22
java.lang.Object r3 = b.l.a.c.f.e.q0.b(r6, r12, r4, r3, r5)
if (r3 != 0) goto L_0x0109
goto L_0x0242
L_0x0109:
b.l.a.c.f.e.d1 r3 = (b.l.a.c.f.e.d1) r3
r1.zzc = r3
return r2
L_0x010e:
if (r6 != r10) goto L_0x03f9
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x0156
int r6 = r3.length
int r6 = r6 - r1
if (r4 > r6) goto L_0x0151
if (r4 != 0) goto L_0x011f
goto L_0x0140
L_0x011f:
b.l.a.c.f.e.um r6 = b.l.a.c.f.e.um.J(r3, r1, r4)
r12.add(r6)
int r1 = r1 + r4
L_0x0127:
if (r1 >= r5) goto L_0x0150
int r4 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x0132
goto L_0x0150
L_0x0132:
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x014b
int r6 = r3.length
int r6 = r6 - r1
if (r4 > r6) goto L_0x0146
if (r4 != 0) goto L_0x011f
L_0x0140:
b.l.a.c.f.e.um r4 = b.l.a.c.f.e.um.f3344i
r12.add(r4)
goto L_0x0127
L_0x0146:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x014b:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x0150:
return r1
L_0x0151:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x0156:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x015b:
if (r6 == r10) goto L_0x015f
goto L_0x03f9
L_0x015f:
b.l.a.c.f.e.o0 r1 = r0.P(r8)
r22 = r1
r23 = r21
r24 = r18
r25 = r19
r26 = r20
r27 = r12
r28 = r30
int r1 = b.l.a.c.b.a.G2(r22, r23, r24, r25, r26, r27, r28)
return r1
L_0x0176:
if (r6 != r10) goto L_0x03f9
r8 = 536870912(0x20000000, double:2.652494739E-315)
long r8 = r25 & r8
int r1 = (r8 > r13 ? 1 : (r8 == r13 ? 0 : -1))
java.lang.String r6 = ""
if (r1 != 0) goto L_0x01c3
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x01be
if (r4 != 0) goto L_0x018e
goto L_0x01ad
L_0x018e:
java.lang.String r8 = new java.lang.String
java.nio.charset.Charset r9 = b.l.a.c.f.e.j.a
r8.<init>(r3, r1, r4, r9)
L_0x0195:
r12.add(r8)
int r1 = r1 + r4
L_0x0199:
if (r1 >= r5) goto L_0x03fa
int r4 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r8 = r7.a
if (r2 != r8) goto L_0x03fa
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x01b9
if (r4 != 0) goto L_0x01b1
L_0x01ad:
r12.add(r6)
goto L_0x0199
L_0x01b1:
java.lang.String r8 = new java.lang.String
java.nio.charset.Charset r9 = b.l.a.c.f.e.j.a
r8.<init>(r3, r1, r4, r9)
goto L_0x0195
L_0x01b9:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x01be:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x01c3:
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x021c
if (r4 != 0) goto L_0x01cf
L_0x01cd:
r8 = r1
goto L_0x01f6
L_0x01cf:
int r8 = r1 + r4
boolean r9 = b.l.a.c.f.e.s1.a(r3, r1, r8)
if (r9 == 0) goto L_0x0217
java.lang.String r9 = new java.lang.String
java.nio.charset.Charset r10 = b.l.a.c.f.e.j.a
r9.<init>(r3, r1, r4, r10)
L_0x01de:
r12.add(r9)
L_0x01e1:
if (r8 >= r5) goto L_0x0214
int r1 = b.l.a.c.b.a.Q0(r3, r8, r7)
int r4 = r7.a
if (r2 != r4) goto L_0x0214
int r1 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r4 = r7.a
if (r4 < 0) goto L_0x020f
if (r4 != 0) goto L_0x01fa
goto L_0x01cd
L_0x01f6:
r12.add(r6)
goto L_0x01e1
L_0x01fa:
int r8 = r1 + r4
boolean r9 = b.l.a.c.f.e.s1.a(r3, r1, r8)
if (r9 == 0) goto L_0x020a
java.lang.String r9 = new java.lang.String
java.nio.charset.Charset r10 = b.l.a.c.f.e.j.a
r9.<init>(r3, r1, r4, r10)
goto L_0x01de
L_0x020a:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.g()
throw r1
L_0x020f:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x0214:
r1 = r8
goto L_0x03fa
L_0x0217:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.g()
throw r1
L_0x021c:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.b()
throw r1
L_0x0221:
r1 = 0
if (r6 != r10) goto L_0x024a
b.l.a.c.f.e.km r12 = (b.l.a.c.f.e.km) r12
int r2 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r4 = r7.a
int r4 = r4 + r2
L_0x022d:
if (r2 >= r4) goto L_0x0240
int r2 = b.l.a.c.b.a.R1(r3, r2, r7)
long r5 = r7.f3100b
int r5 = (r5 > r13 ? 1 : (r5 == r13 ? 0 : -1))
if (r5 == 0) goto L_0x023b
r5 = r11
goto L_0x023c
L_0x023b:
r5 = r1
L_0x023c:
r12.e(r5)
goto L_0x022d
L_0x0240:
if (r2 != r4) goto L_0x0245
L_0x0242:
r1 = r2
goto L_0x03fa
L_0x0245:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x024a:
if (r6 != 0) goto L_0x03f9
b.l.a.c.f.e.km r12 = (b.l.a.c.f.e.km) r12
int r4 = b.l.a.c.b.a.R1(r3, r4, r7)
long r8 = r7.f3100b
int r6 = (r8 > r13 ? 1 : (r8 == r13 ? 0 : -1))
if (r6 == 0) goto L_0x0259
goto L_0x0272
L_0x0259:
r6 = r1
L_0x025a:
r12.e(r6)
if (r4 >= r5) goto L_0x0274
int r6 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r8 = r7.a
if (r2 == r8) goto L_0x0268
goto L_0x0274
L_0x0268:
int r4 = b.l.a.c.b.a.R1(r3, r6, r7)
long r8 = r7.f3100b
int r6 = (r8 > r13 ? 1 : (r8 == r13 ? 0 : -1))
if (r6 == 0) goto L_0x0259
L_0x0272:
r6 = r11
goto L_0x025a
L_0x0274:
return r4
L_0x0275:
if (r6 != r10) goto L_0x0295
b.l.a.c.f.e.f r12 = (b.l.a.c.f.e.f) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x0280:
if (r1 >= r2) goto L_0x028c
int r4 = b.l.a.c.b.a.a2(r3, r1)
r12.l(r4)
int r1 = r1 + 4
goto L_0x0280
L_0x028c:
if (r1 != r2) goto L_0x0290
goto L_0x03fa
L_0x0290:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x0295:
if (r6 != r9) goto L_0x03f9
b.l.a.c.f.e.f r12 = (b.l.a.c.f.e.f) r12
int r1 = b.l.a.c.b.a.a2(r18, r19)
L_0x029d:
r12.l(r1)
int r4 = r4 + 4
if (r4 >= r5) goto L_0x02b5
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x02ad
goto L_0x02b5
L_0x02ad:
int r4 = b.l.a.c.b.a.a2(r3, r1)
r15 = r4
r4 = r1
r1 = r15
goto L_0x029d
L_0x02b5:
return r4
L_0x02b6:
if (r6 != r10) goto L_0x02d6
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x02c1:
if (r1 >= r2) goto L_0x02cd
long r4 = b.l.a.c.b.a.h2(r3, r1)
r12.l(r4)
int r1 = r1 + 8
goto L_0x02c1
L_0x02cd:
if (r1 != r2) goto L_0x02d1
goto L_0x03fa
L_0x02d1:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x02d6:
if (r6 != r11) goto L_0x03f9
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
long r8 = b.l.a.c.b.a.h2(r18, r19)
L_0x02de:
r12.l(r8)
int r4 = r4 + 8
if (r4 >= r5) goto L_0x02f4
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x02ee
goto L_0x02f4
L_0x02ee:
long r8 = b.l.a.c.b.a.h2(r3, r1)
r4 = r1
goto L_0x02de
L_0x02f4:
return r4
L_0x02f5:
if (r6 != r10) goto L_0x02fd
int r1 = b.l.a.c.b.a.E2(r3, r4, r12, r7)
goto L_0x03fa
L_0x02fd:
if (r6 == 0) goto L_0x0301
goto L_0x03f9
L_0x0301:
r22 = r18
r23 = r19
r24 = r20
r25 = r12
r26 = r30
int r1 = b.l.a.c.b.a.C2(r21, r22, r23, r24, r25, r26)
return r1
L_0x0310:
if (r6 != r10) goto L_0x0330
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x031b:
if (r1 >= r2) goto L_0x0327
int r1 = b.l.a.c.b.a.R1(r3, r1, r7)
long r4 = r7.f3100b
r12.l(r4)
goto L_0x031b
L_0x0327:
if (r1 != r2) goto L_0x032b
goto L_0x03fa
L_0x032b:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x0330:
if (r6 != 0) goto L_0x03f9
b.l.a.c.f.e.t r12 = (b.l.a.c.f.e.t) r12
L_0x0334:
int r1 = b.l.a.c.b.a.R1(r3, r4, r7)
long r8 = r7.f3100b
r12.l(r8)
if (r1 >= r5) goto L_0x0347
int r4 = b.l.a.c.b.a.Q0(r3, r1, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x0334
L_0x0347:
return r1
L_0x0348:
if (r6 != r10) goto L_0x036c
b.l.a.c.f.e.mn r12 = (b.l.a.c.f.e.mn) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x0353:
if (r1 >= r2) goto L_0x0363
int r4 = b.l.a.c.b.a.a2(r3, r1)
float r4 = java.lang.Float.intBitsToFloat(r4)
r12.e(r4)
int r1 = r1 + 4
goto L_0x0353
L_0x0363:
if (r1 != r2) goto L_0x0367
goto L_0x03fa
L_0x0367:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x036c:
if (r6 != r9) goto L_0x03f9
b.l.a.c.f.e.mn r12 = (b.l.a.c.f.e.mn) r12
int r1 = b.l.a.c.b.a.a2(r18, r19)
L_0x0374:
float r1 = java.lang.Float.intBitsToFloat(r1)
r12.e(r1)
int r4 = r4 + 4
if (r4 >= r5) goto L_0x0390
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x0388
goto L_0x0390
L_0x0388:
int r4 = b.l.a.c.b.a.a2(r3, r1)
r15 = r4
r4 = r1
r1 = r15
goto L_0x0374
L_0x0390:
return r4
L_0x0391:
if (r6 != r10) goto L_0x03b4
b.l.a.c.f.e.dn r12 = (b.l.a.c.f.e.dn) r12
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r2 = r7.a
int r2 = r2 + r1
L_0x039c:
if (r1 >= r2) goto L_0x03ac
long r4 = b.l.a.c.b.a.h2(r3, r1)
double r4 = java.lang.Double.longBitsToDouble(r4)
r12.e(r4)
int r1 = r1 + 8
goto L_0x039c
L_0x03ac:
if (r1 != r2) goto L_0x03af
goto L_0x03fa
L_0x03af:
b.l.a.c.f.e.l r1 = b.l.a.c.f.e.l.a()
throw r1
L_0x03b4:
if (r6 != r11) goto L_0x03f9
b.l.a.c.f.e.dn r12 = (b.l.a.c.f.e.dn) r12
long r8 = b.l.a.c.b.a.h2(r18, r19)
L_0x03bc:
double r8 = java.lang.Double.longBitsToDouble(r8)
r12.e(r8)
int r4 = r4 + 8
if (r4 >= r5) goto L_0x03d6
int r1 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r6 = r7.a
if (r2 == r6) goto L_0x03d0
goto L_0x03d6
L_0x03d0:
long r8 = b.l.a.c.b.a.h2(r3, r1)
r4 = r1
goto L_0x03bc
L_0x03d6:
return r4
L_0x03d7:
java.lang.Object r8 = r7.c
r12.add(r8)
if (r4 >= r5) goto L_0x03f8
int r8 = b.l.a.c.b.a.Q0(r3, r4, r7)
int r9 = r7.a
if (r2 == r9) goto L_0x03e7
goto L_0x03f8
L_0x03e7:
r22 = r1
r23 = r18
r24 = r8
r25 = r20
r26 = r6
r27 = r30
int r4 = b.l.a.c.b.a.A2(r22, r23, r24, r25, r26, r27)
goto L_0x03d7
L_0x03f8:
return r4
L_0x03f9:
r1 = r4
L_0x03fa:
return r1
*/
throw new UnsupportedOperationException("Method not decompiled: b.l.a.c.f.e.g0.M(java.lang.Object, byte[], int, int, int, int, int, int, long, int, long, b.l.a.c.f.e.jm):int");
} |
//
// unpackTitleSeparator set the Title separator using the first character in
// meta attribute "title-separator" value.
//
func (doc *Document) unpackTitleSeparator() {
v, ok := doc.Attributes[metaNameTitleSeparator]
if ok {
v = strings.TrimSpace(v)
if len(v) > 0 {
doc.Title.sep = v[0]
}
}
} |
# ----------------------------------------------------------------- #
# The HMM-Based Speech Synthesis System (HTS) #
# developed by HTS Working Group #
# http://hts.sp.nitech.ac.jp/ #
# ----------------------------------------------------------------- #
# #
# Copyright (c) 2014-2016 Nagoya Institute of Technology #
# Department of Computer Science #
# #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or #
# without modification, are permitted provided that the following #
# conditions are met: #
# #
# - Redistributions of source code must retain the above copyright #
# notice, this list of conditions and the following disclaimer. #
# - Redistributions in binary form must reproduce the above #
# copyright notice, this list of conditions and the following #
# disclaimer in the documentation and/or other materials provided #
# with the distribution. #
# - Neither the name of the HTS working group nor the names of its #
# contributors may be used to endorse or promote products derived #
# from this software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND #
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, #
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF #
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS #
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED #
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON #
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY #
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# ----------------------------------------------------------------- #
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from six.moves import xrange
import tensorflow as tf
def get_activation_function(string):
word = string.lower()
if word == 'linear':
return tf.identity
elif word == 'sigmoid':
return tf.nn.sigmoid
elif word == 'tanh':
return tf.nn.tanh
elif word == 'relu':
return tf.nn.relu
else:
raise NotImplementedError
def get_optimizer(string, learning_rate):
word = string.lower()
if word == 'sgd':
return tf.train.GradientDescentOptimizer(learning_rate)
elif word == 'momentum':
return tf.train.MomentumOptimizer(learning_rate, 0.9)
elif word == 'adagrad':
return tf.train.AdagradOptimizer(learning_rate)
elif word == 'adadelta':
return tf.train.AdadeltaOptimizer(learning_rate)
elif word == 'adam':
return tf.train.AdamOptimizer(learning_rate)
elif word == 'rmsprop':
return tf.train.RMSPropOptimizer(learning_rate)
else:
raise NotImplementedError
def get_num_parameters():
total_params = 0
for variable in tf.trainable_variables():
num_params = 1
for dimension in variable.get_shape():
num_params *= dimension.value
total_params += num_params
return total_params
def inference(inputs, num_io_units, num_hidden_units,
hidden_activation, output_activation, keep_prob,
seed=None, given_params=None):
tf.set_random_seed(seed)
num_input_units, num_output_units = num_io_units
hidden_activation_function = get_activation_function(hidden_activation)
output_activation_function = get_activation_function(output_activation)
param_num = 0
params = []
hidden_outputs = None
num_hidden_layers = len(num_hidden_units)
for i in xrange(num_hidden_layers):
with tf.name_scope('hidden' + str(i)):
if i == 0:
hidden_inputs = inputs
num_prev_hidden_units = num_input_units
else:
hidden_inputs = hidden_outputs
num_prev_hidden_units = num_hidden_units[i - 1]
if given_params is None:
weights = tf.Variable(
tf.truncated_normal(
[num_prev_hidden_units, num_hidden_units[i]],
stddev=1.0 / math.sqrt(float(num_prev_hidden_units))),
name='weights')
biases = tf.Variable(
tf.zeros([num_hidden_units[i]]),
name='biases')
params.extend([weights, biases])
else:
weights = given_params[param_num]
param_num += 1
biases = given_params[param_num]
param_num += 1
hidden_outputs = hidden_activation_function(
tf.matmul(hidden_inputs, weights) + biases)
hidden_outputs = tf.nn.dropout(hidden_outputs, keep_prob)
with tf.name_scope('output'):
if hidden_outputs is None:
hidden_outputs = inputs
num_prev_output_units = num_input_units
else:
num_prev_output_units = num_hidden_units[num_hidden_layers - 1]
if given_params is None:
weights = tf.Variable(
tf.truncated_normal(
[num_prev_output_units, num_output_units],
stddev=1.0 / math.sqrt(float(num_prev_output_units))),
name='weights')
biases = tf.Variable(
tf.zeros([num_output_units]),
name='biases')
params.extend([weights, biases])
else:
weights = given_params[param_num]
param_num += 1
biases = given_params[param_num]
param_num += 1
outputs = output_activation_function(
tf.matmul(hidden_outputs, weights) + biases)
return outputs, params
def training(cost, optimizer_type, learning_rate):
optimizer = get_optimizer(optimizer_type, learning_rate)
global_step = tf.Variable(0, name='global_step', trainable=False)
train_op = optimizer.minimize(cost, global_step=global_step)
return train_op
def cost(predicted_outputs, observed_outputs, error_adjustments):
cost = tf.reduce_mean(tf.square(tf.div(
predicted_outputs - observed_outputs, error_adjustments)))
return cost
|
<gh_stars>1-10
package org.coinjoin.util;
import java.math.BigInteger;
public class RSABlindedData {
private BigInteger r;
private byte[] m;
public BigInteger GetMultiplier() {
return r;
}
public byte[] GetData() {
return m;
}
public RSABlindedData(BigInteger r, byte[] m) {
this.m = m;
this.r = r;
}
}
|
// Update updates device weight in DeviceWeights slice, or appends it if not found.
func (w *DeviceWeights) Update(maj, min, val int64) {
for index, devWeight := range *w {
if devWeight.Major == maj && devWeight.Minor == min {
(*w)[index].Weight = val
return
}
}
w.Append(maj, min, val)
} |
/* Basically a depth-first search (DFS).
Marks each array value as 1 when visiting (Side-effect: alters array) */
private static boolean solvable(int [] array, int m, int i) {
/* Base Cases */
if (i < 0 || array[i] == 1) {
return false;
} else if (i + 1 >= array.length || i + m >= array.length) {
return true;
}
array[i] = 1;
/* Recursive Cases */
return solvable(array, m, i - 1) ||
solvable(array, m, i + 1) ||
solvable(array, m, i + m);
} |
<gh_stars>1-10
//
// Shoulder
// Copyright (C) 2018 Assured Information Security, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#define CATCH_CONFIG_MAIN
#include <stdint.h>
#include "aarch64_gcc_accessor_macros.h"
#include "catch.hpp"
// -----------------------------------------------------------------------------
// Test Support
// -----------------------------------------------------------------------------
// w19 (32-bit) and x20 (64-bit) are used as test registers because they
// are required by the aarch64 calling convension to be callee-preserved
register uint32_t g_w19 asm ("w19");
register uint64_t g_x20 asm ("x20");
// The FPCR system register (floating point configuration register) is used
// for system register unit tests because it is readable and writable from EL0
// (userspace) and can be modified from within the test program without causing
// the rest of the system to become unstable.
uint64_t get_fpcr(void)
{
uint64_t value;
asm volatile(
"mrs %[v], fpcr\n"
: [v] "=r" (value)
);
return value;
}
void set_fpcr(uint64_t value)
{
asm volatile(
"msr fpcr, %[v]\n"
: : [v] "r" (value)
);
}
namespace test_w19
{
inline uint32_t get(void) noexcept { GET_REG32_FUNC(w19) }
inline void set(uint32_t val) noexcept { SET_REG32_FUNC(w19, val) }
}
namespace test_x20
{
inline uint64_t get(void) noexcept { GET_REG64_FUNC(x20) }
inline void set(uint64_t val) noexcept { SET_REG64_FUNC(x20, val) }
}
namespace test_fpcr
{
inline uint64_t get(void) noexcept { GET_SYSREG_FUNC(fpcr) }
inline void set(uint64_t val) noexcept { SET_SYSREG_BY_VALUE_FUNC(fpcr, val) }
namespace ioe
{
inline uint64_t is_enabled() noexcept { IS_SYSREG_BIT_ENABLED_FUNC(fpcr, 8) }
inline uint64_t is_enabled(uint64_t fpcr_val) noexcept { IS_BIT_ENABLED_FUNC(fpcr_val, 8) }
inline uint64_t is_disabled() noexcept { IS_SYSREG_BIT_DISABLED_FUNC(fpcr, 8) }
inline uint64_t is_disabled(uint64_t fpcr_val) noexcept { IS_BIT_DISABLED_FUNC(fpcr_val, 8) }
inline void enable() noexcept { SET_SYSREG_BITS_BY_MASK_FUNC(fpcr, 0x100) }
inline uint64_t enable(uint64_t fpcr_val) noexcept { SET_BITS_BY_MASK_FUNC(fpcr_val, 0x100) }
inline void disable() noexcept { CLEAR_SYSREG_BITS_BY_MASK_FUNC(fpcr, 0x100) }
inline uint64_t disable(uint64_t fpcr_val) noexcept { CLEAR_BITS_BY_MASK_FUNC(fpcr_val, 0x100) }
}
namespace len
{
inline uint64_t get() noexcept { GET_SYSREG_FIELD_FUNC(fpcr, 0x70000, 16) }
inline uint64_t get(uint64_t fpcr_val) noexcept { GET_BITFIELD_FUNC(fpcr_val, 0x70000, 16) }
inline void set(uint64_t value) noexcept { SET_SYSREG_BITS_BY_VALUE_FUNC(fpcr, value, 0x70000, 16) }
inline uint64_t set(uint64_t fpcr_val, uint64_t value) noexcept { SET_BITS_BY_VALUE_FUNC(fpcr_val, value, 0x70000, 16) }
}
}
// -----------------------------------------------------------------------------
// Test Cases
// -----------------------------------------------------------------------------
TEST_CASE("GET_REG32")
{
uint32_t val;
g_w19 = 0;
GET_REG32(w19, val);
CHECK(val == 0);
g_w19 = 1;
GET_REG32(w19, val);
CHECK(val == 1);
g_w19 = 0xf00dbeef;
GET_REG32(w19, val);
CHECK(val == 0xf00dbeef);
g_w19 = 0xffffffff;
GET_REG32(w19, val);
CHECK(val == 0xffffffff);
}
TEST_CASE("GET_REG32_FUNC")
{
g_w19 = 0xf00dbeef;
uint32_t result = test_w19::get();
CHECK(result == 0xf00dbeef);
g_w19 = 0;
}
TEST_CASE("GET_REG64")
{
uint64_t val;
g_x20 = 0;
GET_REG64(x20, val);
CHECK(val == 0);
g_x20 = 1;
GET_REG64(x20, val);
CHECK(val == 1);
g_x20 = 0xdeadf00dbeefd00d;
GET_REG64(x20, val);
CHECK(val == 0xdeadf00dbeefd00d);
g_x20 = 0xffffffffffffffff;
GET_REG64(x20, val);
CHECK(val == 0xffffffffffffffff);
}
TEST_CASE("GET_REG64_FUNC")
{
g_x20 = 0xdeadf00dbeefd00d;
uint64_t result = test_x20::get();
CHECK(result == 0xdeadf00dbeefd00d);
g_x20 = 0;
}
TEST_CASE("SET_REG32")
{
uint32_t val;
SET_REG32(w19, 0);
val = g_w19;
CHECK(val == 0);
SET_REG32(w19, 1);
val = g_w19;
CHECK(val == 1);
SET_REG32(w19, 0xf00dbeef);
val = g_w19;
CHECK(val == 0xf00dbeef);
SET_REG32(w19, 0xffffffff);
val = g_w19;
CHECK(val == 0xffffffff);
}
TEST_CASE("SET_REG32_FUNC")
{
test_w19::set(0xc001d00d);
uint32_t result = g_w19;
CHECK(result == 0xc001d00d);
g_w19 = 0;
}
TEST_CASE("SET_REG64")
{
uint64_t val;
SET_REG64(x20, 0);
val = g_x20;
CHECK(val == 0);
SET_REG64(x20, 1);
val = g_x20;
CHECK(val == 1);
SET_REG64(x20, 0xdeadf00dbeefd00d);
val = g_x20;
CHECK(val == 0xdeadf00dbeefd00d);
SET_REG64(x20, 0xffffffffffffffff);
val = g_x20;
CHECK(val == 0xffffffffffffffff);
}
TEST_CASE("SET_REG64_FUNC")
{
test_x20::set(0xbadc0feecafebabe);
uint64_t result = g_x20;
CHECK(result == 0xbadc0feecafebabe);
g_x20 = 0;
}
TEST_CASE("GET_BITFIELD")
{
uint64_t fpcr_val, mask;
fpcr_val = 0;
mask = 0;
GET_BITFIELD(fpcr_val, mask, 16);
CHECK(fpcr_val == 0);
fpcr_val = 0;
mask = 1;
GET_BITFIELD(fpcr_val, mask, 0);
CHECK(fpcr_val == 0);
fpcr_val = 0;
mask = 0xffffffffffffffff;
GET_BITFIELD(fpcr_val, mask, 1);
CHECK(fpcr_val == 0);
fpcr_val = 1;
mask = 1;
GET_BITFIELD(fpcr_val, mask, 0);
CHECK(fpcr_val == 1);
fpcr_val = 0xffffffffffffffff;
mask = 1;
GET_BITFIELD(fpcr_val, mask, 0);
CHECK(fpcr_val == 1);
fpcr_val = 0xffffffffffffffff;
mask = 0x400;
GET_BITFIELD(fpcr_val, mask, 10);
CHECK(fpcr_val == 1);
fpcr_val = 0xffffffffffffffff;
mask = 0x8000000000000000;
GET_BITFIELD(fpcr_val, mask, 63);
CHECK(fpcr_val == 1);
fpcr_val = 0xffffffffffffffff;
mask = 0xf0000;
GET_BITFIELD(fpcr_val, mask, 16);
CHECK(fpcr_val == 0xf);
fpcr_val = 0x70000;
mask = 0xf0000;
GET_BITFIELD(fpcr_val, mask, 16);
CHECK(fpcr_val == 7);
fpcr_val = 0x100;
mask = 0x100;
GET_BITFIELD(fpcr_val, mask, 8);
CHECK(fpcr_val == 1);
fpcr_val = 0xffffffffffffffff;
mask = 0xffffffffffffffff;
GET_BITFIELD(fpcr_val, mask, 0);
CHECK(fpcr_val == 0xffffffffffffffff);
fpcr_val = 0xff00;
mask = 0xff00;
GET_BITFIELD(fpcr_val, mask, 0);
CHECK(fpcr_val == 0xff00);
}
TEST_CASE("GET_BITFIELD_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 0);
fpcr_val = 0x70000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 7);
fpcr_val = 0x60000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 6);
fpcr_val = 0x50000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 5);
fpcr_val = 0x40000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 4);
fpcr_val = 0x30000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 3);
fpcr_val = 0x20000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 2);
fpcr_val = 0x10000;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 1);
fpcr_val = 0xffffffffffffffff;
result = test_fpcr::len::get(fpcr_val);
CHECK(result == 7);
}
TEST_CASE("SET_BITS_BY_VALUE")
{
uint64_t fpcr_val, val, mask;
fpcr_val = 0;
val = 0;
mask = 0;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 0);
fpcr_val = 0;
val = 1;
mask = 1;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 1);
fpcr_val = 0;
val = 1;
mask = 0x2;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 1);
CHECK(fpcr_val == 0x2);
fpcr_val = 0;
val = 0xf;
mask = 0xf;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 0xf);
fpcr_val = 0;
val = 8;
mask = 0xf;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 8);
fpcr_val = 0;
val = 0xffffff;
mask = 0xffffff00;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 8);
CHECK(fpcr_val == 0xffffff00);
fpcr_val = 0;
val = 0xffffffff;
mask = 0xffffffff;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 0xffffffff);
fpcr_val = 0;
val = 0xffffffffffffffff;
mask = 0xffffffffffffffff;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 0xffffffffffffffff);
fpcr_val = 0;
val = 0xffffffffffffffff;
mask = 0xff00;
SET_BITS_BY_VALUE(fpcr_val, val, mask, 0);
CHECK(fpcr_val == 0xff00);
}
TEST_CASE("SET_BITS_BY_VALUE_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0;
result = test_fpcr::len::set(fpcr_val, 0);
CHECK(result == 0);
fpcr_val = 0;
result = test_fpcr::len::set(fpcr_val, 1);
CHECK(result == 0x10000);
fpcr_val = 0;
result = test_fpcr::len::set(fpcr_val, 7);
CHECK(result == 0x70000);
fpcr_val = 0xffffffffffffffff;
result = test_fpcr::len::set(fpcr_val, 0);
CHECK(result == 0xfffffffffff8ffff);
fpcr_val = 0xffffffffffffffff;
result = test_fpcr::len::set(fpcr_val, 7);
CHECK(result == 0xffffffffffffffff);
}
TEST_CASE("SET_BITS_BY_MASK")
{
uint64_t value, mask;
value = 0;
mask = 0;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 0);
value = 0;
mask = 1;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 1);
value = 0;
mask = 0xf;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 0xf);
value = 0;
mask = 0x500;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 0x500);
value = 0;
mask = 0xf0000;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 0xf0000);
value = 0;
mask = 0xffffffffffffffff;
SET_BITS_BY_MASK(value, mask);
CHECK(value == 0xffffffffffffffff);
}
TEST_CASE("SET_BITS_BY_MASK_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0;
result = test_fpcr::ioe::enable(fpcr_val);
CHECK(result == 0x100);
result = test_fpcr::ioe::enable(result);
CHECK(result == 0x100);
fpcr_val = 0xfffffffffffffeff;
result = test_fpcr::ioe::enable(fpcr_val);
CHECK(result == 0xffffffffffffffff);
}
TEST_CASE("CLEAR_BITS_BY_MASK")
{
uint64_t value, mask;
value = 0;
mask = 0;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0);
value = 0;
mask = 1;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0);
value = 1;
mask = 1;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0);
value = 1;
mask = 1;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0);
value = 7;
mask = 2;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 5);
value = 0xffffffffffffffff;
mask = 1;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0xfffffffffffffffe);
value = 0xffffffffffffffff;
mask = 0x00000000ff000000;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0xffffffff00ffffff);
value = 0xffffffffffffffff;
mask = 0xffffffffffffffff;
CLEAR_BITS_BY_MASK(value, mask);
CHECK(value == 0);
}
TEST_CASE("CLEAR_BITS_BY_MASK_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0;
result = test_fpcr::ioe::disable(fpcr_val);
CHECK(result == 0);
fpcr_val = 0xffffffffffffffff;
result = test_fpcr::ioe::disable(fpcr_val);
CHECK(result == 0xfffffffffffffeff);
result = test_fpcr::ioe::disable(result);
CHECK(result == 0xfffffffffffffeff);
}
TEST_CASE("IS_BIT_ENABLED")
{
uint64_t result;
g_w19 = 0;
IS_BIT_ENABLED(g_w19, result, 0);
CHECK(result == 0);
g_x20 = 0;
IS_BIT_ENABLED(g_x20, result, 0);
CHECK(result == 0);
g_w19 = 1;
IS_BIT_ENABLED(g_w19, result, 0);
CHECK(result == 1);
IS_BIT_ENABLED(g_w19, result, 1);
CHECK(result == 0);
g_x20 = 1;
IS_BIT_ENABLED(g_x20, result, 0);
CHECK(result == 1);
IS_BIT_ENABLED(g_x20, result, 1);
CHECK(result == 0);
g_w19 = 0x500;
IS_BIT_ENABLED(g_w19, result, 8);
CHECK(result == 1);
IS_BIT_ENABLED(g_w19, result, 9);
CHECK(result == 0);
IS_BIT_ENABLED(g_w19, result, 10);
CHECK(result == 1);
g_x20 = 0x500;
IS_BIT_ENABLED(g_x20, result, 8);
CHECK(result == 1);
IS_BIT_ENABLED(g_x20, result, 9);
CHECK(result == 0);
IS_BIT_ENABLED(g_x20, result, 10);
CHECK(result == 1);
g_w19 = 0xffffffff;
IS_BIT_ENABLED(g_w19, result, 0);
CHECK(result == 1);
IS_BIT_ENABLED(g_w19, result, 1);
CHECK(result == 1);
IS_BIT_ENABLED(g_w19, result, 18);
CHECK(result == 1);
IS_BIT_ENABLED(g_w19, result, 31);
CHECK(result == 1);
g_x20 = 0xffffffffffffffff;
IS_BIT_ENABLED(g_x20, result, 0);
CHECK(result == 1);
IS_BIT_ENABLED(g_x20, result, 1);
CHECK(result == 1);
IS_BIT_ENABLED(g_x20, result, 27);
CHECK(result == 1);
IS_BIT_ENABLED(g_x20, result, 63);
CHECK(result == 1);
}
TEST_CASE("IS_BIT_ENABLED_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0x100;
result = test_fpcr::ioe::is_enabled(fpcr_val);
CHECK(result == 1);
fpcr_val = 0;
result = test_fpcr::ioe::is_enabled(fpcr_val);
CHECK(result == 0);
fpcr_val = 0xfffffffffffffeff;
result = test_fpcr::ioe::is_enabled(fpcr_val);
CHECK(result == 0);
}
TEST_CASE("IS_BIT_DISABLED")
{
uint64_t result;
g_w19 = 0;
IS_BIT_DISABLED(g_w19, result, 0);
CHECK(result == 1);
g_x20 = 0;
IS_BIT_DISABLED(g_x20, result, 0);
CHECK(result == 1);
g_w19 = 1;
IS_BIT_DISABLED(g_w19, result, 0);
CHECK(result == 0);
IS_BIT_DISABLED(g_w19, result, 1);
CHECK(result == 1);
g_x20 = 1;
IS_BIT_DISABLED(g_x20, result, 0);
CHECK(result == 0);
IS_BIT_DISABLED(g_x20, result, 1);
CHECK(result == 1);
g_w19 = 0x500;
IS_BIT_DISABLED(g_w19, result, 8);
CHECK(result == 0);
IS_BIT_DISABLED(g_w19, result, 9);
CHECK(result == 1);
IS_BIT_DISABLED(g_w19, result, 10);
CHECK(result == 0);
g_x20 = 0x500;
IS_BIT_DISABLED(g_x20, result, 8);
CHECK(result == 0);
IS_BIT_DISABLED(g_x20, result, 9);
CHECK(result == 1);
IS_BIT_DISABLED(g_x20, result, 10);
CHECK(result == 0);
g_w19 = 0xffffffff;
IS_BIT_DISABLED(g_w19, result, 0);
CHECK(result == 0);
IS_BIT_DISABLED(g_w19, result, 1);
CHECK(result == 0);
IS_BIT_DISABLED(g_w19, result, 18);
CHECK(result == 0);
IS_BIT_DISABLED(g_w19, result, 31);
CHECK(result == 0);
g_x20 = 0xffffffffffffffff;
IS_BIT_DISABLED(g_x20, result, 0);
CHECK(result == 0);
IS_BIT_DISABLED(g_x20, result, 1);
CHECK(result == 0);
IS_BIT_DISABLED(g_x20, result, 27);
CHECK(result == 0);
IS_BIT_DISABLED(g_x20, result, 63);
CHECK(result == 0);
}
TEST_CASE("IS_BIT_DISABLED_FUNC")
{
uint64_t fpcr_val, result;
fpcr_val = 0x100;
result = test_fpcr::ioe::is_disabled(fpcr_val);
CHECK(result == 0);
fpcr_val = 0;
result = test_fpcr::ioe::is_disabled(fpcr_val);
CHECK(result == 1);
fpcr_val = 0xfffffffffffffeff;
result = test_fpcr::ioe::is_disabled(fpcr_val);
CHECK(result == 1);
}
TEST_CASE("GET_SYSREG")
{
uint64_t val, previous_val;
const uint64_t expected_val = 0x100;
previous_val = get_fpcr();
set_fpcr(expected_val);
GET_SYSREG(fpcr, val);
CHECK(val == expected_val);
set_fpcr(previous_val);
}
TEST_CASE("GET_SYSREG_FUNC")
{
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0x50100);
uint64_t result = test_fpcr::get();
CHECK(result == 0x50100);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("GET_SYSREG_FIELD")
{
uint64_t val, previous_val;
previous_val = get_fpcr();
// Set fpcr.ioe = '1', fpcr.len = '101', and all other bits to '0'
set_fpcr(0x50100);
// fpcr.ioe
GET_SYSREG_FIELD(fpcr, val, 0x100, 8);
CHECK(val == 1);
// fpcr.DZE
GET_SYSREG_FIELD(fpcr, val, 0x200, 9);
CHECK(val == 0);
// fpcr.res0 [7:0]
GET_SYSREG_FIELD(fpcr, val, 0xff, 0);
CHECK(val == 0);
// fpcr.len [18:16]
GET_SYSREG_FIELD(fpcr, val, 0x50000, 16);
CHECK(val == 0b101);
// fpcr.res0 [31:27]
GET_SYSREG_FIELD(fpcr, val, 0xf8000000, 27);
CHECK(val == 0);
set_fpcr(previous_val);
}
TEST_CASE("GET_SYSREG_FIELD_FUNC")
{
uint64_t result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0x100);
result = test_fpcr::len::get();
CHECK(result == 0);
set_fpcr(0x50100);
result = test_fpcr::len::get();
CHECK(result == 5);
set_fpcr(0x70000);
result = test_fpcr::len::get();
CHECK(result == 7);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("SET_SYSREG_BY_VALUE")
{
uint64_t val, previous_val;
previous_val = get_fpcr();
SET_SYSREG_BY_VALUE(fpcr, 0);
val = get_fpcr();
CHECK(val == 0);
// One valid bit on
SET_SYSREG_BY_VALUE(fpcr, 0x100);
val = get_fpcr();
CHECK(val == 0x100);
set_fpcr(previous_val);
}
TEST_CASE("SET_SYSREG_BY_VALUE_FUNC")
{
uint64_t previous_fpcr_val = get_fpcr();
test_fpcr::set(0x50100);
uint64_t result = get_fpcr();
CHECK(result == 0x50100);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("SET_SYSREG_BITS_BY_VALUE")
{
uint64_t reg_val, new_val, old_val, mask, previous_val = 0;
previous_val = get_fpcr();
// Set fpcr.ioe [8] to '1'
set_fpcr(0);
new_val = 1;
mask = 0x100;
SET_SYSREG_BITS_BY_VALUE(fpcr, new_val, old_val, mask, 8);
reg_val = get_fpcr();
CHECK(reg_val == 0x100);
// Set fpcr.len [18:16] to '101'
set_fpcr(0);
new_val = 5;
mask = 0x70000;
SET_SYSREG_BITS_BY_VALUE(fpcr, new_val, old_val, mask, 16);
reg_val = get_fpcr();
CHECK(reg_val == 0x50000);
set_fpcr(previous_val);
}
TEST_CASE("SET_SYSREG_BITS_BY_VALUE_FUNC")
{
uint64_t result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0);
test_fpcr::len::set(7);
result = get_fpcr();
CHECK(result == 0x70000);
test_fpcr::len::set(5);
result = get_fpcr();
CHECK(result == 0x50000);
test_fpcr::len::set(0);
result = get_fpcr();
CHECK(result == 0);
test_fpcr::len::set(0xffffffff);
result = get_fpcr();
CHECK(result == 0x70000);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("SET_SYSREG_BITS_BY_MASK")
{
uint64_t val, previous_val, mask;
previous_val = get_fpcr();
// Set fpcr.ioe [8]
set_fpcr(0);
mask = 0x100;
SET_SYSREG_BITS_BY_MASK(fpcr, val, mask);
val = get_fpcr();
CHECK(val == 0x100);
// Set fpcr.len [18:16]
set_fpcr(0);
mask = 0x70000;
SET_SYSREG_BITS_BY_MASK(fpcr, val, mask);
val = get_fpcr();
CHECK(val == 0x70000);
set_fpcr(previous_val);
}
TEST_CASE("SET_SYSREG_BITS_BY_MASK_FUNC")
{
uint64_t result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0);
test_fpcr::ioe::enable();
result = get_fpcr();
CHECK(result == 0x100);
test_fpcr::ioe::enable();
result = get_fpcr();
CHECK(result == 0x100);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("CLEAR_SYSREG_BITS_BY_MASK")
{
uint64_t val, previous_val, mask;
previous_val = get_fpcr();
// Clear fpcr.ioe [8]
set_fpcr(0x100);
mask = 0x100;
CLEAR_SYSREG_BITS_BY_MASK(fpcr, val, mask);
val = get_fpcr();
CHECK(val == 0);
// Clear fpcr.len [18:16]
set_fpcr(0x70000);
mask = 0x70000;
CLEAR_SYSREG_BITS_BY_MASK(fpcr, val, mask);
val = get_fpcr();
CHECK(val == 0);
set_fpcr(previous_val);
}
TEST_CASE("CLEAR_SYSREG_BITS_BY_MASK_FUNC")
{
uint64_t result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0x100);
test_fpcr::ioe::disable();
result = get_fpcr();
CHECK(result == 0);
test_fpcr::ioe::disable();
result = get_fpcr();
CHECK(result == 0);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("IS_SYSREG_BIT_ENABLED")
{
uint64_t result, previous_val;
previous_val = get_fpcr();
// Set fpcr.ioe = '1', fpcr.len = '101', and all other bits to '0'
set_fpcr(0x50100);
IS_SYSREG_BIT_ENABLED(fpcr, result, 8);
CHECK(result == 1);
IS_SYSREG_BIT_ENABLED(fpcr, result, 16);
CHECK(result == 1);
IS_SYSREG_BIT_ENABLED(fpcr, result, 18);
CHECK(result == 1);
IS_SYSREG_BIT_ENABLED(fpcr, result, 9);
CHECK(result == 0);
IS_SYSREG_BIT_ENABLED(fpcr, result, 17);
CHECK(result == 0);
}
TEST_CASE("IS_SYSREG_BIT_ENABLED_FUNC")
{
bool result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0x100);
result = test_fpcr::ioe::is_enabled();
CHECK(result == true);
set_fpcr(0);
result = test_fpcr::ioe::is_enabled();
CHECK(result == false);
set_fpcr(previous_fpcr_val);
}
TEST_CASE("IS_SYSREG_BIT_DISABLED")
{
uint64_t result, previous_val;
previous_val = get_fpcr();
// Set fpcr.ioe = '1', fpcr.len = '101', and all other bits to '0'
set_fpcr(0x50100);
IS_SYSREG_BIT_DISABLED(fpcr, result, 8);
CHECK(result == 0);
IS_SYSREG_BIT_DISABLED(fpcr, result, 16);
CHECK(result == 0);
IS_SYSREG_BIT_DISABLED(fpcr, result, 18);
CHECK(result == 0);
IS_SYSREG_BIT_DISABLED(fpcr, result, 9);
CHECK(result == 1);
IS_SYSREG_BIT_DISABLED(fpcr, result, 17);
CHECK(result == 1);
}
TEST_CASE("IS_SYSREG_BIT_DISABLED_FUNC")
{
bool result;
uint64_t previous_fpcr_val = get_fpcr();
set_fpcr(0x100);
result = test_fpcr::ioe::is_disabled();
CHECK(result == false);
set_fpcr(0);
result = test_fpcr::ioe::is_disabled();
CHECK(result == true);
set_fpcr(previous_fpcr_val);
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ahat.heapdump;
import java.util.Objects;
/**
* Used by the DiffedField class to return the result of diffing two
* collections of fields.
*/
public class DiffedFieldValue {
/**
* The name of the field.
*/
public final String name;
/**
* The type of the field.
*/
public final Type type;
/**
* The value of the field in the current heap dump.
*/
public final Value current;
/**
* The value of the field in the baseline heap dump.
*/
public final Value baseline;
/**
* Whether the field was added to, deleted from, or matched with a field in
* the baseline heap dump.
*/
public final Status status;
/**
* A status enum to indicate whether a field was added to, deleted from, or
* matched with a field in the baseline heap dump.
*/
public static enum Status {
/**
* The field exists in the current heap dump but not the baseline.
*/
ADDED,
/**
* The field exists in both the current and baseline heap dumps.
*/
MATCHED,
/**
* The field exists in the baseline heap dump but not the current.
*/
DELETED
};
/**
* Constructs a DiffedFieldValue where there are both current and baseline
* fields.
*
* @param current the current field
* @param baseline the baseline field
* @return the constructed DiffedFieldValue
*/
public static DiffedFieldValue matched(FieldValue current, FieldValue baseline) {
return new DiffedFieldValue(current.name,
current.type,
current.value,
baseline.value,
Status.MATCHED);
}
/**
* Constructs a DiffedFieldValue where there is no baseline field.
*
* @param current the current field
* @return the constructed DiffedFieldValue
*/
public static DiffedFieldValue added(FieldValue current) {
return new DiffedFieldValue(current.name, current.type, current.value, null, Status.ADDED);
}
/**
* Constructs a DiffedFieldValue where there is no current field.
*
* @param baseline the baseline field
* @return the constructed DiffedFieldValue
*/
public static DiffedFieldValue deleted(FieldValue baseline) {
return new DiffedFieldValue(baseline.name, baseline.type, null, baseline.value, Status.DELETED);
}
private DiffedFieldValue(String name, Type type, Value current, Value baseline, Status status) {
this.name = name;
this.type = type;
this.current = current;
this.baseline = baseline;
this.status = status;
}
@Override
public boolean equals(Object otherObject) {
if (otherObject instanceof DiffedFieldValue) {
DiffedFieldValue other = (DiffedFieldValue)otherObject;
return name.equals(other.name)
&& type.equals(other.type)
&& Objects.equals(current, other.current)
&& Objects.equals(baseline, other.baseline)
&& Objects.equals(status, other.status);
}
return false;
}
@Override
public String toString() {
switch (status) {
case ADDED:
return "(" + name + " " + type + " +" + current + ")";
case MATCHED:
return "(" + name + " " + type + " " + current + " " + baseline + ")";
case DELETED:
return "(" + name + " " + type + " -" + baseline + ")";
default:
// There are no other members.
throw new AssertionError("unsupported enum member");
}
}
}
|
/* apr.parse_query_string(query_string) -> parameters {{{1
*
* Parse a URL encoded string into a Lua table. On success the table with
* parameter name/value pairs is returned, otherwise nil followed by an error
* message and error code is returned.
*
* This function uses `&` and `;` as the set of tokens to delineate words, and
* will treat a word without `=` as a name/value pair with the value true.
*/
int lua_apr_parse_query_string(lua_State *L)
{
apr_status_t status;
apr_pool_t *pool;
apr_table_t *table;
const char *qs;
pool = to_pool(L);
qs = luaL_checkstring(L, 1);
table = apr_table_make(pool, DEFAULT_TABLE_SIZE);
status = apreq_parse_query_string(pool, table, qs);
if (status != APR_SUCCESS && apr_is_empty_table(table))
return push_http_error(L, status, 1);
lua_newtable(L);
apr_table_do(push_scalars, L, table, NULL);
return push_http_result(L, status, 1);
} |
<filename>src/org/python/indexer/Def.java
/**
* Copyright 2009, Google Inc. All rights reserved.
* Licensed to PSF under a Contributor Agreement.
*/
package org.python.indexer;
import org.python.indexer.ast.NName;
import org.python.indexer.ast.NNode;
import org.python.indexer.ast.NUrl;
/**
* Encapsulates information about a binding definition site.
*/
public class Def {
// Being frugal with fields here is good for memory usage.
private int start;
private int end;
private NBinding binding;
private String fileOrUrl;
private String name;
public Def(NNode node) {
this(node, null);
}
public Def(NNode node, NBinding b) {
if (node == null) {
throw new IllegalArgumentException("null 'node' param");
}
binding = b;
if (node instanceof NUrl) {
String url = ((NUrl)node).getURL();
if (url.startsWith("file://")) {
fileOrUrl = url.substring("file://".length());
} else {
fileOrUrl = url;
}
return;
}
// start/end offsets are invalid/bogus for NUrls
start = node.start();
end = node.end();
fileOrUrl = node.getFile();
if (fileOrUrl == null) {
throw new IllegalArgumentException("Non-URL nodes must have a non-null file");
}
if (node instanceof NName) {
name = ((NName)node).id;
}
}
/**
* Returns the name of the node. Only applies if the definition coincides
* with a {@link NName} node.
* @return the name, or null
*/
public String getName() {
return name;
}
/**
* Returns the file if this node is from a source file, else {@code null}.
*/
public String getFile() {
return isURL() ? null : fileOrUrl;
}
/**
* Returns the URL if this node is from a URL, else {@code null}.
*/
public String getURL() {
return isURL() ? fileOrUrl : null;
}
/**
* Returns the file if from a source file, else the URL.
*/
public String getFileOrUrl() {
return fileOrUrl;
}
/**
* Returns {@code true} if this node is from a URL.
*/
public boolean isURL() {
return fileOrUrl.startsWith("http://");
}
public boolean isModule() {
return binding != null && binding.kind == NBinding.Kind.MODULE;
}
public int start() {
return start;
}
public int end() {
return end;
}
public int length() {
return end - start;
}
public boolean isName() {
return name != null;
}
void setBinding(NBinding b) {
binding = b;
}
public NBinding getBinding() {
return binding;
}
@Override
public String toString() {
return "<Def:" + (name == null ? "" : name) +
":" + start + ":" + fileOrUrl + ">";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Def)) {
return false;
}
Def def = (Def)obj;
if (start != def.start) {
return false;
}
if (end != def.end) {
return false;
}
if (name != null) {
if (!name.equals(def.name)) {
return false;
}
} else {
if (def.name != null) {
return false;
}
}
if (fileOrUrl != null) {
if (!fileOrUrl.equals(def.fileOrUrl)) {
return false;
}
} else {
if (def.fileOrUrl != null) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return ("" + fileOrUrl + name + start + end).hashCode();
}
}
|
#include <bits/stdc++.h>
using namespace std;
int nums[100];
void swap(int i1,int i2){
int temp = nums[i1];
nums[i1] = nums[i2];
nums[i2] = temp;
}
void sort(int l) {
for (int begin = 1;begin<l;begin++){
int cur = begin;
int temp = nums[cur];
while (cur>0 && temp< nums[cur-1]){
swap(cur,cur-1);
cur--;
nums[cur] = temp;
}
}
}
int main(){
int t,n,end;
cin>>t;
for (int i = 0;i<t;i++){
cin>>n;
end = 0;
for(int j = 0;j<n;j++){
cin>>nums[j];
}
sort(n);
if (nums[0] < 0) {
cout << "NO\n";
} else{
cout << "YES\n";
if (n>=nums[n-1]+1){
end = n;
} else{
end = nums[n-1]+1;
}
cout<<end<<"\n";
for (int j = 0;j<end;j++){
cout<<j<<" ";
}
cout<<"\n";
}
}
return 0;
} |
// RemoveAllRecv close and revmove all the receivers.
func (s *Broadcaster) RemoveAllRecv() {
s.mux.Lock()
defer s.mux.Unlock()
for _, rs := range s.recvs {
close(rs)
}
s.recvs = make(map[uuid.UUID]chan processor.Event)
} |
/*
* Given DiffIterable on non-whitespace characters, convert it into DiffIterable on original texts.
*
* matched characters: matched non-space characters + all adjustment whitespaces
*/
@Nonnull
private static DiffIterable matchAdjustmentSpacesIW(@Nonnull CharOffsets chars1,
@Nonnull CharOffsets chars2,
@Nonnull CharSequence text1,
@Nonnull CharSequence text2,
@Nonnull FairDiffIterable changes) {
final List<Range> ranges = new ArrayList<Range>();
for (Range ch : changes.iterateChanges()) {
int startOffset1;
int endOffset1;
if (ch.start1 == ch.end1) {
startOffset1 = endOffset1 = expandForwardW(chars1, chars2, text1, text2, ch, true);
}
else {
startOffset1 = chars1.offsets[ch.start1];
endOffset1 = chars1.offsets[ch.end1 - 1] + 1;
}
int startOffset2;
int endOffset2;
if (ch.start2 == ch.end2) {
startOffset2 = endOffset2 = expandForwardW(chars1, chars2, text1, text2, ch, false);
}
else {
startOffset2 = chars2.offsets[ch.start2];
endOffset2 = chars2.offsets[ch.end2 - 1] + 1;
}
ranges.add(new Range(startOffset1, endOffset1, startOffset2, endOffset2));
}
return create(ranges, text1.length(), text2.length());
} |
/**
* @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code.
* Created by Dark(DarkGuardsman, Robert) on 12/30/2018.
*/
public class EntityXmasSkeletonBoss extends EntityXmasSkeleton
{
private final BossInfoServer bossInfo = (BossInfoServer)(new BossInfoServer(this.getDisplayName(), BossInfo.Color.GREEN, BossInfo.Overlay.PROGRESS)).setDarkenSky(true);
public EntityXmasSkeletonBoss(World worldIn)
{
super(worldIn);
this.setSize(0.8F, 4F);
}
@Override
protected void updateAITasks()
{
super.updateAITasks();
this.bossInfo.setPercent(this.getHealth() / this.getMaxHealth());
}
@Override
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(100);
}
@Override
public float getEyeHeight()
{
return 3.4f;
}
@Override
public void addTrackingPlayer(EntityPlayerMP player)
{
super.addTrackingPlayer(player);
this.bossInfo.addPlayer(player);
}
@Override
public void removeTrackingPlayer(EntityPlayerMP player)
{
super.removeTrackingPlayer(player);
this.bossInfo.removePlayer(player);
}
} |
/**
* To be called before commencing the deletion of a VM.
*
* @param nodeName
* The name of the VM being deleted.
* @return null if the VM is not unwanted (it may have recently been
* deleted). false if another thread is currently trying to delete
* it. true if deletion should be attempted, in which case the
* caller MUST later call {@link #unwantedSlaveNowDeleted(String)}
* or {@link #unwantedSlaveNotDeleted(String)}.
*/
public Boolean isOkToDeleteUnwantedVM(String nodeName) {
final Map.Entry<vSphereCloudSlaveTemplate, CloudProvisioningRecord> entry = findEntryForVM(nodeName);
if (entry == null) {
return null;
}
final CloudProvisioningRecord record = entry.getValue();
final Boolean thisNode = record.isCurrentlyUnwanted(nodeName);
if (thisNode == null) {
return null;
}
boolean someoneElseIsDeletingThis = thisNode.booleanValue();
boolean isOkForUsToDeleteIt = !someoneElseIsDeletingThis;
if (isOkForUsToDeleteIt) {
record.setCurrentlyUnwanted(nodeName, true);
}
return Boolean.valueOf(isOkForUsToDeleteIt);
} |
<reponame>jonfortescue/wpf
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=========================================================================*\
\*=========================================================================*/
#pragma once
/*=========================================================================*\
MIL Status Codes
\*=========================================================================*/
#define FACILITY_WGX 0x898
#define MAKE_WGXHR( sev, code )\
MAKE_HRESULT( sev, FACILITY_WGX, (code) )
#define MAKE_WGXHR_ERR( code )\
MAKE_WGXHR( 1, code )
// Non-error codes
#define WGXHR_CLIPPEDTOEMPTY MAKE_WGXHR(0, 1)
#define WGXHR_EMPTYFILL MAKE_WGXHR(0, 2)
#define WGXHR_INTERNALTEMPORARYSUCCESS MAKE_WGXHR(0, 3)
#define WGXHR_RESETSHAREDHANDLEMANAGER MAKE_WGXHR(0, 4)
// Generic error codes
#define WGXERR_GENERIC_ERROR E_FAIL
#define WGXERR_INVALIDPARAMETER E_INVALIDARG
#define WGXERR_OUTOFMEMORY E_OUTOFMEMORY
#define WGXERR_NOTIMPLEMENTED E_NOTIMPL
#define WGXERR_ABORTED E_ABORT
#define WGXERR_ACCESSDENIED E_ACCESSDENIED
#define WGXERR_VALUEOVERFLOW INTSAFE_E_ARITHMETIC_OVERFLOW
// Error codes shared with wincodecs
#define WGXERR_WRONGSTATE WINCODEC_ERR_WRONGSTATE
#define WGXERR_UNSUPPORTEDVERSION WINCODEC_ERR_UNSUPPORTEDVERSION
#define WGXERR_NOTINITIALIZED WINCODEC_ERR_NOTINITIALIZED
#define WGXERR_UNSUPPORTEDPIXELFORMAT WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT
#define WGXERR_UNSUPPORTED_OPERATION WINCODEC_ERR_UNSUPPORTEDOPERATION
#define WGXERR_PALETTEUNAVAILABLE WINCODEC_ERR_PALETTEUNAVAILABLE
// Unique MIL error codes // Value: 0x8898xxxx -200330nnnn
#define WGXERR_OBJECTBUSY MAKE_WGXHR_ERR(0x001) // 4447
#define WGXERR_INSUFFICIENTBUFFER MAKE_WGXHR_ERR(0x002) // 4446
#define WGXERR_WIN32ERROR MAKE_WGXHR_ERR(0x003) // 4445
#define WGXERR_SCANNER_FAILED MAKE_WGXHR_ERR(0x004) // 4444
#define WGXERR_SCREENACCESSDENIED MAKE_WGXHR_ERR(0x005) // 4443
#define WGXERR_DISPLAYSTATEINVALID MAKE_WGXHR_ERR(0x006) // 4442
#define WGXERR_NONINVERTIBLEMATRIX MAKE_WGXHR_ERR(0x007) // 4441
#define WGXERR_ZEROVECTOR MAKE_WGXHR_ERR(0x008) // 4440
#define WGXERR_TERMINATED MAKE_WGXHR_ERR(0x009) // 4439
#define WGXERR_BADNUMBER MAKE_WGXHR_ERR(0x00A) // 4438
#define WGXERR_UNSUPPORTEDTEXTURESIZE MAKE_WGXHR_ERR(0x00B) // 4437
// An internal error (MIL bug) occurred. On checked builds, we would assert.
#define WGXERR_INTERNALERROR MAKE_WGXHR_ERR(0x080) // 4320
// This is a presentation error that is recoverable. The caller needs
// to reattempt present.
// Known cause for this is another process calling PrintWindow on our hwnd
// when we call UpdateLayeredWindow.
#define WGXERR_NEED_REATTEMPT_PRESENT MAKE_WGXHR_ERR(0x083) // 4317
// The display format we need to render is not supported by the
// hardware device.
#define WGXERR_DISPLAYFORMATNOTSUPPORTED MAKE_WGXHR_ERR(0x084) // 4316
// A call to this method is invalid.
#define WGXERR_INVALIDCALL MAKE_WGXHR_ERR(0x085) // 4315
// Lock attempted on an already locked object.
#define WGXERR_ALREADYLOCKED MAKE_WGXHR_ERR(0x086) // 4314
// Unlock attempted on an unlocked object.
#define WGXERR_NOTLOCKED MAKE_WGXHR_ERR(0x087) // 4313
// No algorithm avaliable to render text with this device
#define WGXERR_DEVICECANNOTRENDERTEXT MAKE_WGXHR_ERR(0x088) // 4312
// Some glyph bitmaps, required for glyph run rendering, are not
// contained in glyph cache.
#define WGXERR_GLYPHBITMAPMISSED MAKE_WGXHR_ERR(0x089) // 4311
// Some glyph bitmaps in glyph cache are unexpectedly big.
#define WGXERR_MALFORMEDGLYPHCACHE MAKE_WGXHR_ERR(0x08A) // 4310
// Marker error for known Win32 errors that are currently being ignored
// by the compositor. This is to avoid returning S_OK when an error has occurred,
// but still unwind the stack in the correct location
#define WGXERR_GENERIC_IGNORE MAKE_WGXHR_ERR(0x08B) // 4309
// Guideline coordinates are not sorted properly or contain NaNs.
#define WGXERR_MALFORMED_GUIDELINE_DATA MAKE_WGXHR_ERR(0x08C) // 4308
// No HW rendering device is available for this operation
#define WGXERR_NO_HARDWARE_DEVICE MAKE_WGXHR_ERR(0x08D) // 4307
// There has been a presentation error that may be recoverable. The caller
// needs to recreate, rerender the entire frame, and reattempt present.
// There are two known case for this:
// 1) D3D Driver Internal error - should be investigated by DXG/IHV
// 2) D3D E_FAIL
// a) Unknown root cause - should be investigated by DXG
// b) When resizing too quickly for DWM and D3D stay in sync
#define WGXERR_NEED_RECREATE_AND_PRESENT MAKE_WGXHR_ERR(0x08E) // 4306
// The object has already been initialized
#define WGXERR_ALREADY_INITIALIZED MAKE_WGXHR_ERR(0x08F) // 4305
// The size of the object does not match the expected size
#define WGXERR_MISMATCHED_SIZE MAKE_WGXHR_ERR(0x090) // 4304
// No Redirection surface avaiable
#define WGXERR_NO_REDIRECTION_SURFACE_AVAILABLE MAKE_WGXHR_ERR(0x091) //4303
// Remoting of this content is not supported
#define WGXERR_REMOTING_NOT_SUPPORTED MAKE_WGXHR_ERR(0x092) // 4302
// Queued Presents are not being used
#define WGXERR_QUEUED_PRESENT_NOT_SUPPORTED MAKE_WGXHR_ERR(0x093) // 4301
// Queued Presents are not being used
#define WGXERR_NOT_QUEUING_PRESENTS MAKE_WGXHR_ERR(0x094) // 4300
// No redirection surface was available retry the call
#define WGXERR_NO_REDIRECTION_SURFACE_RETRY_LATER MAKE_WGXHR_ERR(0x095) // 4299
// Shader construction failed because it was too complex
#define WGXERR_TOOMANYSHADERELEMNTS MAKE_WGXHR_ERR(0x096) // 4298
// AVAILABLE MAKE_WGXHR_ERR(0x097) // 4297
// AVAILABLE MAKE_WGXHR_ERR(0x098) // 4296
// Shader compilation failed
#define WGXERR_SHADER_COMPILE_FAILED MAKE_WGXHR_ERR(0x099) // 4295
// Requested DX redirection surface size exceeded maximum texture size
#define WGXERR_MAX_TEXTURE_SIZE_EXCEEDED MAKE_WGXHR_ERR(0x09A) // 4294
// AVAILABLE MAKE_WGXHR_ERR(0x09B) // 4293
// Caps don't meet min WPF requirement for hw rendering
#define WGXERR_INSUFFICIENT_GPU_CAPS MAKE_WGXHR_ERR(0x09C) // 4292
// Composition engine errors
#define WGXERR_UCE_INVALIDPACKETHEADER MAKE_WGXHR_ERR(0x400) // 3424
#define WGXERR_UCE_UNKNOWNPACKET MAKE_WGXHR_ERR(0x401) // 3423
#define WGXERR_UCE_ILLEGALPACKET MAKE_WGXHR_ERR(0x402) // 3422
#define WGXERR_UCE_MALFORMEDPACKET MAKE_WGXHR_ERR(0x403) // 3421
#define WGXERR_UCE_ILLEGALHANDLE MAKE_WGXHR_ERR(0x404) // 3420
#define WGXERR_UCE_HANDLELOOKUPFAILED MAKE_WGXHR_ERR(0x405) // 3419
#define WGXERR_UCE_RENDERTHREADFAILURE MAKE_WGXHR_ERR(0x406) // 3418
#define WGXERR_UCE_CTXSTACKFRSTTARGETNULL MAKE_WGXHR_ERR(0x407) // 3417
#define WGXERR_UCE_CONNECTIONIDLOOKUPFAILED MAKE_WGXHR_ERR(0x408) // 3416
#define WGXERR_UCE_BLOCKSFULL MAKE_WGXHR_ERR(0x409) // 3415
#define WGXERR_UCE_MEMORYFAILURE MAKE_WGXHR_ERR(0x40A) // 3414
#define WGXERR_UCE_PACKETRECORDOUTOFRANGE MAKE_WGXHR_ERR(0x40B) // 3413
#define WGXERR_UCE_ILLEGALRECORDTYPE MAKE_WGXHR_ERR(0x40C) // 3412
#define WGXERR_UCE_OUTOFHANDLES MAKE_WGXHR_ERR(0x40D) // 3411
#define WGXERR_UCE_UNCHANGABLE_UPDATE_ATTEMPTED MAKE_WGXHR_ERR(0x40E) // 3410
#define WGXERR_UCE_NO_MULTIPLE_WORKER_THREADS MAKE_WGXHR_ERR(0x40F) // 3409
#define WGXERR_UCE_REMOTINGNOTSUPPORTED MAKE_WGXHR_ERR(0x410) // 3408
#define WGXERR_UCE_MISSINGENDCOMMAND MAKE_WGXHR_ERR(0x411) // 3407
#define WGXERR_UCE_MISSINGBEGINCOMMAND MAKE_WGXHR_ERR(0x412) // 3406
#define WGXERR_UCE_CHANNELSYNCTIMEDOUT MAKE_WGXHR_ERR(0x413) // 3405
#define WGXERR_UCE_CHANNELSYNCABANDONED MAKE_WGXHR_ERR(0x414) // 3404
#define WGXERR_UCE_UNSUPPORTEDTRANSPORTVERSION MAKE_WGXHR_ERR(0x415) // 3403
#define WGXERR_UCE_TRANSPORTUNAVAILABLE MAKE_WGXHR_ERR(0x416) // 3402
#define WGXERR_UCE_FEEDBACK_UNSUPPORTED MAKE_WGXHR_ERR(0x417) // 3401
#define WGXERR_UCE_COMMANDTRANSPORTDENIED MAKE_WGXHR_ERR(0x418) // 3400
#define WGXERR_UCE_GRAPHICSSTREAMUNAVAILABLE MAKE_WGXHR_ERR(0x419) // 3399
#define WGXERR_UCE_GRAPHICSSTREAMALREADYOPEN MAKE_WGXHR_ERR(0x420) // 3398
#define WGXERR_UCE_TRANSPORTDISCONNECTED MAKE_WGXHR_ERR(0x421) // 3397
#define WGXERR_UCE_TRANSPORTOVERLOADED MAKE_WGXHR_ERR(0x422) // 3396
#define WGXERR_UCE_PARTITION_ZOMBIED MAKE_WGXHR_ERR(0x423) // 3395
// MIL AV Specific errors
#define WGXERR_AV_NOCLOCK MAKE_WGXHR_ERR(0x500)
#define WGXERR_AV_NOMEDIATYPE MAKE_WGXHR_ERR(0x501)
#define WGXERR_AV_NOVIDEOMIXER MAKE_WGXHR_ERR(0x502)
#define WGXERR_AV_NOVIDEOPRESENTER MAKE_WGXHR_ERR(0x503)
#define WGXERR_AV_NOREADYFRAMES MAKE_WGXHR_ERR(0x504)
#define WGXERR_AV_MODULENOTLOADED MAKE_WGXHR_ERR(0x505)
#define WGXERR_AV_WMPFACTORYNOTREGISTERED MAKE_WGXHR_ERR(0x506)
#define WGXERR_AV_INVALIDWMPVERSION MAKE_WGXHR_ERR(0x507)
#define WGXERR_AV_INSUFFICIENTVIDEORESOURCES MAKE_WGXHR_ERR(0x508)
#define WGXERR_AV_VIDEOACCELERATIONNOTAVAILABLE MAKE_WGXHR_ERR(0x509)
#define WGXERR_AV_REQUESTEDTEXTURETOOBIG MAKE_WGXHR_ERR(0x50A)
#define WGXERR_AV_SEEKFAILED MAKE_WGXHR_ERR(0x50B)
#define WGXERR_AV_UNEXPECTEDWMPFAILURE MAKE_WGXHR_ERR(0x50C)
#define WGXERR_AV_MEDIAPLAYERCLOSED MAKE_WGXHR_ERR(0x50D)
#define WGXERR_AV_UNKNOWNHARDWAREERROR MAKE_WGXHR_ERR(0x50E)
// Unused 0x60E - 0x61b
// D3DImage specific errors
#define WGXERR_D3DI_INVALIDSURFACEUSAGE MAKE_WGXHR_ERR(0x800)
#define WGXERR_D3DI_INVALIDSURFACESIZE MAKE_WGXHR_ERR(0x801)
#define WGXERR_D3DI_INVALIDSURFACEPOOL MAKE_WGXHR_ERR(0x802)
#define WGXERR_D3DI_INVALIDSURFACEDEVICE MAKE_WGXHR_ERR(0x803)
#define WGXERR_D3DI_INVALIDANTIALIASINGSETTINGS MAKE_WGXHR_ERR(0x804)
|
/**
* This method checks if a line is within or crosses a Quad
* @param q1 Quadrilateral one
* @param q2 Quadrilateral two
* @return boolean true if intersection.
*/
public synchronized static boolean checkCollision(Quadrilateral q1, Quadrilateral q2) {
Circle c1 = new Circle(q1.getCenter(), q1.getLongestDist() + q2.getLongestDist());
if (!contains(c1, q2.getCenter())) {
return false;
}
Point[] p1 = q1.getPoints();
Point[] p2 = q2.getPoints();
for (int i = 0; i < p1.length; i++) {
for (int k = 0; k < p2.length; k++) {
if (checkCollision(new Line(p1[i], p1[(i + 1) % p1.length]),
new Line(p2[k], p2[(k + 1) % p1.length]))) {
return true;
}
}
}
split triangles and check
we have a method that does this, contains(QUAD, POINT) but we will
_not_ be calling this as this is mildly faster
QUAD 1
boolean check = true;
check for center and an edge being in quad
for (int i = 0; i < p1.length; i++) {
Line l = new Line(p1[i], p1[(i + 1) % p1.length]);
check = Math.signum(l.compare(q1.getCenter(), true)) ==
Math.signum(l.compare(p2[0], true)) && check;
}
point contained
if (check) {
return true;
}
again for quad 2
check = true;
check for center and an edge being in quad
for (int i = 0; i < p2.length; i++) {
Line l = new Line(p2[i], p2[(i + 1) % p2.length]);
check = Math.signum(l.compare(q2.getCenter(), true)) ==
Math.signum(l.compare(p1[0], true)) && check;
}
point contained
return check;
} |
Confirmed reservations: mental travel.
When Kosslyn, Ball, and Reiser asked subjects to scan a memorized picture, they found a strong positive linear relationship between distance scanned and reaction time. However, more recent research has suggested that this result may be as much a function of the demand characteristics of the experiment as a reflection of any structural properties of the image. To further test this possibility with complex stimuli, college subjects were either presented with Kosslyn's pictorial stimuli or verbal descriptions of same in a "nonexperiment" and were asked to predict their scanning times. The subjects were able to produce high linear correlations between scanning distance and predicted scanning time. This result is consistent with a demand characteristics explanation of the correlation between distance and reaction time that is obtained in actual image-scanning studies. |
<gh_stars>0
package com.blink.shared.common;
import com.blink.utilities.BlinkJSON;
public class File {
private String resource;
private String url;
public File() {}
public File(String resource, String url) {
this.resource = resource;
this.url = url;
}
public String getResource() {
return resource;
}
public File setResource(String resource) {
this.resource = resource;
return this;
}
public String getUrl() {
return url;
}
public File setUrl(String url) {
this.url = url;
return this;
}
@Override
public String toString() {
return BlinkJSON.toPrettyJSON(this);
}
} |
A Carolina Morning
"You boys had better shut up," said Fred, "as soon as I can see again, I'm gonna bust your heads." Dad drove us all back home. He made Fred sit in the back of the truck, for a couple of reasons. He wanted Fred to watch Brian and Eric. He knew that either one would sure enough try to heave the other over the tailgate going down Buck Creek. The other reason was because Fred's pants were still wet where Fred had wet on himself. Dad told Fred and his boys to kind of keep hunkered down, so no one would see him. With Fred's black and swollen eyes, and a large wet spot in his camouflage pants; Eric and Brian covered in welts with Brian's tongue hanging out; none of us wanted anyone to know we were kin. |
#include <bits/stdc++.h>
using namespace::std;
#define ll long long int
#define mp make_pair
#define ff first
#define ss second
const int MOD=1000000007,INF = 1e9,MAX = 2e6;
ll a[MAX],b[MAX],C[MAX];
vector < pair < ll , ll > > v;
int main()
{
std::ios_base::sync_with_stdio(false);
ll i,j,k,l,n,f;
cin>>n>>f;
for(i=0;i<n;i++)
{
cin>>a[i]>>b[i];
v.push_back(mp((min(2*a[i],b[i])-a[i]),i));
}
sort(v.rbegin(),v.rend());
ll ans = 0;
for(i=0;i<n;i++)
{
if(i<f)
ans+=(min(2*a[v[i].ss],b[v[i].ss]));
else
ans+=(min(a[v[i].ss],b[v[i].ss]));
}
cout<<ans<<endl;
}
|
Earlier today the WordPress team noticed suspicious commits to several popular plugins (AddThis, WPtouch, and W3 Total Cache) containing cleverly disguised backdoors. We determined the commits were not from the authors, rolled them back, pushed updates to the plugins, and shut down access to the plugin repository while we looked for anything else unsavory.
We’re still investigating what happened, but as a prophylactic measure we’ve decided to force-reset all passwords on WordPress.org. To use the forums, trac, or commit to a plugin or theme, you’ll need to reset your password to a new one. (Same for bbPress.org and BuddyPress.org.)
As a user, make sure to never use the same password for two different services, and we encourage you not to reset your password to be the same as your old one.
Second, if you use AddThis, WPtouch, or W3 Total Cache and there’s a possibility you could have updated in the past day, make sure to visit your updates page and upgrade each to the latest version.
Share this: Twitter
Facebook
Google
Email |
<reponame>ssavitzky/Silvermine-Resources
/*********************************************************************\
**
** View.c -- View data on the screen
**
** 880422 SS major changes: view data structure
** 880111 SS create PC version from DD
**
\*********************************************************************/
#include <stdio.h>
#include "../lib/curse.h"
#include "../lib/ibmchars.h"
#include "rd7.h"
#include "coops.h"
#include "trees.h"
#include "dirs.h"
#undef global
#define global
#include "view.h"
extern Object objInit(), objClone(), objKill();
extern Object objDoesNotImplement();
TreeViewRec rFileView, rDosFileView;
/*********************************************************************\
**
** Parameters
**
\*********************************************************************/
#define VIEWROWS 19
#define VIEWCOLS 78
#define DIRCOLS 37
#define FILECOLS (VIEWCOLS - DIRCOLS - 1)
#define DATAROW 4
#define DIRCOL 1
#define FILECOL (DIRCOLS + 2)
/* Page Layout */
int swidth = 80; /* width of the screen */
int sheight = 25; /* height of the screen */
int statusRow = 0; /* row for status display */
int menuRow = 1; /* row for menu display */
int headerRow = 3; /* row for headers */
int dataRow = 4; /* first data row */
int bottomRow = VIEWROWS+5; /* bottom row. */
/*********************************************************************\
**
** Line-Drawing Routines
**
\*********************************************************************/
static hline (win, row, width, beg, mid, end)
WINDOW *win;
int row, width;
char beg, mid, end;
{
register int i;
wmove(win, row, 0);
waddch(win, beg);
for (i = 1; ++i < width; ) waddch(win, mid);
waddch(win, end);
}
static vlines (win, row, width, height, chr)
WINDOW *win;
int row, width, height;
char chr;
{
register int i;
for (i = 0; i < height; ++i, ++row) {
wmove(win, row, 0);
waddch(win, chr);
wmove(win, row, width - 1);
waddch(win, chr);
}
}
/*********************************************************************\
**
** Generic Operations
**
\*********************************************************************/
static Object vuInit(v)
View v;
{
char ul = D_LEFT, ur = D_RIGHT, ll = D_LL, lr = D_LR;
ushort nrows = v -> view.rows;
ushort ncols = v -> view.cols;
WINDOW *box = newwin(nrows + 2, ncols + 2,
v -> view.y - 1, v -> view.x - 1);
if (v -> view.x > 1) {
ul = D_TOP;
ll = D_BOT;
}
if (v -> view.x + ncols + 2 < swidth) {
ur = D_TOP;
lr = D_BOT;
}
v -> view.box = box;
v -> view.win = subwin(box, nrows, ncols, 1, 1);
wclear(box);
hline (box, 0, ncols + 2, ul, D_HORIZ, ur);
vlines (box, 1, ncols + 2, nrows, D_VERT);
hline (box, nrows + 1, ncols + 2, ll, D_HORIZ, lr);
return ((Object) v);
}
static String vName(v)
View v;
{
return(v -> view.name);
}
static Object vOpen(v)
View v;
{
static void vLabel();
static void vRefresh();
vLabel(v, gName(v), "=\315");
vRefresh(v);
return ((Object) v);
}
static void vRefresh(v)
View v;
{
if (v -> view.do_update) gVuUpdAll(v);
if (v -> view.partner && v -> view.partner -> view.do_update)
gVuUpdAll(v -> view.partner);
if (v -> view.partner && v -> view.partner -> view.do_refresh) {
wrefresh(v -> view.partner -> view.box);
v -> view.partner -> view.do_refresh = FALSE;
}
wrefresh(v ->view.box);
v -> view.do_refresh = FALSE;
}
static void vLabel(v, s, g)
View v;
String s;
String g;
{
register WINDOW *win = v -> view.win;
register int i;
int x = win -> begx;
int y = win -> begy - 1; /* in the box */
int w = win -> maxx;
int h = win -> maxy;
win = v -> view.box;
v -> view.do_refresh = TRUE;
/*
** First char. of geometry is =, +, or - for center, left, right.
** If =, second char is padding if present.
** Find out where the window is relative to its box.
** Set position accordingly.
*/
if (!g) g = "=";
switch (*g) {
case '=':
if (g[1]) {
wmove(win, y, x);
for (i = 0; i < w; ++i) waddch(win, g[1]);
}
wmove(win, y, x + (w - strlen(s)) / 2);
break;
case '+':
wmove(win, y, x);
break;
case '-':
wmove(win, y, x + w - strlen(s));
break;
}
waddstr(win, s);
}
static void vLnUp(v)
View v;
{
gVuMvLns(v, -1);
}
static void vLnDn(v)
View v;
{
gVuMvLns(v, 1);
}
static void vPgUp(v)
View v;
{
gVuMvLns(v, 0 - v -> view.rows - v -> view.cur_row);
}
static void vPgDn(v)
View v;
{
gVuMvLns(v, 2 * v -> view.rows - v -> view.cur_row - 1);
}
static void vLast(v)
View v;
{
int n;
gVuMvLns(v, 32000);
}
/*********************************************************************\
**
** Generic Tree View Operations
**
\*********************************************************************/
static void vTreeFirst(v)
TreeView v;
{
v -> view.cur_row = 0;
v -> treeview.cur = v -> treeview.top = v -> treeview.root;
v -> view.do_refresh = TRUE;
v -> view.do_update = TRUE;
}
static void vTreeSet(v, t)
TreeView v;
Tree t;
{
v -> treeview.root = t;
gVuFirst(v);
}
static void vTreeReset(v)
TreeView v;
{
if (ISNULL(v -> treeview.root)) return;
v ->treeview.root = (Tree)NIL;
gVuFirst(v);
if (v -> view.partner)
gVuReset(v -> view.partner);
}
/*********************************************************************\
**
** Directory View
**
** Note that these keep the File View up to date in parallel.
**
\*********************************************************************/
static void vDirStat(v)
TreeView v;
{
register Dir d = ((Dir) v -> treeview.root);
register int i;
static char s[80];
sprintf(s, "\315 %s ", v -> view.name);
if (ISNULL(d)) {
sprintf(s + strlen(s), "[empty]");
} else {
sprintf(s + strlen(s), "%s %4d / %d(%ldKb) ",
gName(d), d -> dir.dcount, d -> dir.fcount,
(d -> dir.fsize + 1023) / 1024);
if (d -> dir.tcount) {
sprintf(s + strlen(s), " *%d(%ldKb)", d -> dir.tcount,
(d -> dir.tsize + 1023) / 1024);
}
}
move(statusRow,1);
addstr(s);
for (i = strlen(s) + 2; i < swidth; ++i) addch(D_HORIZ);
}
static Tree dirPrev(d)
Tree d;
{
for (d = gPred(d); NOTNULL(d) && !ISDIR(d); d = gPred(d)) ;
return (d);
}
static Tree dirNext(d)
Tree d;
{
for (d = gSucc(d); NOTNULL(d) && !ISDIR(d); d = gSucc(d)) ;
return (d);
}
static Tree nextSib(d)
Tree d;
{
for (d = gNext(d); NOTNULL(d) && !ISDIR(d); d = gNext(d)) ;
return (d);
}
static Tree nextKid(d)
Tree d;
{
for (d = gDown(d); NOTNULL(d) && !ISDIR(d); d = gNext(d)) ;
return (d);
}
static void vIndentDir(win, node)
WINDOW *win;
Tree node;
{
Tree p;
if (ISNULL(node)) return;
if (NOTNULL(p = gUp(node))) vIndentDir(win, p);
if (NOTNULL(nextSib(node))) waddstr(win, "\263 ");
else waddstr(win, " ");
}
static void vUpdDirPartner(v)
TreeView v;
{
if (NOTNULL(v -> view.partner)) {
vTreeSet(v -> view.partner, gDown(v -> treeview.cur));
gVuUpdAll(v -> view.partner);
} else {
vDirStat(v);
}
}
static void vUpdDir(v, line, node)
TreeView v;
int line;
Dir node;
{
register int i;
register Dir p;
WINDOW *win = v -> view.win;
wmove(win, line, 0);
wclrtoeol(win);
/* if line is empty, just exit */
if (ISNULL(node)) return;
/* indent according to depth */
vIndentDir(win, (p = (Dir)gUp(node)));
/*
** Decide on L vs. T for each end of the branch line
*/
if (NOTNULL(nextSib(node))) waddstr(win, "\303\304");
else if (NOTNULL(p)) waddstr(win, "\300\304");
else waddstr(win, " ");
if (NOTNULL(nextKid(node))) waddch (win, 0302);
else waddch (win, 0304);
/* if line has the cursor, set standout */
if (node == (Dir) v -> treeview.cur)
wstandout(win);
/* put out the node's name */
waddstr(win, gName(node));
/* if node is tagged, so mark it */
if (node -> dir.tcount) {
waddch(win, '*');
} else {
waddch(win, ' ');
}
/* remove standout */
wstandend(win);
}
global void vDirAll(v)
TreeView v;
{
Tree n;
int i;
v -> view.do_update = FALSE;
v -> view.do_refresh= TRUE;
wclear(v -> view.win);
if (ISNULL(v -> treeview.root)) {
wmove(v -> view.win, 0, 0);
waddstr(v -> view.win, " <no directories read>");
vTreeReset(v -> view.partner);
gVuUpdAll(v -> view.partner);
return;
}
if (v -> view.cur_row >= v -> view.rows) {
i = v -> view.cur_row = v -> view.rows - 1;
for (n = v -> treeview.top = v -> treeview.cur;
i && (n = dirPrev(n)); --i, v -> treeview.top = n) ;
v -> view.cur_row -= i;
}
if (v -> view.cur_row < 0) {
v -> view.cur_row = 0;
v -> treeview.top = v -> treeview.cur;
}
for (n = v -> treeview.top, i = 0;
NOTNULL(n) && i < v -> view.rows;
++i, n = dirNext(n)
) vUpdDir(v, i, n);
wrefresh(v -> view.win);
vUpdDirPartner(v);
}
global void vDirLine(v)
TreeView v;
{
v -> view.do_update = FALSE;
if (v -> treeview.cur) {
vUpdDir(v, v -> view.cur_row, v -> treeview.cur);
}
wrefresh(v -> view.win);
if (NOTNULL(v -> view.partner)) {
vTreeSet(v -> view.partner, gDown(v -> treeview.cur));
gVuUpdAll(v -> view.partner);
} else {
vDirStat(v);
}
}
static void vDirMvLns(v, n)
TreeView v;
int n;
{
Tree f;
int r;
int oldRow = v -> view.cur_row;
Tree oldCur = v -> treeview.cur;
if (ISNULL(v -> treeview.root)) return;
v -> view.do_refresh= TRUE;
r = oldRow;
if (n < 0)
for ( ; n && NOTNULL(f = dirPrev(v -> treeview.cur)); ++n) {
-- r;
v -> treeview.cur = f;
}
else
for ( ; n && NOTNULL(f = dirNext(v -> treeview.cur)); --n) {
++ r;
v -> treeview.cur = f;
}
v -> view.cur_row = r;
if (v -> view.do_update) { /* already refreshing */
return; /* don't bother */
} else if (r >= 0 && r < v -> view.rows) { /* on-screen */
vUpdDir(v, oldRow, oldCur);
vUpdDir(v, r, v -> treeview.cur);
vUpdDirPartner(v);
} else if (r == -1) { /* off the top */
vUpdDir(v, oldRow, oldCur);
v -> treeview.top = v -> treeview.cur;
wmove(v -> view.win, 0, 0);
winsertln(v -> view.win);
v -> view.cur_row = 0;
vUpdDir(v, 0, v -> treeview.cur);
vUpdDirPartner(v);
} else if (r == v -> view.rows) { /* off the bottom */
vUpdDir(v, oldRow, oldCur);
v -> treeview.top = dirNext(v -> treeview.top);
wmove(v -> view.win, 0, 0);
wdeleteln(v -> view.win);
v -> view.cur_row = --r;
vUpdDir(v, r, v -> treeview.cur);
vUpdDirPartner(v);
} else { /* too far: refresh */
v -> view.do_update = TRUE;
}
}
ViewClassRec crDirView = {
&crClass, /* class */ /* Object Part */
{ /* ObjectClass Part */
sizeof (ViewRec), /* instance size */
"DirView", /* class name */
&crObject, /* super */
NIL, /* method dict */
vuInit, /* initialize */
objDoesNotImplement, /* new object */
objClone, /* clone self */
objKill, /* kill self */
vOpen, /* open */
objDoesNotImplement, /* close */
vName, /* name */
}, { /* ViewClassPart */
vRefresh, /* refresh display */
vDirAll, /* update function */
vDirLine, /* update line function */
vLabel, /* label */
vDirMvLns, /* move n lines */
vLnUp, /* goes up a line */
vLnDn, /* goes down a line */
vPgUp, /* goes up a page */
vPgDn, /* goes down a page */
vTreeFirst, /* first directory */
vLast, /* last directory */
vTreeSet, /* set tree */
vTreeReset, /* reset tree to null */
},
};
TreeViewRec rDirView = {
(Class)&crDirView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"Idris", /* name */
0, 0, 0, 0, 0, /* flag word */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
DIRCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View)&rFileView, /* associated view */
},
};
TreeViewRec rDosView = {
(Class)&crDirView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"DOS", /* the name */
0, 0, 0, 0, 0, /* flag word */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
DIRCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View)&rDosFileView, /* associated view */
},
};
/*********************************************************************\
**
** File View
**
\*********************************************************************/
static void vUpdFile(v, line, node)
TreeView v;
int line;
Dir node;
{
WINDOW *win = v -> view.win;
char buf[81];
wmove(win, line, 1);
if (NOTNULL(node)) {
if (v -> view.is_active && node == (Dir) (v -> treeview.cur))
wstandout(win); /* if line has the cursor, set standout */
gHeader(node, buf, (Cardinal) v -> view.cols - 1);
waddstr(win, buf);
wstandend(win);
}
wclrtoeol(win);
}
static Tree filePrev(d)
Tree d;
{
for (d = gPrev(d); NOTNULL(d) && ISDIR(d); d = gPrev(d)) ;
return (d);
}
static Tree fileNext(d)
Tree d;
{
for (d = gNext(d); NOTNULL(d) && ISDIR(d); d = gNext(d)) ;
return (d);
}
static void vFileAll(v)
TreeView v;
{
Tree n;
int i;
v -> view.do_update = FALSE;
v -> view.do_refresh= TRUE;
wclear(v -> view.win);
if (v -> view.cur_row >= v -> view.rows) {
i = v -> view.cur_row = v -> view.rows - 1;
for (n = v -> treeview.top = v -> treeview.cur;
i && n && (n = filePrev(n)); --i, v -> treeview.top = n) ;
v -> view.cur_row -= i;
}
if (v -> view.cur_row < 0) {
v -> view.cur_row = 0;
v -> treeview.top = v -> treeview.cur;
}
for (n = v -> treeview.top, i = 0;
NOTNULL(n) && i < v -> view.rows;
n = fileNext(n)
) if (!ISDIR(n)) {vUpdFile(v, i, n); ++i;}
if (i == 0) {
wmove(v -> view.win, 0, 0);
waddstr(v -> view.win, " <no files>");
}
if (v -> view.partner) vDirStat(v -> view.partner);
wrefresh(v -> view.win);
}
static void vFileLine(v)
TreeView v;
{
v -> view.do_update = FALSE;
if (NOTNULL(v -> treeview.cur)) {
vUpdFile(v, v -> view.cur_row, v -> treeview.cur);
}
if (v -> view.partner) vDirStat(v -> view.partner);
wrefresh(v -> view.win);
}
static void vFileMvLns(v, n)
TreeView v;
int n;
{
Tree f;
int r;
int oldRow = v -> view.cur_row;
Tree oldCur = v -> treeview.cur;
if (ISNULL(v -> treeview.root)) return;
v -> view.do_refresh= TRUE;
r = oldRow;
if (n < 0)
for ( ; n && NOTNULL(f = filePrev(v -> treeview.cur)); ++n) {
-- r;
v -> treeview.cur = f;
}
else
for ( ; n && NOTNULL(f = fileNext(v -> treeview.cur)); --n) {
++ r;
v -> treeview.cur = f;
}
v -> view.cur_row = r;
if (v -> view.do_update) { /* already refreshing */
return; /* don't bother */
} else if (r >= 0 && r < v -> view.rows) { /* on-screen */
vUpdFile(v, oldRow, oldCur);
vUpdFile(v, r, v -> treeview.cur);
} else if (r == -1) { /* off the top */
vUpdFile(v, oldRow, oldCur);
v -> treeview.top = v -> treeview.cur;
wmove(v -> view.win, 0, 0);
winsertln(v -> view.win);
v -> view.cur_row = 0;
vUpdFile(v, 0, v -> treeview.cur);
} else if (r == v -> view.rows) { /* off the bottom */
vUpdFile(v, oldRow, oldCur);
v -> treeview.top = fileNext(v -> treeview.top);
wmove(v -> view.win, 0, 0);
wdeleteln(v -> view.win);
v -> view.cur_row = --r;
vUpdFile(v, r, v -> treeview.cur);
} else { /* too far: refresh */
v -> view.do_update = TRUE;
}
}
void vFileFirst (v)
TreeView v;
{
vTreeFirst(v);
for ( ;
NOTNULL(v -> treeview.cur) && ISDIR(v -> treeview.cur);
v -> treeview.cur = gNext(v -> treeview.cur)
) ;
}
ViewClassRec crFileView = {
&crClass, /* class */ /* Object Part */
{ /* ObjectClass Part */
sizeof (ViewRec), /* instance size */
"FileView", /* class name */
&crObject, /* super */
NIL, /* method dict */
vuInit, /* initialize */
objDoesNotImplement, /* new object */
objClone, /* clone self */
objKill, /* kill self */
vOpen, /* open */
objDoesNotImplement, /* close */
vName, /* name */
}, { /* ViewClassPart */
vRefresh, /* refresh display */
vFileAll, /* update function */
vFileLine, /* update line function */
vLabel, /* label */
vFileMvLns, /* move n lines */
vLnUp, /* goes up a line */
vLnDn, /* goes down a line */
vPgUp, /* goes up a page */
vPgDn, /* goes down a page */
vFileFirst, /* first file */
vLast, /* last file */
vTreeSet, /* set tree */
vTreeReset, /* reset tree to null */
},
};
TreeViewRec rFileView = {
(Class) &crFileView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"Files", /* the name */
0, 0, 0, 0, 0, /* flag word */
FILECOL, /* window X position */
DATAROW, /* window Y position */
FILECOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View)&rDirView, /* associated view */
},
};
TreeViewRec rDosFileView = {
(Class) &crFileView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"Files", /* the name */
0, 0, 0, 0, 0, /* flag word */
FILECOL, /* window X position */
DATAROW, /* window Y position */
FILECOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View)&rDosView, /* associated view */
},
};
/*********************************************************************\
**
** Text View
**
\*********************************************************************/
static void vUpdText(v, row, off)
FileView v;
int row;
long off;
{
register int r, c;
WINDOW *w = v -> view.win;
char huge *p = v -> fileview.origin + off;
char huge *lim = v -> fileview.origin + v -> fileview.limit;
/*
** Update the row
*/
wmove(w, row, 0);
for (c = 0; *p && *p != '\n' && p < lim; ++p, ++c) {
if (*p == '\t') c = (c + 8) & ~7;
if (c < v -> view.cols && *p != '\r') waddch (w, *p);
}
wclrtoeol(w);
}
static long textPrev(org, n)
char huge *org;
long n;
{
for ( ; n && org[n] != '\n'; --n) ;
if (n == 0) return(n);
for (--n; n && org[n] != '\n'; --n) ;
return (org[n] == '\n'? n + 1 : n);
}
global void vTextAll(v)
FileView v;
{
register int i, r, c;
WINDOW *w = v -> view.win;
long n;
char huge *org = v -> fileview.origin;
char huge *lim = org + v -> fileview.limit;
char huge *p;
v -> view.do_update = FALSE;
v -> view.do_refresh= TRUE;
wclear(v -> view.win);
if (v -> view.cur_row >= v -> view.rows) {
i = v -> view.cur_row = v -> view.rows - 1;
for (n = v -> fileview.top = v -> fileview.cur;
i && (n = v -> fileview.top = textPrev(org, n));
--i) ;
v -> view.cur_row -= i;
}
if (v -> view.cur_row < 0) {
v -> view.cur_row = 0;
v -> fileview.top = v -> fileview.cur;
}
for (r = 0, p = org + v -> fileview.top; r < v -> view.rows; ++r, ++p) {
wmove(w, r, 0);
for (c = 0; *p && *p != '\n' && p < lim; ++p, ++c) {
if (*p == '\t') c = (c + 8) & ~7;
if (c < v -> view.cols && *p != '\r') waddch (w, *p);
}
wclrtoeol(w);
}
}
void vTextLine(v)
FileView v;
{
vTextAll(v);
}
static void vTextMvLns(v, n)
FileView v;
int n;
{
register char huge *org = v -> fileview.origin;
register ulong lim = v -> fileview.limit;
long off = v -> fileview.cur;
int r;
int oldRow = v -> view.cur_row;
long oldCur = v -> fileview.cur;
if (ISNULL(org)) return;
v -> view.do_refresh= TRUE;
r = oldRow;
if (n >= 0) {
for (; off < lim && n; ++off)
if (org[off] == '\n') --n, ++r;
} else {
if (off > 0) --off; /* in case we're at EOL and no CR */
for ( ; off > 0 && n; --off)
if (org[off] == '\n') ++n, --r;
if (n == 0 && off > 0) {
for ( ; off > 0 && org[off] != '\n'; --off) ;
if (off > 0) ++off;
}
}
v -> view.cur_row = r;
v -> fileview.cur = off;
if (v -> view.do_update) { /* already refreshing */
return; /* don't bother */
} else if (r >= 0 && r < v -> view.rows) { /* on-screen */
vUpdText(v, r, v -> fileview.cur);
} else if (r == -1) { /* off the top */
v -> fileview.top = v -> fileview.cur;
wmove(v -> view.win, 0, 0);
winsertln(v -> view.win);
v -> view.cur_row = 0;
vUpdText(v, 0, v -> fileview.cur);
} else if (r == v -> view.rows) { /* off the bottom */
for (;
org[v -> fileview.top] != '\n';
++ v -> fileview.top) ;
++ v -> fileview.top;
wmove(v -> view.win, 0, 0);
wdeleteln(v -> view.win);
v -> view.cur_row = --r;
vUpdText(v, r, v -> fileview.cur);
} else { /* too far: refresh */
v -> view.do_update = TRUE;
}
}
int vTextFirst(v)
FileView v;
{
v -> view.do_update = TRUE;
v -> fileview.top = v -> fileview.cur = 0;
v -> view.cur_row = 0;
}
void vTextLast(v)
FileView v;
{
v -> view.do_update = TRUE;
v -> fileview.top = v -> fileview.cur = v -> fileview.limit;
v -> view.cur_row = v -> view.rows - 1;
vTextMvLns(v, - (v -> view.rows - 1));
v -> fileview.top = v -> fileview.cur;
}
static void vFileSet(v, s)
FileView v;
char huge *s;
{
v -> fileview.origin = s;
gVuFirst(v);
}
static void vFileReset(v)
FileView v;
{
v -> fileview.origin = NULL;
gVuFirst(v);
}
/*
** The following line up and down operations also apply to HelpView.
** They take into account the fact that the current line is not
** highlighted.
*/
void vTextLnUp(v)
View v;
{
gVuMvLns(v, - (v -> view.cur_row + 1));
}
void vTextLnDn(v)
View v;
{
gVuMvLns(v, v -> view.rows - v -> view.cur_row);
}
ViewClassRec crTextView = {
&crClass, /* class */ /* Object Part */
{ /* ObjectClass Part */
sizeof (ViewRec), /* instance size */
"TextView", /* class name */
&crObject, /* super */
NIL, /* method dict */
vuInit, /* initialize */
objDoesNotImplement, /* new object */
objClone, /* clone self */
objKill, /* kill self */
vOpen, /* open */
objDoesNotImplement, /* close */
vName, /* name */
}, { /* ViewClassPart */
vRefresh, /* refresh display */
vTextAll, /* update function */
vTextLine, /* update line function */
vLabel, /* label */
vTextMvLns, /* move n lines */
vTextLnUp, /* goes up a line */
vTextLnDn, /* goes down a line */
vPgUp, /* goes up a page */
vPgDn, /* goes down a page */
vTextFirst, /* first directory */
vTextLast, /* last directory */
vFileSet, /* set tree */
vFileReset, /* reset tree to null */
},
};
static char pathbuf[256];
FileViewRec rTextView = {
(Class) &crTextView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
pathbuf, /* the name (replaced by filename) */
0, 0, 0, 0, 0, /* flag word */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
VIEWCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View) NIL, /* associated view */
},
};
/*********************************************************************\
**
** Binary View
**
\*********************************************************************/
static char *hexdigits = "0123456789abcdef";
static void vUpdBin(v, row)
FileView v;
int row; /* row 0 is first DATA row, actually row 1 of screen */
{
register int c;
WINDOW *w = v -> view.win;
ulong adr = v -> fileview.top + row * 16; /* address origin in file */
ulong lim = v -> fileview.limit; /* address limit */
char huge *p = v -> fileview.origin + adr; /* first char. of row */
wmove(w, row + 1, 0);
if (adr >= lim) {
wclrtoeol(w);
return;
}
wprintf(w, "%8lx: ", adr);
for (c = 0; c < 16; ++c) {
register ushort d = p[c] & 255;
if (adr + c < lim) {
waddch(w, hexdigits[d >> 4]);
waddch(w, hexdigits[d & 15]);
} else {
waddch(w, ' ');
waddch(w, ' ');
}
waddch(w, ' ');
}
waddch(w, ' ');
for (c = 0; c < 16; ++c) {
register int cc = p[c] & 255;
if (adr + c < lim) {
waddch(w, cc >= ' ' && cc < 0x7f ? cc : '.');
} else {
waddch(w, ' ');
}
}
wclrtoeol(w);
}
global void vBinAll(v)
FileView v;
{
register int r;
WINDOW *w = v -> view.win;
v -> view.do_update = FALSE;
v -> view.do_refresh= TRUE;
wmove(w, 0, 0);
wclrtoeol(w);
for (r = 0; r < 16; ++r) {
vUpdBin(v, r);
}
wmove(w, r + 1, 0);
wclrtobot(w);
}
void vBinLine(v)
FileView v;
{
vBinAll(v);
}
void vBinMvLns(v, n)
FileView v;
int n;
{
long off = v -> fileview.top + (long) n * 16L;
v -> view.do_refresh= TRUE;
if (off < 0L) {
n -= off / 16L;
off = 0L;
}
if (off > (v -> fileview.limit & 0xffffff00L)) {
vBinLast(v); return;
} else
v -> fileview.top = off;
/*
** Now figure out whether a simple scroll will do it.
*/
if (n == 1 && !v -> view.do_update) { /* down 1 */
wmove(v -> view.win, 1, 0);
wdeleteln(v -> view.win);
vUpdBin(v, 15);
} else if (n == -1 && !v -> view.do_update) { /* up 1 */
wmove(v -> view.win, 1, 0);
winsertln(v -> view.win);
vUpdBin(v, 0);
} else {
v -> view.do_update = TRUE;
}
}
static void vBinPgUp(v)
View v;
{
gVuMvLns(v, -16);
}
static void vBinPgDn(v)
View v;
{
gVuMvLns(v, 16);
}
int vBinFirst(v)
FileView v;
{
v -> view.do_update = TRUE;
v -> view.do_refresh= TRUE;
v -> fileview.top = 0;
}
int vBinLast(v)
FileView v;
{
v -> view.do_update = TRUE;
v -> view.do_refresh= TRUE;
if (v -> fileview.limit > 256L) {
v -> fileview.top = (v -> fileview.limit) & 0xffffff00L;
} else {
v -> fileview.top = 0;
}
}
ViewClassRec crBinaryView = {
&crClass, /* class */ /* Object Part */
{ /* ObjectClass Part */
sizeof (ViewRec), /* instance size */
"BinaryView", /* class name */
&crObject, /* super */
NIL, /* method dict */
vuInit, /* initialize */
objDoesNotImplement, /* new object */
objClone, /* clone self */
objKill, /* kill self */
vOpen, /* open */
objDoesNotImplement, /* close */
vName, /* name */
}, { /* ViewClassPart */
vRefresh, /* refresh display */
vBinAll, /* update function */
vBinLine, /* update line function */
vLabel, /* label */
vBinMvLns, /* move n lines */
vLnUp, /* goes up a line */
vLnDn, /* goes down a line */
vBinPgUp, /* goes up a page */
vBinPgDn, /* goes down a page */
vBinFirst, /* first directory */
vBinLast, /* last directory */
vFileSet, /* set tree */
vFileReset, /* reset tree to null */
},
};
FileViewRec rBinaryView = {
(Class) &crBinaryView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
pathbuf, /* the name (replaced by filename) */
0, 0, 0, 0, 0, /* flag word */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
VIEWCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View) NIL, /* associated view */
},
};
/*********************************************************************\
**
** Help
**
\*********************************************************************/
static void vUpdHelp(v, row)
HelpView v;
int row;
{
WINDOW *w = v -> view.win;
char *p = v -> helpview.origin[v -> helpview.top + row];
register int i, r;
/*
** Update the row
*/
wmove(w, row, 0);
if (p && v -> view.is_centered)
for (i = (v -> view.cols - strlen(p))/2; i > 0; --i)
waddch(w, ' ');
if (p) waddstr(w, p);
wclrtoeol(w, row);
}
void vHelpAll(v)
HelpView v;
{
WINDOW *win = v -> view.win;
char **hmsg;
register int i, r;
v -> view.do_update = FALSE;
v -> view.do_refresh= TRUE;
wclear(v -> view.win);
if (v -> view.cur_row >= v -> view.rows) {
v -> view.cur_row = v -> view.rows - 1;
if (v -> view.cur_row > v -> helpview.cur)
v -> view.cur_row = v -> helpview.cur;
}
if (v -> view.cur_row < 0) {
v -> view.cur_row = 0;
v -> helpview.top = v -> helpview.cur;
}
v -> helpview.top = v -> helpview.cur - v -> view.cur_row;
hmsg = v -> helpview.origin + v -> helpview.top;
for (r = 0; *hmsg && r < v -> view.rows; ++hmsg, ++r) {
wmove(win, r, 0);
if (v -> view.is_centered)
for (i = (v -> view.cols - strlen(*hmsg))/2; i > 0; --i)
waddch(win, ' ');
waddstr(win, *hmsg);
wclrtoeol(win, r);
}
if (r < v -> view.rows) {
wmove(win, r, 0);
wclrtobot(win);
}
}
void vHelpLine(v)
HelpView v;
{
if (ISNULL(v -> view.partner))
vHelpAll(v);
else {
vDirStat(v -> view.partner);
}
}
void vHelpMvLns(v, n)
HelpView v;
int n;
{
register char **org = v -> helpview.origin;
register char **cp;
register int i;
long off = v -> helpview.cur;
int r;
int oldRow = v -> view.cur_row;
long oldCur = v -> helpview.cur;
v -> view.do_refresh= TRUE;
r = oldRow;
if (n >= 0) {
for (; org[off] && n; --n, ++off, ++r) ;
} else {
if (off < -n) {
off = 0;
r = 0;
} else {
off += n;
r += n;
}
}
v -> view.cur_row = r;
v -> helpview.cur = off;
if (v -> view.do_update) { /* already refreshing */
return; /* don't bother */
} else if (r >= 0 && r < v -> view.rows) { /* on-screen */
vUpdHelp(v, r);
} else if (r == -1) { /* off the top */
v -> helpview.top = v -> helpview.cur;
wmove(v -> view.win, 0, 0);
winsertln(v -> view.win);
v -> view.cur_row = 0;
vUpdHelp(v, 0);
} else if (r == v -> view.rows) { /* off the bottom */
++ v -> helpview.top;
wmove(v -> view.win, 0, 0);
wdeleteln(v -> view.win);
v -> view.cur_row = --r;
vUpdHelp(v, r);
} else { /* too far: refresh */
v -> view.do_update = TRUE;
}
}
static void vHelpFirst(v)
HelpView v;
{
v -> helpview.cur = v -> helpview.top = 0;
v -> view.cur_row = 0;
v -> view.do_update = TRUE;
}
static void vHelpSet(v, s)
HelpView v;
char **s;
{
v -> helpview.origin = s;
gVuFirst(v);
}
static void vHelpReset(v)
HelpView v;
{
v -> helpview.origin = NULL;
gVuFirst(v);
}
ViewClassRec crHelpView = {
&crClass, /* class */ /* Object Part */
{ /* ObjectClass Part */
sizeof (ViewRec), /* instance size */
"HelpView", /* class name */
&crObject, /* super */
NIL, /* method dict */
vuInit, /* initialize */
objDoesNotImplement, /* new object */
objClone, /* clone self */
objKill, /* kill self */
vOpen, /* open */
objDoesNotImplement, /* close */
vName, /* name */
}, { /* ViewClassPart */
vRefresh, /* refresh display */
vHelpAll, /* update function */
vHelpLine, /* update line function */
vLabel, /* label */
vHelpMvLns, /* move n lines */
vTextLnUp, /* goes up a line */
vTextLnDn, /* goes down a line */
vPgUp, /* goes up a page */
vPgDn, /* goes down a page */
vHelpFirst, /* first directory */
vLast, /* last directory */
vHelpSet, /* set tree */
vHelpReset, /* reset tree to null */
},
};
HelpViewRec rHelpView = {
(Class) &crHelpView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"Help", /* the name */
0, 0, 0, 0, 0, /* flag word */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
VIEWCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View) NIL, /* associated view */
},
};
HelpViewRec rInitView = {
(Class) &crHelpView,
{
(WINDOW *) 0L, /* the window the view is in */
(WINDOW *) 0L, /* the window for the box around it */
"", /* the name */
TRUE, 0, 0, 0, 0, /* flag word -- is_centered = TRUE */
DIRCOL, /* window X position */
DATAROW, /* window Y position */
VIEWCOLS, /* window width */
VIEWROWS, /* window height */
0, /* cursor row */
0, /* cursor column */
(View) NIL, /* associated view */
},
};
/*********************************************************************\
**
** Global Variables
**
\*********************************************************************/
global TreeView oDirView = &rDirView; /* Idris Directory list */
global TreeView oDosView = &rDosView; /* DOS Directory list */
global TreeView oFileView = &rFileView; /* File list */
global TreeView oDosFileView= &rDosFileView; /* File list */
global FileView oTextView = &rTextView; /* File text */
global FileView oBinaryView = &rBinaryView; /* File text */
global HelpView oHelpView = &rHelpView; /* Help Text */
global HelpView oInitView = &rInitView; /* Initial Text */
/* global MenuView oMenuView = &rMenuView; */ /* Menus */
global ViewClass clDirView = &crDirView;
global ViewClass clFileView = &crFileView;
global ViewClass clTextView = &crTextView;
global ViewClass clBinaryView = &crBinaryView;
global ViewClass clHelpViewC = &crHelpView;
/*********************************************************************\
**
** Initialization
**
\*********************************************************************/
global void vInit(imsg)
char **imsg;
{
extern WINDOW *MenuWindow;
/* === At this point we ought to extract screen parameters from stdscr */
/*
** Initialize the views.
*/
gInit(oDirView);
gInit(oDosView);
gInit(oFileView);
gInit(oDosFileView);
gInit(oTextView);
gInit(oHelpView);
gInit(oInitView);
oBinaryView -> view.win = oTextView -> view.win;
oBinaryView -> view.box = oTextView -> view.box;
gVuSet (oInitView, imsg);
MenuWindow = newwin(2, swidth - 4, menuRow, 2);
hline (stdscr, 0, swidth, D_UL, D_HORIZ, D_UR);
vlines (stdscr, 1, swidth, headerRow - 1, D_VERT);
}
|
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Package nrlambda adds support for AWS Lambda.
//
// Use this package to instrument your AWS Lambda handler function. Data is
// sent to CloudWatch when the Lambda is invoked. CloudWatch collects Lambda
// log data and sends it to a New Relic log-ingestion Lambda. The log-ingestion
// Lambda sends that data to us.
//
// Monitoring AWS Lambda requires several steps shown here:
// https://docs.newrelic.com/docs/serverless-function-monitoring/aws-lambda-monitoring/get-started/enable-new-relic-monitoring-aws-lambda
//
// Example: https://github.com/Easypay/go-agent/tree/master/v3/integrations/nrlambda/example/main.go
package nrlambda
import (
"context"
"io"
"net/http"
"os"
"sync"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/lambda/handlertrace"
"github.com/aws/aws-lambda-go/lambdacontext"
"github.com/Easypay/go-agent/v3/internal"
"github.com/Easypay/go-agent/v3/internal/integrationsupport"
"github.com/Easypay/go-agent/v3/newrelic"
)
type response struct {
header http.Header
code int
}
var _ http.ResponseWriter = &response{}
func (r *response) Header() http.Header { return r.header }
func (r *response) Write([]byte) (int, error) { return 0, nil }
func (r *response) WriteHeader(int) {}
func requestEvent(ctx context.Context, event interface{}) {
txn := newrelic.FromContext(ctx)
if nil == txn {
return
}
if sourceARN := getEventSourceARN(event); "" != sourceARN {
integrationsupport.AddAgentAttribute(txn, newrelic.AttributeAWSLambdaEventSourceARN, sourceARN, nil)
}
if request := eventWebRequest(event); nil != request {
txn.SetWebRequest(*request)
}
}
func responseEvent(ctx context.Context, event interface{}) {
txn := newrelic.FromContext(ctx)
if nil == txn {
return
}
if rw := eventResponse(event); nil != rw && 0 != rw.code {
w := txn.SetWebResponse(rw)
w.WriteHeader(rw.code)
}
}
type writerProvider interface {
borrowWriter(needsWriter func(writer io.Writer))
}
type defaultWriterProvider struct {
}
const telemetryNamedPipe = "/tmp/newrelic-telemetry"
func (wp *defaultWriterProvider) borrowWriter(needsWriter func(io.Writer)) {
// If the telemetry named pipe exists and is writable, use it instead of stdout
pipeFile, err := os.OpenFile(telemetryNamedPipe, os.O_WRONLY, 0)
if err != nil {
needsWriter(os.Stdout)
return
}
//We need to close the pipe; of course we don't close stdout
defer pipeFile.Close()
needsWriter(pipeFile)
}
func (h *wrappedHandler) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
var arn, requestID string
if lctx, ok := lambdacontext.FromContext(ctx); ok {
arn = lctx.InvokedFunctionArn
requestID = lctx.AwsRequestID
}
defer h.hasWriter.borrowWriter(func(writer io.Writer) {
internal.ServerlessWrite(h.app.Private, arn, writer)
})
txn := h.app.StartTransaction(h.functionName)
defer txn.End()
integrationsupport.AddAgentAttribute(txn, newrelic.AttributeAWSRequestID, requestID, nil)
integrationsupport.AddAgentAttribute(txn, newrelic.AttributeAWSLambdaARN, arn, nil)
h.firstTransaction.Do(func() {
integrationsupport.AddAgentAttribute(txn, newrelic.AttributeAWSLambdaColdStart, "", true)
})
ctx = newrelic.NewContext(ctx, txn)
ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{
RequestEvent: requestEvent,
ResponseEvent: responseEvent,
})
response, err := h.original.Invoke(ctx, payload)
if nil != err {
txn.NoticeError(err)
}
return response, err
}
type wrappedHandler struct {
original lambda.Handler
app *newrelic.Application
// functionName is copied from lambdacontext.FunctionName for
// deterministic tests that don't depend on environment variables.
functionName string
// Although we are told that each Lambda will only handle one request at
// a time, we use a synchronization primitive to determine if this is
// the first transaction for defensiveness in case of future changes.
firstTransaction sync.Once
// hasWriter is used to log the data JSON at the end of each transaction.
// The writerProvider manages the lifecycle of the file handle being written
// to, similar to the Loan pattern. This field exists mostly for testing.
hasWriter writerProvider
}
// WrapHandler wraps the provided handler and returns a new handler with
// instrumentation. StartHandler should generally be used in place of
// WrapHandler: this function is exposed for consumers who are chaining
// middlewares.
func WrapHandler(handler lambda.Handler, app *newrelic.Application) lambda.Handler {
if nil == app {
return handler
}
return &wrappedHandler{
original: handler,
app: app,
functionName: lambdacontext.FunctionName,
hasWriter: &defaultWriterProvider{},
}
}
// Wrap wraps the provided handler and returns a new handler with
// instrumentation. Start should generally be used in place of Wrap.
func Wrap(handler interface{}, app *newrelic.Application) lambda.Handler {
return WrapHandler(lambda.NewHandler(handler), app)
}
// Start should be used in place of lambda.Start. Replace:
//
// lambda.Start(myhandler)
//
// With:
//
// nrlambda.Start(myhandler, app)
//
func Start(handler interface{}, app *newrelic.Application) {
lambda.StartHandler(Wrap(handler, app))
}
// StartHandler should be used in place of lambda.StartHandler. Replace:
//
// lambda.StartHandler(myhandler)
//
// With:
//
// nrlambda.StartHandler(myhandler, app)
//
func StartHandler(handler lambda.Handler, app *newrelic.Application) {
lambda.StartHandler(WrapHandler(handler, app))
}
|
package com.coltsoftware.liquidsledgehammer.collections;
import org.junit.Before;
import com.coltsoftware.liquidsledgehammer.MoneyTestBase;
import com.coltsoftware.liquidsledgehammer.model.FinancialTransaction;
import com.coltsoftware.liquidsledgehammer.model.Money;
import com.coltsoftware.liquidsledgehammer.model.NullFinancialTransactionSourceInformation;
import com.coltsoftware.liquidsledgehammer.model.SubTransaction;
import com.coltsoftware.liquidsledgehammer.subtransactions.SubTransactionFactory;
public abstract class FinancialTreeNodeTestsBase extends MoneyTestBase {
protected FinancialTreeNode root;
protected SubTransaction createSubTransaction(Money value) {
FinancialTransaction transaction = new FinancialTransaction.Builder()
.source(NullFinancialTransactionSourceInformation.INSTANCE)
.date(2014, 5, 1).value(value).build();
return new SubTransactionFactory().getSubTransactions(transaction)
.iterator().next();
}
@Before
public void setup() {
root = new FinancialTreeNode();
}
}
|
import java.util.*;
public class CodeForces {
public static long max(long a,long b,long c)
{
if(a>=b&&a>=c) {return a;}
if(b>=c&&b>=a) {return b;}
else {
return c;
}
}
public static long min(long a,long b,long c)
{
if(a<=b&&a<=c) {return a;}
if(b<=c&&b<=a) {return b;}
else {
return c;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int i;
int l[]=new int[n];
int r[]=new int[n];
for(i=0;i<n;i++) {
l[i]=sc.nextInt();
r[i]=sc.nextInt();
}
int arr[]=new int[m+1];
int j;
for(i=0;i<n;i++) {
for(j=l[i];j<=r[i];j++) {
arr[j]=20;
}
}
LinkedList<Integer> list=new LinkedList<>();
int count=0;
for(i=1;i<=m;i++) {
if(arr[i]==0) {
count++;
list.add(i);
}
}
Iterator<Integer> k=list.listIterator();
System.out.println(count);
while(k.hasNext()) {
System.out.print((int)k.next()+" ");
}
}
}
|
/**
* To get resultSet from database for Concept Class.
*
* calls oracle stored procedure
* "{call SBREXT_CDE_CURATOR_PKG.SEARCH_CONCEPT(InString, ContName, ASLName, OracleTypes.CURSOR)}"
* loop through the ResultSet and add them to bean which is added to the vector to return
* @param data
*
*/
public void doConceptSearch(ConceptForm data)
{
ResultSet rs = null;
CallableStatement cstmt = null;
Database db = new Database();
try
{
UtilService util = data.getUtil();
if (data.getCurationServlet().getConn() != null)
{
logger.info("ConceptAction - doConceptSearch 1 calling SBREXT.SBREXT_CDE_CURATOR_PKG.SEARCH_CON ...");
db.trace(data.getCurationServlet().getConn());
cstmt = data.getCurationServlet().getConn().prepareCall("{call SBREXT.SBREXT_CDE_CURATOR_PKG.SEARCH_CON(?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(6, OracleTypes.CURSOR);
cstmt.setString(1, util.parsedStringSingleQuoteOracle(data.getSearchTerm()));
cstmt.setString(2, getStatusValues(data.getASLNameList(), data));
cstmt.setString(3, getContextValue(data.getContextName()));
cstmt.setString(4, data.getConID());
cstmt.setString(5, data.getConIDSEQ());
cstmt.setString(7, data.getDecIDseq());
cstmt.setString(8, data.getVdIDseq());
cstmt.setString(9, data.getSearchDefn());
cstmt.execute();
rs = (ResultSet) cstmt.getObject(6);
if(rs!=null)
{
EVS_UserBean eUser = data.getEvsUser();
String sAction = data.getACAction();
Vector<EVS_Bean> vList = new Vector<EVS_Bean>();
while(rs.next())
{
EVS_Bean conBean = new EVS_Bean();
String sConName = util.removeNewLineChar(rs.getString("long_name"));
conBean.setCONCEPT_NAME(sConName);
conBean.setLONG_NAME(sConName);
String sDef = util.removeNewLineChar(rs.getString("preferred_definition"));
conBean.setPREFERRED_DEFINITION(sDef);
conBean.setCONTE_IDSEQ(rs.getString("conte_idseq"));
conBean.setASL_NAME(rs.getString("asl_name"));
conBean.setIDSEQ(rs.getString("con_idseq"));
conBean.setEVS_DEF_SOURCE(rs.getString("definition_source"));
String sVocab = rs.getString("origin");
if (sAction.equals("searchForCreate"))
conBean.setEVS_DATABASE("caDSR");
else
conBean.setEVS_DATABASE(sVocab);
conBean.setcaDSR_COMPONENT("Concept Class");
String selVocab = conBean.getVocabAttr(eUser, sVocab, EVSSearch.VOCAB_DBORIGIN, EVSSearch.VOCAB_NAME);
if (selVocab.equals(EVSSearch.META_VALUE))
conBean.setEVS_ORIGIN(sVocab);
else conBean.setEVS_ORIGIN(selVocab);
conBean.setID(rs.getString("con_ID"));
String rsV = rs.getString("version");
if (rsV == null)
rsV = "";
if (rsV.indexOf('.') >= 0)
conBean.setVERSION(rsV);
else
conBean.setVERSION(rsV + ".0");
conBean.setCONTEXT_NAME(rs.getString("context"));
conBean.setDEC_USING("");
String sPref = util.removeNewLineChar(rs.getString("preferred_name"));
conBean.setCONCEPT_IDENTIFIER(sPref);
conBean.setNCI_CC_TYPE(rs.getString("evs_source"));
if (data.getRequest() != null)
conBean.markNVPConcept(conBean, data.getRequest().getSession());
vList.addElement(conBean);
}
data.setConceptList(vList);
}
}
}
catch(Exception e)
{
logger.error("ERROR - doconceptSearch for other : ", e);
data.setStatusMsg("Error : Unable to do concept search." + e.toString());
data.setActionStatus(ConceptForm.ACTION_STATUS_FAIL);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
db.show();
logger.debug("ConceptAction - doConceptSearch 1 done");
}
} |
def update_contact(self, data):
return self._put('contacts/edit-properties', data=data) |
Local Decode and Update for Big Data Compression
This paper investigates data compression that simultaneously allows local decoding and local update. The main result is a universal compression scheme for memoryless sources with the following features. The rate can be made arbitrarily close to the entropy of the underlying source, contiguous fragments of the source can be recovered or updated by probing or modifying a number of codeword bits that is on average linear in the size of the fragment, and the overall encoding and decoding complexity is quasilinear in the blocklength of the source. In particular, the local decoding or update of a single message symbol can be performed by probing or modifying on average a constant number of codeword bits. This latter part improves over previous best known results for which local decodability or update efficiency grows logarithmically with blocklength. |
// GetKnativeService returns a knative Service that matches the given function
func (c *Collection) GetKnativeService(filter func(*serving.Service) bool) *serving.Service {
var retValue *serving.Service
c.VisitKnativeService(func(re *serving.Service) {
if filter(re) {
retValue = re
}
})
return retValue
} |
Testing growth hormone deficiency in adults.
Growth hormone deficiency (GHD) in adults is a recognized syndrome which is defined biochemically within an appropriate clinical context. Clinically, patients investigated for GHD should include those with signs and symptoms of hypothalamic-pituitary disease, those who have received cranial irradiation or tumor treatment and those with traumatic brain injury or subarachnoid hemorrhage. Patients with three or more pituitary hormone deficiencies and an IGF-I below the reference range do not require provocative testing. The other patients need a provocative test of GH secretory reserve for the diagnosis of GHD. Insulin tolerance test is considered the diagnostic test of choice, however, the GH-releasing hormone (GHRH)+arginine, the GHRH+growth hormone-releasing peptide and the glucagon stimulation tests are well validated alternative tests in adults. Cutoffs differ across tests and results may be influenced by gender, age, body mass index, and the assay reference preparation. |
/**
* Class Product implements a product.
*/
public abstract class Product implements Serializable {
/** Serial number for serialization. */
private static final long serialVersionUID = 2021212121091006L;
/** Product attributes. */
private boolean _isSimpleProduct;
private double _maxPrice;
private double _minPrice;
private String _id;
private List<Batch> _batches = new ArrayList<>();
private List<Partner> _observers = new ArrayList<>();
/**
* Product constructor.
*
* @param id Product's id.
*/
Product(String id) {
_id = id;
}
boolean getIsSimpleProduct() {
return _isSimpleProduct;
}
void setIsSimpleProduct() {
_isSimpleProduct = true;
}
/** Returns product max price. */
double getMaxPrice() {
return _maxPrice;
}
/** Returns product min price. */
double getMinPrice() {
return _minPrice;
}
/** Returns product id. */
String getID() {
return _id;
}
/** Returns list of batches that have the product. */
List<Batch> getBatches() {
return _batches;
}
List<Batch> getBatchesOrderedbyPrice() {
List<Batch> orderedBatches = new ArrayList<>(getBatches());
Collections.sort(orderedBatches, Batch.getComparatorBatchByPrice());
return orderedBatches;
}
List<Partner> getObservers() {
return _observers;
}
/** Returns product total stock. */
int getTotalStock() {
int stock = 0;
for (Batch b : _batches) {
stock += b.getQuantity();
}
return stock;
}
/**
* Sets max price.
*
* @param price
*/
void setMaxPrice(double price) {
if (price > _maxPrice)
_maxPrice = price;
}
void setMinPrice(double price) {
if (price < _minPrice)
_minPrice = price;
}
void updateMinPrice() {
if (hasBatches())
_minPrice = getBatchesOrderedbyPrice().get(0).getPrice();
}
/**
* Sets product id.
*
* @param id
*/
void setID(String id) {
_id = id;
}
/**
* Adds a batch to product.
*
* @param batch
*/
void addBatch(Batch batch) {
_batches.add(batch);
}
void removeBatch(Batch batch) {
_batches.remove(batch);
}
/** Returns true if product has batches. */
boolean hasBatches() {
return !_batches.isEmpty();
}
boolean addObserver(Partner partner) {
return _observers.add(partner);
}
boolean removeObserver(Partner partner) {
return _observers.remove(partner);
}
void notifyObservers(Notification notification) {
for (Observer obs : _observers) {
obs.addNotification(notification);
}
}
/** Override of equals method. Now represented by id. */
@Override
public boolean equals(Object obj) {
return obj instanceof Product && _id.equals(((Product) obj).getID());
}
/** Override of hashCode method. Returns id hash code. */
@Override
public int hashCode() {
return _id.hashCode();
}
/** Returns product comparator by ids. */
public static Comparator<Product> getComparatorById() {
return COMPARE_BY_ID;
}
/** Product comparator. */
private static final Comparator<Product> COMPARE_BY_ID = new Comparator<Product>() {
/**
* Compares two products by their ids.
*
* @param p1
* @param p2
*/
@Override
public int compare(Product p1, Product p2) {
return p1.getID().compareToIgnoreCase(p2.getID());
}
};
} |
<gh_stars>0
from intcode import IntCode
def RunSpringScript(program: str, script: str) -> int:
inputValues = list(map(ord, script))
springDroid = IntCode(program, inputValues, False)
springDroid.run()
for c in springDroid.output_values:
if c < 128:
print(chr(c), end="")
else:
return c
return -1
if __name__ == '__main__':
springScript = """\
NOT A J
NOT J J
AND B J
AND C J
NOT J J
AND D J
WALK
"""
springScript2 = """\
NOT C J
AND H J
NOT B T
OR T J
NOT A T
OR T J
AND D J
RUN
"""
with open('21.txt', 'r') as infile:
program = infile.read().strip()
part1 = RunSpringScript(program, springScript)
print(f"Part 1: {part1}")
part2 = RunSpringScript(program, springScript2)
print(f"Part 2: {part2}")
|
/*FinishTask
if task process finished, invoke this method
*/
func (p *MySQLPicTaskPipe) FinishTask(task *TaskFinished) error {
_, err := p.db.Exec(`
UPDATE pic_task_queue
SET status = 2, nodetype = ?, nodenum = ?, ext = ?
WHERE id = ?;
`, task.NodeType, task.NodeName, task.MIMEInfo, task.Key)
return err
} |
Impacts of pm2.5 on respiratory system among traffic policemen.
BACKGROUND
Malaysian traffic policemen are constantly exposed to unhealthy air in the outdoor environment, which results in various health problems. This study investigates the relationship of the personal exposure level to PM2.5 and lung functions in traffic policemen in Kuala Lumpur and Johor Bahru.
METHODS
A pulmonary function test using a spirometer was carried out to measure the lung function of the traffic policemen. The personal exposure level to PM2.5 was measured using a pump with a PVC filter and 5.0μm pore size. A questionnaire requesting the background data, such as age, height, and weight, was also used for testing lung function abnormalities.
RESULTS
The PM2.5 personal exposure level was found to be significantly related to lung function (predicted FEV1 and predicted FVC) at p-value < 0.05.
CONCLUSIONS
Traffic policemen are mainly exposed to physical hazards from traffic pollutants emitted by vehicles, such as fine particles and particulate matter. The findings of this study indicate that there is a trend of lung function deterioration among traffic policemen. These baseline data can serve as a reference for the top management of traffic police to aid in the development of occupational safety and health guidelines for police officers, as the traffic police are not covered by the Occupational Safety and Health Act (OSHA, Act 514 1994). |
import java.util.Arrays;
import java.util.Scanner;
public class StringProblem {
final static int INF = 99999999;
static int[][] map = new int[30][30];
public static void main(String[] args) {
//System.setIn(new FileInputStream("in.test"));
//System.setOut(new PrintStream(new FileOutputStream("out.test")));
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
char[] s = cin.next().toCharArray();
char[] t = cin.next().toCharArray();
int n = cin.nextInt();
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
map[i][j] = INF;
}
map[i][i] = 0;
}
for (int i = 0; i < n; i++) {
int a = cin.next().charAt(0) - 'a';
int b = cin.next().charAt(0) - 'a';
int w = cin.nextInt();
if (w < map[a][b]) {
map[a][b] = w;
}
}
warshall();
if (s.length != t.length) {
System.out.println("-1");
continue;
}
int ans = 0;
boolean has = true;
for (int i = 0; i < t.length; i++) {
if (s[i] != t[i]) {
int a = s[i] - 'a';
int b = t[i] - 'a';
int c1 = map[a][b];
int c2 = map[b][a];
int c3 = toChar(a, b);
if (c3 == INF) {
has = false;
break;
}
int min = Math.min(map[a][c3] + map[b][c3], Math.min(c1, c2));
ans += min;
if (c1 == min) {
s[i] = t[i];
}
else if (c2 == min) {
t[i] = s[i];
}
else {
s[i] = (char) (c3 + 'a');
}
}
}
if (has) {
System.out.println(ans);
System.out.println(s);
}
else {
System.out.println("-1");
}
}
}
static int toChar(int a, int b) {
int c = INF;
int minCost = INF;
for (int i = 0; i < 30; i++) {
if (map[a][i] + map[b][i] < minCost) {
minCost = map[a][i] + map[b][i];
c = i;
}
}
return c;
}
static void warshall() {
int n = 30;
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] > map[i][k] + map[k][j]) {
map[i][j] = map[i][k] + map[k][j];
}
}
}
}
}
}
|
/**
* @Author Mara
* @CreateDate 2018-7-8
* @Description
* @License Apache License Version 2.0
*/
public class DirectorySynchronizeController extends BaseBatchFileController {
protected boolean isConditional, startHandle;
protected String lastFileName;
protected FileSynchronizeAttributes copyAttr;
protected String strFailedCopy, strCreatedSuccessfully, strCopySuccessfully, strFailedDelete;
protected String strDeleteSuccessfully, strFileDeleteSuccessfully, strDirectoryDeleteSuccessfully;
@FXML
protected ControlPathInput targetPathInputController;
@FXML
protected VBox dirsBox, conditionsBox, condBox, logsBox;
@FXML
protected TextField notCopyInput;
@FXML
protected ToggleGroup copyGroup;
@FXML
protected CheckBox copySubdirCheck, copyEmptyCheck, copyNewCheck, copyHiddenCheck, copyReadonlyCheck;
@FXML
protected CheckBox copyExistedCheck, copyModifiedCheck, deleteNonExistedCheck, notCopyCheck, copyAttrCheck, continueCheck,
deleteSourceCheck;
@FXML
protected DatePicker modifyAfterInput;
public DirectorySynchronizeController() {
baseTitle = Languages.message("DirectorySynchronize");
}
@Override
public void initControls() {
try {
super.initControls();
deleteNonExistedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean oldValue, Boolean newValue) {
if (deleteNonExistedCheck.isSelected()) {
deleteNonExistedCheck.setStyle("-fx-text-fill: #961c1c; -fx-font-weight: bolder;");
} else {
deleteNonExistedCheck.setStyle(null);
}
}
});
deleteSourceCheck.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean oldValue, Boolean newValue) {
if (deleteSourceCheck.isSelected()) {
deleteSourceCheck.setStyle("-fx-text-fill: #961c1c; -fx-font-weight: bolder;");
} else {
deleteSourceCheck.setStyle(null);
}
}
});
ValidationTools.setNonnegativeValidation(maxLinesinput);
checkIsConditional();
copyGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
checkIsConditional();
}
});
targetPathInputController.baseName(baseName).init();
startButton.disableProperty().bind(
Bindings.isEmpty(sourcePathInput.textProperty())
.or(sourcePathInput.styleProperty().isEqualTo(UserConfig.badStyle()))
.or(targetPathInputController.valid.not())
);
operationBarController.openTargetButton.disableProperty().bind(
startButton.disableProperty()
);
} catch (Exception e) {
MyBoxLog.debug(e.toString());
}
}
protected boolean initAttributes() {
try {
sourcePath = new File(sourcePathInput.getText());
if (!paused || lastFileName == null) {
copyAttr = new FileSynchronizeAttributes();
copyAttr.setContinueWhenError(continueCheck.isSelected());
copyAttr.setCopyAttrinutes(copyAttrCheck.isSelected());
copyAttr.setCopyEmpty(copyEmptyCheck.isSelected());
copyAttr.setConditionalCopy(isConditional);
copyAttr.setCopyExisted(copyExistedCheck.isSelected());
copyAttr.setCopyHidden(copyHiddenCheck.isSelected());
copyAttr.setCopyNew(copyNewCheck.isSelected());
copyAttr.setCopySubdir(copySubdirCheck.isSelected());
copyAttr.setNotCopySome(notCopyCheck.isSelected());
copyAttr.setOnlyCopyReadonly(copyReadonlyCheck.isSelected());
List<String> notCopy = new ArrayList<>();
if (copyAttr.isNotCopySome() && notCopyInput.getText() != null && !notCopyInput.getText().trim().isEmpty()) {
String[] s = notCopyInput.getText().split(",");
notCopy.addAll(Arrays.asList(s));
}
copyAttr.setNotCopyNames(notCopy);
copyAttr.setOnlyCopyModified(copyModifiedCheck.isSelected());
copyAttr.setModifyAfter(0);
if (copyAttr.isOnlyCopyModified() && modifyAfterInput.getValue() != null) {
copyAttr.setModifyAfter(DateTools.localDate2Date(modifyAfterInput.getValue()).getTime());
}
copyAttr.setDeleteNotExisteds(deleteNonExistedCheck.isSelected());
if (!copyAttr.isCopyNew() && !copyAttr.isCopyExisted() && !copyAttr.isCopySubdir()) {
alertInformation(Languages.message("NothingCopy"));
return false;
}
// In case that the source path itself is in blacklist
if (copyAttr.isNotCopySome()) {
List<String> keys = copyAttr.getNotCopyNames();
String srcName = sourcePath.getName();
for (String key : keys) {
if (srcName.contains(key)) {
alertInformation(Languages.message("NothingCopy"));
return false;
}
}
}
targetPath = targetPathInputController.file;
if (!targetPath.exists()) {
targetPath.mkdirs();
updateLogs(strCreatedSuccessfully + targetPath.getAbsolutePath(), true);
}
targetPath.setWritable(true);
targetPath.setExecutable(true);
initLogs();
logsTextArea.setText(Languages.message("SourcePath") + ": " + sourcePathInput.getText() + "\n");
logsTextArea.appendText(Languages.message("TargetPath") + ": " + targetPath.getAbsolutePath() + "\n");
strFailedCopy = Languages.message("FailedCopy") + ": ";
strCreatedSuccessfully = Languages.message("CreatedSuccessfully") + ": ";
strCopySuccessfully = Languages.message("CopySuccessfully") + ": ";
strDeleteSuccessfully = Languages.message("DeletedSuccessfully") + ": ";
strFailedDelete = Languages.message("FailedDelete") + ": ";
strFileDeleteSuccessfully = Languages.message("FileDeletedSuccessfully") + ": ";
strDirectoryDeleteSuccessfully = Languages.message("DirectoryDeletedSuccessfully") + ": ";
startHandle = true;
lastFileName = null;
} else {
startHandle = false;
updateLogs(Languages.message("LastHanldedFile") + " " + lastFileName, true);
}
processStartTime = new Date();
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
@FXML
@Override
public void startAction() {
try {
if (!initAttributes()) {
return;
}
updateInterface("Started");
synchronized (this) {
if (task != null && !task.isQuit()) {
return;
}
task = new SingletonTask<Void>(this) {
@Override
protected boolean handle() {
boolean done = false;
if (copyAttr.isConditionalCopy()) {
paused = false;
done = conditionalCopy(sourcePath, targetPath);
} else {
if (!paused && targetPath.exists()) {
updateLogs(Languages.message("ClearingTarget"), true);
if (clearDir(targetPath, false)) {
updateLogs(Languages.message("TargetCleared"), true);
} else if (!copyAttr.isContinueWhenError()) {
updateLogs(Languages.message("FailClearTarget"), true);
return false;
}
}
paused = false;
done = copyWholeDirectory(sourcePath, targetPath);
}
if (!done || task == null || task.isCancelled()) {
return false;
}
if (deleteSourceCheck.isSelected()) {
done = FileDeleteTools.deleteDir(sourcePath);
updateLogs(Languages.message("SourcePathCleared"), true);
}
return done;
}
@Override
protected void whenSucceeded() {
updateInterface("Done");
}
@Override
protected void cancelled() {
super.cancelled();
updateInterface("Canceled");
}
@Override
protected void failed() {
super.failed();
updateInterface("Failed");
}
};
start(task, false);
}
} catch (Exception e) {
updateInterface("Failed");
MyBoxLog.error(e.toString());
}
}
@Override
public void updateInterface(final String newStatus) {
currentStatus = newStatus;
Platform.runLater(new Runnable() {
@Override
public void run() {
if (paused) {
updateLogs(Languages.message("Paused"), true);
} else {
updateLogs(Languages.message(newStatus), true);
}
switch (newStatus) {
case "Started":
operationBarController.statusLabel.setText(Languages.message("Handling...") + " "
+ Languages.message("StartTime")
+ ": " + DateTools.datetimeToString(processStartTime));
StyleTools.setNameIcon(startButton, Languages.message("Stop"), "iconStop.png");
startButton.applyCss();
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
cancelProcess(event);
}
});
operationBarController.pauseButton.setVisible(true);
operationBarController.pauseButton.setDisable(false);
StyleTools.setNameIcon(operationBarController.pauseButton, Languages.message("Pause"), "iconPause.png");
operationBarController.pauseButton.applyCss();
operationBarController.pauseButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
pauseProcess(event);
}
});
operationBarController.progressBar.setProgress(-1);
disableControls(true);
break;
case "Done":
default:
if (paused) {
StyleTools.setNameIcon(startButton, Languages.message("Stop"), "iconStop.png");
startButton.applyCss();
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
cancelProcess(event);
}
});
operationBarController.pauseButton.setVisible(true);
operationBarController.pauseButton.setDisable(false);
StyleTools.setNameIcon(operationBarController.pauseButton, Languages.message("Start"), "iconStart.png");
operationBarController.pauseButton.applyCss();
operationBarController.pauseButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
startAction();
}
});
disableControls(true);
} else {
StyleTools.setNameIcon(startButton, Languages.message("Start"), "iconStart.png");
startButton.applyCss();
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
startAction();
}
});
operationBarController.pauseButton.setVisible(false);
operationBarController.pauseButton.setDisable(true);
operationBarController.progressBar.setProgress(1);
disableControls(false);
}
donePost();
}
}
});
}
@Override
public void disableControls(boolean disable) {
paraBox.setDisable(disable);
batchTabPane.getSelectionModel().select(logsTab);
}
@Override
public void showCost() {
if (operationBarController.statusLabel == null) {
return;
}
long cost = new Date().getTime() - processStartTime.getTime();
double avg = 0;
if (copyAttr.getCopiedFilesNumber() != 0) {
avg = DoubleTools.scale3((double) cost / copyAttr.getCopiedFilesNumber());
}
String s;
if (paused) {
s = Languages.message("Paused");
} else {
s = Languages.message(currentStatus);
}
s += ". " + Languages.message("HandledFiles") + ": " + copyAttr.getCopiedFilesNumber() + " "
+ Languages.message("Cost") + ": " + DateTools.datetimeMsDuration(new Date(), processStartTime) + ". "
+ Languages.message("Average") + ": " + avg + " " + Languages.message("SecondsPerItem") + ". "
+ Languages.message("StartTime") + ": " + DateTools.datetimeToString(processStartTime) + ", "
+ Languages.message("EndTime") + ": " + DateTools.datetimeToString(new Date());
operationBarController.statusLabel.setText(s);
}
@Override
public void donePost() {
showCost();
updateLogs(Languages.message("StartTime") + ": " + DateTools.datetimeToString(processStartTime) + " "
+ Languages.message("Cost") + ": " + DateTools.datetimeMsDuration(new Date(), processStartTime), false, true);
updateLogs(Languages.message("TotalCheckedFiles") + ": " + copyAttr.getTotalFilesNumber() + " "
+ Languages.message("TotalCheckedDirectories") + ": " + copyAttr.getTotalDirectoriesNumber() + " "
+ Languages.message("TotalCheckedSize") + ": " + FileTools.showFileSize(copyAttr.getTotalSize()), false, true);
updateLogs(Languages.message("TotalCopiedFiles") + ": " + copyAttr.getCopiedFilesNumber() + " "
+ Languages.message("TotalCopiedDirectories") + ": " + copyAttr.getCopiedDirectoriesNumber() + " "
+ Languages.message("TotalCopiedSize") + ": " + FileTools.showFileSize(copyAttr.getCopiedSize()), false, true);
if (copyAttr.isConditionalCopy() && copyAttr.isDeleteNotExisteds()) {
updateLogs(Languages.message("TotalDeletedFiles") + ": " + copyAttr.getDeletedFiles() + " "
+ Languages.message("TotalDeletedDirectories") + ": " + copyAttr.getDeletedDirectories() + " "
+ Languages.message("TotalDeletedSize") + ": " + FileTools.showFileSize(copyAttr.getDeletedSize()), false, true);
}
if (operationBarController.miaoCheck.isSelected()) {
SoundTools.miao3();
}
if (operationBarController.openCheck.isSelected()) {
openTarget(null);
}
}
@FXML
@Override
public void openTarget(ActionEvent event) {
try {
browseURI(targetPathInputController.file.toURI());
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
@Override
public double countAverageTime(long cost) {
double avg = 0;
if (copyAttr.getCopiedFilesNumber() != 0) {
avg = DoubleTools.scale3((double) cost / copyAttr.getCopiedFilesNumber());
}
return avg;
}
protected void checkIsConditional() {
RadioButton sort = (RadioButton) copyGroup.getSelectedToggle();
if (!Languages.message("CopyConditionally").equals(sort.getText())) {
condBox.setDisable(true);
isConditional = false;
} else {
condBox.setDisable(false);
isConditional = true;
}
}
protected boolean conditionalCopy(File sourcePath, File targetPath) {
try {
if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) {
return false;
}
if (copyAttr.isDeleteNotExisteds()
&& !deleteNonExisted(sourcePath, targetPath) && !copyAttr.isContinueWhenError()) {
return false;
}
File[] files = sourcePath.listFiles();
if (files == null) {
return false;
}
String srcFileName;
long len;
for (File srcFile : files) {
if (task == null || task.isCancelled()) {
return false;
}
srcFileName = srcFile.getAbsolutePath();
len = srcFile.length();
if (!startHandle) {
if (lastFileName.equals(srcFileName)) {
startHandle = true;
updateLogs(Languages.message("ReachFile") + " " + lastFileName, true);
}
if (srcFile.isFile()) {
continue;
}
} else {
if (srcFile.isFile()) {
copyAttr.setTotalFilesNumber(copyAttr.getTotalFilesNumber() + 1);
} else if (srcFile.isDirectory()) {
copyAttr.setTotalDirectoriesNumber(copyAttr.getTotalDirectoriesNumber() + 1);
}
copyAttr.setTotalSize(copyAttr.getTotalSize() + srcFile.length());
}
if (srcFile.isHidden() && !copyAttr.isCopyHidden()) {
continue;
}
if (srcFile.canWrite() && copyAttr.isOnlyCopyReadonly()) {
continue;
}
if (copyAttr.isNotCopySome()) {
List<String> blacks = copyAttr.getNotCopyNames();
String srcName = srcFile.getName();
boolean black = false;
for (String b : blacks) {
if (srcName.contains(b)) {
black = true;
break;
}
}
if (black) {
continue;
}
}
File tFile = new File(targetPath + File.separator + srcFile.getName());
if (srcFile.isFile()) {
if (copyAttr.isOnlyCopyModified()) {
if (srcFile.lastModified() <= copyAttr.getModifyAfter()) {
continue;
}
}
if (tFile.exists()) {
if (!copyAttr.isCopyExisted()) {
continue;
}
if (copyAttr.isOnlyCopyModified()) {
if (srcFile.lastModified() <= tFile.lastModified()) {
continue;
}
}
} else if (!copyAttr.isCopyNew()) {
continue;
}
if (copyFile(srcFile, tFile)) {
copyAttr.setCopiedFilesNumber(copyAttr.getCopiedFilesNumber() + 1);
copyAttr.setCopiedSize(copyAttr.getCopiedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getCopiedFilesNumber() + " " + strCopySuccessfully
+ srcFileName + " -> " + tFile.getAbsolutePath());
}
lastFileName = srcFileName;
} else if (!copyAttr.isContinueWhenError()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedCopy + srcFileName + " -> " + tFile.getAbsolutePath());
}
return false;
}
} else if (srcFile.isDirectory() && copyAttr.isCopySubdir()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(Languages.message("HandlingDirectory") + " " + srcFileName, true);
}
if (srcFile.listFiles() == null && !copyAttr.isCopyEmpty()) {
continue;
}
if (startHandle && !tFile.exists()) {
tFile.mkdirs();
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strCreatedSuccessfully + tFile.getAbsolutePath());
}
}
if (conditionalCopy(srcFile, tFile)) {
if (startHandle) {
copyAttr.setCopiedDirectoriesNumber(copyAttr.getCopiedDirectoriesNumber() + 1);
copyAttr.setCopiedSize(copyAttr.getCopiedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getCopiedDirectoriesNumber() + " " + strCopySuccessfully
+ srcFileName + " -> " + tFile.getAbsolutePath());
}
}
} else if (!copyAttr.isContinueWhenError()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedCopy + srcFile.getAbsolutePath() + " -> " + tFile.getAbsolutePath());
}
return false;
}
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
updateLogs(strFailedCopy + sourcePath.getAbsolutePath() + "\n" + e.toString());
return false;
}
}
protected boolean copyWholeDirectory(File sourcePath, File targetPath) {
try {
if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) {
return false;
}
File[] files = sourcePath.listFiles();
if (files == null) {
return false;
}
String srcFileName;
long len;
for (File srcFile : files) {
if (task == null || task.isCancelled()) {
return false;
}
srcFileName = srcFile.getAbsolutePath();
len = srcFile.length();
if (!startHandle) {
if (lastFileName.equals(srcFileName)) {
startHandle = true;
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(Languages.message("ReachFile") + " " + lastFileName, true);
}
}
if (srcFile.isFile()) {
continue;
}
} else {
if (srcFile.isFile()) {
copyAttr.setTotalFilesNumber(copyAttr.getTotalFilesNumber() + 1);
} else if (srcFile.isDirectory()) {
copyAttr.setTotalDirectoriesNumber(copyAttr.getTotalDirectoriesNumber() + 1);
}
copyAttr.setTotalSize(copyAttr.getTotalSize() + srcFile.length());
}
File tFile = new File(targetPath + File.separator + srcFile.getName());
if (srcFile.isFile()) {
if (copyFile(srcFile, tFile)) {
copyAttr.setCopiedFilesNumber(copyAttr.getCopiedFilesNumber() + 1);
copyAttr.setCopiedSize(copyAttr.getCopiedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getCopiedFilesNumber() + " " + strCopySuccessfully
+ srcFileName + " -> " + tFile.getAbsolutePath());
}
lastFileName = srcFileName;
} else if (!copyAttr.isContinueWhenError()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedCopy + srcFileName + " -> " + tFile.getAbsolutePath());
}
return false;
}
} else if (srcFile.isDirectory()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(Languages.message("HandlingDirectory") + " " + srcFileName, true);
}
if (startHandle) {
tFile.mkdirs();
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strCreatedSuccessfully + tFile.getAbsolutePath());
}
}
if (copyWholeDirectory(srcFile, tFile)) {
if (startHandle) {
copyAttr.setCopiedDirectoriesNumber(copyAttr.getCopiedDirectoriesNumber() + 1);
copyAttr.setCopiedSize(copyAttr.getCopiedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getCopiedDirectoriesNumber() + " " + strCopySuccessfully
+ srcFileName + " -> " + tFile.getAbsolutePath());
}
}
} else if (!copyAttr.isContinueWhenError()) {
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedCopy + srcFile.getAbsolutePath() + " -> " + tFile.getAbsolutePath());
}
return false;
}
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
updateLogs(strFailedCopy + sourcePath.getAbsolutePath() + "\n" + e.toString());
return false;
}
}
// clearDir can not be paused to avoid logic messed.
protected boolean clearDir(File dir, boolean record) {
File[] files = dir.listFiles();
if (files == null) {
return true;
}
for (File file : files) {
long len = file.length();
String filename = file.getAbsolutePath();
if (file.isDirectory()) {
if (clearDir(file, record)) {
try {
FileDeleteTools.delete(file);
if (record) {
copyAttr.setDeletedDirectories(copyAttr.getDeletedDirectories() + 1);
copyAttr.setDeletedSize(copyAttr.getDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getDeletedDirectories() + " " + strDirectoryDeleteSuccessfully + filename);
}
}
} catch (Exception e) {
if (record) {
copyAttr.setFailedDeletedDirectories(copyAttr.getFailedDeletedDirectories() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
updateLogs(strFailedDelete + filename);
}
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
} else {
if (record) {
copyAttr.setFailedDeletedDirectories(copyAttr.getFailedDeletedDirectories() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedDelete + filename);
}
}
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
}
try {
FileDeleteTools.delete(file);
if (record) {
copyAttr.setDeletedFiles(copyAttr.getDeletedFiles() + 1);
copyAttr.setDeletedSize(copyAttr.getDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(copyAttr.getDeletedFiles() + " " + strFileDeleteSuccessfully + filename);
}
}
} catch (Exception e) {
if (record) {
copyAttr.setFailedDeletedFiles(copyAttr.getFailedDeletedFiles() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
updateLogs(strFailedDelete + filename);
}
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
}
return true; // When return true, it is not necessary that the dir is cleared.
}
protected boolean copyFile(File sourceFile, File targetFile) {
try {
if (task == null || task.isCancelled()
|| sourceFile == null || !sourceFile.exists() || !sourceFile.isFile()) {
return false;
}
if (!targetFile.exists()) {
if (copyAttr.isCopyAttrinutes()) {
Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()),
StandardCopyOption.COPY_ATTRIBUTES);
} else {
Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()));
}
} else if (!copyAttr.isCanReplace() || targetFile.isDirectory()) {
return false;
} else if (copyAttr.isCopyAttrinutes()) {
Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
} else {
Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()),
StandardCopyOption.REPLACE_EXISTING);
}
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
protected boolean deleteNonExisted(File sourcePath, File targetPath) {
if (!copyAttr.isDeleteNotExisteds() || !targetPath.isDirectory()) {
return true;
}
File[] files = targetPath.listFiles();
if (files == null) {
return true;
}
for (File tFile : files) {
if (task == null || task.isCancelled()) {
return false;
}
File srcFile = new File(sourcePath + File.separator + tFile.getName());
if (srcFile.exists()) {
continue;
}
long len = tFile.length();
String filename = tFile.getAbsolutePath();
if (tFile.isDirectory()) {
if (clearDir(tFile, true)) {
try {
FileDeleteTools.delete(tFile);
copyAttr.setDeletedDirectories(copyAttr.getDeletedDirectories() + 1);
copyAttr.setDeletedSize(copyAttr.getDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strDirectoryDeleteSuccessfully + filename);
}
} catch (Exception e) {
copyAttr.setFailedDeletedDirectories(copyAttr.getFailedDeletedDirectories() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedDelete + filename);
}
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
} else {
copyAttr.setFailedDeletedDirectories(copyAttr.getFailedDeletedDirectories() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFailedDelete + filename);
}
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
} else {
try {
FileDeleteTools.delete(tFile);
copyAttr.setDeletedFiles(copyAttr.getDeletedFiles() + 1);
copyAttr.setDeletedSize(copyAttr.getDeletedSize() + len);
if (verboseCheck == null || verboseCheck.isSelected()) {
updateLogs(strFileDeleteSuccessfully + filename);
}
} catch (Exception e) {
copyAttr.setFailedDeletedFiles(copyAttr.getFailedDeletedFiles() + 1);
copyAttr.setFailedDeletedSize(copyAttr.getFailedDeletedSize() + len);
updateLogs(strFailedDelete + filename);
if (!copyAttr.isContinueWhenError()) {
return false;
}
}
}
}
return true; // When return true, it is not necessary that all things are good.
}
} |
<gh_stars>1-10
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stackclass;
/**
*
* @author c3
*/
public class StaticStack extends AbstractStack {
int stack[];
int top;
public StaticStack(){
stack = new int[10];
top = -1;
}
public void push(int elem){
if(top == 9)
System.out.println("Stack full!! No more elements can be inserted");
else{
stack[++top] = elem;
System.out.println("Element inserted");
}
}
public void pop(){
if(top == -1){
System.out.println("No element in stack!!");
}
else{
System.out.println("Element popped : " + stack[top--]);
}
}
public void display(){
if(top == -1)
System.out.println("No element in stack");
else{
for(int i = top; i >= 0; i--)
System.out.println(stack[i]);
}
}
}
|
#ifndef art_Framework_Core_TriggerReport_h
#define art_Framework_Core_TriggerReport_h
// ====================================================================
// TriggerReport: This struct contains all the information relevant to
// reporting on the behavior of the trigger at the time of its
// creation.
// ====================================================================
#include <string>
#include <vector>
namespace art {
struct EventSummary {
int totalEvents;
int totalEventsPassed;
int totalEventsFailed;
};
struct ModuleInPathSummary {
int timesVisited;
int timesPassed;
int timesFailed;
int timesExcept;
std::string moduleLabel;
};
struct PathSummary {
int bitPosition;
int timesRun;
int timesPassed;
int timesFailed;
int timesExcept;
std::string name;
std::vector<ModuleInPathSummary> moduleInPathSummaries;
};
struct WorkerSummary {
int timesVisited;
int timesRun;
int timesPassed;
int timesFailed;
int timesExcept;
std::string moduleLabel;
};
struct TriggerReport {
EventSummary eventSummary;
std::vector<PathSummary> trigPathSummaries;
std::vector<PathSummary> endPathSummaries;
std::vector<WorkerSummary> workerSummaries;
};
} // namespace art
#endif /* art_Framework_Core_TriggerReport_h */
// Local Variables:
// mode: c++
// End:
|
/*!
* @brief This API writes the data into the auxiliary sensor
*/
uint16_t bma4_aux_write(uint8_t aux_reg_addr, uint8_t *aux_data, uint16_t len, struct bma4_dev *dev)
{
uint16_t rslt = BMA4_OK;
rslt |= bma4_null_pointer_check(dev);
if (rslt == BMA4_OK) {
if (len > 0) {
while (len--) {
rslt = bma4_write_regs(BMA4_AUX_WR_DATA_ADDR, aux_data, 1, dev);
dev->delay(BMA4_AUX_COM_DELAY);
if (rslt == BMA4_OK) {
rslt = bma4_write_regs(BMA4_AUX_WR_ADDR, &aux_reg_addr, 1, dev);
dev->delay(BMA4_AUX_COM_DELAY);
if ((rslt == BMA4_OK) && (len > 0)) {
aux_data++;
aux_reg_addr++;
}
} else {
rslt = BMA4_E_FAIL;
}
}
} else {
rslt = BMA4_E_RD_WR_LENGTH_INVALID;
}
}
return rslt;
} |
// Downloads the format part by part, with as many requests as needed
private void downloadByPart(Format format, OutputStream os, final OnYoutubeDownloadListener listener) throws IOException {
long done = 0;
int partNumber = 0;
final String pathPrefix = "&cver=" + clientVersion + "&range=";
final long contentLength = format.contentLength();
byte[] buffer = new byte[BUFFER_SIZE];
while (done < contentLength) {
long toRead = PART_LENGTH;
if (done + toRead > contentLength) {
toRead = (int) (contentLength - done);
}
partNumber++;
String partUrl = format.url() + pathPrefix
+ done + "-" + (done + toRead - 1)
+ "&rn=" + partNumber;
URL url = new URL(partUrl);
InputStream is = url.openStream();
if (listener == null) {
done += copyAndCloseInput(is, os, buffer);
} else {
done += copyAndCloseInput(is, os, buffer, done, contentLength, listener);
}
}
} |
import React from "react";
import styled from "styled-components";
export interface HeadingProps {
// The heading ID used for internal page links.
id?: string;
// The HTML heading tag.
as: "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
// The content of the heading.
children: string;
// Any unknown props.
[key: string]: any;
}
const StyledHeading = styled.h2`
a {
text-decoration: none;
}
`;
const Heading: React.FC<HeadingProps> = ({ as, id, children, ...rest }) => {
return id ? (
<StyledHeading as={as} id={id} {...rest}>
<a href={`#${id}`}>{children}</a>
</StyledHeading>
) : (
<StyledHeading as={as} {...rest} />
);
};
export default Heading;
|
def pilatus_metadata(self):
if not self.is_pilatus:
return None
return pilatus_description_metadata(self.pages[0].description) |
/**
* the following three methods are three activities that would affect parameter
* values
*
* @param stats the int array that stores values for hair, money and knowledge
*/
public static int[] haircare(int[] stats){
if(stats[1]==0){
System.out.println("You don't have any money left. Please choose another activity.");
stats = calculate(stats);
}else if(stats[1]>0){
stats[1]=stats[1]-10;
if(stats[0]<0){
stats[0]=0;
}else if(stats[0]>100){
stats[0]=100;
}else{
stats[0]=stats[0]+10;
}
System.out.println("You've bought a magic hair potion, increase 10% hair, lose 10 dollars.");
}
return stats;
} |
import en from './en'
import zh_cn from './zh-cn'
import {I18nStrings} from './I18nStrings'
export class I18n {
static get(language: string): I18nStrings {
var messages = {
en,
zh_cn
} as any
return messages[language.toLowerCase().replace(/-/g, '_')] as I18nStrings
}
}
|
import { Component, lazy } from "solid-js";
import "./App.scss";
import "./codeTheme.scss";
import "./bootstrap.scss";
import Navbar from "./components/Navbar/Navbar";
import Hero from "./components/Hero/Hero";
import BasicDropdown from "./components/ExamplesSection/BasicDropdown";
import IOSDebugger from "./components/iOSDebugger";
import Modal from "./components/ExamplesSection/Modal";
import IFrame from "./components/Examples/IFrame";
const Docs = lazy(() => import("./components/Docs/Docs"));
import Popup from "./components/ExamplesSection/Popup";
import DropdownMounted from "./components/ExamplesSection/DropdownMounted";
import DropdownOverlay from "./components/ExamplesSection/DropdownOverlay";
import Nested from "./components/ExamplesSection/Nested";
import Animation from "./components/ExamplesSection/Animations";
import NavbarEx from "./components/ExamplesSection/Navbar";
import MultipleButtons from "./components/ExamplesSection/MultipleButtons";
import Caveat from "./components/Docs/Caveat";
import Popper from "./components/ExamplesSection/Popper";
const App: Component = () => {
return (
<>
<Navbar></Navbar>
<main class="main">
<Hero />
<section>
<h2 id="examples" tabindex="-1">
Examples
</h2>
<Popup></Popup>
<BasicDropdown></BasicDropdown>
<DropdownMounted></DropdownMounted>
<DropdownOverlay></DropdownOverlay>
<Modal></Modal>
<Animation></Animation>
<NavbarEx></NavbarEx>
<Popper></Popper>
<MultipleButtons></MultipleButtons>
<Nested></Nested>
</section>
<section>
<h2 id="docs" tabindex="-1">
Docs
</h2>
<Caveat></Caveat>
<h3>Types</h3>
<Docs></Docs>
</section>
</main>
<svg>
<defs>
<linearGradient
id="dismiss-logo-a"
x1="104.71"
x2="94.151"
y1="59.781"
y2="77.909"
gradientTransform="translate(-78.46 -53.379)"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#142cb0" offset="0" />
<stop stop-color="#00bcd4" offset="1" />
</linearGradient>
</defs>
</svg>
{/* <IOSDebugger /> */}
</>
);
};
export default App;
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/planner/operator/logical_index_scan.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/planner/logical_operator.hpp"
#include "duckdb/storage/index.hpp"
namespace duckdb {
//! LogicalIndex represents an Index Scan operation
class LogicalIndexScan : public LogicalOperator {
public:
LogicalIndexScan(TableCatalogEntry &tableref, DataTable &table, Index &index, vector<column_t> column_ids,
idx_t table_index)
: LogicalOperator(LogicalOperatorType::INDEX_SCAN), tableref(tableref), table(table), index(index),
column_ids(column_ids), table_index(table_index) {
}
//! The table to scan
TableCatalogEntry &tableref;
//! The physical data table to scan
DataTable &table;
//! The index to use for the scan
Index &index;
//! The column ids to project
vector<column_t> column_ids;
//! The value for the query predicate
Value low_value;
Value high_value;
Value equal_value;
//! If the predicate is low, high or equal
bool low_index = false;
bool high_index = false;
bool equal_index = false;
//! The expression type (e.g., >, <, >=, <=)
ExpressionType low_expression_type;
ExpressionType high_expression_type;
//! The table index in the current bind context
idx_t table_index;
public:
vector<ColumnBinding> GetColumnBindings() override {
return GenerateColumnBindings(table_index, column_ids.size());
}
ColumnBinding PushdownColumnBinding(ColumnBinding &binding) override {
column_t referenced_rai = binding.column_index == COLUMN_IDENTIFIER_ROW_ID
? COLUMN_IDENTIFIER_ROW_ID
: tableref.columns[binding.column_index].join_index_oid;
auto entry = find(column_ids.begin(), column_ids.end(), referenced_rai);
if (entry != column_ids.end()) {
auto column_idx = distance(column_ids.begin(), entry);
return ColumnBinding(table_index, column_idx, referenced_rai, &tableref);
} else {
column_ids.push_back(referenced_rai);
return ColumnBinding(table_index, column_ids.size() - 1, referenced_rai, &tableref);
}
}
string ParamsToString() const override {
string result = "[" + tableref.name + "<" + std::to_string(table_index) + ">" + " (";
if (column_ids.size() > 0) {
result += StringUtil::Join(column_ids, column_ids.size(), ", ", [&](const idx_t cid) {
if (cid == COLUMN_IDENTIFIER_ROW_ID) {
return "rowid";
}
return tableref.columns[cid].name.c_str();
});
}
return result + ")]";
}
protected:
void ResolveTypes() override {
if (column_ids.size() == 0) {
types = {TypeId::INT32};
} else {
types = tableref.GetTypes(column_ids);
}
}
};
} // namespace duckdb
|
/**
* Created by nanye on 17/5/8.
*/
public class SettingsFragment extends com.dailystudio.app.fragment.SettingsFragment {
private class GetVoiceModalTask extends AsyncTask<Context, Void, VoiceModalItem[]> {
private int mStatus;
private RadioSetting<VoiceModalItem> mSetting;
private GetVoiceModalTask(RadioSetting<VoiceModalItem> radioSetting) {
mSetting = radioSetting;
}
@Override
protected VoiceModalItem[] doInBackground(Context... params) {
if (params == null || params.length <= 0) {
return null;
}
final Context context = params[0];
TextToSpeech tts = null;
synchronized (mOnInitListener) {
tts = new TextToSpeech(context,
mOnInitListener);
try {
mOnInitListener.wait();
} catch (InterruptedException e) {
Logger.warn("wait tts interrupted.");
}
}
if (mStatus != TextToSpeech.SUCCESS) {
return null;
}
Set<Voice> voices = tts.getVoices();
if (voices == null) {
return null;
}
List<VoiceModalItem> items = new ArrayList<>();
for (Voice voice: voices) {
if (voice.isNetworkConnectionRequired() == false
&& Locale.US.equals(voice.getLocale())) {
items.add(new VoiceModalItem(voice));
}
}
Collections.sort(items, mVoiceModalComapator);
tts.shutdown();
return items.toArray(new VoiceModalItem[0]);
}
@Override
protected void onPostExecute(VoiceModalItem[] items) {
super.onPostExecute(items);
if (mSetting != null
&& items != null) {
mSetting.clear();
mSetting.addItems(items);
}
}
private TextToSpeech.OnInitListener mOnInitListener = new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
mStatus = status;
synchronized (this) {
notifyAll();
}
}
};
}
private static class VoiceModalItem implements RadioSettingItem {
private Voice mVoice;
private VoiceModalItem(Voice voice) {
mVoice = voice;
}
@Override
public CharSequence getLabel() {
String name = mVoice.getName();
if (TextUtils.isEmpty(name)) {
return name;
}
String[] parts = name.split("#");
if (parts == null || parts.length < 2) {
return name;
}
return parts[1].replace("-local", "").replace("_", " ");
}
@Override
public String getId() {
return mVoice.getName();
}
@Override
public String toString() {
return getId();
}
}
@Override
protected Setting[] createSettings(Context context) {
Setting voiceOnRecv =
new SwitchSetting(context,
Constants.SETTING_VOICE_ON_RECT,
R.drawable.ic_setting_voice,
R.string.settings_voice_on_recv,
new SwitchSettingsLayoutHolder()) {
@Override
public boolean isSwitchOn(Context context) {
return AppPrefs.isVoiceOnRectEnabled(context);
}
@Override
public void setSwitchOn(Context context, boolean on) {
AppPrefs.setVoiceOnRectEnabled(context, on);
}
};
RadioSetting<VoiceModalItem> voiceModals =
new RadioSetting(context,
Constants.SETTING_VOICE_MODAL,
R.drawable.ic_setting_voice_modal,
R.string.settings_voice_modal,
new RadioSettingsLayoutHolder(),
null) {
@Override
protected String getSelectedId() {
return AppPrefs.getVoiceModal(getContext());
}
@Override
protected void setSelected(String selectedId) {
AppPrefs.setVoiceModal(getContext(), selectedId);
TextToSpeechService.reset(getContext());
TextToSpeechService.textToSpeech(getContext(),
getString(R.string.voice_sample_text));
}
};
new GetVoiceModalTask(voiceModals)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
getContext());
return new Setting[] {
voiceOnRecv,
voiceModals,
};
}
private Comparator<VoiceModalItem> mVoiceModalComapator = new Comparator<VoiceModalItem>() {
@Override
public int compare(VoiceModalItem lhs, VoiceModalItem rhs) {
return lhs.getId().compareTo(rhs.getId());
}
};
@Override
public void onPause() {
super.onPause();
TextToSpeechService.stop(getContext());
}
} |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Textures/SlateShaderResource.h"
#include "Rendering/SlateRenderer.h"
class FSlateDrawBuffer;
class FSlateUpdatableTexture;
class SWindow;
struct Rect;
/** A slate null rendering implementation */
class FSlateNullRenderer : public FSlateRenderer
{
public:
explicit FSlateNullRenderer(const TSharedRef<FSlateFontServices>& InSlateFontServices);
/** FSlateRenderer interface */
virtual bool Initialize() override;
virtual void Destroy() override;
virtual FSlateDrawBuffer& GetDrawBuffer() override;
virtual void OnWindowDestroyed( const TSharedRef<SWindow>& InWindow ) override;
virtual void RequestResize( const TSharedPtr<SWindow>& Window, uint32 NewWidth, uint32 NewHeight ) override;
virtual void CreateViewport( const TSharedRef<SWindow> Window ) override;
virtual void UpdateFullscreenState( const TSharedRef<SWindow> Window, uint32 OverrideResX, uint32 OverrideResY ) override;
virtual void RestoreSystemResolution(const TSharedRef<SWindow> InWindow) override;
virtual void DrawWindows( FSlateDrawBuffer& InWindowDrawBuffer ) override;
virtual void ReleaseDynamicResource( const FSlateBrush& InBrush ) override;
virtual void RemoveDynamicBrushResource( TSharedPtr<FSlateDynamicImageBrush> BrushToRemove ) override;
virtual FIntPoint GenerateDynamicImageResource(const FName InTextureName) override;
virtual bool GenerateDynamicImageResource( FName ResourceName, uint32 Width, uint32 Height, const TArray< uint8 >& Bytes ) override;
virtual void PrepareToTakeScreenshot(const FIntRect& Rect, TArray<FColor>* OutColorData) override;
virtual FSlateResourceHandle GetResourceHandle( const FSlateBrush& Brush ) override;
virtual FSlateUpdatableTexture* CreateUpdatableTexture(uint32 Width, uint32 Height) override;
virtual void ReleaseUpdatableTexture(FSlateUpdatableTexture* Texture) override;
virtual int32 RegisterCurrentScene(FSceneInterface* Scene) override;
virtual int32 GetCurrentSceneIndex() const override;
virtual void ClearScenes() override;
};
|
package sort
/*Insertion []int*/
func Insertion(input []int) []int {
for j := 1; j < len(input); j++ {
key := input[j]
i := j - 1
for input[i] > key {
input[i+1] = input[i]
i -= 1
if i < 0 {
break
}
}
input[i+1] = key
}
return input
}
|
<reponame>mdnu/snake
def cocktailsort(lst):
''' (list of number) -> NoneType
Modify lst to sort the items for smallest to largest.
>>> my_list = [4, 2, 5, 8, 6, 7, 3, 1]
>>> cocktailsort(my_list)
>>> my_list
[1, 2, 3, 4, 5, 6, 7, 8]
'''
top = len(lst) - 1
bottom = 0
while top > bottom:
sort_to_top(lst, bottom, top)
top = top - 1
sort_to_bottom(lst, bottom, top)
bottom += 1
def sort_to_top(lst, bottom, top):
''' (list of number, int, int) -> NoneType
Modify lst to swap the largest item in lst[bottom: top + 1] to index top.
>>> my_list = [1, 2, 4, 6, 3, 5, 7, 8]
>>> sort_to_top(my_list, 2, 5)
>>> my_list
[1, 2, 4, 5, 3, 6, 7, 8]
'''
index_of_largest = bottom
for j in range(bottom + 1, top + 1):
if lst[j] > lst[index_of_largest]:
index_of_largest = j
lst[index_of_largest], lst[top] = lst[top], lst[index_of_largest]
def sort_to_bottom(lst, bottom. top):
''' (list of number, int, int) -> NoneType
Modify lst to swap the smallest item in lst[bottom: top + 1] to index
bottom.
>>> my_list = [1, 2, 4, 5, 3, 5, 7, 8]
>>> sort_to_bottom(my_list, 2, 4)
>>> my_list
[1, 2, 3, 5, 4, 6, 7, 8]
'''
# complete the function body (4 MARKS)
index_of_smallest = bottom
for j in range(bottom + 1, top + 1):
if lst[j] < lst[index_of_smallest]:
index_of_smallest = j
lst[index_of_smallest], lst[bottom] = lst[bottom], lst[index_of_smallest]
# examine the runtime behavior (1 MARK):
# 'This algorithm does not have a different best and worst case number
# of comparisons' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.