repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
arvindrajayadav/unrest
|
CRAB/AnimationFrame.h
|
#pragma once
#include "common_header.h"
#include "AnimationEffect.h"
#include "ImageManager.h"
#include "TextManager.h"
#include "HoverInfo.h"
namespace pyrodactyl
{
namespace anim
{
struct AnimationFrame : public Vector2i
{
//The image drawn in this frame
ImageKey img;
//This is the time in we draw the frame milliseconds relative to the start of the entire animation
Uint32 start, finish;
//The effect applied to the image
AnimationEffect eff;
//In case we want to display any words during the animation
pyrodactyl::ui::HoverInfo text;
//The color drawn on the screen
SDL_Color col;
AnimationFrame(){ img = 0; start = 0; finish = 0; col.r = 0; col.g = 0; col.b = 0; col.a = 255; }
AnimationFrame(rapidxml::xml_node<char> *node);
void Reset();
void Draw(const Uint32 ×tamp);
DrawType InternalEvents(const Uint32 ×tamp);
};
}
}
|
vondrejc/sfepy
|
tests/test_input_biot.py
|
<filename>tests/test_input_biot.py<gh_stars>0
input_name = '../examples/biot/biot.py'
output_name = 'test_biot.vtk'
from tests_basic import TestInput
class Test( TestInput ):
pass
|
edmundoandrade/common-code
|
src/main/java/edworld/common/core/TreeNodeKeys.java
|
<filename>src/main/java/edworld/common/core/TreeNodeKeys.java
package edworld.common.core;
public interface TreeNodeKeys {
public String[] getKeys();
}
|
Scopetta197/chromium
|
chrome/test/functional/find_in_page.py
|
<reponame>Scopetta197/chromium<filename>chrome/test/functional/find_in_page.py<gh_stars>100-1000
#!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import codecs
import os
import unittest
import pyauto_functional
import pyauto
import pyauto_errors
import test_utils
class FindMatchTests(pyauto.PyUITest):
# Data dir where all find test data files are kept
find_test_data_dir = 'find_in_page'
def testCanFindMatchCount(self):
"""Verify Find match count for valid search"""
url = self.GetFileURLForDataPath('title1.html')
self.NavigateToURL(url)
self.assertEqual(1, self.FindInPage('title')['match_count'])
def testCanFindMatchCountFail(self):
"""Verify Find match count for invalid search"""
url = self.GetFileURLForDataPath('title1.html')
self.NavigateToURL(url)
self.assertEqual(0, self.FindInPage('blah')['match_count'])
def testFindIsNotCaseSensitive(self):
"""Verify that find is not case sensitive.
Manually Find is case insensitive. But since FindInPage is
case-sensitive by default we are confirming that we get a
different result when we turn off case matching.
"""
url = self.GetFileURLForDataPath('find_in_page', 'largepage.html')
self.NavigateToURL(url)
case_sensitive_result = self.FindInPage('The')['match_count']
case_insenstive_result = (self.FindInPage('The', match_case=False)
['match_count'])
self.assertTrue(case_insenstive_result >= case_sensitive_result)
def testSearchInTextAreas(self):
"""Verify search for text within various forms and text areas."""
urls = []
urls.append(self.GetFileURLForDataPath(
'find_in_page', 'textintextarea.html'))
urls.append(self.GetFileURLForDataPath(
'find_in_page', 'smalltextarea.html'))
urls.append(self.GetFileURLForDataPath(
'find_in_page', 'populatedform.html'))
for url in urls:
self.NavigateToURL(url)
self.assertEqual(1, self.FindInPage('cat')['match_count'])
self.assertEqual(0, self.FindInPage('bat')['match_count'])
def testSearchWithinSpecialURL(self):
"""Verify search for text within special URLs such as chrome:history.
chrome://history, chrome://downloads, pyAuto Data directory
"""
zip_file = 'a_zip_file.zip'
self.NavigateToURL(self.GetFileURLForPath(self.DataDir()))
# search in Data directory
self.assertEqual(1,
self.FindInPage('downloads', tab_index=0)['match_count'])
# search in History page
self.AppendTab(pyauto.GURL('chrome://history'))
# the contents in the history page load asynchronously after tab loads
search_query = os.path.join('chrome', 'test', 'data')
self.WaitUntil(
lambda: self.FindInPage(search_query, tab_index=1)['match_count'],
expect_retval=1)
self.assertEqual(
1, self.FindInPage(search_query, tab_index=1)['match_count'])
# search in Downloads page
test_utils.DownloadFileFromDownloadsDataDir(self, zip_file)
self.AppendTab(pyauto.GURL('chrome://downloads'))
# the contents in the downloads page load asynchronously after tab loads
self.WaitUntil(
lambda: self.FindInPage(zip_file, tab_index=2)['match_count'],
expect_retval=2)
self.assertEqual(2,
self.FindInPage(zip_file, tab_index=2)['match_count'])
test_utils.RemoveDownloadedTestFile(self, zip_file)
def testFindNextAndPrevious(self):
"""Verify search selection coordinates.
The data file used is set-up such that the text occurs on the same line,
and we verify their positions by verifying their relative positions.
"""
search_string = u'\u5728\u897f\u660c\u536b\u661f\u53d1'
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'specialchar.html')
self.NavigateToURL(url)
first_find = self.FindInPage(search_string)
second_find = self.FindInPage(search_string, find_next=True)
# We have search occurrence in the same row, so top-bottom
# coordinates should be the same even for second search.
self.assertEqual(first_find['match_top'], second_find['match_top'],
'Words\' top coordinates should be same')
self.assertEqual(first_find['match_bottom'], second_find['match_bottom'],
'Words\' bottom coordinates should be same')
# And left-right coordinates should be in order.
self.assertTrue(first_find['match_left'] < second_find['match_left'],
'Second find left coordinate should be greater than '
'the first find left coordinate')
self.assertTrue(first_find['match_right'] < second_find['match_right'],
'Second find right coordinate should be greater than '
'the first find right coordinate')
first_find_reverse = self.FindInPage(
search_string, find_next=True, forward=False)
# We find next and we go back so find coordinates should be the same
# as previous ones.
self.assertEqual(first_find, first_find_reverse,
'First occurrence must be selected, since we went back')
def testSpecialChars(self):
"""Test find in page with unicode and special characters.
Finds from page content, comments and meta data and verifies that comments
and meta data are not searchable.
"""
search_string = u'\u5728\u897f\u660c\u536b\u661f\u53d1'
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'specialchar.html')
self.NavigateToURL(url)
self.assertEqual(4, self.FindInPage(search_string)['match_count'])
search_string = u'240^*&%!#~!*&\u518d\u5c31\u8077\u624b\u5f53'
self.assertEqual(2, self.FindInPage(search_string)['match_count'])
# Find for the special chars in the comment and in the meta tag
search_string = u'\u4e2d\u65b0\u793e\u8bb0\u8005\u5b8b\u5409'\
u'\u6cb3\u6444\u4e2d\u65b0\u7f51'
self.assertEqual(0, self.FindInPage(search_string)['match_count'],
'Chrome should not find chars from comment or meta tags')
def testFindInLargePage(self):
"""Find in a very large page"""
url = self.GetFileURLForDataPath(self.find_test_data_dir, 'largepage.html')
self.NavigateToURL(url)
self.assertEqual(373, self.FindInPage('daughter of Prince')['match_count'])
def testFindLongString(self):
"""Find a very long string in a large page"""
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'largepage.html')
self.NavigateToURL(url)
file = codecs.open(os.path.join(self.DataDir(), self.find_test_data_dir,
'LongFind.txt'), 'r', 'utf-8')
search = file.read()
self.assertEqual(1, self.FindInPage(search)['match_count'])
def testFindBigString(self):
"""Find a big font string in a page"""
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'BigText.html')
self.NavigateToURL(url)
self.assertEqual(1, self.FindInPage('SomeLargeString')['match_count'])
def testVariousFindTests(self):
"""Test find in page for <span> style text, lists, html comments, etc."""
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'FindRandomTests.html')
self.NavigateToURL(url)
search = 'has light blue eyes and my father has dark'
self.assertEqual(1, self.FindInPage(search)['match_count'],
'Failed to find text with <span> tag')
# Find for list items
search = 'Google\nApple\nandroid'
self.assertEqual(1, self.FindInPage(search)['match_count'],
'Failed to find the list items')
# Find HTML comments
self.assertEqual(0, self.FindInPage('example comment')['match_count'],
'We should not find HTML comments')
def testFindWholeFileContent(self):
"""Find the whole text file page and find count should be 1"""
find_test_file = os.path.join(self.DataDir(), self.find_test_data_dir,
'find_test.txt')
url = self.GetFileURLForPath(find_test_file)
self.NavigateToURL(url)
file = open(find_test_file)
search = file.read()
self.assertEqual(1, self.FindInPage(search)['match_count'],
'Failed to find the whole page')
def testSingleOccurrence(self):
"""Search Back and Forward on a single occurrence"""
url = self.GetFileURLForDataPath(
self.find_test_data_dir, 'FindRandomTests.html')
self.NavigateToURL(url)
self.assertEqual(1, self.FindInPage('2010 Pro Bowl')['match_count'])
# First occurrence find
first_occurence_dict = self.FindInPage('2010 Pro Bowl')
# Finding next occurrence
next_occurence_dict = self.FindInPage('2010 Pro Bowl', find_next = True)
self.assertEqual(first_occurence_dict, next_occurence_dict,
'We have only one occurrence in this page so'
'first and next coordinates must be same')
# Doing a fake find so we have no previous search
self.FindInPage('ghgfjgfh201232rere')
first_occurence_dict = self.FindInPage('2010 Pro Bowl')
# Finding previous occurrence
back_occurence_dict = self.FindInPage('2010 Pro Bowl',
find_next = True, forward = False)
self.assertEqual(first_occurence_dict, back_occurence_dict,
'We have only one occurrence in this page so '
'first and back search coordinates must be same')
def _VerifySearchInPDFURL(self, url, word, expected_count):
"""Verify that we can find in a pdf file."""
self.NavigateToURL(url)
# Check for JSONInterfaceError thrown when FindInPage called before page
# loaded crbug.com/107448.
num_loops = 10
for loop in range(num_loops):
try:
search_count = self.FindInPage(word, timeout=1000)['match_count']
break
except pyauto_errors.JSONInterfaceError:
if loop == num_loops - 1:
raise
self.assertEqual(expected_count, search_count,
'Failed to find in the %s pdf file' % url)
def testSearchInPDF(self):
"""Verify that we can find in a pdf file.
Only for Google Chrome builds (Chromium builds do not have internal pdf).
"""
# bail out if not a branded build
properties = self.GetBrowserInfo()['properties']
if properties['branding'] != 'Google Chrome':
return
# Search in pdf file over file://.
file_url = self.GetFileURLForDataPath('plugin', 'Embed.pdf')
self._VerifySearchInPDFURL(file_url, 'adobe', 8)
# Search in pdf file over http://.
http_url = 'http://www.irs.gov/pub/irs-pdf/fw4.pdf'
self._VerifySearchInPDFURL(http_url, 'Allowances', 16)
if __name__ == '__main__':
pyauto_functional.Main()
|
dslowikowski/commcare-hq
|
corehq/apps/locations/static/locations/ko/location_drilldown.async.js
|
<reponame>dslowikowski/commcare-hq
function api_get_children(loc_uuid, callback) {
var params = (loc_uuid ? {parent_id: loc_uuid} : {});
$('#loc_ajax').show();
$.getJSON(LOAD_LOCS_URL, params, function(allData) {
$('#loc_ajax').hide();
callback(allData.objects);
});
}
function LocationSelectViewModel(hierarchy, default_caption, auto_drill, loc_filter, func) {
var model = this;
this.default_caption = default_caption || 'All';
this.auto_drill = (auto_drill == null ? true : auto_drill);
this.loc_filter = loc_filter || function(loc) { return true; };
this.func = typeof func !== 'undefined' ? func : LocationModel;
this.root = ko.observable();
this.selected_path = ko.observableArray();
this.location_types = $.map(hierarchy, function(e) {
return {type: e[0], allowed_parents: e[1]};
});
// currently selected location in the tree (or null)
this.selected_location = ko.computed(function() {
for (var i = this.selected_path().length - 1; i >= 0; i--) {
var loc = this.selected_path()[i];
if (loc.selected_is_valid()) {
return loc.selected_child();
}
}
return null;
}, this);
// uuid of currently selected location (or null)
this.selected_locid = ko.computed(function() {
return this.selected_location() ? this.selected_location().uuid() : null;
}, this);
// add a new level of drill-down to the tree
this.path_push = function(loc) {
if (this.selected_path().length != this.location_types.length) {
this.selected_path.push(loc);
if (this.auto_drill && loc.num_children() == 1) {
loc.selected_child(loc.get_child(0));
}
}
}
// search for a location within the tree by uuid; return path to location if found
this.find_loc = function(uuid, loc) {
loc = loc || this.root();
if (loc.uuid() == uuid) {
return [loc];
} else {
var path = null;
$.each(loc.children(), function(i, e) {
var subpath = model.find_loc(uuid, e);
if (subpath) {
path = subpath;
path.splice(0, 0, loc);
return false;
}
});
return path;
}
}
// load location hierarchy and set initial path
this.load = function(locs, selected, restriction) {
this.root(new model.func({name: '_root', children: locs, 'restriction': restriction}, this));
this.path_push(this.root());
if (selected) {
// this relies on the hierarchy of the selected location being pre-populated
// in the initial locations set from the server (i.e., no location of the
// pre-selected location's lineage is loaded asynchronously
var sel_path = this.find_loc(selected);
if (sel_path) {
for (var i = 1; i < sel_path.length; i++) {
sel_path[i - 1].selected_child(sel_path[i]);
}
}
}
}
}
function LocationModel(data, root, depth, func, withAllOption) {
var loc = this;
this.name = ko.observable();
this.type = ko.observable();
this.uuid = ko.observable();
this.location_restriction = ko.observable();
this.children = ko.observableArray();
this.depth = depth || 0;
this.children_loaded = false;
this.func = typeof func !== 'undefined' ? func : LocationModel;
this.withAllOption = typeof withAllOption !== 'undefined' ? withAllOption : true;
this.display_name = ko.computed(function() {
return this.name() == '_all' ? root.default_caption : this.name();
}, this);
this.selected_child = ko.observable();
// when a location is selected, update the drill-down tree
this.selected_child.subscribe(function(val) {
if (val == null) {
return;
}
var removed = root.selected_path.splice(val.depth, 99);
$.each(removed, function(i, e) {
// reset so dropdown for loc will default to 'all' if shown again
e.selected_child(null);
});
var post_children_loaded = function(parent) {
if (parent.num_children()) {
root.path_push(parent);
}
};
if (val.uuid() != null && !val.children_loaded) {
val.load_children_async(post_children_loaded);
} else {
post_children_loaded(val);
}
}, this);
this.selected_is_valid = ko.computed(function() {
return this.selected_child() && this.selected_child().name() != '_all';
}, this);
// helpers to account for the 'all' meta-entry
this.num_children = ko.computed(function() {
return (this.children().length == 0 ? 0 : this.children().length - 1);
}, this);
this.get_child = function(i) {
return this.children()[i + 1];
}
this.load = function(data) {
this.name(data.name);
this.type(data.location_type);
this.uuid(data.uuid);
this.location_restriction(data.restriction);
if (data.children != null) {
$.map(data.children, function(e) {
e.restriction = data.restriction
});
this.set_children(data.children);
}
}
this.set_children = function(data) {
var children = [];
if (data) {
children = _.sortBy(data, function(e) { return e.name; });
//'all choices' meta-entry; annoying that we have to stuff this in
//the children list, but all my attempts to make computed observables
//based of children() caused infinite loops.
if(loc.withAllOption || (!loc.withAllOption && loc.depth > REQUIRED))
children.splice(0, 0, {name: '_all'});
}
this.children($.map(children, function(e) {
var child = new loc.func(e, root, loc.depth + 1);
return (child.filter() ? child : null);
}));
this.children_loaded = true;
}
this.load_children_async = function(callback) {
api_get_children(this.uuid(), function(resp) {
loc.set_children(resp);
callback(loc);
});
}
//warning: duplicate code with location_tree.async.js
this.allowed_child_types = ko.computed(function() {
var loc = this;
var types = [];
$.each(root.location_types, function(i, loc_type) {
$.each(loc_type.allowed_parents, function(i, parent_type) {
if (loc.type() == parent_type) {
types.push(loc_type.type);
}
});
});
return types;
}, this);
this.can_have_children = ko.computed(function() {
return (this.allowed_child_types().length > 0);
}, this);
this.filter = function() {
return this.name() == '_all' || root.loc_filter(this);
}
this.load(data);
}
|
torbjornvatn/cuke4duke
|
cuke4duke/src/main/java/cuke4duke/internal/JRuby.java
|
package cuke4duke.internal;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.exceptions.RaiseException;
import java.util.Collection;
/**
* Keeps a reference to the Ruby instance that was used to
* start the whole machinery. I hate this static stuff, but
* there is currently no clean way around it.
*/
public class JRuby {
private static Ruby runtime;
public static void setRuntime(Ruby runtime) {
JRuby.runtime = runtime;
}
public static Ruby getRuntime() {
if(runtime == null) {
runtime = Ruby.getGlobalRuntime();
}
return runtime;
}
public static RaiseException cucumberPending(String message) {
return error("Pending", message);
}
public static RaiseException cucumberArityMismatchError(String message) {
return error("ArityMismatchError", message);
}
public static RaiseException cucumberUndefined(String message){
return error("Undefined", message);
}
public static RaiseException error(String errorClass, String message) {
RubyModule cucumber = getRuntime().getModule("Cucumber");
RubyClass error = cucumber.getClass(errorClass);
return new RaiseException(
getRuntime(),
error,
message,
true
);
}
public static RubyArray newArray(Collection<?> collection) {
RubyArray result = RubyArray.newArray(getRuntime());
for (Object o : collection) {
result.add(o);
}
return result;
}
}
|
jlaluces123/grommet-icons
|
src/js/icons/DocumentConfig.js
|
<reponame>jlaluces123/grommet-icons
import React from 'react';
import { StyledIcon } from '../StyledIcon';
export const DocumentConfig = props => (
<StyledIcon viewBox='0 0 24 24' a11yTitle='DocumentConfig' {...props}>
<path fill='none' stroke='#000' strokeWidth='2' d='M4.998 9V1H19.5L23 4.5V23h-7m2-22v5h5M9 14v-3m0 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm0 3v-3m3-3h3M3 17h3m-1-4 2 2m4 4 2 2m0-8-2 2m-4 4-2 2' />
</StyledIcon>
);
|
Antonio-Neves/Gestao-Escolar
|
responsaveis/apps.py
|
from django.apps import AppConfig
class ResponsaveisConfig(AppConfig):
name = 'responsaveis'
|
BuildJet/sat4envi
|
s4e-backend/src/main/java/pl/cyfronet/s4e/controller/InvitationController.java
|
<reponame>BuildJet/sat4envi
/*
* Copyright 2020 ACC Cyfronet AGH
*
* 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
*
* https://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 pl.cyfronet.s4e.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import pl.cyfronet.s4e.bean.Invitation;
import pl.cyfronet.s4e.controller.request.InvitationRequest;
import pl.cyfronet.s4e.controller.request.InvitationResendInvitation;
import pl.cyfronet.s4e.controller.response.BasicInstitutionResponse;
import pl.cyfronet.s4e.controller.response.BasicInvitationResponse;
import pl.cyfronet.s4e.event.OnConfirmInvitationEvent;
import pl.cyfronet.s4e.event.OnDeleteInvitationEvent;
import pl.cyfronet.s4e.event.OnRejectInvitationEvent;
import pl.cyfronet.s4e.event.OnSendInvitationEvent;
import pl.cyfronet.s4e.ex.NotFoundException;
import pl.cyfronet.s4e.service.InvitationService;
import pl.cyfronet.s4e.util.AppUserDetailsSupplier;
import javax.validation.Valid;
import java.util.Set;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static pl.cyfronet.s4e.Constants.API_PREFIX_V1;
@RestController
@RequestMapping(path = API_PREFIX_V1, produces = APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
@Tag(name = "invitation", description = "Invite by email API")
public class InvitationController {
private final InvitationService invitationService;
private final ApplicationEventPublisher eventPublisher;
@Operation(summary = "Fetch all invitations for specific institution")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Successfully retrieved list"),
@ApiResponse(responseCode = "400", description = "Incorrect request", content = @Content),
@ApiResponse(responseCode = "401", description = "Unauthenticated", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content)
})
@GetMapping(value = "/institutions/{institution}/invitations")
public Set<BasicInvitationResponse> get(@PathVariable("institution") String institutionSlug) {
return invitationService.findAllBy(institutionSlug, BasicInvitationResponse.class);
}
@Operation(summary = "Send invitation email to user")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Invitation was send"),
@ApiResponse(responseCode = "400", description = "Incorrect request", content = @Content),
@ApiResponse(responseCode = "401", description = "Unauthenticated", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
})
@PostMapping(value = "/institutions/{institution}/invitations", consumes = APPLICATION_JSON_VALUE)
public BasicInvitationResponse send(
@RequestBody @Valid InvitationRequest request,
@PathVariable("institution") String institutionSlug
) throws Exception {
val token = invitationService.createInvitationFrom(
request.getEmail(),
institutionSlug,
request.isForAdmin()
);
val invitationEvent = new OnSendInvitationEvent(token, LocaleContextHolder.getLocale());
eventPublisher.publishEvent(invitationEvent);
return invitationService.findByToken(token, BasicInvitationResponse.class).get();
}
@Operation(summary = "Resend invitation and delete last one")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Invitation was resend"),
@ApiResponse(
responseCode = "400",
description = "Institution in url and invitation institution are different",
content = @Content
),
@ApiResponse(responseCode = "401", description = "Unauthenticated", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
})
@PutMapping(value = "/institutions/{institution}/invitations", consumes = APPLICATION_JSON_VALUE)
public BasicInvitationResponse resend(
@RequestBody @Valid InvitationResendInvitation request,
@PathVariable("institution") String institutionSlug
) throws Exception {
invitationService.deleteBy(request.getOldEmail(), institutionSlug);
val newToken = invitationService.createInvitationFrom(
request.getNewEmail(),
institutionSlug,
request.isForAdmin()
);
val invitationEvent = new OnSendInvitationEvent(newToken, LocaleContextHolder.getLocale());
eventPublisher.publishEvent(invitationEvent);
return invitationService.findByToken(newToken, BasicInvitationResponse.class).get();
}
@Operation(summary = "Delete invitation")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Invitation have been removed"),
@ApiResponse(
responseCode = "400",
description = "Institution in url and invitation institution are different",
content = @Content
),
@ApiResponse(responseCode = "401", description = "Unauthenticated", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
})
@DeleteMapping(value = "/institutions/{institution}/invitations/{id}")
public void delete(
@PathVariable("institution") String institutionSlug,
@PathVariable Long id
) throws Exception {
val invitation = invitationService
.findByIdAndInstitutionSlug(id, institutionSlug, Invitation.class)
.orElseThrow(() -> new NotFoundException("Invitation couldn't be found"));
val deleteInvitationEvent = new OnDeleteInvitationEvent(invitation.getToken(), LocaleContextHolder.getLocale());
eventPublisher.publishEvent(deleteInvitationEvent);
}
@Operation(summary = "Confirm invitation")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Invitation have been confirmed"),
@ApiResponse(responseCode = "400", description = "Incorrect request", content = @Content),
@ApiResponse(responseCode = "401", description = "Unauthenticated", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
})
@PostMapping(value = "/invitations/{token}/confirm")
public BasicInstitutionResponse confirm(@PathVariable String token) throws NotFoundException {
invitationService.confirmInvitation(AppUserDetailsSupplier.get().getEmail(), token);
val institution = invitationService.findInstitutionBy(token, BasicInstitutionResponse.class)
.orElseThrow(() -> new NotFoundException("Institution couldn't be found"));
val confirmInvitationEvent = new OnConfirmInvitationEvent(token, LocaleContextHolder.getLocale());
eventPublisher.publishEvent(confirmInvitationEvent);
return institution;
}
@Operation(summary = "Reject invitation")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Invitation have been rejected"),
@ApiResponse(responseCode = "400", description = "Incorrect request", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
})
@PutMapping(value = "/invitations/{token}/reject")
public void reject(@PathVariable String token) throws NotFoundException {
invitationService.rejectInvitation(token);
val rejectInvitationEvent = new OnRejectInvitationEvent(token, LocaleContextHolder.getLocale());
eventPublisher.publishEvent(rejectInvitationEvent);
}
}
|
mellowdrifter/bio-rd
|
protocols/bgp/server/peer.go
|
package server
import (
"sync"
"time"
"github.com/bio-routing/bio-rd/config"
bnet "github.com/bio-routing/bio-rd/net"
"github.com/bio-routing/bio-rd/protocols/bgp/packet"
"github.com/bio-routing/bio-rd/routingtable"
"github.com/bio-routing/bio-rd/routingtable/filter"
"github.com/bio-routing/bio-rd/routingtable/locRIB"
)
type PeerInfo struct {
PeerAddr bnet.IP
PeerASN uint32
LocalASN uint32
States []string
}
type peer struct {
server *bgpServer
addr bnet.IP
localAddr bnet.IP
peerASN uint32
localASN uint32
// guarded by fsmsMu
fsms []*FSM
fsmsMu sync.Mutex
routerID uint32
reconnectInterval time.Duration
keepaliveTime time.Duration
holdTime time.Duration
optOpenParams []packet.OptParam
routeServerClient bool
routeReflectorClient bool
ipv4MultiProtocolAdvertised bool
clusterID uint32
ipv4 *peerAddressFamily
ipv6 *peerAddressFamily
}
type peerAddressFamily struct {
rib *locRIB.LocRIB
importFilter *filter.Filter
exportFilter *filter.Filter
addPathSend routingtable.ClientOptions
addPathReceive bool
}
func (p *peer) addressFamily(afi uint16, safi uint8) *peerAddressFamily {
if safi != packet.UnicastSAFI {
return nil
}
switch afi {
case packet.IPv4AFI:
return p.ipv4
case packet.IPv6AFI:
return p.ipv6
default:
return nil
}
}
func (p *peer) snapshot() PeerInfo {
p.fsmsMu.Lock()
defer p.fsmsMu.Unlock()
states := make([]string, 0, len(p.fsms))
for _, fsm := range p.fsms {
fsm.stateMu.RLock()
states = append(states, stateName(fsm.state))
fsm.stateMu.RUnlock()
}
return PeerInfo{
PeerAddr: p.addr,
PeerASN: p.peerASN,
LocalASN: p.localASN,
States: states,
}
}
func (p *peer) collisionHandling(callingFSM *FSM) bool {
p.fsmsMu.Lock()
defer p.fsmsMu.Unlock()
for _, fsm := range p.fsms {
if callingFSM == fsm {
continue
}
fsm.stateMu.RLock()
isEstablished := isEstablishedState(fsm.state)
isOpenConfirm := isOpenConfirmState(fsm.state)
fsm.stateMu.RUnlock()
if isEstablished {
return true
}
if !isOpenConfirm {
continue
}
if p.routerID < callingFSM.neighborID {
fsm.cease()
} else {
return true
}
}
return false
}
func isOpenConfirmState(s state) bool {
switch s.(type) {
case openConfirmState:
return true
}
return false
}
func isEstablishedState(s state) bool {
switch s.(type) {
case establishedState:
return true
}
return false
}
// NewPeer creates a new peer with the given config. If an connection is established, the adjRIBIN of the peer is connected
// to the given rib. To actually connect the peer, call Start() on the returned peer.
func newPeer(c config.Peer, server *bgpServer) (*peer, error) {
if c.LocalAS == 0 {
c.LocalAS = server.localASN
}
p := &peer{
server: server,
addr: c.PeerAddress,
peerASN: c.PeerAS,
localASN: c.LocalAS,
fsms: make([]*FSM, 0),
reconnectInterval: c.ReconnectInterval,
keepaliveTime: c.KeepAlive,
holdTime: c.HoldTime,
optOpenParams: make([]packet.OptParam, 0),
routeServerClient: c.RouteServerClient,
routeReflectorClient: c.RouteReflectorClient,
clusterID: c.RouteReflectorClusterID,
}
if c.IPv4 != nil {
p.ipv4 = &peerAddressFamily{
rib: c.IPv4.RIB,
importFilter: filterOrDefault(c.IPv4.ImportFilter),
exportFilter: filterOrDefault(c.IPv4.ExportFilter),
addPathReceive: c.IPv4.AddPathRecv,
addPathSend: c.IPv4.AddPathSend,
}
}
// If we are a route reflector and no ClusterID was set, use our RouterID
if p.routeReflectorClient && p.clusterID == 0 {
p.clusterID = c.RouterID
}
caps := make(packet.Capabilities, 0)
caps = append(caps, addPathCapabilities(c)...)
caps = append(caps, asn4Capability(c))
if c.IPv4 != nil && c.AdvertiseIPv4MultiProtocol {
caps = append(caps, multiProtocolCapability(packet.IPv4AFI))
p.ipv4MultiProtocolAdvertised = true
}
if c.IPv6 != nil {
p.ipv6 = &peerAddressFamily{
rib: c.IPv6.RIB,
importFilter: filterOrDefault(c.IPv6.ImportFilter),
exportFilter: filterOrDefault(c.IPv6.ExportFilter),
addPathReceive: c.IPv6.AddPathRecv,
addPathSend: c.IPv6.AddPathSend,
}
caps = append(caps, multiProtocolCapability(packet.IPv6AFI))
}
p.optOpenParams = append(p.optOpenParams, packet.OptParam{
Type: packet.CapabilitiesParamType,
Value: caps,
})
p.fsms = append(p.fsms, NewActiveFSM(p))
return p, nil
}
func asn4Capability(c config.Peer) packet.Capability {
return packet.Capability{
Code: packet.ASN4CapabilityCode,
Value: packet.ASN4Capability{
ASN4: c.LocalAS,
},
}
}
func multiProtocolCapability(afi uint16) packet.Capability {
return packet.Capability{
Code: packet.MultiProtocolCapabilityCode,
Value: packet.MultiProtocolCapability{
AFI: afi,
SAFI: packet.UnicastSAFI,
},
}
}
func addPathCapabilities(c config.Peer) []packet.Capability {
caps := make([]packet.Capability, 0)
enabled, cap := addPathCapabilityForFamily(c.IPv4, packet.IPv4AFI, packet.UnicastSAFI)
if enabled {
caps = append(caps, cap)
}
enabled, cap = addPathCapabilityForFamily(c.IPv6, packet.IPv6AFI, packet.UnicastSAFI)
if enabled {
caps = append(caps, cap)
}
return caps
}
func addPathCapabilityForFamily(f *config.AddressFamilyConfig, afi uint16, safi uint8) (enabled bool, cap packet.Capability) {
if f == nil {
return false, packet.Capability{}
}
addPath := uint8(0)
if f.AddPathRecv {
addPath += packet.AddPathReceive
}
if !f.AddPathSend.BestOnly {
addPath += packet.AddPathSend
}
if addPath == 0 {
return false, packet.Capability{}
}
return true, packet.Capability{
Code: packet.AddPathCapabilityCode,
Value: packet.AddPathCapability{
AFI: afi,
SAFI: safi,
SendReceive: addPath,
},
}
}
func filterOrDefault(f *filter.Filter) *filter.Filter {
if f != nil {
return f
}
return filter.NewDrainFilter()
}
// GetAddr returns the IP address of the peer
func (p *peer) GetAddr() bnet.IP {
return p.addr
}
func (p *peer) Start() {
p.fsms[0].start()
}
|
wintermao/test
|
ddr_layout_V5/ip/dac2904/inc/dac2904_regs.h
|
<filename>ddr_layout_V5/ip/dac2904/inc/dac2904_regs.h
/******************************************************************************
//by mmh create 2018.3.4
******************************************************************************/
#ifndef __DAC2904_REGS_H__
#define __DAC2904_REGS_H__
#include <io.h>
#define DAC2904_REG 0
#define IOADDR_DAC2904_DATA(base) __IO_CALC_ADDRESS_NATIVE(base, DAC2904_REG)
#define IORD_DAC2904_DATA(base) IORD(base, DAC2904_REG)
#define IOWR_DAC2904_DATA(base, data) IOWR(base, DAC2904_REG, data)
#endif /* __DAC2904_REGS_H__ */
|
Cedric-Huguenin/PI-InfoAutonomie
|
gateway/Aleoncean/src/main/java/eu/aleon/aleoncean/packet/radio/userdata/eepd201/DimTimer.java
|
<reponame>Cedric-Huguenin/PI-InfoAutonomie
/*
* Copyright (c) 2014 aleon GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Note for all commercial users of this library:
* Please contact the EnOcean Alliance (http://www.enocean-alliance.org/)
* about a possible requirement to become member of the alliance to use the
* EnOcean protocol implementations.
*
* Contributors:
* <NAME> - initial API and implementation and/or initial documentation
*/
package eu.aleon.aleoncean.packet.radio.userdata.eepd201;
/**
*
* @author <NAME> <<EMAIL>>
*/
public enum DimTimer {
NOT_USED((byte) 0x0),
TIMER_0_5_SEC((byte) 0x01),
TIMER_1_0_SEC((byte) 0x02),
TIMER_1_5_SEC((byte) 0x03),
TIMER_2_0_SEC((byte) 0x04),
TIMER_2_5_SEC((byte) 0x05),
TIMER_3_0_SEC((byte) 0x06),
TIMER_3_5_SEC((byte) 0x07),
TIMER_4_0_SEC((byte) 0x08),
TIMER_4_5_SEC((byte) 0x09),
TIMER_5_0_SEC((byte) 0x0A),
TIMER_5_5_SEC((byte) 0x0B),
TIMER_6_0_SEC((byte) 0x0C),
TIMER_6_5_SEC((byte) 0x0D),
TIMER_7_0_SEC((byte) 0x0E),
TIMER_7_5_SEC((byte) 0x0F);
private final byte value;
public static DimTimer fromByte(final byte value) {
switch (value) {
case 0x00:
return DimTimer.NOT_USED;
case 0x01:
return DimTimer.TIMER_0_5_SEC;
case 0x02:
return DimTimer.TIMER_1_0_SEC;
case 0x03:
return DimTimer.TIMER_1_5_SEC;
case 0x04:
return DimTimer.TIMER_2_0_SEC;
case 0x05:
return DimTimer.TIMER_2_5_SEC;
case 0x06:
return DimTimer.TIMER_3_0_SEC;
case 0x07:
return DimTimer.TIMER_3_5_SEC;
case 0x08:
return DimTimer.TIMER_4_0_SEC;
case 0x09:
return DimTimer.TIMER_4_5_SEC;
case 0x0A:
return DimTimer.TIMER_5_0_SEC;
case 0x0B:
return DimTimer.TIMER_5_5_SEC;
case 0x0C:
return DimTimer.TIMER_6_0_SEC;
case 0x0D:
return DimTimer.TIMER_6_5_SEC;
case 0x0E:
return DimTimer.TIMER_7_0_SEC;
case 0x0F:
return DimTimer.TIMER_7_5_SEC;
default:
return DimTimer.NOT_USED;
}
}
private DimTimer(final byte value) {
this.value = value;
}
public byte toByte() {
return value;
}
}
|
ryo-rm/expo
|
ios/versioned-react-native/ABI45_0_0/ReactNative/ReactCommon/react/renderer/components/text/ABI45_0_0RawTextProps.h
|
<filename>ios/versioned-react-native/ABI45_0_0/ReactNative/ReactCommon/react/renderer/components/text/ABI45_0_0RawTextProps.h
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <ABI45_0_0React/ABI45_0_0renderer/core/Props.h>
#include <ABI45_0_0React/ABI45_0_0renderer/core/PropsParserContext.h>
#include <ABI45_0_0React/ABI45_0_0renderer/debug/DebugStringConvertible.h>
namespace ABI45_0_0facebook {
namespace ABI45_0_0React {
class RawTextProps;
using SharedRawTextProps = std::shared_ptr<const RawTextProps>;
class RawTextProps : public Props {
public:
RawTextProps() = default;
RawTextProps(
const PropsParserContext &context,
const RawTextProps &sourceProps,
const RawProps &rawProps);
#pragma mark - Props
std::string text{};
#pragma mark - DebugStringConvertible
#if ABI45_0_0RN_DEBUG_STRING_CONVERTIBLE
SharedDebugStringConvertibleList getDebugProps() const override;
#endif
};
} // namespace ABI45_0_0React
} // namespace ABI45_0_0facebook
|
OpenMunicipality/api-service-casemanagement
|
src/main/generated-sources/cxf/v1/service/minutmiljo/api/ecos/SearchFacilityCollectionResponse.java
|
package v1.service.minutmiljo.api.ecos;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import v1.datacontracts.minutmiljo.api.ecos.ArrayOfSearchFacilityCollectioResultSvcDto;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="SearchFacilityCollectionResult" type="{urn:Ecos.API.MinutMiljo.DataContracts.V1}ArrayOfSearchFacilityCollectioResultSvcDto" minOccurs="0"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"searchFacilityCollectionResult"
})
@XmlRootElement(name = "SearchFacilityCollectionResponse")
public class SearchFacilityCollectionResponse {
@XmlElement(name = "SearchFacilityCollectionResult", nillable = true)
protected ArrayOfSearchFacilityCollectioResultSvcDto searchFacilityCollectionResult;
/**
* Gets the value of the searchFacilityCollectionResult property.
*
* @return
* possible object is
* {@link ArrayOfSearchFacilityCollectioResultSvcDto }
*
*/
public ArrayOfSearchFacilityCollectioResultSvcDto getSearchFacilityCollectionResult() {
return searchFacilityCollectionResult;
}
/**
* Sets the value of the searchFacilityCollectionResult property.
*
* @param value
* allowed object is
* {@link ArrayOfSearchFacilityCollectioResultSvcDto }
*
*/
public void setSearchFacilityCollectionResult(ArrayOfSearchFacilityCollectioResultSvcDto value) {
this.searchFacilityCollectionResult = value;
}
}
|
DamieFC/fuchsia
|
src/ui/a11y/lib/screen_reader/recover_a11y_focus_action.cc
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/a11y/lib/screen_reader/recover_a11y_focus_action.h"
#include <lib/syslog/cpp/macros.h>
#include "src/ui/a11y/lib/screen_reader/util/util.h"
namespace a11y {
RecoverA11YFocusAction::RecoverA11YFocusAction(ActionContext* action_context,
ScreenReaderContext* screen_reader_context)
: ScreenReaderAction(action_context, screen_reader_context) {}
RecoverA11YFocusAction::~RecoverA11YFocusAction() = default;
void RecoverA11YFocusAction::Run(ActionData process_data) {
auto a11y_focus_manager = screen_reader_context_->GetA11yFocusManager();
FX_DCHECK(a11y_focus_manager);
auto a11y_focus = a11y_focus_manager->GetA11yFocus();
if (!a11y_focus) {
return;
}
if (!action_context_->semantics_source->ViewHasSemantics(a11y_focus->view_ref_koid)) {
a11y_focus_manager->ClearA11yFocus();
return;
}
// Get the node in focus.
const auto* focused_node = action_context_->semantics_source->GetSemanticNode(
a11y_focus->view_ref_koid, a11y_focus->node_id);
if (focused_node) {
// If the semantic tree has been updated, it's possible that the bounding
// box of the currently focused node has changed. Therefore, we should
// redraw highlights.
a11y_focus_manager->UpdateHighlights();
// the node still exists, we can stop here.
return;
}
// The node is no longer present but the view is still providing semantics.
// The current strategy is from the root, tries to find the first focusable node and set the focus
// to it.
const int starting_id = 0;
focused_node =
action_context_->semantics_source->GetSemanticNode(a11y_focus->view_ref_koid, starting_id);
if (!focused_node) {
a11y_focus_manager->ClearA11yFocus();
return;
}
// Now, put in focus a node that is describable and speak it to the user, to inform where the
// Screen Reader navigated.
if (!NodeIsDescribable(focused_node)) {
focused_node = action_context_->semantics_source->GetNextNode(
a11y_focus->view_ref_koid, starting_id,
[](const fuchsia::accessibility::semantics::Node* node) {
return NodeIsDescribable(node);
});
if (!focused_node) {
// This tree does not have a node that is describable.
return;
}
}
uint32_t focused_node_id = focused_node->node_id();
auto promise =
ExecuteAccessibilityActionPromise(a11y_focus->view_ref_koid, focused_node_id,
fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN)
.and_then([this, focused_node_id, a11y_focus]() mutable {
return SetA11yFocusPromise(focused_node_id, a11y_focus->view_ref_koid);
})
.and_then([this, a11y_focus, focused_node_id]() mutable {
return BuildSpeechTaskFromNodePromise(a11y_focus->view_ref_koid, focused_node_id);
})
// Cancel any promises if this class goes out of scope.
.wrap_with(scope_);
auto* executor = screen_reader_context_->executor();
executor->schedule_task(std::move(promise));
}
} // namespace a11y
|
tashiscool/bc-fips
|
core/src/main/java/org/bouncycastle/util/IPAddress.java
|
<filename>core/src/main/java/org/bouncycastle/util/IPAddress.java
/***************************************************************/
/****** DO NOT EDIT THIS CLASS bc-java SOURCE FILE ******/
/***************************************************************/
package org.bouncycastle.util;
/**
* Utility methods for processing String objects containing IP addresses.
*/
public class IPAddress
{
/**
* Validate the given IPv4 or IPv6 address.
*
* @param address the IP address as a String.
*
* @return true if a valid address, false otherwise
*/
public static boolean isValid(
String address)
{
return isValidIPv4(address) || isValidIPv6(address);
}
/**
* Validate the given IPv4 or IPv6 address and netmask.
*
* @param address the IP address as a String.
*
* @return true if a valid address with netmask, false otherwise
*/
public static boolean isValidWithNetMask(
String address)
{
return isValidIPv4WithNetmask(address) || isValidIPv6WithNetmask(address);
}
/**
* Validate the given IPv4 address.
*
* @param address the IP address as a String.
*
* @return true if a valid IPv4 address, false otherwise
*/
public static boolean isValidIPv4(
String address)
{
if (address.length() == 0)
{
return false;
}
int octet;
int octets = 0;
String temp = address+".";
int pos;
int start = 0;
while (start < temp.length()
&& (pos = temp.indexOf('.', start)) > start)
{
if (octets == 4)
{
return false;
}
try
{
octet = Integer.parseInt(temp.substring(start, pos));
}
catch (NumberFormatException ex)
{
return false;
}
if (octet < 0 || octet > 255)
{
return false;
}
start = pos + 1;
octets++;
}
return octets == 4;
}
public static boolean isValidIPv4WithNetmask(
String address)
{
int index = address.indexOf("/");
String mask = address.substring(index + 1);
return (index > 0) && isValidIPv4(address.substring(0, index))
&& (isValidIPv4(mask) || isMaskValue(mask, 32));
}
public static boolean isValidIPv6WithNetmask(
String address)
{
int index = address.indexOf("/");
String mask = address.substring(index + 1);
return (index > 0) && (isValidIPv6(address.substring(0, index))
&& (isValidIPv6(mask) || isMaskValue(mask, 128)));
}
private static boolean isMaskValue(String component, int size)
{
try
{
int value = Integer.parseInt(component);
return value >= 0 && value <= size;
}
catch (NumberFormatException e)
{
return false;
}
}
/**
* Validate the given IPv6 address.
*
* @param address the IP address as a String.
*
* @return true if a valid IPv4 address, false otherwise
*/
public static boolean isValidIPv6(
String address)
{
if (address.length() == 0)
{
return false;
}
int octet;
int octets = 0;
String temp = address + ":";
boolean doubleColonFound = false;
int pos;
int start = 0;
while (start < temp.length()
&& (pos = temp.indexOf(':', start)) >= start)
{
if (octets == 8)
{
return false;
}
if (start != pos)
{
String value = temp.substring(start, pos);
if (pos == (temp.length() - 1) && value.indexOf('.') > 0)
{
if (!isValidIPv4(value))
{
return false;
}
octets++; // add an extra one as address covers 2 words.
}
else
{
try
{
octet = Integer.parseInt(temp.substring(start, pos), 16);
}
catch (NumberFormatException ex)
{
return false;
}
if (octet < 0 || octet > 0xffff)
{
return false;
}
}
}
else
{
if (pos != 1 && pos != temp.length() - 1 && doubleColonFound)
{
return false;
}
doubleColonFound = true;
}
start = pos + 1;
octets++;
}
return octets == 8 || doubleColonFound;
}
}
|
cavalier99/thorium
|
client/src/App.js
|
import React from "react";
import { ApolloProvider } from "react-apollo";
import { ApolloProvider as ApolloHooksProvider } from "@apollo/react-hooks";
import client from "./helpers/graphqlClient";
import Routes from "./containers/routes";
import ErrorBoundary from "./helpers/errorBoundary";
import EasterEgg from "./helpers/easter-egg";
import IntlProvider from "./helpers/intl";
import "./app.scss";
import "./fonts.scss";
const ApolloApp = () => (
<ApolloProvider client={client}>
<ApolloHooksProvider client={client}>
<IntlProvider>
<ErrorBoundary>
<Routes />
<EasterEgg />
</ErrorBoundary>
</IntlProvider>
</ApolloHooksProvider>
</ApolloProvider>
);
export default ApolloApp;
|
SabheeR/hobbits
|
src/hobbits-python/py_bitarray.cpp
|
<reponame>SabheeR/hobbits<filename>src/hobbits-python/py_bitarray.cpp
#include "py_bitarray.h"
#include "bitarray.h"
#include <QSharedPointer>
#include <structmember.h>
#define UNUSED(expr) do { (void)(expr); } while (0);
#define BITS(X) static_cast<BitArray*>(PyCapsule_GetPointer(X, nullptr))
typedef struct {
PyObject_HEAD
PyObject* bitsCapsule;
} BitArrayPyObj;
static void BitArrayPy_dealloc(BitArrayPyObj *self)
{
Py_XDECREF(self->bitsCapsule);
Py_TYPE(self)->tp_free((PyObject*) self);
}
static PyObject* BitArrayPy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
UNUSED(args)
UNUSED(kwds)
BitArrayPyObj *self;
self = reinterpret_cast<BitArrayPyObj*>(type->tp_alloc(type, 0));
if (self != nullptr) {
self->bitsCapsule = nullptr;
}
return (PyObject*) self;
}
static int BitArrayPy_init(BitArrayPyObj *self, PyObject *args, PyObject *kwds)
{
UNUSED(kwds)
PyObject *bitArrayCapsule;
if (!PyArg_ParseTuple(args, "O", &bitArrayCapsule)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a bit array capsule");
return -1;
}
Py_INCREF(bitArrayCapsule);
self->bitsCapsule = bitArrayCapsule;
return 0;
}
static PyObject* BitArrayPy_size(BitArrayPyObj *self, PyObject *Py_UNUSED(ignored))
{
BitArray* bits = BITS(self->bitsCapsule);
return PyLong_FromLongLong(bits->sizeInBits());
}
static PyObject* BitArrayPy_at(BitArrayPyObj *self, PyObject *args )
{
long long idx;
if (!PyArg_ParseTuple(args, "L", &idx)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a bit index");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
if (bits->sizeInBits() <= idx || idx < 0) {
PyErr_SetString(PyExc_IndexError, "provided bit index is not valid");
return nullptr;
}
return PyBool_FromLong(bits->at(idx));
}
static PyObject* BitArrayPy_resize(BitArrayPyObj *self, PyObject *args )
{
long long size;
if (!PyArg_ParseTuple(args, "L", &size)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a size in bits");
return nullptr;
}
if (size < 0) {
PyErr_SetString(PyExc_IndexError, "negative bit array size is not valid");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
bits->resize(size);
Py_RETURN_NONE;
}
static PyObject* BitArrayPy_set(BitArrayPyObj *self, PyObject *args )
{
long long idx;
int val;
if (!PyArg_ParseTuple(args, "Lp", &idx, &val)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a bit index and value");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
if (bits->sizeInBits() <= idx || idx < 0) {
PyErr_SetString(PyExc_IndexError, "provided bit index is not valid");
return nullptr;
}
bits->set(idx, val);
Py_RETURN_NONE;
}
static PyObject* BitArrayPy_read_bytes(BitArrayPyObj *self, PyObject *args )
{
long long byteOffset;
long long length;
if (!PyArg_ParseTuple(args, "LL", &byteOffset, &length)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a byte offset and a length");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
if (bits->sizeInBytes() <= byteOffset || byteOffset < 0) {
PyErr_SetString(PyExc_IndexError, "provided byte offset is not valid");
return nullptr;
}
QByteArray bytes = bits->readBytes(byteOffset, length);
return PyByteArray_FromStringAndSize(bytes.data(), bytes.length());
}
static PyObject* BitArrayPy_set_bytes(BitArrayPyObj *self, PyObject *args )
{
long long byteOffset;
Py_buffer bytes;
if (!PyArg_ParseTuple(args, "Ly*", &byteOffset, &bytes)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a byte offset (int) and a bytes-like object");
return nullptr;
}
if (byteOffset < 0) {
PyErr_SetString(PyExc_IndexError, "invalid argument - cannot have a negative byte offset");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
bits->setBytes(byteOffset, reinterpret_cast<const char*>(bytes.buf), 0, bytes.len);
Py_RETURN_NONE;
}
static PyObject* BitArrayPy_write_to(BitArrayPyObj *self, PyObject *args )
{
const char *filename;
if (!PyArg_ParseTuple(args, "s", &filename)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a file name");
return nullptr;
}
QFile file(filename);
if (!file.open(QFile::WriteOnly | QFile::Truncate)) {
PyErr_SetString(PyExc_TypeError, "file could not be opened for writing");
return nullptr;
}
BitArray* bits = BITS(self->bitsCapsule);
bits->writeTo(&file);
file.close();
Py_RETURN_NONE;
}
static PyObject* BitArrayPy_read_from(BitArrayPyObj *self, PyObject *args )
{
long long byteOffset;
const char *filename;
if (!PyArg_ParseTuple(args, "Ls", &byteOffset, &filename)) {
PyErr_SetString(PyExc_TypeError, "invalid arguments - requires a byte offset and a file name");
return nullptr;
}
if (byteOffset < 0) {
PyErr_SetString(PyExc_IndexError, "invalid argument - cannot have a negative byte offset");
return nullptr;
}
QFile file(filename);
if (!file.open(QFile::ReadOnly)) {
PyErr_SetString(PyExc_TypeError, "file could not be opened for reading");
return nullptr;
}
QScopedPointer<BitArray> otherBits(new BitArray(&file));
file.close();
BitArray* bits = BITS(self->bitsCapsule);
otherBits->copyBits(0, bits, byteOffset * 8, otherBits->sizeInBits());
Py_RETURN_NONE;
}
static PyMethodDef BitArrayPy_methods[] = {
{ "size", PyCFunction(BitArrayPy_size), METH_NOARGS, nullptr },
{ "at", PyCFunction(BitArrayPy_at), METH_VARARGS, nullptr },
{ "resize", PyCFunction(BitArrayPy_resize), METH_VARARGS, nullptr },
{ "set", PyCFunction(BitArrayPy_set), METH_VARARGS, nullptr },
{ "read_bytes", PyCFunction(BitArrayPy_read_bytes), METH_VARARGS, nullptr },
{ "set_bytes", PyCFunction(BitArrayPy_set_bytes), METH_VARARGS, nullptr },
{ "write_to", PyCFunction(BitArrayPy_write_to), METH_VARARGS, nullptr },
{ "read_from", PyCFunction(BitArrayPy_read_from), METH_VARARGS, nullptr },
{} /* Sentinel */
};
static PyMethodDef ImmutableBitArrayPy_methods[] = {
{ "size", PyCFunction(BitArrayPy_size), METH_NOARGS, nullptr },
{ "at", PyCFunction(BitArrayPy_at), METH_VARARGS, nullptr },
{ "read_bytes", PyCFunction(BitArrayPy_read_bytes), METH_VARARGS, nullptr },
{ "write_to", PyCFunction(BitArrayPy_write_to), METH_VARARGS, nullptr },
{} /* Sentinel */
};
static PyMemberDef ImmutableBitArrayPy_members[] = {
{} /* Sentinel */
};
static PyMemberDef BitArrayPy_members[] = {
{} /* Sentinel */
};
PyTypeObject PyBitArray = {
PyVarObject_HEAD_INIT(nullptr, 0)
"hobbits.BitArray", // const char *tp_name; /* For printing, in format "<module>.<name>" */
sizeof(BitArrayPyObj), // Py_ssize_t tp_basicsize, ; /* For allocation */
0, //tp_itemsize
/* Methods to implement standard operations */
destructor(BitArrayPy_dealloc), // destructor tp_dealloc;
0, // Py_ssize_t tp_vectorcall_offset;
nullptr, // getattrfunc tp_getattr;
nullptr, // setattrfunc tp_setattr;
nullptr, // PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */
nullptr, // reprfunc tp_repr;
/* Method suites for standard classes */
nullptr, // PyNumberMethods *tp_as_number;
nullptr, // PySequenceMethods *tp_as_sequence;
nullptr, // PyMappingMethods *tp_as_mapping;
/* More standard operations (here for binary compatibility) */
nullptr, // hashfunc tp_hash;
nullptr, // ternaryfunc tp_call;
nullptr, // reprfunc tp_str;
nullptr, // getattrofunc tp_getattro;
nullptr, // setattrofunc tp_setattro;
/* Functions to access object as input/output buffer */
nullptr, // PyBufferProcs *tp_as_buffer;
/* Flags to define presence of optional/expanded features */
Py_TPFLAGS_DEFAULT, // unsigned long tp_flags;
"Hobbits Bit Array", // const char *tp_doc; /* Documentation string */
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
nullptr, // traverseproc tp_traverse;
/* delete references to contained objects */
nullptr, // inquiry tp_clear;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
nullptr, // richcmpfunc tp_richcompare;
/* weak reference enabler */
0, // Py_ssize_t tp_weaklistoffset;
/* Iterators */
nullptr, // getiterfunc tp_iter;
nullptr, // iternextfunc tp_iternext;
/* Attribute descriptor and subclassing stuff */
BitArrayPy_methods, // struct PyMethodDef *tp_methods;
BitArrayPy_members, // struct PyMemberDef *tp_members;
nullptr, // struct PyGetSetDef *tp_getset;
nullptr, // struct _typeobject *tp_base;
nullptr, // PyObject *tp_dict;
nullptr, // descrgetfunc tp_descr_get;
nullptr, // descrsetfunc tp_descr_set;
0, // Py_ssize_t tp_dictoffset;
initproc(BitArrayPy_init), // initproc tp_init;
nullptr, // allocfunc tp_alloc;
BitArrayPy_new, // newfunc tp_new;
nullptr, // freefunc tp_free; /* Low-level free-memory routine */
nullptr, // inquiry tp_is_gc; /* For PyObject_IS_GC */
nullptr, // PyObject *tp_bases;
nullptr, // PyObject *tp_mro; /* method resolution order */
nullptr, // PyObject *tp_cache;
nullptr, // PyObject *tp_subclasses;
nullptr, // PyObject *tp_weaklist;
nullptr, // destructor tp_del;
/* Type attribute cache version tag. Added in version 2.6 */
0, // unsigned int tp_version_tag;
nullptr, // destructor tp_finalize;
nullptr, // vectorcallfunc tp_vectorcall;
// Py_DEPRECATED(3.8) int (*tp_print)(PyObject *, FILE *, int);
};
PyTypeObject PyImmutableBitArray = {
PyVarObject_HEAD_INIT(nullptr, 0)
"hobbits.ImmutableBitArray", // const char *tp_name; /* For printing, in format "<module>.<name>" */
sizeof(BitArrayPyObj), // Py_ssize_t tp_basicsize, ; /* For allocation */
0, //tp_itemsize
/* Methods to implement standard operations */
destructor(BitArrayPy_dealloc), // destructor tp_dealloc;
0, // Py_ssize_t tp_vectorcall_offset;
nullptr, // getattrfunc tp_getattr;
nullptr, // setattrfunc tp_setattr;
nullptr, // PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */
nullptr, // reprfunc tp_repr;
/* Method suites for standard classes */
nullptr, // PyNumberMethods *tp_as_number;
nullptr, // PySequenceMethods *tp_as_sequence;
nullptr, // PyMappingMethods *tp_as_mapping;
/* More standard operations (here for binary compatibility) */
nullptr, // hashfunc tp_hash;
nullptr, // ternaryfunc tp_call;
nullptr, // reprfunc tp_str;
nullptr, // getattrofunc tp_getattro;
nullptr, // setattrofunc tp_setattro;
/* Functions to access object as input/output buffer */
nullptr, // PyBufferProcs *tp_as_buffer;
/* Flags to define presence of optional/expanded features */
Py_TPFLAGS_DEFAULT, // unsigned long tp_flags;
"Immutable Hobbits Bit Array", // const char *tp_doc; /* Documentation string */
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
nullptr, // traverseproc tp_traverse;
/* delete references to contained objects */
nullptr, // inquiry tp_clear;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
nullptr, // richcmpfunc tp_richcompare;
/* weak reference enabler */
0, // Py_ssize_t tp_weaklistoffset;
/* Iterators */
nullptr, // getiterfunc tp_iter;
nullptr, // iternextfunc tp_iternext;
/* Attribute descriptor and subclassing stuff */
ImmutableBitArrayPy_methods, // struct PyMethodDef *tp_methods;
ImmutableBitArrayPy_members, // struct PyMemberDef *tp_members;
nullptr, // struct PyGetSetDef *tp_getset;
nullptr, // struct _typeobject *tp_base;
nullptr, // PyObject *tp_dict;
nullptr, // descrgetfunc tp_descr_get;
nullptr, // descrsetfunc tp_descr_set;
0, // Py_ssize_t tp_dictoffset;
initproc(BitArrayPy_init), // initproc tp_init;
nullptr, // allocfunc tp_alloc;
BitArrayPy_new, // newfunc tp_new;
nullptr, // freefunc tp_free; /* Low-level free-memory routine */
nullptr, // inquiry tp_is_gc; /* For PyObject_IS_GC */
nullptr, // PyObject *tp_bases;
nullptr, // PyObject *tp_mro; /* method resolution order */
nullptr, // PyObject *tp_cache;
nullptr, // PyObject *tp_subclasses;
nullptr, // PyObject *tp_weaklist;
nullptr, // destructor tp_del;
/* Type attribute cache version tag. Added in version 2.6 */
0, // unsigned int tp_version_tag;
nullptr, // destructor tp_finalize;
nullptr, // vectorcallfunc tp_vectorcall;
// Py_DEPRECATED(3.8) int (*tp_print)(PyObject *, FILE *, int);
};
|
xuanquang226/nhom2_CDPTUDdidong
|
ontap/OnTapQLNS/app/src/main/java/com/example/quang/ontapqlns/onTapQLNSActivity.java
|
<reponame>xuanquang226/nhom2_CDPTUDdidong
package com.example.quang.ontapqlns;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
public class onTapQLNSActivity extends AppCompatActivity {
ArrayList<QLNS> nhanSu = new ArrayList<QLNS>();
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.on_tap_qlns_layout);
//Ini
final EditText edtHoTen = (EditText) findViewById(R.id.edtHoTen);
final EditText edtSTK = (EditText) findViewById(R.id.edtSoThichKhac);
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdgroup);
RadioButton rbtnDH = (RadioButton) findViewById(R.id.rbtnDH);
RadioButton rbtnCD = (RadioButton) findViewById(R.id.rbtnCD);
RadioButton rbtnTC = (RadioButton) findViewById(R.id.rbtnTC);
final CheckBox chkDS = (CheckBox) findViewById(R.id.chkDS);
final CheckBox chkNN = (CheckBox) findViewById(R.id.chkNN);
Button btnOK = (Button) findViewById(R.id.btnOK);
Button btnCancel = (Button) findViewById(R.id.btnCancel);
ListView listView = (ListView) findViewById(R.id.listviewA);
adapter = new MyAdapter(onTapQLNSActivity.this, R.layout.listview_custom, nhanSu);
listView.setAdapter(adapter);
btnOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int bc = -1;
int id = radioGroup.getCheckedRadioButtonId();
switch (id) {
case R.id.rbtnDH:
bc = 0;
break;
case R.id.rbtnCD:
bc = 1;
break;
case R.id.rbtnTC:
bc = 2;
break;
}
String sothich = " ";
if (chkDS.isChecked()) {
sothich += chkDS.getText().toString() + ",";
}
if (chkNN.isChecked()) {
sothich += chkNN.getText().toString() + ",";
}
sothich += edtSTK.getText().toString();
QLNS nhanvien = new QLNS(edtHoTen.getText().toString(), bc, sothich);
nhanSu.add(nhanvien);
if (!edtHoTen.getText().toString().isEmpty()) {
edtHoTen.setText("");
edtSTK.setText(" ");
radioGroup.clearCheck();
chkDS.setChecked(false);
chkNN.setChecked(false);
}
adapter.notifyDataSetChanged();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
registerForContextMenu(listView);
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.deleteItem:
deleteItem();
return true;
case R.id.updateItem:
updateItem();
return true;
case R.id.saveItem:
saveItem();
return true;
case R.id.loadItem:
loadItem();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.menu_action_bar, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
nhanSu.get(menuInfo.position).setChecked(true);
switch (item.getItemId()) {
case R.id.deleteItem:
deleteItem();
return true;
case R.id.updateItem:
updateItem();
return true;
case R.id.saveItem:
saveItem();
return true;
case R.id.loadItem:
loadItem();
return true;
default:
return super.onContextItemSelected(item);
}
}
public void deleteItem() {
for (int i = 0; i < nhanSu.size(); i ++){
if(nhanSu.get(i).isChecked()){
Database database = new Database(this);
database.deleteItem(nhanSu.get(i));
nhanSu.remove(i);
--i;
}
adapter.notifyDataSetChanged();
}
}
public void updateItem() {
final Dialog dialog = new Dialog(this);
dialog.setTitle("Chỉnh sửa thông tin");
dialog.setContentView(R.layout.dialog_update);
final EditText edtHoTen = (EditText) dialog.findViewById(R.id.edtHoTen);
final EditText edtSTK = (EditText) dialog.findViewById(R.id.edtSoThichKhac);
final RadioGroup radioGroup = (RadioGroup) dialog.findViewById(R.id.rdgroup);
RadioButton rbtnDH = (RadioButton) dialog.findViewById(R.id.rbtnDH);
RadioButton rbtnCD = (RadioButton) dialog.findViewById(R.id.rbtnCD);
RadioButton rbtnTC = (RadioButton) dialog.findViewById(R.id.rbtnTC);
final CheckBox chkDS = (CheckBox) dialog.findViewById(R.id.chkDS);
final CheckBox chkNN = (CheckBox) dialog.findViewById(R.id.chkNN);
Button btnOK = (Button) dialog.findViewById(R.id.btnOK);
Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int bc = -1;
int id = radioGroup.getCheckedRadioButtonId();
switch (id) {
case R.id.rbtnDH:
bc = 0;
break;
case R.id.rbtnCD:
bc = 1;
break;
case R.id.rbtnTC:
bc = 2;
break;
}
String sothich = " ";
if (chkDS.isChecked()) {
sothich += chkDS.getText().toString() + ",";
}
if (chkNN.isChecked()) {
sothich += chkNN.getText().toString() + ",";
}
sothich += edtSTK.getText().toString();
for(QLNS nhanvien:nhanSu){
Database database = new Database(onTapQLNSActivity.this);
database.updateItem(nhanvien, new QLNS(edtHoTen.getText().toString(),bc,sothich));
nhanvien.setHoten(edtHoTen.getText().toString());
nhanvien.setBangcap(bc);
nhanvien.setSothich(sothich);
}
dialog.dismiss();
adapter.notifyDataSetChanged();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
public void saveItem() {
Database database = new Database(this);
database.saveItem(nhanSu);
}
public void loadItem() {
Database database = new Database(this);
nhanSu.clear();
database.loadItem(nhanSu);
adapter.notifyDataSetChanged();
}
}
|
bradfordb-vmware/gpdb
|
gpcontrib/orafce/plvdate.c
|
/*
This code implements one part of functonality of
free available library PL/Vision. Please look www.quest.com
This library isn't optimalized for big numbers, for working
with n days (n > 10000), can be slow (on my P4 31ms).
Original author: <NAME>, 1996 - 2002
PostgreSQL implementation author: <NAME>, 2006-2018
This module is under BSD Licence
*/
#define PLVDATE_VERSION "PostgreSQL PLVdate, version 3.7, October 2018"
#include "postgres.h"
#include "utils/date.h"
#include "utils/builtins.h"
#include <sys/time.h>
#include <stdlib.h>
#include "orafce.h"
#include "builtins.h"
PG_FUNCTION_INFO_V1(plvdate_add_bizdays);
PG_FUNCTION_INFO_V1(plvdate_nearest_bizday);
PG_FUNCTION_INFO_V1(plvdate_next_bizday);
PG_FUNCTION_INFO_V1(plvdate_bizdays_between);
PG_FUNCTION_INFO_V1(plvdate_prev_bizday);
PG_FUNCTION_INFO_V1(plvdate_isbizday);
PG_FUNCTION_INFO_V1(plvdate_set_nonbizday_dow);
PG_FUNCTION_INFO_V1(plvdate_unset_nonbizday_dow);
PG_FUNCTION_INFO_V1(plvdate_set_nonbizday_day);
PG_FUNCTION_INFO_V1(plvdate_unset_nonbizday_day);
PG_FUNCTION_INFO_V1(plvdate_use_easter);
PG_FUNCTION_INFO_V1(plvdate_using_easter);
PG_FUNCTION_INFO_V1(plvdate_use_great_friday);
PG_FUNCTION_INFO_V1(plvdate_using_great_friday);
PG_FUNCTION_INFO_V1(plvdate_include_start);
PG_FUNCTION_INFO_V1(plvdate_including_start);
PG_FUNCTION_INFO_V1(plvdate_default_holidays);
PG_FUNCTION_INFO_V1(plvdate_version);
PG_FUNCTION_INFO_V1(plvdate_days_inmonth);
PG_FUNCTION_INFO_V1(plvdate_isleapyear);
#define CHECK_SEQ_SEARCH(_l, _s) \
do { \
if ((_l) < 0) { \
ereport(ERROR, \
(errcode(ERRCODE_INVALID_DATETIME_FORMAT), \
errmsg("invalid value for %s", (_s)))); \
} \
} while (0)
#define SUNDAY (1 << 0)
#define SATURDAY (1 << 6)
static unsigned char nonbizdays = SUNDAY | SATURDAY;
static bool use_easter = true;
static bool use_great_friday = true;
static bool include_start = true;
static int country_id = -1; /* unknown */
#define MAX_holidays 30
#define MAX_EXCEPTIONS 50
typedef struct {
char day;
char month;
} holiday_desc;
typedef struct {
unsigned char nonbizdays;
bool use_easter;
bool use_great_friday;
holiday_desc *holidays;
int holidays_c;
} cultural_info;
static holiday_desc holidays[MAX_holidays]; /* sorted array */
static DateADT exceptions[MAX_EXCEPTIONS]; /* sorted array */
static int holidays_c = 0;
static int exceptions_c = 0;
static holiday_desc czech_holidays[] = {
{1,1}, // Novy rok
{1,5}, // Svatek prace
{8,5}, // Den osvobozeni
{5,7}, // Den slovanskych verozvestu
{6,7}, // Den upaleni mistra <NAME>
{28,9}, // Den ceske statnosti
{28,10}, // Den vzniku samostatneho ceskoslovenskeho statu
{17,11}, // Den boje za svobodu a demokracii
{24,12}, // <NAME>
{25,12}, // 1. svatek vanocni
{26,12} // 2. svatek vanocni
};
static holiday_desc germany_holidays[] = {
{1,1},{1,5},{25,5},{4,6},{5,6},
{15,8},{3,10},{25,12},{26,12}
};
static holiday_desc poland_holidays[] = {
{1,1},{1,5},{3,5},{15,6},{15,8},
{1,11},{11,11},{25,12},{26,12}
};
static holiday_desc austria_holidays[] = {
{1,1},{6,1},{1,5},{25,5},{4,6},
{5,6},{15,6},{15,8},{26,10},{1,11},
{8,12},{25,12},{26,12}
};
static holiday_desc slovakia_holidays[] = {
{1,1},{6,1},{1,5},{8,5},{5,7},
{29,8},{1,9},{15,9},{1,11},{17,11},
{24,12},{25,12},{26,12}
};
static holiday_desc russian_holidays[] = {
{1,1},{2,1},{3,1},{4,1},{5,1},
{7,1},{23,2},{8,3},{1,5},{9,5},
{12,6}, {4,11}
};
static holiday_desc england_holidays[] = {
{1,1},{2,1},{1,5},{29,5},{28,8},
{25,12},{26,12}
};
static holiday_desc usa_holidays[] = {
{1,1},{16,1},{20,2},{29,5},{4,7},
{4,9},{9,10},{11,11},{23,11},{25,12}
};
cultural_info defaults_ci[] = {
{SUNDAY | SATURDAY, true, true, czech_holidays, 11},
{SUNDAY | SATURDAY, true, true, germany_holidays, 9},
{SUNDAY | SATURDAY, true, false, poland_holidays, 9},
{SUNDAY | SATURDAY, true, false, austria_holidays, 13},
{SUNDAY | SATURDAY, true, true, slovakia_holidays, 13},
{SUNDAY | SATURDAY, false, false, russian_holidays, 12},
{SUNDAY | SATURDAY, true, true, england_holidays, 7},
{SUNDAY | SATURDAY, false, false, usa_holidays, 10}
};
STRING_PTR_FIELD_TYPE states[] = {
"Czech", "Germany", "Poland",
"Austria", "Slovakia", "Russia",
"Gb", "Usa",
NULL,
};
static int
dateadt_comp(const void* a, const void* b)
{
DateADT *_a = (DateADT*)a;
DateADT *_b = (DateADT*)b;
return *_a - *_b;
}
static int
holiday_desc_comp(const void* a, const void* b)
{
int result;
if (0 == (result = ((holiday_desc*)a)->month - ((holiday_desc*)b)->month))
result = ((holiday_desc*)a)->day - ((holiday_desc*)b)->day;
return result;
}
static void
calc_easter_sunday(int year, int* dd, int* mm)
{
int b, d, e, q;
if (year < 1900 || year > 2099)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("date is out of range"),
errdetail("Easter is defined only for years between 1900 and 2099")));
b = 255 - 11 * (year % 19);
d = ((b - 21) % 30) + 21;
if (d > 38) d -= 1;
e = (year + year/4 + d + 1) % 7;
q = d + 7 - e;
if (q < 32)
{
*dd = q; *mm = 3;
}
else
{
*dd = q - 31; *mm = 4;
}
}
/*
* returns true, when day d is any easter holiday.
*
*/
static bool
easter_holidays(DateADT day, int y, int m)
{
if (use_great_friday || use_easter)
{
if (m == 3 || m == 4)
{
int easter_sunday_day;
int easter_sunday_month;
int easter_sunday;
calc_easter_sunday(y, &easter_sunday_day, &easter_sunday_month);
easter_sunday = date2j(y, easter_sunday_month, easter_sunday_day) - POSTGRES_EPOCH_JDATE;
if (use_easter && (day == easter_sunday || day == easter_sunday + 1))
return true;
if (use_great_friday && day == easter_sunday - 2)
{
/* Great Friday is introduced in Czech Republic in 2016 */
if (country_id == 0)
{
if (y >= 2016)
return true;
}
else
return true;
}
}
}
return false;
}
static DateADT
ora_add_bizdays(DateADT day, int days)
{
int d, dx;
int y, m, auxd;
holiday_desc hd;
d = j2day(day+POSTGRES_EPOCH_JDATE);
dx = days > 0? 1 : -1;
while (days != 0)
{
d = (d+dx) % 7;
d = (d < 0) ? 6:d;
day += dx;
if ((1 << d) & nonbizdays)
continue;
if (NULL != bsearch(&day, exceptions, exceptions_c,
sizeof(DateADT), dateadt_comp))
continue;
j2date(day + POSTGRES_EPOCH_JDATE, &y, &m, &auxd);
hd.day = (char) auxd;
hd.month = (char) m;
if (easter_holidays(day, y, m))
continue;
if (NULL != bsearch(&hd, holidays, holidays_c,
sizeof(holiday_desc), holiday_desc_comp))
continue;
days -= dx;
}
return day;
}
static int
ora_diff_bizdays(DateADT day1, DateADT day2)
{
int d, days;
int y, m, auxd;
holiday_desc hd;
int loops = 0;
bool start_is_bizday = false;
DateADT aux_day;
if (day1 > day2)
{
aux_day = day1;
day1 = day2; day2 = aux_day;
}
/* d is incremented on start of cycle, so now I have to decrease one */
d = j2day(day1+POSTGRES_EPOCH_JDATE-1);
days = 0;
while (day1 <= day2)
{
loops++;
day1 += 1;
d = (d+1) % 7;
if ((1 << d) & nonbizdays)
continue;
if (NULL != bsearch(&day1, exceptions, exceptions_c,
sizeof(DateADT), dateadt_comp))
continue;
j2date(day1 + POSTGRES_EPOCH_JDATE, &y, &m, &auxd);
hd.day = (char) auxd;
hd.month = (char) m;
if (easter_holidays(day1, y, m))
continue;
if (NULL != bsearch(&hd, holidays, holidays_c,
sizeof(holiday_desc), holiday_desc_comp))
continue;
/* now the day have to be bizday, remember if first day was bizday */
if (loops == 1)
start_is_bizday = true;
days += 1;
}
/*
* decrease result when first day was bizday, but we don't want
* calculate first day.
*/
if ( start_is_bizday && !include_start && days > 0)
days -= 1;
return days;
}
/****************************************************************
* PLVdate.add_bizdays
*
* Syntax:
* FUNCTION add_bizdays(IN dt DATE, IN days int) RETURNS DATE;
*
* Purpouse:
* Get the date created by adding <n> business days to a date
*
****************************************************************/
Datum
plvdate_add_bizdays (PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
int days = PG_GETARG_INT32(1);
PG_RETURN_DATEADT(ora_add_bizdays(day,days));
}
/****************************************************************
* PLVdate.nearest_bizday
*
* Syntax:
* FUNCTION nearest_bizday(IN dt DATE) RETURNS DATE;
*
* Purpouse:
* Get the nearest business date to a given date, user defined
*
****************************************************************/
Datum
plvdate_nearest_bizday (PG_FUNCTION_ARGS)
{
DateADT dt = PG_GETARG_DATEADT(0);
DateADT d1, d2, res;
d1 = ora_add_bizdays(dt, -1);
d2 = ora_add_bizdays(dt, 1);
if ((dt - d1) > (d2 - dt))
res = d2;
else
res = d1;
PG_RETURN_DATEADT(res);
}
/****************************************************************
* PLVdate.next_bizday
*
* Syntax:
* FUNCTION next_bizday(IN dt DATE) RETURNS DATE;
*
* Purpouse:
* Get the next business date from a given date, user defined
*
****************************************************************/
Datum
plvdate_next_bizday (PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
PG_RETURN_DATEADT(ora_add_bizdays(day,1));
}
/****************************************************************
* PLVdate.bizdays_between
*
* Syntax:
* FUNCTION bizdays_between(IN dt1 DATE, IN dt2 DATE)
* RETURNS int;
*
* Purpouse:
* Get the number of business days between two dates
*
****************************************************************/
Datum
plvdate_bizdays_between (PG_FUNCTION_ARGS)
{
DateADT day1 = PG_GETARG_DATEADT(0);
DateADT day2 = PG_GETARG_DATEADT(1);
PG_RETURN_INT32(ora_diff_bizdays(day1,day2));
}
/****************************************************************
* PLVdate.prev_bizday
*
* Syntax:
* FUNCTION prev_bizday(IN dt DATE) RETURNS date;
*
* Purpouse:
* Get the previous business date from a given date, user
* defined
*
****************************************************************/
Datum
plvdate_prev_bizday (PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
PG_RETURN_DATEADT(ora_add_bizdays(day,-1));
}
/****************************************************************
* PLVdate.isbizday
*
* Syntax:
* FUNCTION isbizday(IN dt DATE) RETURNS bool;
*
* Purpouse:
* Call this function to determine if a date is a business day
*
****************************************************************/
Datum
plvdate_isbizday (PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
int y, m, d;
holiday_desc hd;
if (0 != ((1 << j2day(day+POSTGRES_EPOCH_JDATE)) & nonbizdays))
return false;
if (NULL != bsearch(&day, exceptions, exceptions_c,
sizeof(DateADT), dateadt_comp))
return false;
j2date(day + POSTGRES_EPOCH_JDATE, &y, &m, &d);
hd.month = m; hd.day = d;
if (easter_holidays(day, y, m))
return false;
PG_RETURN_BOOL (NULL == bsearch(&hd, holidays, holidays_c,
sizeof(holiday_desc), holiday_desc_comp));
}
/****************************************************************
* PLVdate.set_nonbizday
*
* Syntax:
* FUNCTION set_nonbizday(IN dow VARCHAR) RETURNS void;
*
* Purpouse:
* Set day of week as non bussines day
*
****************************************************************/
Datum
plvdate_set_nonbizday_dow (PG_FUNCTION_ARGS)
{
unsigned char check;
text *day_txt = PG_GETARG_TEXT_PP(0);
int d = ora_seq_search(VARDATA_ANY(day_txt), ora_days, VARSIZE_ANY_EXHDR(day_txt));
CHECK_SEQ_SEARCH(d, "DAY/Day/day");
check = nonbizdays | (1 << d);
if (check == 0x7f)
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("nonbizday registeration error"),
errdetail("Constraint violation."),
errhint("One day in week have to be bizday.")));
nonbizdays = nonbizdays | (1 << d);
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.unset_nonbizday
*
* Syntax:
* FUNCTION unset_nonbizday(IN dow VARCHAR) RETURNS void;
*
* Purpouse:
* Unset day of week as non bussines day
*
****************************************************************/
Datum
plvdate_unset_nonbizday_dow (PG_FUNCTION_ARGS)
{
text *day_txt = PG_GETARG_TEXT_PP(0);
int d = ora_seq_search(VARDATA_ANY(day_txt), ora_days, VARSIZE_ANY_EXHDR(day_txt));
CHECK_SEQ_SEARCH(d, "DAY/Day/day");
nonbizdays = (nonbizdays | (1 << d)) ^ (1 << d);
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.set_nonbizday
*
* Syntax:
* FUNCTION set_nonbizday(IN day DATE) RETURNS void;
* FUNCTION set_nonbizday(IN day DATE, IN repeat := false BOOL) RETURNS void;
*
* Purpouse:
* Set day as non bussines day, second arg specify year's
* periodicity
*
****************************************************************/
Datum
plvdate_set_nonbizday_day (PG_FUNCTION_ARGS)
{
DateADT arg1 = PG_GETARG_DATEADT(0);
bool arg2 = PG_GETARG_BOOL(1);
int y, m, d;
holiday_desc hd;
if (arg2)
{
if (holidays_c == MAX_holidays)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("nonbizday registeration error"),
errdetail("Too much registered nonbizdays."),
errhint("Increase MAX_holidays in 'plvdate.c'.")));
j2date(arg1 + POSTGRES_EPOCH_JDATE, &y, &m, &d);
hd.month = m; hd.day = d;
if (NULL != bsearch(&hd, holidays, holidays_c, sizeof(holiday_desc), holiday_desc_comp))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("nonbizday registeration error"),
errdetail("Date is registered.")));
holidays[holidays_c].month = m;
holidays[holidays_c].day = d;
holidays_c += 1;
qsort(holidays, holidays_c, sizeof(holiday_desc), holiday_desc_comp);
}
else
{
if (exceptions_c == MAX_EXCEPTIONS)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("nonbizday registeration error"),
errdetail("Too much registered nonrepeated nonbizdays."),
errhint("Increase MAX_EXCEPTIONS in 'plvdate.c'.")));
if (NULL != bsearch(&arg1, exceptions, exceptions_c, sizeof(DateADT), dateadt_comp))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("nonbizday registeration error"),
errdetail("Date is registered.")));
exceptions[exceptions_c++] = arg1;
qsort(exceptions, exceptions_c, sizeof(DateADT), dateadt_comp);
}
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.unset_nonbizday
*
* Syntax:
* FUNCTION unset_nonbizday(IN day DATE) RETURNS void;
* FUNCTION unset_nonbizday(IN day DATE, IN repeat := false BOOL) RETURNS void;
*
* Purpouse:
* Unset day as non bussines day, second arg specify year's
* periodicity
*
****************************************************************/
Datum
plvdate_unset_nonbizday_day (PG_FUNCTION_ARGS)
{
DateADT arg1 = PG_GETARG_DATEADT(0);
bool arg2 = PG_GETARG_BOOL(1);
int y, m, d;
bool found = false;
int i;
if (arg2)
{
j2date(arg1 + POSTGRES_EPOCH_JDATE, &y, &m, &d);
for (i = 0; i < holidays_c; i++)
{
if (!found && holidays[i].month == m && holidays[i].day == d)
found = true;
else if (found)
{
holidays[i-1].month = holidays[i].month;
holidays[i-1].day = holidays[i].day;
}
}
if (found)
holidays_c -= 1;
}
else
{
for (i = 0; i < exceptions_c; i++)
if (!found && exceptions[i] == arg1)
found = true;
else if (found)
exceptions[i-1] = exceptions[i];
if (found)
exceptions_c -= 1;
}
if (!found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("nonbizday unregisteration error"),
errdetail("Nonbizday not found.")));
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.use_easter
*
* Syntax:
* FUNCTION unuse_easter() RETURNS void;
* FUNCTION use_easter() RETURNS void;
* FUNCTION use_easter(IN bool) RETURNS void
*
* Purpouse:
* Have to use easter as nonbizday?
*
****************************************************************/
Datum
plvdate_use_easter (PG_FUNCTION_ARGS)
{
use_easter = PG_GETARG_BOOL(0);
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.using_easter
*
* Syntax:
* FUNCTION using_easter() RETURNS bool
*
* Purpouse:
* Use it easter as nonbizday?
*
****************************************************************/
Datum
plvdate_using_easter (PG_FUNCTION_ARGS)
{
PG_RETURN_BOOL(use_easter);
}
/****************************************************************
* PLVdate.use_great_friday
*
* Syntax:
* FUNCTION unuse_great_friday() RETURNS void;
* FUNCTION use_great_friday() RETURNS void;
* FUNCTION use_great_friday(IN bool) RETURNS void
*
* Purpouse:
* Have to use great_friday as nonbizday?
*
****************************************************************/
Datum
plvdate_use_great_friday (PG_FUNCTION_ARGS)
{
use_great_friday = PG_GETARG_BOOL(0);
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.using_great_friday
*
* Syntax:
* FUNCTION using_great_friday() RETURNS bool
*
* Purpouse:
* Use it great friday as nonbizday?
*
****************************************************************/
Datum
plvdate_using_great_friday (PG_FUNCTION_ARGS)
{
PG_RETURN_BOOL(use_great_friday);
}
/****************************************************************
* PLVdate.include_start
*
* Syntax:
* FUNCTION include_start() RETURNS void;
* FUNCTION noinclude_start() RETURNS void;
* FUNCTION include_start(IN bool) RETURNS void
*
* Purpouse:
* Have to include current day in bizdays_between calculation?
*
****************************************************************/
Datum
plvdate_include_start (PG_FUNCTION_ARGS)
{
include_start = PG_GETARG_BOOL(0);
PG_RETURN_VOID();
}
/****************************************************************
* PLVdate.including_start
*
* Syntax:
* FUNCTION including_start() RETURNS bool
*
* Purpouse:
* include current day in bizdays_between calculation?
*
****************************************************************/
Datum
plvdate_including_start (PG_FUNCTION_ARGS)
{
PG_RETURN_BOOL(include_start);
}
/*
* Load some national configurations
*
*/
Datum
plvdate_default_holidays (PG_FUNCTION_ARGS)
{
text *country = PG_GETARG_TEXT_PP(0);
country_id = ora_seq_search(VARDATA_ANY(country), states, VARSIZE_ANY_EXHDR(country));
CHECK_SEQ_SEARCH(country_id, "STATE/State/state");
nonbizdays = defaults_ci[country_id].nonbizdays;
use_easter = defaults_ci[country_id].use_easter;
use_great_friday = defaults_ci[country_id].use_great_friday;
exceptions_c = 0;
holidays_c = defaults_ci[country_id].holidays_c;
memcpy(holidays, defaults_ci[country_id].holidays, holidays_c*sizeof(holiday_desc));
PG_RETURN_VOID();
}
/*
* helper maintaince functions
*/
Datum
plvdate_version (PG_FUNCTION_ARGS)
{
PG_RETURN_CSTRING(PLVDATE_VERSION);
}
/****************************************************************
* PLVdate.days_inmonth
*
* Syntax:
* FUNCTION days_inmonth(date) RETURNS integer
*
* Purpouse:
* Returns month's length
*
****************************************************************/
Datum
plvdate_days_inmonth(PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
int result;
int y, m, d;
j2date(day + POSTGRES_EPOCH_JDATE, &y, &m, &d);
result = date2j(y, m+1, 1) - date2j(y, m, 1);
PG_RETURN_INT32(result);
}
/****************************************************************
* PLVdate.isleapyear
*
* Syntax:
* FUNCTION isleapyear() RETURNS bool
*
* Purpouse:
* Returns true, if year is leap
*
****************************************************************/
Datum
plvdate_isleapyear(PG_FUNCTION_ARGS)
{
DateADT day = PG_GETARG_DATEADT(0);
int y, m, d;
bool result;
j2date(day + POSTGRES_EPOCH_JDATE, &y, &m, &d);
result = ((( y % 4) == 0) && ((y % 100) != 0)) || ((y / 400) == 0);
PG_RETURN_BOOL(result);
}
/****************************************************************
* PLVdate.set_nonbizdays
*
* Syntax:
* FUNCTION set_nonbizdays(IN dow bool[7]) RETURNS void;
*
* Purpouse:
* Set pattern bussines/nonbussines days in week
*
****************************************************************/
/****************************************************************
* PLVdate.set_nonbizday
*
* Syntax:
* FUNCTION set_nonbizdays(IN days DATE[]) RETURNS void;
* FUNCTION set_nonbizdays(IN days DATE[], IN repeat := false BOOL) RETURNS void;
*
* Purpouse:
* Set days as non bussines day, second arg specify year's
* periodicity
*
****************************************************************/
/****************************************************************
* PLVdate.display
*
* Syntax:
* FUNCTION display() RETURNS void;
*
* Purpouse:
* Show current calendar
*
****************************************************************/
|
Unk3wn/AdvancedSoftwareEngineering
|
Software Project/X - Legacy - Historisch Gewachsen - Backend - Spring/src/main/java/de/dhbw/ase/whiskey_o_clock/helper/DTOMapper.java
|
package de.dhbw.ase.whiskey_o_clock.helper;
import de.dhbw.ase.whiskey_o_clock.model.*;
import de.dhbw.ase.whiskey_o_clock.model.builder.BottleBuilder;
import de.dhbw.ase.whiskey_o_clock.repository.BottleRepository;
import de.dhbw.ase.whiskey_o_clock.repository.CountryRepository;
import de.dhbw.ase.whiskey_o_clock.repository.ManufacturerRepository;
import de.dhbw.ase.whiskey_o_clock.repository.SeriesRepository;
import javax.validation.ValidationException;
import java.util.LinkedList;
import java.util.List;
public class DTOMapper {
private DTOMapper() throws InstantiationException {
throw new InstantiationException("Utility Class should not be instanciated!");
}
// Hier sollte man auf ein Framework zurückgeifen, wenn mehr Entitys verwendet werden sollen!
public static CountryDTO convertCountryToDTO(Country country) {
return new CountryDTO(country.getAbbreviation(), country.getName());
}
public static Country convertDTOToCountry(CountryDTO countryDTO) {
return new Country(countryDTO.getCountryAbbreviation(), countryDTO.getCountryName());
}
public static void updateCountryWithDTO(Country country, CountryDTO countryDTO) {
if (countryDTO.getCountryName() != null) {
country.setName(countryDTO.getCountryName());
}
if (countryDTO.getCountryAbbreviation() != null) {
country.setAbbreviation(countryDTO.getCountryAbbreviation());
}
}
public static void updateManufacturerWithDTO(CountryRepository countryRepository, Manufacturer manufacturer, ManufacturerDTO manufacturerDTO) {
if (manufacturerDTO.getManufacturerName() != null) {
manufacturer.setName(manufacturerDTO.getManufacturerName());
}
if (manufacturerDTO.getOriginCountryAbbreviation() != null) {
manufacturer.setOriginCountry(countryRepository.getCountryByAbbreviation(manufacturerDTO.getOriginCountryAbbreviation()));
}
}
public static BottleDTO convertBottleToDTO(Bottle bottle) {
if (bottle.getSeries() != null) {
return new BottleDTO(bottle.getLabel(), bottle.getPrice(), bottle.getYearOfManufacture(), bottle.getManufacturer().getUuid(), bottle.isForSale(), bottle.isFavorite(), bottle.isUnsaleable(), bottle.getSeries().getUuid());
} else {
return new BottleDTO(bottle.getLabel(), bottle.getPrice(), bottle.getYearOfManufacture(), bottle.getManufacturer().getUuid(), bottle.isForSale(), bottle.isFavorite(), bottle.isUnsaleable(), null);
}
}
public static Bottle convertDTOToBottle(ManufacturerRepository manufacturerRepository, SeriesRepository seriesRepository, BottleDTO bottleDTO) {
if (null != bottleDTO.getLabel()) {
BottleBuilder bottleBuilder = new BottleBuilder(bottleDTO.getLabel());
if (null != bottleDTO.getPrice())
bottleBuilder.price(bottleDTO.getPrice());
if (null != bottleDTO.getYearOfManufacture())
bottleBuilder.yearOfManufacture(bottleDTO.getYearOfManufacture());
if (null != bottleDTO.getManufacturer())
bottleBuilder.manufacturer(manufacturerRepository.getManufacturerByUuid(bottleDTO.getManufacturer()));
if (bottleDTO.isForSale())
bottleBuilder.forSale(bottleDTO.isForSale());
if (bottleDTO.isFavorite())
bottleBuilder.favorite(bottleDTO.isFavorite());
if (bottleDTO.isUnsaleable())
bottleBuilder.unsaleable(bottleDTO.isUnsaleable());
if (null != bottleDTO.getSeries())
bottleBuilder.series(seriesRepository.getSeriesByUuid(bottleDTO.getSeries()));
return bottleBuilder.build();
}
throw new ValidationException("Label not given!");
}
public static void updateBottleWithDTO(ManufacturerRepository manufacturerRepository, SeriesRepository seriesRepository, BottleRepository bottleRepository, Bottle bottle, BottleDTO bottleDTO) {
if (null != bottle.getLabel() && !bottle.getLabel().equals(bottleDTO.getLabel())) {
bottle.setLabel(bottleDTO.getLabel());
}
if (null != bottleDTO.getPrice() && bottle.getPrice() == bottleDTO.getPrice()) {
bottle.setPrice(bottleDTO.getPrice());
}
if (null != bottleDTO.getYearOfManufacture() && bottle.getYearOfManufacture() == bottleDTO.getYearOfManufacture()) {
bottle.setYearOfManufacture(bottleDTO.getYearOfManufacture());
}
if (!bottle.getManufacturer().equals(manufacturerRepository.getManufacturerByUuid(bottleDTO.getManufacturer()))) {
bottle.setManufacturer(manufacturerRepository.getManufacturerByUuid(bottleDTO.getManufacturer()));
} else if (null == bottleDTO.getManufacturer()) {
bottle.setManufacturer(null);
}
if (bottle.isForSale() != bottleDTO.isForSale()) {
bottle.setForSale(bottleDTO.isForSale());
}
if (bottle.isFavorite() != bottleDTO.isFavorite()) {
bottle.setFavorite(bottleDTO.isFavorite());
}
if (bottle.isUnsaleable() != bottleDTO.isUnsaleable()) {
bottle.setUnsaleable(bottleDTO.isUnsaleable());
}
if (null == bottleDTO.getSeries()) {
bottle.setSeries(null);
} else if (null != bottleDTO.getSeries() || null != bottle.getSeries() && bottle.getSeries() != seriesRepository.getSeriesByUuid(bottleDTO.getSeries())) {
bottle.setSeries(seriesRepository.getSeriesByUuid(bottleDTO.getSeries()));
}
bottleRepository.save(bottle);
}
public static SeriesDTO convertSeriesToDTO(Series series) {
List<BottleDTO> bottleDTOList = new LinkedList<>();
for (Bottle bottle : series.getBottleList()) {
bottleDTOList.add(convertBottleToDTO(bottle));
}
return new SeriesDTO(series.getLabel(), bottleDTOList);
}
public static Series convertDTOToSeries(BottleRepository bottleRepository, ManufacturerRepository manufacturerRepository, SeriesDTO seriesDTO) {
if (null != seriesDTO.getSeriesBottleList()) {
List<Bottle> bottleList = new LinkedList<>();
for (BottleDTO bottleDTO : seriesDTO.getSeriesBottleList()) {
// Hierbei wird ausgegangen, dass beim Selben Manufacturer keine zwei Whiskey's existieren, die den selben Namen haben
bottleList.add(bottleRepository.getFirstBottleByLabelAndManufacturer(bottleDTO.getLabel(), manufacturerRepository.getManufacturerByUuid(bottleDTO.getManufacturer())));
}
return new Series(seriesDTO.getSeriesLabel(), bottleList);
} else {
return new Series(seriesDTO.getSeriesLabel());
}
}
}
|
restato/bunnybook
|
backend/comment/api.py
|
<filename>backend/comment/api.py
import datetime as dt
from typing import List, Optional
from uuid import UUID
from fastapi import Depends, Query, BackgroundTasks
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
from starlette import status
from auth.models import User
from auth.security import get_user, get_optional_user
from comment.models import Comment
from comment.notifications import CommentNotificationService
from comment.schemas import CommentCreateRead, CommentCreate, CommentRead
from comment.service import CommentService
from common.injection import on
from common.rate_limiter import RateLimitTo
from post.api_utils import PostApiUtils
from post.service import PostService
comment_router = InferringRouter()
@cbv(comment_router)
class CommentApi:
_service: CommentService = Depends(on(CommentService))
_post_service: PostService = Depends(on(PostService))
_post_api_utils: PostApiUtils = Depends(on(PostApiUtils))
_notifications: CommentNotificationService = Depends(
on(CommentNotificationService))
@comment_router.post(
"/posts/{post_id}/comments",
response_model=CommentCreateRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(RateLimitTo(times=5, seconds=1))])
async def create_comment(
self,
post_id: UUID,
comment_in: CommentCreate,
background_tasks: BackgroundTasks,
user: User = Depends(get_user)):
"""Create a new comment under a post."""
await self._post_api_utils.check_user_can_see_post(user, post_id)
new_comment = await self._service.create_comment(
Comment(**comment_in.dict(),
post_id=post_id,
profile_id=user.id,
username=user.username))
background_tasks.add_task(
self._notifications.create_comment_notification,
post_id, user.id, user.username, new_comment.content)
return new_comment
@comment_router.get(
"/posts/{post_id}/comments",
response_model=List[CommentRead],
dependencies=[Depends(RateLimitTo(times=5, seconds=1))])
async def get_comments(
self,
post_id: UUID,
older_than: Optional[dt.datetime] = Query(None),
limit: Optional[int] = Query(10, ge=1, le=20),
user: Optional[User] = Depends(get_optional_user)):
"""Get comments under a post."""
await self._post_api_utils.check_user_can_see_post(user, post_id)
return await self._service.find_comments_by_post_id(
post_id, older_than, limit)
|
Keneral/asystem
|
core/init/init.cpp
|
<reponame>Keneral/asystem
/*
* Copyright (C) 2008 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.
*/
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <libgen.h>
#include <paths.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <mtd/mtd-user.h>
#include <selinux/selinux.h>
#include <selinux/label.h>
#include <selinux/android.h>
#include <android-base/file.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <cutils/android_reboot.h>
#include <cutils/fs.h>
#include <cutils/iosched_policy.h>
#include <cutils/list.h>
#include <cutils/sockets.h>
#include <private/android_filesystem_config.h>
#include <memory>
#include "action.h"
#include "bootchart.h"
#include "devices.h"
#include "import_parser.h"
#include "init.h"
#include "init_parser.h"
#include "keychords.h"
#include "log.h"
#include "property_service.h"
#include "service.h"
#include "signal_handler.h"
#include "ueventd.h"
#include "util.h"
#include "watchdogd.h"
struct selabel_handle *sehandle;
struct selabel_handle *sehandle_prop;
static int property_triggers_enabled = 0;
static char qemu[32];
int have_console;
std::string console_name = "/dev/console";
static time_t process_needs_restart;
const char *ENV[32];
bool waiting_for_exec = false;
static int epoll_fd = -1;
void register_epoll_handler(int fd, void (*fn)()) {
epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = reinterpret_cast<void*>(fn);
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
ERROR("epoll_ctl failed: %s\n", strerror(errno));
}
}
/* add_environment - add "key=value" to the current environment */
int add_environment(const char *key, const char *val)
{
size_t n;
size_t key_len = strlen(key);
/* The last environment entry is reserved to terminate the list */
for (n = 0; n < (ARRAY_SIZE(ENV) - 1); n++) {
/* Delete any existing entry for this key */
if (ENV[n] != NULL) {
size_t entry_key_len = strcspn(ENV[n], "=");
if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
free((char*)ENV[n]);
ENV[n] = NULL;
}
}
/* Add entry if a free slot is available */
if (ENV[n] == NULL) {
char* entry;
asprintf(&entry, "%s=%s", key, val);
ENV[n] = entry;
return 0;
}
}
ERROR("No env. room to store: '%s':'%s'\n", key, val);
return -1;
}
void property_changed(const char *name, const char *value)
{
if (property_triggers_enabled)
ActionManager::GetInstance().QueuePropertyTrigger(name, value);
}
static void restart_processes()
{
process_needs_restart = 0;
ServiceManager::GetInstance().
ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
s->RestartIfNeeded(process_needs_restart);
});
}
void handle_control_message(const std::string& msg, const std::string& name) {
Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
if (svc == nullptr) {
ERROR("no such service '%s'\n", name.c_str());
return;
}
if (msg == "start") {
svc->Start();
} else if (msg == "stop") {
svc->Stop();
} else if (msg == "restart") {
svc->Restart();
} else {
ERROR("unknown control msg '%s'\n", msg.c_str());
}
}
static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
Timer t;
NOTICE("Waiting for %s...\n", COLDBOOT_DONE);
// Any longer than 1s is an unreasonable length of time to delay booting.
// If you're hitting this timeout, check that you didn't make your
// sepolicy regular expressions too expensive (http://b/19899875).
if (wait_for_file(COLDBOOT_DONE, 1)) {
ERROR("Timed out waiting for %s\n", COLDBOOT_DONE);
}
NOTICE("Waiting for %s took %.2fs.\n", COLDBOOT_DONE, t.duration());
return 0;
}
/*
* Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
* by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
* Does nothing if Hardware RNG is not present.
*
* Since we don't yet trust the quality of Hardware RNG, these bytes are not
* mixed into the primary pool of Linux RNG and the entropy estimate is left
* unmodified.
*
* If the HW RNG device /dev/hw_random is present, we require that at least
* 512 bytes read from it are written into Linux RNG. QA is expected to catch
* devices/configurations where these I/O operations are blocking for a long
* time. We do not reboot or halt on failures, as this is a best-effort
* attempt.
*/
static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
{
int result = -1;
int hwrandom_fd = -1;
int urandom_fd = -1;
char buf[512];
ssize_t chunk_size;
size_t total_bytes_written = 0;
hwrandom_fd = TEMP_FAILURE_RETRY(
open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
if (hwrandom_fd == -1) {
if (errno == ENOENT) {
ERROR("/dev/hw_random not found\n");
/* It's not an error to not have a Hardware RNG. */
result = 0;
} else {
ERROR("Failed to open /dev/hw_random: %s\n", strerror(errno));
}
goto ret;
}
urandom_fd = TEMP_FAILURE_RETRY(
open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
if (urandom_fd == -1) {
ERROR("Failed to open /dev/urandom: %s\n", strerror(errno));
goto ret;
}
while (total_bytes_written < sizeof(buf)) {
chunk_size = TEMP_FAILURE_RETRY(
read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
if (chunk_size == -1) {
ERROR("Failed to read from /dev/hw_random: %s\n", strerror(errno));
goto ret;
} else if (chunk_size == 0) {
ERROR("Failed to read from /dev/hw_random: EOF\n");
goto ret;
}
chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
if (chunk_size == -1) {
ERROR("Failed to write to /dev/urandom: %s\n", strerror(errno));
goto ret;
}
total_bytes_written += chunk_size;
}
INFO("Mixed %zu bytes from /dev/hw_random into /dev/urandom",
total_bytes_written);
result = 0;
ret:
if (hwrandom_fd != -1) {
close(hwrandom_fd);
}
if (urandom_fd != -1) {
close(urandom_fd);
}
return result;
}
static void security_failure() {
ERROR("Security failure; rebooting into recovery mode...\n");
android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
while (true) { pause(); } // never reached
}
#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
/* __attribute__((unused)) due to lack of mips support: see mips block
* in set_mmap_rnd_bits_action */
static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) {
std::string path;
if (compat) {
path = MMAP_RND_COMPAT_PATH;
} else {
path = MMAP_RND_PATH;
}
std::ifstream inf(path, std::fstream::in);
if (!inf) {
return false;
}
while (start >= min) {
// try to write out new value
std::string str_val = std::to_string(start);
std::ofstream of(path, std::fstream::out);
if (!of) {
return false;
}
of << str_val << std::endl;
of.close();
// check to make sure it was recorded
inf.seekg(0);
std::string str_rec;
inf >> str_rec;
if (str_val.compare(str_rec) == 0) {
break;
}
start--;
}
inf.close();
return (start >= min);
}
/*
* Set /proc/sys/vm/mmap_rnd_bits and potentially
* /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
* Returns -1 if unable to set these to an acceptable value. Apply
* upstream patch-sets https://lkml.org/lkml/2015/12/21/337 and
* https://lkml.org/lkml/2016/2/4/831 to enable this.
*/
static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
{
int ret = -1;
/* values are arch-dependent */
#if defined(__aarch64__)
/* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */
if (set_mmap_rnd_bits_min(33, 24, false)
&& set_mmap_rnd_bits_min(16, 16, true)) {
ret = 0;
}
#elif defined(__x86_64__)
/* x86_64 supports 28 - 32 bits */
if (set_mmap_rnd_bits_min(32, 32, false)
&& set_mmap_rnd_bits_min(16, 16, true)) {
ret = 0;
}
#elif defined(__arm__) || defined(__i386__)
/* check to see if we're running on 64-bit kernel */
bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
/* supported 32-bit architecture must have 16 bits set */
if (set_mmap_rnd_bits_min(16, 16, h64)) {
ret = 0;
}
#elif defined(__mips__) || defined(__mips64__)
// TODO: add mips support b/27788820
ret = 0;
#else
ERROR("Unknown architecture\n");
#endif
#ifdef __BRILLO__
// TODO: b/27794137
ret = 0;
#endif
if (ret == -1) {
ERROR("Unable to set adequate mmap entropy value!\n");
security_failure();
}
return ret;
}
static int keychord_init_action(const std::vector<std::string>& args)
{
keychord_init();
return 0;
}
static int console_init_action(const std::vector<std::string>& args)
{
std::string console = property_get("ro.boot.console");
if (!console.empty()) {
console_name = "/dev/" + console;
}
int fd = open(console_name.c_str(), O_RDWR | O_CLOEXEC);
if (fd >= 0)
have_console = 1;
close(fd);
fd = open("/dev/tty0", O_WRONLY | O_CLOEXEC);
if (fd >= 0) {
const char *msg;
msg = "\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n" // console is 40 cols x 30 lines
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
" A N D R O I D ";
write(fd, msg, strlen(msg));
close(fd);
}
return 0;
}
static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
if (key.empty()) return;
if (for_emulator) {
// In the emulator, export any kernel option with the "ro.kernel." prefix.
property_set(android::base::StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
return;
}
if (key == "qemu") {
strlcpy(qemu, value.c_str(), sizeof(qemu));
} else if (android::base::StartsWith(key, "androidboot.")) {
property_set(android::base::StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(),
value.c_str());
}
}
static void export_oem_lock_status() {
if (property_get("ro.oem_unlock_supported") != "1") {
return;
}
std::string value = property_get("ro.boot.verifiedbootstate");
if (!value.empty()) {
property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
}
}
static void export_kernel_boot_props() {
struct {
const char *src_prop;
const char *dst_prop;
const char *default_value;
} prop_map[] = {
{ "ro.boot.serialno", "ro.serialno", "", },
{ "ro.boot.mode", "ro.bootmode", "unknown", },
{ "ro.boot.baseband", "ro.baseband", "unknown", },
{ "ro.boot.bootloader", "ro.bootloader", "unknown", },
{ "ro.boot.hardware", "ro.hardware", "unknown", },
{ "ro.boot.revision", "ro.revision", "0", },
};
for (size_t i = 0; i < ARRAY_SIZE(prop_map); i++) {
std::string value = property_get(prop_map[i].src_prop);
property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
}
}
static void process_kernel_dt() {
static const char android_dir[] = "/proc/device-tree/firmware/android";
std::string file_name = android::base::StringPrintf("%s/compatible", android_dir);
std::string dt_file;
android::base::ReadFileToString(file_name, &dt_file);
if (!dt_file.compare("android,firmware")) {
ERROR("firmware/android is not compatible with 'android,firmware'\n");
return;
}
std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(android_dir), closedir);
if (!dir) return;
struct dirent *dp;
while ((dp = readdir(dir.get())) != NULL) {
if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
continue;
}
file_name = android::base::StringPrintf("%s/%s", android_dir, dp->d_name);
android::base::ReadFileToString(file_name, &dt_file);
std::replace(dt_file.begin(), dt_file.end(), ',', '.');
std::string property_name = android::base::StringPrintf("ro.boot.%s", dp->d_name);
property_set(property_name.c_str(), dt_file.c_str());
}
}
static void process_kernel_cmdline() {
// Don't expose the raw commandline to unprivileged processes.
chmod("/proc/cmdline", 0440);
// The first pass does the common stuff, and finds if we are in qemu.
// The second pass is only necessary for qemu to export all kernel params
// as properties.
import_kernel_cmdline(false, import_kernel_nv);
if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
}
static int queue_property_triggers_action(const std::vector<std::string>& args)
{
ActionManager::GetInstance().QueueAllPropertyTriggers();
/* enable property triggers */
property_triggers_enabled = 1;
return 0;
}
static void selinux_init_all_handles(void)
{
sehandle = selinux_android_file_context_handle();
selinux_android_set_sehandle(sehandle);
sehandle_prop = selinux_android_prop_context_handle();
}
enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
static selinux_enforcing_status selinux_status_from_cmdline() {
selinux_enforcing_status status = SELINUX_ENFORCING;
import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
if (key == "androidboot.selinux" && value == "permissive") {
status = SELINUX_PERMISSIVE;
}
});
return status;
}
static bool selinux_is_enforcing(void)
{
if (ALLOW_PERMISSIVE_SELINUX) {
return selinux_status_from_cmdline() == SELINUX_ENFORCING;
}
return true;
}
int selinux_reload_policy(void)
{
INFO("SELinux: Attempting to reload policy files\n");
if (selinux_android_reload_policy() == -1) {
return -1;
}
if (sehandle)
selabel_close(sehandle);
if (sehandle_prop)
selabel_close(sehandle_prop);
selinux_init_all_handles();
return 0;
}
static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
if (!d || !d->name || !d->cr) {
ERROR("audit_callback invoked with null data arguments!");
return 0;
}
snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
d->cr->pid, d->cr->uid, d->cr->gid);
return 0;
}
static void selinux_initialize(bool in_kernel_domain) {
Timer t;
selinux_callback cb;
cb.func_log = selinux_klog_callback;
selinux_set_callback(SELINUX_CB_LOG, cb);
cb.func_audit = audit_callback;
selinux_set_callback(SELINUX_CB_AUDIT, cb);
if (in_kernel_domain) {
INFO("Loading SELinux policy...\n");
if (selinux_android_load_policy() < 0) {
ERROR("failed to load policy: %s\n", strerror(errno));
security_failure();
}
bool kernel_enforcing = (security_getenforce() == 1);
bool is_enforcing = selinux_is_enforcing();
if (kernel_enforcing != is_enforcing) {
if (security_setenforce(is_enforcing)) {
ERROR("security_setenforce(%s) failed: %s\n",
is_enforcing ? "true" : "false", strerror(errno));
security_failure();
}
}
if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) {
security_failure();
}
NOTICE("(Initializing SELinux %s took %.2fs.)\n",
is_enforcing ? "enforcing" : "non-enforcing", t.duration());
} else {
selinux_init_all_handles();
}
}
int main(int argc, char** argv) {
if (!strcmp(basename(argv[0]), "ueventd")) {
return ueventd_main(argc, argv);
}
if (!strcmp(basename(argv[0]), "watchdogd")) {
return watchdogd_main(argc, argv);
}
// Clear the umask.
umask(0);
add_environment("PATH", _PATH_DEFPATH);
bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
// Get the basic filesystem setup we need put together in the initramdisk
// on / and then we'll let the rc file figure out the rest.
if (is_first_stage) {
mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
mkdir("/dev/pts", 0755);
mkdir("/dev/socket", 0755);
mount("devpts", "/dev/pts", "devpts", 0, NULL);
#define MAKE_STR(x) __STRING(x)
mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
mount("sysfs", "/sys", "sysfs", 0, NULL);
}
// We must have some place other than / to create the device nodes for
// kmsg and null, otherwise we won't be able to remount / read-only
// later on. Now that tmpfs is mounted on /dev, we can actually talk
// to the outside world.
open_devnull_stdio();
klog_init();
klog_set_level(KLOG_NOTICE_LEVEL);
NOTICE("init %s started!\n", is_first_stage ? "first stage" : "second stage");
if (!is_first_stage) {
// Indicate that booting is in progress to background fw loaders, etc.
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
property_init();
// If arguments are passed both on the command line and in DT,
// properties set in DT always have priority over the command-line ones.
process_kernel_dt();
process_kernel_cmdline();
// Propagate the kernel variables to internal variables
// used by init as well as the current required properties.
export_kernel_boot_props();
}
// Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
selinux_initialize(is_first_stage);
// If we're in the kernel domain, re-exec init to transition to the init domain now
// that the SELinux policy has been loaded.
if (is_first_stage) {
if (restorecon("/init") == -1) {
ERROR("restorecon failed: %s\n", strerror(errno));
security_failure();
}
char* path = argv[0];
char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
if (execv(path, args) == -1) {
ERROR("execv(\"%s\") failed: %s\n", path, strerror(errno));
security_failure();
}
}
// These directories were necessarily created before initial policy load
// and therefore need their security context restored to the proper value.
// This must happen before /dev is populated by ueventd.
NOTICE("Running restorecon...\n");
restorecon("/dev");
restorecon("/dev/socket");
restorecon("/dev/__properties__");
restorecon("/property_contexts");
restorecon_recursive("/sys");
epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (epoll_fd == -1) {
ERROR("epoll_create1 failed: %s\n", strerror(errno));
exit(1);
}
signal_handler_init();
property_load_boot_defaults();
export_oem_lock_status();
start_property_service();
const BuiltinFunctionMap function_map;
Action::set_function_map(&function_map);
Parser& parser = Parser::GetInstance();
parser.AddSectionParser("service",std::make_unique<ServiceParser>());
parser.AddSectionParser("on", std::make_unique<ActionParser>());
parser.AddSectionParser("import", std::make_unique<ImportParser>());
parser.ParseConfig("/init.rc");
ActionManager& am = ActionManager::GetInstance();
am.QueueEventTrigger("early-init");
// Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
// ... so that we can start queuing up actions that require stuff from /dev.
am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
am.QueueBuiltinAction(keychord_init_action, "keychord_init");
am.QueueBuiltinAction(console_init_action, "console_init");
// Trigger all the boot actions to get us started.
am.QueueEventTrigger("init");
// Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
// wasn't ready immediately after wait_for_coldboot_done
am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
// Don't mount filesystems or start core system services in charger mode.
std::string bootmode = property_get("ro.bootmode");
if (bootmode == "charger") {
am.QueueEventTrigger("charger");
} else {
am.QueueEventTrigger("late-init");
}
// Run all property triggers based on current state of the properties.
am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
while (true) {
if (!waiting_for_exec) {
am.ExecuteOneCommand();
restart_processes();
}
int timeout = -1;
if (process_needs_restart) {
timeout = (process_needs_restart - gettime()) * 1000;
if (timeout < 0)
timeout = 0;
}
if (am.HasMoreCommands()) {
timeout = 0;
}
bootchart_sample(&timeout);
epoll_event ev;
int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
if (nr == -1) {
ERROR("epoll_wait failed: %s\n", strerror(errno));
} else if (nr == 1) {
((void (*)()) ev.data.ptr)();
}
}
return 0;
}
|
drabinowitz/Brainstorm
|
server/interests/interestRoutes.js
|
var interestController = require('./interestController.js');
module.exports = function (app) {
app.route('/:idea_id')
.post(interestController.newInterest)
.get(interestController.allInterests);
app.route('/:interest_id')
.delete(interestController.deleteInterest);
};
|
successful-try/study
|
Algorithm Trainings from Yandex (September 2021)/Binary Search/C-cubic_equation.cpp
|
<reponame>successful-try/study
#include <bits/stdc++.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
int a,b,c,d;
double equation(double x){
double result;
result = a*x*x*x + b*x*x + c*x + d;
return result;
}
double find_point(double left, double right){
double mid = 0;
while(fabs(right - left) > 0.0000001){
mid = (right + left) / 2;
if(equation(right)*equation(mid)> 0){
right = mid;
}
else{
left = mid;
}
}
return mid;
}
int main()
{
cin >> a >> b >> c >> d;
int first = 0,second=0;
double res,left=-1001,right=1001;
res = d;
res = find_point(left,right);
cout << setprecision(10) << res;
return 0;
}
|
petergp/XVim2
|
XVim2/XcodeHeader/IDEKit/_TtC6IDEKit36IDEMultiSelectionTableViewController.h
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 6 2019 20:12:56).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <AppKit/NSViewController.h>
#import <IDEKit/NSTableViewDataSource-Protocol.h>
#import <IDEKit/NSTableViewDelegate-Protocol.h>
@class NSArray, NSTableColumn, NSTableView, _TtC6IDEKit17IDEMultiSelection;
@interface _TtC6IDEKit36IDEMultiSelectionTableViewController : NSViewController <NSTableViewDataSource, NSTableViewDelegate>
{
// Error parsing type: , name: tableView
// Error parsing type: , name: selectionColumn
// Error parsing type: , name: items
// Error parsing type: , name: selection
// Error parsing type: , name: heightMode
// Error parsing type: , name: onlyDisplaySeparatorForAllSelectionRow
// Error parsing type: , name: heightConstraint
// Error parsing type: , name: selectionChangedCallback
// Error parsing type: , name: viewAdapter
}
+ (id)defaultCellIdentifier;
- (void).cxx_destruct;
- (id)initWithNibName:(id)arg1 bundle:(id)arg2;
- (void)clampHeightTo:(double)arg1;
- (void)handleCheckboxChanged:(id)arg1;
- (void)tableViewSelectionDidChange:(id)arg1;
- (id)tableView:(id)arg1 rowViewForRow:(long long)arg2;
- (id)tableView:(id)arg1 viewForTableColumn:(id)arg2 row:(long long)arg3;
- (long long)numberOfRowsInTableView:(id)arg1;
- (void)viewDidLoad;
- (id)initWithCoder:(id)arg1;
- (id)initWithViewAdapter:(CDUnknownBlockType)arg1;
@property(nonatomic, readonly) CDUnknownBlockType viewAdapter;
@property(nonatomic, copy) CDUnknownBlockType selectionChangedCallback;
@property(nonatomic) BOOL onlyDisplaySeparatorForAllSelectionRow; // @synthesize onlyDisplaySeparatorForAllSelectionRow;
@property(nonatomic, retain) _TtC6IDEKit17IDEMultiSelection *selection; // @synthesize selection;
@property(nonatomic, copy) NSArray *items;
@property(nonatomic) __weak NSTableColumn *selectionColumn; // @synthesize selectionColumn;
@property(nonatomic) __weak NSTableView *tableView; // @synthesize tableView;
@end
|
kevvdp/operator
|
vendor/github.com/SermoDigital/jose/jws/jws.go
|
package jws
import (
"bytes"
"encoding/json"
"sort"
"github.com/SermoDigital/jose"
"github.com/SermoDigital/jose/crypto"
)
// JWS represents a specific JWS.
type JWS struct {
payload *payload
plcache rawBase64
clean bool
sb []sigHead
isJWT bool
}
// Payload returns the JWS' payload.
func (j *JWS) Payload() interface{} { return j.payload.v }
// SetPayload sets the JWS' raw, unexported payload.
func (j *JWS) SetPayload(val interface{}) { j.payload.v = val }
// sigHead represents the 'signatures' member of the JWS' "general"
// serialization form per
// https://tools.ietf.org/html/rfc7515#section-7.2.1
//
// It's embedded inside the "flat" structure in order to properly
// create the "flat" JWS.
type sigHead struct {
Protected rawBase64 `json:"protected,omitempty"`
Unprotected rawBase64 `json:"header,omitempty"`
Signature crypto.Signature `json:"signature"`
protected jose.Protected
unprotected jose.Header
clean bool
method crypto.SigningMethod
}
func (s *sigHead) unmarshal() error {
if err := s.protected.UnmarshalJSON(s.Protected); err != nil {
return err
}
if err := s.unprotected.UnmarshalJSON(s.Unprotected); err != nil {
return err
}
return nil
}
// New creates a new JWS with the provided crypto.SigningMethods.
func New(content interface{}, methods ...crypto.SigningMethod) *JWS {
sb := make([]sigHead, len(methods))
for i := range methods {
sb[i] = sigHead{
protected: jose.Protected{
"alg": methods[i].Alg(),
},
unprotected: jose.Header{},
method: methods[i],
}
}
return &JWS{
payload: &payload{v: content},
sb: sb,
}
}
func (s *sigHead) assignMethod(p jose.Protected) error {
alg, ok := p.Get("alg").(string)
if !ok {
return ErrNoAlgorithm
}
sm := GetSigningMethod(alg)
if sm == nil {
return ErrNoAlgorithm
}
s.method = sm
return nil
}
type generic struct {
Payload rawBase64 `json:"payload"`
sigHead
Signatures []sigHead `json:"signatures,omitempty"`
}
// Parse parses any of the three serialized JWS forms into a physical
// JWS per https://tools.ietf.org/html/rfc7515#section-5.2
//
// It accepts a json.Unmarshaler in order to properly parse
// the payload. In order to keep the caller from having to do extra
// parsing of the payload, a json.Unmarshaler can be passed
// which will be then to unmarshal the payload however the caller
// wishes. Do note that if json.Unmarshal returns an error the
// original payload will be used as if no json.Unmarshaler was
// passed.
//
// Internally, Parse applies some heuristics and then calls either
// ParseGeneral, ParseFlat, or ParseCompact.
// It should only be called if, for whatever reason, you do not
// know which form the serialized JWT is in.
func Parse(encoded []byte, u ...json.Unmarshaler) (*JWS, error) {
// Try and unmarshal into a generic struct that'll
// hopefully hold either of the two JSON serialization
// formats.s
var g generic
// Not valid JSON. Let's try compact.
if err := json.Unmarshal(encoded, &g); err != nil {
return ParseCompact(encoded, u...)
}
if g.Signatures == nil {
return g.parseFlat(u...)
}
return g.parseGeneral(u...)
}
// ParseGeneral parses a JWS serialized into its "general" form per
// https://tools.ietf.org/html/rfc7515#section-7.2.1
// into a physical JWS per
// https://tools.ietf.org/html/rfc7515#section-5.2
//
// For information on the json.Unmarshaler parameter, see Parse.
func ParseGeneral(encoded []byte, u ...json.Unmarshaler) (*JWS, error) {
var g generic
if err := json.Unmarshal(encoded, &g); err != nil {
return nil, err
}
return g.parseGeneral(u...)
}
func (g *generic) parseGeneral(u ...json.Unmarshaler) (*JWS, error) {
var p payload
if len(u) > 0 {
p.u = u[0]
}
if err := p.UnmarshalJSON(g.Payload); err != nil {
return nil, err
}
for i := range g.Signatures {
if err := g.Signatures[i].unmarshal(); err != nil {
return nil, err
}
if err := checkHeaders(jose.Header(g.Signatures[i].protected), g.Signatures[i].unprotected); err != nil {
return nil, err
}
if err := g.Signatures[i].assignMethod(g.Signatures[i].protected); err != nil {
return nil, err
}
g.clean = true
}
return &JWS{
payload: &p,
plcache: g.Payload,
clean: true,
sb: g.Signatures,
}, nil
}
// ParseFlat parses a JWS serialized into its "flat" form per
// https://tools.ietf.org/html/rfc7515#section-7.2.2
// into a physical JWS per
// https://tools.ietf.org/html/rfc7515#section-5.2
//
// For information on the json.Unmarshaler parameter, see Parse.
func ParseFlat(encoded []byte, u ...json.Unmarshaler) (*JWS, error) {
var g generic
if err := json.Unmarshal(encoded, &g); err != nil {
return nil, err
}
return g.parseFlat(u...)
}
func (g *generic) parseFlat(u ...json.Unmarshaler) (*JWS, error) {
var p payload
if len(u) > 0 {
p.u = u[0]
}
if err := p.UnmarshalJSON(g.Payload); err != nil {
return nil, err
}
if err := g.sigHead.unmarshal(); err != nil {
return nil, err
}
g.sigHead.clean = true
if err := checkHeaders(jose.Header(g.sigHead.protected), g.sigHead.unprotected); err != nil {
return nil, err
}
if err := g.sigHead.assignMethod(g.sigHead.protected); err != nil {
return nil, err
}
return &JWS{
payload: &p,
plcache: g.Payload,
clean: true,
sb: []sigHead{g.sigHead},
}, nil
}
// ParseCompact parses a JWS serialized into its "compact" form per
// https://tools.ietf.org/html/rfc7515#section-7.1
// into a physical JWS per
// https://tools.ietf.org/html/rfc7515#section-5.2
//
// For information on the json.Unmarshaler parameter, see Parse.
func ParseCompact(encoded []byte, u ...json.Unmarshaler) (*JWS, error) {
// This section loosely follows
// https://tools.ietf.org/html/rfc7519#section-7.2
// because it's used to parse _both_ JWS and JWTs.
parts := bytes.Split(encoded, []byte{'.'})
if len(parts) != 3 {
return nil, ErrNotCompact
}
var p jose.Protected
if err := p.UnmarshalJSON(parts[0]); err != nil {
return nil, err
}
s := sigHead{
protected: p,
clean: true,
}
if err := s.assignMethod(p); err != nil {
return nil, err
}
j := JWS{
payload: &payload{},
sb: []sigHead{s},
}
if err := j.payload.UnmarshalJSON(parts[1]); err != nil {
return nil, err
}
j.clean = true
if err := j.sb[0].Signature.UnmarshalJSON(parts[2]); err != nil {
return nil, err
}
// https://tools.ietf.org/html/rfc7519#section-7.2.8
cty, ok := p.Get("cty").(string)
if ok && cty == "JWT" {
return &j, ErrHoldsJWE
}
return &j, nil
}
// IgnoreDupes should be set to true if the internal duplicate header key check
// should ignore duplicate Header keys instead of reporting an error when
// duplicate Header keys are found.
//
// Note: Duplicate Header keys are defined in
// https://tools.ietf.org/html/rfc7515#section-5.2
// meaning keys that both the protected and unprotected
// Headers possess.
var IgnoreDupes bool
// checkHeaders returns an error per the constraints described in
// IgnoreDupes' comment.
func checkHeaders(a, b jose.Header) error {
if len(a)+len(b) == 0 {
return ErrTwoEmptyHeaders
}
for key := range a {
if b.Has(key) && !IgnoreDupes {
return ErrDuplicateHeaderParameter
}
}
return nil
}
// Any means any of the JWS signatures need to validate.
// Refer to ValidateMulti for more information.
const Any int = -1
// ValidateMulti validates the current JWS as-is. Since it's meant to be
// called after parsing a stream of bytes into a JWS, it doesn't do any
// internal parsing like the Sign, Flat, Compact, or General methods do.
// idx represents which signatures need to validate
// in order for the JWS to be considered valid.
// Use the constant `Any` (-1) if *any* should validate the JWS. Otherwise,
// use the indexes of the signatures that need to validate in order
// for the JWS to be considered valid.
//
// Notes:
// 1.) If idx is omitted it defaults to requiring *all*
// signatures validate
// 2.) The JWS spec requires *at least* one
// signature to validate in order for the JWS to be considered valid.
func (j *JWS) ValidateMulti(keys []interface{}, methods []crypto.SigningMethod, idx ...int) error {
if len(j.sb) != len(methods) {
return ErrNotEnoughMethods
}
if len(keys) < 1 ||
len(keys) > 1 && len(keys) != len(j.sb) {
return ErrNotEnoughKeys
}
if len(keys) == 1 {
k := keys[0]
keys = make([]interface{}, len(methods))
for i := range keys {
keys[i] = k
}
}
any := len(idx) == 1 && idx[0] == Any
if !any {
sort.Ints(idx)
}
rp := 0
for i := range j.sb {
if j.sb[i].validate(j.plcache, keys[i], methods[i]) == nil &&
any || (rp < len(idx) && idx[rp] == i) {
rp++
}
}
if rp < len(idx) {
return ErrDidNotValidate
}
return nil
}
// Validate validates the current JWS as-is. Refer to ValidateMulti
// for more information.
func (j *JWS) Validate(key interface{}, method crypto.SigningMethod) error {
if len(j.sb) < 1 {
return ErrCannotValidate
}
return j.sb[0].validate(j.plcache, key, method)
}
func (s *sigHead) validate(pl []byte, key interface{}, method crypto.SigningMethod) error {
if s.method != method {
return ErrMismatchedAlgorithms
}
return method.Verify(format(s.Protected, pl), s.Signature, key)
}
// SetProtected sets the protected Header with the given value.
// If i is provided, it'll assume the JWS is in the "general" format,
// and set the Header at index i (inside the signatures member) with
// the given value.
func (j *JWS) SetProtected(key string, val interface{}, i ...int) {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
j.sb[k].protected.Set(key, val)
}
// RemoveProtected removes the value inside the protected Header that
// corresponds with the given key.
// For information on parameter i, see SetProtected.
func (j *JWS) RemoveProtected(key string, i ...int) {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
j.sb[k].protected.Del(key)
}
// GetProtected retrieves the value inside the protected Header that
// corresponds with the given key.
// For information on parameter i, see SetProtected.
func (j *JWS) GetProtected(key string, i ...int) interface{} {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
return j.sb[k].protected.Get(key)
}
// SetUnprotected sets the protected Header with the given value.
// If i is provided, it'll assume the JWS is in the "general" format,
// and set the Header at index i (inside the signatures member) with
// the given value.
func (j *JWS) SetUnprotected(key string, val interface{}, i ...int) {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
j.sb[k].unprotected.Set(key, val)
}
// RemoveUnprotected removes the value inside the unprotected Header that
// corresponds with the given key.
// For information on parameter i, see SetUnprotected.
func (j *JWS) RemoveUnprotected(key string, i ...int) {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
j.sb[k].unprotected.Del(key)
}
// GetUnprotected retrieves the value inside the protected Header that
// corresponds with the given key.
// For information on parameter i, see SetUnprotected.
func (j *JWS) GetUnprotected(key string, i ...int) interface{} {
k := 0
if len(i) > 0 && len(i) < len(j.sb) && i[0] > -1 {
k = i[0]
}
return j.sb[k].unprotected.Get(key)
}
|
icemanzp/Orion-Server
|
src/main/java/com/jack/netty/server/servlet/WFJFilterFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jack.netty.server.servlet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import com.jack.netty.server.container.factory.ServerConfigWrappar;
/**
* Factory for the creation and caching of Filters and creation
* of Filter Chains.
*
* @author <NAME>
* @author <NAME>
*/
public final class WFJFilterFactory {
private WFJFilterFactory() {
// Prevent instance creation. This is a utility class.
}
/**
* Construct and return a FilterChain implementation that will wrap the
* execution of the specified servlet instance. If we should not execute
* a filter chain at all, return <code>null</code>.
*
* @param request The servlet request we are processing
* @param servlet The servlet instance to be wrapped
*/
public static WFJFilterChain createFilterChain(ServletRequest request, Servlet servlet) {
// 如果Servlet 没有内容则不执行任何创建
if (servlet == null) {
return (null);
}
// 从请求中获取分发类型
DispatcherType dispatcher = request.getDispatcherType();
String requestPath = ((HttpServletRequest) request).getRequestURI();
// 开始构建过滤链
WFJFilterChain filterChain = new WFJFilterChain();
filterChain.setServlet(servlet);
//从 Servlet 获取 ServletContext
WFJServletContext context = (WFJServletContext) servlet.getServletConfig().getServletContext();
WFJFilterMap filterMaps[] = ServerConfigWrappar.findFilterMaps();
// 如果不存在后续过滤链,则无需处理返回空对象,执行后续 Servlet
if ((filterMaps == null) || (filterMaps.length == 0)) {
return (filterChain);
}
// 设定 Servlet 对象名称
String servletName = servlet.getServletConfig().getServletName();
// 首先根据请求路径检索是否需要过滤,如需要则加入过滤链中
for (int i = 0; i < filterMaps.length; i++) {
if (!matchDispatcher(filterMaps[i], dispatcher)) {
continue;
}
if (!matchFiltersURL(filterMaps[i], requestPath)) {
continue;
}
Filter filter = context.getFilter(filterMaps[i].getFilterName());
if (filter == null) {
// FIXME - log configuration problem
continue;
}
filterChain.addFilter(filter);
}
// 其次根据 Servlet 名称检索是否需要过滤,如需要则键入过滤链中
for (int i = 0; i < filterMaps.length; i++) {
if (!matchDispatcher(filterMaps[i], dispatcher)) {
continue;
}
if (!matchFiltersServlet(filterMaps[i], servletName)) {
continue;
}
Filter filter = context.getFilter(filterMaps[i].getFilterName());
if (filter == null) {
// FIXME - log configuration problem
continue;
}
filterChain.addFilter(filter);
}
// 完成构建返回
return (filterChain);
}
/**
* Return <code>true</code> if the context-relative request path
* matches the requirements of the specified filter mapping;
* otherwise, return <code>false</code>.
*
* @param filterMap Filter mapping being checked
* @param requestPath Context-relative request path of this request
*/
private static boolean matchFiltersURL(WFJFilterMap filterMap, String requestPath) {
// Check the specific "*" special URL pattern, which also matches
// named dispatches
if (filterMap.getMatchAllUrlPatterns()) {
return (true);
}
if (requestPath == null) {
return (false);
}
// Match on context relative request path
String[] testPaths = filterMap.getURLPatterns();
for (int i = 0; i < testPaths.length; i++) {
if (matchFiltersURL(testPaths[i], requestPath)) {
return (true);
}
}
// No match
return (false);
}
/**
* Return <code>true</code> if the context-relative request path
* matches the requirements of the specified filter mapping;
* otherwise, return <code>false</code>.
*
* @param testPath URL mapping being checked
* @param requestPath Context-relative request path of this request
*/
private static boolean matchFiltersURL(String testPath, String requestPath) {
if (testPath == null) {
return (false);
}
// Case 1 - Exact Match
if (testPath.equals(requestPath)) {
return (true);
}
// Case 2 - Path Match ("/.../*")
if (testPath.equals("/*")) {
return (true);
}
if (testPath.endsWith("/*")) {
if (testPath.regionMatches(0, requestPath, 0,
testPath.length() - 2)) {
if (requestPath.length() == (testPath.length() - 2)) {
return (true);
} else if ('/' == requestPath.charAt(testPath.length() - 2)) {
return (true);
}
}
return (false);
}
// Case 3 - Extension Match
if (testPath.startsWith("*.")) {
int slash = requestPath.lastIndexOf('/');
int period = requestPath.lastIndexOf('.');
if ((slash >= 0) && (period > slash)
&& (period != requestPath.length() - 1)
&& ((requestPath.length() - period)
== (testPath.length() - 1))) {
return (testPath.regionMatches(2, requestPath, period + 1,
testPath.length() - 2));
}
}
// Case 4 - "Default" Match
return (false); // NOTE - Not relevant for selecting filters
}
/**
* Return <code>true</code> if the specified servlet name matches
* the requirements of the specified filter mapping; otherwise
* return <code>false</code>.
*
* @param filterMap Filter mapping being checked
* @param servletName Servlet name being checked
*/
private static boolean matchFiltersServlet(WFJFilterMap filterMap,
String servletName) {
if (servletName == null) {
return (false);
}
// Check the specific "*" special servlet name
else if (filterMap.getMatchAllServletNames()) {
return (true);
} else {
String[] servletNames = filterMap.getServletNames();
for (int i = 0; i < servletNames.length; i++) {
if (servletName.equals(servletNames[i])) {
return (true);
}
}
return false;
}
}
/**
* Convenience method which returns true if the dispatcher type
* matches the dispatcher types specified in the FilterMap
*/
private static boolean matchDispatcher(WFJFilterMap filterMap, DispatcherType type) {
switch (type) {
case FORWARD:
if ((filterMap.getDispatcherMapping() & WFJFilterMap.FORWARD) > 0) {
return true;
}
break;
case INCLUDE:
if ((filterMap.getDispatcherMapping() & WFJFilterMap.INCLUDE) > 0) {
return true;
}
break;
case REQUEST:
if ((filterMap.getDispatcherMapping() & WFJFilterMap.REQUEST) > 0) {
return true;
}
break;
case ERROR:
if ((filterMap.getDispatcherMapping() & WFJFilterMap.ERROR) > 0) {
return true;
}
break;
case ASYNC:
if ((filterMap.getDispatcherMapping() & WFJFilterMap.ASYNC) > 0) {
return true;
}
break;
}
return false;
}
}
|
suluner/tencentcloud-sdk-cpp
|
ess/include/tencentcloud/ess/v20201111/model/UserInfo.h
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_ESS_V20201111_MODEL_USERINFO_H_
#define TENCENTCLOUD_ESS_V20201111_MODEL_USERINFO_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Ess
{
namespace V20201111
{
namespace Model
{
/**
* 用户信息
*/
class UserInfo : public AbstractModel
{
public:
UserInfo();
~UserInfo() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取用户在平台的编号
* @return UserId 用户在平台的编号
*/
std::string GetUserId() const;
/**
* 设置用户在平台的编号
* @param UserId 用户在平台的编号
*/
void SetUserId(const std::string& _userId);
/**
* 判断参数 UserId 是否已赋值
* @return UserId 是否已赋值
*/
bool UserIdHasBeenSet() const;
/**
* 获取用户的来源渠道
* @return Channel 用户的来源渠道
*/
std::string GetChannel() const;
/**
* 设置用户的来源渠道
* @param Channel 用户的来源渠道
*/
void SetChannel(const std::string& _channel);
/**
* 判断参数 Channel 是否已赋值
* @return Channel 是否已赋值
*/
bool ChannelHasBeenSet() const;
/**
* 获取用户在渠道的编号
* @return OpenId 用户在渠道的编号
*/
std::string GetOpenId() const;
/**
* 设置用户在渠道的编号
* @param OpenId 用户在渠道的编号
*/
void SetOpenId(const std::string& _openId);
/**
* 判断参数 OpenId 是否已赋值
* @return OpenId 是否已赋值
*/
bool OpenIdHasBeenSet() const;
/**
* 获取用户真实IP
* @return ClientIp 用户真实IP
*/
std::string GetClientIp() const;
/**
* 设置用户真实IP
* @param ClientIp 用户真实IP
*/
void SetClientIp(const std::string& _clientIp);
/**
* 判断参数 ClientIp 是否已赋值
* @return ClientIp 是否已赋值
*/
bool ClientIpHasBeenSet() const;
/**
* 获取用户代理IP
* @return ProxyIp 用户代理IP
*/
std::string GetProxyIp() const;
/**
* 设置用户代理IP
* @param ProxyIp 用户代理IP
*/
void SetProxyIp(const std::string& _proxyIp);
/**
* 判断参数 ProxyIp 是否已赋值
* @return ProxyIp 是否已赋值
*/
bool ProxyIpHasBeenSet() const;
private:
/**
* 用户在平台的编号
*/
std::string m_userId;
bool m_userIdHasBeenSet;
/**
* 用户的来源渠道
*/
std::string m_channel;
bool m_channelHasBeenSet;
/**
* 用户在渠道的编号
*/
std::string m_openId;
bool m_openIdHasBeenSet;
/**
* 用户真实IP
*/
std::string m_clientIp;
bool m_clientIpHasBeenSet;
/**
* 用户代理IP
*/
std::string m_proxyIp;
bool m_proxyIpHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ESS_V20201111_MODEL_USERINFO_H_
|
GodIsWord/NewFindSecret
|
FindSecret/Classes/Native/mscorlib_System_OrdinalComparer3407243298.h
|
<filename>FindSecret/Classes/Native/mscorlib_System_OrdinalComparer3407243298.h<gh_stars>0
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_StringComparer3301955079.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.OrdinalComparer
struct OrdinalComparer_t3407243298 : public StringComparer_t3301955079
{
public:
// System.Boolean System.OrdinalComparer::_ignoreCase
bool ____ignoreCase_4;
public:
inline static int32_t get_offset_of__ignoreCase_4() { return static_cast<int32_t>(offsetof(OrdinalComparer_t3407243298, ____ignoreCase_4)); }
inline bool get__ignoreCase_4() const { return ____ignoreCase_4; }
inline bool* get_address_of__ignoreCase_4() { return &____ignoreCase_4; }
inline void set__ignoreCase_4(bool value)
{
____ignoreCase_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
yujianyuanhaha/Co-Channel-Sig-Detection
|
solvers/java/src/main/java/com/analog/lyric/dimple/factorfunctions/DiscreteTransition.java
|
<filename>solvers/java/src/main/java/com/analog/lyric/dimple/factorfunctions/DiscreteTransition.java<gh_stars>1-10
/*******************************************************************************
* Copyright 2013 Analog Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
package com.analog.lyric.dimple.factorfunctions;
import com.analog.lyric.dimple.exceptions.DimpleException;
import com.analog.lyric.dimple.factorfunctions.core.FactorFunction;
import com.analog.lyric.dimple.model.values.Value;
/**
* Parameterized discrete transition factor, which corresponds to p(y | x, A),
* where A is a matrix of transition probabilities that are
* parameterized as normalized probabilities.
* The transition matrix is organized such that each column is represented as
* a single RealJoint variable that corresponds to
* the output distribution for each input state. That is, the transition
* matrix multiplies on the left. The domain of x and y do not need to be
* the same.
*
* Representing A as described, the conjugate prior for A is such that
* each column vector of the A matrix is distributed according to
* a Dirichlet distribution.
* Depending on the solver, it may or may not be necessary to use a
* conjugate prior (for the Gibbs solver, for example, it is not).
*
* The variables in the argument list are ordered as follows:
*
* y: Discrete output variable (MUST be zero-based integer values) // TODO: remove this restriction
* x: Discrete input variable (MUST be zero-based integer values) // TODO: remove this restriction
* A: Matrix of transition matrix values (1D vector of RealJoint variables)
*
*/
public class DiscreteTransition extends FactorFunction
{
private final static int NUM_DATA_ARGUMENTS = 2;
@Override
public final double evalEnergy(Value[] arguments)
{
if (arguments.length < NUM_DATA_ARGUMENTS + 1)
throw new DimpleException("Insufficient number of arguments.");
final int y = arguments[0].getInt(); // First argument is y (output variable)
final int x = arguments[1].getInt(); // Second argument is x (input variable)
// Choose column of A indexed by input variable x
final double[] Acol = arguments[x + NUM_DATA_ARGUMENTS].getDoubleArray();
return -Math.log(Acol[y]);
}
}
|
zhaozeq/zus-cli
|
lib/utils/common/clearConsole.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = clearConsole;
function clearConsole() {
process.stdout.write(process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H');
}
|
AndrewGHC/image-share
|
compiled/db/sequelize/connect.js
|
<filename>compiled/db/sequelize/connect.js<gh_stars>0
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _models = require('./models');
var _models2 = _interopRequireDefault(_models);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var sequelize = _models2.default.sequelize;
exports.default = function () {
sequelize.authenticate().then(function () {
console.log('Successfully connected to sequelize database');
}, function (err) {
console.log('Unable to connect to the sequelize database: ', err);
});
};
|
nanditadubey/customeronboard_nanditadubey
|
src/main/java/io/apitest/example/repository/CustomerRepository.java
|
<filename>src/main/java/io/apitest/example/repository/CustomerRepository.java
package io.apitest.example.repository;
import io.apitest.example.model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by prasantabiswas on 27/06/18.
*/
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long>{
}
|
ArcanaOrpheus/HibernateRecu
|
src/main/java/dao/IClientDao.java
|
package dao;
import java.util.List;
import database.Direccio;
import database.Clients;
import database.ComandaClient;
public interface IClientDao extends IGenericDao<Clients,Integer>{
void saveOrUpdate(Clients p);
Clients get(Integer id);
List<Clients> list();
void delete(Integer id);
boolean setComanda(Clients c, ComandaClient co);
boolean setAddress(Clients c, Direccio a);
}
|
sirinath/Harmony
|
classlib/modules/portlib/src/main/native/port/windows/hyshmem.h
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(hyshmem_h)
#define hyshmem_h
#include <Windows.h>
typedef struct hyshmem_handle
{
void *region;
char *rootName;
I_32 size;
IDATA mappedFile;
HANDLE shmHandle;
DWORD perm;
PROCESS_INFORMATION *helperpi;
BOOL creator;
} hyshmem_handle;
I_32 VMCALL hyshmem_startup (struct HyPortLibrary *portLibrary);
IDATA VMCALL hyshmem_open (struct HyPortLibrary *portLibrary,
struct hyshmem_handle **handle,
const char *rootname, I_32 size, I_32 perm);
void VMCALL hyshmem_close (struct HyPortLibrary *portLibrary,
struct hyshmem_handle **handle);
UDATA VMCALL hyshmem_findfirst (struct HyPortLibrary *portLibrary,
char *resultbuf);
I_32 VMCALL hyshmem_findnext (struct HyPortLibrary *portLibrary,
UDATA findHandle, char *resultbuf);
UDATA VMCALL hyshmem_stat (struct HyPortLibrary *portLibrary,
const char *name,
struct HyPortShmemStatistic *statbuf);
IDATA VMCALL hyshmem_destroy (struct HyPortLibrary *portLibrary,
struct hyshmem_handle **handle);
IDATA VMCALL hyshmem_detach (struct HyPortLibrary *portLibrary,
struct hyshmem_handle **handle);
void VMCALL hyshmem_findclose (struct HyPortLibrary *portLibrary,
UDATA findhandle);
void *VMCALL hyshmem_attach (struct HyPortLibrary *portLibrary,
struct hyshmem_handle *handle);
void VMCALL hyshmem_shutdown (struct HyPortLibrary *portLibrary);
#endif /* hyshmem_h */
|
dmyerscough/salt
|
tests/unit/modules/test_seed.py
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`<NAME> <<EMAIL>>`
'''
# Import Python libs
from __future__ import absolute_import
import os
import shutil
import uuid
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch)
# Import Salt Libs
import salt.utils.files
import salt.utils.odict
import salt.modules.seed as seed
@skipIf(NO_MOCK, NO_MOCK_REASON)
class SeedTestCase(TestCase, LoaderModuleMockMixin):
'''
Test cases for salt.modules.seed
'''
def setup_loader_modules(self):
return {seed: {}}
def test_mkconfig_odict(self):
with patch.dict(seed.__opts__,
{'master': 'foo'}):
ddd = salt.utils.odict.OrderedDict()
ddd['b'] = 'b'
ddd['a'] = 'b'
data = seed.mkconfig(ddd, approve_key=False)
with salt.utils.files.fopen(data['config']) as fic:
fdata = fic.read()
self.assertEqual(fdata, 'b: b\na: b\nmaster: foo\n')
def test_prep_bootstrap(self):
'''
Test to update and get the random script to a random place
'''
with patch.dict(seed.__salt__, {'config.gather_bootstrap_script': MagicMock(return_value=os.path.join('BS_PATH', 'BS'))}),\
patch.object(uuid, 'uuid4', return_value='UUID'),\
patch.object(os.path, 'exists', return_value=True),\
patch.object(os, 'chmod', return_value=None),\
patch.object(shutil, 'copy', return_value=None):
expect = (os.path.join('MPT', 'tmp', 'UUID', 'BS'),
os.sep + os.path.join('tmp', 'UUID'))
self.assertEqual(seed.prep_bootstrap('MPT'), expect)
expect = (os.sep + os.path.join('MPT', 'tmp', 'UUID', 'BS'),
os.sep + os.path.join('tmp', 'UUID'))
self.assertEqual(seed.prep_bootstrap(os.sep + 'MPT'), expect)
def test_apply_(self):
'''
Test to seed a location (disk image, directory, or block device)
with the minion config, approve the minion's key, and/or install
salt-minion.
'''
mock = MagicMock(side_effect=[False, {'type': 'type',
'target': 'target'},
{'type': 'type', 'target': 'target'},
{'type': 'type', 'target': 'target'}])
with patch.dict(seed.__salt__, {'file.stats': mock}):
self.assertEqual(seed.apply_('path'), 'path does not exist')
with patch.object(seed, '_mount', return_value=False):
self.assertEqual(seed.apply_('path'),
'target could not be mounted')
with patch.object(seed, '_mount', return_value=True):
with patch.object(os.path, 'join', return_value='A'):
with patch.object(os, 'makedirs',
MagicMock(side_effect=OSError('f'))):
with patch.object(os.path, 'isdir',
return_value=False):
self.assertRaises(OSError, seed.apply_, 'p')
with patch.object(os, 'makedirs', MagicMock()):
with patch.object(seed, 'mkconfig', return_value='A'):
with patch.object(seed, '_check_install',
return_value=False):
with patch.object(seed, '_umount',
return_value=None):
self.assertFalse(seed.apply_('path',
install=False))
|
loolzaaa/sso-authentication-client
|
sso-client-spring-boot-autoconfigure/src/main/java/ru/loolzaaa/sso/client/autoconfigure/SsoClientHttpConfigurer.java
|
<gh_stars>0
package ru.loolzaaa.sso.client.autoconfigure;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.NullSecurityContextRepository;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import ru.loolzaaa.sso.client.core.security.DefaultSsoClientAuthenticationEntryPoint;
import ru.loolzaaa.sso.client.core.security.DefaultSsoClientLogoutSuccessHandler;
import ru.loolzaaa.sso.client.core.filter.JwtTokenFilter;
import ru.loolzaaa.sso.client.core.filter.QueryJwtTokenFilter;
public class SsoClientHttpConfigurer extends AbstractHttpConfigurer<SsoClientHttpConfigurer, HttpSecurity> {
private final SsoClientProperties properties;
private final DefaultSsoClientAuthenticationEntryPoint authenticationEntryPoint;
private final DefaultSsoClientLogoutSuccessHandler logoutSuccessHandler;
private final QueryJwtTokenFilter queryJwtTokenFilter;
private final JwtTokenFilter jwtTokenFilter;
public SsoClientHttpConfigurer(SsoClientProperties properties,
DefaultSsoClientAuthenticationEntryPoint authenticationEntryPoint,
DefaultSsoClientLogoutSuccessHandler logoutSuccessHandler,
QueryJwtTokenFilter queryJwtTokenFilter,
JwtTokenFilter jwtTokenFilter) {
this.properties = properties;
this.authenticationEntryPoint = authenticationEntryPoint;
this.logoutSuccessHandler = logoutSuccessHandler;
this.queryJwtTokenFilter = queryJwtTokenFilter;
this.jwtTokenFilter = jwtTokenFilter;
}
@Override
public void init(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.cors()
.and()
.securityContext()
.securityContextRepository(new NullSecurityContextRepository())
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.authorizeRequests()
.anyRequest()
.hasAuthority(properties.getApplicationName())
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.httpBasic()
.disable()
.formLogin()
.disable()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/do_logout", "POST"))
.logoutSuccessHandler(logoutSuccessHandler)
.deleteCookies("JSESSIONID", "_t_access", "_t_rfid")
.invalidateHttpSession(true)
.clearAuthentication(true)
.permitAll()
.and()
// Filters order is important!
.addFilterBefore(queryJwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
}
|
liujiayii/SkylarkWebsite
|
src/main/java/com/websit/service/IT_picture_videoService.java
|
<filename>src/main/java/com/websit/service/IT_picture_videoService.java<gh_stars>0
package com.websit.service;
import com.websit.entity.T_picture_video;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 图片视频表(蔺) 服务类
* </p>
*
* @author lichangchun
* @since 2019-03-21
*/
public interface IT_picture_videoService extends IService<T_picture_video> {
}
|
Coffeekraken/coffeekraken
|
packages/tools/sugar/src/shared/is/__tests__.wip/yyyymmddDate.js
|
"use strict";
module.exports = (__testFn) => {
describe('sugar.js.is.yyyymmdd', () => {
it('Should detect the passed variable type correctly', () => {
expect(__testFn('2020.10.13')).toBe(true);
expect(__testFn('2020.20.13')).toBe(false);
});
});
};
//# sourceMappingURL=data:application/json;base64,<KEY>
|
cragkhit/elasticsearch
|
references/bcb_chosen_clones/selected#2037851#59#69.java
|
public Matrice transposee() {
final int ni = ni();
final int nj = nj();
final Matrice r = new Matrice(nj, ni);
for (int i = 0; i < ni; i++) {
for (int j = 0; j < nj; j++) {
r.a_[j][i] = a_[i][j];
}
}
return r;
}
|
myoukaku/bksge
|
libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_is_nothrow_copy_assignable.cpp
|
/**
* @file unit_test_fnd_type_traits_is_nothrow_copy_assignable.cpp
*
* @brief is_nothrow_copy_assignable のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/type_traits/is_nothrow_copy_assignable.hpp>
#include <bksge/fnd/config.hpp>
#include <gtest/gtest.h>
#include <cstddef>
#include "type_traits_test_utility.hpp"
#if defined(BKSGE_HAS_CXX14_VARIABLE_TEMPLATES)
#define BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(b, T) \
static_assert(bksge::is_nothrow_copy_assignable_v<T> == b, #T ", " #b); \
static_assert(bksge::is_nothrow_copy_assignable<T>::value == b, #T ", " #b); \
static_assert(bksge::is_nothrow_copy_assignable<T>() == b, #T ", " #b)
#else
#define BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(b, T) \
static_assert(bksge::is_nothrow_copy_assignable<T>::value == b, #T ", " #b); \
static_assert(bksge::is_nothrow_copy_assignable<T>() == b, #T ", " #b)
#endif
namespace bksge_type_traits_test
{
namespace is_nothrow_copy_assignable_test
{
// トリビアルなコピー代入演算子を持つ
struct S1
{
int n;
};
// 非トリビアルだが例外を投げないコピー代入演算子を持つ
struct S2
{
S2& operator=(const S2&) BKSGE_NOEXCEPT_OR_NOTHROW;
};
// 非トリビアルだが例外を投げないコピー代入演算子を持つクラスをメンバに持つ
struct S3
{
S2 member;
};
// コピー代入演算子が例外を投げる
struct S4
{
S4& operator=(const S4&);
};
// コピー代入演算子が例外を投げる
struct S5
{
S5& operator=(const S5&) BKSGE_NOEXCEPT_IF(false);
};
// コピー代入演算子を持たない
struct S6
{
S6& operator=(const S6&) = delete;
};
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, S1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, S2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, S3);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, S4);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, S5);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, S6);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, void);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const void);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile void);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile void);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const int);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile int);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile int);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const int*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile int*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const volatile int*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const int&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile int&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile int&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const int&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile int&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile int&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int(*)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int(*)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int(&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int(&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int(&&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, int(&&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const volatile UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, UDT(*)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, UDT(*)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT(&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT(&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT(&&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, UDT(&&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const POD_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile POD_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile POD_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const POD_UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, volatile POD_UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, const volatile POD_UDT*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const POD_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile POD_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile POD_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const POD_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile POD_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile POD_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT(*)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_UDT(*)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT(&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT(&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT(&&)[2]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, POD_UDT(&&)[]);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_default_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_default_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_default_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_default_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_default_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_default_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_default_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_default_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_default_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_default_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_default_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_default_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_dtor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_dtor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_dtor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_dtor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_dtor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_dtor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_dtor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_dtor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_dtor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_dtor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_dtor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_dtor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_copy_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_copy_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_copy_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, nothrow_copy_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, nothrow_copy_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, nothrow_copy_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_copy_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_copy_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_copy_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_ctor_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_ctor_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_ctor_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_assign_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_assign_UDT&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, nothrow_move_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const nothrow_move_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, volatile nothrow_move_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, const volatile nothrow_move_assign_UDT&&);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, bool);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, char);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, wchar_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, signed char);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, short);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, long);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, long long);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, unsigned char);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, unsigned int);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, unsigned short);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, unsigned long);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, unsigned long long);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, std::size_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, float);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, double);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, long double);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, void*);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, std::nullptr_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, decltype(nullptr));
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_uint32_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_uint16_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_uint8_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_int32_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_int16_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_int8_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_uint32_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_uint16_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_uint8_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_int32_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_int16_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum_class_int8_t_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, empty_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, empty_POD_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, union_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, POD_union_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, empty_union_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, empty_POD_union_UDT);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, Base);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, Derived);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, Derived2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, MultiBase);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, PrivateBase);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, NonDerived);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, enum2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, VB);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, VD);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, non_pointer);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, non_int_pointer);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int_constructible);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, int_convertible);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, test_abc1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, test_abc2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, test_abc3);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, test_concrete1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, test_concrete2);
//BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, incomplete_type);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, polymorphic_base);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, polymorphic_derived1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, polymorphic_derived2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, virtual_inherit1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, virtual_inherit2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, virtual_inherit3);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, virtual_inherit5);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, virtual_inherit6);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, trivial_except_construct);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, trivial_except_destroy);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, trivial_except_copy_ctor);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, trivial_except_copy_assign);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, trivial_except_move_ctor);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, trivial_except_move_assign);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, f1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, f2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, f3);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, mf1);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, mf2);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, mf3);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, mf4);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, mp);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(true, cmf);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, foo0_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, foo1_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, foo2_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, foo3_t);
BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST(false, foo4_t);
} // namespace is_nothrow_copy_assignable_test
} // namespace bksge_type_traits_test
#undef BKSGE_IS_NOTHROW_COPY_ASSIGNABLE_TEST
|
DanTupi/personal_setup
|
qmk_firmware/drivers/chibios/usbpd_stm32g4.c
|
<reponame>DanTupi/personal_setup
/* Copyright 2021 <NAME> (@tzarc)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <quantum.h>
#ifndef USBPD_UCPD1_CFG1
# define USBPD_UCPD1_CFG1 (UCPD_CFG1_PSC_UCPDCLK_0 | UCPD_CFG1_TRANSWIN_3 | UCPD_CFG1_IFRGAP_4 | UCPD_CFG1_HBITCLKDIV_4)
#endif // USBPD_UCPD1_CFG1
// Initialises the USBPD subsystem
__attribute__((weak)) void usbpd_init(void) {
// Disable dead-battery signals
PWR->CR3 |= PWR_CR3_UCPD_DBDIS;
// Enable the clock for the UCPD1 peripheral
RCC->APB1ENR2 |= RCC_APB1ENR2_UCPD1EN;
// Copy the existing value
uint32_t CFG1 = UCPD1->CFG1;
// Force-disable UCPD1 before configuring
CFG1 &= ~UCPD_CFG1_UCPDEN;
// Configure UCPD1
CFG1 = USBPD_UCPD1_CFG1;
// Apply the changes
UCPD1->CFG1 = CFG1;
// Enable UCPD1
UCPD1->CFG1 |= UCPD_CFG1_UCPDEN;
// Copy the existing value
uint32_t CR = UCPD1->CR;
// Clear out ANASUBMODE (irrelevant as a sink device)
CR &= ~UCPD_CR_ANASUBMODE_Msk;
// Advertise our capabilities as a sink, with both CC lines enabled
CR |= UCPD_CR_ANAMODE | UCPD_CR_CCENABLE_Msk;
// Apply the changes
UCPD1->CR = CR;
}
// Gets the current state of the USBPD allowance
__attribute__((weak)) usbpd_allowance_t usbpd_get_allowance(void) {
uint32_t CR = UCPD1->CR;
int ucpd_enabled = (UCPD1->CFG1 & UCPD_CFG1_UCPDEN_Msk) >> UCPD_CFG1_UCPDEN_Pos;
int anamode = (CR & UCPD_CR_ANAMODE_Msk) >> UCPD_CR_ANAMODE_Pos;
int cc_enabled = (CR & UCPD_CR_CCENABLE_Msk) >> UCPD_CR_CCENABLE_Pos;
if (ucpd_enabled && anamode && cc_enabled) {
uint32_t SR = UCPD1->SR;
int vstate_cc1 = (SR & UCPD_SR_TYPEC_VSTATE_CC1_Msk) >> UCPD_SR_TYPEC_VSTATE_CC1_Pos;
int vstate_cc2 = (SR & UCPD_SR_TYPEC_VSTATE_CC2_Msk) >> UCPD_SR_TYPEC_VSTATE_CC2_Pos;
int vstate_max = vstate_cc1 > vstate_cc2 ? vstate_cc1 : vstate_cc2;
switch (vstate_max) {
case 0:
case 1:
return USBPD_500MA; // Note that this is 500mA (i.e. max USB 2.0), not 900mA, as we're not using USB 3.1 as a sink device.
case 2:
return USBPD_1500MA;
case 3:
return USBPD_3000MA;
}
}
return USBPD_500MA;
}
|
superkit01/jt809
|
jt809-sdk/src/main/java/com/superkit/jt809/entity/linkManager/SubLinkTestRspEntity.java
|
package com.superkit.jt809.entity.linkManager;
import com.superkit.jt809.MsgConstant;
import com.superkit.jt809.entity.BaseEntity;
import com.superkit.jt809.entity.Codec;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;
/**
* 从链路连接保持应答消息
* <p>
* 业务数据类型标识:DOWN_LINKTEST_RSP
* <p>
* 下级平台收到上级平台链路连接保持请求消息后,向上级平台返回从链路连接保持应答消息,保持从链路连接状态
*/
@Setter
@Getter
public class SubLinkTestRspEntity implements Codec<SubLinkTestRspEntity> {
private BaseEntity base;
/**
* 数据体为空
*/
@Override
public SubLinkTestRspEntity decode(ByteBuf buf) {
this.base = new BaseEntity().decode(buf);
return this;
}
public static SubLinkTestRspEntity create(long userId, String password) {
SubLinkTestRspEntity baseMsg = new SubLinkTestRspEntity();
baseMsg.base = BaseEntity.create(MsgConstant.PrimaryServiceType.DOWN_LINKTEST_RSP, new byte[0]);
return baseMsg;
}
@Override
public byte[] encode() {
return base.encode();
}
}
|
junphine/dremio-oss
|
apr/dremio-ce-mongo-plugin/src/main/java/com/dremio/plugins/mongo/connection/MongoConnectionKey.java
|
package com.dremio.plugins.mongo.connection;
import com.mongodb.*;
public class MongoConnectionKey
{
private final ServerAddress address;
private final String user;
public MongoConnectionKey(final ServerAddress address, final String user) {
this.address = address;
this.user = user;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = 31 * result + ((this.address == null) ? 0 : this.address.hashCode());
result = 31 * result + ((this.user == null) ? 0 : this.user.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final MongoConnectionKey other = (MongoConnectionKey)obj;
if (this.address == null) {
if (other.address != null) {
return false;
}
}
else if (!this.address.equals(other.address)) {
return false;
}
if (this.user == null) {
if (other.user != null) {
return false;
}
}
else if (!this.user.equals(other.user)) {
return false;
}
return true;
}
@Override
public String toString() {
return "[address=" + this.address.toString() + ", user=" + this.user + "]";
}
}
|
efalayi/population-management-system
|
dist/server/middlewares/validations/validateLocationUpdate.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectHelper = _interopRequireDefault(require("../../helpers/objectHelper"));
var _fields = _interopRequireDefault(require("../../../constants/fields"));
var _validateLocationField = _interopRequireDefault(require("./validateLocationField"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const {
LOCATION_FIELDS
} = _fields.default;
const validateLocationUpdate = (req, res, next) => {
const locationUpdate = req.body;
const isUpdateEmpty = _objectHelper.default.isEmpty(locationUpdate);
if (isUpdateEmpty) {
return res.status(200).send({
message: 'Nothing to update'
});
}
let errors = {};
const updateFields = Object.keys(locationUpdate);
updateFields.forEach(field => {
const fieldValue = locationUpdate[field];
if (LOCATION_FIELDS.includes(field)) {
errors[field] = (0, _validateLocationField.default)(field, fieldValue);
}
});
if (locationUpdate.subLocations) {
const {
subLocations
} = locationUpdate;
errors['subLocations'] = (0, _validateLocationField.default)('subLocations', subLocations);
}
errors = _objectHelper.default.removeBooleanKeysFromObject(errors);
const isEmpty = _objectHelper.default.isEmpty(errors);
if (!isEmpty) {
return res.status(400).send({
errors,
message: 'Location update failed'
});
}
next();
};
var _default = validateLocationUpdate;
exports.default = _default;
|
jjuliano/brutal
|
sources/libs/embed/brutal/app.c
|
#include <ipc/ipc.h>
#include <embed/app.h>
#include <embed/win.h>
void embed_app_init(UiApp *)
{
}
void embed_app_deinit(UiApp *)
{
}
void embed_app_pump(UiApp *)
{
}
void embed_app_wait(UiApp *)
{
ipc_component_run(ipc_component_self());
}
|
haizhenhan/Kepler
|
kernel/2.6.32/drivers/net/wimax/i2400m/sdio-rx.c
|
/*
* Intel Wireless WiMAX Connection 2400m
* SDIO RX handling
*
*
* Copyright (C) 2007-2008 Intel Corporation. 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 Intel Corporation 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.
*
*
* Intel Corporation <<EMAIL>>
* <NAME> <<EMAIL>>
* - Initial implementation
*
*
* This handles the RX path on SDIO.
*
* The SDIO bus driver calls the "irq" routine when data is available.
* This is not a traditional interrupt routine since the SDIO bus
* driver calls us from its irq thread context. Because of this
* sleeping in the SDIO RX IRQ routine is okay.
*
* From there on, we obtain the size of the data that is available,
* allocate an skb, copy it and then pass it to the generic driver's
* RX routine [i2400m_rx()].
*
* ROADMAP
*
* i2400ms_irq()
* i2400ms_rx()
* __i2400ms_rx_get_size()
* i2400m_rx()
*
* i2400ms_rx_setup()
*
* i2400ms_rx_release()
*/
#include <linux/workqueue.h>
#include <linux/wait.h>
#include <linux/skbuff.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/sdio_func.h>
#include "i2400m-sdio.h"
#define D_SUBMODULE rx
#include "sdio-debug-levels.h"
static const __le32 i2400m_ACK_BARKER[4] = {
__constant_cpu_to_le32(I2400M_ACK_BARKER),
__constant_cpu_to_le32(I2400M_ACK_BARKER),
__constant_cpu_to_le32(I2400M_ACK_BARKER),
__constant_cpu_to_le32(I2400M_ACK_BARKER)
};
/*
* Read and return the amount of bytes available for RX
*
* The RX size has to be read like this: byte reads of three
* sequential locations; then glue'em together.
*
* sdio_readl() doesn't work.
*/
ssize_t __i2400ms_rx_get_size(struct i2400ms *i2400ms)
{
int ret, cnt, val;
ssize_t rx_size;
unsigned xfer_size_addr;
struct sdio_func *func = i2400ms->func;
struct device *dev = &i2400ms->func->dev;
d_fnstart(7, dev, "(i2400ms %p)\n", i2400ms);
xfer_size_addr = I2400MS_INTR_GET_SIZE_ADDR;
rx_size = 0;
for (cnt = 0; cnt < 3; cnt++) {
val = sdio_readb(func, xfer_size_addr + cnt, &ret);
if (ret < 0) {
dev_err(dev, "RX: Can't read byte %d of RX size from "
"0x%08x: %d\n", cnt, xfer_size_addr + cnt, ret);
rx_size = ret;
goto error_read;
}
rx_size = rx_size << 8 | (val & 0xff);
}
d_printf(6, dev, "RX: rx_size is %ld\n", (long) rx_size);
error_read:
d_fnend(7, dev, "(i2400ms %p) = %ld\n", i2400ms, (long) rx_size);
return rx_size;
}
/*
* Read data from the device (when in normal)
*
* Allocate an SKB of the right size, read the data in and then
* deliver it to the generic layer.
*
* We also check for a reboot barker. That means the device died and
* we have to reboot it.
*/
static
void i2400ms_rx(struct i2400ms *i2400ms)
{
int ret;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
struct sk_buff *skb;
ssize_t rx_size;
d_fnstart(7, dev, "(i2400ms %p)\n", i2400ms);
rx_size = __i2400ms_rx_get_size(i2400ms);
if (rx_size < 0) {
ret = rx_size;
goto error_get_size;
}
ret = -ENOMEM;
skb = alloc_skb(rx_size, GFP_ATOMIC);
if (NULL == skb) {
dev_err(dev, "RX: unable to alloc skb\n");
goto error_alloc_skb;
}
ret = sdio_memcpy_fromio(func, skb->data,
I2400MS_DATA_ADDR, rx_size);
if (ret < 0) {
dev_err(dev, "RX: SDIO data read failed: %d\n", ret);
goto error_memcpy_fromio;
}
rmb(); /* make sure we get boot_mode from dev_reset_handle */
if (i2400m->boot_mode == 1) {
spin_lock(&i2400m->rx_lock);
i2400ms->bm_ack_size = rx_size;
spin_unlock(&i2400m->rx_lock);
memcpy(i2400m->bm_ack_buf, skb->data, rx_size);
wake_up(&i2400ms->bm_wfa_wq);
dev_err(dev, "RX: SDIO boot mode message\n");
kfree_skb(skb);
} else if (unlikely(!memcmp(skb->data, i2400m_NBOOT_BARKER,
sizeof(i2400m_NBOOT_BARKER))
|| !memcmp(skb->data, i2400m_SBOOT_BARKER,
sizeof(i2400m_SBOOT_BARKER)))) {
ret = i2400m_dev_reset_handle(i2400m);
dev_err(dev, "RX: SDIO reboot barker\n");
kfree_skb(skb);
} else {
skb_put(skb, rx_size);
i2400m_rx(i2400m, skb);
}
d_fnend(7, dev, "(i2400ms %p) = void\n", i2400ms);
return;
error_memcpy_fromio:
kfree_skb(skb);
error_alloc_skb:
error_get_size:
d_fnend(7, dev, "(i2400ms %p) = %d\n", i2400ms, ret);
return;
}
/*
* Process an interrupt from the SDIO card
*
* FIXME: need to process other events that are not just ready-to-read
*
* Checks there is data ready and then proceeds to read it.
*/
static
void i2400ms_irq(struct sdio_func *func)
{
int ret;
struct i2400ms *i2400ms = sdio_get_drvdata(func);
struct device *dev = &func->dev;
int val;
d_fnstart(6, dev, "(i2400ms %p)\n", i2400ms);
val = sdio_readb(func, I2400MS_INTR_STATUS_ADDR, &ret);
if (ret < 0) {
dev_err(dev, "RX: Can't read interrupt status: %d\n", ret);
goto error_no_irq;
}
if (!val) {
dev_err(dev, "RX: BUG? got IRQ but no interrupt ready?\n");
goto error_no_irq;
}
sdio_writeb(func, 1, I2400MS_INTR_CLEAR_ADDR, &ret);
i2400ms_rx(i2400ms);
error_no_irq:
d_fnend(6, dev, "(i2400ms %p) = void\n", i2400ms);
return;
}
/*
* Setup SDIO RX
*
* Hooks up the IRQ handler and then enables IRQs.
*/
int i2400ms_rx_setup(struct i2400ms *i2400ms)
{
int result;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
d_fnstart(5, dev, "(i2400ms %p)\n", i2400ms);
init_waitqueue_head(&i2400ms->bm_wfa_wq);
spin_lock(&i2400m->rx_lock);
i2400ms->bm_wait_result = -EINPROGRESS;
spin_unlock(&i2400m->rx_lock);
sdio_claim_host(func);
result = sdio_claim_irq(func, i2400ms_irq);
if (result < 0) {
dev_err(dev, "Cannot claim IRQ: %d\n", result);
goto error_irq_claim;
}
result = 0;
sdio_writeb(func, 1, I2400MS_INTR_ENABLE_ADDR, &result);
if (result < 0) {
sdio_release_irq(func);
dev_err(dev, "Failed to enable interrupts %d\n", result);
}
error_irq_claim:
sdio_release_host(func);
d_fnend(5, dev, "(i2400ms %p) = %d\n", i2400ms, result);
return result;
}
/*
* Tear down SDIO RX
*
* Disables IRQs in the device and removes the IRQ handler.
*/
void i2400ms_rx_release(struct i2400ms *i2400ms)
{
int result;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
d_fnstart(5, dev, "(i2400ms %p)\n", i2400ms);
spin_lock(&i2400m->rx_lock);
i2400ms->bm_ack_size = -EINTR;
spin_unlock(&i2400m->rx_lock);
wake_up_all(&i2400ms->bm_wfa_wq);
sdio_claim_host(func);
sdio_writeb(func, 0, I2400MS_INTR_ENABLE_ADDR, &result);
sdio_release_irq(func);
sdio_release_host(func);
d_fnend(5, dev, "(i2400ms %p) = %d\n", i2400ms, result);
}
|
bloomen/densitas
|
test/manipulation_extract_row.cpp
|
<gh_stars>1-10
#include "utils.hpp"
COLLECTION(manipulation_extract_row) {
auto function = densitas::core::extract_row<double, vector_t, matrix_t>;
TEST(test_happy_path) {
const auto row1 = mkrow({1, 2, 3});
const auto row2 = mkrow({10, 20, 30});
auto matrix = matrix_t(2, 3);
matrix.row(0) = row1;
matrix.row(1) = row2;
const auto extracted_row = function(matrix, 1);
assert_equal_containers(row2, extracted_row, SPOT);
}
TEST(test_row_index_too_big) {
auto matrix = matrix_t(2, 3);
assert_throw<densitas::densitas_error>([&]() { function(matrix, 2); });
}
}
|
covers1624/WorkspaceTool
|
src/common/java/net/covers1624/wt/api/dependency/WorkspaceModuleDependency.java
|
<gh_stars>1-10
package net.covers1624.wt.api.dependency;
import net.covers1624.wt.api.workspace.WorkspaceModule;
/**
* Created by covers1624 on 8/9/19.
*/
public interface WorkspaceModuleDependency extends Dependency {
WorkspaceModule getModule();
WorkspaceModuleDependency setModule(WorkspaceModule module);
@Override
WorkspaceModuleDependency setExport(boolean value);
@Override
Dependency copy();
}
|
YongJin-Cho/poseidonos
|
test/unit-tests/journal_manager/log_buffer/journal_write_context_test.cpp
|
#include "src/journal_manager/log_buffer/journal_write_context.h"
#include <gtest/gtest.h>
namespace pos
{
TEST(LogGroupResetContext, JournalResetContext_)
{
}
TEST(LogGroupResetContext, GetLogGroupId_)
{
}
TEST(LogGroupResetContext, ResetDone_)
{
}
} // namespace pos
|
myleandrov/YogeshPateliOS
|
gruul/gruul-order-open/gruul-order-open-service/src/main/java/com/medusa/gruul/order/model/ManageDeliveryOrderVo.java
|
<filename>gruul/gruul-order-open/gruul-order-open-service/src/main/java/com/medusa/gruul/order/model/ManageDeliveryOrderVo.java<gh_stars>100-1000
package com.medusa.gruul.order.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.medusa.gruul.order.api.enums.OrderTypeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* The type Manage delivery order vo.
* <p>
* 管理端订单返回结果
*
* @author alan
* @date 2019 /11/5 21:29
*/
@Data
@ApiModel(value = "管理端订单返回结果")
public class ManageDeliveryOrderVo implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单id
*/
@ApiModelProperty(value = "订单id", example = "1")
private Long orderId;
/**
* 订单类型
*/
@ApiModelProperty(value = "订单类型")
private OrderTypeEnum type;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
private String createTime;
@ApiModelProperty(value = "用户id", example = "1")
private Long userId;
/**
* 用户帐号
*/
@ApiModelProperty(value = "用户帐号")
private String userName;
/**
* 用户头像
*/
@ApiModelProperty(value = "用户头像")
private String userAvatarUrl;
/**
* 收货人姓名
*/
@ApiModelProperty(value = "收货人姓名")
private String receiverName;
/**
* 收货人电话
*/
@ApiModelProperty(value = "收货人电话")
private String receiverPhone;
/**
* 收货人邮编
*/
@ApiModelProperty(value = "收货人邮编")
private String receiverPostCode;
/**
* 省份/直辖市
*/
@ApiModelProperty(value = "省份/直辖市")
private String receiverProvince;
/**
* 城市
*/
@ApiModelProperty(value = "城市")
private String receiverCity;
/**
* 区
*/
@ApiModelProperty(value = "区")
private String receiverRegion;
/**
* 详细地址
*/
@ApiModelProperty(value = "详细地址")
private String receiverDetailAddress;
/**
* 订单支付金额
*/
@ApiModelProperty(value = "订单支付金额")
private BigDecimal payAmount;
/**
* 订单单个商品详情
*/
@ApiModelProperty(value = "订单单个商品详情")
private List<SimpleOrderItemVo> itemVoList;
}
|
TheeBryanWhite/threepoint
|
src/redux/reducer/reducer.js
|
import { types } from "../constants/types";
const initialState = {
activeSlide: 0,
activeTeam: 0,
activeWork: 0,
footerVisible: false,
headerVisible: false,
inactiveSlide: null,
inactiveTeam: null,
inactiveWork: null,
menuOpen: false,
slideDirection: null
};
export default (state = initialState, action) => {
switch (action.type) {
case types.SET_ACTIVE_SLIDE:
return {
...state,
activeSlide: action.payload
}
case types.SET_ACTIVE_TEAM:
return {
...state,
activeTeam: action.payload
}
case types.SET_ACTIVE_WORK:
return {
...state,
activeWork: action.payload
}
case types.SET_FOOTER_STATUS:
return {
...state,
footerVisible: action.payload
}
case types.SET_HEADER_STATUS:
return {
...state,
headerVisible: action.payload
}
case types.SET_INACTIVE_SLIDE:
return {
...state,
inactiveSlide: action.payload
}
case types.SET_INACTIVE_TEAM:
return {
...state,
inactiveTeam: action.payload
}
case types.SET_INACTIVE_WORK:
return {
...state,
inactiveWork: action.payload
}
case types.SET_MENU:
return {
...state,
menuOpen: action.payload
}
case types.SET_SLIDE_DIRECTION:
return {
...state,
slideDirection: action.payload
}
default:
return {
...state
}
}
};
|
mohdab98/cmps252_hw4.2
|
src/cmps252/HW4_2/UnitTesting/record_2970.java
|
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("8")
class Record_2970 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 2970: FirstName is Rhonda")
void FirstNameOfRecord2970() {
assertEquals("Rhonda", customers.get(2969).getFirstName());
}
@Test
@DisplayName("Record 2970: LastName is Barcellos")
void LastNameOfRecord2970() {
assertEquals("Barcellos", customers.get(2969).getLastName());
}
@Test
@DisplayName("Record 2970: Company is Murnane, Robert W Esq")
void CompanyOfRecord2970() {
assertEquals("Murnane, Robert W Esq", customers.get(2969).getCompany());
}
@Test
@DisplayName("Record 2970: Address is 2320 Westwood Blvd")
void AddressOfRecord2970() {
assertEquals("2320 Westwood Blvd", customers.get(2969).getAddress());
}
@Test
@DisplayName("Record 2970: City is Los Angeles")
void CityOfRecord2970() {
assertEquals("Los Angeles", customers.get(2969).getCity());
}
@Test
@DisplayName("Record 2970: County is Los Angeles")
void CountyOfRecord2970() {
assertEquals("Los Angeles", customers.get(2969).getCounty());
}
@Test
@DisplayName("Record 2970: State is CA")
void StateOfRecord2970() {
assertEquals("CA", customers.get(2969).getState());
}
@Test
@DisplayName("Record 2970: ZIP is 90064")
void ZIPOfRecord2970() {
assertEquals("90064", customers.get(2969).getZIP());
}
@Test
@DisplayName("Record 2970: Phone is 310-474-8978")
void PhoneOfRecord2970() {
assertEquals("310-474-8978", customers.get(2969).getPhone());
}
@Test
@DisplayName("Record 2970: Fax is 310-474-0625")
void FaxOfRecord2970() {
assertEquals("310-474-0625", customers.get(2969).getFax());
}
@Test
@DisplayName("Record 2970: Email is <EMAIL>")
void EmailOfRecord2970() {
assertEquals("<EMAIL>", customers.get(2969).getEmail());
}
@Test
@DisplayName("Record 2970: Web is http://www.rhondabarcellos.com")
void WebOfRecord2970() {
assertEquals("http://www.rhondabarcellos.com", customers.get(2969).getWeb());
}
}
|
MikuNyanya/RabbitBot
|
src/main/java/gugugu/service/ImageService.java
|
package gugugu.service;
import gugugu.apirequest.saucenao.SaucenaoImageSearch;
import gugugu.bots.LoggerRabbit;
import gugugu.constant.ConstantCommon;
import gugugu.constant.ConstantConfig;
import gugugu.constant.ConstantImage;
import gugugu.entity.ImageInfo;
import gugugu.entity.apirequest.saucenao.SaucenaoSearchInfoResult;
import gugugu.entity.apirequest.saucenao.SaucenaoSearchResult;
import net.coobird.thumbnailator.Thumbnails;
import utils.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* create by MikuLink on 2020/1/15 11:17
* for the Reisen
* 一些图片处理的方法
* 有些图片处理的代码会跟随业务代码
* 这里主要存放共用且业务划分不明显的处理逻辑
*/
public class ImageService {
/**
* 随机获取一张鸽子图
* 伪随机
*
* @return 生成好的CQ码
*/
public static String getGuguguRandom() throws IOException {
String guguguPath = ConstantImage.DEFAULT_IMAGE_SAVE_PATH + "/gugugu";
//如果集合为空,读取文件列表
//只存放路径,由于使用伪随机,所以list里面的内容会一直减少
List<String> imageGuguguList = ConstantImage.map_images.get(ConstantImage.IMAGE_MAP_KEY_GUGUGU);
if (null == imageGuguguList || imageGuguguList.size() <= 0) {
String[] guguguImages = FileUtil.getList(guguguPath);
if (null == guguguImages || guguguImages.length <= 0) {
return "";
}
imageGuguguList = new ArrayList<>();
//过滤掉文件夹,和后缀不是图片的文件
for (String imagePath : guguguImages) {
if (!ImageUtil.isImage(imagePath)) {
continue;
}
//刷新内存中的列表
imageGuguguList.add(imagePath);
}
ConstantImage.map_images.put(ConstantImage.IMAGE_MAP_KEY_GUGUGU, imageGuguguList);
}
//列表中有图片,随机一个,使用伪随机
String guguguImageFullName = RandomUtil.rollAndDelStrFromList(imageGuguguList);
//生成CQ码并返回
return parseCQByLocalImagePath(guguguPath + File.separator + guguguImageFullName);
}
/**
* 根据q号获取头像CQ码,获取不到会返回空
* 大概100x100
* 使用的是第三方接口
*
* @param qq q号
* @return 生成好的cq码
*/
public static String getQLogoCq(Long qq) {
if (null == qq) {
return null;
}
String url = String.format("http://q.qlogo.cn/g?b=qq&s=100&nk=%s", qq);
//链接无后缀,是重定向后直接返回图片的,所以使用qq名称作为图片名
String qlogoImgName = String.format("qlogo_%s.jpg", qq);
try {
//检查酷Q目录下image是否存在该图片,存在就删掉重新下载,毕竟头像会变的
String coolqImgPath = ConstantImage.COOLQ_IMAGE_SAVE_PATH + File.separator + qlogoImgName;
boolean imageExists = FileUtil.exists(coolqImgPath);
if (imageExists) {
FileUtil.delete(coolqImgPath);
}
//下载头像
String qlogoLocalPath = ImageUtil.downloadImage(url, ConstantImage.DEFAULT_IMAGE_SAVE_PATH + File.separator + "qlogo", qlogoImgName);
//返回cq
return parseCQByLocalImagePath(qlogoLocalPath);
} catch (Exception ex) {
LoggerRabbit.logger().error("qq[" + qq + "]获取头像异常:" + ex.toString(), ex);
return null;
}
}
/**
* 生成本地图片的CQ码
* 如果使用CQ码通过酷Q发送图片,该图片必须在酷Q的data\image文件夹下
*
* @param localImagePath 本地文件路径,带文件和后缀的那种
* @return 生成的CQ码
*/
public static String parseCQByLocalImagePath(String localImagePath) throws IOException {
if (StringUtil.isEmpty(localImagePath)) {
return "";
}
//本地图片是否存在
if (!FileUtil.exists(localImagePath)) {
return "";
}
//获取图片名称
String imageFullName = FileUtil.getFileName(localImagePath);
//如果图片超出大小,则缩小图片,不然无法通过酷Q发送
//判断图片的大小
boolean isScale = false;
//强制转化配置
//是否不加载p站图片,由于从p站本体拉数据,还没代理,很慢
String image_scale_force = ConstantCommon.common_config.get(ConstantConfig.CONFIG_IMAGE_SCALE_FORCE);
if (ConstantConfig.ON.equalsIgnoreCase(image_scale_force)) {
isScale = true;
} else {
ImageInfo imageInfo = ImageUtil.getImageInfo(localImagePath);
boolean overSize = ConstantImage.IMAGE_SCALE_MIN_SIZE * 1024 * 1024 < imageInfo.getSize();
boolean overHeight = ConstantImage.IMAGE_SCALE_MIN_HEIGHT < imageInfo.getHeight();
boolean overWidth = ConstantImage.IMAGE_SCALE_MIN_WIDTH < imageInfo.getWidth();
isScale = overSize || overHeight || overWidth;
}
if (isScale) {
//生成修改后的文件名和路径,后缀为jpg
imageFullName = imageFullName.substring(0, imageFullName.lastIndexOf("."));
String scaleImgName = ConstantImage.IMAGE_SCALE_PREFIX + imageFullName + ".jpg";
String scaleImgPath = ConstantImage.DEFAULT_IMAGE_SCALE_SAVE_PATH + File.separator + scaleImgName;
//如果已经存在就不重复处理了
if (!FileUtil.exists(scaleImgPath)) {
//压缩图片尺寸,实际上这个方法的作用是向指定尺寸数值靠拢,比例不会变,取长宽中最接近指定数值的一方为准
// Thumbnails.of(localImagePath).size(2500, 2500).toFile(scaleImgPath);
//处理出来jpg的dpi是91,文件挺小的 所以基本上太大的文件转为jpg就行了
Thumbnails.of(localImagePath).scale(1).toFile(scaleImgPath);
}
//使用处理后的本地图片路径和文件名
imageFullName = scaleImgName;
localImagePath = scaleImgPath;
}
//检查酷Q目录下image是否存在该图片(同名文件就行,严格点需要做MD5校验确认是否是同一文件,但没必要)
boolean imageExists = FileUtil.exists(ConstantImage.COOLQ_IMAGE_SAVE_PATH + File.separator + imageFullName);
if (imageExists) {
return ImageUtil.parseCQ(imageFullName);
}
//把图片复制一份到酷Q目录下
FileUtil.copy(localImagePath, ConstantImage.COOLQ_IMAGE_SAVE_PATH);
//随机挑选一张
return ImageUtil.parseCQ(imageFullName);
}
/**
* 使用Saucenao搜图
*
* @param imgUrl 网络图片链接
* @return 搜索结果
*/
public static String searchImgFromSaucenao(String imgUrl) {
String apiKey = ConstantCommon.common_config.get(ConstantImage.SAUCENAO_API_KEY);
if (StringUtil.isEmpty(apiKey)) {
LoggerRabbit.logger().warning(ConstantImage.SAUCENAO_API_KEY_EMPTY);
return ConstantImage.SAUCENAO_API_KEY_EMPTY;
}
SaucenaoSearchInfoResult searchResult = null;
try {
//调用API
SaucenaoImageSearch request = new SaucenaoImageSearch();
request.setAccessToken(apiKey);
request.setNumres(1);
request.setUrl(imgUrl);
request.doRequest();
SaucenaoSearchResult saucenaoSearchResult = request.getEntity();
if (null == saucenaoSearchResult) {
return ConstantImage.SAUCENAO_API_SEARCH_FAIL;
}
//解析结果 header基本不用看,看结果就行,取第一个
List<SaucenaoSearchInfoResult> infoResultList = saucenaoSearchResult.getResults();
if (null == infoResultList || infoResultList.size() <= 0) {
return ConstantImage.SAUCENAO_SEARCH_FAIL;
}
for (SaucenaoSearchInfoResult infoResult : infoResultList) {
//暂时只识别pixiv和Danbooru的
int indexId = infoResult.getHeader().getIndex_id();
boolean isPixiv = 5 == indexId;
boolean isDanbooru = (9 == indexId || null != infoResult.getData().getDanbooru_id());
if (!isPixiv && !isDanbooru) {
continue;
}
//过滤掉相似度50一下的
String similarity = infoResult.getHeader().getSimilarity();
if (StringUtil.isEmpty(similarity) || 50.0 > NumberUtil.toDouble(similarity)) {
continue;
}
searchResult = infoResult;
break;
}
} catch (Exception ex) {
LoggerRabbit.logger().error(ConstantImage.SAUCENAO_API_REQUEST_ERROR + ex.toString(), ex);
return ConstantImage.SAUCENAO_API_REQUEST_ERROR;
}
if (null == searchResult) {
//没有符合条件的图片,识图失败
return ConstantImage.SAUCENAO_SEARCH_FAIL_PARAM;
}
try {
//获取信息,并返回结果
if (5 == searchResult.getHeader().getIndex_id()) {
//pixiv
//是否走爬虫
String pixiv_config_use_api = ConstantCommon.common_config.get(ConstantImage.PIXIV_CONFIG_USE_API);
if (ConstantImage.OFF.equalsIgnoreCase(pixiv_config_use_api)) {
return PixivBugService.parsePixivImgRequest(searchResult);
} else {
return PixivService.parsePixivImgRequest(searchResult);
}
} else {
//Danbooru
return DanbooruService.parseDanbooruImgRequest(searchResult);
}
} catch (FileNotFoundException fileNotFoundEx) {
LoggerRabbit.logger().warning(ConstantImage.PIXIV_IMAGE_DELETE + fileNotFoundEx.toString());
return ConstantImage.PIXIV_IMAGE_DELETE;
} catch (Exception ex) {
LoggerRabbit.logger().error(ConstantImage.IMAGE_GET_ERROR + ex.toString(), ex);
return ConstantImage.IMAGE_GET_ERROR;
}
}
}
|
Andres1599/store-arq
|
src/main/java/unis/stores/services/vehicle/IVehicleService.java
|
<reponame>Andres1599/store-arq
package unis.stores.services.vehicle;
import unis.stores.entities.Vehicle;
import java.util.List;
public interface IVehicleService {
/**
* Returns the vehicles of the system
*
* @return the list of the vehicles from the database.
*/
List<Vehicle> getVehicles();
/**
* Returns a vehicle searched by the universalCode
*
* @param universalCode this is the universalCode of the vehicle that we are looking for
* @return the vehicle retrieved from the database
*/
Vehicle getVehicle(String universalCode);
/**
* Creates a vehicle in the system
*
* @param universalCode this is the universalCode of the vehicle we want to create
* @param brand this is the brandId of the brand we want to update
* @param line this is the lineId of the line we want to update
* @param year this is the year of the vehicle we want to update
* @return the created vehicle
*/
Vehicle createVehicle(String universalCode, int brand, int line, String year);
/**
* Updates the param of a vehicle
*
* @param universalCode this is the universalCode of the vehicle that we want to update
* @param brand this is the brandId of the brand we want to update
* @param line this is the lineId of the line we want to update
* @param year this is the year of the vehicle we want to update
* @return the updated vehicle
*/
Vehicle updateVehicle(String universalCode, int brand, int line, String year);
/**
* Deletes a vehicle
*
* @param universalCode this is the universalCode of the vehicle that we are deleting
* @return a boolean specifying true if success and false in case of error
*/
boolean deleteVehicle(String universalCode);
}
|
spatialcurrent/go-adaptive-functions
|
pkg/af/Repeat.go
|
<reponame>spatialcurrent/go-adaptive-functions<filename>pkg/af/Repeat.go
// =================================================================
//
// Copyright (C) 2019 Spatial Current, Inc. - All Rights Reserved
// Released as open source under the MIT License. See LICENSE file.
//
// =================================================================
package af
import (
"bytes"
"reflect"
"strings"
)
func repeat(args ...interface{}) (interface{}, error) {
if len(args) != 2 {
return nil, &ErrInvalidArguments{Function: "Repeat", Arguments: args}
}
if count, ok := args[1].(int); ok {
if v, ok := args[0].(string); ok {
return strings.Repeat(v, count), nil
} else if v, ok := args[0].(byte); ok {
return bytes.Repeat([]byte{v}, count), nil
} else if v, ok := args[0].([]byte); ok {
return bytes.Repeat(v, count), nil
}
t := reflect.TypeOf(args[0])
if !(t.Kind() == reflect.Array || t.Kind() == reflect.Slice) {
return nil, &ErrInvalidArguments{Function: "Repeat", Arguments: args}
}
v := reflect.ValueOf(args[0])
arr := reflect.MakeSlice(t, 0, count*v.Len())
for i := 0; i < count; i++ {
arr = reflect.AppendSlice(arr, v)
}
return arr.Interface(), nil
}
return nil, &ErrInvalidArguments{Function: "Repeat", Arguments: args}
}
var Repeat = Function{
Name: "Repeat",
Aliases: []string{"repeat"},
Definitions: []Definition{
Definition{Inputs: []interface{}{reflect.Array, reflect.Int}, Output: reflect.Array},
Definition{Inputs: []interface{}{reflect.Slice, reflect.Int}, Output: reflect.Slice},
Definition{Inputs: []interface{}{reflect.String, reflect.Int}, Output: reflect.String},
Definition{Inputs: []interface{}{reflect.Uint8, reflect.Int}, Output: reflect.Slice},
},
Function: repeat,
}
|
helios-h2020/socialgraphmining
|
src/main/java/eu/h2020/helios_social/modules/socialgraphmining/GNN/simulated_communication/UncertainAvailabilitySimulation.java
|
package eu.h2020.helios_social.modules.socialgraphmining.GNN.simulated_communication;
import java.util.HashMap;
import eu.h2020.helios_social.core.contextualegonetwork.Node;
import mklab.JGNN.core.Tensor;
public class UncertainAvailabilitySimulation extends EmbeddingExchangeProtocol {
private static HashMap<String, Tensor> lastEmbeddings = new HashMap<String, Tensor>();
private double availability;
public UncertainAvailabilitySimulation(double availability) {
this.availability = availability;
}
@Override
public Tensor requestEmbeddings(Node ego, Node alter) {
if(Math.random()>availability)
return null;
return lastEmbeddings.get(alter.getId());
}
@Override
public void registerEmbeddings(Node ego, Node alter, Tensor parameters) {
if(ego == alter)
lastEmbeddings.put(ego.getId(), parameters.copy());
}
}
|
vsawchuk/CPDBv2_frontend
|
src/js/reducers/social-graph-page/geographic-data/is-crs-requested.js
|
<filename>src/js/reducers/social-graph-page/geographic-data/is-crs-requested.js
import { handleActions } from 'redux-actions';
import { LOCATION_CHANGE } from 'connected-react-router';
import { FIRST_PAGE_GEOGRAPHIC_CRS_REQUEST_SUCCESS } from 'utils/constants';
export default handleActions({
[FIRST_PAGE_GEOGRAPHIC_CRS_REQUEST_SUCCESS]: (state, action) => true,
[LOCATION_CHANGE]: (state, action) => false,
}, false);
|
Tian97/LeetCodePracticeAndSummary
|
Companies/Microsoft/src/LongestSemiAlternatingSubstring.java
|
<reponame>Tian97/LeetCodePracticeAndSummary
public class LongestSemiAlternatingSubstring {
public class Solution {
/**
* @param s: the string
* @return: length of longest semi alternating substring
*/
public int longestSemiAlternatingSubstring(String s) {
// write your code here
if(s == null || s.length() == 0)
return 0;
if(s.length() < 3)
return s.length();
int cnt = 1, l = 0, lastSeen = 0;
int res = 0;
for(int r = 1;r < s.length();r++) {
char c = s.charAt(r);
if(s.charAt(r-1) == c) {
cnt++;
}else {
cnt = 1;
lastSeen = r;
}
if(cnt > 2 && l < lastSeen)
l = lastSeen;
while(cnt > 2) {
l++;
cnt--;
}
res = Math.max(res, r - l + 1);
}
return res;
}
}
}
|
odidev/virgil-crypto-c
|
wrappers/python/virgil_crypto_lib/foundation/ctr_drbg.py
|
<gh_stars>10-100
# Copyright (C) 2015-2021 Virgil Security, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# (2) 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.
#
# (3) Neither the name of the copyright holder 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 AUTHOR ''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 AUTHOR 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.
#
# Lead Maintainer: <NAME> Inc. <<EMAIL>>
from ctypes import *
from ._c_bridge import VscfCtrDrbg
from virgil_crypto_lib.common._c_bridge import Buffer
from ._c_bridge import VscfStatus
from .random import Random
class CtrDrbg(Random):
"""Implementation of the RNG using deterministic random bit generators
based on block ciphers in counter mode (CTR_DRBG from NIST SP800-90A).
This class is thread-safe if the build option VSCF_MULTI_THREADING was enabled."""
# The interval before reseed is performed by default.
RESEED_INTERVAL = 10000
# The amount of entropy used per seed by default.
ENTROPY_LEN = 48
def __init__(self):
"""Create underlying C context."""
self._lib_vscf_ctr_drbg = VscfCtrDrbg()
self._c_impl = None
self._ctx = None
self.ctx = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_new()
def __delete__(self, instance):
"""Destroy underlying C context."""
self._lib_vscf_ctr_drbg.vscf_ctr_drbg_delete(self.ctx)
def set_entropy_source(self, entropy_source):
self._lib_vscf_ctr_drbg.vscf_ctr_drbg_use_entropy_source(self.ctx, entropy_source.c_impl)
def random(self, data_len):
"""Generate random bytes.
All RNG implementations must be thread-safe."""
data = Buffer(data_len)
status = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_random(self.ctx, data_len, data.c_buffer)
VscfStatus.handle_status(status)
return data.get_bytes()
def reseed(self):
"""Retrieve new seed data from the entropy sources."""
status = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_reseed(self.ctx)
VscfStatus.handle_status(status)
def setup_defaults(self):
"""Setup predefined values to the uninitialized class dependencies."""
status = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_setup_defaults(self.ctx)
VscfStatus.handle_status(status)
def enable_prediction_resistance(self):
"""Force entropy to be gathered at the beginning of every call to
the random() method.
Note, use this if your entropy source has sufficient throughput."""
self._lib_vscf_ctr_drbg.vscf_ctr_drbg_enable_prediction_resistance(self.ctx)
def set_reseed_interval(self, interval):
"""Sets the reseed interval.
Default value is reseed interval."""
self._lib_vscf_ctr_drbg.vscf_ctr_drbg_set_reseed_interval(self.ctx, interval)
def set_entropy_len(self, len):
"""Sets the amount of entropy grabbed on each seed or reseed.
The default value is entropy len."""
self._lib_vscf_ctr_drbg.vscf_ctr_drbg_set_entropy_len(self.ctx, len)
@classmethod
def take_c_ctx(cls, c_ctx):
inst = cls.__new__(cls)
inst._lib_vscf_ctr_drbg = VscfCtrDrbg()
inst.ctx = c_ctx
return inst
@classmethod
def use_c_ctx(cls, c_ctx):
inst = cls.__new__(cls)
inst._lib_vscf_ctr_drbg = VscfCtrDrbg()
inst.ctx = inst._lib_vscf_ctr_drbg.vscf_ctr_drbg_shallow_copy(c_ctx)
return inst
@property
def c_impl(self):
return self._c_impl
@property
def ctx(self):
return self._ctx
@ctx.setter
def ctx(self, value):
self._ctx = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_shallow_copy(value)
self._c_impl = self._lib_vscf_ctr_drbg.vscf_ctr_drbg_impl(self.ctx)
|
coderxiang/incubator-flink
|
flink-examples/flink-java-examples/src/main/java/org/apache/flink/examples/java/graph/util/EnumTrianglesData.java
|
<gh_stars>1-10
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.examples.java.graph.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.examples.java.graph.util.EnumTrianglesDataTypes.Edge;
/**
* Provides the default data sets used for the Triangle Enumeration example programs.
* The default data sets are used, if no parameters are given to the program.
*
*/
public class EnumTrianglesData {
public static final Object[][] EDGES = {
{1, 2},
{1, 3},
{1 ,4},
{1, 5},
{2, 3},
{2, 5},
{3, 4},
{3, 7},
{3, 8},
{5, 6},
{7, 8}
};
public static DataSet<Edge> getDefaultEdgeDataSet(ExecutionEnvironment env) {
List<Edge> edges = new ArrayList<Edge>();
for(Object[] e : EDGES) {
edges.add(new Edge((Integer)e[0], (Integer)e[1]));
}
return env.fromCollection(edges);
}
}
|
eapowertools/masterlib
|
tests/deleteMetricsTest.js
|
var qsocks = require('qsocks');
var qsocksInstance = require('./qsocksInstance');
var fs = require('fs');
var Promise = require('bluebird');
var appId = '831bc2ea-a43b-46f7-9ad2-d843cb9c4764';
var app2Connect = qsocksInstance(appId);
var stuff = {};
stuff.appId = appId;
qsocks.Connect(app2Connect)
.then(function(global)
{
stuff.global = global;
return global;
})
.then(function(global)
{
return global.openDoc(appId, '', '', '', true);
})
.then(function(app)
{
return stuff.app = app;
})
.then(function(app)
{
return stuff.measureList = stuff.app.createSessionObject(measureListDef());
})
.then(function(obj)
{
return obj.getLayout();
})
.then(function(layout)
{
var items = layout.qMeasureList.qItems;
var mList = items.filter(filterMasterItems);
return Promise.all(mList.map(function(listItem)
{
return stuff.app.destroyMeasure(listItem.qInfo.qId)
.then(function(success)
{
var measureInfo = listItem.qMeta.title + ':' + listItem.qInfo.qId;
console.log(measureInfo + " deleted!");
return null;
});
}));
})
.then(function()
{
return stuff.dimensionList = stuff.app.createSessionObject(dimensionListDef());
})
.then(function(obj)
{
return obj.getLayout();
})
.then(function(layout)
{
var items = layout.qDimensionList.qItems;
var dList = items.filter(filterMasterItems);
return Promise.all(dList.map(function(listItem)
{
return stuff.app.destroyDimension(listItem.qInfo.qId)
.then(function(success)
{
var dimInfo = listItem.qMeta.title + ':' + listItem.qInfo.qId;
console.log(dimInfo + " deleted!");
return null;
});
}));
})
.then(function()
{
console.log("Delete Complete");
stuff.global.connection.close();
})
.catch(function(error)
{
console.log(error);
});
function measureListDef()
{
var measureList =
{
qInfo:
{
qType: "MeasureList"
},
qMeasureListDef:
{
qType: "measure",
qData: {
title: "/title",
tags: "/tags"
}
}
};
return measureList;
};
function dimensionListDef()
{
var dimensionList =
{
qInfo:
{
qType: "DimensionList"
},
qDimensionListDef:
{
qType: "dimension",
qData: {
title: "/title",
tags: "/tags"
}
}
};
return dimensionList;
};
// function filterMasterItems(items)
// {
// //console.log(items.qMeta.tags);
// if(items.qInfo.qId.startsWith("revenue_")== true)
// {
// //console.log('Found One!');
// return true;
// }
// else
// {
// //console.log('Not a MasterItem');
// return false;
// }
// };
function filterMasterItems(items)
{
//console.log(items.qMeta.tags);
if(items.qMeta.tags.indexOf("MasterItem")!=-1)
{
//console.log('Found One!');
return true;
}
else
{
//console.log('Not a MasterItem');
return false;
}
};
|
fossabot/evemonk
|
app/workers/eve/local_graphics_importer_worker.rb
|
<filename>app/workers/eve/local_graphics_importer_worker.rb
# frozen_string_literal: true
module Eve
class LocalGraphicsImporterWorker
include Sidekiq::Worker
def perform(*)
Eve::LocalGraphicsImporter.new.import
end
end
end
|
j420247/platform_frameworks_support
|
car/core/src/main/java/androidx/car/util/CarUxRestrictionsHelper.java
|
/*
* Copyright 2018 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 androidx.car.util;
import android.app.Activity;
import android.car.Car;
import android.car.CarNotConnectedException;
import android.car.drivingstate.CarUxRestrictionsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.car.uxrestrictions.CarUxRestrictions;
import androidx.car.uxrestrictions.OnUxRestrictionsChangedListener;
/**
* Helps registering {@link OnUxRestrictionsChangedListener} and managing car connection.
*/
public class CarUxRestrictionsHelper {
private static final String TAG = "CarUxRestrictionsHelper";
// mCar is created in the constructor, but can be null if connection to the car is not
// successful.
@SuppressWarnings("WeakerAccess") /* synthetic access */
@Nullable final Car mCar;
@SuppressWarnings("WeakerAccess") /* synthetic access */
@Nullable CarUxRestrictionsManager mCarUxRestrictionsManager;
@SuppressWarnings("WeakerAccess") /* synthetic access */
final OnUxRestrictionsChangedListener mListener;
public CarUxRestrictionsHelper(Context context,
@NonNull OnUxRestrictionsChangedListener listener) {
if (listener == null) {
throw new IllegalArgumentException("Listener cannot be null.");
}
mListener = listener;
mCar = Car.createCar(context, mServiceConnection);
}
/**
* Starts monitoring any changes in {@link CarUxRestrictions}.
*
* <p>This method can be called from {@code Activity}'s {@link Activity#onStart()}, or at the
* time of construction.
*
* <p>This method must be accompanied with a matching {@link #stop()} to avoid leak.
*/
public void start() {
try {
if (mCar != null && !mCar.isConnected()) {
mCar.connect();
}
} catch (IllegalStateException e) {
// Do nothing.
Log.w(TAG, "start(); cannot connect to Car");
}
}
/**
* Stops monitoring any changes in {@link CarUxRestrictions}.
*
* <p>This method should be called from {@code Activity}'s {@link Activity#onStop()}, or at the
* time of being discarded.
*
* <p>After {@link #stop()} has been called, {@link #start()} can be called again to resume
* monitoring car ux restrictions change.
*/
public void stop() {
if (mCarUxRestrictionsManager != null) {
try {
mCarUxRestrictionsManager.unregisterListener();
} catch (CarNotConnectedException e) {
// Do nothing.
Log.w(TAG, "stop(); cannot unregister listener.");
}
}
try {
if (mCar != null && mCar.isConnected()) {
mCar.disconnect();
}
} catch (IllegalStateException e) {
// Do nothing.
Log.w(TAG, "stop(); cannot disconnect from Car.");
}
}
/**
* Gets the current UX restrictions {@link CarUxRestrictions} in place.
*
* @return current UX restrictions that is in effect. If the current UX restrictions cannot
* be obtained, the default of no active restrictions is returned.
*/
@NonNull
public CarUxRestrictions getCurrentCarUxRestrictions() {
try {
if (mCarUxRestrictionsManager != null) {
return new CarUxRestrictions(
mCarUxRestrictionsManager.getCurrentCarUxRestrictions());
}
} catch (CarNotConnectedException e) {
// Do nothing.
Log.w(TAG, "getCurrentCarUxRestrictions(); cannot get current UX restrictions.");
}
return new CarUxRestrictions.Builder(false,
CarUxRestrictions.UX_RESTRICTIONS_BASELINE, SystemClock.elapsedRealtimeNanos())
.build();
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
mCarUxRestrictionsManager = (CarUxRestrictionsManager)
mCar.getCarManager(Car.CAR_UX_RESTRICTION_SERVICE);
// Convert framework UX restrictions to androidx type.
mCarUxRestrictionsManager.registerListener(restrictions ->
mListener.onUxRestrictionsChanged(new CarUxRestrictions(restrictions)));
mListener.onUxRestrictionsChanged(new CarUxRestrictions(
mCarUxRestrictionsManager.getCurrentCarUxRestrictions()));
} catch (CarNotConnectedException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mCarUxRestrictionsManager = null;
}
};
}
|
JutelSiulad/Simulink2dL
|
Simulink2dL-Src/simulink2dl.transform/src/simulink2dl/transform/macro/SizePropagationMacro.java
|
/*******************************************************************************
* Copyright (c) 2020
* AG Embedded Systems, University of Münster
* SESE Software and Embedded Systems Engineering, TU Berlin
*
* Authors:
* <NAME>
* <NAME>
* <NAME>
*
* 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.
******************************************************************************/
package simulink2dl.transform.macro;
import java.util.LinkedList;
import java.util.List;
import simulink2dl.dlmodel.elements.Variable;
import simulink2dl.dlmodel.hybridprogram.HybridProgramCollection;
import simulink2dl.dlmodel.operator.formula.Conjunction;
import simulink2dl.dlmodel.term.PortIdentifier;
import simulink2dl.dlmodel.term.ReplaceableTerm;
import simulink2dl.dlmodel.term.Term;
import simulink2dl.dlmodel.term.VectorTerm;
import simulink2dl.transform.dlmodel.term.ExpandedTerm;
import simulink2dl.transform.model.ContinuousEvolutionBehavior;
import simulink2dl.util.PluginLogger;
/**
* Propagates the size of a linkedPort to a Term.
* Size is applied, when a VectorTerm is applied to the SizePropagationMacro
*
*/
public class SizePropagationMacro extends Macro{
private ReplaceableTerm linkedPort;
private ReplaceableTerm linkedTerm;
public SizePropagationMacro(ReplaceableTerm term, ReplaceableTerm replaceableTerm) {
linkedPort = term;
linkedTerm = replaceableTerm;
}
@Override
public ReplaceableTerm getToReplace() {
PluginLogger.error("getToReplace() should not be called for SizePropagationMacro");
return new PortIdentifier("none");
}
@Override
public Term getReplaceWith() {
return linkedTerm;
}
@Override
public void applyToContinuousBehavior(ContinuousEvolutionBehavior continuousBehavior) {
}
@Override
public void applyToHybridProgramCollection(HybridProgramCollection behavior) {
}
@Override
public boolean containsTerm(Term toReplace) {
return linkedPort.equals(toReplace);
}
@Override
public Macro createDeepCopy() {
return new SizePropagationMacro(linkedPort.createDeepCopy(), linkedTerm.createDeepCopy());
}
@Override
protected List<Macro> applySimpleMacro(SimpleMacro other) {
List<Macro> resultList = new LinkedList<Macro>();
return resultList;
}
@Override
protected List<Macro> applyVectorMacro(VectorMacro other) {
List<Macro> resultList = new LinkedList<Macro>();
VectorTerm expandedTerm = new ExpandedTerm();
int newSize = other.getReplaceWithVector().size();
if (linkedTerm instanceof Variable) {
Variable linkedVariable = (Variable) linkedTerm;
linkedVariable.setSize(newSize);
//getVector can not return ExpandedTerm directly
//as including ExpandedTerm in simulink2dl.model leads to broken project
expandedTerm = new ExpandedTerm(linkedVariable.getVector());
} else {
for (int i = 0; i<newSize; i++) {
expandedTerm.add(linkedTerm.createDeepCopy());
}
}
resultList.add(new VectorMacro(linkedTerm, expandedTerm));
return resultList;
}
public String toString() {
return linkedTerm + " resizeWith " + linkedPort;
}
@Override
public void applyToInitialConditions(Conjunction initialConditions) {
}
@Override
protected List<Macro> applyConditionalMacro(ConditionalMacro other) {
List<Macro> resultList = new LinkedList<Macro>();
for (MacroContainer outerContainer : other.getMacroContainers()) {
Macro toApply = outerContainer.getMacro();
if (!(toApply instanceof VectorMacro)) {
continue;
}
resultList = this.applyVectorMacro((VectorMacro) toApply);
break;
//TODO check for same sizes in multiple VectorMacros
}
return resultList;
}
}
|
PendaRed/sackfix
|
sackfix-common/src/main/scala/org/sackfix/field/AllocStatusField.scala
|
package org.sackfix.field
import org.sackfix.common.validated.fields.SfFieldInt
/**
* Generated by SackFix code generator on 20210314
*/
case class AllocStatusField(override val value: Int) extends SfFieldInt(87, value) {
override def toString = appendStringBuilder().toString
override def appendStringBuilder(b:StringBuilder = new StringBuilder()) = b.append("(87)AllocStatus=(").append(value).append(")").append(AllocStatusField.fixDescriptionByValue.getOrElse(value,""))
}
object AllocStatusField {
val TagId = 87
val Accepted=0
val BlockLevelReject=1
val AccountLevelReject=2
val Received=3
val Incomplete=4
val RejectedByIntermediary=5
val AllocationPending=6
val Reversed=7
lazy val fixDescriptionByValue = Map(0->"ACCEPTED",1->"BLOCK_LEVEL_REJECT",
2->"ACCOUNT_LEVEL_REJECT",3->"RECEIVED",4->"INCOMPLETE",
5->"REJECTED_BY_INTERMEDIARY",6->"ALLOCATION_PENDING",7->"REVERSED")
def apply(value: String) = try {
new AllocStatusField(value.toInt)
} catch {
case ex: Exception => throw new IllegalArgumentException("new AllocStatus("+value.toString+") failed with exception", ex)
}
def decode(a: Option[Any]) : Option[AllocStatusField] = a match {
case Some(v) => decode(v)
case _ => scala.Option.empty[AllocStatusField]
}
def decode(a: Any) : Option[AllocStatusField] = a match {
case v: String => Some(AllocStatusField(v))
case v: Int => Some(AllocStatusField(v))
case v: AllocStatusField => Some(v)
case _ => scala.Option.empty[AllocStatusField]
}
}
|
andr92/neptune
|
selenium/src/main/java/ru/tinkoff/qa/neptune/selenium/properties/SupportedWebDriverProperty.java
|
package ru.tinkoff.qa.neptune.selenium.properties;
import ru.tinkoff.qa.neptune.core.api.properties.PropertyDefaultValue;
import ru.tinkoff.qa.neptune.core.api.properties.PropertyDescription;
import ru.tinkoff.qa.neptune.core.api.properties.PropertyName;
import ru.tinkoff.qa.neptune.core.api.properties.enums.EnumPropertySuppler;
@PropertyDescription(description = {"Defines WebDriver to be started.",
"Available values: REMOTE_DRIVER, CHROME_DRIVER, EDGE_DRIVER, FIREFOX_DRIVER, IE_DRIVER, OPERA_DRIVER, SAFARI_DRIVER"},
section = "Selenium. Web driver to launch")
@PropertyName("WEB_DRIVER_TO_LAUNCH")
@PropertyDefaultValue("CHROME_DRIVER")
public final class SupportedWebDriverProperty implements EnumPropertySuppler<SupportedWebDrivers> {
public static final SupportedWebDriverProperty SUPPORTED_WEB_DRIVER_PROPERTY_PROPERTY =
new SupportedWebDriverProperty();
private SupportedWebDriverProperty() {
super();
}
}
|
Almeida154/URI-ONLINE-JUDGE
|
JAVA/BEGINNER/Uri1002.java
|
package Beginner;
// Circle Area
import java.util.Scanner;
public class Uri1002 {
public static void main(String[] args){
double r,a;
Scanner ler = new Scanner(System.in);
r=ler.nextDouble();
a=3.14159*r*r;
System.out.printf("A=%.4f\n", +a);
}
}
|
havocp/hwf
|
deps/spidermonkey/jsgc.cpp
|
<reponame>havocp/hwf<filename>deps/spidermonkey/jsgc.cpp<gh_stars>1-10
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=78:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* JS Mark-and-Sweep Garbage Collector.
*
* This GC allocates fixed-sized things with sizes up to GC_NBYTES_MAX (see
* jsgc.h). It allocates from a special GC arena pool with each arena allocated
* using malloc. It uses an ideally parallel array of flag bytes to hold the
* mark bit, finalizer type index, etc.
*
* XXX swizzle page to freelist for better locality of reference
*/
#include <stdlib.h> /* for free */
#include <math.h>
#include <string.h> /* for memset used when DEBUG */
#include "jstypes.h"
#include "jsstdint.h"
#include "jsutil.h" /* Added by JSIFY */
#include "jshash.h" /* Added by JSIFY */
#include "jsbit.h"
#include "jsclist.h"
#include "jsprf.h"
#include "jsapi.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsversion.h"
#include "jsdbgapi.h"
#include "jsexn.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsgcchunk.h"
#include "jsinterp.h"
#include "jsiter.h"
#include "jslock.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsparse.h"
#include "jsproxy.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jsstaticcheck.h"
#include "jsstr.h"
#include "jstask.h"
#include "jstracer.h"
#if JS_HAS_XML_SUPPORT
#include "jsxml.h"
#endif
#include "jsdtracef.h"
#include "jscntxtinlines.h"
#include "jsobjinlines.h"
#include "jshashtable.h"
#ifdef MOZ_VALGRIND
# define JS_VALGRIND
#endif
#ifdef JS_VALGRIND
# include <valgrind/memcheck.h>
#endif
using namespace js;
/*
* Check that JSTRACE_XML follows JSTRACE_OBJECT and JSTRACE_STRING.
*/
JS_STATIC_ASSERT(JSTRACE_OBJECT == 0);
JS_STATIC_ASSERT(JSTRACE_STRING == 1);
JS_STATIC_ASSERT(JSTRACE_XML == 2);
/*
* JS_IS_VALID_TRACE_KIND assumes that JSTRACE_STRING is the last non-xml
* trace kind when JS_HAS_XML_SUPPORT is false.
*/
JS_STATIC_ASSERT(JSTRACE_STRING + 1 == JSTRACE_XML);
/*
* Check consistency of external string constants from JSFinalizeGCThingKind.
*/
JS_STATIC_ASSERT(FINALIZE_EXTERNAL_STRING_LAST - FINALIZE_EXTERNAL_STRING0 ==
JS_EXTERNAL_STRING_LIMIT - 1);
/*
* GC memory is allocated in chunks. The size of each chunk is GC_CHUNK_SIZE.
* The chunk contains an array of GC arenas holding GC things, an array of
* the mark bitmaps for each arena, an array of JSGCArenaInfo arena
* descriptors, an array of JSGCMarkingDelay descriptors, the GCChunkInfo
* chunk descriptor and a bitmap indicating free arenas in the chunk. The
* following picture demonstrates the layout:
*
* +--------+--------------+-------+--------+------------+-----------------+
* | arenas | mark bitmaps | infos | delays | chunk info | free arena bits |
* +--------+--------------+-------+--------+------------+-----------------+
*
* To ensure fast O(1) lookup of mark bits and arena descriptors each chunk is
* allocated on GC_CHUNK_SIZE boundary. This way a simple mask and shift
* operation gives an arena index into the mark and JSGCArenaInfo arrays.
*
* All chunks that have at least one free arena are put on the doubly-linked
* list with the head stored in JSRuntime.gcChunkList. GCChunkInfo contains
* the head of the chunk's free arena list together with the link fields for
* gcChunkList.
*
* A GC arena contains GC_ARENA_SIZE bytes aligned on GC_ARENA_SIZE boundary
* and holds things of the same size and kind. The size of each thing in the
* arena must be divisible by GC_CELL_SIZE, the minimal allocation unit, and
* the size of the mark bitmap is fixed and is independent of the thing's
* size with one bit per each GC_CELL_SIZE bytes. For thing sizes that exceed
* GC_CELL_SIZE this implies that we waste space in the mark bitmap. The
* advantage is that we can find the mark bit for the thing using just
* integer shifts avoiding an expensive integer division. We trade some space
* for speed here.
*
* The number of arenas in the chunk is given by GC_ARENAS_PER_CHUNK. We find
* that number as follows. Suppose chunk contains n arenas. Together with the
* word-aligned free arena bitmap and GCChunkInfo they should fit into the
* chunk. Hence GC_ARENAS_PER_CHUNK or n_max is the maximum value of n for
* which the following holds:
*
* n*s + ceil(n/B) <= M (1)
*
* where "/" denotes normal real division,
* ceil(r) gives the least integer not smaller than the number r,
* s is the number of words in the GC arena, arena's mark bitmap,
* JSGCArenaInfo and JSGCMarkingDelay or GC_ARENA_ALL_WORDS.
* B is number of bits per word or B == JS_BITS_PER_WORD
* M is the number of words in the chunk without GCChunkInfo or
* M == (GC_CHUNK_SIZE - sizeof(JSGCArenaInfo)) / sizeof(jsuword).
*
* We rewrite the inequality as
*
* n*B*s/B + ceil(n/B) <= M,
* ceil(n*B*s/B + n/B) <= M,
* ceil(n*(B*s + 1)/B) <= M (2)
*
* We define a helper function e(n, s, B),
*
* e(n, s, B) := ceil(n*(B*s + 1)/B) - n*(B*s + 1)/B, 0 <= e(n, s, B) < 1.
*
* It gives:
*
* n*(B*s + 1)/B + e(n, s, B) <= M,
* n + e*B/(B*s + 1) <= M*B/(B*s + 1)
*
* We apply the floor function to both sides of the last equation, where
* floor(r) gives the biggest integer not greater than r. As a consequence we
* have:
*
* floor(n + e*B/(B*s + 1)) <= floor(M*B/(B*s + 1)),
* n + floor(e*B/(B*s + 1)) <= floor(M*B/(B*s + 1)),
* n <= floor(M*B/(B*s + 1)), (3)
*
* where floor(e*B/(B*s + 1)) is zero as e*B/(B*s + 1) < B/(B*s + 1) < 1.
* Thus any n that satisfies the original constraint (1) or its equivalent (2),
* must also satisfy (3). That is, we got an upper estimate for the maximum
* value of n. Lets show that this upper estimate,
*
* floor(M*B/(B*s + 1)), (4)
*
* also satisfies (1) and, as such, gives the required maximum value.
* Substituting it into (2) gives:
*
* ceil(floor(M*B/(B*s + 1))*(B*s + 1)/B) == ceil(floor(M/X)*X)
*
* where X == (B*s + 1)/B > 1. But then floor(M/X)*X <= M/X*X == M and
*
* ceil(floor(M/X)*X) <= ceil(M) == M.
*
* Thus the value of (4) gives the maximum n satisfying (1).
*
* For the final result we observe that in (4)
*
* M*B == (GC_CHUNK_SIZE - sizeof(GCChunkInfo)) / sizeof(jsuword) *
* JS_BITS_PER_WORD
* == (GC_CHUNK_SIZE - sizeof(GCChunkInfo)) * JS_BITS_PER_BYTE
*
* since GC_CHUNK_SIZE and sizeof(GCChunkInfo) are at least word-aligned.
*/
const jsuword GC_ARENA_SHIFT = 12;
const jsuword GC_ARENA_MASK = JS_BITMASK(GC_ARENA_SHIFT);
const jsuword GC_ARENA_SIZE = JS_BIT(GC_ARENA_SHIFT);
const jsuword GC_MAX_CHUNK_AGE = 3;
const size_t GC_CELL_SHIFT = 3;
const size_t GC_CELL_SIZE = size_t(1) << GC_CELL_SHIFT;
const size_t GC_CELL_MASK = GC_CELL_SIZE - 1;
const size_t BITS_PER_GC_CELL = GC_CELL_SIZE * JS_BITS_PER_BYTE;
const size_t GC_CELLS_PER_ARENA = size_t(1) << (GC_ARENA_SHIFT - GC_CELL_SHIFT);
const size_t GC_MARK_BITMAP_SIZE = GC_CELLS_PER_ARENA / JS_BITS_PER_BYTE;
const size_t GC_MARK_BITMAP_WORDS = GC_CELLS_PER_ARENA / JS_BITS_PER_WORD;
JS_STATIC_ASSERT(sizeof(jsbitmap) == sizeof(jsuword));
JS_STATIC_ASSERT(sizeof(JSString) % GC_CELL_SIZE == 0);
JS_STATIC_ASSERT(sizeof(JSObject) % GC_CELL_SIZE == 0);
JS_STATIC_ASSERT(sizeof(JSFunction) % GC_CELL_SIZE == 0);
#ifdef JSXML
JS_STATIC_ASSERT(sizeof(JSXML) % GC_CELL_SIZE == 0);
#endif
#ifdef JS_GCMETER
# define METER(x) ((void) (x))
# define METER_IF(condition, x) ((void) ((condition) && (x)))
#else
# define METER(x) ((void) 0)
# define METER_IF(condition, x) ((void) 0)
#endif
struct JSGCArenaInfo {
/*
* Allocation list for the arena.
*/
JSGCArenaList *list;
/*
* Pointer to the previous arena in a linked list. The arena can either
* belong to one of JSContext.gcArenaList lists or, when it does not have
* any allocated GC things, to the list of free arenas in the chunk with
* head stored in GCChunkInfo.lastFreeArena.
*/
JSGCArena *prev;
JSGCThing *freeList;
static inline JSGCArenaInfo *fromGCThing(void* thing);
};
/* See comments before ThingsPerUnmarkedBit below. */
struct JSGCMarkingDelay {
JSGCArena *link;
jsuword unmarkedChildren;
};
struct JSGCArena {
uint8 data[GC_ARENA_SIZE];
void checkAddress() const {
JS_ASSERT(!(reinterpret_cast<jsuword>(this) & GC_ARENA_MASK));
}
jsuword toPageStart() const {
checkAddress();
return reinterpret_cast<jsuword>(this);
}
static inline JSGCArena *fromGCThing(void* thing);
static inline JSGCArena *fromChunkAndIndex(jsuword chunk, size_t index);
jsuword getChunk() {
return toPageStart() & ~GC_CHUNK_MASK;
}
jsuword getIndex() {
return (toPageStart() & GC_CHUNK_MASK) >> GC_ARENA_SHIFT;
}
inline JSGCArenaInfo *getInfo();
inline JSGCMarkingDelay *getMarkingDelay();
inline jsbitmap *getMarkBitmap();
};
namespace js {
struct GCChunkInfo {
JSRuntime *runtime;
size_t numFreeArenas;
size_t gcChunkAge;
inline void init(JSRuntime *rt);
inline jsbitmap *getFreeArenaBitmap();
inline jsuword getChunk();
inline void clearMarkBitmap();
static inline GCChunkInfo *fromChunk(jsuword chunk);
};
} /* namespace js */
/* Check that all chunk arrays at least word-aligned. */
JS_STATIC_ASSERT(sizeof(JSGCArena) == GC_ARENA_SIZE);
JS_STATIC_ASSERT(GC_MARK_BITMAP_WORDS % sizeof(jsuword) == 0);
JS_STATIC_ASSERT(sizeof(JSGCArenaInfo) % sizeof(jsuword) == 0);
JS_STATIC_ASSERT(sizeof(JSGCMarkingDelay) % sizeof(jsuword) == 0);
const size_t GC_ARENA_ALL_WORDS = (GC_ARENA_SIZE + GC_MARK_BITMAP_SIZE +
sizeof(JSGCArenaInfo) +
sizeof(JSGCMarkingDelay)) / sizeof(jsuword);
/* The value according (4) above. */
const size_t GC_ARENAS_PER_CHUNK =
(GC_CHUNK_SIZE - sizeof(GCChunkInfo)) * JS_BITS_PER_BYTE /
(JS_BITS_PER_WORD * GC_ARENA_ALL_WORDS + 1);
const size_t GC_FREE_ARENA_BITMAP_WORDS = (GC_ARENAS_PER_CHUNK +
JS_BITS_PER_WORD - 1) /
JS_BITS_PER_WORD;
const size_t GC_FREE_ARENA_BITMAP_SIZE = GC_FREE_ARENA_BITMAP_WORDS *
sizeof(jsuword);
/* Check that GC_ARENAS_PER_CHUNK indeed maximises (1). */
JS_STATIC_ASSERT(GC_ARENAS_PER_CHUNK * GC_ARENA_ALL_WORDS +
GC_FREE_ARENA_BITMAP_WORDS <=
(GC_CHUNK_SIZE - sizeof(GCChunkInfo)) / sizeof(jsuword));
JS_STATIC_ASSERT((GC_ARENAS_PER_CHUNK + 1) * GC_ARENA_ALL_WORDS +
(GC_ARENAS_PER_CHUNK + 1 + JS_BITS_PER_WORD - 1) /
JS_BITS_PER_WORD >
(GC_CHUNK_SIZE - sizeof(GCChunkInfo)) / sizeof(jsuword));
const size_t GC_MARK_BITMAP_ARRAY_OFFSET = GC_ARENAS_PER_CHUNK
<< GC_ARENA_SHIFT;
const size_t GC_ARENA_INFO_ARRAY_OFFSET =
GC_MARK_BITMAP_ARRAY_OFFSET + GC_MARK_BITMAP_SIZE * GC_ARENAS_PER_CHUNK;
const size_t GC_MARKING_DELAY_ARRAY_OFFSET =
GC_ARENA_INFO_ARRAY_OFFSET + sizeof(JSGCArenaInfo) * GC_ARENAS_PER_CHUNK;
const size_t GC_CHUNK_INFO_OFFSET = GC_CHUNK_SIZE - GC_FREE_ARENA_BITMAP_SIZE -
sizeof(GCChunkInfo);
inline jsuword
GCChunkInfo::getChunk() {
jsuword addr = reinterpret_cast<jsuword>(this);
JS_ASSERT((addr & GC_CHUNK_MASK) == GC_CHUNK_INFO_OFFSET);
jsuword chunk = addr & ~GC_CHUNK_MASK;
return chunk;
}
inline void
GCChunkInfo::clearMarkBitmap()
{
PodZero(reinterpret_cast<jsbitmap *>(getChunk() + GC_MARK_BITMAP_ARRAY_OFFSET),
GC_MARK_BITMAP_WORDS * GC_ARENAS_PER_CHUNK);
}
/* static */
inline GCChunkInfo *
GCChunkInfo::fromChunk(jsuword chunk) {
JS_ASSERT(!(chunk & GC_CHUNK_MASK));
jsuword addr = chunk | GC_CHUNK_INFO_OFFSET;
return reinterpret_cast<GCChunkInfo *>(addr);
}
inline jsbitmap *
GCChunkInfo::getFreeArenaBitmap()
{
jsuword addr = reinterpret_cast<jsuword>(this);
return reinterpret_cast<jsbitmap *>(addr + sizeof(GCChunkInfo));
}
inline void
GCChunkInfo::init(JSRuntime *rt)
{
runtime = rt;
numFreeArenas = GC_ARENAS_PER_CHUNK;
gcChunkAge = 0;
/*
* For simplicity we set all bits to 1 including the high bits in the
* last word that corresponds to nonexistent arenas. This is fine since
* the arena scans the bitmap words from lowest to highest bits and the
* allocation checks numFreeArenas before doing the search.
*/
memset(getFreeArenaBitmap(), 0xFF, GC_FREE_ARENA_BITMAP_SIZE);
}
inline void
CheckValidGCThingPtr(void *thing)
{
#ifdef DEBUG
JS_ASSERT(!JSString::isStatic(thing));
jsuword addr = reinterpret_cast<jsuword>(thing);
JS_ASSERT(!(addr & GC_CELL_MASK));
JS_ASSERT((addr & GC_CHUNK_MASK) < GC_MARK_BITMAP_ARRAY_OFFSET);
#endif
}
/* static */
inline JSGCArenaInfo *
JSGCArenaInfo::fromGCThing(void* thing)
{
CheckValidGCThingPtr(thing);
jsuword addr = reinterpret_cast<jsuword>(thing);
jsuword chunk = addr & ~GC_CHUNK_MASK;
JSGCArenaInfo *array =
reinterpret_cast<JSGCArenaInfo *>(chunk | GC_ARENA_INFO_ARRAY_OFFSET);
size_t arenaIndex = (addr & GC_CHUNK_MASK) >> GC_ARENA_SHIFT;
return array + arenaIndex;
}
/* static */
inline JSGCArena *
JSGCArena::fromGCThing(void* thing)
{
CheckValidGCThingPtr(thing);
jsuword addr = reinterpret_cast<jsuword>(thing);
return reinterpret_cast<JSGCArena *>(addr & ~GC_ARENA_MASK);
}
/* static */
inline JSGCArena *
JSGCArena::fromChunkAndIndex(jsuword chunk, size_t index) {
JS_ASSERT(chunk);
JS_ASSERT(!(chunk & GC_CHUNK_MASK));
JS_ASSERT(index < GC_ARENAS_PER_CHUNK);
return reinterpret_cast<JSGCArena *>(chunk | (index << GC_ARENA_SHIFT));
}
inline JSGCArenaInfo *
JSGCArena::getInfo()
{
jsuword chunk = getChunk();
jsuword index = getIndex();
jsuword offset = GC_ARENA_INFO_ARRAY_OFFSET + index * sizeof(JSGCArenaInfo);
return reinterpret_cast<JSGCArenaInfo *>(chunk | offset);
}
inline JSGCMarkingDelay *
JSGCArena::getMarkingDelay()
{
jsuword chunk = getChunk();
jsuword index = getIndex();
jsuword offset = GC_MARKING_DELAY_ARRAY_OFFSET +
index * sizeof(JSGCMarkingDelay);
return reinterpret_cast<JSGCMarkingDelay *>(chunk | offset);
}
inline jsbitmap *
JSGCArena::getMarkBitmap()
{
jsuword chunk = getChunk();
jsuword index = getIndex();
jsuword offset = GC_MARK_BITMAP_ARRAY_OFFSET + index * GC_MARK_BITMAP_SIZE;
return reinterpret_cast<jsbitmap *>(chunk | offset);
}
/*
* Helpers for GC-thing operations.
*/
inline jsbitmap *
GetGCThingMarkBit(void *thing, size_t &bitIndex)
{
CheckValidGCThingPtr(thing);
jsuword addr = reinterpret_cast<jsuword>(thing);
jsuword chunk = addr & ~GC_CHUNK_MASK;
bitIndex = (addr & GC_CHUNK_MASK) >> GC_CELL_SHIFT;
return reinterpret_cast<jsbitmap *>(chunk | GC_MARK_BITMAP_ARRAY_OFFSET);
}
/*
* Live objects are marked black. How many other additional colors are available
* depends on the size of the GCThing.
*/
static const uint32 BLACK = 0;
static void
AssertValidColor(void *thing, uint32 color)
{
JS_ASSERT_IF(color, color < JSGCArenaInfo::fromGCThing(thing)->list->thingSize / GC_CELL_SIZE);
}
inline bool
IsMarkedGCThing(void *thing, uint32 color = BLACK)
{
AssertValidColor(thing, color);
size_t index;
jsbitmap *markBitmap = GetGCThingMarkBit(thing, index);
return !!JS_TEST_BIT(markBitmap, index + color);
}
/*
* The GC always marks live objects BLACK. If color is not BLACK, we also mark
* the object with that additional color.
*/
inline bool
MarkIfUnmarkedGCThing(void *thing, uint32 color = BLACK)
{
AssertValidColor(thing, color);
size_t index;
jsbitmap *markBitmap = GetGCThingMarkBit(thing, index);
if (JS_TEST_BIT(markBitmap, index))
return false;
JS_SET_BIT(markBitmap, index);
if (color != BLACK)
JS_SET_BIT(markBitmap, index + color);
return true;
}
size_t
ThingsPerArena(size_t thingSize)
{
JS_ASSERT(!(thingSize & GC_CELL_MASK));
JS_ASSERT(thingSize <= GC_ARENA_SIZE);
return GC_ARENA_SIZE / thingSize;
}
/* Can only be called if thing belongs to an arena where a->list is not null. */
inline size_t
GCThingToArenaIndex(void *thing)
{
CheckValidGCThingPtr(thing);
jsuword addr = reinterpret_cast<jsuword>(thing);
jsuword offsetInArena = addr & GC_ARENA_MASK;
JSGCArenaInfo *a = JSGCArenaInfo::fromGCThing(thing);
JS_ASSERT(a->list);
JS_ASSERT(offsetInArena % a->list->thingSize == 0);
return offsetInArena / a->list->thingSize;
}
/* Can only be applicable to arena where a->list is not null. */
inline uint8 *
GCArenaIndexToThing(JSGCArena *a, JSGCArenaInfo *ainfo, size_t index)
{
JS_ASSERT(a->getInfo() == ainfo);
/*
* We use "<=" and not "<" in the assert so index can mean the limit.
* For the same reason we use "+", not "|" when finding the thing address
* as the limit address can start at the next arena.
*/
JS_ASSERT(index <= ThingsPerArena(ainfo->list->thingSize));
jsuword offsetInArena = index * ainfo->list->thingSize;
return reinterpret_cast<uint8 *>(a->toPageStart() + offsetInArena);
}
/*
* The private JSGCThing struct, which describes a JSRuntime.gcFreeList element.
*/
struct JSGCThing {
JSGCThing *link;
};
static inline JSGCThing *
MakeNewArenaFreeList(JSGCArena *a, size_t thingSize)
{
jsuword thingsStart = a->toPageStart();
jsuword lastThingMinAddr = thingsStart + GC_ARENA_SIZE - thingSize * 2 + 1;
jsuword thingPtr = thingsStart;
do {
jsuword nextPtr = thingPtr + thingSize;
JS_ASSERT((nextPtr & GC_ARENA_MASK) + thingSize <= GC_ARENA_SIZE);
JSGCThing *thing = reinterpret_cast<JSGCThing *>(thingPtr);
thing->link = reinterpret_cast<JSGCThing *>(nextPtr);
thingPtr = nextPtr;
} while (thingPtr < lastThingMinAddr);
JSGCThing *lastThing = reinterpret_cast<JSGCThing *>(thingPtr);
lastThing->link = NULL;
return reinterpret_cast<JSGCThing *>(thingsStart);
}
inline jsuword
GetGCChunk(JSRuntime *rt)
{
void *p = rt->gcChunkAllocator->alloc();
#ifdef MOZ_GCTIMER
if (p)
JS_ATOMIC_INCREMENT(&newChunkCount);
#endif
METER_IF(p, rt->gcStats.nchunks++);
METER_UPDATE_MAX(rt->gcStats.maxnchunks, rt->gcStats.nchunks);
return reinterpret_cast<jsuword>(p);
}
inline void
ReleaseGCChunk(JSRuntime *rt, jsuword chunk)
{
void *p = reinterpret_cast<void *>(chunk);
JS_ASSERT(p);
#ifdef MOZ_GCTIMER
JS_ATOMIC_INCREMENT(&destroyChunkCount);
#endif
JS_ASSERT(rt->gcStats.nchunks != 0);
METER(rt->gcStats.nchunks--);
rt->gcChunkAllocator->free(p);
}
static JSGCArena *
NewGCArena(JSContext *cx)
{
JSRuntime *rt = cx->runtime;
if (!JS_THREAD_DATA(cx)->waiveGCQuota && rt->gcBytes >= rt->gcMaxBytes) {
/*
* FIXME bug 524051 We cannot run a last-ditch GC on trace for now, so
* just pretend we are out of memory which will throw us off trace and
* we will re-try this code path from the interpreter.
*/
if (!JS_ON_TRACE(cx))
return NULL;
js_TriggerGC(cx, true);
}
if (rt->gcFreeArenaChunks.empty()) {
#ifdef DEBUG
for (GCChunkSet::Range r(rt->gcChunkSet.all()); !r.empty(); r.popFront())
JS_ASSERT(GCChunkInfo::fromChunk(r.front())->numFreeArenas == 0);
#endif
/*
* Make sure that after the GC we can append all allocated chunks to
* gcFreeArenaChunks.
*
* FIXME bug 583729 - use the same for the rt->gcChunkSet.
*/
if (!rt->gcFreeArenaChunks.reserve(rt->gcChunkSet.count() + 1))
return NULL;
jsuword chunk = GetGCChunk(rt);
if (!chunk)
return NULL;
GCChunkInfo *ci = GCChunkInfo::fromChunk(chunk);
ci->init(rt);
/*
* FIXME bug 583732 - chunk is newly allocated and cannot present in
* the table so using ordinary lookupForAdd is suboptimal here.
*/
GCChunkSet::AddPtr p = rt->gcChunkSet.lookupForAdd(chunk);
JS_ASSERT(!p);
if (!rt->gcChunkSet.add(p, chunk)) {
ReleaseGCChunk(rt, chunk);
return NULL;
}
JS_ALWAYS_TRUE(rt->gcFreeArenaChunks.append(ci));
}
GCChunkInfo *ci = rt->gcFreeArenaChunks.back();
JS_ASSERT(ci->numFreeArenas);
/* Scan the bitmap for the first non-zero bit. */
jsbitmap *freeArenas = ci->getFreeArenaBitmap();
size_t arenaIndex = 0;
while (!*freeArenas) {
arenaIndex += JS_BITS_PER_WORD;
freeArenas++;
}
size_t bit = CountTrailingZeros(*freeArenas);
arenaIndex += bit;
JS_ASSERT(arenaIndex < GC_ARENAS_PER_CHUNK);
JS_ASSERT(*freeArenas & (jsuword(1) << bit));
*freeArenas &= ~(jsuword(1) << bit);
--ci->numFreeArenas;
if (ci->numFreeArenas == 0) {
JS_ASSERT(ci == rt->gcFreeArenaChunks.back());
rt->gcFreeArenaChunks.popBack();
}
rt->gcBytes += GC_ARENA_SIZE;
METER(rt->gcStats.nallarenas++);
METER_UPDATE_MAX(rt->gcStats.maxnallarenas, rt->gcStats.nallarenas);
return JSGCArena::fromChunkAndIndex(ci->getChunk(), arenaIndex);
}
/*
* This function does not touch the arena or release its memory so code can
* still refer into it.
*/
static void
ReleaseGCArena(JSRuntime *rt, JSGCArena *a)
{
METER(rt->gcStats.afree++);
JS_ASSERT(rt->gcBytes >= GC_ARENA_SIZE);
rt->gcBytes -= GC_ARENA_SIZE;
JS_ASSERT(rt->gcStats.nallarenas != 0);
METER(rt->gcStats.nallarenas--);
jsuword chunk = a->getChunk();
GCChunkInfo *ci = GCChunkInfo::fromChunk(chunk);
JS_ASSERT(ci->numFreeArenas <= GC_ARENAS_PER_CHUNK - 1);
jsbitmap *freeArenas = ci->getFreeArenaBitmap();
JS_ASSERT(!JS_TEST_BIT(freeArenas, a->getIndex()));
JS_SET_BIT(freeArenas, a->getIndex());
ci->numFreeArenas++;
if (ci->numFreeArenas == GC_ARENAS_PER_CHUNK)
ci->gcChunkAge = 0;
#ifdef DEBUG
a->getInfo()->prev = rt->gcEmptyArenaList;
rt->gcEmptyArenaList = a;
#endif
}
static void
FreeGCChunks(JSRuntime *rt)
{
#ifdef DEBUG
while (rt->gcEmptyArenaList) {
JSGCArena *next = rt->gcEmptyArenaList->getInfo()->prev;
memset(rt->gcEmptyArenaList, JS_FREE_PATTERN, GC_ARENA_SIZE);
rt->gcEmptyArenaList = next;
}
#endif
/* Remove unused chunks and rebuild gcFreeArenaChunks. */
rt->gcFreeArenaChunks.clear();
JS_ASSERT(rt->gcFreeArenaChunks.capacity() >= rt->gcChunkSet.count());
for (GCChunkSet::Enum e(rt->gcChunkSet); !e.empty(); e.popFront()) {
GCChunkInfo *ci = GCChunkInfo::fromChunk(e.front());
JS_ASSERT(ci->runtime == rt);
if (ci->numFreeArenas == GC_ARENAS_PER_CHUNK) {
if (ci->gcChunkAge > GC_MAX_CHUNK_AGE) {
e.removeFront();
ReleaseGCChunk(rt, ci->getChunk());
continue;
}
ci->gcChunkAge++;
}
if (ci->numFreeArenas)
JS_ALWAYS_TRUE(rt->gcFreeArenaChunks.append(ci));
}
}
static inline size_t
GetFinalizableThingSize(unsigned thingKind)
{
JS_STATIC_ASSERT(JS_EXTERNAL_STRING_LIMIT == 8);
static const uint8 map[FINALIZE_LIMIT] = {
sizeof(JSObject), /* FINALIZE_OBJECT */
sizeof(JSFunction), /* FINALIZE_FUNCTION */
#if JS_HAS_XML_SUPPORT
sizeof(JSXML), /* FINALIZE_XML */
#endif
sizeof(JSShortString), /* FINALIZE_SHORT_STRING */
sizeof(JSString), /* FINALIZE_STRING */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING0 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING1 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING2 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING3 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING4 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING5 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING6 */
sizeof(JSString), /* FINALIZE_EXTERNAL_STRING7 */
};
JS_ASSERT(thingKind < FINALIZE_LIMIT);
return map[thingKind];
}
static inline size_t
GetFinalizableTraceKind(size_t thingKind)
{
JS_STATIC_ASSERT(JS_EXTERNAL_STRING_LIMIT == 8);
static const uint8 map[FINALIZE_LIMIT] = {
JSTRACE_OBJECT, /* FINALIZE_OBJECT */
JSTRACE_OBJECT, /* FINALIZE_FUNCTION */
#if JS_HAS_XML_SUPPORT /* FINALIZE_XML */
JSTRACE_XML,
#endif
JSTRACE_STRING, /* FINALIZE_SHORT_STRING */
JSTRACE_STRING, /* FINALIZE_STRING */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING0 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING1 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING2 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING3 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING4 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING5 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING6 */
JSTRACE_STRING, /* FINALIZE_EXTERNAL_STRING7 */
};
JS_ASSERT(thingKind < FINALIZE_LIMIT);
return map[thingKind];
}
static inline size_t
GetFinalizableArenaTraceKind(JSGCArenaInfo *ainfo)
{
JS_ASSERT(ainfo->list);
return GetFinalizableTraceKind(ainfo->list->thingKind);
}
static inline size_t
GetArenaTraceKind(JSGCArenaInfo *ainfo)
{
return GetFinalizableArenaTraceKind(ainfo);
}
static inline size_t
GetFinalizableThingTraceKind(void *thing)
{
JSGCArenaInfo *ainfo = JSGCArenaInfo::fromGCThing(thing);
return GetFinalizableArenaTraceKind(ainfo);
}
static void
InitGCArenaLists(JSRuntime *rt)
{
for (unsigned i = 0; i != FINALIZE_LIMIT; ++i) {
JSGCArenaList *arenaList = &rt->gcArenaList[i];
arenaList->head = NULL;
arenaList->cursor = NULL;
arenaList->thingKind = i;
arenaList->thingSize = GetFinalizableThingSize(i);
}
}
static void
FinishGCArenaLists(JSRuntime *rt)
{
for (unsigned i = 0; i < FINALIZE_LIMIT; i++) {
rt->gcArenaList[i].head = NULL;
rt->gcArenaList[i].cursor = NULL;
}
rt->gcBytes = 0;
for (GCChunkSet::Range r(rt->gcChunkSet.all()); !r.empty(); r.popFront())
ReleaseGCChunk(rt, r.front());
rt->gcChunkSet.clear();
rt->gcFreeArenaChunks.clear();
}
intN
js_GetExternalStringGCType(JSString *str)
{
JS_STATIC_ASSERT(FINALIZE_STRING + 1 == FINALIZE_EXTERNAL_STRING0);
JS_ASSERT(!JSString::isStatic(str));
unsigned thingKind = JSGCArenaInfo::fromGCThing(str)->list->thingKind;
JS_ASSERT(IsFinalizableStringKind(thingKind));
return intN(thingKind) - intN(FINALIZE_EXTERNAL_STRING0);
}
JS_FRIEND_API(uint32)
js_GetGCThingTraceKind(void *thing)
{
if (JSString::isStatic(thing))
return JSTRACE_STRING;
JSGCArenaInfo *ainfo = JSGCArenaInfo::fromGCThing(thing);
return GetArenaTraceKind(ainfo);
}
JSRuntime *
js_GetGCThingRuntime(void *thing)
{
jsuword chunk = JSGCArena::fromGCThing(thing)->getChunk();
return GCChunkInfo::fromChunk(chunk)->runtime;
}
JS_FRIEND_API(bool)
js_IsAboutToBeFinalized(void *thing)
{
if (JSString::isStatic(thing))
return false;
return !IsMarkedGCThing(thing);
}
JS_FRIEND_API(bool)
js_GCThingIsMarked(void *thing, uint32 color)
{
return IsMarkedGCThing(thing, color);
}
JSBool
js_InitGC(JSRuntime *rt, uint32 maxbytes)
{
InitGCArenaLists(rt);
/*
* Make room for at least 16 chunks so the table would not grow before
* the browser starts up.
*/
if (!rt->gcChunkSet.init(16))
return false;
if (!rt->gcRootsHash.init(256))
return false;
if (!rt->gcLocksHash.init(256))
return false;
#ifdef JS_THREADSAFE
if (!rt->gcHelperThread.init())
return false;
#endif
/*
* Separate gcMaxMallocBytes from gcMaxBytes but initialize to maxbytes
* for default backward API compatibility.
*/
rt->gcMaxBytes = maxbytes;
rt->setGCMaxMallocBytes(maxbytes);
rt->gcEmptyArenaPoolLifespan = 30000;
/*
* By default the trigger factor gets maximum possible value. This
* means that GC will not be triggered by growth of GC memory (gcBytes).
*/
rt->setGCTriggerFactor((uint32) -1);
/*
* The assigned value prevents GC from running when GC memory is too low
* (during JS engine start).
*/
rt->setGCLastBytes(8192);
METER(PodZero(&rt->gcStats));
return true;
}
namespace js {
/*
* Returns CGCT_VALID if the w can be a live GC thing and sets thing and traceKind
* accordingly. Otherwise returns the reason for rejection.
*/
inline ConservativeGCTest
IsGCThingWord(JSRuntime *rt, jsuword w, void *&thing, uint32 &traceKind)
{
/*
* The conservative scanner may access words that valgrind considers as
* undefined. To avoid false positives and not to alter valgrind view of
* the memory we make as memcheck-defined the argument, a copy of the
* original word. See bug 572678.
*/
#ifdef JS_VALGRIND
VALGRIND_MAKE_MEM_DEFINED(&w, sizeof(w));
#endif
/*
* We assume that the compiler never uses sub-word alignment to store
* pointers and does not tag pointers on its own. Additionally, the value
* representation for all values and the jsid representation for GC-things
* do not touch the low two bits. Thus any word with the low two bits set
* is not a valid GC-thing.
*/
JS_STATIC_ASSERT(JSID_TYPE_STRING == 0 && JSID_TYPE_OBJECT == 4);
if (w & 0x3)
return CGCT_LOWBITSET;
/*
* An object jsid has its low bits tagged. In the value representation on
* 64-bit, the high bits are tagged.
*/
const jsuword JSID_PAYLOAD_MASK = ~jsuword(JSID_TYPE_MASK);
#if JS_BITS_PER_WORD == 32
jsuword payload = w & JSID_PAYLOAD_MASK;
#elif JS_BITS_PER_WORD == 64
jsuword payload = w & JSID_PAYLOAD_MASK & JSVAL_PAYLOAD_MASK;
#endif
jsuword chunk = payload & ~GC_CHUNK_MASK;
if (!rt->gcChunkSet.has(chunk))
return CGCT_NOTCHUNK;
GCChunkInfo *ci = GCChunkInfo::fromChunk(chunk);
if ((payload & GC_CHUNK_MASK) >= GC_MARK_BITMAP_ARRAY_OFFSET)
return CGCT_NOTARENA;
size_t arenaIndex = (payload & GC_CHUNK_MASK) >> GC_ARENA_SHIFT;
if (JS_TEST_BIT(ci->getFreeArenaBitmap(), arenaIndex))
return CGCT_FREEARENA;
JSGCArena *a = JSGCArena::fromChunkAndIndex(chunk, arenaIndex);
JSGCArenaInfo *ainfo = a->getInfo();
traceKind = GetFinalizableArenaTraceKind(ainfo);
/*
* On 64-bit we might consider using the tag bits in w to disqualify
* additional false roots, however, the condition would have to look
* something like:
*
* if ((traceKind == JSTRACE_STRING && tag > 0 && tag != JSVAL_TAG_SHIFT) ||
* (traceKind == JSTRACE_OBJECT && tag > 0 && tag != JSVAL_TAG_OBJECT))
* return CGCT_WRONGTAG;
*
* However, it seems like we should measure how often this actually avoids
* false roots.
*/
jsuword start = a->toPageStart();
jsuword offset = payload - start;
size_t thingSize = ainfo->list->thingSize;
offset -= offset % thingSize;
/*
* If GC_ARENA_SIZE % thingSize != 0 or when thingSize is not a power
* of two, thingSize-aligned pointer may point at the end of the last
* thing yet be inside the arena.
*/
if (offset + thingSize > GC_ARENA_SIZE) {
JS_ASSERT(thingSize & (thingSize - 1));
return CGCT_NOTARENA;
}
thing = (JSGCThing *) (start + offset);
/* Make sure the thing is not on the freelist of the arena. */
JSGCThing *cursor = ainfo->freeList;
while (cursor) {
JS_ASSERT((((jsuword) cursor) & GC_ARENA_MASK) % thingSize == 0);
JS_ASSERT(!IsMarkedGCThing(cursor));
/* If the cursor moves past the thing, it's not in the freelist. */
if (thing < cursor)
break;
/* If we find it on the freelist, it's dead. */
if (thing == cursor)
return CGCT_NOTLIVE;
JS_ASSERT_IF(cursor->link, cursor < cursor->link);
cursor = cursor->link;
}
return CGCT_VALID;
}
inline ConservativeGCTest
IsGCThingWord(JSRuntime *rt, jsuword w)
{
void *thing;
uint32 traceKind;
return IsGCThingWord(rt, w, thing, traceKind);
}
static void
MarkWordConservatively(JSTracer *trc, jsuword w)
{
/*
* The conservative scanner may access words that valgrind considers as
* undefined. To avoid false positives and not to alter valgrind view of
* the memory we make as memcheck-defined the argument, a copy of the
* original word. See bug 572678.
*/
#ifdef JS_VALGRIND
VALGRIND_MAKE_MEM_DEFINED(&w, sizeof(w));
#endif
void *thing;
uint32 traceKind;
ConservativeGCTest test = IsGCThingWord(trc->context->runtime, w, thing, traceKind);
if (test == CGCT_VALID) {
Mark(trc, thing, traceKind, "machine stack");
#ifdef JS_DUMP_CONSERVATIVE_GC_ROOTS
if (IS_GC_MARKING_TRACER(trc) && static_cast<GCMarker *>(trc)->conservativeDumpFileName) {
GCMarker::ConservativeRoot root = {thing, traceKind};
static_cast<GCMarker *>(trc)->conservativeRoots.append(root);
}
#endif
}
#if defined JS_DUMP_CONSERVATIVE_GC_ROOTS || defined JS_GCMETER
if (IS_GC_MARKING_TRACER(trc))
static_cast<GCMarker *>(trc)->conservativeStats.counter[test]++;
#endif
}
static void
MarkRangeConservatively(JSTracer *trc, jsuword *begin, jsuword *end)
{
JS_ASSERT(begin <= end);
for (jsuword *i = begin; i != end; ++i)
MarkWordConservatively(trc, *i);
}
void
MarkConservativeStackRoots(JSTracer *trc)
{
/* Do conservative scanning of the stack and registers. */
for (ThreadDataIter i(trc->context->runtime); !i.empty(); i.popFront()) {
JSThreadData *td = i.threadData();
ConservativeGCThreadData *ctd = &td->conservativeGC;
if (ctd->isEnabled()) {
jsuword *stackMin, *stackEnd;
#if JS_STACK_GROWTH_DIRECTION > 0
stackMin = td->nativeStackBase;
stackEnd = ctd->nativeStackTop;
#else
stackMin = ctd->nativeStackTop + 1;
stackEnd = td->nativeStackBase;
#endif
JS_ASSERT(stackMin <= stackEnd);
MarkRangeConservatively(trc, stackMin, stackEnd);
MarkRangeConservatively(trc, ctd->registerSnapshot.words,
JS_ARRAY_END(ctd->registerSnapshot.words));
}
}
}
JS_NEVER_INLINE JS_FRIEND_API(void)
ConservativeGCThreadData::enable(bool knownStackBoundary)
{
++enableCount;
if (enableCount <= 0)
return;
/* Update the native stack pointer if it points to a bigger stack. */
#if JS_STACK_GROWTH_DIRECTION > 0
# define CMP >
#else
# define CMP <
#endif
jsuword dummy;
if (knownStackBoundary || enableCount == 1 || &dummy CMP nativeStackTop)
nativeStackTop = &dummy;
#undef CMP
/* Update the register snapshot with the latest values. */
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable: 4611)
#endif
setjmp(registerSnapshot.jmpbuf);
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
}
JS_NEVER_INLINE JS_FRIEND_API(void)
ConservativeGCThreadData::disable()
{
--enableCount;
#ifdef DEBUG
if (enableCount == 0)
nativeStackTop = NULL;
#endif
}
} /* namespace js */
#ifdef DEBUG
static void
CheckLeakedRoots(JSRuntime *rt);
#endif
void
js_FinishGC(JSRuntime *rt)
{
#ifdef JS_ARENAMETER
JS_DumpArenaStats(stdout);
#endif
#ifdef JS_GCMETER
if (JS_WANT_GC_METER_PRINT)
js_DumpGCStats(rt, stdout);
#endif
#ifdef JS_THREADSAFE
rt->gcHelperThread.cancel();
#endif
FinishGCArenaLists(rt);
#ifdef DEBUG
if (!rt->gcRootsHash.empty())
CheckLeakedRoots(rt);
#endif
rt->gcRootsHash.clear();
rt->gcLocksHash.clear();
}
JSBool
js_AddRoot(JSContext *cx, Value *vp, const char *name)
{
JSBool ok = js_AddRootRT(cx->runtime, Jsvalify(vp), name);
if (!ok)
JS_ReportOutOfMemory(cx);
return ok;
}
JSBool
js_AddGCThingRoot(JSContext *cx, void **rp, const char *name)
{
JSBool ok = js_AddGCThingRootRT(cx->runtime, rp, name);
if (!ok)
JS_ReportOutOfMemory(cx);
return ok;
}
JS_FRIEND_API(JSBool)
js_AddRootRT(JSRuntime *rt, jsval *vp, const char *name)
{
/*
* Due to the long-standing, but now removed, use of rt->gcLock across the
* bulk of js_GC, API users have come to depend on JS_AddRoot etc. locking
* properly with a racing GC, without calling JS_AddRoot from a request.
* We have to preserve API compatibility here, now that we avoid holding
* rt->gcLock across the mark phase (including the root hashtable mark).
*/
AutoLockGC lock(rt);
js_WaitForGC(rt);
return !!rt->gcRootsHash.put((void *)vp,
RootInfo(name, JS_GC_ROOT_VALUE_PTR));
}
JS_FRIEND_API(JSBool)
js_AddGCThingRootRT(JSRuntime *rt, void **rp, const char *name)
{
/*
* Due to the long-standing, but now removed, use of rt->gcLock across the
* bulk of js_GC, API users have come to depend on JS_AddRoot etc. locking
* properly with a racing GC, without calling JS_AddRoot from a request.
* We have to preserve API compatibility here, now that we avoid holding
* rt->gcLock across the mark phase (including the root hashtable mark).
*/
AutoLockGC lock(rt);
js_WaitForGC(rt);
return !!rt->gcRootsHash.put((void *)rp,
RootInfo(name, JS_GC_ROOT_GCTHING_PTR));
}
JS_FRIEND_API(JSBool)
js_RemoveRoot(JSRuntime *rt, void *rp)
{
/*
* Due to the JS_RemoveRootRT API, we may be called outside of a request.
* Same synchronization drill as above in js_AddRoot.
*/
AutoLockGC lock(rt);
js_WaitForGC(rt);
rt->gcRootsHash.remove(rp);
rt->gcPoke = JS_TRUE;
return JS_TRUE;
}
typedef RootedValueMap::Range RootRange;
typedef RootedValueMap::Entry RootEntry;
typedef RootedValueMap::Enum RootEnum;
#ifdef DEBUG
static void
CheckLeakedRoots(JSRuntime *rt)
{
uint32 leakedroots = 0;
/* Warn (but don't assert) debug builds of any remaining roots. */
for (RootRange r = rt->gcRootsHash.all(); !r.empty(); r.popFront()) {
RootEntry &entry = r.front();
leakedroots++;
fprintf(stderr,
"JS engine warning: leaking GC root \'%s\' at %p\n",
entry.value.name ? entry.value.name : "", entry.key);
}
if (leakedroots > 0) {
if (leakedroots == 1) {
fprintf(stderr,
"JS engine warning: 1 GC root remains after destroying the JSRuntime at %p.\n"
" This root may point to freed memory. Objects reachable\n"
" through it have not been finalized.\n",
(void *) rt);
} else {
fprintf(stderr,
"JS engine warning: %lu GC roots remain after destroying the JSRuntime at %p.\n"
" These roots may point to freed memory. Objects reachable\n"
" through them have not been finalized.\n",
(unsigned long) leakedroots, (void *) rt);
}
}
}
void
js_DumpNamedRoots(JSRuntime *rt,
void (*dump)(const char *name, void *rp, JSGCRootType type, void *data),
void *data)
{
for (RootRange r = rt->gcRootsHash.all(); !r.empty(); r.popFront()) {
RootEntry &entry = r.front();
if (const char *name = entry.value.name)
dump(name, entry.key, entry.value.type, data);
}
}
#endif /* DEBUG */
uint32
js_MapGCRoots(JSRuntime *rt, JSGCRootMapFun map, void *data)
{
AutoLockGC lock(rt);
int ct = 0;
for (RootEnum e(rt->gcRootsHash); !e.empty(); e.popFront()) {
RootEntry &entry = e.front();
ct++;
intN mapflags = map(entry.key, entry.value.type, entry.value.name, data);
if (mapflags & JS_MAP_GCROOT_REMOVE)
e.removeFront();
if (mapflags & JS_MAP_GCROOT_STOP)
break;
}
return ct;
}
void
JSRuntime::setGCTriggerFactor(uint32 factor)
{
JS_ASSERT(factor >= 100);
gcTriggerFactor = factor;
setGCLastBytes(gcLastBytes);
}
void
JSRuntime::setGCLastBytes(size_t lastBytes)
{
gcLastBytes = lastBytes;
uint64 triggerBytes = uint64(lastBytes) * uint64(gcTriggerFactor / 100);
if (triggerBytes != size_t(triggerBytes))
triggerBytes = size_t(-1);
gcTriggerBytes = size_t(triggerBytes);
}
void
JSGCFreeLists::purge()
{
/*
* Return the free list back to the arena so the GC finalization will not
* run the finalizers over unitialized bytes from free things.
*/
for (JSGCThing **p = finalizables; p != JS_ARRAY_END(finalizables); ++p) {
JSGCThing *freeListHead = *p;
if (freeListHead) {
JSGCArenaInfo *ainfo = JSGCArenaInfo::fromGCThing(freeListHead);
JS_ASSERT(!ainfo->freeList);
ainfo->freeList = freeListHead;
*p = NULL;
}
}
}
void
JSGCFreeLists::moveTo(JSGCFreeLists *another)
{
*another = *this;
PodArrayZero(finalizables);
JS_ASSERT(isEmpty());
}
static inline bool
IsGCThresholdReached(JSRuntime *rt)
{
#ifdef JS_GC_ZEAL
if (rt->gcZeal >= 1)
return true;
#endif
/*
* Since the initial value of the gcLastBytes parameter is not equal to
* zero (see the js_InitGC function) the return value is false when
* the gcBytes value is close to zero at the JS engine start.
*/
return rt->isGCMallocLimitReached() || rt->gcBytes >= rt->gcTriggerBytes;
}
static void
LastDitchGC(JSContext *cx)
{
JS_ASSERT(!JS_ON_TRACE(cx));
/* The last ditch GC preserves weak roots and all atoms. */
AutoKeepAtoms keep(cx->runtime);
/*
* Keep rt->gcLock across the call into the GC so we don't starve and
* lose to racing threads who deplete the heap just after the GC has
* replenished it (or has synchronized with a racing GC that collected a
* bunch of garbage). This unfair scheduling can happen on certain
* operating systems. For the gory details, see bug 162779.
*/
js_GC(cx, GC_LOCK_HELD);
}
static JSGCThing *
RefillFinalizableFreeList(JSContext *cx, unsigned thingKind)
{
JS_ASSERT(!JS_THREAD_DATA(cx)->gcFreeLists.finalizables[thingKind]);
JSRuntime *rt = cx->runtime;
JSGCArenaList *arenaList;
JSGCArena *a;
{
AutoLockGC lock(rt);
JS_ASSERT(!rt->gcRunning);
if (rt->gcRunning)
return NULL;
bool canGC = !JS_ON_TRACE(cx) && !JS_THREAD_DATA(cx)->waiveGCQuota;
bool doGC = canGC && IsGCThresholdReached(rt);
arenaList = &rt->gcArenaList[thingKind];
for (;;) {
if (doGC) {
LastDitchGC(cx);
METER(cx->runtime->gcArenaStats[thingKind].retry++);
canGC = false;
/*
* The JSGC_END callback can legitimately allocate new GC
* things and populate the free list. If that happens, just
* return that list head.
*/
JSGCThing *freeList = JS_THREAD_DATA(cx)->gcFreeLists.finalizables[thingKind];
if (freeList)
return freeList;
}
while ((a = arenaList->cursor) != NULL) {
JSGCArenaInfo *ainfo = a->getInfo();
arenaList->cursor = ainfo->prev;
JSGCThing *freeList = ainfo->freeList;
if (freeList) {
ainfo->freeList = NULL;
return freeList;
}
}
a = NewGCArena(cx);
if (a)
break;
if (!canGC) {
METER(cx->runtime->gcArenaStats[thingKind].fail++);
return NULL;
}
doGC = true;
}
/*
* Do only minimal initialization of the arena inside the GC lock. We
* can do the rest outside the lock because no other threads will see
* the arena until the GC is run.
*/
JSGCArenaInfo *ainfo = a->getInfo();
ainfo->list = arenaList;
ainfo->prev = arenaList->head;
ainfo->freeList = NULL;
arenaList->head = a;
}
JSGCMarkingDelay *markingDelay = a->getMarkingDelay();
markingDelay->link = NULL;
markingDelay->unmarkedChildren = 0;
return MakeNewArenaFreeList(a, arenaList->thingSize);
}
static inline void
CheckGCFreeListLink(JSGCThing *thing)
{
/*
* The GC things on the free lists come from one arena and the things on
* the free list are linked in ascending address order.
*/
JS_ASSERT_IF(thing->link,
JSGCArena::fromGCThing(thing) ==
JSGCArena::fromGCThing(thing->link));
JS_ASSERT_IF(thing->link, thing < thing->link);
}
void *
js_NewFinalizableGCThing(JSContext *cx, unsigned thingKind)
{
JS_ASSERT(thingKind < FINALIZE_LIMIT);
#ifdef JS_THREADSAFE
JS_ASSERT(cx->thread);
#endif
/* Updates of metering counters here may not be thread-safe. */
METER(cx->runtime->gcArenaStats[thingKind].alloc++);
JSGCThing **freeListp =
JS_THREAD_DATA(cx)->gcFreeLists.finalizables + thingKind;
JSGCThing *thing = *freeListp;
if (thing) {
*freeListp = thing->link;
CheckGCFreeListLink(thing);
METER(cx->runtime->gcArenaStats[thingKind].localalloc++);
return thing;
}
thing = RefillFinalizableFreeList(cx, thingKind);
if (!thing) {
js_ReportOutOfMemory(cx);
return NULL;
}
/*
* See comments in RefillFinalizableFreeList about a possibility
* of *freeListp == thing.
*/
JS_ASSERT(!*freeListp || *freeListp == thing);
*freeListp = thing->link;
CheckGCFreeListLink(thing);
return thing;
}
JSBool
js_LockGCThingRT(JSRuntime *rt, void *thing)
{
GCLocks *locks;
if (!thing)
return true;
locks = &rt->gcLocksHash;
AutoLockGC lock(rt);
GCLocks::AddPtr p = locks->lookupForAdd(thing);
if (!p) {
if (!locks->add(p, thing, 1))
return false;
} else {
JS_ASSERT(p->value >= 1);
p->value++;
}
METER(rt->gcStats.lock++);
return true;
}
void
js_UnlockGCThingRT(JSRuntime *rt, void *thing)
{
if (!thing)
return;
AutoLockGC lock(rt);
GCLocks::Ptr p = rt->gcLocksHash.lookup(thing);
if (p) {
rt->gcPoke = true;
if (--p->value == 0)
rt->gcLocksHash.remove(p);
METER(rt->gcStats.unlock++);
}
}
JS_PUBLIC_API(void)
JS_TraceChildren(JSTracer *trc, void *thing, uint32 kind)
{
switch (kind) {
case JSTRACE_OBJECT: {
/* If obj has no map, it must be a newborn. */
JSObject *obj = (JSObject *) thing;
if (!obj->map)
break;
if (JSObject *proto = obj->getProto())
JS_CALL_OBJECT_TRACER(trc, proto, "proto");
if (JSObject *parent = obj->getParent())
JS_CALL_OBJECT_TRACER(trc, parent, "parent");
JSTraceOp op = obj->getOps()->trace;
(op ? op : js_TraceObject)(trc, obj);
break;
}
case JSTRACE_STRING: {
JSString *str = (JSString *) thing;
if (str->isDependent())
JS_CALL_STRING_TRACER(trc, str->dependentBase(), "base");
else if (str->isRope()) {
if (str->isInteriorNode())
JS_CALL_STRING_TRACER(trc, str->interiorNodeParent(), "parent");
JS_CALL_STRING_TRACER(trc, str->ropeLeft(), "left child");
JS_CALL_STRING_TRACER(trc, str->ropeRight(), "right child");
}
break;
}
#if JS_HAS_XML_SUPPORT
case JSTRACE_XML:
js_TraceXML(trc, (JSXML *)thing);
break;
#endif
}
}
namespace js {
/*
* When the native stack is low, the GC does not call JS_TraceChildren to mark
* the reachable "children" of the thing. Rather the thing is put aside and
* JS_TraceChildren is called later with more space on the C stack.
*
* To implement such delayed marking of the children with minimal overhead for
* the normal case of sufficient native stack, the code uses two fields per
* arena stored in JSGCMarkingDelay. The first field, JSGCMarkingDelay::link,
* links all arenas with delayed things into a stack list with the pointer to
* stack top in JSRuntime::gcUnmarkedArenaStackTop. delayMarkingChildren adds
* arenas to the stack as necessary while markDelayedChildren pops the arenas
* from the stack until it empties.
*
* The second field, JSGCMarkingDelay::unmarkedChildren, is a bitmap that
* tells for which things the GC should call JS_TraceChildren later. The
* bitmap is a single word. As such it does not pinpoint the delayed things
* in the arena but rather tells the intervals containing
* ThingsPerUnmarkedBit(thingSize) things. Later the code in
* markDelayedChildren discovers such intervals and calls JS_TraceChildren on
* any marked thing in the interval. This implies that JS_TraceChildren can be
* called many times for a single thing if the thing shares the same interval
* with some delayed things. This should be fine as any GC graph
* marking/traversing hooks must allow repeated calls during the same GC cycle.
* In particular, xpcom cycle collector relies on this.
*
* Note that such repeated scanning may slow down the GC. In particular, it is
* possible to construct an object graph where the GC calls JS_TraceChildren
* ThingsPerUnmarkedBit(thingSize) for almost all things in the graph. We
* tolerate this as the max value for ThingsPerUnmarkedBit(thingSize) is 4.
* This is archived for JSObject on 32 bit system as it is exactly JSObject
* that has the smallest size among the GC things that can be delayed. On 32
* bit CPU we have less than 128 objects per 4K GC arena so each bit in
* unmarkedChildren covers 4 objects.
*/
inline unsigned
ThingsPerUnmarkedBit(unsigned thingSize)
{
return JS_HOWMANY(ThingsPerArena(thingSize), JS_BITS_PER_WORD);
}
GCMarker::GCMarker(JSContext *cx)
: color(0), unmarkedArenaStackTop(NULL)
{
JS_TRACER_INIT(this, cx, NULL);
#ifdef DEBUG
markLaterCount = 0;
#endif
#ifdef JS_DUMP_CONSERVATIVE_GC_ROOTS
conservativeDumpFileName = getenv("JS_DUMP_CONSERVATIVE_GC_ROOTS");
memset(&conservativeStats, 0, sizeof(conservativeStats));
#endif
}
GCMarker::~GCMarker()
{
#ifdef JS_DUMP_CONSERVATIVE_GC_ROOTS
dumpConservativeRoots();
#endif
#ifdef JS_GCMETER
/* Update total stats. */
context->runtime->gcStats.conservative.add(conservativeStats);
#endif
}
void
GCMarker::delayMarkingChildren(void *thing)
{
JS_ASSERT(this == context->runtime->gcMarkingTracer);
JS_ASSERT(IsMarkedGCThing(thing));
METER(context->runtime->gcStats.unmarked++);
JSGCArena *a = JSGCArena::fromGCThing(thing);
JSGCArenaInfo *ainfo = a->getInfo();
JSGCMarkingDelay *markingDelay = a->getMarkingDelay();
size_t thingArenaIndex = GCThingToArenaIndex(thing);
size_t unmarkedBitIndex = thingArenaIndex /
ThingsPerUnmarkedBit(ainfo->list->thingSize);
JS_ASSERT(unmarkedBitIndex < JS_BITS_PER_WORD);
jsuword bit = jsuword(1) << unmarkedBitIndex;
if (markingDelay->unmarkedChildren != 0) {
JS_ASSERT(unmarkedArenaStackTop);
if (markingDelay->unmarkedChildren & bit) {
/* bit already covers things with children to mark later. */
return;
}
markingDelay->unmarkedChildren |= bit;
} else {
/*
* The thing is the first thing with not yet marked children in the
* whole arena, so push the arena on the stack of arenas with things
* to be marked later unless the arena has already been pushed. We
* detect that through checking prevUnmarked as the field is 0
* only for not yet pushed arenas. To ensure that
* prevUnmarked != 0
* even when the stack contains one element, we make prevUnmarked
* for the arena at the bottom to point to itself.
*
* See comments in markDelayedChildren.
*/
markingDelay->unmarkedChildren = bit;
if (!markingDelay->link) {
if (!unmarkedArenaStackTop) {
/* Stack was empty, mark the arena as the bottom element. */
markingDelay->link = a;
} else {
JS_ASSERT(unmarkedArenaStackTop->getMarkingDelay()->link);
markingDelay->link = unmarkedArenaStackTop;
}
unmarkedArenaStackTop = a;
}
JS_ASSERT(unmarkedArenaStackTop);
}
#ifdef DEBUG
markLaterCount += ThingsPerUnmarkedBit(ainfo->list->thingSize);
METER_UPDATE_MAX(context->runtime->gcStats.maxunmarked, markLaterCount);
#endif
}
JS_FRIEND_API(void)
GCMarker::markDelayedChildren()
{
JS_ASSERT(this == context->runtime->gcMarkingTracer);
JSGCArena *a = unmarkedArenaStackTop;
if (!a) {
JS_ASSERT(markLaterCount == 0);
return;
}
for (;;) {
/*
* The following assert verifies that the current arena belongs to the
* unmarked stack, since delayMarkingChildren ensures that even for
* the stack's bottom, prevUnmarked != 0 but rather points to
* itself.
*/
JSGCArenaInfo *ainfo = a->getInfo();
JSGCMarkingDelay *markingDelay = a->getMarkingDelay();
JS_ASSERT(markingDelay->link);
JS_ASSERT(unmarkedArenaStackTop->getMarkingDelay()->link);
unsigned thingSize = ainfo->list->thingSize;
unsigned traceKind = GetFinalizableArenaTraceKind(ainfo);
unsigned indexLimit = ThingsPerArena(thingSize);
unsigned thingsPerUnmarkedBit = ThingsPerUnmarkedBit(thingSize);
/*
* We cannot use do-while loop here as a->unmarkedChildren can be zero
* before the loop as a leftover from the previous iterations. See
* comments after the loop.
*/
while (markingDelay->unmarkedChildren != 0) {
unsigned unmarkedBitIndex = JS_FLOOR_LOG2W(markingDelay->unmarkedChildren);
markingDelay->unmarkedChildren &= ~(jsuword(1) << unmarkedBitIndex);
#ifdef DEBUG
JS_ASSERT(markLaterCount >= thingsPerUnmarkedBit);
markLaterCount -= thingsPerUnmarkedBit;
#endif
unsigned thingIndex = unmarkedBitIndex * thingsPerUnmarkedBit;
unsigned endIndex = thingIndex + thingsPerUnmarkedBit;
/*
* endIndex can go beyond the last allocated thing as the real
* limit can be "inside" the bit.
*/
if (endIndex > indexLimit)
endIndex = indexLimit;
uint8 *thing = GCArenaIndexToThing(a, ainfo, thingIndex);
uint8 *end = GCArenaIndexToThing(a, ainfo, endIndex);
do {
JS_ASSERT(thing < end);
if (IsMarkedGCThing(thing))
JS_TraceChildren(this, thing, traceKind);
thing += thingSize;
} while (thing != end);
}
/*
* We finished tracing of all things in the the arena but we can only
* pop it from the stack if the arena is the stack's top.
*
* When JS_TraceChildren from the above calls JS_CallTracer that in
* turn on low C stack calls delayMarkingChildren and the latter
* pushes new arenas to the unmarked stack, we have to skip popping
* of this arena until it becomes the top of the stack again.
*/
if (a == unmarkedArenaStackTop) {
JSGCArena *aprev = markingDelay->link;
markingDelay->link = NULL;
if (a == aprev) {
/*
* prevUnmarked points to itself and we reached the bottom of
* the stack.
*/
break;
}
unmarkedArenaStackTop = a = aprev;
} else {
a = unmarkedArenaStackTop;
}
}
JS_ASSERT(unmarkedArenaStackTop);
JS_ASSERT(!unmarkedArenaStackTop->getMarkingDelay()->link);
unmarkedArenaStackTop = NULL;
JS_ASSERT(markLaterCount == 0);
}
void
GCMarker::slowifyArrays()
{
while (!arraysToSlowify.empty()) {
JSObject *obj = arraysToSlowify.back();
arraysToSlowify.popBack();
if (IsMarkedGCThing(obj))
obj->makeDenseArraySlow(context);
}
}
void
Mark(JSTracer *trc, void *thing, uint32 kind)
{
JS_ASSERT(thing);
JS_ASSERT(JS_IS_VALID_TRACE_KIND(kind));
JS_ASSERT(trc->debugPrinter || trc->debugPrintArg);
JS_ASSERT_IF(!JSString::isStatic(thing), kind == GetFinalizableThingTraceKind(thing));
#ifdef DEBUG
if (IS_GC_MARKING_TRACER(trc)) {
JSRuntime *rt = trc->context->runtime;
JS_ASSERT(rt->gcMarkingTracer == trc);
JS_ASSERT(rt->gcRunning);
}
#endif
if (!IS_GC_MARKING_TRACER(trc)) {
trc->callback(trc, thing, kind);
} else {
GCMarker *gcmarker = static_cast<GCMarker *>(trc);
if (kind == JSTRACE_STRING) {
/*
* Optimize for string as their marking is not recursive.
*
* Iterate through all nodes and leaves in the rope if this is
* part of a rope; otherwise, we only iterate once: on the string
* itself.
*/
JSRopeNodeIterator iter((JSString *) thing);
JSString *str = iter.init();
do {
for (;;) {
if (JSString::isStatic(str))
break;
JS_ASSERT(kind == GetFinalizableThingTraceKind(str));
if (!MarkIfUnmarkedGCThing(str))
break;
if (!str->isDependent())
break;
str = str->dependentBase();
}
str = iter.next();
} while (str);
} else if (MarkIfUnmarkedGCThing(thing, gcmarker->getMarkColor())) {
/*
* With JS_GC_ASSUME_LOW_C_STACK defined the mark phase of GC
* always uses the non-recursive code that otherwise would be
* called only on a low C stack condition.
*/
#ifdef JS_GC_ASSUME_LOW_C_STACK
# define RECURSION_TOO_DEEP() true
#else
int stackDummy;
# define RECURSION_TOO_DEEP() (!JS_CHECK_STACK_SIZE(trc->context, stackDummy))
#endif
if (RECURSION_TOO_DEEP())
gcmarker->delayMarkingChildren(thing);
else
JS_TraceChildren(trc, thing, kind);
}
}
#ifdef DEBUG
trc->debugPrinter = NULL;
trc->debugPrintArg = NULL;
#endif
}
void
MarkGCThing(JSTracer *trc, void *thing)
{
JS_ASSERT(size_t(thing) % JS_GCTHING_ALIGN == 0);
if (!thing)
return;
uint32 kind = js_GetGCThingTraceKind(thing);
Mark(trc, thing, kind);
}
} /* namespace js */
static void
gc_root_traversal(JSTracer *trc, const RootEntry &entry)
{
#ifdef DEBUG
void *ptr;
if (entry.value.type == JS_GC_ROOT_GCTHING_PTR) {
ptr = *reinterpret_cast<void **>(entry.key);
} else {
Value *vp = reinterpret_cast<Value *>(entry.key);
ptr = vp->isGCThing() ? vp->asGCThing() : NULL;
}
if (ptr) {
if (!JSString::isStatic(ptr)) {
bool root_points_to_gcArenaList = false;
jsuword thing = (jsuword) ptr;
JSRuntime *rt = trc->context->runtime;
for (unsigned i = 0; i != FINALIZE_LIMIT; i++) {
JSGCArenaList *arenaList = &rt->gcArenaList[i];
size_t thingSize = arenaList->thingSize;
size_t limit = ThingsPerArena(thingSize) * thingSize;
for (JSGCArena *a = arenaList->head;
a;
a = a->getInfo()->prev) {
if (thing - a->toPageStart() < limit) {
root_points_to_gcArenaList = true;
break;
}
}
}
if (!root_points_to_gcArenaList && entry.value.name) {
fprintf(stderr,
"JS API usage error: the address passed to JS_AddNamedRoot currently holds an\n"
"invalid gcthing. This is usually caused by a missing call to JS_RemoveRoot.\n"
"The root's name is \"%s\".\n",
entry.value.name);
}
JS_ASSERT(root_points_to_gcArenaList);
}
}
#endif
JS_SET_TRACING_NAME(trc, entry.value.name ? entry.value.name : "root");
if (entry.value.type == JS_GC_ROOT_GCTHING_PTR)
MarkGCThing(trc, *reinterpret_cast<void **>(entry.key));
else
MarkValueRaw(trc, *reinterpret_cast<Value *>(entry.key));
}
static void
gc_lock_traversal(const GCLocks::Entry &entry, JSTracer *trc)
{
uint32 traceKind;
JS_ASSERT(entry.value >= 1);
traceKind = js_GetGCThingTraceKind(entry.key);
JS_CALL_TRACER(trc, entry.key, traceKind, "locked object");
}
void
js_TraceStackFrame(JSTracer *trc, JSStackFrame *fp)
{
if (fp->hasCallObj())
JS_CALL_OBJECT_TRACER(trc, fp->getCallObj(), "call");
if (fp->hasArgsObj())
JS_CALL_OBJECT_TRACER(trc, fp->getArgsObj(), "arguments");
if (fp->hasScript())
js_TraceScript(trc, fp->getScript());
/* Allow for primitive this parameter due to JSFUN_THISP_* flags. */
MarkValue(trc, fp->getThisValue(), "this");
MarkValue(trc, fp->getReturnValue(), "rval");
if (fp->hasScopeChain())
JS_CALL_OBJECT_TRACER(trc, fp->getScopeChain(), "scope chain");
}
inline void
AutoGCRooter::trace(JSTracer *trc)
{
switch (tag) {
case JSVAL:
MarkValue(trc, static_cast<AutoValueRooter *>(this)->val, "js::AutoValueRooter.val");
return;
case SPROP:
static_cast<AutoScopePropertyRooter *>(this)->sprop->trace(trc);
return;
case PARSER:
static_cast<Parser *>(this)->trace(trc);
return;
case SCRIPT:
if (JSScript *script = static_cast<AutoScriptRooter *>(this)->script)
js_TraceScript(trc, script);
return;
case ENUMERATOR:
static_cast<AutoEnumStateRooter *>(this)->trace(trc);
return;
case IDARRAY: {
JSIdArray *ida = static_cast<AutoIdArray *>(this)->idArray;
MarkIdRange(trc, ida->length, ida->vector, "js::AutoIdArray.idArray");
return;
}
case DESCRIPTORS: {
PropDescArray &descriptors =
static_cast<AutoPropDescArrayRooter *>(this)->descriptors;
for (size_t i = 0, len = descriptors.length(); i < len; i++) {
PropDesc &desc = descriptors[i];
MarkValue(trc, desc.pd, "PropDesc::pd");
MarkValue(trc, desc.value, "PropDesc::value");
MarkValue(trc, desc.get, "PropDesc::get");
MarkValue(trc, desc.set, "PropDesc::set");
MarkId(trc, desc.id, "PropDesc::id");
}
return;
}
case DESCRIPTOR : {
PropertyDescriptor &desc = *static_cast<AutoPropertyDescriptorRooter *>(this);
if (desc.obj)
MarkObject(trc, desc.obj, "Descriptor::obj");
MarkValue(trc, desc.value, "Descriptor::value");
if ((desc.attrs & JSPROP_GETTER) && desc.getter)
MarkObject(trc, CastAsObject(desc.getter), "Descriptor::get");
if (desc.attrs & JSPROP_SETTER && desc.setter)
MarkObject(trc, CastAsObject(desc.setter), "Descriptor::set");
return;
}
case NAMESPACES: {
JSXMLArray &array = static_cast<AutoNamespaceArray *>(this)->array;
MarkObjectRange(trc, array.length, reinterpret_cast<JSObject **>(array.vector),
"JSXMLArray.vector");
array.cursors->trace(trc);
return;
}
case XML:
js_TraceXML(trc, static_cast<AutoXMLRooter *>(this)->xml);
return;
case OBJECT:
if (JSObject *obj = static_cast<AutoObjectRooter *>(this)->obj)
MarkObject(trc, obj, "js::AutoObjectRooter.obj");
return;
case ID:
MarkId(trc, static_cast<AutoIdRooter *>(this)->id_, "js::AutoIdRooter.val");
return;
case VALVECTOR: {
Vector<Value, 8> &vector = static_cast<js::AutoValueVector *>(this)->vector;
MarkValueRange(trc, vector.length(), vector.begin(), "js::AutoValueVector.vector");
return;
}
case STRING:
if (JSString *str = static_cast<js::AutoStringRooter *>(this)->str)
MarkString(trc, str, "js::AutoStringRooter.str");
return;
case IDVECTOR: {
Vector<jsid, 8> &vector = static_cast<js::AutoIdVector *>(this)->vector;
MarkIdRange(trc, vector.length(), vector.begin(), "js::AutoIdVector.vector");
return;
}
}
JS_ASSERT(tag >= 0);
MarkValueRange(trc, tag, static_cast<AutoArrayRooter *>(this)->array, "js::AutoArrayRooter.array");
}
void
js_TraceContext(JSTracer *trc, JSContext *acx)
{
/* Stack frames and slots are traced by StackSpace::mark. */
/* Mark other roots-by-definition in acx. */
if (acx->globalObject && !JS_HAS_OPTION(acx, JSOPTION_UNROOTED_GLOBAL))
JS_CALL_OBJECT_TRACER(trc, acx->globalObject, "global object");
if (acx->throwing) {
MarkValue(trc, acx->exception, "exception");
} else {
/* Avoid keeping GC-ed junk stored in JSContext.exception. */
acx->exception.setNull();
}
for (js::AutoGCRooter *gcr = acx->autoGCRooters; gcr; gcr = gcr->down)
gcr->trace(trc);
if (acx->sharpObjectMap.depth > 0)
js_TraceSharpMap(trc, &acx->sharpObjectMap);
js_TraceRegExpStatics(trc, acx);
MarkValue(trc, acx->iterValue, "iterValue");
acx->compartment->marked = true;
#ifdef JS_TRACER
TracerState* state = acx->tracerState;
while (state) {
if (state->nativeVp)
MarkValueRange(trc, state->nativeVpLen, state->nativeVp, "nativeVp");
state = state->prev;
}
#endif
}
JS_REQUIRES_STACK void
js_TraceRuntime(JSTracer *trc)
{
JSRuntime *rt = trc->context->runtime;
if (rt->state != JSRTS_LANDING)
MarkConservativeStackRoots(trc);
/*
* Verify that we do not have at this point unmarked GC things stored in
* autorooters. To maximize test coverage we abort even in non-debug
* builds for now, see bug 574313.
*/
JSContext *iter;
#if 1
iter = NULL;
while (JSContext *acx = js_ContextIterator(rt, JS_TRUE, &iter)) {
for (AutoGCRooter *gcr = acx->autoGCRooters; gcr; gcr = gcr->down) {
#ifdef JS_THREADSAFE
JS_ASSERT(acx->outstandingRequests != 0);
#endif
JS_ASSERT(JS_THREAD_DATA(acx)->conservativeGC.isEnabled());
void *thing;
switch (gcr->tag) {
default:
continue;
case AutoGCRooter::JSVAL: {
const Value &v = static_cast<AutoValueRooter *>(gcr)->val;
if (!v.isMarkable())
continue;
thing = v.asGCThing();
break;
}
case AutoGCRooter::XML:
thing = static_cast<AutoXMLRooter *>(gcr)->xml;
break;
case AutoGCRooter::OBJECT:
thing = static_cast<AutoObjectRooter *>(gcr)->obj;
if (!thing)
continue;
break;
case AutoGCRooter::ID: {
jsid id = static_cast<AutoIdRooter *>(gcr)->id();
if (!JSID_IS_GCTHING(id))
continue;
thing = JSID_TO_GCTHING(id);
break;
}
}
if (JSString::isStatic(thing))
continue;
if (!IsMarkedGCThing(thing)) {
ConservativeGCTest test = IsGCThingWord(rt, reinterpret_cast<jsuword>(thing));
fprintf(stderr,
"Conservative GC scanner has missed the root 0x%p with tag %ld"
" on the stack due to %d. The root location 0x%p, distance from"
" the stack base %ld, conservative gc span %ld."
" Consevtaive GC status for the thread %d."
" Aborting.\n",
thing, (long) gcr->tag, int(test), (void *) gcr,
(long) ((jsword) JS_THREAD_DATA(acx)->nativeStackBase - (jsword) gcr),
(long) ((jsword) JS_THREAD_DATA(acx)->nativeStackBase -
(jsword) JS_THREAD_DATA(acx)->conservativeGC.nativeStackTop),
JS_THREAD_DATA(acx)->conservativeGC.enableCount);
JS_ASSERT(false);
abort();
}
}
}
#endif
for (RootRange r = rt->gcRootsHash.all(); !r.empty(); r.popFront())
gc_root_traversal(trc, r.front());
for (GCLocks::Range r = rt->gcLocksHash.all(); !r.empty(); r.popFront())
gc_lock_traversal(r.front(), trc);
js_TraceAtomState(trc);
js_MarkTraps(trc);
iter = NULL;
while (JSContext *acx = js_ContextIterator(rt, JS_TRUE, &iter))
js_TraceContext(trc, acx);
for (ThreadDataIter i(rt); !i.empty(); i.popFront())
i.threadData()->mark(trc);
/*
* We mark extra roots at the last thing so it can use use additional
* colors to implement cycle collection.
*/
if (rt->gcExtraRootsTraceOp)
rt->gcExtraRootsTraceOp(trc, rt->gcExtraRootsData);
#ifdef DEBUG
if (rt->functionMeterFilename) {
for (int k = 0; k < 2; k++) {
typedef JSRuntime::FunctionCountMap HM;
HM &h = (k == 0) ? rt->methodReadBarrierCountMap : rt->unjoinedFunctionCountMap;
for (HM::Range r = h.all(); !r.empty(); r.popFront()) {
JSFunction *fun = r.front().key;
JS_CALL_OBJECT_TRACER(trc, fun, "FunctionCountMap key");
}
}
}
#endif
}
void
js_TriggerGC(JSContext *cx, JSBool gcLocked)
{
JSRuntime *rt = cx->runtime;
#ifdef JS_THREADSAFE
JS_ASSERT(cx->requestDepth > 0);
#endif
JS_ASSERT(!rt->gcRunning);
if (rt->gcIsNeeded)
return;
/*
* Trigger the GC when it is safe to call an operation callback on any
* thread.
*/
rt->gcIsNeeded = JS_TRUE;
js_TriggerAllOperationCallbacks(rt, gcLocked);
}
void
js_DestroyScriptsToGC(JSContext *cx, JSThreadData *data)
{
JSScript **listp, *script;
for (size_t i = 0; i != JS_ARRAY_LENGTH(data->scriptsToGC); ++i) {
listp = &data->scriptsToGC[i];
while ((script = *listp) != NULL) {
*listp = script->u.nextToGC;
script->u.nextToGC = NULL;
js_DestroyScript(cx, script);
}
}
}
inline void
FinalizeObject(JSContext *cx, JSObject *obj, unsigned thingKind)
{
JS_ASSERT(thingKind == FINALIZE_OBJECT ||
thingKind == FINALIZE_FUNCTION);
/* Cope with stillborn objects that have no map. */
if (!obj->map)
return;
/* Finalize obj first, in case it needs map and slots. */
Class *clasp = obj->getClass();
if (clasp->finalize)
clasp->finalize(cx, obj);
DTrace::finalizeObject(obj);
if (JS_LIKELY(obj->isNative())) {
JSScope *scope = obj->scope();
if (scope->isSharedEmpty())
static_cast<JSEmptyScope *>(scope)->dropFromGC(cx);
else
scope->destroy(cx);
}
if (obj->hasSlotsArray())
obj->freeSlotsArray(cx);
}
inline void
FinalizeFunction(JSContext *cx, JSFunction *fun, unsigned thingKind)
{
FinalizeObject(cx, FUN_OBJECT(fun), thingKind);
}
#if JS_HAS_XML_SUPPORT
inline void
FinalizeXML(JSContext *cx, JSXML *xml, unsigned thingKind)
{
js_FinalizeXML(cx, xml);
}
#endif
JS_STATIC_ASSERT(JS_EXTERNAL_STRING_LIMIT == 8);
static JSStringFinalizeOp str_finalizers[JS_EXTERNAL_STRING_LIMIT] = {
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
intN
js_ChangeExternalStringFinalizer(JSStringFinalizeOp oldop,
JSStringFinalizeOp newop)
{
for (uintN i = 0; i != JS_ARRAY_LENGTH(str_finalizers); i++) {
if (str_finalizers[i] == oldop) {
str_finalizers[i] = newop;
return intN(i);
}
}
return -1;
}
inline void
FinalizeShortString(JSContext *cx, JSShortString *str, unsigned thingKind)
{
JS_ASSERT(FINALIZE_SHORT_STRING == thingKind);
JS_ASSERT(!JSString::isStatic(str->header()));
JS_ASSERT(str->header()->isFlat());
JS_RUNTIME_UNMETER(cx->runtime, liveStrings);
}
inline void
FinalizeString(JSContext *cx, JSString *str, unsigned thingKind)
{
JS_ASSERT(FINALIZE_STRING == thingKind);
JS_ASSERT(!JSString::isStatic(str));
JS_RUNTIME_UNMETER(cx->runtime, liveStrings);
if (str->isDependent()) {
JS_ASSERT(str->dependentBase());
JS_RUNTIME_UNMETER(cx->runtime, liveDependentStrings);
} else if (str->isFlat()) {
/*
* flatChars for stillborn string is null, but cx->free checks
* for a null pointer on its own.
*/
cx->free(str->flatChars());
} else if (str->isTopNode()) {
cx->free(str->topNodeBuffer());
}
/* Nothing to be done for rope interior nodes. */
}
inline void
FinalizeExternalString(JSContext *cx, JSString *str, unsigned thingKind)
{
unsigned type = thingKind - FINALIZE_EXTERNAL_STRING0;
JS_ASSERT(type < JS_ARRAY_LENGTH(str_finalizers));
JS_ASSERT(!JSString::isStatic(str));
JS_ASSERT(str->isFlat());
JS_RUNTIME_UNMETER(cx->runtime, liveStrings);
/* A stillborn string has null chars. */
jschar *chars = str->flatChars();
if (!chars)
return;
JSStringFinalizeOp finalizer = str_finalizers[type];
if (finalizer)
finalizer(cx, str);
}
/*
* This function is called from js_FinishAtomState to force the finalization
* of the permanently interned strings when cx is not available.
*/
void
js_FinalizeStringRT(JSRuntime *rt, JSString *str)
{
JS_RUNTIME_UNMETER(rt, liveStrings);
JS_ASSERT(!JSString::isStatic(str));
JS_ASSERT(!str->isRope());
if (str->isDependent()) {
/* A dependent string can not be external and must be valid. */
JS_ASSERT(JSGCArenaInfo::fromGCThing(str)->list->thingKind == FINALIZE_STRING);
JS_ASSERT(str->dependentBase());
JS_RUNTIME_UNMETER(rt, liveDependentStrings);
} else {
unsigned thingKind = JSGCArenaInfo::fromGCThing(str)->list->thingKind;
JS_ASSERT(IsFinalizableStringKind(thingKind));
/* A stillborn string has null chars, so is not valid. */
jschar *chars = str->flatChars();
if (!chars)
return;
if (thingKind == FINALIZE_STRING) {
rt->free(chars);
} else if (thingKind != FINALIZE_SHORT_STRING) {
unsigned type = thingKind - FINALIZE_EXTERNAL_STRING0;
JS_ASSERT(type < JS_ARRAY_LENGTH(str_finalizers));
JSStringFinalizeOp finalizer = str_finalizers[type];
if (finalizer) {
/*
* Assume that the finalizer for the permanently interned
* string knows how to deal with null context.
*/
finalizer(NULL, str);
}
}
}
}
template<typename T,
void finalizer(JSContext *cx, T *thing, unsigned thingKind)>
static void
FinalizeArenaList(JSContext *cx, unsigned thingKind)
{
JS_STATIC_ASSERT(!(sizeof(T) & GC_CELL_MASK));
JSGCArenaList *arenaList = &cx->runtime->gcArenaList[thingKind];
JS_ASSERT(sizeof(T) == arenaList->thingSize);
JSGCArena **ap = &arenaList->head;
JSGCArena *a = *ap;
if (!a)
return;
#ifdef JS_GCMETER
uint32 nlivearenas = 0, nkilledarenas = 0, nthings = 0;
#endif
for (;;) {
JSGCArenaInfo *ainfo = a->getInfo();
JS_ASSERT(ainfo->list == arenaList);
JS_ASSERT(!a->getMarkingDelay()->link);
JS_ASSERT(a->getMarkingDelay()->unmarkedChildren == 0);
JSGCThing *freeList = NULL;
JSGCThing **tailp = &freeList;
bool allClear = true;
jsuword thing = a->toPageStart();
jsuword thingsEnd = thing + GC_ARENA_SIZE / sizeof(T) * sizeof(T);
jsuword nextFree = reinterpret_cast<jsuword>(ainfo->freeList);
if (!nextFree) {
nextFree = thingsEnd;
} else {
JS_ASSERT(thing <= nextFree);
JS_ASSERT(nextFree < thingsEnd);
}
jsuword gcCellIndex = 0;
jsbitmap *bitmap = a->getMarkBitmap();
for (;; thing += sizeof(T), gcCellIndex += sizeof(T) >> GC_CELL_SHIFT) {
if (thing == nextFree) {
if (thing == thingsEnd)
break;
nextFree = reinterpret_cast<jsuword>(
reinterpret_cast<JSGCThing *>(nextFree)->link);
if (!nextFree) {
nextFree = thingsEnd;
} else {
JS_ASSERT(thing < nextFree);
JS_ASSERT(nextFree < thingsEnd);
}
} else if (JS_TEST_BIT(bitmap, gcCellIndex)) {
allClear = false;
METER(nthings++);
continue;
} else {
T *t = reinterpret_cast<T *>(thing);
finalizer(cx, t, thingKind);
#ifdef DEBUG
memset(t, JS_FREE_PATTERN, sizeof(T));
#endif
}
JSGCThing *t = reinterpret_cast<JSGCThing *>(thing);
*tailp = t;
tailp = &t->link;
}
#ifdef DEBUG
/* Check that the free list is consistent. */
unsigned nfree = 0;
if (freeList) {
JS_ASSERT(tailp != &freeList);
JSGCThing *t = freeList;
for (;;) {
++nfree;
if (&t->link == tailp)
break;
JS_ASSERT(t < t->link);
t = t->link;
}
}
#endif
if (allClear) {
/*
* Forget just assembled free list head for the arena and
* add the arena itself to the destroy list.
*/
JS_ASSERT(nfree == ThingsPerArena(sizeof(T)));
*ap = ainfo->prev;
ReleaseGCArena(cx->runtime, a);
METER(nkilledarenas++);
} else {
JS_ASSERT(nfree < ThingsPerArena(sizeof(T)));
*tailp = NULL;
ainfo->freeList = freeList;
ap = &ainfo->prev;
METER(nlivearenas++);
}
if (!(a = *ap))
break;
}
arenaList->cursor = arenaList->head;
METER(UpdateArenaStats(&cx->runtime->gcArenaStats[thingKind],
nlivearenas, nkilledarenas, nthings));
}
#ifdef JS_THREADSAFE
namespace js {
JS_FRIEND_API(void)
BackgroundSweepTask::replenishAndFreeLater(void *ptr)
{
JS_ASSERT(freeCursor == freeCursorEnd);
do {
if (freeCursor && !freeVector.append(freeCursorEnd - FREE_ARRAY_LENGTH))
break;
freeCursor = (void **) js_malloc(FREE_ARRAY_SIZE);
if (!freeCursor) {
freeCursorEnd = NULL;
break;
}
freeCursorEnd = freeCursor + FREE_ARRAY_LENGTH;
*freeCursor++ = ptr;
return;
} while (false);
js_free(ptr);
}
void
BackgroundSweepTask::run()
{
if (freeCursor) {
void **array = freeCursorEnd - FREE_ARRAY_LENGTH;
freeElementsAndArray(array, freeCursor);
freeCursor = freeCursorEnd = NULL;
} else {
JS_ASSERT(!freeCursorEnd);
}
for (void ***iter = freeVector.begin(); iter != freeVector.end(); ++iter) {
void **array = *iter;
freeElementsAndArray(array, array + FREE_ARRAY_LENGTH);
}
}
}
#endif /* JS_THREADSAFE */
static void
SweepCompartments(JSContext *cx)
{
JSRuntime *rt = cx->runtime;
JSCompartmentCallback callback = rt->compartmentCallback;
JSCompartment **read = rt->compartments.begin();
JSCompartment **end = rt->compartments.end();
JSCompartment **write = read;
/* Delete defaultCompartment only during runtime shutdown */
rt->defaultCompartment->marked = true;
while (read < end) {
JSCompartment *compartment = (*read++);
if (compartment->marked) {
compartment->marked = false;
*write++ = compartment;
/* Remove dead wrappers from the compartment map. */
compartment->sweep(cx);
} else {
if (callback)
(void) callback(cx, compartment, JSCOMPARTMENT_DESTROY);
if (compartment->principals)
JSPRINCIPALS_DROP(cx, compartment->principals);
delete compartment;
}
}
rt->compartments.resize(write - rt->compartments.begin());
}
/*
* Common cache invalidation and so forth that must be done before GC. Even if
* GCUntilDone calls GC several times, this work only needs to be done once.
*/
static void
PreGCCleanup(JSContext *cx, JSGCInvocationKind gckind)
{
JSRuntime *rt = cx->runtime;
/* Clear gcIsNeeded now, when we are about to start a normal GC cycle. */
rt->gcIsNeeded = JS_FALSE;
/* Reset malloc counter. */
rt->resetGCMallocBytes();
#ifdef JS_DUMP_SCOPE_METERS
{
extern void js_DumpScopeMeters(JSRuntime *rt);
js_DumpScopeMeters(rt);
}
#endif
/*
* Reset the property cache's type id generator so we can compress ids.
* Same for the protoHazardShape proxy-shape standing in for all object
* prototypes having readonly or setter properties.
*/
if (rt->shapeGen & SHAPE_OVERFLOW_BIT
#ifdef JS_GC_ZEAL
|| rt->gcZeal >= 1
#endif
) {
rt->gcRegenShapes = true;
rt->gcRegenShapesScopeFlag ^= JSScope::SHAPE_REGEN;
rt->shapeGen = JSScope::LAST_RESERVED_SHAPE;
rt->protoHazardShape = 0;
}
js_PurgeThreads(cx);
{
JSContext *iter = NULL;
while (JSContext *acx = js_ContextIterator(rt, JS_TRUE, &iter))
acx->purge();
}
}
/*
* Perform mark-and-sweep GC.
*
* In a JS_THREADSAFE build, the calling thread must be rt->gcThread and each
* other thread must be either outside all requests or blocked waiting for GC
* to finish. Note that the caller does not hold rt->gcLock.
*/
static void
GC(JSContext *cx GCTIMER_PARAM)
{
JSRuntime *rt = cx->runtime;
rt->gcNumber++;
/*
* Mark phase.
*/
GCMarker gcmarker(cx);
JS_ASSERT(IS_GC_MARKING_TRACER(&gcmarker));
JS_ASSERT(gcmarker.getMarkColor() == BLACK);
rt->gcMarkingTracer = &gcmarker;
for (GCChunkSet::Range r(rt->gcChunkSet.all()); !r.empty(); r.popFront())
GCChunkInfo::fromChunk(r.front())->clearMarkBitmap();
js_TraceRuntime(&gcmarker);
js_MarkScriptFilenames(rt);
/*
* Mark children of things that caused too deep recursion during the above
* tracing.
*/
gcmarker.markDelayedChildren();
rt->gcMarkingTracer = NULL;
if (rt->gcCallback)
(void) rt->gcCallback(cx, JSGC_MARK_END);
#ifdef JS_THREADSAFE
JS_ASSERT(!cx->gcSweepTask);
if (!rt->gcHelperThread.busy())
cx->gcSweepTask = new js::BackgroundSweepTask();
#endif
/*
* Sweep phase.
*
* Finalize as we sweep, outside of rt->gcLock but with rt->gcRunning set
* so that any attempt to allocate a GC-thing from a finalizer will fail,
* rather than nest badly and leave the unmarked newborn to be swept.
*
* We first sweep atom state so we can use js_IsAboutToBeFinalized on
* JSString held in a hashtable to check if the hashtable entry can be
* freed. Note that even after the entry is freed, JSObject finalizers can
* continue to access the corresponding JSString* assuming that they are
* unique. This works since the atomization API must not be called during
* the GC.
*/
TIMESTAMP(startSweep);
js_SweepAtomState(cx);
/* Finalize watch points associated with unreachable objects. */
js_SweepWatchPoints(cx);
#ifdef DEBUG
/* Save the pre-sweep count of scope-mapped properties. */
rt->liveScopePropsPreSweep = rt->liveScopeProps;
#endif
/*
* We finalize iterators before other objects so the iterator can use the
* object which properties it enumerates over to finalize the enumeration
* state. We finalize objects before other GC things to ensure that
* object's finalizer can access them even if they will be freed.
*/
JS_ASSERT(!rt->gcEmptyArenaList);
FinalizeArenaList<JSObject, FinalizeObject>(cx, FINALIZE_OBJECT);
FinalizeArenaList<JSFunction, FinalizeFunction>(cx, FINALIZE_FUNCTION);
#if JS_HAS_XML_SUPPORT
FinalizeArenaList<JSXML, FinalizeXML>(cx, FINALIZE_XML);
#endif
TIMESTAMP(sweepObjectEnd);
/*
* We sweep the deflated cache before we finalize the strings so the
* cache can safely use js_IsAboutToBeFinalized..
*/
rt->deflatedStringCache->sweep(cx);
FinalizeArenaList<JSShortString, FinalizeShortString>(cx, FINALIZE_SHORT_STRING);
FinalizeArenaList<JSString, FinalizeString>(cx, FINALIZE_STRING);
for (unsigned i = FINALIZE_EXTERNAL_STRING0;
i <= FINALIZE_EXTERNAL_STRING_LAST;
++i) {
FinalizeArenaList<JSString, FinalizeExternalString>(cx, i);
}
TIMESTAMP(sweepStringEnd);
SweepCompartments(cx);
/*
* Sweep the runtime's property tree after finalizing objects, in case any
* had watchpoints referencing tree nodes.
*/
js::SweepScopeProperties(cx);
/*
* Sweep script filenames after sweeping functions in the generic loop
* above. In this way when a scripted function's finalizer destroys the
* script and calls rt->destroyScriptHook, the hook can still access the
* script's filename. See bug 323267.
*/
js_SweepScriptFilenames(rt);
/* Slowify arrays we have accumulated. */
gcmarker.slowifyArrays();
/*
* Destroy arenas after we finished the sweeping so finalizers can safely
* use js_IsAboutToBeFinalized().
*/
FreeGCChunks(rt);
TIMESTAMP(sweepDestroyEnd);
#ifdef JS_THREADSAFE
if (cx->gcSweepTask) {
rt->gcHelperThread.schedule(cx->gcSweepTask);
cx->gcSweepTask = NULL;
}
#endif
if (rt->gcCallback)
(void) rt->gcCallback(cx, JSGC_FINALIZE_END);
#ifdef DEBUG_srcnotesize
{ extern void DumpSrcNoteSizeHist();
DumpSrcNoteSizeHist();
printf("GC HEAP SIZE %lu\n", (unsigned long)rt->gcBytes);
}
#endif
#ifdef JS_SCOPE_DEPTH_METER
DumpScopeDepthMeter(rt);
#endif
#ifdef JS_DUMP_LOOP_STATS
DumpLoopStats(rt);
#endif
}
#ifdef JS_THREADSAFE
/*
* If the GC is running and we're called on another thread, wait for this GC
* activation to finish. We can safely wait here without fear of deadlock (in
* the case where we are called within a request on another thread's context)
* because the GC doesn't set rt->gcRunning until after it has waited for all
* active requests to end.
*
* We call here js_CurrentThreadId() after checking for rt->gcState to avoid
* an expensive call when the GC is not running.
*/
void
js_WaitForGC(JSRuntime *rt)
{
if (rt->gcRunning && rt->gcThread->id != js_CurrentThreadId()) {
do {
JS_AWAIT_GC_DONE(rt);
} while (rt->gcRunning);
}
}
/*
* GC is running on another thread. Temporarily suspend all requests running
* on the current thread and wait until the GC is done.
*/
static void
LetOtherGCFinish(JSContext *cx)
{
JSRuntime *rt = cx->runtime;
JS_ASSERT(rt->gcThread);
JS_ASSERT(cx->thread != rt->gcThread);
size_t requestDebit = cx->thread->requestContext ? 1 : 0;
JS_ASSERT(requestDebit <= rt->requestCount);
#ifdef JS_TRACER
JS_ASSERT_IF(requestDebit == 0, !JS_ON_TRACE(cx));
#endif
if (requestDebit != 0) {
#ifdef JS_TRACER
if (JS_ON_TRACE(cx)) {
/*
* Leave trace before we decrease rt->requestCount and notify the
* GC. Otherwise the GC may start immediately after we unlock while
* this thread is still on trace.
*/
AutoUnlockGC unlock(rt);
LeaveTrace(cx);
}
#endif
rt->requestCount -= requestDebit;
if (rt->requestCount == 0)
JS_NOTIFY_REQUEST_DONE(rt);
}
/* See comments before another call to js_ShareWaitingTitles below. */
cx->thread->gcWaiting = true;
js_ShareWaitingTitles(cx);
/*
* Check that we did not release the GC lock above and let the GC to
* finish before we wait.
*/
JS_ASSERT(rt->gcThread);
JS_THREAD_DATA(cx)->conservativeGC.enable(true);
/*
* Wait for GC to finish on the other thread, even if requestDebit is 0
* and even if GC has not started yet because the gcThread is waiting in
* BeginGCSession. This ensures that js_GC never returns without a full GC
* cycle happening.
*/
do {
JS_AWAIT_GC_DONE(rt);
} while (rt->gcThread);
JS_THREAD_DATA(cx)->conservativeGC.disable();
cx->thread->gcWaiting = false;
rt->requestCount += requestDebit;
}
#endif
/*
* Start a new GC session assuming no GC is running on this or other threads.
* Together with LetOtherGCFinish this function contains the rendezvous
* algorithm by which we stop the world for GC.
*
* This thread becomes the GC thread. Wait for all other threads to quiesce.
* Then set rt->gcRunning and return. The caller must call EndGCSession when
* GC work is done.
*/
static void
BeginGCSession(JSContext *cx)
{
JSRuntime *rt = cx->runtime;
JS_ASSERT(!rt->gcRunning);
#ifdef JS_THREADSAFE
/* No other thread is in GC, so indicate that we're now in GC. */
JS_ASSERT(!rt->gcThread);
rt->gcThread = cx->thread;
/*
* Notify operation callbacks on other threads, which will give them a
* chance to yield their requests. Threads without requests perform their
* callback at some later point, which then will be unnecessary, but
* harmless.
*/
for (JSThread::Map::Range r = rt->threads.all(); !r.empty(); r.popFront()) {
JSThread *thread = r.front().value;
if (thread != cx->thread)
thread->data.triggerOperationCallback();
}
/*
* Discount the request on the current thread from contributing to
* rt->requestCount before we wait for all other requests to finish.
* JS_NOTIFY_REQUEST_DONE, which will wake us up, is only called on
* rt->requestCount transitions to 0.
*/
JS_ASSERT_IF(cx->requestDepth != 0, cx->thread->requestContext);
size_t requestDebit = cx->thread->requestContext ? 1 : 0;
JS_ASSERT(requestDebit <= rt->requestCount);
if (requestDebit != rt->requestCount) {
rt->requestCount -= requestDebit;
/*
* Share any title that is owned by the GC thread before we wait, to
* avoid a deadlock with ClaimTitle. We also set the gcWaiting flag so
* that ClaimTitle can claim the title ownership from the GC thread if
* that function is called while the GC is waiting.
*/
cx->thread->gcWaiting = true;
js_ShareWaitingTitles(cx);
do {
JS_AWAIT_REQUEST_DONE(rt);
} while (rt->requestCount > 0);
cx->thread->gcWaiting = false;
rt->requestCount += requestDebit;
}
#endif /* JS_THREADSAFE */
/*
* Set rt->gcRunning here within the GC lock, and after waiting for any
* active requests to end. This way js_WaitForGC called outside a request
* would not block on the GC that is waiting for other requests to finish
* with rt->gcThread set while JS_BeginRequest would do such wait.
*/
rt->gcRunning = true;
}
/* End the current GC session and allow other threads to proceed. */
static void
EndGCSession(JSContext *cx)
{
JSRuntime *rt = cx->runtime;
rt->gcRunning = false;
#ifdef JS_THREADSAFE
JS_ASSERT(rt->gcThread == cx->thread);
rt->gcThread = NULL;
JS_NOTIFY_GC_DONE(rt);
#endif
}
/*
* GC, repeatedly if necessary, until we think we have not created any new
* garbage and no other threads are demanding more GC.
*/
static void
GCUntilDone(JSContext *cx, JSGCInvocationKind gckind GCTIMER_PARAM)
{
if (JS_ON_TRACE(cx))
return;
JSRuntime *rt = cx->runtime;
/* Recursive GC or a call from another thread restarts the GC cycle. */
#ifndef JS_THREADSAFE
if (rt->gcRunning) {
rt->gcPoke = true;
return;
}
#else /* JS_THREADSAFE */
if (rt->gcThread) {
rt->gcPoke = true;
if (cx->thread == rt->gcThread) {
JS_ASSERT(rt->gcRunning);
return;
}
LetOtherGCFinish(cx);
/*
* Check if the GC on another thread have collected the garbage and
* it was not a set slot request.
*/
if (!rt->gcPoke)
return;
}
#endif /* JS_THREADSAFE */
BeginGCSession(cx);
METER(rt->gcStats.poke++);
/*
* Do not scan the current thread on the shutdown or when the GC is called
* outside a request.
*/
bool scanGCThreadStack = (rt->state != JSRTS_LANDING);
#ifdef JS_THREADSAFE
scanGCThreadStack &= !!cx->thread->requestContext;
#endif
if (scanGCThreadStack)
JS_THREAD_DATA(cx)->conservativeGC.enable(true);
bool firstRun = true;
do {
rt->gcPoke = false;
AutoUnlockGC unlock(rt);
if (firstRun) {
PreGCCleanup(cx, gckind);
TIMESTAMP(startMark);
firstRun = false;
}
GC(cx GCTIMER_ARG);
// GC again if:
// - another thread, not in a request, called js_GC
// - js_GC was called recursively
// - a finalizer called js_RemoveRoot or js_UnlockGCThingRT.
} while (rt->gcPoke);
if (scanGCThreadStack)
JS_THREAD_DATA(cx)->conservativeGC.disable();
rt->gcRegenShapes = false;
rt->setGCLastBytes(rt->gcBytes);
EndGCSession(cx);
}
/*
* The gckind flag bit GC_LOCK_HELD indicates a call from js_NewGCThing with
* rt->gcLock already held, so the lock should be kept on return.
*/
void
js_GC(JSContext *cx, JSGCInvocationKind gckind)
{
JSRuntime *rt = cx->runtime;
/*
* Don't collect garbage if the runtime isn't up, and cx is not the last
* context in the runtime. The last context must force a GC, and nothing
* should suppress that final collection or there may be shutdown leaks,
* or runtime bloat until the next context is created.
*/
if (rt->state != JSRTS_UP && gckind != GC_LAST_CONTEXT)
return;
GCTIMER_BEGIN();
do {
/*
* Let the API user decide to defer a GC if it wants to (unless this
* is the last context). Invoke the callback regardless. Sample the
* callback in case we are freely racing with a JS_SetGCCallback{,RT}
* on another thread.
*/
if (JSGCCallback callback = rt->gcCallback) {
Conditionally<AutoUnlockGC> unlockIf(!!(gckind & GC_LOCK_HELD), rt);
if (!callback(cx, JSGC_BEGIN) && gckind != GC_LAST_CONTEXT)
return;
}
{
/* Lock out other GC allocator and collector invocations. */
Conditionally<AutoLockGC> lockIf(!(gckind & GC_LOCK_HELD), rt);
GCUntilDone(cx, gckind GCTIMER_ARG);
}
/* We re-sample the callback again as the finalizers can change it. */
if (JSGCCallback callback = rt->gcCallback) {
Conditionally<AutoUnlockGC> unlockIf(gckind & GC_LOCK_HELD, rt);
(void) callback(cx, JSGC_END);
}
/*
* On shutdown, iterate until the JSGC_END callback stops creating
* garbage.
*/
} while (gckind == GC_LAST_CONTEXT && rt->gcPoke);
GCTIMER_END(gckind == GC_LAST_CONTEXT);
}
namespace js {
bool
SetProtoCheckingForCycles(JSContext *cx, JSObject *obj, JSObject *proto)
{
JSRuntime *rt = cx->runtime;
/*
* This function cannot be called during the GC and always requires a
* request.
*/
#ifdef JS_THREADSAFE
JS_ASSERT(cx->requestDepth);
#endif
AutoLockGC lock(rt);
/*
* The set slot request cannot be called recursively and must not be
* called during a normal GC. So if at this point JSRuntime::gcThread is
* set it must be a GC or a set slot request from another thread.
*/
#ifdef JS_THREADSAFE
if (rt->gcThread) {
JS_ASSERT(cx->thread != rt->gcThread);
LetOtherGCFinish(cx);
}
#endif
BeginGCSession(cx);
bool cycle;
{
AutoUnlockGC unlock(rt);
cycle = false;
for (JSObject *obj2 = proto; obj2;) {
obj2 = obj2->wrappedObject(cx);
if (obj2 == obj) {
cycle = true;
break;
}
obj2 = obj2->getProto();
}
if (!cycle)
obj->setProto(proto);
}
EndGCSession(cx);
return !cycle;
}
JSCompartment *
NewCompartment(JSContext *cx, JSPrincipals *principals)
{
JSRuntime *rt = cx->runtime;
JSCompartment *compartment = new JSCompartment(rt);
if (!compartment || !compartment->init()) {
JS_ReportOutOfMemory(cx);
return NULL;
}
if (principals) {
compartment->principals = principals;
JSPRINCIPALS_HOLD(cx, principals);
}
{
AutoLockGC lock(rt);
if (!rt->compartments.append(compartment)) {
AutoUnlockGC unlock(rt);
JS_ReportOutOfMemory(cx);
return NULL;
}
}
JSCompartmentCallback callback = rt->compartmentCallback;
if (callback && !callback(cx, compartment, JSCOMPARTMENT_NEW)) {
AutoLockGC lock(rt);
rt->compartments.popBack();
return NULL;
}
return compartment;
}
}
|
C0DEC0L0NY/authentication-service-java
|
src/main/java/com/gregburgoon/authenticationservice/dto/CredentialsDTO.java
|
package com.gregburgoon.authenticationservice.dto;
import com.gregburgoon.authenticationservice.constraint.ValidPassword;
import com.gregburgoon.authenticationservice.constraint.group.PrimaryValidations;
import com.gregburgoon.authenticationservice.constraint.group.SecondaryValidations;
import lombok.Builder;
import lombok.Getter;
import javax.validation.GroupSequence;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
@GroupSequence({PrimaryValidations.class, SecondaryValidations.class, CredentialsDTO.class})
@ValidPassword(groups = SecondaryValidations.class)
@Builder
public class CredentialsDTO {
@NotBlank(message = "Must have a Password", groups = PrimaryValidations.class)
@Getter
private String password;
@NotBlank(message = "Must have an Email", groups = PrimaryValidations.class)
@Getter
@Pattern(regexp = "^[_A-Za-z0-9-+]+(.[_A-Za-z0-9-]+)*@" +
"[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$",
message = "Invalid Email", groups = SecondaryValidations.class)
private String email;
}
|
kmikhailov-tmn/NaviGridContour
|
test/ru/navilab/grid/contour/WktShow.java
|
package ru.navilab.grid.contour;
import javax.swing.*;
import java.awt.*;
/**
* Created by: Mikhailov_KG
* Date: 24.07.2020
*/
public class WktShow {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
WktShowForm wktShowForm = new WktShowForm();
JPanel mainPanel = wktShowForm.getMainPanel();
JFrame frame = new JFrame("Wkt");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(800,600));
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
}
|
em-mcg/cse223b-mesos
|
src/examples/long_lived_framework.cpp
|
<filename>src/examples/long_lived_framework.cpp<gh_stars>0
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <glog/logging.h>
#include <iostream>
#include <queue>
#include <string>
#include <mesos/v1/mesos.hpp>
#include <mesos/v1/resources.hpp>
#include <mesos/v1/scheduler.hpp>
#include <mesos/authorizer/acls.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/help.hpp>
#include <process/http.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/time.hpp>
#include <process/metrics/counter.hpp>
#include <process/metrics/pull_gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/flags.hpp>
#include <stout/foreach.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/protobuf.hpp>
#include <stout/stringify.hpp>
#include <stout/os/realpath.hpp>
#include "common/parse.hpp"
#include "examples/flags.hpp"
#include "logging/logging.hpp"
using std::queue;
using std::string;
using std::vector;
using google::protobuf::RepeatedPtrField;
using mesos::v1::AgentID;
using mesos::v1::CommandInfo;
using mesos::v1::Credential;
using mesos::v1::ExecutorID;
using mesos::v1::ExecutorInfo;
using mesos::v1::Filters;
using mesos::v1::FrameworkID;
using mesos::v1::FrameworkInfo;
using mesos::v1::Offer;
using mesos::v1::Resources;
using mesos::v1::TaskInfo;
using mesos::v1::TaskState;
using mesos::v1::TaskStatus;
using mesos::v1::scheduler::Call;
using mesos::v1::scheduler::Event;
using mesos::v1::scheduler::Mesos;
using process::AUTHENTICATION;
using process::Clock;
using process::defer;
using process::DESCRIPTION;
using process::HELP;
using process::Owned;
using process::TLDR;
using process::http::OK;
using process::metrics::PullGauge;
using process::metrics::Counter;
// NOTE: Per-task resources are nominal because all of the resources for the
// container are provisioned when the executor is created. The executor can
// run multiple tasks at once, but uses a constant amount of resources
// regardless of the number of tasks.
const double CPUS_PER_TASK = 0.001;
const int32_t MEM_PER_TASK = 1;
const double CPUS_PER_EXECUTOR = 0.1;
const int32_t MEM_PER_EXECUTOR = 32;
constexpr char EXECUTOR_BINARY[] = "long-lived-executor";
constexpr char EXECUTOR_NAME[] = "Long Lived Executor (C++)";
constexpr char FRAMEWORK_NAME[] = "Long Lived Framework (C++)";
constexpr char FRAMEWORK_METRICS_PREFIX[] = "long_lived_framework";
// This scheduler picks one agent and repeatedly launches sleep tasks on it,
// using a single multi-task executor. If the agent or executor fails, the
// scheduler will pick another agent and continue launching sleep tasks.
class LongLivedScheduler : public process::Process<LongLivedScheduler>
{
public:
LongLivedScheduler(
const string& _master,
const FrameworkInfo& _framework,
const ExecutorInfo& _executor,
const Option<Credential>& _credential)
: state(DISCONNECTED),
master(_master),
framework(_framework),
role(_framework.roles(0)),
executor(_executor),
taskResources([this]() {
Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_TASK) +
";mem:" + stringify(MEM_PER_TASK)).get();
resources.allocate(this->role);
return resources;
}()),
tasksLaunched(0),
credential(_credential),
metrics(*this)
{
start_time = Clock::now();
}
virtual ~LongLivedScheduler() {}
protected:
virtual void initialize()
{
// We initialize the library here to ensure that callbacks are only invoked
// after the process has spawned.
mesos.reset(
new Mesos(
master,
mesos::ContentType::PROTOBUF,
process::defer(self(), &Self::connected),
process::defer(self(), &Self::disconnected),
process::defer(self(), &Self::received, lambda::_1),
credential));
}
void connected()
{
state = CONNECTED;
doReliableRegistration();
}
void disconnected()
{
LOG(INFO) << "Disconnected!";
state = DISCONNECTED;
}
void doReliableRegistration()
{
if (state == SUBSCRIBED || state == DISCONNECTED) {
return;
}
Call call;
call.set_type(Call::SUBSCRIBE);
if (framework.has_id()) {
call.mutable_framework_id()->CopyFrom(framework.id());
}
Call::Subscribe* subscribe = call.mutable_subscribe();
subscribe->mutable_framework_info()->CopyFrom(framework);
mesos->send(call);
process::delay(Seconds(1), self(), &Self::doReliableRegistration);
}
void received(queue<Event> events)
{
while (!events.empty()) {
Event event = events.front();
events.pop();
LOG(INFO) << "Received " << event.type() << " event";
switch (event.type()) {
case Event::SUBSCRIBED: {
framework.mutable_id()->CopyFrom(event.subscribed().framework_id());
LOG(INFO) << "Subscribed with ID '" << framework.id() << "'";
state = SUBSCRIBED;
break;
}
case Event::OFFERS: {
offers(google::protobuf::convert(event.offers().offers()));
break;
}
case Event::UPDATE: {
update(event.update().status());
break;
}
// TODO(greggomann): Implement handling of operation status updates.
case Event::UPDATE_OPERATION_STATUS:
break;
case Event::FAILURE: {
const Event::Failure& failure = event.failure();
if (failure.has_agent_id() && failure.has_executor_id()) {
executorFailed(
failure.executor_id(),
failure.agent_id(),
failure.has_status() ? Option<int>(failure.status()) : None());
} else {
CHECK(failure.has_agent_id());
agentFailed(failure.agent_id());
}
break;
}
case Event::ERROR: {
EXIT(EXIT_FAILURE) << "Error: " << event.error().message();
break;
}
case Event::HEARTBEAT:
case Event::INVERSE_OFFERS:
case Event::RESCIND:
case Event::RESCIND_INVERSE_OFFER:
case Event::MESSAGE: {
break;
}
case Event::UNKNOWN: {
LOG(WARNING) << "Received an UNKNOWN event and ignored";
break;
}
}
}
}
void offers(const vector<Offer>& offers)
{
CHECK_EQ(SUBSCRIBED, state);
const Resources executorResources = [this]() {
Resources resources(executor.resources());
resources.allocate(role);
return resources;
}();
metrics.offers_received += offers.size();
foreach (const Offer& offer, offers) {
if (agentId.isNone()) {
// No active executor running in the cluster.
// Launch a new task with executor.
if (Resources(offer.resources())
.toUnreserved()
.contains(taskResources + executorResources)) {
LOG(INFO) << "Starting executor and task " << tasksLaunched << " on "
<< offer.hostname();
launch(offer);
agentId = offer.agent_id();
} else {
decline(offer);
}
} else if (agentId == offer.agent_id()) {
// Offer from the same agent that has an active executor.
// Launch more tasks on that executor.
if (Resources(offer.resources())
.toUnreserved()
.contains(taskResources)) {
LOG(INFO) << "Starting task " << tasksLaunched << " on "
<< offer.hostname();
launch(offer);
} else {
decline(offer);
}
} else {
// We have an active executor but this offer comes from a
// different agent; decline the offer.
decline(offer);
}
}
}
void update(const TaskStatus& status)
{
CHECK_EQ(SUBSCRIBED, state);
LOG(INFO)
<< "Task " << status.task_id().value()
<< " is in state " << TaskState_Name(status.state())
<< (status.has_message() ? " with message: " + status.message() : "");
if (status.has_uuid()) {
Call call;
call.set_type(Call::ACKNOWLEDGE);
CHECK(framework.has_id());
call.mutable_framework_id()->CopyFrom(framework.id());
Call::Acknowledge* acknowledge = call.mutable_acknowledge();
acknowledge->mutable_agent_id()->CopyFrom(status.agent_id());
acknowledge->mutable_task_id()->CopyFrom(status.task_id());
acknowledge->set_uuid(status.uuid());
mesos->send(call);
}
if (status.state() == TaskState::TASK_KILLED ||
status.state() == TaskState::TASK_LOST ||
status.state() == TaskState::TASK_FAILED ||
status.state() == TaskState::TASK_ERROR) {
// Launch on an invalid offer should not be
// counted as abnormal termination.
if (status.reason() != TaskStatus::REASON_INVALID_OFFERS) {
++metrics.abnormal_terminations;
}
}
}
void agentFailed(const AgentID& _agentId)
{
CHECK_EQ(SUBSCRIBED, state);
LOG(INFO) << "Agent lost: " << _agentId;
if (agentId == _agentId) {
agentId = None();
}
}
void executorFailed(
const ExecutorID& executorId,
const AgentID& _agentId,
const Option<int>& status)
{
CHECK_EQ(SUBSCRIBED, state);
LOG(INFO)
<< "Executor '" << executorId << "' lost on agent '" << _agentId
<< (status.isSome() ? "' with status: " + stringify(status.get()) : "");
agentId = None();
}
private:
// Helper to decline an offer.
void decline(const Offer& offer)
{
Filters filters;
filters.set_refuse_seconds(600);
Call call;
call.set_type(Call::DECLINE);
CHECK(framework.has_id());
call.mutable_framework_id()->CopyFrom(framework.id());
Call::Decline* decline = call.mutable_decline();
decline->add_offer_ids()->CopyFrom(offer.id());
decline->mutable_filters()->CopyFrom(filters);
mesos->send(call);
}
// Helper to launch a task using an offer.
void launch(const Offer& offer)
{
int taskId = tasksLaunched++;
++metrics.tasks_launched;
TaskInfo task;
task.set_name("Task " + stringify(taskId));
task.mutable_task_id()->set_value(stringify(taskId));
task.mutable_agent_id()->MergeFrom(offer.agent_id());
task.mutable_resources()->CopyFrom(taskResources);
task.mutable_executor()->CopyFrom(executor);
Call call;
call.set_type(Call::ACCEPT);
CHECK(framework.has_id());
call.mutable_framework_id()->CopyFrom(framework.id());
Call::Accept* accept = call.mutable_accept();
accept->add_offer_ids()->CopyFrom(offer.id());
Offer::Operation* operation = accept->add_operations();
operation->set_type(Offer::Operation::LAUNCH);
operation->mutable_launch()->add_task_infos()->CopyFrom(task);
mesos->send(call);
}
enum State
{
DISCONNECTED,
CONNECTED,
SUBSCRIBED
} state;
const string master;
FrameworkInfo framework;
const string role;
const ExecutorInfo executor;
const Resources taskResources;
string uri;
int tasksLaunched;
const Option<Credential> credential;
// The agent that is running the long-lived-executor.
// Unless that agent/executor dies, this framework will not launch
// an executor on any other agent.
Option<AgentID> agentId;
Owned<Mesos> mesos;
process::Time start_time;
double _uptime_secs()
{
return (Clock::now() - start_time).secs();
}
double _subscribed()
{
return state == SUBSCRIBED ? 1 : 0;
}
struct Metrics
{
Metrics(const LongLivedScheduler& scheduler)
: uptime_secs(
string(FRAMEWORK_METRICS_PREFIX) + "/uptime_secs",
defer(scheduler, &LongLivedScheduler::_uptime_secs)),
subscribed(
string(FRAMEWORK_METRICS_PREFIX) + "/subscribed",
defer(scheduler, &LongLivedScheduler::_subscribed)),
offers_received(
string(FRAMEWORK_METRICS_PREFIX) + "/offers_received"),
tasks_launched(
string(FRAMEWORK_METRICS_PREFIX) + "/tasks_launched"),
abnormal_terminations(
string(FRAMEWORK_METRICS_PREFIX) + "/abnormal_terminations")
{
process::metrics::add(uptime_secs);
process::metrics::add(subscribed);
process::metrics::add(offers_received);
process::metrics::add(tasks_launched);
process::metrics::add(abnormal_terminations);
}
~Metrics()
{
process::metrics::remove(uptime_secs);
process::metrics::remove(subscribed);
process::metrics::remove(offers_received);
process::metrics::remove(tasks_launched);
process::metrics::remove(abnormal_terminations);
}
process::metrics::PullGauge uptime_secs;
process::metrics::PullGauge subscribed;
process::metrics::Counter offers_received;
process::metrics::Counter tasks_launched;
// The only expected terminal state is TASK_FINISHED.
// Other terminal states are considered incorrect.
process::metrics::Counter abnormal_terminations;
} metrics;
};
class Flags : public virtual mesos::internal::examples::Flags
{
public:
Flags()
{
add(&Flags::build_dir,
"build_dir",
"The build directory of Mesos. If set, the framework will assume\n"
"that the executor, framework, and agent(s) all live on the same\n"
"machine.");
add(&Flags::executor_uri,
"executor_uri",
"URI the fetcher should use to get the executor's binary.\n"
"NOTE: This flag is deprecated in favor of `--executor_uris`");
add(&Flags::executor_uris,
"executor_uris",
"The value could be a JSON-formatted string of `URI`s that\n"
"should be fetched before running the executor, or a file\n"
"path containing the JSON-formatted `URI`s. Path must be of\n"
"the form `file:///path/to/file` or `/path/to/file`.\n"
"This flag replaces `--executor_uri`.\n"
"See the `CommandInfo::URI` message in `mesos.proto` for the\n"
"expected format.\n"
"Example:\n"
"[\n"
" {\n"
" \"value\":\"mesos.apache.org/balloon_executor\",\n"
" \"executable\":\"true\"\n"
" },\n"
" {\n"
" \"value\":\"mesos.apache.org/bundle_for_executor.tar.gz\",\n"
" \"cache\":\"true\"\n"
" }\n"
"]");
add(&Flags::executor_command,
"executor_command",
"The command that should be used to start the executor.\n"
"This will override the value set by `--build_dir`.");
}
// Flags for specifying the executor binary and other URIs.
//
// TODO(armand): Remove the `--executor_uri` flag after the
// deprecation cycle, started in 1.4.0.
Option<string> build_dir;
Option<string> executor_uri;
Option<JSON::Array> executor_uris;
Option<string> executor_command;
};
int main(int argc, char** argv)
{
Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_EXAMPLE_", argc, argv);
if (flags.help) {
std::cout << flags.usage() << std::endl;
return EXIT_SUCCESS;
}
if (load.isError()) {
std::cerr << flags.usage(load.error()) << std::endl;
return EXIT_FAILURE;
}
mesos::internal::logging::initialize(argv[0], false);
// Log any flag warnings.
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
const Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_EXECUTOR) +
";mem:" + stringify(MEM_PER_EXECUTOR)).get();
ExecutorInfo executor;
executor.mutable_executor_id()->set_value("default");
executor.mutable_resources()->CopyFrom(resources);
executor.set_name(EXECUTOR_NAME);
// Determine the command to run the executor based on three possibilities:
// 1) `--executor_command` was set, which overrides the below cases.
// 2) We are in the Mesos build directory, so the targeted executable
// is actually a libtool wrapper script.
// 3) We have not detected the Mesos build directory, so assume the
// executor is in the same directory as the framework.
string command;
// Find this executable's directory to locate executor.
if (flags.executor_command.isSome()) {
command = flags.executor_command.get();
} else if (flags.build_dir.isSome()) {
command = path::join(flags.build_dir.get(), "src", EXECUTOR_BINARY);
} else {
command =
path::join(os::realpath(Path(argv[0]).dirname()).get(), EXECUTOR_BINARY);
}
executor.mutable_command()->set_value(command);
if (flags.executor_uris.isSome() && flags.executor_uri.isSome()) {
EXIT(EXIT_FAILURE)
<< "Flag '--executor_uris' shall not be used with '--executor_uri'";
}
// Copy `--executor_uri` into the command.
if (flags.executor_uri.isSome()) {
LOG(WARNING)
<< "Flag '--executor_uri' is deprecated, use '--executor_uris' instead";
CommandInfo::URI* uri = executor.mutable_command()->add_uris();
uri->set_value(flags.executor_uri.get());
uri->set_executable(true);
}
// Copy `--executor_uris` into the command.
if (flags.executor_uris.isSome()) {
Try<RepeatedPtrField<CommandInfo::URI>> parse =
::protobuf::parse<RepeatedPtrField<CommandInfo::URI>>(
flags.executor_uris.get());
if (parse.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to convert '--executor_uris' to protobuf: " << parse.error();
}
executor.mutable_command()->mutable_uris()->CopyFrom(parse.get());
}
FrameworkInfo framework;
framework.set_user(os::user().get());
framework.set_principal(flags.principal);
framework.set_name(FRAMEWORK_NAME);
framework.set_checkpoint(flags.checkpoint);
framework.add_roles(flags.role);
framework.add_capabilities()->set_type(
FrameworkInfo::Capability::MULTI_ROLE);
framework.add_capabilities()->set_type(
FrameworkInfo::Capability::RESERVATION_REFINEMENT);
Option<Credential> credential = None();
if (flags.authenticate) {
Credential credential_;
credential_.set_principal(flags.principal);
if (flags.secret.isSome()) {
credential_.set_secret(flags.secret.get());
}
credential = credential_;
}
if (flags.master == "local") {
// Configure master.
os::setenv("MESOS_ROLES", flags.role);
os::setenv(
"MESOS_AUTHENTICATE_HTTP_FRAMEWORKS",
stringify(flags.authenticate));
os::setenv("MESOS_HTTP_FRAMEWORK_AUTHENTICATORS", "basic");
mesos::ACLs acls;
mesos::ACL::RegisterFramework* acl = acls.add_register_frameworks();
acl->mutable_principals()->set_type(mesos::ACL::Entity::ANY);
acl->mutable_roles()->add_values(flags.role);
os::setenv("MESOS_ACLS", stringify(JSON::protobuf(acls)));
}
Owned<LongLivedScheduler> scheduler(new LongLivedScheduler(
flags.master,
framework,
executor,
credential));
process::spawn(scheduler.get());
process::wait(scheduler.get());
return EXIT_SUCCESS;
}
|
abrahamtovarmob/flang
|
tools/flang2/flang2exe/dinit.h
|
<filename>tools/flang2/flang2exe/dinit.h
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#ifndef DINIT_H_
#define DINIT_H_
/** \file
* \brief (Fortran) declarations needed to use dinitutil.c module.
*/
#include "gbldefs.h"
#include "symtab.h"
#include <stdio.h>
struct CONST;
struct VAR;
typedef struct DREC {/* dinit file record */
DTYPE dtype; /* also sptr */
ISZ_T conval; /* also offset */
} DREC;
#define DINIT_ENDFILE ((DTYPE)-96)
#define DINIT_STARTARY ((DTYPE)-95)
#define DINIT_ENDARY ((DTYPE)-94)
#define DINIT_TYPEDEF ((DTYPE)-93)
#define DINIT_ENDTYPE ((DTYPE)-92)
#define DINIT_LOC ((DTYPE)-99)
#define DINIT_SLOC ((DTYPE)-91)
#define DINIT_REPEAT ((DTYPE)-88)
#define DINIT_SECT ((DTYPE)-87) /* conval field is sptr to string with section name */
#define DINIT_DATASECT ((DTYPE)-86) /* return to data section */
#define DINIT_OFFSET ((DTYPE)-77)
#define DINIT_LABEL ((DTYPE)-33)
#define DINIT_ZEROES ((DTYPE)-66)
#define DINIT_VPUINSTR ((DTYPE)-55) /* sparc/VPU compiler only */
#define DINIT_COMMENT ((DTYPE)-44) /* comment string for asm file - the
* DREC.conval field is an int index into
* the getitem_p table (salloc.c) which
* contains the pointer to the string.
*/
#define DINIT_FILL ((DTYPE)-59)
#define DINIT_MASK ((DTYPE)-60)
#define DINIT_ZEROINIT ((DTYPE)-61) /* llvm : use zeroinitializer */
#define DINIT_FUNCCOUNT ((DTYPE)-31) /* gbl.func_count value */
#define DINIT_STRING ((DTYPE)-30) // holds string initialization, length given
#define DINIT_PROC ((DTYPE)-42) /* procedure symbol value */
/**
\brief ...
*/
bool dinit_ok(int sptr);
/**
\brief ...
*/
int mk_largest_val(DTYPE dtype);
/**
\brief ...
*/
int mk_smallest_val(DTYPE dtype);
/**
\brief ...
*/
int mk_unop(int optype, int lop, DTYPE dtype);
/**
\brief ...
*/
void dinit(struct VAR *ivl, struct CONST *ict);
/**
\brief ...
*/
void dmp_ict(struct CONST *ict, FILE *f);
/**
\brief ...
*/
void dmp_ivl(struct VAR *ivl, FILE *f);
/**
\brief ...
*/
void do_dinit(void);
#endif
|
guzhigang001/MKDataDemo
|
lib/src/main/java/com/ggxiaozhi/lib/class9/class5/NumArray4.java
|
<gh_stars>0
package com.ggxiaozhi.lib.class9.class5;
import com.ggxiaozhi.lib.class9.class1_4.Merger;
import com.ggxiaozhi.lib.class9.class1_4.SegmentTree;
/**
* 307. 区域和检索 - 数组可修改
*/
class NumArray4 {
private SegmentTree<Integer> sg;
public NumArray4(int[] nums) {
if (nums.length > 0) {
Integer[] integers = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
integers[i] = nums[i];
}
sg = new SegmentTree<>(integers, new Merger<Integer>() {
@Override
public Integer merge(Integer a, Integer b) {
return a + b;
}
});
}
}
public int sumRange(int i, int j) {
return sg.query(i, j);
}
/**
* 将第i个元素更新后 那么 sum中i+1以后的元素都要更新
*
* 经过main方法的测试没问题
* @param index
* @param val
*/
public void update(int index, int val) {
sg.set(index,val);
}
public static void main(String[] args) {
int[] nums = {-2, 0, 3, -5, 2, -1};
NumArray4 numArray = new NumArray4(nums);
System.out.println(numArray.sumRange(0, 2));
System.out.println(numArray.sumRange(2, 5));
System.out.println(numArray.sumRange(0, 5));
numArray.update(1,1);
System.out.println();
//int[] nums = {-2, 1, 3, -5, 2, -1};
System.out.println(numArray.sumRange(0, 2));
System.out.println(numArray.sumRange(2, 5));
System.out.println(numArray.sumRange(0, 5));
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
|
iaugv27d98/ex
|
httpserver/system.go
|
<reponame>iaugv27d98/ex<filename>httpserver/system.go<gh_stars>1-10
package httpserver
import (
"context"
"fmt"
"net/http"
"github.com/circleci/ex/system"
)
func Load(ctx context.Context, name, addr string, handler http.Handler, sys *system.System) (*HTTPServer, error) {
server, err := New(ctx, name, addr, handler)
if err != nil {
return nil, fmt.Errorf("error starting %q server", name)
}
sys.AddService(server.Serve)
sys.AddMetrics(server.MetricsProducer())
return server, nil
}
|
cu-coders/cucoders
|
src/components/resources/resources.js
|
<reponame>cu-coders/cucoders
import React, { useState } from "react";
import { motion } from "framer-motion";
import tw from "twin.macro";
import styled from "styled-components";
import { css } from "styled-components/macro"; //eslint-disable-line
import { Container, ContentWithPaddingXl } from "components/misc/Layouts.js";
import { SectionHeading } from "components/misc/Headings.js";
import { PrimaryButton as PrimaryButtonBase } from "components/misc/Buttons.js";
import { ReactComponent as SvgDecoratorBlob1 } from "images/svg-decorator-blob-5.svg";
import { ReactComponent as SvgDecoratorBlob2 } from "images/svg-decorator-blob-7.svg";
import AnimationRevealPage from "helpers/AnimationRevealPage.js";
import Header1 from "components/headers/light.js";
import Footer from "components/footers/footers.js";
const HeaderRow = tw.div`flex justify-between items-center flex-col xl:flex-row`;
const Header = tw(SectionHeading)``;
const TabContent = tw(motion.div)`mt-6 flex flex-wrap sm:-mr-10 md:-mr-6 lg:-mr-12`;
const CardContainer = tw.div`mt-10 w-full sm:w-1/2 md:w-1/3 lg:w-1/4 sm:pr-10 md:pr-6 lg:pr-12`;
const Card = tw(motion.a)`bg-gray-200 rounded-b block max-w-xs mx-auto sm:max-w-none sm:mx-0`;
const CardImageContainer = styled.div`
${props => css`background-image: url("${props.imageSrc}");`}
${tw`h-56 xl:h-64 bg-center bg-cover relative rounded-t`}
`;
const CardHoverOverlay = styled(motion.div)`
background-color: rgba(255, 255, 255, 0.5);
${tw`absolute inset-0 flex justify-center items-center`}
`;
const CardButton = tw(PrimaryButtonBase)`text-sm`;
const CardText = tw.div`p-4 text-gray-900`;
const CardTitle = tw.h5`text-lg font-semibold group-hover:text-primary-500`;
const CardContent = tw.p`mt-1 text-sm font-medium text-gray-600`;
const DecoratorBlob1 = styled(SvgDecoratorBlob1)`
${tw`pointer-events-none -z-20 absolute right-0 top-0 h-64 w-64 opacity-15 transform translate-x-2/3 -translate-y-12 text-pink-400`}
`;
const DecoratorBlob2 = styled(SvgDecoratorBlob2)`
${tw`pointer-events-none -z-20 absolute left-0 bottom-0 h-80 w-80 opacity-15 transform -translate-x-2/3 text-primary-500`}
`;
export default ({
isLoggedIn,
heading = "Checkout the Resources",
tabs = {
Starters: [
{
imageSrc:
"https://images.unsplash.com/photo-1477039181047-efb4357d01bd?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Data Structure & Algorithm",
content: "A good algorithm usually comes together with a set of good data structures that allow the algorithm to manipulate the data efficiently.",
price: "$5.99",
rating: "5.0",
reviews: "87",
url: "algo"
},
{
imageSrc:
"https://images.unsplash.com/photo-1515879218367-8466d910aaa4?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Competitive Programming",
content: "Competitive programming is a mind sport usually held over the Internet or a local network, involving participants trying to program according to provided specifications.",
price: "$7.99",
rating: "4.9",
reviews: "89",
url: "cp"
},
{
imageSrc:
"https://images.unsplash.com/photo-1571171637578-41bc2dd41cd2?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Web Development",
content: "Web development is the work involved in developing a Web site for the Internet or an intranet.",
price: "$8.99",
rating: "4.6",
reviews: "12",
url: "web"
},
{
imageSrc:
"https://images.unsplash.com/photo-1613068687893-5e85b4638b56?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Programming Language",
content: "A programming language is a formal language comprising a set of instructions that produce various kinds of output. Programming languages are used in computer programming to implement algorithms. Most programming languages consist of instructions for computers.",
price: "$7.99",
rating: "4.2",
reviews: "19",
url: "language"
},
{
imageSrc:
"https://images.unsplash.com/photo-1531746790731-6c087fecd65a?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "AI & ML",
content: "I refers to the concept of machines mimicking human cognition. To reference artificial intelligence is to allude to machines performing tasks that only seemed plausible with human thinking and logic.",
price: "$7.99",
rating: "4.2",
reviews: "19",
url: "ComingNow"
},
{
imageSrc:
"https://images.unsplash.com/photo-1610924125440-db821b18a56e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Database",
content: "A database is an organized collection of data, generally stored and accessed electronically from a computer system. Where databases are more complex they are often developed using formal design and modeling techniques.",
price: "$2.99",
rating: "5.0",
reviews: "61",
url: "database"
},
{
imageSrc:
"https://images.unsplash.com/photo-1514168757508-07ffe9ae125b?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTR8fGV0aGljYWwlMjBoYWNraW5nfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Security",
content: "Computer security, cybersecurity or information technology security is the protection of computer systems and networks from information disclosure, theft of or damage to their hardware, software, or electronic data, as well as from the disruption or misdirection of the services they provide.",
price: "$2.99",
rating: "5.0",
reviews: "61",
url: "security"
},
{
imageSrc:
"https://images.unsplash.com/photo-1526498460520-4c246339dccb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Version Control",
content: "In software engineering, version control is a class of systems responsible for managing changes to computer programs, documents, large web sites, or other collections of information. Version control is a component of software configuration management.",
price: "$3.99",
rating: "4.2",
reviews: "95",
url: "versioncontrol"
},
{
imageSrc:
"https://images.unsplash.com/photo-1526498460520-4c246339dccb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Mobile Development",
content: "Mobile app development is the act or process by which a mobile app is developed for mobile devices, such as personal digital assistants, enterprise digital assistants or mobile phones.",
price: "$3.99",
rating: "4.2",
reviews: "95",
url: "ComingNow"
},
{
imageSrc:
"https://images.unsplash.com/photo-1599227577308-4323e4e2c946?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80",
title: "Cloud",
content: "Cloud computing is the on-demand availability of computer system resources, especially data storage and computing power, without direct active management by the user.",
price: "$3.99",
rating: "3.9",
reviews: "26",
url: "ComingNow"
}
]
}
}) => {
/*
* To customize the tabs, pass in data using the `tabs` prop. It should be an object which contains the name of the tab
* as the key and value of the key will be its content (as an array of objects).
* To see what attributes are configurable of each object inside this array see the example above for "Starters".
*/
const tabsKeys = Object.keys(tabs);
const [activeTab] = useState(tabsKeys[0]);
return (
<>
<AnimationRevealPage>
<Header1 isLoggedIn={ isLoggedIn}/>
<Container>
<ContentWithPaddingXl>
<HeaderRow>
<Header>{heading}</Header>
</HeaderRow>
{tabsKeys.map((tabKey, index) => (
<TabContent
key={index}
variants={{
current: {
opacity: 1,
scale:1,
display: "flex",
},
hidden: {
opacity: 0,
scale:0.8,
display: "none",
}
}}
transition={{ duration: 0.4 }}
initial={activeTab === tabKey ? "current" : "hidden"}
animate={activeTab === tabKey ? "current" : "hidden"}
>
{tabs[tabKey].map((card, index) => (
<CardContainer key={index}>
<Card className="group" href={card.url} initial="rest" whileHover="hover" animate="rest">
<CardImageContainer imageSrc={card.imageSrc}>
<CardHoverOverlay
variants={{
hover: {
opacity: 1,
height: "auto"
},
rest: {
opacity: 0,
height: 0
}
}}
transition={{ duration: 0.3 }}
>
<CardButton>See Resources</CardButton>
</CardHoverOverlay>
</CardImageContainer>
<CardText>
<CardTitle>{card.title}</CardTitle>
<CardContent>{card.content}</CardContent>
</CardText>
</Card>
</CardContainer>
))}
</TabContent>
))}
</ContentWithPaddingXl>
<DecoratorBlob1 />
<DecoratorBlob2 />
</Container>
<Footer />
</AnimationRevealPage>
</>
);
};
|
iondv/ion-old-java-version-20140819
|
ion-modeler/src/ion/modeler/resources/IonSectionResource.java
|
package ion.modeler.resources;
import ion.viewmodel.plain.StoredNavSection;
import org.eclipse.core.resources.IFile;
public class IonSectionResource extends IonFileBasedResource {
public IonSectionResource(IFile src, StoredNavSection section) {
super(src);
refresh(section);
}
public void refresh(StoredNavSection section){
this.name = section.name;
this.displayName = section.caption;
}
}
|
broken98/QueryItSmart
|
src/reducers/forecastReducers.js
|
import _ from 'lodash'
import { types } from '../actions/index'
import { bytesToSize } from '../utils'
import TEMPERATURES from '../data/average_temperatures.json'
import { TIME_MAP } from '../const'
const location = "newyork"
const unit = "fahrenheit"
const averageTemperature = (month) => _.get(TEMPERATURES, `${location}.${unit}.${month}`, 0)
const currentDate = new Date()
const temperatureAve = averageTemperature(currentDate.getMonth())
const initialState = {
param: {
month: new Date().getMonth()+1,
weekday: new Date().getDay()+1,
temperature: temperatureAve,
weather: "sunny",
},
temperatureAve: temperatureAve,
sql: null,
searching: false,
finished: false,
hour: new Date().getHours(),
sliderValue: _.findIndex(TIME_MAP, time => time === new Date().getHours()),
results: [],
totalSize: 0,
basedTimeResult: {},
startTime: null,
finishedTime: null,
elapsedTime: null,
showSQL: false,
hideFinished: false,
error: null,
}
const forecast = (state = initialState, action) => {
switch (action.type) {
case types.FORECAST_PARAM_CHANGE: {
const { key, value } = action
if (key === "month") {
const ave = averageTemperature(value - 1)
return {
...state,
param: {
...state.param,
[key]: value,
temperature: ave,
},
temperatureAve: ave,
}
} else {
return {
...state,
param: {
...state.param,
[key]: value
},
}
}
}
case types.FORECAST_REQUEST_START:
return {
...state,
searching: true,
finished: false,
param: action.param,
sql: action.sql,
startTime: action.time,
}
case types.FORECAST_REQUEST_FINISH: {
const { time, results, totalBytesProcessed } = action
return {
...state,
searching: false,
finished: true,
finishedTime: time,
elapsedTime: time - state.startTime,
results: results,
basedTimeResult: basedTime(results),
totalSize: bytesToSize(totalBytesProcessed),
}
}
case types.FORECAST_REQUEST_ERROR:
return {
...state,
searching: false,
finished: true,
error: action.err,
}
case types.FORECAST_SLIDER_CHANGE: {
const { value } = action
return {
...state,
hour: TIME_MAP[Math.round(value)],
sliderValue: value,
}
}
case types.FORECAST_FINISHED_CLOSE:
return {
...state,
hideFinished: true,
}
case types.FORECAT_SQL_SHOW:
return {
...state,
showSQL: true
}
case types.FORECAT_SQL_CLOSE:
return {
...state,
showSQL: false
}
case types.FORECAT_RESTART:
return {
...initialState
}
default:
return state
}
}
const basedTime = (data) => {
let result = {}
_.times(24, hour => {
const stations = _.filter(data, o => o.hour === hour)
result[hour] = stations
})
return result
}
/**
* @deprecated
*/
const transform = (data) => {
let results = _.times(24, i => {
return {
hour: i+1,
stations: []
}
})
// Get the minimum and maximum values
let { min, max } = _.reduce(data, (acc, data) => {
_.each(data.times, time => {
if (acc.min === -1) {
acc.min = time.num
} else if (time.num < acc.min) {
acc.min = time.num
} else if (time.num > acc.max) {
acc.max = time.num
}
})
return acc;
}, {
min: -1,
max: 0
})
// Add weightLocation for heatmap
const weighted = (current, min, max) => (current / max) * 2.0
_.each(data, (obj, i) => {
const stationId = obj.station_id
_.each(obj.times, time => {
const hour = time.hour
const num = time.num
results = _.map(results, ret => {
if (ret.hour === hour) {
// map latlng of station
const station = _.find(stations, st => st.station_id == stationId) || {}
ret.stations.push({
stationId: stationId,
latitude: station.latitude,
longitude: station.longitude,
num: num,
weight: weighted(num, min, max)
})
}
return ret
})
})
})
return results
}
export default forecast
|
axetang/AxePython
|
PyMOTW/source/dis/dis_faster_loop.py
|
<gh_stars>1-10
#!/usr/bin/env python3
# encoding: utf-8
import string
class Dictionary:
def __init__(self, words):
self.by_letter = {
letter: []
for letter in string.ascii_letters
}
self.load_data(words)
def load_data(self, words):
for word in words:
self.by_letter[word[0]].append(word)
|
h-rover/gtsam
|
gtsam/nonlinear/Values.h
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: <NAME>, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Values.h
* @author <NAME>
*
* @brief A non-templated config holding any types of Manifold-group elements
*
* Detailed story:
* A values structure is a map from keys to values. It is used to specify the value of a bunch
* of variables in a factor graph. A Values is a values structure which can hold variables that
* are elements on manifolds, not just vectors. It then, as a whole, implements a aggregate type
* which is also a manifold element, and hence supports operations dim, retract, and localCoordinates.
*/
#pragma once
#include <gtsam/base/FastDefaultAllocator.h>
#include <gtsam/base/GenericValue.h>
#include <gtsam/base/VectorSpace.h>
#include <gtsam/inference/Key.h>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/ptr_container/serialize_ptr_map.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <utility>
namespace gtsam {
// Forward declarations / utilities
class VectorValues;
class ValueAutomaticCasting;
template<typename T> static bool _truePredicate(const T&) { return true; }
/* ************************************************************************* */
class GTSAM_EXPORT ValueCloneAllocator {
public:
static Value* allocate_clone(const Value& a) { return a.clone_(); }
static void deallocate_clone(const Value* a) { a->deallocate_(); }
ValueCloneAllocator() {}
};
/**
* A non-templated config holding any types of Manifold-group elements. A
* values structure is a map from keys to values. It is used to specify the
* value of a bunch of variables in a factor graph. A Values is a values
* structure which can hold variables that are elements on manifolds, not just
* vectors. It then, as a whole, implements a aggregate type which is also a
* manifold element, and hence supports operations dim, retract, and
* localCoordinates.
*/
class GTSAM_EXPORT Values {
private:
// Internally we store a boost ptr_map, with a ValueCloneAllocator (defined
// below) to clone and deallocate the Value objects, and our compile-flag-
// dependent FastDefaultAllocator to allocate map nodes. In this way, the
// user defines the allocation details (i.e. optimize for memory pool/arenas
// concurrency).
typedef internal::FastDefaultAllocator<typename std::pair<const Key, void*>>::type KeyValuePtrPairAllocator;
typedef boost::ptr_map<
Key,
Value,
std::less<Key>,
ValueCloneAllocator,
KeyValuePtrPairAllocator > KeyValueMap;
// The member to store the values, see just above
KeyValueMap values_;
// Types obtained by iterating
typedef KeyValueMap::const_iterator::value_type ConstKeyValuePtrPair;
typedef KeyValueMap::iterator::value_type KeyValuePtrPair;
public:
/// A shared_ptr to this class
typedef boost::shared_ptr<Values> shared_ptr;
/// A const shared_ptr to this class
typedef boost::shared_ptr<const Values> const_shared_ptr;
/// A key-value pair, which you get by dereferencing iterators
struct GTSAM_EXPORT KeyValuePair {
const Key key; ///< The key
Value& value; ///< The value
KeyValuePair(Key _key, Value& _value) : key(_key), value(_value) {}
};
/// A key-value pair, which you get by dereferencing iterators
struct GTSAM_EXPORT ConstKeyValuePair {
const Key key; ///< The key
const Value& value; ///< The value
ConstKeyValuePair(Key _key, const Value& _value) : key(_key), value(_value) {}
ConstKeyValuePair(const KeyValuePair& kv) : key(kv.key), value(kv.value) {}
};
/// Mutable forward iterator, with value type KeyValuePair
typedef boost::transform_iterator<
std::function<KeyValuePair(const KeyValuePtrPair&)>, KeyValueMap::iterator> iterator;
/// Const forward iterator, with value type ConstKeyValuePair
typedef boost::transform_iterator<
std::function<ConstKeyValuePair(const ConstKeyValuePtrPair&)>, KeyValueMap::const_iterator> const_iterator;
/// Mutable reverse iterator, with value type KeyValuePair
typedef boost::transform_iterator<
std::function<KeyValuePair(const KeyValuePtrPair&)>, KeyValueMap::reverse_iterator> reverse_iterator;
/// Const reverse iterator, with value type ConstKeyValuePair
typedef boost::transform_iterator<
std::function<ConstKeyValuePair(const ConstKeyValuePtrPair&)>, KeyValueMap::const_reverse_iterator> const_reverse_iterator;
typedef KeyValuePair value_type;
/** A filtered view of a Values, returned from Values::filter. */
template<class ValueType = Value>
class Filtered;
/** A filtered view of a const Values, returned from Values::filter. */
template<class ValueType = Value>
class ConstFiltered;
/** Default constructor creates an empty Values class */
Values() {}
/** Copy constructor duplicates all keys and values */
Values(const Values& other);
/** Move constructor */
Values(Values&& other);
/** Constructor from initializer list. Example usage:
* \code
* Values v = {{k1, genericValue(pose1)}, {k2, genericValue(point2)}};
* \endcode
*/
Values(std::initializer_list<ConstKeyValuePair> init);
/** Construct from a Values and an update vector: identical to other.retract(delta) */
Values(const Values& other, const VectorValues& delta);
/** Constructor from a Filtered view copies out all values */
template<class ValueType>
Values(const Filtered<ValueType>& view);
/** Constructor from a Filtered or ConstFiltered view */
template<class ValueType>
Values(const ConstFiltered<ValueType>& view);
/// @name Testable
/// @{
/** print method for testing and debugging */
void print(const std::string& str = "", const KeyFormatter& keyFormatter = DefaultKeyFormatter) const;
/** Test whether the sets of keys and values are identical */
bool equals(const Values& other, double tol=1e-9) const;
/// @}
/** Retrieve a variable by key \c j. The type of the value associated with
* this key is supplied as a template argument to this function.
* @param j Retrieve the value associated with this key
* @tparam ValueType The type of the value stored with this key, this method
* Throws DynamicValuesIncorrectType if this requested type is not correct.
* Dynamic matrices/vectors can be retrieved as fixed-size, but not vice-versa.
* @return The stored value
*/
template <typename ValueType>
const ValueType at(Key j) const;
/// version for double
double atDouble(size_t key) const { return at<double>(key);}
/** Retrieve a variable by key \c j. This version returns a reference
* to the base Value class, and needs to be casted before use.
* @param j Retrieve the value associated with this key
* @return A const reference to the stored value
*/
const Value& at(Key j) const;
/** Check if a value exists with key \c j. See exists<>(Key j)
* and exists(const TypedKey& j) for versions that return the value if it
* exists. */
bool exists(Key j) const;
/** Check if a value with key \c j exists, returns the value with type
* \c Value if the key does exist, or boost::none if it does not exist.
* Throws DynamicValuesIncorrectType if the value type associated with the
* requested key does not match the stored value type. */
template<typename ValueType>
boost::optional<const ValueType&> exists(Key j) const;
/** Find an element by key, returning an iterator, or end() if the key was
* not found. */
iterator find(Key j) { return boost::make_transform_iterator(values_.find(j), &make_deref_pair); }
/** Find an element by key, returning an iterator, or end() if the key was
* not found. */
const_iterator find(Key j) const { return boost::make_transform_iterator(values_.find(j), &make_const_deref_pair); }
/** Find the element greater than or equal to the specified key. */
iterator lower_bound(Key j) { return boost::make_transform_iterator(values_.lower_bound(j), &make_deref_pair); }
/** Find the element greater than or equal to the specified key. */
const_iterator lower_bound(Key j) const { return boost::make_transform_iterator(values_.lower_bound(j), &make_const_deref_pair); }
/** Find the lowest-ordered element greater than the specified key. */
iterator upper_bound(Key j) { return boost::make_transform_iterator(values_.upper_bound(j), &make_deref_pair); }
/** Find the lowest-ordered element greater than the specified key. */
const_iterator upper_bound(Key j) const { return boost::make_transform_iterator(values_.upper_bound(j), &make_const_deref_pair); }
/** The number of variables in this config */
size_t size() const { return values_.size(); }
/** whether the config is empty */
bool empty() const { return values_.empty(); }
const_iterator begin() const { return boost::make_transform_iterator(values_.begin(), &make_const_deref_pair); }
const_iterator end() const { return boost::make_transform_iterator(values_.end(), &make_const_deref_pair); }
iterator begin() { return boost::make_transform_iterator(values_.begin(), &make_deref_pair); }
iterator end() { return boost::make_transform_iterator(values_.end(), &make_deref_pair); }
const_reverse_iterator rbegin() const { return boost::make_transform_iterator(values_.rbegin(), &make_const_deref_pair); }
const_reverse_iterator rend() const { return boost::make_transform_iterator(values_.rend(), &make_const_deref_pair); }
reverse_iterator rbegin() { return boost::make_transform_iterator(values_.rbegin(), &make_deref_pair); }
reverse_iterator rend() { return boost::make_transform_iterator(values_.rend(), &make_deref_pair); }
/// @name Manifold Operations
/// @{
/** Add a delta config to current config and returns a new config */
Values retract(const VectorValues& delta) const;
/** Get a delta config about a linearization point c0 (*this) */
VectorValues localCoordinates(const Values& cp) const;
///@}
/** Add a variable with the given j, throws KeyAlreadyExists<J> if j is already present */
void insert(Key j, const Value& val);
/** Add a set of variables, throws KeyAlreadyExists<J> if a key is already present */
void insert(const Values& values);
/** Templated version to add a variable with the given j,
* throws KeyAlreadyExists<J> if j is already present
*/
template <typename ValueType>
void insert(Key j, const ValueType& val);
/// version for double
void insertDouble(Key j, double c) { insert<double>(j,c); }
/** insert that mimics the STL map insert - if the value already exists, the map is not modified
* and an iterator to the existing value is returned, along with 'false'. If the value did not
* exist, it is inserted and an iterator pointing to the new element, along with 'true', is
* returned. */
std::pair<iterator, bool> tryInsert(Key j, const Value& value);
/** single element change of existing element */
void update(Key j, const Value& val);
/** Templated version to update a variable with the given j,
* throws KeyDoesNotExist<J> if j is not present.
* If no chart is specified, the DefaultChart<ValueType> is used.
*/
template <typename T>
void update(Key j, const T& val);
/** update the current available values without adding new ones */
void update(const Values& values);
/// If key j exists, update value, else perform an insert.
void insert_or_assign(Key j, const Value& val);
/**
* Update a set of variables.
* If any variable key doe not exist, then perform an insert.
*/
void insert_or_assign(const Values& values);
/// Templated version to insert_or_assign a variable with the given j.
template <typename ValueType>
void insert_or_assign(Key j, const ValueType& val);
/** Remove a variable from the config, throws KeyDoesNotExist<J> if j is not present */
void erase(Key j);
/**
* Returns a set of keys in the config
* Note: by construction, the list is ordered
*/
KeyVector keys() const;
/** Replace all keys and variables */
Values& operator=(const Values& rhs);
/** Swap the contents of two Values without copying data */
void swap(Values& other) { values_.swap(other.values_); }
/** Remove all variables from the config */
void clear() { values_.clear(); }
/** Compute the total dimensionality of all values (\f$ O(n) \f$) */
size_t dim() const;
/** Return a VectorValues of zero vectors for each variable in this Values */
VectorValues zeroVectors() const;
/**
* Return a filtered view of this Values class, without copying any data.
* When iterating over the filtered view, only the key-value pairs
* with a key causing \c filterFcn to return \c true are visited. Because
* the object Filtered<Value> returned from filter() is only a
* <em>view</em> the original Values object must not be deallocated or
* go out of scope as long as the view is needed.
* @param filterFcn The function that determines which key-value pairs are
* included in the filtered view, for which this function returns \c true
* on their keys.
* @return A filtered view of the original Values class, which references
* the original Values class.
*/
Filtered<Value>
filter(const std::function<bool(Key)>& filterFcn);
/**
* Return a filtered view of this Values class, without copying any data.
* In this templated version, only key-value pairs whose value matches the
* template argument \c ValueType and whose key causes the function argument
* \c filterFcn to return true are visited when iterating over the filtered
* view. Because the object Filtered<Value> returned from filter() is only
* a <em>view</em> the original Values object must not be deallocated or
* go out of scope as long as the view is needed.
* @tparam ValueType The type that the value in a key-value pair must match
* to be included in the filtered view. Currently, base classes are not
* resolved so the type must match exactly, except if ValueType = Value, in
* which case no type filtering is done.
* @param filterFcn The function that determines which key-value pairs are
* included in the filtered view, for which this function returns \c true
* on their keys (default: always return true so that filter() only
* filters by type, matching \c ValueType).
* @return A filtered view of the original Values class, which references
* the original Values class.
*/
template<class ValueType>
Filtered<ValueType>
filter(const std::function<bool(Key)>& filterFcn = &_truePredicate<Key>);
/**
* Return a filtered view of this Values class, without copying any data.
* When iterating over the filtered view, only the key-value pairs
* with a key causing \c filterFcn to return \c true are visited. Because
* the object Filtered<Value> returned from filter() is only a
* <em>view</em> the original Values object must not be deallocated or
* go out of scope as long as the view is needed.
* @param filterFcn The function that determines which key-value pairs are
* included in the filtered view, for which this function returns \c true
* on their keys.
* @return A filtered view of the original Values class, which references
* the original Values class.
*/
ConstFiltered<Value>
filter(const std::function<bool(Key)>& filterFcn) const;
/**
* Return a filtered view of this Values class, without copying any data.
* In this templated version, only key-value pairs whose value matches the
* template argument \c ValueType and whose key causes the function argument
* \c filterFcn to return true are visited when iterating over the filtered
* view. Because the object Filtered<Value> returned from filter() is only
* a <em>view</em> the original Values object must not be deallocated or
* go out of scope as long as the view is needed.
* @tparam ValueType The type that the value in a key-value pair must match
* to be included in the filtered view. Currently, base classes are not
* resolved so the type must match exactly, except if ValueType = Value, in
* which case no type filtering is done.
* @param filterFcn The function that determines which key-value pairs are
* included in the filtered view, for which this function returns \c true
* on their keys.
* @return A filtered view of the original Values class, which references
* the original Values class.
*/
template<class ValueType>
ConstFiltered<ValueType>
filter(const std::function<bool(Key)>& filterFcn = &_truePredicate<Key>) const;
// Count values of given type \c ValueType
template<class ValueType>
size_t count() const {
size_t i = 0;
for (const auto key_value : *this) {
if (dynamic_cast<const GenericValue<ValueType>*>(&key_value.value))
++i;
}
return i;
}
private:
// Filters based on ValueType (if not Value) and also based on the user-
// supplied \c filter function.
template<class ValueType>
static bool filterHelper(const std::function<bool(Key)> filter, const ConstKeyValuePair& key_value) {
BOOST_STATIC_ASSERT((!boost::is_same<ValueType, Value>::value));
// Filter and check the type
return filter(key_value.key) && (dynamic_cast<const GenericValue<ValueType>*>(&key_value.value));
}
/** Serialization function */
friend class boost::serialization::access;
template<class ARCHIVE>
void serialize(ARCHIVE & ar, const unsigned int /*version*/) {
ar & BOOST_SERIALIZATION_NVP(values_);
}
static ConstKeyValuePair make_const_deref_pair(const KeyValueMap::const_iterator::value_type& key_value) {
return ConstKeyValuePair(key_value.first, *key_value.second); }
static KeyValuePair make_deref_pair(const KeyValueMap::iterator::value_type& key_value) {
return KeyValuePair(key_value.first, *key_value.second); }
};
/* ************************************************************************* */
class ValuesKeyAlreadyExists : public std::exception {
protected:
const Key key_; ///< The key that already existed
private:
mutable std::string message_;
public:
/// Construct with the key-value pair attempted to be added
ValuesKeyAlreadyExists(Key key) noexcept :
key_(key) {}
~ValuesKeyAlreadyExists() noexcept override {}
/// The duplicate key that was attempted to be added
Key key() const noexcept { return key_; }
/// The message to be displayed to the user
GTSAM_EXPORT const char* what() const noexcept override;
};
/* ************************************************************************* */
class ValuesKeyDoesNotExist : public std::exception {
protected:
const char* operation_; ///< The operation that attempted to access the key
const Key key_; ///< The key that does not exist
private:
mutable std::string message_;
public:
/// Construct with the key that does not exist in the values
ValuesKeyDoesNotExist(const char* operation, Key key) noexcept :
operation_(operation), key_(key) {}
~ValuesKeyDoesNotExist() noexcept override {}
/// The key that was attempted to be accessed that does not exist
Key key() const noexcept { return key_; }
/// The message to be displayed to the user
GTSAM_EXPORT const char* what() const noexcept override;
};
/* ************************************************************************* */
class ValuesIncorrectType : public std::exception {
protected:
const Key key_; ///< The key requested
const std::type_info& storedTypeId_;
const std::type_info& requestedTypeId_;
private:
mutable std::string message_;
public:
/// Construct with the key that does not exist in the values
ValuesIncorrectType(Key key,
const std::type_info& storedTypeId, const std::type_info& requestedTypeId) noexcept :
key_(key), storedTypeId_(storedTypeId), requestedTypeId_(requestedTypeId) {}
~ValuesIncorrectType() noexcept override {}
/// The key that was attempted to be accessed that does not exist
Key key() const noexcept { return key_; }
/// The typeid of the value stores in the Values
const std::type_info& storedTypeId() const { return storedTypeId_; }
/// The requested typeid
const std::type_info& requestedTypeId() const { return requestedTypeId_; }
/// The message to be displayed to the user
GTSAM_EXPORT const char* what() const noexcept override;
};
/* ************************************************************************* */
class DynamicValuesMismatched : public std::exception {
public:
DynamicValuesMismatched() noexcept {}
~DynamicValuesMismatched() noexcept override {}
const char* what() const noexcept override {
return "The Values 'this' and the argument passed to Values::localCoordinates have mismatched keys and values";
}
};
/* ************************************************************************* */
class NoMatchFoundForFixed: public std::exception {
protected:
const size_t M1_, N1_;
const size_t M2_, N2_;
private:
mutable std::string message_;
public:
NoMatchFoundForFixed(size_t M1, size_t N1, size_t M2, size_t N2) noexcept :
M1_(M1), N1_(N1), M2_(M2), N2_(N2) {
}
~NoMatchFoundForFixed() noexcept override {
}
GTSAM_EXPORT const char* what() const noexcept override;
};
/* ************************************************************************* */
/// traits
template<>
struct traits<Values> : public Testable<Values> {
};
} //\ namespace gtsam
#include <gtsam/nonlinear/Values-inl.h>
|
Shashi-rk/azure-sdk-for-java
|
sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/ReplicationStatusImpl.java
|
<filename>sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/ReplicationStatusImpl.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.netapp.implementation;
import com.azure.resourcemanager.netapp.fluent.models.ReplicationStatusInner;
import com.azure.resourcemanager.netapp.models.MirrorState;
import com.azure.resourcemanager.netapp.models.RelationshipStatus;
import com.azure.resourcemanager.netapp.models.ReplicationStatus;
public final class ReplicationStatusImpl implements ReplicationStatus {
private ReplicationStatusInner innerObject;
private final com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager;
ReplicationStatusImpl(
ReplicationStatusInner innerObject, com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public Boolean healthy() {
return this.innerModel().healthy();
}
public RelationshipStatus relationshipStatus() {
return this.innerModel().relationshipStatus();
}
public MirrorState mirrorState() {
return this.innerModel().mirrorState();
}
public String totalProgress() {
return this.innerModel().totalProgress();
}
public String errorMessage() {
return this.innerModel().errorMessage();
}
public ReplicationStatusInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.netapp.NetAppFilesManager manager() {
return this.serviceManager;
}
}
|
masud-technope/ACER-Replication-Package-ASE2017
|
corpus/class/eclipse.pde.ui/5016.java
|
/*******************************************************************************
* Copyright (c) 2006, 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.internal.ui.editor.contentassist.display;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.formatter.IndentManipulation;
import org.eclipse.jface.internal.text.html.SingleCharReader;
/**
* Reads a java doc comment from a java doc comment. Skips star-character
* on begin of line.
* <p>
* XXX: copied from <code>org.eclipse.jdt.ui</code>.
* </p>
*/
public class JavaDocCommentReader extends SingleCharReader {
private IBuffer fBuffer;
private int fCurrPos;
private int fStartPos;
private int fEndPos;
private boolean fWasNewLine;
public JavaDocCommentReader(IBuffer buf, int start, int end) {
fBuffer = buf;
fStartPos = start + 3;
fEndPos = end - 2;
reset();
}
/**
* @see java.io.Reader#read()
*/
@Override
public int read() {
if (fCurrPos < fEndPos) {
char ch;
if (fWasNewLine) {
do {
ch = fBuffer.getChar(fCurrPos++);
} while (fCurrPos < fEndPos && Character.isWhitespace(ch));
if (ch == '*') {
if (fCurrPos < fEndPos) {
do {
ch = fBuffer.getChar(fCurrPos++);
} while (ch == '*');
} else {
return -1;
}
}
} else {
ch = fBuffer.getChar(fCurrPos++);
}
fWasNewLine = IndentManipulation.isLineDelimiterChar(ch);
return ch;
}
return -1;
}
/**
* @see java.io.Reader#close()
*/
@Override
public void close() {
fBuffer = null;
}
/**
* @see java.io.Reader#reset()
*/
@Override
public void reset() {
fCurrPos = fStartPos;
fWasNewLine = true;
}
/**
* Returns the offset of the last read character in the passed buffer.
*
* @return the offset
*/
public int getOffset() {
return fCurrPos;
}
}
|
hluk/product-definition-center
|
pdc/apps/release/filters.py
|
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters
from pdc.apps.common import filters
from .models import Release, ProductVersion, Product, ReleaseType, Variant, CPE, VariantCPE, BaseProduct, ReleaseGroup
class ActiveReleasesFilter(filters.CaseInsensitiveBooleanFilter):
"""
Filter objects depending on whether their releases are active or not. If
active=True, it will only keep objects with at least one active release.
If active=False, it will keep only objects with no active releases.
The `name` argument to __init__ should specify how to get to relases from
the object.
"""
help_text = """
- If "true", show objects with at least one active release.
- If "false", show objects with no active releases.
"""
def _filter(self, qs, name, value):
if not value:
return qs
self._validate_boolean(value)
name = self.name + '__active'
if value.lower() in self.TRUE_STRINGS:
return qs.filter(**{name: True}).distinct()
else:
return qs.exclude(**{name: True}).distinct()
class AllowedPushTargetsFilter(filters.MultiValueFilter):
def __init__(self, parent_names):
super(AllowedPushTargetsFilter, self).__init__()
self.parent_names = parent_names
@filters.value_is_not_empty
def _filter(self, qs, name, value):
qs = qs.exclude(**{'masked_push_targets__name__in': value})
prefix = ''
for parent_name in self.parent_names:
prefix += parent_name + '__'
qs = qs.exclude(**{prefix + 'masked_push_targets__name__in': value})
return qs.filter(**{prefix + 'product__allowed_push_targets__name__in': value})
class ReleaseFilter(django_filters.FilterSet):
release_id = filters.MultiValueFilter(name='release_id')
base_product = filters.MultiValueFilter(name='base_product__base_product_id')
has_base_product = django_filters.CharFilter(method='find_has_base_product')
release_type = filters.MultiValueFilter(name='release_type__short')
product_version = filters.MultiValueFilter(name='product_version__product_version_id')
integrated_with = filters.NullableCharFilter(name='integrated_with__release_id')
active = filters.CaseInsensitiveBooleanFilter()
name = filters.MultiValueFilter(name='name')
short = filters.MultiValueFilter(name='short')
version = filters.MultiValueFilter(name='version')
sigkey = filters.MultiValueFilter(name='sigkey__key_id')
allow_buildroot_push = filters.CaseInsensitiveBooleanFilter()
allowed_debuginfo_services = filters.MultiValueFilter(name='allowed_debuginfo_services__name')
allowed_push_targets = AllowedPushTargetsFilter(['product_version'])
class Meta:
model = Release
fields = ("release_id", "name", "short", "version", 'product_version',
"release_type", "base_product", 'active', 'integrated_with',
'sigkey', 'allow_buildroot_push', 'allowed_debuginfo_services',
'allowed_push_targets')
def find_has_base_product(self, queryset, name, value, *args, **kwargs):
"""
Make it possible to filter releases if base_product is null or not.
"""
if value == 'True':
return queryset.filter(base_product__isnull=False).distinct()
elif value == 'False':
return queryset.filter(base_product__isnull=True).distinct()
return queryset
class BaseProductFilter(django_filters.FilterSet):
short = filters.MultiValueFilter(name='short')
version = filters.MultiValueFilter(name='version')
name = filters.MultiValueFilter(name='name')
base_product_id = filters.MultiValueFilter(name='base_product_id')
class Meta:
model = BaseProduct
fields = ("base_product_id", "short", "version", 'name')
class ProductVersionFilter(django_filters.FilterSet):
active = ActiveReleasesFilter(name='release')
short = filters.MultiValueFilter(name='short')
version = filters.MultiValueFilter(name='version')
name = filters.MultiValueFilter(name='name')
product_version_id = filters.MultiValueFilter(name='product_version_id')
allowed_push_targets = AllowedPushTargetsFilter([])
class Meta:
model = ProductVersion
fields = ('name', 'product_version_id', 'version', 'short', 'active', 'allowed_push_targets')
class ProductFilter(django_filters.FilterSet):
active = ActiveReleasesFilter(name='productversion__release')
name = filters.MultiValueFilter(name='name')
short = filters.MultiValueFilter(name='short')
allowed_push_targets = filters.MultiValueFilter(name='allowed_push_targets__name')
class Meta:
model = Product
fields = ('name', 'short', 'active', 'allowed_push_targets')
class ReleaseTypeFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr="icontains")
short = filters.MultiValueFilter(name='short')
class Meta:
model = ReleaseType
fields = ('name', 'short')
class ReleaseVariantFilter(django_filters.FilterSet):
release = filters.MultiValueFilter(name='release__release_id')
id = filters.MultiValueFilter(name='variant_id')
uid = filters.MultiValueFilter(name='variant_uid')
name = filters.MultiValueFilter(name='variant_name')
type = filters.MultiValueFilter(name='variant_type__name')
variant_version = filters.MultiValueFilter(name='variant_version')
variant_release = filters.MultiValueFilter(name='variant_release')
allowed_push_targets = AllowedPushTargetsFilter(['release', 'product_version'])
class Meta:
model = Variant
fields = ('release', 'id', 'uid', 'name', 'type', 'allowed_push_targets')
class CPEFilter(django_filters.FilterSet):
cpe = filters.MultiValueFilter(name='cpe')
description = filters.MultiValueFilter(name='description')
class Meta:
model = CPE
fields = ('cpe', 'description')
class ReleaseVariantCPEFilter(django_filters.FilterSet):
release = filters.MultiValueFilter(name='variant__release__release_id')
variant_uid = filters.MultiValueFilter(name='variant__variant_uid')
cpe = filters.MultiValueFilter(name='cpe__cpe')
class Meta:
model = VariantCPE
fields = ('id', 'release', 'variant_uid', 'cpe')
class ReleaseGroupFilter(django_filters.FilterSet):
name = filters.MultiValueFilter(name='name')
description = filters.MultiValueFilter(name='description')
type = filters.MultiValueFilter(name='type__name')
releases = filters.MultiValueFilter(name='releases__release_id')
active = filters.CaseInsensitiveBooleanFilter()
class Meta:
model = ReleaseGroup
fields = ('name', 'description', 'type', 'releases', 'active')
|
dgeb/cardstack
|
packages/codegen/cardstack/middleware.js
|
<reponame>dgeb/cardstack
const { declareInjections } = require("@cardstack/di");
const route = require("koa-better-route");
const compose = require("koa-compose");
const { transform } = require("@babel/core");
module.exports = declareInjections(
{
// TODO: the code-generators service really belongs in this package,
// not the hub. But that depends on refactoring the relationship
// between hub and ember-cli, which I'm planning to do anyway as
// part of containerization.
service: `hub:code-generators`,
},
class CodeGenMiddleware {
constructor() {
this.before = "authentication";
}
middleware() {
return compose([this._scriptRoute(), this._modulesRoute()]);
}
_scriptRoute() {
return route.get("/codegen/:module_prefix", async ctxt => {
let { appModules, modules } = await this.service.generateCode();
let modulePrefix = ctxt.routeParams.module_prefix;
ctxt.body =
compileModules(appModules, modulePrefix) + compileModules(modules);
ctxt.response.set("Access-Control-Allow-Origin", "*");
ctxt.response.set("Content-Type", "application/javascript");
ctxt.status = 200;
});
}
_modulesRoute() {
return route.get("/codegen-modules", async ctxt => {
let { appModules, modules } = await this.service.generateCode();
ctxt.body = JSON.stringify({
modules: [...modules],
appModules: [...appModules],
});
ctxt.response.set("Access-Control-Allow-Origin", "*");
ctxt.response.set("Content-Type", "application/json");
ctxt.status = 200;
});
}
}
);
function compileModules(modules, packagePrefix = null) {
let results = [];
for (let [name, code] of modules) {
results.push(
transform(code, {
plugins: ["@babel/plugin-transform-modules-amd"],
moduleId: packagePrefix ? `${packagePrefix}/${name}` : name,
}).code
);
}
return results.join("\n");
}
|
jacqt/alasql
|
test/test160.js
|
if (typeof exports === 'object') {
var assert = require('assert');
var alasql = require('..');
} else {
__dirname = '.';
}
//if(typeof exports == 'object') {
if (false) {
var DOMStorage = require('dom-storage');
global.localStorage = new DOMStorage('./test159.json', {strict: false, ws: ''});
describe('Test 160 - load text file, csv, tab, and other functions', function() {
it('1. Text file', function(done) {
alasql(
"select column * from txt('test160.txt') where [0] like 'M%' order by [0]",
[],
function(res) {
assert(res, ['Madrid', 'Minsk', 'Mogadisho']);
done();
}
);
});
it('2. TAB file without headers', function(done) {
alasql(
"select column [1] from tab('test160.tab') where [0] like 'M%' order by [1]",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
it('3. TAB file with headers', function(done) {
alasql(
"select column population from tab('test160h.tab',{headers:true}) where city like 'M%' order by population",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
it('4. CSV file without headers', function(done) {
alasql(
"select column [1] from csv('test160.csv') where [0] like 'M%' order by [1]",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
it('5. CSV file with headers', function(done) {
alasql(
"select column population from csv('test160h.csv',{headers:true}) where city like 'M%' order by population",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
it('6. CSV file with headers with semicolon', function(done) {
alasql(
"select column population from csv('test160hs.csv',{headers:true, separator:';'}) where city like 'M%' order by population",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
it('4. CSV file without extension', function(done) {
alasql(
"select column [1] from csv('test160') where [0] like 'M%' order by [1]",
[],
function(res) {
assert(res, [10, 20, 30]);
done();
}
);
});
});
}
|
vollmerr/state-template
|
src/lib/components/Form/Form.test.js
|
import React from 'react';
import { shallow } from 'enzyme';
import { Form as fromLib } from '../..';
import defaultExport, { Form } from './Form';
const props = {
handleSubmit: jest.fn(),
onSubmit: jest.fn(),
children: <div>children...</div>,
};
let wrapper;
describe('Form', () => {
beforeEach(() => {
wrapper = shallow(<Form {...props} />);
});
it('should be exported as part of the library', () => {
expect(fromLib).toEqual(defaultExport);
});
it('should render correctly', () => {
expect(wrapper).toMatchSnapshot();
});
it('should call the `onSubmit` using redux-form`s `handleSubmit` when submitting', () => {
wrapper.find('form').simulate('submit');
expect(props.handleSubmit).toBeCalledWith(props.onSubmit);
});
});
|
peter-y/sample-spring-framework
|
spring-framework-basic/src/main/java/com/ycz/spring/framework/sample/aoptx/UnsupportOperationException.java
|
package com.ycz.spring.framework.sample.aoptx;
public class UnsupportOperationException extends RuntimeException {
}
|
sargassum-world/fluitans
|
pkg/godest/template-fingerprints.go
|
package godest
import (
"bytes"
_ "embed"
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
type fingerprints struct {
app string
page map[string]string
}
func (f fingerprints) getEtagSegments(templateName string) ([]string, error) {
if templateName == "" {
return []string{f.app}, nil
}
pageFingerprint, ok := f.page[templateName]
if !ok {
return []string{f.app}, errors.Errorf(
"couldn't find page fingerprint for template %s", templateName,
)
}
return []string{f.app, pageFingerprint}, nil
}
func (f fingerprints) mustHaveForPage(templateName string) {
if _, err := f.getEtagSegments(templateName); err != nil {
panic(errors.Wrapf(
err, "couldn't find template etag segments for page template %s", templateName,
))
}
}
func (f fingerprints) setAndCheckEtag(
w http.ResponseWriter, r *http.Request, templateName string, data interface{},
) (noContent bool, err error) {
// Look up data-independent etag segments
templateEtagSegments, err := f.getEtagSegments(templateName)
if err != nil {
return false, err
}
// Encode data
var buf bytes.Buffer
// github.com/vmihailenco/msgpack has better performance, but we use the JSON encoder because
// the msgpack encoder can only sort the map keys of map[string]string and map[string]interface{}
// maps, and it's too much trouble to convert our maps into map[string]interface{}. If we can
// work around this limitation, we should use msgpack though.
if err = json.NewEncoder(&buf).Encode(data); err != nil {
return false, err
}
encoded := buf.Bytes()
noContent = setAndCheckEtag(
w, r, append(templateEtagSegments, computeFingerprint(encoded))...,
)
if noContent {
w.WriteHeader(http.StatusNotModified)
}
return noContent, nil
}
|
Dream101/ftme
|
ftme/src/com/ftme/common/model/base/BaseRole.java
|
<gh_stars>0
package com.ftme.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseRole<M extends BaseRole<M>> extends Model<M> implements IBean {
public void setId(java.lang.Integer id) {
set("id", id);
}
public java.lang.Integer getId() {
return get("id");
}
public void setRoleNo(java.lang.String roleNo) {
set("roleNo", roleNo);
}
public java.lang.String getRoleNo() {
return get("roleNo");
}
public void setRoleType(java.lang.String roleType) {
set("roleType", roleType);
}
public java.lang.String getRoleType() {
return get("roleType");
}
public void setState(java.lang.String state) {
set("state", state);
}
public java.lang.String getState() {
return get("state");
}
}
|
Robbbert/messui
|
src/devices/machine/stvcd.h
|
// license:LGPL-2.1+
// copyright-holders:<NAME>, <NAME>
#ifndef MAME_MACHINE_STVCD_H
#define MAME_MACHINE_STVCD_H
#pragma once
#include "cdrom.h"
#include "imagedev/chd_cd.h"
#include "machine/timer.h"
#include "sound/cdda.h"
class stvcd_device : public device_t,
public device_mixer_interface,
public device_memory_interface
{
static constexpr unsigned MAX_FILTERS = 24;
static constexpr unsigned MAX_BLOCKS = 200;
static constexpr uint32_t MAX_DIR_SIZE = 256*1024;
public:
stvcd_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
uint32_t stvcd_r(offs_t offset, uint32_t mem_mask = ~0);
void stvcd_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
void set_tray_open();
void set_tray_close();
protected:
virtual void device_add_mconfig(machine_config &config) override;
virtual void device_start() override;
virtual void device_reset() override;
virtual void device_stop() override;
virtual space_config_vector memory_space_config() const override;
private:
const address_space_config m_space_config;
void io_regs(address_map &map);
TIMER_DEVICE_CALLBACK_MEMBER( stv_sector_cb );
TIMER_DEVICE_CALLBACK_MEMBER( stv_sh1_sim );
struct direntryT
{
uint8_t record_size;
uint8_t xa_record_size;
uint32_t firstfad; // first sector of file
uint32_t length; // length of file
uint8_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
uint8_t gmt_offset;
uint8_t flags; // iso9660 flags
uint8_t file_unit_size;
uint8_t interleave_gap_size;
uint16_t volume_sequencer_number;
uint8_t name[128];
};
struct filterT
{
uint8_t mode;
uint8_t chan;
uint8_t smmask;
uint8_t cimask;
uint8_t fid;
uint8_t smval;
uint8_t cival;
uint8_t condtrue;
uint8_t condfalse;
uint32_t fad;
uint32_t range;
};
struct blockT
{
int32_t size; // size of block
int32_t FAD; // FAD on disc
uint8_t data[CD_MAX_SECTOR_DATA];
uint8_t chan; // channel
uint8_t fnum; // file number
uint8_t subm; // subchannel mode
uint8_t cinf; // coding information
};
struct partitionT
{
int32_t size;
blockT *blocks[MAX_BLOCKS];
uint8_t bnum[MAX_BLOCKS];
uint8_t numblks;
};
// 16-bit transfer types
enum transT
{
XFERTYPE_INVALID,
XFERTYPE_TOC,
XFERTYPE_FILEINFO_1,
XFERTYPE_FILEINFO_254,
XFERTYPE_SUBQ,
XFERTYPE_SUBRW
};
// 32-bit transfer types
enum trans32T
{
XFERTYPE32_INVALID,
XFERTYPE32_GETSECTOR,
XFERTYPE32_GETDELETESECTOR,
XFERTYPE32_PUTSECTOR,
XFERTYPE32_MOVESECTOR
};
int get_track_index(uint32_t fad);
int sega_cdrom_get_adr_control(cdrom_file *file, int track);
void cr_standard_return(uint16_t cur_status);
void mpeg_standard_return(uint16_t cur_status);
void cd_free_block(blockT *blktofree);
void cd_defragblocks(partitionT *part);
void cd_getsectoroffsetnum(uint32_t bufnum, uint32_t *sectoffs, uint32_t *sectnum);
void cd_readTOC();
void cd_readblock(uint32_t fad, uint8_t *dat);
void cd_playdata();
void cd_exec_command( void );
// iso9660 utilities
void make_dir_current(uint32_t fad);
void read_new_dir(uint32_t fileno);
blockT *cd_alloc_block(uint8_t *blknum);
partitionT *cd_filterdata(filterT *flt, int trktype, uint8_t *p_ok);
partitionT *cd_read_filtered_sector(int32_t fad, uint8_t *p_ok);
cdrom_file *cdrom;// = (cdrom_file *)nullptr;
// local variables
partitionT partitions[MAX_FILTERS];
partitionT *transpart;
blockT blocks[MAX_BLOCKS];
blockT curblock;
uint8_t tocbuf[102*4];
uint8_t subqbuf[5*2];
uint8_t subrwbuf[12*2];
uint8_t finfbuf[256];
int32_t sectlenin, sectlenout;
uint8_t lastbuf, playtype;
transT xfertype;
trans32T xfertype32;
uint32_t xfercount, calcsize;
uint32_t xferoffs, xfersect, xfersectpos, xfersectnum, xferdnum;
filterT filters[MAX_FILTERS];
filterT *cddevice;
int cddevicenum;
uint16_t cr1, cr2, cr3, cr4;
uint16_t prev_cr1, prev_cr2, prev_cr3, prev_cr4;
uint8_t status_type;
uint16_t hirqmask, hirqreg;
uint16_t cd_stat;
uint32_t cd_curfad;// = 0;
uint32_t cd_fad_seek;
uint32_t fadstoplay;// = 0;
uint32_t in_buffer;// = 0; // amount of data in the buffer
int oddframe;// = 0;
int buffull, sectorstore, freeblocks;
int cur_track;
uint8_t cmd_pending;
uint8_t cd_speed;
uint8_t cdda_maxrepeat;
uint8_t cdda_repeat_count;
uint8_t tray_is_closed;
int get_timing_command( void );
direntryT curroot; // root entry of current filesystem
std::vector<direntryT> curdir; // current directory
int numfiles; // # of entries in current directory
int firstfile; // first non-directory file
required_device<cdrom_image_device> m_cdrom_image;
required_device<timer_device> m_sector_timer;
required_device<timer_device> m_sh1_timer;
required_device<cdda_device> m_cdda;
// CDC commands
// 0x00
void cmd_get_status();
void cmd_get_hw_info();
void cmd_get_toc();
void cmd_get_session_info();
void cmd_init_cdsystem();
void cmd_end_data_transfer();
// 0x10
void cmd_play_disc();
void cmd_seek_disc();
void cmd_ffwd_rew_disc();
// 0x20
void cmd_get_subcode_q_rw_channel();
// 0x30
void cmd_set_cddevice_connection();
void cmd_get_cddevice_connection();
void cmd_last_buffer_destination();
// 0x40
void cmd_set_filter_range();
void cmd_get_filter_range();
void cmd_set_filter_subheader_conditions();
void cmd_get_filter_subheader_conditions();
void cmd_set_filter_mode();
void cmd_get_filter_mode();
void cmd_set_filter_connection();
void cmd_reset_selector();
// 0x50
void cmd_get_buffer_size();
void cmd_get_buffer_partition_sector_number();
void cmd_calculate_actual_data_size();
void cmd_get_actual_data_size();
void cmd_get_sector_information();
// 0x60
void cmd_set_sector_length();
void cmd_get_sector_data();
void cmd_delete_sector_data();
void cmd_get_and_delete_sector_data();
void cmd_put_sector_data();
void cmd_move_sector_data();
void cmd_copy_sector_data();
void cmd_get_sector_data_copy_or_move_error();
// 0x70
void cmd_change_directory();
void cmd_read_directory();
void cmd_get_file_scope();
void cmd_get_target_file_info();
void cmd_read_file();
void cmd_abort_file();
// 0x90
void cmd_mpeg_get_status();
void cmd_mpeg_get_irq();
void cmd_mpeg_set_irq_mask();
void cmd_mpeg_init();
void cmd_mpeg_set_mode();
// 0xe0
void cmd_check_copy_protection();
void cmd_get_disc_region();
void cmd_get_mpeg_card_boot_rom();
// comms
uint32_t datatrns_r(offs_t offset, uint32_t mem_mask = ~0);
void datatrns_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
inline u32 dataxfer_long_r();
inline u16 dataxfer_word_r();
inline void dataxfer_long_w(u32 data);
uint16_t cr1_r();
uint16_t cr2_r();
uint16_t cr3_r();
uint16_t cr4_r();
void cr1_w(uint16_t data);
void cr2_w(uint16_t data);
void cr3_w(uint16_t data);
void cr4_w(uint16_t data);
uint16_t hirq_r();
void hirq_w(uint16_t data);
uint16_t hirqmask_r();
void hirqmask_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0);
};
// device type definition
DECLARE_DEVICE_TYPE(STVCD, stvcd_device)
#endif // MAME_MACHINE_STVCD_H
|
nomos/go-lokas
|
util/ringbuffer.go
|
package util
import (
"fmt"
"github.com/nomos/go-lokas/log"
"github.com/nomos/go-lokas/util/slice"
"sync"
)
type RingBuffer struct {
elements []interface{}
first int
last int
size int
capacity int
end int
mutex sync.RWMutex
}
func NewRingBuffer(capacity int) *RingBuffer {
ret := &RingBuffer{
elements: make([]interface{}, capacity, capacity),
first: 0,
last: 0,
size: 0,
capacity: capacity,
end: 0,
mutex: sync.RWMutex{},
}
return ret
}
func (this *RingBuffer) Capacity() int {
return this.capacity
}
func (this *RingBuffer) IsEmpty() bool {
return this.size == 0
}
func (this *RingBuffer) IsFull() bool {
return this.size == this.Capacity()
}
func (this *RingBuffer) Peek() interface{} {
this.mutex.RLock()
defer this.mutex.RUnlock()
if this.IsEmpty() {
log.Warn("isEmpty")
return nil
}
return this.elements[this.first]
}
func (this *RingBuffer) PeekN(count int) interface{} {
this.mutex.RLock()
defer this.mutex.RUnlock()
if count > this.size {
count = this.size
}
end := Ternary((this.first+count) > this.capacity, this.capacity, this.first+count).(int)
firstHalf := this.elements[this.first:end]
if end < this.capacity {
return firstHalf
}
secondHalf := this.elements[0 : count-len(firstHalf)]
return slice.SliceConcat(secondHalf)
}
func (this *RingBuffer) Deq() interface{} {
this.mutex.Lock()
defer this.mutex.Unlock()
element := this.Peek()
if element != nil {
this.size--
this.first = (this.first + 1) % this.capacity
return element
}
return nil
}
func (this *RingBuffer) DeqN(count int) interface{} {
this.mutex.Lock()
defer this.mutex.Unlock()
elements := this.PeekN(count)
count = len(elements.([]interface{}))
this.size-=count
this.first = (this.first+count)%this.capacity
return nil
}
func (this *RingBuffer) Enq(element interface{})int {
this.mutex.Lock()
defer this.mutex.Unlock()
this.end = (this.first+this.size)%this.capacity
full:=this.IsFull()
if full {
fmt.Println("RingBuffer is Full")
}
this.elements[this.end] = element
if full {
this.first = (this.first+1)%this.capacity
} else {
this.size++
}
return this.size
}
func (this RingBuffer) Size()int {
return this.size
}
|
philip-alldredge/AGREE
|
com.rockwellcollins.atc.agree/src-gen/com/rockwellcollins/atc/agree/agree/impl/WheneverImpliesStatementImpl.java
|
/**
*/
package com.rockwellcollins.atc.agree.agree.impl;
import com.rockwellcollins.atc.agree.agree.AgreePackage;
import com.rockwellcollins.atc.agree.agree.Expr;
import com.rockwellcollins.atc.agree.agree.WheneverImpliesStatement;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Whenever Implies Statement</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.WheneverImpliesStatementImpl#getLhs <em>Lhs</em>}</li>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.WheneverImpliesStatementImpl#getRhs <em>Rhs</em>}</li>
* </ul>
*
* @generated
*/
public class WheneverImpliesStatementImpl extends WheneverStatementImpl implements WheneverImpliesStatement
{
/**
* The cached value of the '{@link #getLhs() <em>Lhs</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLhs()
* @generated
* @ordered
*/
protected Expr lhs;
/**
* The cached value of the '{@link #getRhs() <em>Rhs</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRhs()
* @generated
* @ordered
*/
protected Expr rhs;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected WheneverImpliesStatementImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return AgreePackage.Literals.WHENEVER_IMPLIES_STATEMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Expr getLhs()
{
return lhs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetLhs(Expr newLhs, NotificationChain msgs)
{
Expr oldLhs = lhs;
lhs = newLhs;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS, oldLhs, newLhs);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setLhs(Expr newLhs)
{
if (newLhs != lhs)
{
NotificationChain msgs = null;
if (lhs != null)
msgs = ((InternalEObject)lhs).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS, null, msgs);
if (newLhs != null)
msgs = ((InternalEObject)newLhs).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS, null, msgs);
msgs = basicSetLhs(newLhs, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS, newLhs, newLhs));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Expr getRhs()
{
return rhs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetRhs(Expr newRhs, NotificationChain msgs)
{
Expr oldRhs = rhs;
rhs = newRhs;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS, oldRhs, newRhs);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setRhs(Expr newRhs)
{
if (newRhs != rhs)
{
NotificationChain msgs = null;
if (rhs != null)
msgs = ((InternalEObject)rhs).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS, null, msgs);
if (newRhs != null)
msgs = ((InternalEObject)newRhs).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS, null, msgs);
msgs = basicSetRhs(newRhs, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS, newRhs, newRhs));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS:
return basicSetLhs(null, msgs);
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS:
return basicSetRhs(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS:
return getLhs();
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS:
return getRhs();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS:
setLhs((Expr)newValue);
return;
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS:
setRhs((Expr)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS:
setLhs((Expr)null);
return;
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS:
setRhs((Expr)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__LHS:
return lhs != null;
case AgreePackage.WHENEVER_IMPLIES_STATEMENT__RHS:
return rhs != null;
}
return super.eIsSet(featureID);
}
} //WheneverImpliesStatementImpl
|
alexavila150/luciddb
|
farrago/src/net/sf/farrago/session/FarragoSessionModelExtension.java
|
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
*/
package net.sf.farrago.session;
import java.util.*;
import net.sf.farrago.ddl.*;
/**
* FarragoSessionModelExtension defines the SPI for plugging in custom behavior
* for model extensions. Although model extensions may be independent of session
* personalities, they still interact with them, which is why they are defined
* at this level.
*
* @author <NAME>
* @version $Id$
*/
public interface FarragoSessionModelExtension
{
//~ Methods ----------------------------------------------------------------
/**
* Defines the handlers to be used to validate and execute DDL actions for
* object types in this model extension. See {@link
* FarragoSessionDdlHandler} for an explanation of how to define the handler
* objects in this list. Optionally, may also define drop rules.
*
* @param ddlValidator validator which will invoke handlers
* @param handlerList receives handler objects in order in which they should
*/
public void defineDdlHandlers(
FarragoSessionDdlValidator ddlValidator,
List<DdlHandler> handlerList);
/**
* Defines resource bundles to be used for localizing model object names.
* Any resource having a name of the form "UmlXXX" will be interpreted as
* the localized name for UML class XXX.
*
* @param bundleList receives instances of ResourceBundle
*/
public void defineResourceBundles(List<ResourceBundle> bundleList);
/**
* Defines privileges allowed on various object types.
*
* @param map receives allowed privileges
*/
public void definePrivileges(
FarragoSessionPrivilegeMap map);
}
// End FarragoSessionModelExtension.java
|
itsraina/whs.js
|
tools/jestPreprocess.js
|
const babelConfig = require('../.babelrc').env.test;
module.exports = require('babel-jest').createTransformer(babelConfig);
|
gatordevin/BoofCV
|
main/boofcv-geo/src/test/java/boofcv/alg/geo/pose/TestPnPInfinitesimalPlanePoseEstimation.java
|
/*
* Copyright (c) 2020, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.geo.pose;
import boofcv.struct.geo.AssociatedPair;
import boofcv.testing.BoofStandardJUnit;
import georegression.geometry.ConvertRotation3D_F64;
import georegression.struct.EulerType;
import georegression.struct.point.Point3D_F64;
import georegression.struct.point.Vector3D_F64;
import georegression.struct.se.Se3_F64;
import georegression.transform.se.SePointOps_F64;
import org.ejml.UtilEjml;
import org.ejml.data.DMatrix2x2;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.row.MatrixFeatures_DDRM;
import org.ejml.dense.row.NormOps_DDRM;
import org.ejml.equation.Equation;
import org.ejml.ops.DConvertMatrixStruct;
import org.ejml.simple.SimpleMatrix;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <NAME>
*/
public class TestPnPInfinitesimalPlanePoseEstimation extends BoofStandardJUnit {
@Test
public void perfectObservations() {
Se3_F64 actual = new Se3_F64();
for (int i = 0; i < 100; i++) {
ConvertRotation3D_F64.eulerToMatrix(EulerType.XYZ,
0.2+rand.nextGaussian()*0.05,
0.1+rand.nextGaussian()*0.05,
0.05+rand.nextGaussian()*0.001,actual.R);
actual.T.setTo(rand.nextGaussian(),1+rand.nextGaussian(),20+rand.nextGaussian()*2);
List<AssociatedPair> observation = createRandomInputs(20,actual);
PnPInfinitesimalPlanePoseEstimation alg = new PnPInfinitesimalPlanePoseEstimation();
assertTrue(alg.process(observation));
assertTrue(alg.getError0()<alg.getError1());
double error0 = computeModelError(alg.getWorldToCamera0(),actual);
double error1 = computeModelError(alg.getWorldToCamera1(),actual);
assertTrue(error0<error1);
assertTrue(error0 < 0.006);
}
}
public double computeModelError( Se3_F64 found , Se3_F64 expected ) {
Se3_F64 d = found.concat(expected.invert(null),null);
// it should be identity
d.R.data[0] -= 1;
d.R.data[4] -= 1;
d.R.data[8] -= 1;
return NormOps_DDRM.normF(d.R)/9 + d.T.norm()/3;
}
@Test
public void estimateTranslation() {
Se3_F64 actual = new Se3_F64();
ConvertRotation3D_F64.eulerToMatrix(EulerType.XYZ,0.1,0.05,0,actual.R);
actual.T.setTo(0.1,0,3);
List<AssociatedPair> observation = createRandomInputs(20,actual);
PnPInfinitesimalPlanePoseEstimation alg = new PnPInfinitesimalPlanePoseEstimation();
Vector3D_F64 found = new Vector3D_F64();
alg.estimateTranslation(actual.R,observation,found);
assertTrue(actual.T.isIdentical(found,UtilEjml.TEST_F64));
}
private List<AssociatedPair> createRandomInputs( int N , Se3_F64 worldToCamera ) {
List<AssociatedPair> list = new ArrayList<>();
for (int i = 0; i < N; i++) {
Point3D_F64 world = new Point3D_F64();
world.x = rand.nextGaussian();
world.y = rand.nextGaussian();
world.z = 0;
Point3D_F64 camera = new Point3D_F64();
SePointOps_F64.transform(worldToCamera,world,camera);
AssociatedPair pair = new AssociatedPair();
pair.p1.setTo(world.x,world.y);
pair.p2.setTo(camera.x/camera.z,camera.y/camera.z);
list.add( pair );
}
return list;
}
@Test
public void constructR() {
Equation eq = new Equation();
eq.process("R_v=randn(3,3)");
eq.process("R22=[1 2;3 4]");
eq.process("c=[1.1;2.1]");
eq.process("a=3.1");
eq.process("b=[-0.4;0.2]");
eq.process("R1=R_v*[R22 c;b' a]");
eq.process("R2=R_v*[R22, -c;-b', a]");
DMatrixRMaj found = new DMatrixRMaj(3,3);
DMatrixRMaj R_v = eq.lookupDDRM("R_v");
DMatrix2x2 R22 = new DMatrix2x2();
DConvertMatrixStruct.convert(eq.lookupDDRM("R22"),R22);
Vector3D_F64 ca = new Vector3D_F64(1.1,2.1,3.1);
PnPInfinitesimalPlanePoseEstimation.constructR(found,R_v,R22,-0.4,0.2,ca,1,new DMatrixRMaj(3,3));
assertTrue(MatrixFeatures_DDRM.isIdentical(eq.lookupDDRM("R1"),found,UtilEjml.TEST_F64));
PnPInfinitesimalPlanePoseEstimation.constructR(found,R_v,R22,-0.4,0.2,ca,-1,new DMatrixRMaj(3,3));
assertTrue(MatrixFeatures_DDRM.isIdentical(eq.lookupDDRM("R2"),found,UtilEjml.TEST_F64));
}
@Test
public void compute_B() {
Equation eq = new Equation();
eq.process("v=[1.1,0.5]'");
eq.process("R_v=[1,2,3;4,5,6;7,8,9]'");
eq.process("B=[eye(2),-v]*R_v");
DMatrixRMaj v = eq.lookupDDRM("v");
DMatrixRMaj R_v = eq.lookupDDRM("R_v");
DMatrixRMaj expected = eq.lookupDDRM("B");
double v1 = v.get(0);
double v2 = v.get(1);
DMatrix2x2 B = new DMatrix2x2();
PnPInfinitesimalPlanePoseEstimation.compute_B(B,R_v,v1,v2);
assertEquals(expected.get(0,0),B.a11, UtilEjml.TEST_F64);
assertEquals(expected.get(0,1),B.a12, UtilEjml.TEST_F64);
assertEquals(expected.get(1,0),B.a21, UtilEjml.TEST_F64);
assertEquals(expected.get(1,1),B.a22, UtilEjml.TEST_F64);
}
@Test
public void largestSingularValue2x2() {
DMatrix2x2 M = new DMatrix2x2(1,-1.5,0.5,1.8);
SimpleMatrix A = new SimpleMatrix(new double[][]{{M.a11,M.a12},{M.a21,M.a22}});
double[] s = A.svd().getSingularValues();
PnPInfinitesimalPlanePoseEstimation alg = new PnPInfinitesimalPlanePoseEstimation();
double found = alg.largestSingularValue2x2(M);
assertEquals(s[0],found,UtilEjml.TEST_F64);
}
@Test
public void compute_Rv() {
Equation eq = new Equation();
eq.process("v=[1.1,0.5]'");
eq.process("t=normF(v)");
eq.process("s=normF([v',1]')");
eq.process("cosT=1.0/s");
eq.process("sinT=sqrt(1-1.0/s^2)");
eq.process("Kx=(1.0/t)*[[0 0;0 0] v;-v' 0]");
eq.process("R_v = eye(3) + sinT*Kx + (1.0-cosT)*Kx*Kx");
PnPInfinitesimalPlanePoseEstimation alg = new PnPInfinitesimalPlanePoseEstimation();
DMatrixRMaj V = eq.lookupDDRM("v");
alg.v1 = V.get(0);
alg.v2 = V.get(1);
alg.compute_Rv();
DMatrixRMaj expected_R_v = eq.lookupDDRM("R_v");
assertTrue(MatrixFeatures_DDRM.isEquals(expected_R_v,alg.R_v, UtilEjml.TEST_F64));
}
}
|
yuanliangding/qxcmp-framework
|
qxcmp-core/src/main/java/com/qxcmp/account/form/AccountResetPhoneForm.java
|
package com.qxcmp.account.form;
import com.qxcmp.account.AccountCode;
import com.qxcmp.core.validation.Phone;
import com.qxcmp.web.view.annotation.form.Form;
import com.qxcmp.web.view.annotation.form.PhoneCaptchaField;
import com.qxcmp.web.view.annotation.form.PhoneField;
import lombok.Data;
/**
* 手机账户密码找回平台统一表单
* <p>
* 用户在使用手机号找回密码的时候需要填写的信息
* <p>
* 找回流程如下: <ol> <li>用户填写手机号,并点击发送短信验证码按钮</li> <li>验证手机号是否已经注册</li> <li>发送短信验证码到指定手机号</li> <li>用户输入短信验证码</li>
* <li>如果验证码正确则生成一个密码重置链接并跳转到该链接{@link AccountCode}</li> </ol>
*
* @author aaric
*/
@Form(submitText = "立即重置")
@Data
public class AccountResetPhoneForm {
@Phone
@PhoneField(value = "手机号码", placeholder = "请输入您账户绑定的手机号码")
private String phone;
@PhoneCaptchaField(value = "短信验证码", placeholder = "请输入你收到的短信验证码", phoneField = "phone")
private String captcha;
}
|
guileschool/BEAGLEBONE-tutorials
|
BBB-firmware/u-boot-v2015.10-rc2/arch/arm/mach-exynos/pinmux.c
|
<gh_stars>1-10
/*
* Copyright (c) 2012 Samsung Electronics.
* <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <fdtdec.h>
#include <asm/gpio.h>
#include <asm/arch/pinmux.h>
#include <asm/arch/sromc.h>
static void exynos5_uart_config(int peripheral)
{
int i, start, count;
switch (peripheral) {
case PERIPH_ID_UART0:
start = EXYNOS5_GPIO_A00;
count = 4;
break;
case PERIPH_ID_UART1:
start = EXYNOS5_GPIO_D00;
count = 4;
break;
case PERIPH_ID_UART2:
start = EXYNOS5_GPIO_A10;
count = 4;
break;
case PERIPH_ID_UART3:
start = EXYNOS5_GPIO_A14;
count = 2;
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return;
}
for (i = start; i < start + count; i++) {
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
}
}
static void exynos5420_uart_config(int peripheral)
{
int i, start, count;
switch (peripheral) {
case PERIPH_ID_UART0:
start = EXYNOS5420_GPIO_A00;
count = 4;
break;
case PERIPH_ID_UART1:
start = EXYNOS5420_GPIO_A04;
count = 4;
break;
case PERIPH_ID_UART2:
start = EXYNOS5420_GPIO_A10;
count = 4;
break;
case PERIPH_ID_UART3:
start = EXYNOS5420_GPIO_A14;
count = 2;
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return;
}
for (i = start; i < start + count; i++) {
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
}
}
static int exynos5_mmc_config(int peripheral, int flags)
{
int i, start, start_ext, gpio_func = 0;
switch (peripheral) {
case PERIPH_ID_SDMMC0:
start = EXYNOS5_GPIO_C00;
start_ext = EXYNOS5_GPIO_C10;
gpio_func = S5P_GPIO_FUNC(0x2);
break;
case PERIPH_ID_SDMMC1:
start = EXYNOS5_GPIO_C20;
start_ext = 0;
break;
case PERIPH_ID_SDMMC2:
start = EXYNOS5_GPIO_C30;
start_ext = EXYNOS5_GPIO_C43;
gpio_func = S5P_GPIO_FUNC(0x3);
break;
case PERIPH_ID_SDMMC3:
start = EXYNOS5_GPIO_C40;
start_ext = 0;
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
if ((flags & PINMUX_FLAG_8BIT_MODE) && !start_ext) {
debug("SDMMC device %d does not support 8bit mode",
peripheral);
return -1;
}
if (flags & PINMUX_FLAG_8BIT_MODE) {
for (i = start_ext; i <= (start_ext + 3); i++) {
gpio_cfg_pin(i, gpio_func);
gpio_set_pull(i, S5P_GPIO_PULL_UP);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
}
for (i = start; i < (start + 2); i++) {
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
for (i = (start + 3); i <= (start + 6); i++) {
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
gpio_set_pull(i, S5P_GPIO_PULL_UP);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
return 0;
}
static int exynos5420_mmc_config(int peripheral, int flags)
{
int i, start = 0, start_ext = 0;
switch (peripheral) {
case PERIPH_ID_SDMMC0:
start = EXYNOS5420_GPIO_C00;
start_ext = EXYNOS5420_GPIO_C30;
break;
case PERIPH_ID_SDMMC1:
start = EXYNOS5420_GPIO_C10;
start_ext = EXYNOS5420_GPIO_D14;
break;
case PERIPH_ID_SDMMC2:
start = EXYNOS5420_GPIO_C20;
start_ext = 0;
break;
default:
start = 0;
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
if ((flags & PINMUX_FLAG_8BIT_MODE) && !start_ext) {
debug("SDMMC device %d does not support 8bit mode",
peripheral);
return -1;
}
if (flags & PINMUX_FLAG_8BIT_MODE) {
for (i = start_ext; i <= (start_ext + 3); i++) {
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
gpio_set_pull(i, S5P_GPIO_PULL_UP);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
}
for (i = start; i < (start + 3); i++) {
/*
* MMC0 is intended to be used for eMMC. The
* card detect pin is used as a VDDEN signal to
* power on the eMMC. The 5420 iROM makes
* this same assumption.
*/
if ((peripheral == PERIPH_ID_SDMMC0) && (i == (start + 2))) {
#ifndef CONFIG_SPL_BUILD
gpio_request(i, "sdmmc0_vdden");
#endif
gpio_set_value(i, 1);
gpio_cfg_pin(i, S5P_GPIO_OUTPUT);
} else {
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
}
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
for (i = (start + 3); i <= (start + 6); i++) {
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
gpio_set_pull(i, S5P_GPIO_PULL_UP);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
return 0;
}
static void exynos5_sromc_config(int flags)
{
int i;
/*
* SROM:CS1 and EBI
*
* GPY0[0] SROM_CSn[0]
* GPY0[1] SROM_CSn[1](2)
* GPY0[2] SROM_CSn[2]
* GPY0[3] SROM_CSn[3]
* GPY0[4] EBI_OEn(2)
* GPY0[5] EBI_EEn(2)
*
* GPY1[0] EBI_BEn[0](2)
* GPY1[1] EBI_BEn[1](2)
* GPY1[2] SROM_WAIT(2)
* GPY1[3] EBI_DATA_RDn(2)
*/
gpio_cfg_pin(EXYNOS5_GPIO_Y00 + (flags & PINMUX_FLAG_BANK),
S5P_GPIO_FUNC(2));
gpio_cfg_pin(EXYNOS5_GPIO_Y04, S5P_GPIO_FUNC(2));
gpio_cfg_pin(EXYNOS5_GPIO_Y05, S5P_GPIO_FUNC(2));
for (i = 0; i < 4; i++)
gpio_cfg_pin(EXYNOS5_GPIO_Y10 + i, S5P_GPIO_FUNC(2));
/*
* EBI: 8 Addrss Lines
*
* GPY3[0] EBI_ADDR[0](2)
* GPY3[1] EBI_ADDR[1](2)
* GPY3[2] EBI_ADDR[2](2)
* GPY3[3] EBI_ADDR[3](2)
* GPY3[4] EBI_ADDR[4](2)
* GPY3[5] EBI_ADDR[5](2)
* GPY3[6] EBI_ADDR[6](2)
* GPY3[7] EBI_ADDR[7](2)
*
* EBI: 16 Data Lines
*
* GPY5[0] EBI_DATA[0](2)
* GPY5[1] EBI_DATA[1](2)
* GPY5[2] EBI_DATA[2](2)
* GPY5[3] EBI_DATA[3](2)
* GPY5[4] EBI_DATA[4](2)
* GPY5[5] EBI_DATA[5](2)
* GPY5[6] EBI_DATA[6](2)
* GPY5[7] EBI_DATA[7](2)
*
* GPY6[0] EBI_DATA[8](2)
* GPY6[1] EBI_DATA[9](2)
* GPY6[2] EBI_DATA[10](2)
* GPY6[3] EBI_DATA[11](2)
* GPY6[4] EBI_DATA[12](2)
* GPY6[5] EBI_DATA[13](2)
* GPY6[6] EBI_DATA[14](2)
* GPY6[7] EBI_DATA[15](2)
*/
for (i = 0; i < 8; i++) {
gpio_cfg_pin(EXYNOS5_GPIO_Y30 + i, S5P_GPIO_FUNC(2));
gpio_set_pull(EXYNOS5_GPIO_Y30 + i, S5P_GPIO_PULL_UP);
gpio_cfg_pin(EXYNOS5_GPIO_Y50 + i, S5P_GPIO_FUNC(2));
gpio_set_pull(EXYNOS5_GPIO_Y50 + i, S5P_GPIO_PULL_UP);
gpio_cfg_pin(EXYNOS5_GPIO_Y60 + i, S5P_GPIO_FUNC(2));
gpio_set_pull(EXYNOS5_GPIO_Y60 + i, S5P_GPIO_PULL_UP);
}
}
static void exynos5_i2c_config(int peripheral, int flags)
{
int func01, func23;
/* High-Speed I2C */
if (flags & PINMUX_FLAG_HS_MODE) {
func01 = 4;
func23 = 4;
} else {
func01 = 2;
func23 = 3;
}
switch (peripheral) {
case PERIPH_ID_I2C0:
gpio_cfg_pin(EXYNOS5_GPIO_B30, S5P_GPIO_FUNC(func01));
gpio_cfg_pin(EXYNOS5_GPIO_B31, S5P_GPIO_FUNC(func01));
break;
case PERIPH_ID_I2C1:
gpio_cfg_pin(EXYNOS5_GPIO_B32, S5P_GPIO_FUNC(func01));
gpio_cfg_pin(EXYNOS5_GPIO_B33, S5P_GPIO_FUNC(func01));
break;
case PERIPH_ID_I2C2:
gpio_cfg_pin(EXYNOS5_GPIO_A06, S5P_GPIO_FUNC(func23));
gpio_cfg_pin(EXYNOS5_GPIO_A07, S5P_GPIO_FUNC(func23));
break;
case PERIPH_ID_I2C3:
gpio_cfg_pin(EXYNOS5_GPIO_A12, S5P_GPIO_FUNC(func23));
gpio_cfg_pin(EXYNOS5_GPIO_A13, S5P_GPIO_FUNC(func23));
break;
case PERIPH_ID_I2C4:
gpio_cfg_pin(EXYNOS5_GPIO_A20, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5_GPIO_A21, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C5:
gpio_cfg_pin(EXYNOS5_GPIO_A22, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5_GPIO_A23, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C6:
gpio_cfg_pin(EXYNOS5_GPIO_B13, S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS5_GPIO_B14, S5P_GPIO_FUNC(0x4));
break;
case PERIPH_ID_I2C7:
gpio_cfg_pin(EXYNOS5_GPIO_B22, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5_GPIO_B23, S5P_GPIO_FUNC(0x3));
break;
}
}
static void exynos5420_i2c_config(int peripheral)
{
switch (peripheral) {
case PERIPH_ID_I2C0:
gpio_cfg_pin(EXYNOS5420_GPIO_B30, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS5420_GPIO_B31, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C1:
gpio_cfg_pin(EXYNOS5420_GPIO_B32, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS5420_GPIO_B33, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C2:
gpio_cfg_pin(EXYNOS5420_GPIO_A06, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5420_GPIO_A07, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C3:
gpio_cfg_pin(EXYNOS5420_GPIO_A12, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5420_GPIO_A13, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C4:
gpio_cfg_pin(EXYNOS5420_GPIO_A20, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5420_GPIO_A21, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C5:
gpio_cfg_pin(EXYNOS5420_GPIO_A22, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5420_GPIO_A23, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C6:
gpio_cfg_pin(EXYNOS5420_GPIO_B13, S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS5420_GPIO_B14, S5P_GPIO_FUNC(0x4));
break;
case PERIPH_ID_I2C7:
gpio_cfg_pin(EXYNOS5420_GPIO_B22, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS5420_GPIO_B23, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C8:
gpio_cfg_pin(EXYNOS5420_GPIO_B34, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS5420_GPIO_B35, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C9:
gpio_cfg_pin(EXYNOS5420_GPIO_B36, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS5420_GPIO_B37, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C10:
gpio_cfg_pin(EXYNOS5420_GPIO_B40, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS5420_GPIO_B41, S5P_GPIO_FUNC(0x2));
break;
}
}
static void exynos5_i2s_config(int peripheral)
{
int i;
switch (peripheral) {
case PERIPH_ID_I2S0:
for (i = 0; i < 5; i++)
gpio_cfg_pin(EXYNOS5_GPIO_Z0 + i, S5P_GPIO_FUNC(0x02));
break;
case PERIPH_ID_I2S1:
for (i = 0; i < 5; i++)
gpio_cfg_pin(EXYNOS5_GPIO_B00 + i, S5P_GPIO_FUNC(0x02));
break;
}
}
void exynos5_spi_config(int peripheral)
{
int cfg = 0, pin = 0, i;
switch (peripheral) {
case PERIPH_ID_SPI0:
cfg = S5P_GPIO_FUNC(0x2);
pin = EXYNOS5_GPIO_A20;
break;
case PERIPH_ID_SPI1:
cfg = S5P_GPIO_FUNC(0x2);
pin = EXYNOS5_GPIO_A24;
break;
case PERIPH_ID_SPI2:
cfg = S5P_GPIO_FUNC(0x5);
pin = EXYNOS5_GPIO_B11;
break;
case PERIPH_ID_SPI3:
cfg = S5P_GPIO_FUNC(0x2);
pin = EXYNOS5_GPIO_F10;
break;
case PERIPH_ID_SPI4:
for (i = 0; i < 2; i++) {
gpio_cfg_pin(EXYNOS5_GPIO_F02 + i, S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS5_GPIO_E04 + i, S5P_GPIO_FUNC(0x4));
}
break;
}
if (peripheral != PERIPH_ID_SPI4) {
for (i = pin; i < pin + 4; i++)
gpio_cfg_pin(i, cfg);
}
}
void exynos5420_spi_config(int peripheral)
{
int cfg, pin, i;
switch (peripheral) {
case PERIPH_ID_SPI0:
pin = EXYNOS5420_GPIO_A20;
cfg = S5P_GPIO_FUNC(0x2);
break;
case PERIPH_ID_SPI1:
pin = EXYNOS5420_GPIO_A24;
cfg = S5P_GPIO_FUNC(0x2);
break;
case PERIPH_ID_SPI2:
pin = EXYNOS5420_GPIO_B11;
cfg = S5P_GPIO_FUNC(0x5);
break;
case PERIPH_ID_SPI3:
pin = EXYNOS5420_GPIO_F10;
cfg = S5P_GPIO_FUNC(0x2);
break;
case PERIPH_ID_SPI4:
cfg = 0;
pin = 0;
break;
default:
cfg = 0;
pin = 0;
debug("%s: invalid peripheral %d", __func__, peripheral);
return;
}
if (peripheral != PERIPH_ID_SPI4) {
for (i = pin; i < pin + 4; i++)
gpio_cfg_pin(i, cfg);
} else {
for (i = 0; i < 2; i++) {
gpio_cfg_pin(EXYNOS5420_GPIO_F02 + i,
S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS5420_GPIO_E04 + i,
S5P_GPIO_FUNC(0x4));
}
}
}
static int exynos5_pinmux_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_UART0:
case PERIPH_ID_UART1:
case PERIPH_ID_UART2:
case PERIPH_ID_UART3:
exynos5_uart_config(peripheral);
break;
case PERIPH_ID_SDMMC0:
case PERIPH_ID_SDMMC1:
case PERIPH_ID_SDMMC2:
case PERIPH_ID_SDMMC3:
return exynos5_mmc_config(peripheral, flags);
case PERIPH_ID_SROMC:
exynos5_sromc_config(flags);
break;
case PERIPH_ID_I2C0:
case PERIPH_ID_I2C1:
case PERIPH_ID_I2C2:
case PERIPH_ID_I2C3:
case PERIPH_ID_I2C4:
case PERIPH_ID_I2C5:
case PERIPH_ID_I2C6:
case PERIPH_ID_I2C7:
exynos5_i2c_config(peripheral, flags);
break;
case PERIPH_ID_I2S0:
case PERIPH_ID_I2S1:
exynos5_i2s_config(peripheral);
break;
case PERIPH_ID_SPI0:
case PERIPH_ID_SPI1:
case PERIPH_ID_SPI2:
case PERIPH_ID_SPI3:
case PERIPH_ID_SPI4:
exynos5_spi_config(peripheral);
break;
case PERIPH_ID_DPHPD:
/* Set Hotplug detect for DP */
gpio_cfg_pin(EXYNOS5_GPIO_X07, S5P_GPIO_FUNC(0x3));
/*
* Hotplug detect should have an external pullup; disable the
* internal pulldown so they don't fight.
*/
gpio_set_pull(EXYNOS5_GPIO_X07, S5P_GPIO_PULL_NONE);
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
return 0;
}
static int exynos5420_pinmux_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_UART0:
case PERIPH_ID_UART1:
case PERIPH_ID_UART2:
case PERIPH_ID_UART3:
exynos5420_uart_config(peripheral);
break;
case PERIPH_ID_SDMMC0:
case PERIPH_ID_SDMMC1:
case PERIPH_ID_SDMMC2:
case PERIPH_ID_SDMMC3:
return exynos5420_mmc_config(peripheral, flags);
case PERIPH_ID_SPI0:
case PERIPH_ID_SPI1:
case PERIPH_ID_SPI2:
case PERIPH_ID_SPI3:
case PERIPH_ID_SPI4:
exynos5420_spi_config(peripheral);
break;
case PERIPH_ID_I2C0:
case PERIPH_ID_I2C1:
case PERIPH_ID_I2C2:
case PERIPH_ID_I2C3:
case PERIPH_ID_I2C4:
case PERIPH_ID_I2C5:
case PERIPH_ID_I2C6:
case PERIPH_ID_I2C7:
case PERIPH_ID_I2C8:
case PERIPH_ID_I2C9:
case PERIPH_ID_I2C10:
exynos5420_i2c_config(peripheral);
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
return 0;
}
static void exynos4_i2c_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_I2C0:
gpio_cfg_pin(EXYNOS4_GPIO_D10, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS4_GPIO_D11, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C1:
gpio_cfg_pin(EXYNOS4_GPIO_D12, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS4_GPIO_D13, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C2:
gpio_cfg_pin(EXYNOS4_GPIO_A06, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4_GPIO_A07, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C3:
gpio_cfg_pin(EXYNOS4_GPIO_A12, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4_GPIO_A13, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C4:
gpio_cfg_pin(EXYNOS4_GPIO_B2, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4_GPIO_B3, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C5:
gpio_cfg_pin(EXYNOS4_GPIO_B6, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4_GPIO_B7, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C6:
gpio_cfg_pin(EXYNOS4_GPIO_C13, S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS4_GPIO_C14, S5P_GPIO_FUNC(0x4));
break;
case PERIPH_ID_I2C7:
gpio_cfg_pin(EXYNOS4_GPIO_D02, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4_GPIO_D03, S5P_GPIO_FUNC(0x3));
break;
}
}
static int exynos4_mmc_config(int peripheral, int flags)
{
int i, start = 0, start_ext = 0;
unsigned int func, ext_func;
switch (peripheral) {
case PERIPH_ID_SDMMC0:
start = EXYNOS4_GPIO_K00;
start_ext = EXYNOS4_GPIO_K13;
func = S5P_GPIO_FUNC(0x2);
ext_func = S5P_GPIO_FUNC(0x3);
break;
case PERIPH_ID_SDMMC2:
start = EXYNOS4_GPIO_K20;
start_ext = EXYNOS4_GPIO_K33;
func = S5P_GPIO_FUNC(0x2);
ext_func = S5P_GPIO_FUNC(0x3);
break;
case PERIPH_ID_SDMMC4:
start = EXYNOS4_GPIO_K00;
start_ext = EXYNOS4_GPIO_K13;
func = S5P_GPIO_FUNC(0x3);
ext_func = S5P_GPIO_FUNC(0x4);
break;
default:
return -1;
}
for (i = start; i < (start + 7); i++) {
if (i == (start + 2))
continue;
gpio_cfg_pin(i, func);
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
/* SDMMC2 do not use 8bit mode at exynos4 */
if (flags & PINMUX_FLAG_8BIT_MODE) {
for (i = start_ext; i < (start_ext + 4); i++) {
gpio_cfg_pin(i, ext_func);
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
}
return 0;
}
static void exynos4_uart_config(int peripheral)
{
int i, start, count;
switch (peripheral) {
case PERIPH_ID_UART0:
start = EXYNOS4_GPIO_A00;
count = 4;
break;
case PERIPH_ID_UART1:
start = EXYNOS4_GPIO_A04;
count = 4;
break;
case PERIPH_ID_UART2:
start = EXYNOS4_GPIO_A10;
count = 4;
break;
case PERIPH_ID_UART3:
start = EXYNOS4_GPIO_A14;
count = 2;
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return;
}
for (i = start; i < (start + count); i++) {
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
}
}
static void exynos4x12_i2c_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_I2C0:
gpio_cfg_pin(EXYNOS4X12_GPIO_D10, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS4X12_GPIO_D11, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C1:
gpio_cfg_pin(EXYNOS4X12_GPIO_D12, S5P_GPIO_FUNC(0x2));
gpio_cfg_pin(EXYNOS4X12_GPIO_D13, S5P_GPIO_FUNC(0x2));
break;
case PERIPH_ID_I2C2:
gpio_cfg_pin(EXYNOS4X12_GPIO_A06, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4X12_GPIO_A07, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C3:
gpio_cfg_pin(EXYNOS4X12_GPIO_A12, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4X12_GPIO_A13, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C4:
gpio_cfg_pin(EXYNOS4X12_GPIO_B2, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4X12_GPIO_B3, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C5:
gpio_cfg_pin(EXYNOS4X12_GPIO_B6, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4X12_GPIO_B7, S5P_GPIO_FUNC(0x3));
break;
case PERIPH_ID_I2C6:
gpio_cfg_pin(EXYNOS4X12_GPIO_C13, S5P_GPIO_FUNC(0x4));
gpio_cfg_pin(EXYNOS4X12_GPIO_C14, S5P_GPIO_FUNC(0x4));
break;
case PERIPH_ID_I2C7:
gpio_cfg_pin(EXYNOS4X12_GPIO_D02, S5P_GPIO_FUNC(0x3));
gpio_cfg_pin(EXYNOS4X12_GPIO_D03, S5P_GPIO_FUNC(0x3));
break;
}
}
static int exynos4x12_mmc_config(int peripheral, int flags)
{
int i, start = 0, start_ext = 0;
unsigned int func, ext_func;
switch (peripheral) {
case PERIPH_ID_SDMMC0:
start = EXYNOS4X12_GPIO_K00;
start_ext = EXYNOS4X12_GPIO_K13;
func = S5P_GPIO_FUNC(0x2);
ext_func = S5P_GPIO_FUNC(0x3);
break;
case PERIPH_ID_SDMMC2:
start = EXYNOS4X12_GPIO_K20;
start_ext = EXYNOS4X12_GPIO_K33;
func = S5P_GPIO_FUNC(0x2);
ext_func = S5P_GPIO_FUNC(0x3);
break;
case PERIPH_ID_SDMMC4:
start = EXYNOS4X12_GPIO_K00;
start_ext = EXYNOS4X12_GPIO_K13;
func = S5P_GPIO_FUNC(0x3);
ext_func = S5P_GPIO_FUNC(0x4);
break;
default:
return -1;
}
for (i = start; i < (start + 7); i++) {
if (i == (start + 2))
continue;
gpio_cfg_pin(i, func);
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
if (flags & PINMUX_FLAG_8BIT_MODE) {
for (i = start_ext; i < (start_ext + 4); i++) {
gpio_cfg_pin(i, ext_func);
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_set_drv(i, S5P_GPIO_DRV_4X);
}
}
return 0;
}
static void exynos4x12_uart_config(int peripheral)
{
int i, start, count;
switch (peripheral) {
case PERIPH_ID_UART0:
start = EXYNOS4X12_GPIO_A00;
count = 4;
break;
case PERIPH_ID_UART1:
start = EXYNOS4X12_GPIO_A04;
count = 4;
break;
case PERIPH_ID_UART2:
start = EXYNOS4X12_GPIO_A10;
count = 4;
break;
case PERIPH_ID_UART3:
start = EXYNOS4X12_GPIO_A14;
count = 2;
break;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return;
}
for (i = start; i < (start + count); i++) {
gpio_set_pull(i, S5P_GPIO_PULL_NONE);
gpio_cfg_pin(i, S5P_GPIO_FUNC(0x2));
}
}
static int exynos4_pinmux_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_UART0:
case PERIPH_ID_UART1:
case PERIPH_ID_UART2:
case PERIPH_ID_UART3:
exynos4_uart_config(peripheral);
break;
case PERIPH_ID_I2C0:
case PERIPH_ID_I2C1:
case PERIPH_ID_I2C2:
case PERIPH_ID_I2C3:
case PERIPH_ID_I2C4:
case PERIPH_ID_I2C5:
case PERIPH_ID_I2C6:
case PERIPH_ID_I2C7:
exynos4_i2c_config(peripheral, flags);
break;
case PERIPH_ID_SDMMC0:
case PERIPH_ID_SDMMC2:
case PERIPH_ID_SDMMC4:
return exynos4_mmc_config(peripheral, flags);
case PERIPH_ID_SDMMC1:
case PERIPH_ID_SDMMC3:
debug("SDMMC device %d not implemented\n", peripheral);
return -1;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
return 0;
}
static int exynos4x12_pinmux_config(int peripheral, int flags)
{
switch (peripheral) {
case PERIPH_ID_UART0:
case PERIPH_ID_UART1:
case PERIPH_ID_UART2:
case PERIPH_ID_UART3:
exynos4x12_uart_config(peripheral);
break;
case PERIPH_ID_I2C0:
case PERIPH_ID_I2C1:
case PERIPH_ID_I2C2:
case PERIPH_ID_I2C3:
case PERIPH_ID_I2C4:
case PERIPH_ID_I2C5:
case PERIPH_ID_I2C6:
case PERIPH_ID_I2C7:
exynos4x12_i2c_config(peripheral, flags);
break;
case PERIPH_ID_SDMMC0:
case PERIPH_ID_SDMMC2:
case PERIPH_ID_SDMMC4:
return exynos4x12_mmc_config(peripheral, flags);
case PERIPH_ID_SDMMC1:
case PERIPH_ID_SDMMC3:
debug("SDMMC device %d not implemented\n", peripheral);
return -1;
default:
debug("%s: invalid peripheral %d", __func__, peripheral);
return -1;
}
return 0;
}
int exynos_pinmux_config(int peripheral, int flags)
{
if (cpu_is_exynos5()) {
if (proid_is_exynos5420() || proid_is_exynos5800())
return exynos5420_pinmux_config(peripheral, flags);
else if (proid_is_exynos5250())
return exynos5_pinmux_config(peripheral, flags);
} else if (cpu_is_exynos4()) {
if (proid_is_exynos4412())
return exynos4x12_pinmux_config(peripheral, flags);
else
return exynos4_pinmux_config(peripheral, flags);
}
debug("pinmux functionality not supported\n");
return -1;
}
#if CONFIG_IS_ENABLED(OF_CONTROL)
static int exynos4_pinmux_decode_periph_id(const void *blob, int node)
{
int err;
u32 cell[3];
err = fdtdec_get_int_array(blob, node, "interrupts", cell,
ARRAY_SIZE(cell));
if (err) {
debug(" invalid peripheral id\n");
return PERIPH_ID_NONE;
}
return cell[1];
}
static int exynos5_pinmux_decode_periph_id(const void *blob, int node)
{
int err;
u32 cell[3];
err = fdtdec_get_int_array(blob, node, "interrupts", cell,
ARRAY_SIZE(cell));
if (err)
return PERIPH_ID_NONE;
return cell[1];
}
int pinmux_decode_periph_id(const void *blob, int node)
{
if (cpu_is_exynos5())
return exynos5_pinmux_decode_periph_id(blob, node);
else if (cpu_is_exynos4())
return exynos4_pinmux_decode_periph_id(blob, node);
return PERIPH_ID_NONE;
}
#endif
|
shaoweijin/ralasafe-ggd543
|
orm/org/ralasafe/db/sql/QueryFactory.java
|
<reponame>shaoweijin/ralasafe-ggd543
/**
* Copyright (c) 2004-2011 <NAME>(<NAME>), http://www.ralasafe.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
package org.ralasafe.db.sql;
import org.ralasafe.RalasafeException;
import org.ralasafe.db.*;
import org.ralasafe.db.sql.xml.Operand1;
import org.ralasafe.db.sql.xml.Operand2;
import org.ralasafe.db.sql.xml.types.SimpleOperatorType;
import org.ralasafe.util.StringUtil;
import java.util.ArrayList;
import java.util.Collection;
public class QueryFactory {
public static Query getQuery(org.ralasafe.db.sql.xml.QueryType xmlQuery) {
ArrayList values = new ArrayList();
Query query = getQuery(xmlQuery, values);
query.setValues(values);
return query;
}
private static Query getQuery(org.ralasafe.db.sql.xml.QueryType xmlQuery,
ArrayList values) {
String type = xmlQuery.getType().toString();
Query query = new Query();
query.setName(xmlQuery.getName());
String ds = xmlQuery.getDs();
if (ds == null || ds.equals("") || DBPower.getDataSource(ds) == null) {
ds = DBPower.getDefaultAppDsName();
}
query.setDs(ds);
query.setType(type);
query.setIsRawSQL(xmlQuery.isIsRawSQL());
if (xmlQuery.getRawSQL() != null) {
query.setRawSQL(getRawSQL(xmlQuery.getRawSQL(), values, type
.equals(Query.SQL_TYPE)
&& xmlQuery.isIsRawSQL()));
} else {
query.setRawSQL(new RawSQL());
}
if (xmlQuery.getStoredProcedure() != null) {
query.setStoredProcedure(getStoredProcedure(xmlQuery
.getStoredProcedure(), values, type
.equals(Query.STORED_PROCEDURE_TYPE)));
} else {
query.setStoredProcedure(new StoredProcedure());
}
query.setSelect(getSelect(xmlQuery.getQueryTypeSequence().getSelect()));
query.setFrom(getFrom(xmlQuery.getQueryTypeSequence().getFrom()));
if (xmlQuery.getQueryTypeSequence().getWhere() != null
&&!xmlQuery.isIsRawSQL()
&&!xmlQuery.isIsStoredProcedure()) {
query.setWhere(getWhere(xmlQuery.getQueryTypeSequence().getWhere(),
values, type.equals(Query.SQL_TYPE)
&& !xmlQuery.isIsRawSQL()));
}
if (xmlQuery.getQueryTypeSequence().getGroupBy() != null) {
query.setGroupBy(getGroupBy(xmlQuery.getQueryTypeSequence()
.getGroupBy()));
}
if (xmlQuery.getQueryTypeSequence().getOrderBy() != null) {
query.setOrderBy(getOrderBy(xmlQuery.getQueryTypeSequence()
.getOrderBy()));
}
return query;
}
private static RawSQL getRawSQL(org.ralasafe.db.sql.xml.RawSQL xmlRawSQL,
ArrayList values, boolean addParam2Values) {
RawSQL rawSQL = new RawSQL();
rawSQL.setContent(xmlRawSQL.getContent());
rawSQL.setParameters(getParameters(xmlRawSQL.getParameter(), values,
addParam2Values));
if (xmlRawSQL.getSelect() != null) {
rawSQL.setSelect(getSelect(xmlRawSQL.getSelect()));
}
return rawSQL;
}
private static StoredProcedure getStoredProcedure(
org.ralasafe.db.sql.xml.StoredProcedure xmlStoredProcedure,
ArrayList values, boolean addParam2Values) {
StoredProcedure storedProcedure = new StoredProcedure();
storedProcedure.setContent(xmlStoredProcedure.getContent());
storedProcedure.setParameters(getParameters(xmlStoredProcedure
.getParameter(), values, addParam2Values));
if (xmlStoredProcedure.getSelect() != null) {
storedProcedure
.setSelect(getSelect(xmlStoredProcedure.getSelect()));
}
return storedProcedure;
}
private static ArrayList getParameters(
org.ralasafe.db.sql.xml.Parameter[] xmlParameters, ArrayList values,
boolean addParam2Values) {
ArrayList parameters = new ArrayList(xmlParameters.length);
for (int i = 0; i < xmlParameters.length; i++) {
parameters.add(getParameter(xmlParameters[i], values,
addParam2Values));
}
return parameters;
}
private static Parameter getParameter(
org.ralasafe.db.sql.xml.Parameter xmlParameter, ArrayList values,
boolean addParam2Values) {
if (xmlParameter.getContextValue() != null) {
Value value = getContextValue(xmlParameter.getContextValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlParameter.getHintValue() != null) {
Value value = getHintValue(xmlParameter.getHintValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlParameter.getSimpleValue() != null) {
Value value = getSimpleValue(xmlParameter.getSimpleValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlParameter.getUserValue() != null) {
Value value = getUserValue(xmlParameter.getUserValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
throw new RalasafeException("No Parameter found.");
}
private static Where getWhere(org.ralasafe.db.sql.xml.Where xmlWhere,
ArrayList values, boolean addParam2Values) {
Where where = new Where();
where.setExpressionGroup(getExpressionGroup(xmlWhere
.getExpressionGroup(), values, addParam2Values));
return where;
}
private static ExpressionGroup getExpressionGroup(
org.ralasafe.db.sql.xml.ExpressionGroup xmlExpressionGroup,
ArrayList values, boolean addParam2Values) {
ExpressionGroup expressionGroup = new ExpressionGroup();
expressionGroup.setExpressions(getExpressions(xmlExpressionGroup
.getExpressionGroupTypeItem(), values, addParam2Values));
expressionGroup.setLinker(xmlExpressionGroup.getLinker().toString());
return expressionGroup;
}
private static Expression getExpression(
org.ralasafe.db.sql.xml.ExpressionGroupTypeItem xmlExpression,
ArrayList values, boolean addParam2Values) {
if (xmlExpression.getBinaryExpression() != null)
return getBinaryExpression(xmlExpression.getBinaryExpression(),
values, addParam2Values);
if (xmlExpression.getInExpression() != null)
return getInExpression(xmlExpression.getInExpression(), values,
addParam2Values);
if (xmlExpression.getNotInExpression() != null)
return getNotInExpression(xmlExpression.getNotInExpression(),
values, addParam2Values);
if (xmlExpression.getIsNullExpression() != null)
return getIsNullExpression(xmlExpression.getIsNullExpression());
if (xmlExpression.getIsNotNullExpression() != null)
return getIsNotNullExpression(xmlExpression
.getIsNotNullExpression());
if (xmlExpression.getExpressionGroup() != null)
return getExpressionGroup(xmlExpression.getExpressionGroup(),
values, addParam2Values);
throw new RalasafeException("No Expression found");
}
private static Expression getIsNullExpression(
org.ralasafe.db.sql.xml.IsNullExpression xmlIsNullExpression) {
IsNullExpression isNullExpression = new IsNullExpression();
isNullExpression.setColumn(getColumn(xmlIsNullExpression.getColumn()));
return isNullExpression;
}
private static Expression getIsNotNullExpression(
org.ralasafe.db.sql.xml.IsNotNullExpression xmlIsNotNullExpression) {
IsNotNullExpression isNotNullExpression = new IsNotNullExpression();
isNotNullExpression.setColumn(getColumn(xmlIsNotNullExpression
.getColumn()));
return isNotNullExpression;
}
private static Collection getExpressions(
org.ralasafe.db.sql.xml.ExpressionGroupTypeItem[] xmlExpressions,
ArrayList values, boolean addParam2Values) {
Collection expressions = new ArrayList();
int count = xmlExpressions.length;
for (int i = 0; i < count; i++) {
expressions.add(getExpression(xmlExpressions[i], values,
addParam2Values));
}
return expressions;
}
private static NotInExpression getNotInExpression(
org.ralasafe.db.sql.xml.NotInExpression xmlNotInExpression,
ArrayList values, boolean addParam2Values) {
NotInExpression notInExpression = new NotInExpression();
notInExpression.setLeft(getLeft(xmlNotInExpression.getLeft()
.getLeftOfIn(), values, addParam2Values));
notInExpression.setRight(getRight(xmlNotInExpression.getRight()
.getRightOfIn(), values, addParam2Values));
return notInExpression;
}
private static InExpression getInExpression(
org.ralasafe.db.sql.xml.InExpression xmlInExpression, ArrayList values,
boolean addParam2Values) {
InExpression inExpression = new InExpression();
inExpression.setLeft(getLeft(xmlInExpression.getLeft().getLeftOfIn(),
values, addParam2Values));
inExpression.setRight(getRight(xmlInExpression.getRight()
.getRightOfIn(), values, addParam2Values));
return inExpression;
}
private static LeftOfIn getLeft(org.ralasafe.db.sql.xml.LeftOfIn xmlLeft,
ArrayList values, boolean addParam2Values) {
if (xmlLeft.getQuery() != null)
return getQuery(xmlLeft.getQuery(), values);
if (xmlLeft.getColumn() != null) {
ColumnsOfIn columnsOfIn = new ColumnsOfIn();
columnsOfIn.setColumns(getColumns(xmlLeft.getColumn()));
return columnsOfIn;
}
throw new RalasafeException("No LeftOfIn found.");
}
private static RightOfIn getRight(org.ralasafe.db.sql.xml.RightOfIn xmlRight,
ArrayList values, boolean addParam2Values) {
if (xmlRight.getQuery() != null)
return getQuery(xmlRight.getQuery(), values);
if (xmlRight.getValue() != null) {
ValuesOfIn valuesOfIn = new ValuesOfIn();
valuesOfIn.setValues(getValues(xmlRight.getValue(), values,
addParam2Values));
return valuesOfIn;
}
throw new RalasafeException("No RightOfIn found.");
}
private static ArrayList getValues(org.ralasafe.db.sql.xml.Value[] xmlValues,
ArrayList values, boolean addParam2Values) {
ArrayList list = new ArrayList();
int count = xmlValues.length;
for (int i = 0; i < count; i++) {
list.add(getValue(xmlValues[i], values, addParam2Values));
}
return list;
}
private static BinaryExpression getBinaryExpression(
org.ralasafe.db.sql.xml.BinaryExpression xmlBinaryExpression,
ArrayList values, boolean addParam2Values) {
BinaryExpression binaryExpression = new BinaryExpression();
binaryExpression.setOperand1(getOperand(xmlBinaryExpression
.getOperand1(), values, addParam2Values));
binaryExpression.setOperand2(getOperand(xmlBinaryExpression
.getOperand2(), values, addParam2Values));
binaryExpression.setOperator(getOperator(xmlBinaryExpression
.getOperator()));
return binaryExpression;
}
private static Operand getOperand(Operand1 operand1, ArrayList values,
boolean addParam2Values) {
return getOperand(operand1.getOperand(), values, addParam2Values);
}
private static Operand getOperand(Operand2 operand2, ArrayList values,
boolean addParam2Values) {
return getOperand(operand2.getOperand(), values, addParam2Values);
}
private static Operand getOperand(org.ralasafe.db.sql.xml.Operand xmlOperand,
ArrayList values, boolean addParam2Values) {
if (xmlOperand.getColumn() != null)
return getColumn(xmlOperand.getColumn());
if (xmlOperand.getValue() != null)
return getValue(xmlOperand.getValue(), values, addParam2Values);
if (xmlOperand.getQuery() != null)
return getQuery(xmlOperand.getQuery(), values);
throw new RalasafeException("No Operand found.");
}
private static Value getValue(org.ralasafe.db.sql.xml.Value xmlValue,
ArrayList values, boolean addParam2Values) {
if (xmlValue.getSimpleValue() != null) {
Value value = getSimpleValue(xmlValue.getSimpleValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlValue.getContextValue() != null) {
Value value = getContextValue(xmlValue.getContextValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlValue.getHintValue() != null) {
Value value = getHintValue(xmlValue.getHintValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
if (xmlValue.getUserValue() != null) {
Value value = getUserValue(xmlValue.getUserValue());
if (addParam2Values) {
values.add(value);
}
return value;
}
throw new RalasafeException("No Value found.");
}
private static UserValue getUserValue(
org.ralasafe.db.sql.xml.UserValue xmlUserValue) {
UserValue userValue = new UserValue();
userValue.setKey(xmlUserValue.getKey());
return userValue;
}
private static HintValue getHintValue(
org.ralasafe.db.sql.xml.HintValue xmlHintValue) {
HintValue hintValue = new HintValue();
hintValue.setHint(xmlHintValue.getHint());
hintValue.setKey(xmlHintValue.getKey());
return hintValue;
}
private static ContextValue getContextValue(
org.ralasafe.db.sql.xml.ContextValue xmlContextValue) {
ContextValue contextValue = new ContextValue();
contextValue.setKey(xmlContextValue.getKey());
return contextValue;
}
private static SimpleValue getSimpleValue(
org.ralasafe.db.sql.xml.SimpleValue xmlSimpleValue) {
SimpleValue simpleValue = new SimpleValue();
simpleValue.setType(xmlSimpleValue.getType().toString());
simpleValue.setValue(xmlSimpleValue.getContent());
return simpleValue;
}
private static Operator getOperator(org.ralasafe.db.sql.xml.Operator xmlOperator) {
if (xmlOperator.getSimpleOperator() != null)
return getSimpleOperator(xmlOperator.getSimpleOperator());
throw new RalasafeException("No SimpleOperator found.");
}
private static SimpleOperator getSimpleOperator(
SimpleOperatorType xmlSimpleOperator) {
SimpleOperator simpleOperator = new SimpleOperator();
simpleOperator.setValue(xmlSimpleOperator.toString());
return simpleOperator;
}
private static OrderBy getOrderBy(org.ralasafe.db.sql.xml.OrderBy xmlOrderBy) {
OrderBy orderBy = new OrderBy();
orderBy.setColumns(getColumns(xmlOrderBy.getColumn()));
return orderBy;
}
private static GroupBy getGroupBy(org.ralasafe.db.sql.xml.GroupBy xmlGroupBy) {
GroupBy groupBy = new GroupBy();
groupBy.setColumns(getColumns(xmlGroupBy.getColumn()));
return groupBy;
}
private static From getFrom(org.ralasafe.db.sql.xml.From xmlFrom) {
From from = new From();
from.setTables(getTables(xmlFrom.getTable()));
return from;
}
private static Collection getTables(org.ralasafe.db.sql.xml.Table[] xmlTables) {
Collection tables = new ArrayList();
int count = xmlTables.length;
for (int i = 0; i < count; i++) {
tables.add(getTable(xmlTables[i]));
}
return tables;
}
private static Table getTable(org.ralasafe.db.sql.xml.Table xmlTable) {
Table table = new Table();
table.setSchema(xmlTable.getSchema());
table.setName(xmlTable.getName());
table.setAlias(xmlTable.getAlias());
return table;
}
private static Select getSelect(org.ralasafe.db.sql.xml.Select xmlSelect) {
Select select = new Select();
select.setMappingClass(xmlSelect.getMappingClass());
select.setDistinct(xmlSelect.getIsDistinct());
select.setColumns(getColumns(xmlSelect.getColumn()));
// set mapping class, also known as ObjectNewer
if (select.getMappingClass() == null
|| select.getMappingClass().equals(""))
select.setObjectNewer(new MapStorageObjectNewer());
else
select.setObjectNewer(new JavaBeanObjectNewer(select
.getMappingClass()));
// set ColumnAdapter
ArrayList columns = select.getColumns();
int count = columns.size();
for (int i = 0; i < count; i++) {
Column column = (Column) columns.get(i);
// if no property value, then use column name instead
String property = column.getProperty();
if (StringUtil.isEmpty(property)) {
property = column.getName();
}
String javaType = column.getJavaType();
if (StringUtil.isEmpty(javaType)) {
javaType = "java.lang.Object";
}
if (select.getMappingClass() == null
|| select.getMappingClass().equals(""))
column.setAdapter(new MapStorgeColumnAdapter(property,javaType));
else
column
.setAdapter(new JavaBeanColumnAdapter(property,
javaType));
}
return select;
}
private static ArrayList getColumns(org.ralasafe.db.sql.xml.Column[] xmlColumns) {
ArrayList columns = new ArrayList();
int count = xmlColumns.length;
for (int i = 0; i < count; i++) {
columns.add(getColumn(xmlColumns[i]));
}
return columns;
}
private static Column getColumn(org.ralasafe.db.sql.xml.Column xmlColumn) {
Column column = new Column();
column.setName(xmlColumn.getName());
column.setTableAlias(xmlColumn.getTableAlias());
column.setSqlType(xmlColumn.getSqlType());
column.setJavaType(xmlColumn.getJavaType());
column.setProperty(xmlColumn.getProperty());
column.setOrder(xmlColumn.getOrder().toString());
column.setReadOnly(xmlColumn.isReadOnly());
if (xmlColumn.getFunction() != null)
column.setFunction(xmlColumn.getFunction().toString());
return column;
}
}
|
arxitics/arxiv-analytics
|
models/oss.js
|
<reponame>arxitics/arxiv-analytics
/**
* Aliyun OSS.
*/
var fs = require('fs');
var url = require('url');
var http = require('http');
var path = require('path');
var crypto = require('crypto');
var multer = require('multer');
var file = require('./file');
var mime = require('./mime');
var settings = require('../settings').oss;
// Handle `multipart/form-data`
exports.upload = function () {
return multer({
dest: settings.directory,
limits: settings.limits,
rename: function (fieldname, filename) {
return filename + '-' + Date.now()
},
onParseStart: function () {
console.log('parsing form ...');
},
onParseEnd: function (req, next) {
console.log('form parsing completed');
next();
},
onFileUploadStart: function (file) {
console.log('uploading ' + file.fieldname + ' ...');
return mime.types.hasOwnProperty(file.extension);
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
},
onFileSizeLimit: function (file) {
console.log(file.originalname + ' is too large');
fs.unlink(path.join(__dirname, file.path));
}
});
};
// Generate authorization
exports.authorize = function (query) {
var params = [
query.method,
query.md5 || '',
query.type || '',
query.date
];
if (query.hasOwnProperty('meta')) {
var meta = query.meta;
Object.keys(meta).sort().forEach(function (key) {
params.push('x-oss-' + key + ':' + meta[key]);
});
}
params.push('/' + settings.bucket + query.resource);
var hmac = crypto.createHmac('sha1', settings.key).update(params.join('\n'));
return 'OSS ' + settings.id + ':' + hmac.digest('base64');
};
// Get HTTP request headers
exports.getHeaders = function (query) {
var headers = {
'Date': new Date().toGMTString()
};
if (query.hasOwnProperty('origin')) {
headers['Content-Type'] = query.type;
headers['Content-Length'] = query.size;
headers['Content-MD5'] = query.md5;
}
if (query.hasOwnProperty('meta')) {
var meta = query.meta;
for (var key in meta) {
if (meta.hasOwnProperty(key)) {
headers['x-oss-' + key] = meta[key];
}
}
}
query.date = headers['Date'];
headers['Authorization'] = exports.authorize(query);
return headers;
};
// HTTP request
exports.request = function (query, callback) {
var options = {
method: query.method,
host: settings.host,
port: settings.port,
path: query.resource,
headers: exports.getHeaders(query)
};
var req = http.request(options, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (err) {
console.error(err);
console.log('problem with request: ' + err.message);
});
res.on('end', function () {
return (typeof callback === 'function') ? callback(data) : null;
});
});
req.on('error', function (err) {
console.error(err);
console.log('an error happened while sending OSS request');
});
if (query.hasOwnProperty('body')) {
req.write(query.body);
}
req.end();
};
// Get an object from OSS
exports.getObject = function (query, callback) {
query.method = 'GET';
exports.request(query, function (data) {
console.log('get the OSS object ' + query.resource + ' successfully');
return (typeof callback === 'function') ? callback(data) : null;
});
};
// Put an object to OSS
exports.putObject = function (query, callback) {
callback = (typeof callback === 'function') ? callback : function () {};
query.method = 'PUT';
if (query.hasOwnProperty('origin')) {
var origin = query.origin;
query.type = mime.lookup(path.extname(origin));
fs.stat(origin, function (err, stats) {
if (err) {
console.error(err);
return callback(false);
}
query.size = stats.size;
file.read(origin, function (content) {
query.body = content;
query.md5 = crypto.createHash('md5').update(content).digest('base64');
exports.request(query, function (data) {
console.log('put the object ' + origin + ' to OSS successfully');
return callback(true);
});
});
});
}
};
// Copy an object of OSS
exports.copyObject = function (query, callback) {
query.method = 'PUT';
query.meta = {
'copy-source': '/' + settings.bucket + query.source
};
exports.request(query, function (data) {
console.log('copy the OSS object ' + query.source + ' successfully');
return (typeof callback === 'function') ? callback(true) : null;
});
};
// Delete an object of OSS
exports.deleteObject = function (query, callback) {
query.method = 'DELETE';
exports.request(query, function (data) {
console.log('delete the OSS object ' + query.resource + ' successfully');
return (typeof callback === 'function') ? callback(true) : null;
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.