file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
39k
| suffix
large_stringlengths 0
36.1k
| middle
large_stringlengths 0
29.4k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
factory.py | # Copyright 2012 Kevin Ormbrek
#
# 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.
from suds.sudsobject import Object as SudsObject
class _FactoryKeywords(object):
def set_wsdl_object_attribute(self, object, name, value):
"""Sets the attribute of a WSDL object.
Example:
| ${order search request}= | Create Wsdl Object | OrderSearchRequest | |
| Set Wsdl Object Attribute | ${order search request} | id | 4065 |
"""
self._assert_is_suds_object(object)
getattr(object, name)
setattr(object, name, value)
def get_wsdl_object_attribute(self, object, name):
|
def create_wsdl_object(self, type, *name_value_pairs):
"""Creates a WSDL object of the specified `type`.
Requested `type` must be defined in the WSDL, in an import specified
by the WSDL, or with `Add Doctor Import`. `type` is case sensitive.
Example:
| ${contact}= | Create Wsdl Object | Contact | |
| Set Wsdl Object Attribute | ${contact} | Name | Kelly Newman |
Attribute values can be set by passing the attribute name and value in
pairs. This is equivalent to the two lines above:
| ${contact}= | Create Wsdl Object | Contact | Name | Kelly Newman |
"""
if len(name_value_pairs) % 2 != 0:
raise ValueError("Creating a WSDL object failed. There should be "
"an even number of name-value pairs.")
obj = self._client().factory.create(type)
for i in range(0, len(name_value_pairs), 2):
self.set_wsdl_object_attribute(obj, name_value_pairs[i], name_value_pairs[i + 1])
return obj
# private
def _assert_is_suds_object(self, object):
if not isinstance(object, SudsObject):
raise ValueError("Object must be a WSDL object (suds.sudsobject.Object).")
| """Gets the attribute of a WSDL object.
Extendend variable syntax may be used to access attributes; however,
some WSDL objects may have attribute names that are illegal in Python,
necessitating this keyword.
Example:
| ${sale record}= | Call Soap Method | getLastSale | |
| ${price}= | Get Wsdl Object Attribute | ${sale record} | Price |
"""
self._assert_is_suds_object(object)
return getattr(object, name) | identifier_body |
factory.py | # Copyright 2012 Kevin Ormbrek
#
# 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.
from suds.sudsobject import Object as SudsObject
class | (object):
def set_wsdl_object_attribute(self, object, name, value):
"""Sets the attribute of a WSDL object.
Example:
| ${order search request}= | Create Wsdl Object | OrderSearchRequest | |
| Set Wsdl Object Attribute | ${order search request} | id | 4065 |
"""
self._assert_is_suds_object(object)
getattr(object, name)
setattr(object, name, value)
def get_wsdl_object_attribute(self, object, name):
"""Gets the attribute of a WSDL object.
Extendend variable syntax may be used to access attributes; however,
some WSDL objects may have attribute names that are illegal in Python,
necessitating this keyword.
Example:
| ${sale record}= | Call Soap Method | getLastSale | |
| ${price}= | Get Wsdl Object Attribute | ${sale record} | Price |
"""
self._assert_is_suds_object(object)
return getattr(object, name)
def create_wsdl_object(self, type, *name_value_pairs):
"""Creates a WSDL object of the specified `type`.
Requested `type` must be defined in the WSDL, in an import specified
by the WSDL, or with `Add Doctor Import`. `type` is case sensitive.
Example:
| ${contact}= | Create Wsdl Object | Contact | |
| Set Wsdl Object Attribute | ${contact} | Name | Kelly Newman |
Attribute values can be set by passing the attribute name and value in
pairs. This is equivalent to the two lines above:
| ${contact}= | Create Wsdl Object | Contact | Name | Kelly Newman |
"""
if len(name_value_pairs) % 2 != 0:
raise ValueError("Creating a WSDL object failed. There should be "
"an even number of name-value pairs.")
obj = self._client().factory.create(type)
for i in range(0, len(name_value_pairs), 2):
self.set_wsdl_object_attribute(obj, name_value_pairs[i], name_value_pairs[i + 1])
return obj
# private
def _assert_is_suds_object(self, object):
if not isinstance(object, SudsObject):
raise ValueError("Object must be a WSDL object (suds.sudsobject.Object).")
| _FactoryKeywords | identifier_name |
daint.rs | #[doc = "Register `DAINT` reader"]
pub struct R(crate::R<DAINT_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DAINT_SPEC>;
#[inline(always)]
fn | (&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DAINT_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DAINT_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"]
pub struct INEPINT_R(crate::FieldReader<u16, u16>);
impl INEPINT_R {
pub(crate) fn new(bits: u16) -> Self {
INEPINT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"]
pub struct OUTEPINT_R(crate::FieldReader<u16, u16>);
impl OUTEPINT_R {
pub(crate) fn new(bits: u16) -> Self {
OUTEPINT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for OUTEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"]
#[inline(always)]
pub fn in_ep_int(&self) -> INEPINT_R {
INEPINT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"]
#[inline(always)]
pub fn out_epint(&self) -> OUTEPINT_R {
OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
#[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"]
pub struct DAINT_SPEC;
impl crate::RegisterSpec for DAINT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [daint::R](R) reader structure"]
impl crate::Readable for DAINT_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets DAINT to value 0"]
impl crate::Resettable for DAINT_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| deref | identifier_name |
daint.rs | #[doc = "Register `DAINT` reader"]
pub struct R(crate::R<DAINT_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DAINT_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DAINT_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DAINT_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"]
pub struct INEPINT_R(crate::FieldReader<u16, u16>);
impl INEPINT_R {
pub(crate) fn new(bits: u16) -> Self {
INEPINT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"]
pub struct OUTEPINT_R(crate::FieldReader<u16, u16>);
impl OUTEPINT_R {
pub(crate) fn new(bits: u16) -> Self |
}
impl core::ops::Deref for OUTEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"]
#[inline(always)]
pub fn in_ep_int(&self) -> INEPINT_R {
INEPINT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"]
#[inline(always)]
pub fn out_epint(&self) -> OUTEPINT_R {
OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
#[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"]
pub struct DAINT_SPEC;
impl crate::RegisterSpec for DAINT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [daint::R](R) reader structure"]
impl crate::Readable for DAINT_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets DAINT to value 0"]
impl crate::Resettable for DAINT_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
OUTEPINT_R(crate::FieldReader::new(bits))
} | identifier_body |
daint.rs | #[doc = "Register `DAINT` reader"]
pub struct R(crate::R<DAINT_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DAINT_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DAINT_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DAINT_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"]
pub struct INEPINT_R(crate::FieldReader<u16, u16>);
impl INEPINT_R {
pub(crate) fn new(bits: u16) -> Self {
INEPINT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OutEPInt` reader - OUT Endpoint Interrupt Bits"]
pub struct OUTEPINT_R(crate::FieldReader<u16, u16>);
impl OUTEPINT_R {
pub(crate) fn new(bits: u16) -> Self {
OUTEPINT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for OUTEPINT_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"]
#[inline(always)]
pub fn in_ep_int(&self) -> INEPINT_R {
INEPINT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - OUT Endpoint Interrupt Bits"]
#[inline(always)]
pub fn out_epint(&self) -> OUTEPINT_R {
OUTEPINT_R::new(((self.bits >> 16) & 0xffff) as u16)
} | pub struct DAINT_SPEC;
impl crate::RegisterSpec for DAINT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [daint::R](R) reader structure"]
impl crate::Readable for DAINT_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets DAINT to value 0"]
impl crate::Resettable for DAINT_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | }
#[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"] | random_line_split |
detector.py | """ Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_breaking`.
The breaking change detector creates a temporary directory, copies in
each file to compute a protobuf "state", computes a diff of the "before"
and "after" states, and runs the diff against a set of rules to determine
if there was a breaking change.
The tool is currently implemented with buf (https://buf.build/)
"""
from pathlib import Path
from typing import List
from tools.api_proto_breaking_change_detector.buf_utils import check_breaking, pull_buf_deps
from tools.api_proto_breaking_change_detector.detector_errors import ChangeDetectorError
class ProtoBreakingChangeDetector(object):
"""Abstract breaking change detector interface"""
def run_detector(self) -> None:
"""Run the breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocations
to the breaking change detector.
"""
pass
def is_breaking(self) -> bool:
"""Return True if breaking changes were detected in the given protos"""
pass
def get_breaking_changes(self) -> List[str]:
"""Return a list of strings containing breaking changes output by the tool"""
pass
class BufWrapper(ProtoBreakingChangeDetector):
"""Breaking change detector implemented with buf"""
def __init__(
self,
path_to_changed_dir: str,
git_ref: str,
git_path: str,
subdir: str = None,
buf_path: str = None,
config_file_loc: str = None,
additional_args: List[str] = None) -> None:
|
def run_detector(self) -> None:
self._final_result = check_breaking(
self._buf_path,
self._path_to_changed_dir,
git_ref=self._git_ref,
git_path=self._git_path,
subdir=self._subdir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def is_breaking(self) -> bool:
if not self._final_result:
raise ChangeDetectorError("Must invoke run_detector() before checking if is_breaking()")
final_code, final_out, final_err = self._final_result
final_out, final_err = '\n'.join(final_out), '\n'.join(final_err)
if final_err != "":
raise ChangeDetectorError(f"Error from buf: {final_err}")
if final_code != 0:
return True
if final_out != "":
return True
return False
def get_breaking_changes(self) -> List[str]:
_, final_out, _ = self._final_result
return filter(lambda x: len(x) > 0, final_out) if self.is_breaking() else []
| """Initialize the configuration of buf
This function sets up any necessary config without actually
running buf against any proto files.
BufWrapper takes a path to a directory containing proto files
as input, and it checks if these proto files break any changes
from a given initial state.
The initial state is input as a git ref. The constructor expects
a git ref string, as well as an absolute path to a .git folder
for the repository.
Args:
path_to_changed_dir {str} -- absolute path to a directory containing proto files in the after state
buf_path {str} -- path to the buf binary (default: "buf")
git_ref {str} -- git reference to use for the initial state of the protos (typically a commit hash)
git_path {str} -- absolute path to .git folder for the repository of interest
subdir {str} -- subdirectory within git repository from which to search for .proto files (default: None, e.g. stay in root)
additional_args {List[str]} -- additional arguments passed into the buf binary invocations
config_file_loc {str} -- absolute path to buf.yaml configuration file (if not provided, uses default buf configuration)
"""
if not Path(path_to_changed_dir).is_dir():
raise ValueError(f"path_to_changed_dir {path_to_changed_dir} is not a valid directory")
if Path.cwd() not in Path(path_to_changed_dir).parents:
raise ValueError(
f"path_to_changed_dir {path_to_changed_dir} must be a subdirectory of the cwd ({ Path.cwd() })"
)
if not Path(git_path).exists():
raise ChangeDetectorError(f'path to .git folder {git_path} does not exist')
self._path_to_changed_dir = path_to_changed_dir
self._additional_args = additional_args
self._buf_path = buf_path or "buf"
self._config_file_loc = config_file_loc
self._git_ref = git_ref
self._git_path = git_path
self._subdir = subdir
self._final_result = None
pull_buf_deps(
self._buf_path,
self._path_to_changed_dir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args) | identifier_body |
detector.py | """ Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_breaking`.
The breaking change detector creates a temporary directory, copies in
each file to compute a protobuf "state", computes a diff of the "before"
and "after" states, and runs the diff against a set of rules to determine
if there was a breaking change.
The tool is currently implemented with buf (https://buf.build/)
"""
from pathlib import Path
from typing import List
from tools.api_proto_breaking_change_detector.buf_utils import check_breaking, pull_buf_deps
from tools.api_proto_breaking_change_detector.detector_errors import ChangeDetectorError
class ProtoBreakingChangeDetector(object):
"""Abstract breaking change detector interface"""
def run_detector(self) -> None:
"""Run the breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocations
to the breaking change detector.
"""
pass
def is_breaking(self) -> bool:
"""Return True if breaking changes were detected in the given protos"""
pass
def get_breaking_changes(self) -> List[str]:
"""Return a list of strings containing breaking changes output by the tool"""
pass
class BufWrapper(ProtoBreakingChangeDetector):
"""Breaking change detector implemented with buf"""
def __init__(
self,
path_to_changed_dir: str,
git_ref: str,
git_path: str,
subdir: str = None,
buf_path: str = None,
config_file_loc: str = None,
additional_args: List[str] = None) -> None:
"""Initialize the configuration of buf
This function sets up any necessary config without actually
running buf against any proto files.
BufWrapper takes a path to a directory containing proto files
as input, and it checks if these proto files break any changes
from a given initial state.
The initial state is input as a git ref. The constructor expects
a git ref string, as well as an absolute path to a .git folder
for the repository.
Args:
path_to_changed_dir {str} -- absolute path to a directory containing proto files in the after state
buf_path {str} -- path to the buf binary (default: "buf")
git_ref {str} -- git reference to use for the initial state of the protos (typically a commit hash)
git_path {str} -- absolute path to .git folder for the repository of interest
subdir {str} -- subdirectory within git repository from which to search for .proto files (default: None, e.g. stay in root)
additional_args {List[str]} -- additional arguments passed into the buf binary invocations
config_file_loc {str} -- absolute path to buf.yaml configuration file (if not provided, uses default buf configuration)
"""
if not Path(path_to_changed_dir).is_dir():
raise ValueError(f"path_to_changed_dir {path_to_changed_dir} is not a valid directory")
if Path.cwd() not in Path(path_to_changed_dir).parents:
raise ValueError(
f"path_to_changed_dir {path_to_changed_dir} must be a subdirectory of the cwd ({ Path.cwd() })"
)
if not Path(git_path).exists():
raise ChangeDetectorError(f'path to .git folder {git_path} does not exist')
self._path_to_changed_dir = path_to_changed_dir
self._additional_args = additional_args
self._buf_path = buf_path or "buf"
self._config_file_loc = config_file_loc
self._git_ref = git_ref
self._git_path = git_path
self._subdir = subdir
self._final_result = None
pull_buf_deps(
self._buf_path,
self._path_to_changed_dir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def run_detector(self) -> None:
self._final_result = check_breaking(
self._buf_path,
self._path_to_changed_dir,
git_ref=self._git_ref,
git_path=self._git_path,
subdir=self._subdir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def is_breaking(self) -> bool:
if not self._final_result:
raise ChangeDetectorError("Must invoke run_detector() before checking if is_breaking()")
final_code, final_out, final_err = self._final_result
final_out, final_err = '\n'.join(final_out), '\n'.join(final_err)
if final_err != "":
raise ChangeDetectorError(f"Error from buf: {final_err}")
if final_code != 0:
return True
if final_out != "":
return True
return False
def get_breaking_changes(self) -> List[str]:
_, final_out, _ = self._final_result | return filter(lambda x: len(x) > 0, final_out) if self.is_breaking() else [] | random_line_split |
|
detector.py | """ Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_breaking`.
The breaking change detector creates a temporary directory, copies in
each file to compute a protobuf "state", computes a diff of the "before"
and "after" states, and runs the diff against a set of rules to determine
if there was a breaking change.
The tool is currently implemented with buf (https://buf.build/)
"""
from pathlib import Path
from typing import List
from tools.api_proto_breaking_change_detector.buf_utils import check_breaking, pull_buf_deps
from tools.api_proto_breaking_change_detector.detector_errors import ChangeDetectorError
class ProtoBreakingChangeDetector(object):
"""Abstract breaking change detector interface"""
def run_detector(self) -> None:
"""Run the breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocations
to the breaking change detector.
"""
pass
def is_breaking(self) -> bool:
"""Return True if breaking changes were detected in the given protos"""
pass
def | (self) -> List[str]:
"""Return a list of strings containing breaking changes output by the tool"""
pass
class BufWrapper(ProtoBreakingChangeDetector):
"""Breaking change detector implemented with buf"""
def __init__(
self,
path_to_changed_dir: str,
git_ref: str,
git_path: str,
subdir: str = None,
buf_path: str = None,
config_file_loc: str = None,
additional_args: List[str] = None) -> None:
"""Initialize the configuration of buf
This function sets up any necessary config without actually
running buf against any proto files.
BufWrapper takes a path to a directory containing proto files
as input, and it checks if these proto files break any changes
from a given initial state.
The initial state is input as a git ref. The constructor expects
a git ref string, as well as an absolute path to a .git folder
for the repository.
Args:
path_to_changed_dir {str} -- absolute path to a directory containing proto files in the after state
buf_path {str} -- path to the buf binary (default: "buf")
git_ref {str} -- git reference to use for the initial state of the protos (typically a commit hash)
git_path {str} -- absolute path to .git folder for the repository of interest
subdir {str} -- subdirectory within git repository from which to search for .proto files (default: None, e.g. stay in root)
additional_args {List[str]} -- additional arguments passed into the buf binary invocations
config_file_loc {str} -- absolute path to buf.yaml configuration file (if not provided, uses default buf configuration)
"""
if not Path(path_to_changed_dir).is_dir():
raise ValueError(f"path_to_changed_dir {path_to_changed_dir} is not a valid directory")
if Path.cwd() not in Path(path_to_changed_dir).parents:
raise ValueError(
f"path_to_changed_dir {path_to_changed_dir} must be a subdirectory of the cwd ({ Path.cwd() })"
)
if not Path(git_path).exists():
raise ChangeDetectorError(f'path to .git folder {git_path} does not exist')
self._path_to_changed_dir = path_to_changed_dir
self._additional_args = additional_args
self._buf_path = buf_path or "buf"
self._config_file_loc = config_file_loc
self._git_ref = git_ref
self._git_path = git_path
self._subdir = subdir
self._final_result = None
pull_buf_deps(
self._buf_path,
self._path_to_changed_dir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def run_detector(self) -> None:
self._final_result = check_breaking(
self._buf_path,
self._path_to_changed_dir,
git_ref=self._git_ref,
git_path=self._git_path,
subdir=self._subdir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def is_breaking(self) -> bool:
if not self._final_result:
raise ChangeDetectorError("Must invoke run_detector() before checking if is_breaking()")
final_code, final_out, final_err = self._final_result
final_out, final_err = '\n'.join(final_out), '\n'.join(final_err)
if final_err != "":
raise ChangeDetectorError(f"Error from buf: {final_err}")
if final_code != 0:
return True
if final_out != "":
return True
return False
def get_breaking_changes(self) -> List[str]:
_, final_out, _ = self._final_result
return filter(lambda x: len(x) > 0, final_out) if self.is_breaking() else []
| get_breaking_changes | identifier_name |
detector.py | """ Protocol Buffer Breaking Change Detector
This tool is used to detect "breaking changes" in protobuf files, to
ensure proper backwards-compatibility in protobuf API updates. The tool
can check for breaking changes of a single API by taking 2 .proto file
paths as input (before and after) and outputting a bool `is_breaking`.
The breaking change detector creates a temporary directory, copies in
each file to compute a protobuf "state", computes a diff of the "before"
and "after" states, and runs the diff against a set of rules to determine
if there was a breaking change.
The tool is currently implemented with buf (https://buf.build/)
"""
from pathlib import Path
from typing import List
from tools.api_proto_breaking_change_detector.buf_utils import check_breaking, pull_buf_deps
from tools.api_proto_breaking_change_detector.detector_errors import ChangeDetectorError
class ProtoBreakingChangeDetector(object):
"""Abstract breaking change detector interface"""
def run_detector(self) -> None:
"""Run the breaking change detector to detect rule violations
This method should populate the detector's internal data such
that `is_breaking` does not require any additional invocations
to the breaking change detector.
"""
pass
def is_breaking(self) -> bool:
"""Return True if breaking changes were detected in the given protos"""
pass
def get_breaking_changes(self) -> List[str]:
"""Return a list of strings containing breaking changes output by the tool"""
pass
class BufWrapper(ProtoBreakingChangeDetector):
"""Breaking change detector implemented with buf"""
def __init__(
self,
path_to_changed_dir: str,
git_ref: str,
git_path: str,
subdir: str = None,
buf_path: str = None,
config_file_loc: str = None,
additional_args: List[str] = None) -> None:
"""Initialize the configuration of buf
This function sets up any necessary config without actually
running buf against any proto files.
BufWrapper takes a path to a directory containing proto files
as input, and it checks if these proto files break any changes
from a given initial state.
The initial state is input as a git ref. The constructor expects
a git ref string, as well as an absolute path to a .git folder
for the repository.
Args:
path_to_changed_dir {str} -- absolute path to a directory containing proto files in the after state
buf_path {str} -- path to the buf binary (default: "buf")
git_ref {str} -- git reference to use for the initial state of the protos (typically a commit hash)
git_path {str} -- absolute path to .git folder for the repository of interest
subdir {str} -- subdirectory within git repository from which to search for .proto files (default: None, e.g. stay in root)
additional_args {List[str]} -- additional arguments passed into the buf binary invocations
config_file_loc {str} -- absolute path to buf.yaml configuration file (if not provided, uses default buf configuration)
"""
if not Path(path_to_changed_dir).is_dir():
|
if Path.cwd() not in Path(path_to_changed_dir).parents:
raise ValueError(
f"path_to_changed_dir {path_to_changed_dir} must be a subdirectory of the cwd ({ Path.cwd() })"
)
if not Path(git_path).exists():
raise ChangeDetectorError(f'path to .git folder {git_path} does not exist')
self._path_to_changed_dir = path_to_changed_dir
self._additional_args = additional_args
self._buf_path = buf_path or "buf"
self._config_file_loc = config_file_loc
self._git_ref = git_ref
self._git_path = git_path
self._subdir = subdir
self._final_result = None
pull_buf_deps(
self._buf_path,
self._path_to_changed_dir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def run_detector(self) -> None:
self._final_result = check_breaking(
self._buf_path,
self._path_to_changed_dir,
git_ref=self._git_ref,
git_path=self._git_path,
subdir=self._subdir,
config_file_loc=self._config_file_loc,
additional_args=self._additional_args)
def is_breaking(self) -> bool:
if not self._final_result:
raise ChangeDetectorError("Must invoke run_detector() before checking if is_breaking()")
final_code, final_out, final_err = self._final_result
final_out, final_err = '\n'.join(final_out), '\n'.join(final_err)
if final_err != "":
raise ChangeDetectorError(f"Error from buf: {final_err}")
if final_code != 0:
return True
if final_out != "":
return True
return False
def get_breaking_changes(self) -> List[str]:
_, final_out, _ = self._final_result
return filter(lambda x: len(x) > 0, final_out) if self.is_breaking() else []
| raise ValueError(f"path_to_changed_dir {path_to_changed_dir} is not a valid directory") | conditional_block |
htmlhrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLHRElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> |
}
| {
let element = HTMLHRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap)
} | identifier_body |
htmlhrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLHRElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn | (localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
let element = HTMLHRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap)
}
}
| new_inherited | identifier_name |
htmlhrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLHRElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLHRElement {
htmlelement: HTMLElement,
}
impl HTMLHRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement { |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
let element = HTMLHRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap)
}
} | htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
} | random_line_split |
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool |
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| {
self.is_anon_box()
} | identifier_body |
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
} | } | random_line_split |
|
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn | (&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| property_restriction | identifier_name |
CreateSamples.py | import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "CreateSamples" # TODO make this more human readable by adding spaces
self.parent.categories = ["Examples"]
self.parent.dependencies = []
self.parent.contributors = ["John Doe (AnyWare Corp.)"] # replace with "Firstname Lastname (Organization)"
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
It performs a simple thresholding on the input volume and optionally captures a screenshot.
"""
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
""" # replace with organization, grant and thanks.
#
# CreateSamplesWidget
#
class CreateSamplesWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
generalParametersCollapsibleButton = ctk.ctkCollapsibleButton()
generalParametersCollapsibleButton.text = "General parameters"
self.layout.addWidget(generalParametersCollapsibleButton)
# Layout within the dummy collapsible button
hlayout = qt.QHBoxLayout(generalParametersCollapsibleButton)
self.label=qt.QLabel("Volume Name:")
hlayout.addWidget(self.label)
self.volumeNameLine=qt.QLineEdit()
hlayout.addWidget(self.volumeNameLine)
self.volumeNameLine.connect('textChanged(QString)', self.onLabelChanged)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Sample From Nothing"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
#
# Sample Label map Button
#
self.labelButton = qt.QPushButton("Create Sample Label Map")
self.labelButton.toolTip = "Create sample label map."
self.labelButton.enabled = True
parametersFormLayout.addRow(self.labelButton)
#
# Sample Volume Button
#
self.volumeButton = qt.QPushButton("Create Sample Volume")
self.volumeButton.toolTip = "Create sample volume."
self.volumeButton.enabled = True
parametersFormLayout.addRow(self.volumeButton)
#
# Sample model Button
#
self.modelButton = qt.QPushButton("Create Sample Model")
self.modelButton.toolTip = "Create sample Model."
self.modelButton.enabled = True
parametersFormLayout.addRow(self.modelButton)
# connections
self.labelButton.connect('clicked(bool)', self.onLabelButton)
self.volumeButton.connect('clicked(bool)', self.onVolumeButton)
self.modelButton.connect('clicked(bool)', self.onModelButton)
parametersCollapsibleButton2 = ctk.ctkCollapsibleButton()
parametersCollapsibleButton2.text = "Sample From example"
self.layout.addWidget(parametersCollapsibleButton2)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton2)
#
# input volume selector
#
self.inputSelector = slicer.qMRMLNodeComboBox()
self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
# Keep the following line as an example
#self.inputSelector.addAttribute( "vtkMRMLScalarVolumeNode", "LabelMap", 0 )
self.inputSelector.selectNodeUponCreation = True
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.noneEnabled = True
self.inputSelector.showHidden = False
self.inputSelector.showChildNodeTypes = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputSelector.setToolTip( "reference image." )
parametersFormLayout.addRow("Reference Volume: ", self.inputSelector)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSampleFromReferenceSelect)
#
# Sample From reference Button
#
self.referenceButton = qt.QPushButton("Create Sample Model from a reference")
self.referenceButton.toolTip = "Create sample Model from a reference."
parametersFormLayout.addRow(self.referenceButton)
self.referenceButton.connect('clicked(bool)', self.onReferenceButton)
# Add vertical spacer
self.layout.addStretch(1)
# Refresh Apply button state
self.onLabelChanged(self.volumeNameLine.text)
def ButtonsClickable(self, value):
self.labelButton.setEnabled(value)
self.volumeButton.setEnabled(value)
self.modelButton.setEnabled(value)
self.onSampleFromReferenceSelect()
def cleanup(self):
pass
def onLabelChanged(self,myString):
if not myString=='':
self.ButtonsClickable(True)
else:
self.ButtonsClickable(False)
def onSampleFromReferenceSelect(self):
self.referenceButton.enabled = self.inputSelector.currentNode() and self.volumeNameLine.text != ''
def onLabelButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True)
def onVolumeButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text)
def onModelButton(self):
logic = CreateSamplesLogic()
logic.createModel()
def onReferenceButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True, reference=self.inputSelector.currentNode())
#
# CreateSamplesLogic
# | """This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setVolumeAsBackgroundImage(self, node):
count = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceCompositeNode')
for n in xrange(count):
compNode = slicer.mrmlScene.GetNthNodeByClass(n, 'vtkMRMLSliceCompositeNode')
compNode.SetBackgroundVolumeID(node.GetID())
return True
# Create sample labelmap with same geometry as input volume
def createVolume(self , volumeName, labelmap=False, reference=None):
if volumeName == '':
raise Exception('The name of the output volume cannot be empty')
value = 1
sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
imageData = vtk.vtkImageData()
if reference == None:
mySpacing = (0.5,0.6,0.5)
myOrigin = (20,50,50)
# Do NOT set the spacing and the origin of imageData (vtkImageData)
# The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
imageData.SetDimensions(30,5,15)
imageData.AllocateScalars(vtk.VTK_DOUBLE, 1)
sampleVolumeNode.SetSpacing(mySpacing[0],mySpacing[1],mySpacing[2])
sampleVolumeNode.SetOrigin(myOrigin[0],myOrigin[1],myOrigin[2])
else:
sampleVolumeNode.Copy(reference)
imageData.DeepCopy(reference.GetImageData())
sampleVolumeNode.SetName(volumeName)
sampleVolumeNode.SetAndObserveImageData(imageData)
extent = imageData.GetExtent()
for x in xrange(extent[0], extent[1]+1):
for y in xrange(extent[2], extent[3]+1):
for z in xrange(extent[4], extent[5]+1):
if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
imageData.SetScalarComponentFromDouble(x,y,z,0,value)
else:
imageData.SetScalarComponentFromDouble(x,y,z,0,0)
# Display labelmap
if labelmap:
sampleVolumeNode.SetLabelMap(1)
labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
colorNode = slicer.util.getNode('GenericAnatomyColors')
labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
labelmapVolumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())
else:
volumeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
slicer.mrmlScene.AddNode(volumeDisplayNode)
colorNode = slicer.util.getNode('Grey')
volumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
volumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(volumeDisplayNode.GetID())
self.setVolumeAsBackgroundImage(sampleVolumeNode)
return True
def createModel(self):
print "model"
class CreateSamplesTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setUp(self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear(0)
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp() |
class CreateSamplesLogic(ScriptedLoadableModuleLogic): | random_line_split |
CreateSamples.py | import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "CreateSamples" # TODO make this more human readable by adding spaces
self.parent.categories = ["Examples"]
self.parent.dependencies = []
self.parent.contributors = ["John Doe (AnyWare Corp.)"] # replace with "Firstname Lastname (Organization)"
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
It performs a simple thresholding on the input volume and optionally captures a screenshot.
"""
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
""" # replace with organization, grant and thanks.
#
# CreateSamplesWidget
#
class CreateSamplesWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
generalParametersCollapsibleButton = ctk.ctkCollapsibleButton()
generalParametersCollapsibleButton.text = "General parameters"
self.layout.addWidget(generalParametersCollapsibleButton)
# Layout within the dummy collapsible button
hlayout = qt.QHBoxLayout(generalParametersCollapsibleButton)
self.label=qt.QLabel("Volume Name:")
hlayout.addWidget(self.label)
self.volumeNameLine=qt.QLineEdit()
hlayout.addWidget(self.volumeNameLine)
self.volumeNameLine.connect('textChanged(QString)', self.onLabelChanged)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Sample From Nothing"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
#
# Sample Label map Button
#
self.labelButton = qt.QPushButton("Create Sample Label Map")
self.labelButton.toolTip = "Create sample label map."
self.labelButton.enabled = True
parametersFormLayout.addRow(self.labelButton)
#
# Sample Volume Button
#
self.volumeButton = qt.QPushButton("Create Sample Volume")
self.volumeButton.toolTip = "Create sample volume."
self.volumeButton.enabled = True
parametersFormLayout.addRow(self.volumeButton)
#
# Sample model Button
#
self.modelButton = qt.QPushButton("Create Sample Model")
self.modelButton.toolTip = "Create sample Model."
self.modelButton.enabled = True
parametersFormLayout.addRow(self.modelButton)
# connections
self.labelButton.connect('clicked(bool)', self.onLabelButton)
self.volumeButton.connect('clicked(bool)', self.onVolumeButton)
self.modelButton.connect('clicked(bool)', self.onModelButton)
parametersCollapsibleButton2 = ctk.ctkCollapsibleButton()
parametersCollapsibleButton2.text = "Sample From example"
self.layout.addWidget(parametersCollapsibleButton2)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton2)
#
# input volume selector
#
self.inputSelector = slicer.qMRMLNodeComboBox()
self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
# Keep the following line as an example
#self.inputSelector.addAttribute( "vtkMRMLScalarVolumeNode", "LabelMap", 0 )
self.inputSelector.selectNodeUponCreation = True
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.noneEnabled = True
self.inputSelector.showHidden = False
self.inputSelector.showChildNodeTypes = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputSelector.setToolTip( "reference image." )
parametersFormLayout.addRow("Reference Volume: ", self.inputSelector)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSampleFromReferenceSelect)
#
# Sample From reference Button
#
self.referenceButton = qt.QPushButton("Create Sample Model from a reference")
self.referenceButton.toolTip = "Create sample Model from a reference."
parametersFormLayout.addRow(self.referenceButton)
self.referenceButton.connect('clicked(bool)', self.onReferenceButton)
# Add vertical spacer
self.layout.addStretch(1)
# Refresh Apply button state
self.onLabelChanged(self.volumeNameLine.text)
def ButtonsClickable(self, value):
self.labelButton.setEnabled(value)
self.volumeButton.setEnabled(value)
self.modelButton.setEnabled(value)
self.onSampleFromReferenceSelect()
def cleanup(self):
pass
def onLabelChanged(self,myString):
if not myString=='':
self.ButtonsClickable(True)
else:
self.ButtonsClickable(False)
def onSampleFromReferenceSelect(self):
self.referenceButton.enabled = self.inputSelector.currentNode() and self.volumeNameLine.text != ''
def onLabelButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True)
def onVolumeButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text)
def onModelButton(self):
logic = CreateSamplesLogic()
logic.createModel()
def onReferenceButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True, reference=self.inputSelector.currentNode())
#
# CreateSamplesLogic
#
class CreateSamplesLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setVolumeAsBackgroundImage(self, node):
count = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceCompositeNode')
for n in xrange(count):
compNode = slicer.mrmlScene.GetNthNodeByClass(n, 'vtkMRMLSliceCompositeNode')
compNode.SetBackgroundVolumeID(node.GetID())
return True
# Create sample labelmap with same geometry as input volume
def createVolume(self , volumeName, labelmap=False, reference=None):
if volumeName == '':
raise Exception('The name of the output volume cannot be empty')
value = 1
sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
imageData = vtk.vtkImageData()
if reference == None:
mySpacing = (0.5,0.6,0.5)
myOrigin = (20,50,50)
# Do NOT set the spacing and the origin of imageData (vtkImageData)
# The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
imageData.SetDimensions(30,5,15)
imageData.AllocateScalars(vtk.VTK_DOUBLE, 1)
sampleVolumeNode.SetSpacing(mySpacing[0],mySpacing[1],mySpacing[2])
sampleVolumeNode.SetOrigin(myOrigin[0],myOrigin[1],myOrigin[2])
else:
sampleVolumeNode.Copy(reference)
imageData.DeepCopy(reference.GetImageData())
sampleVolumeNode.SetName(volumeName)
sampleVolumeNode.SetAndObserveImageData(imageData)
extent = imageData.GetExtent()
for x in xrange(extent[0], extent[1]+1):
for y in xrange(extent[2], extent[3]+1):
for z in xrange(extent[4], extent[5]+1):
if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
imageData.SetScalarComponentFromDouble(x,y,z,0,value)
else:
imageData.SetScalarComponentFromDouble(x,y,z,0,0)
# Display labelmap
if labelmap:
sampleVolumeNode.SetLabelMap(1)
labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
colorNode = slicer.util.getNode('GenericAnatomyColors')
labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
labelmapVolumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())
else:
volumeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
slicer.mrmlScene.AddNode(volumeDisplayNode)
colorNode = slicer.util.getNode('Grey')
volumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
volumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(volumeDisplayNode.GetID())
self.setVolumeAsBackgroundImage(sampleVolumeNode)
return True
def createModel(self):
print "model"
class CreateSamplesTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def | (self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear(0)
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp()
| setUp | identifier_name |
CreateSamples.py | import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "CreateSamples" # TODO make this more human readable by adding spaces
self.parent.categories = ["Examples"]
self.parent.dependencies = []
self.parent.contributors = ["John Doe (AnyWare Corp.)"] # replace with "Firstname Lastname (Organization)"
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
It performs a simple thresholding on the input volume and optionally captures a screenshot.
"""
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
""" # replace with organization, grant and thanks.
#
# CreateSamplesWidget
#
class CreateSamplesWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
generalParametersCollapsibleButton = ctk.ctkCollapsibleButton()
generalParametersCollapsibleButton.text = "General parameters"
self.layout.addWidget(generalParametersCollapsibleButton)
# Layout within the dummy collapsible button
hlayout = qt.QHBoxLayout(generalParametersCollapsibleButton)
self.label=qt.QLabel("Volume Name:")
hlayout.addWidget(self.label)
self.volumeNameLine=qt.QLineEdit()
hlayout.addWidget(self.volumeNameLine)
self.volumeNameLine.connect('textChanged(QString)', self.onLabelChanged)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Sample From Nothing"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
#
# Sample Label map Button
#
self.labelButton = qt.QPushButton("Create Sample Label Map")
self.labelButton.toolTip = "Create sample label map."
self.labelButton.enabled = True
parametersFormLayout.addRow(self.labelButton)
#
# Sample Volume Button
#
self.volumeButton = qt.QPushButton("Create Sample Volume")
self.volumeButton.toolTip = "Create sample volume."
self.volumeButton.enabled = True
parametersFormLayout.addRow(self.volumeButton)
#
# Sample model Button
#
self.modelButton = qt.QPushButton("Create Sample Model")
self.modelButton.toolTip = "Create sample Model."
self.modelButton.enabled = True
parametersFormLayout.addRow(self.modelButton)
# connections
self.labelButton.connect('clicked(bool)', self.onLabelButton)
self.volumeButton.connect('clicked(bool)', self.onVolumeButton)
self.modelButton.connect('clicked(bool)', self.onModelButton)
parametersCollapsibleButton2 = ctk.ctkCollapsibleButton()
parametersCollapsibleButton2.text = "Sample From example"
self.layout.addWidget(parametersCollapsibleButton2)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton2)
#
# input volume selector
#
self.inputSelector = slicer.qMRMLNodeComboBox()
self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
# Keep the following line as an example
#self.inputSelector.addAttribute( "vtkMRMLScalarVolumeNode", "LabelMap", 0 )
self.inputSelector.selectNodeUponCreation = True
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.noneEnabled = True
self.inputSelector.showHidden = False
self.inputSelector.showChildNodeTypes = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputSelector.setToolTip( "reference image." )
parametersFormLayout.addRow("Reference Volume: ", self.inputSelector)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSampleFromReferenceSelect)
#
# Sample From reference Button
#
self.referenceButton = qt.QPushButton("Create Sample Model from a reference")
self.referenceButton.toolTip = "Create sample Model from a reference."
parametersFormLayout.addRow(self.referenceButton)
self.referenceButton.connect('clicked(bool)', self.onReferenceButton)
# Add vertical spacer
self.layout.addStretch(1)
# Refresh Apply button state
self.onLabelChanged(self.volumeNameLine.text)
def ButtonsClickable(self, value):
self.labelButton.setEnabled(value)
self.volumeButton.setEnabled(value)
self.modelButton.setEnabled(value)
self.onSampleFromReferenceSelect()
def cleanup(self):
pass
def onLabelChanged(self,myString):
if not myString=='':
self.ButtonsClickable(True)
else:
self.ButtonsClickable(False)
def onSampleFromReferenceSelect(self):
self.referenceButton.enabled = self.inputSelector.currentNode() and self.volumeNameLine.text != ''
def onLabelButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True)
def onVolumeButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text)
def onModelButton(self):
logic = CreateSamplesLogic()
logic.createModel()
def onReferenceButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True, reference=self.inputSelector.currentNode())
#
# CreateSamplesLogic
#
class CreateSamplesLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setVolumeAsBackgroundImage(self, node):
count = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceCompositeNode')
for n in xrange(count):
compNode = slicer.mrmlScene.GetNthNodeByClass(n, 'vtkMRMLSliceCompositeNode')
compNode.SetBackgroundVolumeID(node.GetID())
return True
# Create sample labelmap with same geometry as input volume
def createVolume(self , volumeName, labelmap=False, reference=None):
if volumeName == '':
raise Exception('The name of the output volume cannot be empty')
value = 1
sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
imageData = vtk.vtkImageData()
if reference == None:
mySpacing = (0.5,0.6,0.5)
myOrigin = (20,50,50)
# Do NOT set the spacing and the origin of imageData (vtkImageData)
# The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
imageData.SetDimensions(30,5,15)
imageData.AllocateScalars(vtk.VTK_DOUBLE, 1)
sampleVolumeNode.SetSpacing(mySpacing[0],mySpacing[1],mySpacing[2])
sampleVolumeNode.SetOrigin(myOrigin[0],myOrigin[1],myOrigin[2])
else:
sampleVolumeNode.Copy(reference)
imageData.DeepCopy(reference.GetImageData())
sampleVolumeNode.SetName(volumeName)
sampleVolumeNode.SetAndObserveImageData(imageData)
extent = imageData.GetExtent()
for x in xrange(extent[0], extent[1]+1):
for y in xrange(extent[2], extent[3]+1):
for z in xrange(extent[4], extent[5]+1):
if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
imageData.SetScalarComponentFromDouble(x,y,z,0,value)
else:
imageData.SetScalarComponentFromDouble(x,y,z,0,0)
# Display labelmap
if labelmap:
|
else:
volumeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
slicer.mrmlScene.AddNode(volumeDisplayNode)
colorNode = slicer.util.getNode('Grey')
volumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
volumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(volumeDisplayNode.GetID())
self.setVolumeAsBackgroundImage(sampleVolumeNode)
return True
def createModel(self):
print "model"
class CreateSamplesTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setUp(self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear(0)
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp()
| sampleVolumeNode.SetLabelMap(1)
labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
colorNode = slicer.util.getNode('GenericAnatomyColors')
labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
labelmapVolumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID()) | conditional_block |
CreateSamples.py | import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "CreateSamples" # TODO make this more human readable by adding spaces
self.parent.categories = ["Examples"]
self.parent.dependencies = []
self.parent.contributors = ["John Doe (AnyWare Corp.)"] # replace with "Firstname Lastname (Organization)"
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
It performs a simple thresholding on the input volume and optionally captures a screenshot.
"""
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
""" # replace with organization, grant and thanks.
#
# CreateSamplesWidget
#
class CreateSamplesWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
generalParametersCollapsibleButton = ctk.ctkCollapsibleButton()
generalParametersCollapsibleButton.text = "General parameters"
self.layout.addWidget(generalParametersCollapsibleButton)
# Layout within the dummy collapsible button
hlayout = qt.QHBoxLayout(generalParametersCollapsibleButton)
self.label=qt.QLabel("Volume Name:")
hlayout.addWidget(self.label)
self.volumeNameLine=qt.QLineEdit()
hlayout.addWidget(self.volumeNameLine)
self.volumeNameLine.connect('textChanged(QString)', self.onLabelChanged)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Sample From Nothing"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
#
# Sample Label map Button
#
self.labelButton = qt.QPushButton("Create Sample Label Map")
self.labelButton.toolTip = "Create sample label map."
self.labelButton.enabled = True
parametersFormLayout.addRow(self.labelButton)
#
# Sample Volume Button
#
self.volumeButton = qt.QPushButton("Create Sample Volume")
self.volumeButton.toolTip = "Create sample volume."
self.volumeButton.enabled = True
parametersFormLayout.addRow(self.volumeButton)
#
# Sample model Button
#
self.modelButton = qt.QPushButton("Create Sample Model")
self.modelButton.toolTip = "Create sample Model."
self.modelButton.enabled = True
parametersFormLayout.addRow(self.modelButton)
# connections
self.labelButton.connect('clicked(bool)', self.onLabelButton)
self.volumeButton.connect('clicked(bool)', self.onVolumeButton)
self.modelButton.connect('clicked(bool)', self.onModelButton)
parametersCollapsibleButton2 = ctk.ctkCollapsibleButton()
parametersCollapsibleButton2.text = "Sample From example"
self.layout.addWidget(parametersCollapsibleButton2)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton2)
#
# input volume selector
#
self.inputSelector = slicer.qMRMLNodeComboBox()
self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
# Keep the following line as an example
#self.inputSelector.addAttribute( "vtkMRMLScalarVolumeNode", "LabelMap", 0 )
self.inputSelector.selectNodeUponCreation = True
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.noneEnabled = True
self.inputSelector.showHidden = False
self.inputSelector.showChildNodeTypes = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputSelector.setToolTip( "reference image." )
parametersFormLayout.addRow("Reference Volume: ", self.inputSelector)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSampleFromReferenceSelect)
#
# Sample From reference Button
#
self.referenceButton = qt.QPushButton("Create Sample Model from a reference")
self.referenceButton.toolTip = "Create sample Model from a reference."
parametersFormLayout.addRow(self.referenceButton)
self.referenceButton.connect('clicked(bool)', self.onReferenceButton)
# Add vertical spacer
self.layout.addStretch(1)
# Refresh Apply button state
self.onLabelChanged(self.volumeNameLine.text)
def ButtonsClickable(self, value):
self.labelButton.setEnabled(value)
self.volumeButton.setEnabled(value)
self.modelButton.setEnabled(value)
self.onSampleFromReferenceSelect()
def cleanup(self):
pass
def onLabelChanged(self,myString):
if not myString=='':
self.ButtonsClickable(True)
else:
self.ButtonsClickable(False)
def onSampleFromReferenceSelect(self):
self.referenceButton.enabled = self.inputSelector.currentNode() and self.volumeNameLine.text != ''
def onLabelButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True)
def onVolumeButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text)
def onModelButton(self):
logic = CreateSamplesLogic()
logic.createModel()
def onReferenceButton(self):
logic = CreateSamplesLogic()
logic.createVolume(self.volumeNameLine.text, labelmap=True, reference=self.inputSelector.currentNode())
#
# CreateSamplesLogic
#
class CreateSamplesLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setVolumeAsBackgroundImage(self, node):
count = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceCompositeNode')
for n in xrange(count):
compNode = slicer.mrmlScene.GetNthNodeByClass(n, 'vtkMRMLSliceCompositeNode')
compNode.SetBackgroundVolumeID(node.GetID())
return True
# Create sample labelmap with same geometry as input volume
def createVolume(self , volumeName, labelmap=False, reference=None):
if volumeName == '':
raise Exception('The name of the output volume cannot be empty')
value = 1
sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
imageData = vtk.vtkImageData()
if reference == None:
mySpacing = (0.5,0.6,0.5)
myOrigin = (20,50,50)
# Do NOT set the spacing and the origin of imageData (vtkImageData)
# The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
imageData.SetDimensions(30,5,15)
imageData.AllocateScalars(vtk.VTK_DOUBLE, 1)
sampleVolumeNode.SetSpacing(mySpacing[0],mySpacing[1],mySpacing[2])
sampleVolumeNode.SetOrigin(myOrigin[0],myOrigin[1],myOrigin[2])
else:
sampleVolumeNode.Copy(reference)
imageData.DeepCopy(reference.GetImageData())
sampleVolumeNode.SetName(volumeName)
sampleVolumeNode.SetAndObserveImageData(imageData)
extent = imageData.GetExtent()
for x in xrange(extent[0], extent[1]+1):
for y in xrange(extent[2], extent[3]+1):
for z in xrange(extent[4], extent[5]+1):
if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
imageData.SetScalarComponentFromDouble(x,y,z,0,value)
else:
imageData.SetScalarComponentFromDouble(x,y,z,0,0)
# Display labelmap
if labelmap:
sampleVolumeNode.SetLabelMap(1)
labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
colorNode = slicer.util.getNode('GenericAnatomyColors')
labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
labelmapVolumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())
else:
volumeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
slicer.mrmlScene.AddNode(volumeDisplayNode)
colorNode = slicer.util.getNode('Grey')
volumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
volumeDisplayNode.VisibilityOn()
sampleVolumeNode.SetAndObserveDisplayNodeID(volumeDisplayNode.GetID())
self.setVolumeAsBackgroundImage(sampleVolumeNode)
return True
def createModel(self):
print "model"
class CreateSamplesTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setUp(self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear(0)
def runTest(self):
| """Run as few or as many tests as needed here.
"""
self.setUp() | identifier_body |
|
flatten.rs | use std::borrow::Cow;
use std::io::{self, Write};
use tabwriter::TabWriter;
use CliResult;
use config::{Config, Delimiter};
use util;
static USAGE: &'static str = "
Prints flattened records such that fields are labeled separated by a new line.
This mode is particularly useful for viewing one record at a time. Each
record is separated by a special '#' character (on a line by itself), which
can be changed with the --separator flag.
There is also a condensed view (-c or --condense) that will shorten the
contents of each field to provide a summary view.
Usage:
xsv flatten [options] [<input>]
flatten options:
-c, --condense <arg> Limits the length of each field to the value
specified. If the field is UTF-8 encoded, then
<arg> refers to the number of code points.
Otherwise, it refers to the number of bytes.
-s, --separator <arg> A string of characters to write after each record.
When non-empty, a new line is automatically
appended to the separator.
[default: #]
Common options:
-h, --help Display this message
-n, --no-headers When set, the first row will not be interpreted
as headers. When set, the name of each field
will be its index.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(RustcDecodable)]
struct Args {
arg_input: Option<String>,
flag_condense: Option<usize>,
flag_separator: String,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> | {
let args: Args = util::get_args(USAGE, argv)?;
let rconfig = Config::new(&args.arg_input)
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
let mut rdr = rconfig.reader()?;
let headers = rdr.byte_headers()?.clone();
let mut wtr = TabWriter::new(io::stdout());
let mut first = true;
for r in rdr.byte_records() {
if !first && !args.flag_separator.is_empty() {
writeln!(&mut wtr, "{}", args.flag_separator)?;
}
first = false;
let r = r?;
for (i, (header, field)) in headers.iter().zip(&r).enumerate() {
if rconfig.no_headers {
write!(&mut wtr, "{}", i)?;
} else {
wtr.write_all(&header)?;
}
wtr.write_all(b"\t")?;
wtr.write_all(&*util::condense(
Cow::Borrowed(&*field), args.flag_condense))?;
wtr.write_all(b"\n")?;
}
}
wtr.flush()?;
Ok(())
} | identifier_body |
|
flatten.rs | use std::borrow::Cow;
use std::io::{self, Write};
use tabwriter::TabWriter;
use CliResult;
use config::{Config, Delimiter};
use util;
static USAGE: &'static str = "
Prints flattened records such that fields are labeled separated by a new line.
This mode is particularly useful for viewing one record at a time. Each
record is separated by a special '#' character (on a line by itself), which
can be changed with the --separator flag.
There is also a condensed view (-c or --condense) that will shorten the
contents of each field to provide a summary view.
Usage:
xsv flatten [options] [<input>]
flatten options:
-c, --condense <arg> Limits the length of each field to the value
specified. If the field is UTF-8 encoded, then
<arg> refers to the number of code points.
Otherwise, it refers to the number of bytes.
-s, --separator <arg> A string of characters to write after each record.
When non-empty, a new line is automatically
appended to the separator.
[default: #]
| -d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(RustcDecodable)]
struct Args {
arg_input: Option<String>,
flag_condense: Option<usize>,
flag_separator: String,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
let rconfig = Config::new(&args.arg_input)
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
let mut rdr = rconfig.reader()?;
let headers = rdr.byte_headers()?.clone();
let mut wtr = TabWriter::new(io::stdout());
let mut first = true;
for r in rdr.byte_records() {
if !first && !args.flag_separator.is_empty() {
writeln!(&mut wtr, "{}", args.flag_separator)?;
}
first = false;
let r = r?;
for (i, (header, field)) in headers.iter().zip(&r).enumerate() {
if rconfig.no_headers {
write!(&mut wtr, "{}", i)?;
} else {
wtr.write_all(&header)?;
}
wtr.write_all(b"\t")?;
wtr.write_all(&*util::condense(
Cow::Borrowed(&*field), args.flag_condense))?;
wtr.write_all(b"\n")?;
}
}
wtr.flush()?;
Ok(())
} | Common options:
-h, --help Display this message
-n, --no-headers When set, the first row will not be interpreted
as headers. When set, the name of each field
will be its index. | random_line_split |
flatten.rs | use std::borrow::Cow;
use std::io::{self, Write};
use tabwriter::TabWriter;
use CliResult;
use config::{Config, Delimiter};
use util;
static USAGE: &'static str = "
Prints flattened records such that fields are labeled separated by a new line.
This mode is particularly useful for viewing one record at a time. Each
record is separated by a special '#' character (on a line by itself), which
can be changed with the --separator flag.
There is also a condensed view (-c or --condense) that will shorten the
contents of each field to provide a summary view.
Usage:
xsv flatten [options] [<input>]
flatten options:
-c, --condense <arg> Limits the length of each field to the value
specified. If the field is UTF-8 encoded, then
<arg> refers to the number of code points.
Otherwise, it refers to the number of bytes.
-s, --separator <arg> A string of characters to write after each record.
When non-empty, a new line is automatically
appended to the separator.
[default: #]
Common options:
-h, --help Display this message
-n, --no-headers When set, the first row will not be interpreted
as headers. When set, the name of each field
will be its index.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(RustcDecodable)]
struct Args {
arg_input: Option<String>,
flag_condense: Option<usize>,
flag_separator: String,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
let rconfig = Config::new(&args.arg_input)
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
let mut rdr = rconfig.reader()?;
let headers = rdr.byte_headers()?.clone();
let mut wtr = TabWriter::new(io::stdout());
let mut first = true;
for r in rdr.byte_records() {
if !first && !args.flag_separator.is_empty() {
writeln!(&mut wtr, "{}", args.flag_separator)?;
}
first = false;
let r = r?;
for (i, (header, field)) in headers.iter().zip(&r).enumerate() {
if rconfig.no_headers {
write!(&mut wtr, "{}", i)?;
} else |
wtr.write_all(b"\t")?;
wtr.write_all(&*util::condense(
Cow::Borrowed(&*field), args.flag_condense))?;
wtr.write_all(b"\n")?;
}
}
wtr.flush()?;
Ok(())
}
| {
wtr.write_all(&header)?;
} | conditional_block |
flatten.rs | use std::borrow::Cow;
use std::io::{self, Write};
use tabwriter::TabWriter;
use CliResult;
use config::{Config, Delimiter};
use util;
static USAGE: &'static str = "
Prints flattened records such that fields are labeled separated by a new line.
This mode is particularly useful for viewing one record at a time. Each
record is separated by a special '#' character (on a line by itself), which
can be changed with the --separator flag.
There is also a condensed view (-c or --condense) that will shorten the
contents of each field to provide a summary view.
Usage:
xsv flatten [options] [<input>]
flatten options:
-c, --condense <arg> Limits the length of each field to the value
specified. If the field is UTF-8 encoded, then
<arg> refers to the number of code points.
Otherwise, it refers to the number of bytes.
-s, --separator <arg> A string of characters to write after each record.
When non-empty, a new line is automatically
appended to the separator.
[default: #]
Common options:
-h, --help Display this message
-n, --no-headers When set, the first row will not be interpreted
as headers. When set, the name of each field
will be its index.
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(RustcDecodable)]
struct Args {
arg_input: Option<String>,
flag_condense: Option<usize>,
flag_separator: String,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn | (argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?;
let rconfig = Config::new(&args.arg_input)
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers);
let mut rdr = rconfig.reader()?;
let headers = rdr.byte_headers()?.clone();
let mut wtr = TabWriter::new(io::stdout());
let mut first = true;
for r in rdr.byte_records() {
if !first && !args.flag_separator.is_empty() {
writeln!(&mut wtr, "{}", args.flag_separator)?;
}
first = false;
let r = r?;
for (i, (header, field)) in headers.iter().zip(&r).enumerate() {
if rconfig.no_headers {
write!(&mut wtr, "{}", i)?;
} else {
wtr.write_all(&header)?;
}
wtr.write_all(b"\t")?;
wtr.write_all(&*util::condense(
Cow::Borrowed(&*field), args.flag_condense))?;
wtr.write_all(b"\n")?;
}
}
wtr.flush()?;
Ok(())
}
| run | identifier_name |
lib.rs | //! Library that contains utility functions for tests.
//!
//! It also contains a test module, which checks if all source files are covered by `Cargo.toml`
extern crate hyper;
extern crate regex;
extern crate rustc_serialize;
pub mod rosetta_code;
use std::fmt::Debug;
#[allow(dead_code)]
fn main() {}
/// Check if a slice is sorted properly.
pub fn check_sorted<E>(candidate: &[E])
where E: Ord + Clone + Debug
{
let sorted = {
let mut copy = candidate.iter().cloned().collect::<Vec<_>>();
copy.sort();
copy
};
assert_eq!(sorted.as_slice(), candidate);
}
#[test]
fn test_check_sorted() {
let sorted = vec![1, 2, 3, 4, 5];
check_sorted(&sorted);
}
#[test]
#[should_panic]
fn test_check_unsorted() {
let unsorted = vec![1, 3, 2];
check_sorted(&unsorted);
}
#[cfg(test)]
mod tests {
use regex::Regex;
use std::collections::HashSet;
use std::io::{BufReader, BufRead};
use std::fs::{self, File};
use std::path::Path;
/// A test to check if all source files are covered by `Cargo.toml`
#[test]
fn check_sources_covered() {
let sources = get_source_files();
let bins = get_toml_paths();
let not_covered = get_not_covered(&sources, &bins);
if !not_covered.is_empty() {
println!("Error, the following source files are not covered by Cargo.toml:");
for source in ¬_covered {
println!("{}", source);
}
panic!("Please add the previous source files to Cargo.toml");
}
}
/// Returns the names of the source files in the `src` directory
fn get_source_files() -> HashSet<String> {
let paths = fs::read_dir("./src").unwrap();
paths.map(|p| {
p.unwrap()
.path()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap()
})
.filter(|s| s[..].ends_with(".rs"))
.collect()
}
/// Returns the paths of the source files referenced in Cargo.toml
fn get_toml_paths() -> HashSet<String> {
let c_toml = File::open("./Cargo.toml").unwrap();
let reader = BufReader::new(c_toml);
let regex = Regex::new("path = \"(.*)\"").unwrap();
reader.lines()
.filter_map(|l| {
let l = l.unwrap();
regex.captures(&l).map(|c| {
c.at(1)
.map(|s| Path::new(s))
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
})
})
.collect()
}
/// Returns the filenames of the source files which are not covered by Cargo.toml
fn get_not_covered<'a>(sources: &'a HashSet<String>,
paths: &'a HashSet<String>)
-> HashSet<&'a String> |
}
| {
sources.difference(paths).collect()
} | identifier_body |
lib.rs | //! Library that contains utility functions for tests.
//!
//! It also contains a test module, which checks if all source files are covered by `Cargo.toml`
extern crate hyper;
extern crate regex;
extern crate rustc_serialize;
pub mod rosetta_code;
use std::fmt::Debug;
#[allow(dead_code)]
fn main() {}
/// Check if a slice is sorted properly.
pub fn check_sorted<E>(candidate: &[E])
where E: Ord + Clone + Debug
{
let sorted = {
let mut copy = candidate.iter().cloned().collect::<Vec<_>>();
copy.sort();
copy
};
assert_eq!(sorted.as_slice(), candidate);
}
#[test]
fn test_check_sorted() {
let sorted = vec![1, 2, 3, 4, 5];
check_sorted(&sorted);
}
#[test]
#[should_panic]
fn | () {
let unsorted = vec![1, 3, 2];
check_sorted(&unsorted);
}
#[cfg(test)]
mod tests {
use regex::Regex;
use std::collections::HashSet;
use std::io::{BufReader, BufRead};
use std::fs::{self, File};
use std::path::Path;
/// A test to check if all source files are covered by `Cargo.toml`
#[test]
fn check_sources_covered() {
let sources = get_source_files();
let bins = get_toml_paths();
let not_covered = get_not_covered(&sources, &bins);
if !not_covered.is_empty() {
println!("Error, the following source files are not covered by Cargo.toml:");
for source in ¬_covered {
println!("{}", source);
}
panic!("Please add the previous source files to Cargo.toml");
}
}
/// Returns the names of the source files in the `src` directory
fn get_source_files() -> HashSet<String> {
let paths = fs::read_dir("./src").unwrap();
paths.map(|p| {
p.unwrap()
.path()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap()
})
.filter(|s| s[..].ends_with(".rs"))
.collect()
}
/// Returns the paths of the source files referenced in Cargo.toml
fn get_toml_paths() -> HashSet<String> {
let c_toml = File::open("./Cargo.toml").unwrap();
let reader = BufReader::new(c_toml);
let regex = Regex::new("path = \"(.*)\"").unwrap();
reader.lines()
.filter_map(|l| {
let l = l.unwrap();
regex.captures(&l).map(|c| {
c.at(1)
.map(|s| Path::new(s))
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
})
})
.collect()
}
/// Returns the filenames of the source files which are not covered by Cargo.toml
fn get_not_covered<'a>(sources: &'a HashSet<String>,
paths: &'a HashSet<String>)
-> HashSet<&'a String> {
sources.difference(paths).collect()
}
}
| test_check_unsorted | identifier_name |
lib.rs | //! Library that contains utility functions for tests.
//!
//! It also contains a test module, which checks if all source files are covered by `Cargo.toml`
extern crate hyper;
extern crate regex;
extern crate rustc_serialize;
pub mod rosetta_code;
use std::fmt::Debug;
#[allow(dead_code)]
fn main() {}
/// Check if a slice is sorted properly.
pub fn check_sorted<E>(candidate: &[E])
where E: Ord + Clone + Debug
{
let sorted = {
let mut copy = candidate.iter().cloned().collect::<Vec<_>>();
copy.sort();
copy
};
assert_eq!(sorted.as_slice(), candidate);
}
#[test]
fn test_check_sorted() {
let sorted = vec![1, 2, 3, 4, 5];
check_sorted(&sorted);
}
#[test]
#[should_panic]
fn test_check_unsorted() {
let unsorted = vec![1, 3, 2];
check_sorted(&unsorted);
}
#[cfg(test)]
mod tests {
use regex::Regex;
use std::collections::HashSet;
use std::io::{BufReader, BufRead};
use std::fs::{self, File};
use std::path::Path;
/// A test to check if all source files are covered by `Cargo.toml`
#[test]
fn check_sources_covered() {
let sources = get_source_files();
let bins = get_toml_paths();
let not_covered = get_not_covered(&sources, &bins);
if !not_covered.is_empty() |
}
/// Returns the names of the source files in the `src` directory
fn get_source_files() -> HashSet<String> {
let paths = fs::read_dir("./src").unwrap();
paths.map(|p| {
p.unwrap()
.path()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap()
})
.filter(|s| s[..].ends_with(".rs"))
.collect()
}
/// Returns the paths of the source files referenced in Cargo.toml
fn get_toml_paths() -> HashSet<String> {
let c_toml = File::open("./Cargo.toml").unwrap();
let reader = BufReader::new(c_toml);
let regex = Regex::new("path = \"(.*)\"").unwrap();
reader.lines()
.filter_map(|l| {
let l = l.unwrap();
regex.captures(&l).map(|c| {
c.at(1)
.map(|s| Path::new(s))
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
})
})
.collect()
}
/// Returns the filenames of the source files which are not covered by Cargo.toml
fn get_not_covered<'a>(sources: &'a HashSet<String>,
paths: &'a HashSet<String>)
-> HashSet<&'a String> {
sources.difference(paths).collect()
}
}
| {
println!("Error, the following source files are not covered by Cargo.toml:");
for source in ¬_covered {
println!("{}", source);
}
panic!("Please add the previous source files to Cargo.toml");
} | conditional_block |
lib.rs | //! Library that contains utility functions for tests.
//!
//! It also contains a test module, which checks if all source files are covered by `Cargo.toml`
extern crate hyper;
extern crate regex;
extern crate rustc_serialize;
pub mod rosetta_code;
use std::fmt::Debug;
#[allow(dead_code)]
fn main() {}
/// Check if a slice is sorted properly.
pub fn check_sorted<E>(candidate: &[E])
where E: Ord + Clone + Debug
{
let sorted = {
let mut copy = candidate.iter().cloned().collect::<Vec<_>>();
copy.sort();
copy
};
assert_eq!(sorted.as_slice(), candidate);
}
#[test]
fn test_check_sorted() {
let sorted = vec![1, 2, 3, 4, 5];
check_sorted(&sorted);
}
#[test]
#[should_panic]
fn test_check_unsorted() {
let unsorted = vec![1, 3, 2];
check_sorted(&unsorted);
}
#[cfg(test)]
mod tests {
use regex::Regex;
use std::collections::HashSet;
use std::io::{BufReader, BufRead};
use std::fs::{self, File};
use std::path::Path;
/// A test to check if all source files are covered by `Cargo.toml`
#[test]
fn check_sources_covered() {
let sources = get_source_files();
let bins = get_toml_paths();
let not_covered = get_not_covered(&sources, &bins);
if !not_covered.is_empty() {
println!("Error, the following source files are not covered by Cargo.toml:");
for source in ¬_covered {
println!("{}", source);
}
panic!("Please add the previous source files to Cargo.toml");
}
}
/// Returns the names of the source files in the `src` directory
fn get_source_files() -> HashSet<String> {
let paths = fs::read_dir("./src").unwrap();
paths.map(|p| {
p.unwrap()
.path()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap()
})
.filter(|s| s[..].ends_with(".rs"))
.collect() | /// Returns the paths of the source files referenced in Cargo.toml
fn get_toml_paths() -> HashSet<String> {
let c_toml = File::open("./Cargo.toml").unwrap();
let reader = BufReader::new(c_toml);
let regex = Regex::new("path = \"(.*)\"").unwrap();
reader.lines()
.filter_map(|l| {
let l = l.unwrap();
regex.captures(&l).map(|c| {
c.at(1)
.map(|s| Path::new(s))
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
})
})
.collect()
}
/// Returns the filenames of the source files which are not covered by Cargo.toml
fn get_not_covered<'a>(sources: &'a HashSet<String>,
paths: &'a HashSet<String>)
-> HashSet<&'a String> {
sources.difference(paths).collect()
}
} | }
| random_line_split |
variablesView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RunOnceScheduler, sequence } from 'vs/base/common/async';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import { IHighlightEvent, IActionProvider, ITree, IDataSource, IRenderer, IAccessibilityProvider } from 'vs/base/parts/tree/browser/tree';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { TreeViewsViewletPanel, IViewletViewOptions, IViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IDebugService, State, CONTEXT_VARIABLES_FOCUSED, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Variable, Scope } from 'vs/workbench/parts/debug/common/debugModel';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MenuId } from 'vs/platform/actions/common/actions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { once } from 'vs/base/common/event';
import { twistiePixels, renderViewTree, IVariableTemplateData, BaseDebugController, renderRenameBox, renderVariable } from 'vs/workbench/parts/debug/electron-browser/baseDebugView';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionItem } from 'vs/base/common/actions';
import { SetValueAction, AddToWatchExpressionsAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { WorkbenchTree, IListService } from 'vs/platform/list/browser/listService';
const $ = dom.$;
export class VariablesView extends TreeViewsViewletPanel {
private static readonly MEMENTO = 'variablesview.memento';
private onFocusStackFrameScheduler: RunOnceScheduler;
private settings: any;
private expandedElements: any[];
private needsRefresh: boolean;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IListService private listService: IListService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IThemeService private themeService: IThemeService
) {
super({ ...(options as IViewOptions), ariaHeaderLabel: nls.localize('variablesSection', "Variables Section") }, keybindingService, contextMenuService);
this.settings = options.viewletSettings;
this.expandedElements = [];
// Use scheduler to prevent unnecessary flashing
this.onFocusStackFrameScheduler = new RunOnceScheduler(() => {
// Remember expanded elements when there are some (otherwise don't override/erase the previous ones)
const expanded = this.tree.getExpandedElements();
if (expanded.length > 0) {
this.expandedElements = expanded;
}
// Always clear tree highlight to avoid ending up in a broken state #12203
this.tree.clearHighlight();
this.needsRefresh = false;
this.tree.refresh().then(() => {
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
return sequence(this.expandedElements.map(e => () => this.tree.expand(e))).then(() => {
// If there is no preserved expansion state simply expand the first scope
if (stackFrame && this.tree.getExpandedElements().length === 0) {
return stackFrame.getScopes().then(scopes => {
if (scopes.length > 0 && !scopes[0].expensive) {
return this.tree.expand(scopes[0]);
}
return undefined;
});
}
return undefined;
});
}).done(null, errors.onUnexpectedError);
}, 400);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-variables');
this.treeContainer = renderViewTree(container);
this.tree = new WorkbenchTree(this.treeContainer, {
dataSource: new VariablesDataSource(),
renderer: this.instantiationService.createInstance(VariablesRenderer),
accessibilityProvider: new VariablesAccessibilityProvider(),
controller: this.instantiationService.createInstance(VariablesController, new VariablesActionProvider(this.debugService, this.keybindingService), MenuId.DebugVariablesContext)
}, {
ariaLabel: nls.localize('variablesAriaTreeLabel', "Debug Variables"),
twistiePixels,
keyboardSupport: false
}, this.contextKeyService, this.listService, this.themeService);
CONTEXT_VARIABLES_FOCUSED.bindTo(this.tree.contextKeyService);
const viewModel = this.debugService.getViewModel();
this.tree.setInput(viewModel);
const collapseAction = new CollapseAction(this.tree, false, 'explorer-action collapse-explorer');
this.toolbar.setActions([collapseAction])();
this.disposables.push(viewModel.onDidFocusStackFrame(sf => {
if (!this.isVisible() || !this.isExpanded()) {
this.needsRefresh = true;
return;
}
// Refresh the tree immediately if it is not visible.
// Otherwise postpone the refresh until user stops stepping.
if (!this.tree.getContentHeight() || sf.explicit) {
this.onFocusStackFrameScheduler.schedule(0);
} else {
this.onFocusStackFrameScheduler.schedule();
}
}));
this.disposables.push(this.debugService.onDidChangeState(state => {
collapseAction.enabled = state === State.Running || state === State.Stopped;
}));
this.disposables.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Variable)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
once(this.tree.onDidChangeHighlight)((e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public setExpanded(expanded: boolean): void {
super.setExpanded(expanded);
if (expanded && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
}
public setVisible(visible: boolean): TPromise<void> {
return super.setVisible(visible).then(() => {
if (visible && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
});
}
public shutdown(): void {
this.settings[VariablesView.MEMENTO] = !this.isExpanded();
super.shutdown();
}
}
class VariablesActionProvider implements IActionProvider {
constructor(private debugService: IDebugService, private keybindingService: IKeybindingService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
// Only show context menu on "real" variables. Not on array chunk nodes.
return element instanceof Variable && !!element.value;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
const variable = <Variable>element;
actions.push(new SetValueAction(SetValueAction.ID, SetValueAction.LABEL, variable, this.debugService, this.keybindingService));
actions.push(new CopyValueAction(CopyValueAction.ID, CopyValueAction.LABEL, variable, this.debugService));
actions.push(new Separator());
actions.push(new AddToWatchExpressionsAction(AddToWatchExpressionsAction.ID, AddToWatchExpressionsAction.LABEL, variable, this.debugService, this.keybindingService));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class VariablesDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
if (element instanceof ViewModel || element instanceof Scope) {
return true;
}
let variable = <Variable>element;
return variable.hasChildren && !equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof ViewModel) {
const focusedStackFrame = (<ViewModel>element).focusedStackFrame;
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <Scope>element;
return scope.getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export class VariablesRenderer implements IRenderer {
private static readonly SCOPE_TEMPLATE_ID = 'scope';
private static readonly VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@IDebugService private debugService: IDebugService,
@IContextViewService private contextViewService: IContextViewService,
@IThemeService private themeService: IThemeService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
return 22;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, this.themeService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
class VariablesAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<Scope>element).name);
}
if (element instanceof Variable) |
return null;
}
}
class VariablesController extends BaseDebugController {
protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
const process = this.debugService.getViewModel().focusedProcess;
if (element instanceof Variable && event.detail === 2 && process && process.session.capabilities.supportsSetVariable) {
const expression = <IExpression>element;
this.debugService.getViewModel().setSelectedExpression(expression);
return true;
}
return super.onLeftClick(tree, element, event);
}
}
| {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<Variable>element).name, (<Variable>element).value);
} | conditional_block |
variablesView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RunOnceScheduler, sequence } from 'vs/base/common/async';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import { IHighlightEvent, IActionProvider, ITree, IDataSource, IRenderer, IAccessibilityProvider } from 'vs/base/parts/tree/browser/tree';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { TreeViewsViewletPanel, IViewletViewOptions, IViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IDebugService, State, CONTEXT_VARIABLES_FOCUSED, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Variable, Scope } from 'vs/workbench/parts/debug/common/debugModel';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MenuId } from 'vs/platform/actions/common/actions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { once } from 'vs/base/common/event';
import { twistiePixels, renderViewTree, IVariableTemplateData, BaseDebugController, renderRenameBox, renderVariable } from 'vs/workbench/parts/debug/electron-browser/baseDebugView';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionItem } from 'vs/base/common/actions';
import { SetValueAction, AddToWatchExpressionsAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { WorkbenchTree, IListService } from 'vs/platform/list/browser/listService';
const $ = dom.$;
export class VariablesView extends TreeViewsViewletPanel {
private static readonly MEMENTO = 'variablesview.memento';
private onFocusStackFrameScheduler: RunOnceScheduler;
private settings: any;
private expandedElements: any[];
private needsRefresh: boolean;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IListService private listService: IListService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IThemeService private themeService: IThemeService
) {
super({ ...(options as IViewOptions), ariaHeaderLabel: nls.localize('variablesSection', "Variables Section") }, keybindingService, contextMenuService);
this.settings = options.viewletSettings;
this.expandedElements = [];
// Use scheduler to prevent unnecessary flashing
this.onFocusStackFrameScheduler = new RunOnceScheduler(() => {
// Remember expanded elements when there are some (otherwise don't override/erase the previous ones)
const expanded = this.tree.getExpandedElements();
if (expanded.length > 0) {
this.expandedElements = expanded;
}
// Always clear tree highlight to avoid ending up in a broken state #12203
this.tree.clearHighlight();
this.needsRefresh = false;
this.tree.refresh().then(() => {
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
return sequence(this.expandedElements.map(e => () => this.tree.expand(e))).then(() => {
// If there is no preserved expansion state simply expand the first scope
if (stackFrame && this.tree.getExpandedElements().length === 0) {
return stackFrame.getScopes().then(scopes => {
if (scopes.length > 0 && !scopes[0].expensive) {
return this.tree.expand(scopes[0]);
}
return undefined;
});
}
return undefined;
});
}).done(null, errors.onUnexpectedError);
}, 400);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-variables');
this.treeContainer = renderViewTree(container);
this.tree = new WorkbenchTree(this.treeContainer, {
dataSource: new VariablesDataSource(),
renderer: this.instantiationService.createInstance(VariablesRenderer),
accessibilityProvider: new VariablesAccessibilityProvider(),
controller: this.instantiationService.createInstance(VariablesController, new VariablesActionProvider(this.debugService, this.keybindingService), MenuId.DebugVariablesContext)
}, {
ariaLabel: nls.localize('variablesAriaTreeLabel', "Debug Variables"),
twistiePixels,
keyboardSupport: false
}, this.contextKeyService, this.listService, this.themeService);
CONTEXT_VARIABLES_FOCUSED.bindTo(this.tree.contextKeyService);
const viewModel = this.debugService.getViewModel();
this.tree.setInput(viewModel);
const collapseAction = new CollapseAction(this.tree, false, 'explorer-action collapse-explorer');
this.toolbar.setActions([collapseAction])();
this.disposables.push(viewModel.onDidFocusStackFrame(sf => {
if (!this.isVisible() || !this.isExpanded()) {
this.needsRefresh = true;
return;
}
// Refresh the tree immediately if it is not visible.
// Otherwise postpone the refresh until user stops stepping.
if (!this.tree.getContentHeight() || sf.explicit) {
this.onFocusStackFrameScheduler.schedule(0);
} else {
this.onFocusStackFrameScheduler.schedule();
}
}));
this.disposables.push(this.debugService.onDidChangeState(state => {
collapseAction.enabled = state === State.Running || state === State.Stopped;
}));
this.disposables.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Variable)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
once(this.tree.onDidChangeHighlight)((e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public setExpanded(expanded: boolean): void {
super.setExpanded(expanded);
if (expanded && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
}
public setVisible(visible: boolean): TPromise<void> {
return super.setVisible(visible).then(() => {
if (visible && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
});
}
public shutdown(): void {
this.settings[VariablesView.MEMENTO] = !this.isExpanded();
super.shutdown();
}
}
class VariablesActionProvider implements IActionProvider {
constructor(private debugService: IDebugService, private keybindingService: IKeybindingService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
// Only show context menu on "real" variables. Not on array chunk nodes.
return element instanceof Variable && !!element.value;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
const variable = <Variable>element;
actions.push(new SetValueAction(SetValueAction.ID, SetValueAction.LABEL, variable, this.debugService, this.keybindingService));
actions.push(new CopyValueAction(CopyValueAction.ID, CopyValueAction.LABEL, variable, this.debugService));
actions.push(new Separator());
actions.push(new AddToWatchExpressionsAction(AddToWatchExpressionsAction.ID, AddToWatchExpressionsAction.LABEL, variable, this.debugService, this.keybindingService));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class | implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
if (element instanceof ViewModel || element instanceof Scope) {
return true;
}
let variable = <Variable>element;
return variable.hasChildren && !equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof ViewModel) {
const focusedStackFrame = (<ViewModel>element).focusedStackFrame;
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <Scope>element;
return scope.getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export class VariablesRenderer implements IRenderer {
private static readonly SCOPE_TEMPLATE_ID = 'scope';
private static readonly VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@IDebugService private debugService: IDebugService,
@IContextViewService private contextViewService: IContextViewService,
@IThemeService private themeService: IThemeService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
return 22;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, this.themeService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
class VariablesAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<Scope>element).name);
}
if (element instanceof Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<Variable>element).name, (<Variable>element).value);
}
return null;
}
}
class VariablesController extends BaseDebugController {
protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
const process = this.debugService.getViewModel().focusedProcess;
if (element instanceof Variable && event.detail === 2 && process && process.session.capabilities.supportsSetVariable) {
const expression = <IExpression>element;
this.debugService.getViewModel().setSelectedExpression(expression);
return true;
}
return super.onLeftClick(tree, element, event);
}
}
| VariablesDataSource | identifier_name |
variablesView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RunOnceScheduler, sequence } from 'vs/base/common/async';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import { IHighlightEvent, IActionProvider, ITree, IDataSource, IRenderer, IAccessibilityProvider } from 'vs/base/parts/tree/browser/tree';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { TreeViewsViewletPanel, IViewletViewOptions, IViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IDebugService, State, CONTEXT_VARIABLES_FOCUSED, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Variable, Scope } from 'vs/workbench/parts/debug/common/debugModel';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MenuId } from 'vs/platform/actions/common/actions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { once } from 'vs/base/common/event';
import { twistiePixels, renderViewTree, IVariableTemplateData, BaseDebugController, renderRenameBox, renderVariable } from 'vs/workbench/parts/debug/electron-browser/baseDebugView';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionItem } from 'vs/base/common/actions';
import { SetValueAction, AddToWatchExpressionsAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { WorkbenchTree, IListService } from 'vs/platform/list/browser/listService';
const $ = dom.$;
export class VariablesView extends TreeViewsViewletPanel {
private static readonly MEMENTO = 'variablesview.memento';
private onFocusStackFrameScheduler: RunOnceScheduler;
private settings: any;
private expandedElements: any[];
private needsRefresh: boolean;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IListService private listService: IListService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IThemeService private themeService: IThemeService
) {
super({ ...(options as IViewOptions), ariaHeaderLabel: nls.localize('variablesSection', "Variables Section") }, keybindingService, contextMenuService);
this.settings = options.viewletSettings;
this.expandedElements = [];
// Use scheduler to prevent unnecessary flashing
this.onFocusStackFrameScheduler = new RunOnceScheduler(() => {
// Remember expanded elements when there are some (otherwise don't override/erase the previous ones)
const expanded = this.tree.getExpandedElements();
if (expanded.length > 0) {
this.expandedElements = expanded;
}
// Always clear tree highlight to avoid ending up in a broken state #12203
this.tree.clearHighlight();
this.needsRefresh = false;
this.tree.refresh().then(() => {
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
return sequence(this.expandedElements.map(e => () => this.tree.expand(e))).then(() => {
// If there is no preserved expansion state simply expand the first scope
if (stackFrame && this.tree.getExpandedElements().length === 0) {
return stackFrame.getScopes().then(scopes => {
if (scopes.length > 0 && !scopes[0].expensive) {
return this.tree.expand(scopes[0]);
}
return undefined;
});
}
return undefined;
});
}).done(null, errors.onUnexpectedError);
}, 400);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-variables');
this.treeContainer = renderViewTree(container);
this.tree = new WorkbenchTree(this.treeContainer, {
dataSource: new VariablesDataSource(),
renderer: this.instantiationService.createInstance(VariablesRenderer),
accessibilityProvider: new VariablesAccessibilityProvider(),
controller: this.instantiationService.createInstance(VariablesController, new VariablesActionProvider(this.debugService, this.keybindingService), MenuId.DebugVariablesContext)
}, {
ariaLabel: nls.localize('variablesAriaTreeLabel', "Debug Variables"),
twistiePixels,
keyboardSupport: false
}, this.contextKeyService, this.listService, this.themeService);
CONTEXT_VARIABLES_FOCUSED.bindTo(this.tree.contextKeyService);
const viewModel = this.debugService.getViewModel();
this.tree.setInput(viewModel);
const collapseAction = new CollapseAction(this.tree, false, 'explorer-action collapse-explorer');
this.toolbar.setActions([collapseAction])();
this.disposables.push(viewModel.onDidFocusStackFrame(sf => {
if (!this.isVisible() || !this.isExpanded()) {
this.needsRefresh = true;
return;
}
// Refresh the tree immediately if it is not visible.
// Otherwise postpone the refresh until user stops stepping.
if (!this.tree.getContentHeight() || sf.explicit) {
this.onFocusStackFrameScheduler.schedule(0);
} else {
this.onFocusStackFrameScheduler.schedule();
}
}));
this.disposables.push(this.debugService.onDidChangeState(state => {
collapseAction.enabled = state === State.Running || state === State.Stopped;
}));
this.disposables.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Variable)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
once(this.tree.onDidChangeHighlight)((e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public setExpanded(expanded: boolean): void {
super.setExpanded(expanded);
if (expanded && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
}
public setVisible(visible: boolean): TPromise<void> {
return super.setVisible(visible).then(() => {
if (visible && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
});
}
public shutdown(): void {
this.settings[VariablesView.MEMENTO] = !this.isExpanded();
super.shutdown();
}
}
class VariablesActionProvider implements IActionProvider {
constructor(private debugService: IDebugService, private keybindingService: IKeybindingService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean |
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
// Only show context menu on "real" variables. Not on array chunk nodes.
return element instanceof Variable && !!element.value;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
const variable = <Variable>element;
actions.push(new SetValueAction(SetValueAction.ID, SetValueAction.LABEL, variable, this.debugService, this.keybindingService));
actions.push(new CopyValueAction(CopyValueAction.ID, CopyValueAction.LABEL, variable, this.debugService));
actions.push(new Separator());
actions.push(new AddToWatchExpressionsAction(AddToWatchExpressionsAction.ID, AddToWatchExpressionsAction.LABEL, variable, this.debugService, this.keybindingService));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class VariablesDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
if (element instanceof ViewModel || element instanceof Scope) {
return true;
}
let variable = <Variable>element;
return variable.hasChildren && !equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof ViewModel) {
const focusedStackFrame = (<ViewModel>element).focusedStackFrame;
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <Scope>element;
return scope.getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export class VariablesRenderer implements IRenderer {
private static readonly SCOPE_TEMPLATE_ID = 'scope';
private static readonly VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@IDebugService private debugService: IDebugService,
@IContextViewService private contextViewService: IContextViewService,
@IThemeService private themeService: IThemeService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
return 22;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, this.themeService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
class VariablesAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<Scope>element).name);
}
if (element instanceof Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<Variable>element).name, (<Variable>element).value);
}
return null;
}
}
class VariablesController extends BaseDebugController {
protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
const process = this.debugService.getViewModel().focusedProcess;
if (element instanceof Variable && event.detail === 2 && process && process.session.capabilities.supportsSetVariable) {
const expression = <IExpression>element;
this.debugService.getViewModel().setSelectedExpression(expression);
return true;
}
return super.onLeftClick(tree, element, event);
}
}
| {
return false;
} | identifier_body |
variablesView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RunOnceScheduler, sequence } from 'vs/base/common/async';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import { IHighlightEvent, IActionProvider, ITree, IDataSource, IRenderer, IAccessibilityProvider } from 'vs/base/parts/tree/browser/tree';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { TreeViewsViewletPanel, IViewletViewOptions, IViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IDebugService, State, CONTEXT_VARIABLES_FOCUSED, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Variable, Scope } from 'vs/workbench/parts/debug/common/debugModel';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MenuId } from 'vs/platform/actions/common/actions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { once } from 'vs/base/common/event';
import { twistiePixels, renderViewTree, IVariableTemplateData, BaseDebugController, renderRenameBox, renderVariable } from 'vs/workbench/parts/debug/electron-browser/baseDebugView';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionItem } from 'vs/base/common/actions';
import { SetValueAction, AddToWatchExpressionsAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { WorkbenchTree, IListService } from 'vs/platform/list/browser/listService';
const $ = dom.$;
export class VariablesView extends TreeViewsViewletPanel {
private static readonly MEMENTO = 'variablesview.memento';
private onFocusStackFrameScheduler: RunOnceScheduler;
private settings: any;
private expandedElements: any[];
private needsRefresh: boolean;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IListService private listService: IListService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IThemeService private themeService: IThemeService
) {
super({ ...(options as IViewOptions), ariaHeaderLabel: nls.localize('variablesSection', "Variables Section") }, keybindingService, contextMenuService);
this.settings = options.viewletSettings;
this.expandedElements = [];
// Use scheduler to prevent unnecessary flashing
this.onFocusStackFrameScheduler = new RunOnceScheduler(() => {
// Remember expanded elements when there are some (otherwise don't override/erase the previous ones)
const expanded = this.tree.getExpandedElements();
if (expanded.length > 0) {
this.expandedElements = expanded;
}
// Always clear tree highlight to avoid ending up in a broken state #12203
this.tree.clearHighlight();
this.needsRefresh = false;
this.tree.refresh().then(() => {
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
return sequence(this.expandedElements.map(e => () => this.tree.expand(e))).then(() => {
// If there is no preserved expansion state simply expand the first scope
if (stackFrame && this.tree.getExpandedElements().length === 0) {
return stackFrame.getScopes().then(scopes => {
if (scopes.length > 0 && !scopes[0].expensive) {
return this.tree.expand(scopes[0]);
}
return undefined;
});
}
return undefined;
});
}).done(null, errors.onUnexpectedError);
}, 400);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-variables');
this.treeContainer = renderViewTree(container);
this.tree = new WorkbenchTree(this.treeContainer, {
dataSource: new VariablesDataSource(),
renderer: this.instantiationService.createInstance(VariablesRenderer),
accessibilityProvider: new VariablesAccessibilityProvider(),
controller: this.instantiationService.createInstance(VariablesController, new VariablesActionProvider(this.debugService, this.keybindingService), MenuId.DebugVariablesContext)
}, {
ariaLabel: nls.localize('variablesAriaTreeLabel', "Debug Variables"),
twistiePixels,
keyboardSupport: false
}, this.contextKeyService, this.listService, this.themeService);
CONTEXT_VARIABLES_FOCUSED.bindTo(this.tree.contextKeyService);
const viewModel = this.debugService.getViewModel();
this.tree.setInput(viewModel);
const collapseAction = new CollapseAction(this.tree, false, 'explorer-action collapse-explorer');
this.toolbar.setActions([collapseAction])();
this.disposables.push(viewModel.onDidFocusStackFrame(sf => {
if (!this.isVisible() || !this.isExpanded()) {
this.needsRefresh = true;
return;
}
// Refresh the tree immediately if it is not visible.
// Otherwise postpone the refresh until user stops stepping.
if (!this.tree.getContentHeight() || sf.explicit) {
this.onFocusStackFrameScheduler.schedule(0);
} else {
this.onFocusStackFrameScheduler.schedule();
}
}));
this.disposables.push(this.debugService.onDidChangeState(state => {
collapseAction.enabled = state === State.Running || state === State.Stopped;
}));
this.disposables.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Variable)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
once(this.tree.onDidChangeHighlight)((e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public setExpanded(expanded: boolean): void {
super.setExpanded(expanded);
if (expanded && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
}
public setVisible(visible: boolean): TPromise<void> {
return super.setVisible(visible).then(() => {
if (visible && this.needsRefresh) {
this.onFocusStackFrameScheduler.schedule();
}
});
}
public shutdown(): void {
this.settings[VariablesView.MEMENTO] = !this.isExpanded();
super.shutdown();
}
}
class VariablesActionProvider implements IActionProvider {
constructor(private debugService: IDebugService, private keybindingService: IKeybindingService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
// Only show context menu on "real" variables. Not on array chunk nodes.
return element instanceof Variable && !!element.value;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
const variable = <Variable>element;
actions.push(new SetValueAction(SetValueAction.ID, SetValueAction.LABEL, variable, this.debugService, this.keybindingService));
actions.push(new CopyValueAction(CopyValueAction.ID, CopyValueAction.LABEL, variable, this.debugService));
actions.push(new Separator());
actions.push(new AddToWatchExpressionsAction(AddToWatchExpressionsAction.ID, AddToWatchExpressionsAction.LABEL, variable, this.debugService, this.keybindingService));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class VariablesDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
if (element instanceof ViewModel || element instanceof Scope) {
return true;
}
let variable = <Variable>element;
return variable.hasChildren && !equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof ViewModel) {
const focusedStackFrame = (<ViewModel>element).focusedStackFrame;
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <Scope>element;
return scope.getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export class VariablesRenderer implements IRenderer {
private static readonly SCOPE_TEMPLATE_ID = 'scope';
private static readonly VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@IDebugService private debugService: IDebugService,
@IContextViewService private contextViewService: IContextViewService,
@IThemeService private themeService: IThemeService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
return 22;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, this.themeService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
class VariablesAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<Scope>element).name);
}
if (element instanceof Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<Variable>element).name, (<Variable>element).value); |
return null;
}
}
class VariablesController extends BaseDebugController {
protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
const process = this.debugService.getViewModel().focusedProcess;
if (element instanceof Variable && event.detail === 2 && process && process.session.capabilities.supportsSetVariable) {
const expression = <IExpression>element;
this.debugService.getViewModel().setSelectedExpression(expression);
return true;
}
return super.onLeftClick(tree, element, event);
}
} | } | random_line_split |
rcp_log_linter.py | #!/usr/bin/env python3
import optparse
class RcpLogValidator(object):
MAX_ERRORS = 25
MAX_INTERVAL_STEP_MS = 3000
MIN_INTERVAL_STEP_MS = 1
def __init__(self):
self.interval = 0
self.columns = 0
def _count_commas(self, line):
return line.count(',')
def _validate_column_count(self, line, line_no):
columns = self._count_commas(line)
if columns == self.columns:
return True
# If here we failed. Print msg.
print(("Error: Column count mismatch on line {}. Expected {}, " +
"found {}").format(line_no, self.columns, columns))
return False
def _validate_interval_time(self, line, line_no):
try:
interval = int(line.split(',', 1)[0])
except ValueError:
interval = 0
# Deal with initialization.
if self.interval == 0:
self.interval = interval
return True
interval_min = self.interval + self.MIN_INTERVAL_STEP_MS
interval_max = self.interval + self.MAX_INTERVAL_STEP_MS
if interval_min <= interval and interval <= interval_max:
self.interval = interval
return True
# If here we failed. Print msg.
print(("Error: Inconsistent interval value on line {}. Expected " +
"{} - {}, found {}").format(line_no, interval_min, \
interval_max, interval))
return False
def _validate_line(self, line, line_no='?'):
# Check if its a header line.
if '|' in line:
self.columns = self._count_commas(line)
return True
return \
self._validate_column_count(line, line_no) and \
self._validate_interval_time(line, line_no)
def validate_logfile(self, log_path):
errors = 0
line_no = 0
with open(log_path, 'r') as fil:
for line in fil:
|
print()
print("=== Final Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Errors Found: {}".format(errors))
print()
def clean_logfile(self, input_path, output_path):
errors = 0
line_no = 0
with open(input_path, 'r') as file_in:
with open(output_path, 'w') as file_out:
for line in file_in:
line_no += 1
if not self._validate_line(line, line_no):
errors += 1
else:
file_out.write(line)
print()
print("=== Processing Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Lines Pruned: {}".format(errors))
print()
def main():
parser = optparse.OptionParser()
parser.add_option('-f', '--filename',
dest="log_file",
help="Path of log file to process")
parser.add_option('-o', '--output',
dest="out_file",
help="Path to output file of processed data")
options, remainder = parser.parse_args()
if not options.log_file:
parser.error("No log file path given")
rcplv = RcpLogValidator()
if not options.out_file:
rcplv.validate_logfile(options.log_file)
else:
rcplv.clean_logfile(options.log_file, options.out_file)
if __name__ == '__main__':
main()
| line_no += 1
if errors >= self.MAX_ERRORS:
break
if not self._validate_line(line, line_no):
errors += 1 | conditional_block |
rcp_log_linter.py | #!/usr/bin/env python3
import optparse
class RcpLogValidator(object):
MAX_ERRORS = 25
MAX_INTERVAL_STEP_MS = 3000
MIN_INTERVAL_STEP_MS = 1
def __init__(self):
self.interval = 0
self.columns = 0
def _count_commas(self, line):
return line.count(',')
def _validate_column_count(self, line, line_no):
columns = self._count_commas(line)
if columns == self.columns:
return True
# If here we failed. Print msg. |
def _validate_interval_time(self, line, line_no):
try:
interval = int(line.split(',', 1)[0])
except ValueError:
interval = 0
# Deal with initialization.
if self.interval == 0:
self.interval = interval
return True
interval_min = self.interval + self.MIN_INTERVAL_STEP_MS
interval_max = self.interval + self.MAX_INTERVAL_STEP_MS
if interval_min <= interval and interval <= interval_max:
self.interval = interval
return True
# If here we failed. Print msg.
print(("Error: Inconsistent interval value on line {}. Expected " +
"{} - {}, found {}").format(line_no, interval_min, \
interval_max, interval))
return False
def _validate_line(self, line, line_no='?'):
# Check if its a header line.
if '|' in line:
self.columns = self._count_commas(line)
return True
return \
self._validate_column_count(line, line_no) and \
self._validate_interval_time(line, line_no)
def validate_logfile(self, log_path):
errors = 0
line_no = 0
with open(log_path, 'r') as fil:
for line in fil:
line_no += 1
if errors >= self.MAX_ERRORS:
break
if not self._validate_line(line, line_no):
errors += 1
print()
print("=== Final Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Errors Found: {}".format(errors))
print()
def clean_logfile(self, input_path, output_path):
errors = 0
line_no = 0
with open(input_path, 'r') as file_in:
with open(output_path, 'w') as file_out:
for line in file_in:
line_no += 1
if not self._validate_line(line, line_no):
errors += 1
else:
file_out.write(line)
print()
print("=== Processing Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Lines Pruned: {}".format(errors))
print()
def main():
parser = optparse.OptionParser()
parser.add_option('-f', '--filename',
dest="log_file",
help="Path of log file to process")
parser.add_option('-o', '--output',
dest="out_file",
help="Path to output file of processed data")
options, remainder = parser.parse_args()
if not options.log_file:
parser.error("No log file path given")
rcplv = RcpLogValidator()
if not options.out_file:
rcplv.validate_logfile(options.log_file)
else:
rcplv.clean_logfile(options.log_file, options.out_file)
if __name__ == '__main__':
main() | print(("Error: Column count mismatch on line {}. Expected {}, " +
"found {}").format(line_no, self.columns, columns))
return False | random_line_split |
rcp_log_linter.py | #!/usr/bin/env python3
import optparse
class RcpLogValidator(object):
MAX_ERRORS = 25
MAX_INTERVAL_STEP_MS = 3000
MIN_INTERVAL_STEP_MS = 1
def __init__(self):
self.interval = 0
self.columns = 0
def _count_commas(self, line):
return line.count(',')
def _validate_column_count(self, line, line_no):
columns = self._count_commas(line)
if columns == self.columns:
return True
# If here we failed. Print msg.
print(("Error: Column count mismatch on line {}. Expected {}, " +
"found {}").format(line_no, self.columns, columns))
return False
def _validate_interval_time(self, line, line_no):
try:
interval = int(line.split(',', 1)[0])
except ValueError:
interval = 0
# Deal with initialization.
if self.interval == 0:
self.interval = interval
return True
interval_min = self.interval + self.MIN_INTERVAL_STEP_MS
interval_max = self.interval + self.MAX_INTERVAL_STEP_MS
if interval_min <= interval and interval <= interval_max:
self.interval = interval
return True
# If here we failed. Print msg.
print(("Error: Inconsistent interval value on line {}. Expected " +
"{} - {}, found {}").format(line_no, interval_min, \
interval_max, interval))
return False
def _validate_line(self, line, line_no='?'):
# Check if its a header line.
if '|' in line:
self.columns = self._count_commas(line)
return True
return \
self._validate_column_count(line, line_no) and \
self._validate_interval_time(line, line_no)
def validate_logfile(self, log_path):
|
def clean_logfile(self, input_path, output_path):
errors = 0
line_no = 0
with open(input_path, 'r') as file_in:
with open(output_path, 'w') as file_out:
for line in file_in:
line_no += 1
if not self._validate_line(line, line_no):
errors += 1
else:
file_out.write(line)
print()
print("=== Processing Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Lines Pruned: {}".format(errors))
print()
def main():
parser = optparse.OptionParser()
parser.add_option('-f', '--filename',
dest="log_file",
help="Path of log file to process")
parser.add_option('-o', '--output',
dest="out_file",
help="Path to output file of processed data")
options, remainder = parser.parse_args()
if not options.log_file:
parser.error("No log file path given")
rcplv = RcpLogValidator()
if not options.out_file:
rcplv.validate_logfile(options.log_file)
else:
rcplv.clean_logfile(options.log_file, options.out_file)
if __name__ == '__main__':
main()
| errors = 0
line_no = 0
with open(log_path, 'r') as fil:
for line in fil:
line_no += 1
if errors >= self.MAX_ERRORS:
break
if not self._validate_line(line, line_no):
errors += 1
print()
print("=== Final Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Errors Found: {}".format(errors))
print() | identifier_body |
rcp_log_linter.py | #!/usr/bin/env python3
import optparse
class RcpLogValidator(object):
MAX_ERRORS = 25
MAX_INTERVAL_STEP_MS = 3000
MIN_INTERVAL_STEP_MS = 1
def __init__(self):
self.interval = 0
self.columns = 0
def _count_commas(self, line):
return line.count(',')
def | (self, line, line_no):
columns = self._count_commas(line)
if columns == self.columns:
return True
# If here we failed. Print msg.
print(("Error: Column count mismatch on line {}. Expected {}, " +
"found {}").format(line_no, self.columns, columns))
return False
def _validate_interval_time(self, line, line_no):
try:
interval = int(line.split(',', 1)[0])
except ValueError:
interval = 0
# Deal with initialization.
if self.interval == 0:
self.interval = interval
return True
interval_min = self.interval + self.MIN_INTERVAL_STEP_MS
interval_max = self.interval + self.MAX_INTERVAL_STEP_MS
if interval_min <= interval and interval <= interval_max:
self.interval = interval
return True
# If here we failed. Print msg.
print(("Error: Inconsistent interval value on line {}. Expected " +
"{} - {}, found {}").format(line_no, interval_min, \
interval_max, interval))
return False
def _validate_line(self, line, line_no='?'):
# Check if its a header line.
if '|' in line:
self.columns = self._count_commas(line)
return True
return \
self._validate_column_count(line, line_no) and \
self._validate_interval_time(line, line_no)
def validate_logfile(self, log_path):
errors = 0
line_no = 0
with open(log_path, 'r') as fil:
for line in fil:
line_no += 1
if errors >= self.MAX_ERRORS:
break
if not self._validate_line(line, line_no):
errors += 1
print()
print("=== Final Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Errors Found: {}".format(errors))
print()
def clean_logfile(self, input_path, output_path):
errors = 0
line_no = 0
with open(input_path, 'r') as file_in:
with open(output_path, 'w') as file_out:
for line in file_in:
line_no += 1
if not self._validate_line(line, line_no):
errors += 1
else:
file_out.write(line)
print()
print("=== Processing Stats ===")
print(" Lines Checked: {}".format(line_no))
print(" Lines Pruned: {}".format(errors))
print()
def main():
parser = optparse.OptionParser()
parser.add_option('-f', '--filename',
dest="log_file",
help="Path of log file to process")
parser.add_option('-o', '--output',
dest="out_file",
help="Path to output file of processed data")
options, remainder = parser.parse_args()
if not options.log_file:
parser.error("No log file path given")
rcplv = RcpLogValidator()
if not options.out_file:
rcplv.validate_logfile(options.log_file)
else:
rcplv.clean_logfile(options.log_file, options.out_file)
if __name__ == '__main__':
main()
| _validate_column_count | identifier_name |
004-ship-movement.js | /* demo/test/004-ship-controls.js */
define ([
'keypress',
'physicsjs',
'howler',
'1401/objects/sysloop',
'1401/settings',
'1401/system/renderer',
'1401/system/visualfactory',
'1401/system/piecefactory',
'1401-games/demo/modules/controls'
], function (
KEY,
PHYSICS,
HOWLER,
SYSLOOP,
SETTINGS,
RENDERER,
VISUALFACTORY,
PIECEFACTORY,
SHIPCONTROLS
) {
var DBGOUT = true;
///////////////////////////////////////////////////////////////////////////////
/** SUBMODULE TEST 004 *******************************************************\
Add rudimentary physics and ship controls
///////////////////////////////////////////////////////////////////////////////
/** MODULE DECLARATION *******************************************************/
var MOD = SYSLOOP.New("Test04");
MOD.EnableUpdate( true );
MOD.EnableInput( true );
MOD.SetHandler( 'GetInput', m_GetInput);
MOD.SetHandler( 'Start', m_Start );
MOD.SetHandler( 'Construct', m_Construct );
MOD.SetHandler( 'Update', m_Update);
///////////////////////////////////////////////////////////////////////////////
/** PRIVATE VARS *************************************************************/
var crixa; // ship piece
var crixa_inputs; // encoded controller inputs
var starfields = []; // parallax starfield layersey
var snd_pewpew; // sound instance (howler.js)
var snd_music;
///////////////////////////////////////////////////////////////////////////////
/** MODULE HANDLER FUNCTIONS *************************************************/
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Construct() {
var i, platform;
var cam = RENDERER.Viewport().WorldCam3D();
var z = cam.position.z;
var fog = new THREE.Fog(0x000000,z-100,z+50);
RENDERER.SetWorldVisualFog(fog);
/* add lights so mesh colors show */
var ambientLight = new THREE.AmbientLight(0x222222);
RENDERER.AddWorldVisual(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
RENDERER.AddWorldVisual(directionalLight);
/* make starfield */
var starBright = [
new THREE.Color( 1.0, 1.0, 1.0 ),
new THREE.Color( 0.5, 0.5, 0.7 ),
new THREE.Color( 0.3, 0.3, 0.5 )
];
var starSpec = {
parallax: 1
};
starfields = [];
for (i=0;i<3;i++) {
starSpec.color=starBright[i];
var sf = VISUALFACTORY.MakeStarField( starSpec );
starSpec.parallax *= 0.5;
sf.position.set(0,0,-100-i);
RENDERER.AddBackgroundVisual(sf);
starfields.push(sf);
}
/* make crixa ship */
var shipSprite = VISUALFACTORY.MakeDefaultSprite();
shipSprite.SetZoom(1.0);
RENDERER.AddWorldVisual(shipSprite);
var seq = {
grid: { columns:2, rows:1, stacked:true },
sequences: [
{ name: 'flicker', framecount: 2, fps:4 }
]
};
shipSprite.DefineSequences(SETTINGS.AssetPath('resources/crixa.png'),seq);
// shipSprite.PlaySequence("flicker");
crixa = PIECEFACTORY.NewMovingPiece("crixa");
crixa.SetVisual(shipSprite);
crixa.SetPositionXYZ(0,0,0);
// add extra shooting command
crixa.Shoot = function ( bool ) {
if (bool) snd_pewpew.play();
};
// demonstration of texture validity
var textureLoaded = crixa.Visual().TextureIsLoaded();
console.log("SHIP TEXTURE LOADED TEST OK?",textureLoaded);
if (textureLoaded) {
console.log(". spritesheet dim",crixa.Visual().TextureDimensions());
console.log(". sprite dim",crixa.Visual().SpriteDimensions());
} else {
console.log(".. note textures load asynchronously, so the dimensions are not available yet...");
console.log(".. sprite class handles this automatically so you don't have to.");
}
// make sprites
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.SetZoom(1.0);
platform.position.set(0,100,100-(i*50));
RENDERER.AddWorldVisual(platform);
}
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.position.set(0,-125,100-(i*50));
platform.SetZoom(1.25);
RENDERER.AddWorldVisual(platform);
}
function do_nothing () {}
// load sound
var sfx = SETTINGS.AssetPath('resources/pewpew.ogg');
snd_pewpew = new Howl({
urls: [sfx]
});
}
/// HEAP-SAVING PRE-ALLOCATED VARIABLES /////////////////////////////////////
var x, rot, vp, layers, i, sf;
var cin;
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Start() {
RENDERER.SelectWorld3D();
SHIPCONTROLS.BindKeys();
window.DBG_Out( "TEST 04 <b>Simple Ship Movement and Control</b>" );
window.DBG_Out( "<tt>game-main include: 1401-games/demo/tests/004</tt>" );
window.DBG_Out( "Use WASDQE to move. SPACE brakes. C fires." );
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_GetInput ( interval_ms ) {
cin = crixa_inputs = SHIPCONTROLS.GetInput();
if (!!crixa_inputs.forward_acc) {
crixa.Visual().GoSequence("flicker",1);
} else {
crixa.Visual().GoSequence("flicker",0);
}
crixa.Accelerate(cin.forward_acc,cin.side_acc);
crixa.Brake(crixa_inputs.brake_lin);
crixa.AccelerateRotation(cin.rot_acc);
crixa.BrakeRotation(crixa_inputs.brake_rot);
crixa.Shoot(SHIPCONTROLS.Fire());
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var counter = 0;
var dx = 3;
function | ( interval_ms ) {
vp = RENDERER.Viewport();
vp.Track(crixa.Position());
/* rotate stars */
layers = starfields.length;
for (i=0;i<starfields.length;i++){
sf = starfields[i];
sf.Track(crixa.Position());
}
counter += interval_ms;
}
///////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
return MOD;
});
| m_Update | identifier_name |
004-ship-movement.js | /* demo/test/004-ship-controls.js */
define ([
'keypress',
'physicsjs',
'howler',
'1401/objects/sysloop',
'1401/settings',
'1401/system/renderer',
'1401/system/visualfactory',
'1401/system/piecefactory',
'1401-games/demo/modules/controls'
], function (
KEY,
PHYSICS,
HOWLER,
SYSLOOP,
SETTINGS,
RENDERER,
VISUALFACTORY,
PIECEFACTORY,
SHIPCONTROLS
) {
var DBGOUT = true;
///////////////////////////////////////////////////////////////////////////////
/** SUBMODULE TEST 004 *******************************************************\
Add rudimentary physics and ship controls
///////////////////////////////////////////////////////////////////////////////
/** MODULE DECLARATION *******************************************************/
var MOD = SYSLOOP.New("Test04");
MOD.EnableUpdate( true );
MOD.EnableInput( true );
MOD.SetHandler( 'GetInput', m_GetInput);
MOD.SetHandler( 'Start', m_Start );
MOD.SetHandler( 'Construct', m_Construct );
MOD.SetHandler( 'Update', m_Update);
///////////////////////////////////////////////////////////////////////////////
/** PRIVATE VARS *************************************************************/
var crixa; // ship piece
var crixa_inputs; // encoded controller inputs
var starfields = []; // parallax starfield layersey
var snd_pewpew; // sound instance (howler.js)
var snd_music;
///////////////////////////////////////////////////////////////////////////////
/** MODULE HANDLER FUNCTIONS *************************************************/
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Construct() {
var i, platform;
var cam = RENDERER.Viewport().WorldCam3D();
var z = cam.position.z;
var fog = new THREE.Fog(0x000000,z-100,z+50);
RENDERER.SetWorldVisualFog(fog);
/* add lights so mesh colors show */
var ambientLight = new THREE.AmbientLight(0x222222);
RENDERER.AddWorldVisual(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
RENDERER.AddWorldVisual(directionalLight);
/* make starfield */
var starBright = [
new THREE.Color( 1.0, 1.0, 1.0 ),
new THREE.Color( 0.5, 0.5, 0.7 ),
new THREE.Color( 0.3, 0.3, 0.5 )
];
var starSpec = {
parallax: 1
};
starfields = [];
for (i=0;i<3;i++) {
starSpec.color=starBright[i];
var sf = VISUALFACTORY.MakeStarField( starSpec );
starSpec.parallax *= 0.5;
sf.position.set(0,0,-100-i);
RENDERER.AddBackgroundVisual(sf);
starfields.push(sf);
}
/* make crixa ship */
var shipSprite = VISUALFACTORY.MakeDefaultSprite();
shipSprite.SetZoom(1.0);
RENDERER.AddWorldVisual(shipSprite);
var seq = {
grid: { columns:2, rows:1, stacked:true },
sequences: [
{ name: 'flicker', framecount: 2, fps:4 }
]
};
shipSprite.DefineSequences(SETTINGS.AssetPath('resources/crixa.png'),seq);
// shipSprite.PlaySequence("flicker");
crixa = PIECEFACTORY.NewMovingPiece("crixa");
crixa.SetVisual(shipSprite);
crixa.SetPositionXYZ(0,0,0);
// add extra shooting command
crixa.Shoot = function ( bool ) {
if (bool) snd_pewpew.play();
};
// demonstration of texture validity
var textureLoaded = crixa.Visual().TextureIsLoaded();
console.log("SHIP TEXTURE LOADED TEST OK?",textureLoaded);
if (textureLoaded) {
console.log(". spritesheet dim",crixa.Visual().TextureDimensions());
console.log(". sprite dim",crixa.Visual().SpriteDimensions());
} else {
console.log(".. note textures load asynchronously, so the dimensions are not available yet...");
console.log(".. sprite class handles this automatically so you don't have to.");
}
// make sprites
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.SetZoom(1.0);
platform.position.set(0,100,100-(i*50));
RENDERER.AddWorldVisual(platform);
}
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.position.set(0,-125,100-(i*50));
platform.SetZoom(1.25);
RENDERER.AddWorldVisual(platform);
}
function do_nothing () {}
// load sound
var sfx = SETTINGS.AssetPath('resources/pewpew.ogg');
snd_pewpew = new Howl({
urls: [sfx]
});
}
/// HEAP-SAVING PRE-ALLOCATED VARIABLES /////////////////////////////////////
var x, rot, vp, layers, i, sf;
var cin;
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Start() {
RENDERER.SelectWorld3D();
SHIPCONTROLS.BindKeys();
window.DBG_Out( "TEST 04 <b>Simple Ship Movement and Control</b>" );
window.DBG_Out( "<tt>game-main include: 1401-games/demo/tests/004</tt>" );
window.DBG_Out( "Use WASDQE to move. SPACE brakes. C fires." );
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_GetInput ( interval_ms ) |
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var counter = 0;
var dx = 3;
function m_Update ( interval_ms ) {
vp = RENDERER.Viewport();
vp.Track(crixa.Position());
/* rotate stars */
layers = starfields.length;
for (i=0;i<starfields.length;i++){
sf = starfields[i];
sf.Track(crixa.Position());
}
counter += interval_ms;
}
///////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
return MOD;
});
| {
cin = crixa_inputs = SHIPCONTROLS.GetInput();
if (!!crixa_inputs.forward_acc) {
crixa.Visual().GoSequence("flicker",1);
} else {
crixa.Visual().GoSequence("flicker",0);
}
crixa.Accelerate(cin.forward_acc,cin.side_acc);
crixa.Brake(crixa_inputs.brake_lin);
crixa.AccelerateRotation(cin.rot_acc);
crixa.BrakeRotation(crixa_inputs.brake_rot);
crixa.Shoot(SHIPCONTROLS.Fire());
} | identifier_body |
004-ship-movement.js | /* demo/test/004-ship-controls.js */
define ([
'keypress',
'physicsjs',
'howler',
'1401/objects/sysloop',
'1401/settings',
'1401/system/renderer',
'1401/system/visualfactory',
'1401/system/piecefactory',
'1401-games/demo/modules/controls'
], function (
KEY,
PHYSICS,
HOWLER,
SYSLOOP,
SETTINGS,
RENDERER,
VISUALFACTORY,
PIECEFACTORY,
SHIPCONTROLS
) {
var DBGOUT = true;
///////////////////////////////////////////////////////////////////////////////
/** SUBMODULE TEST 004 *******************************************************\
Add rudimentary physics and ship controls
///////////////////////////////////////////////////////////////////////////////
/** MODULE DECLARATION *******************************************************/
var MOD = SYSLOOP.New("Test04");
MOD.EnableUpdate( true );
MOD.EnableInput( true );
MOD.SetHandler( 'GetInput', m_GetInput);
MOD.SetHandler( 'Start', m_Start );
MOD.SetHandler( 'Construct', m_Construct );
MOD.SetHandler( 'Update', m_Update);
///////////////////////////////////////////////////////////////////////////////
/** PRIVATE VARS *************************************************************/
var crixa; // ship piece
var crixa_inputs; // encoded controller inputs
var starfields = []; // parallax starfield layersey
var snd_pewpew; // sound instance (howler.js)
var snd_music;
///////////////////////////////////////////////////////////////////////////////
/** MODULE HANDLER FUNCTIONS *************************************************/
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Construct() {
var i, platform;
var cam = RENDERER.Viewport().WorldCam3D();
var z = cam.position.z;
var fog = new THREE.Fog(0x000000,z-100,z+50);
RENDERER.SetWorldVisualFog(fog);
/* add lights so mesh colors show */
var ambientLight = new THREE.AmbientLight(0x222222);
RENDERER.AddWorldVisual(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
RENDERER.AddWorldVisual(directionalLight);
/* make starfield */
var starBright = [
new THREE.Color( 1.0, 1.0, 1.0 ),
new THREE.Color( 0.5, 0.5, 0.7 ),
new THREE.Color( 0.3, 0.3, 0.5 )
];
var starSpec = {
parallax: 1
};
starfields = [];
for (i=0;i<3;i++) {
starSpec.color=starBright[i];
var sf = VISUALFACTORY.MakeStarField( starSpec );
starSpec.parallax *= 0.5;
sf.position.set(0,0,-100-i);
RENDERER.AddBackgroundVisual(sf);
starfields.push(sf);
}
/* make crixa ship */
var shipSprite = VISUALFACTORY.MakeDefaultSprite();
shipSprite.SetZoom(1.0);
RENDERER.AddWorldVisual(shipSprite);
var seq = {
grid: { columns:2, rows:1, stacked:true },
sequences: [
{ name: 'flicker', framecount: 2, fps:4 }
]
};
shipSprite.DefineSequences(SETTINGS.AssetPath('resources/crixa.png'),seq);
// shipSprite.PlaySequence("flicker");
crixa = PIECEFACTORY.NewMovingPiece("crixa");
crixa.SetVisual(shipSprite);
crixa.SetPositionXYZ(0,0,0);
// add extra shooting command
crixa.Shoot = function ( bool ) {
if (bool) snd_pewpew.play();
};
// demonstration of texture validity
var textureLoaded = crixa.Visual().TextureIsLoaded();
console.log("SHIP TEXTURE LOADED TEST OK?",textureLoaded);
if (textureLoaded) {
console.log(". spritesheet dim",crixa.Visual().TextureDimensions());
console.log(". sprite dim",crixa.Visual().SpriteDimensions());
} else {
console.log(".. note textures load asynchronously, so the dimensions are not available yet...");
console.log(".. sprite class handles this automatically so you don't have to.");
}
// make sprites
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.SetZoom(1.0);
platform.position.set(0,100,100-(i*50));
RENDERER.AddWorldVisual(platform);
}
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.position.set(0,-125,100-(i*50));
platform.SetZoom(1.25);
RENDERER.AddWorldVisual(platform);
}
function do_nothing () {}
// load sound
var sfx = SETTINGS.AssetPath('resources/pewpew.ogg');
snd_pewpew = new Howl({
urls: [sfx]
});
}
/// HEAP-SAVING PRE-ALLOCATED VARIABLES /////////////////////////////////////
var x, rot, vp, layers, i, sf;
var cin;
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Start() {
RENDERER.SelectWorld3D();
SHIPCONTROLS.BindKeys();
window.DBG_Out( "TEST 04 <b>Simple Ship Movement and Control</b>" );
window.DBG_Out( "<tt>game-main include: 1401-games/demo/tests/004</tt>" );
window.DBG_Out( "Use WASDQE to move. SPACE brakes. C fires." );
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_GetInput ( interval_ms ) {
cin = crixa_inputs = SHIPCONTROLS.GetInput();
if (!!crixa_inputs.forward_acc) {
crixa.Visual().GoSequence("flicker",1);
} else {
crixa.Visual().GoSequence("flicker",0);
}
crixa.Accelerate(cin.forward_acc,cin.side_acc);
crixa.Brake(crixa_inputs.brake_lin);
crixa.AccelerateRotation(cin.rot_acc);
crixa.BrakeRotation(crixa_inputs.brake_rot);
crixa.Shoot(SHIPCONTROLS.Fire());
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var counter = 0;
var dx = 3;
function m_Update ( interval_ms ) {
vp = RENDERER.Viewport();
vp.Track(crixa.Position());
/* rotate stars */
layers = starfields.length;
for (i=0;i<starfields.length;i++){
sf = starfields[i];
sf.Track(crixa.Position());
}
counter += interval_ms;
}
///////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
return MOD;
| }); | random_line_split |
|
004-ship-movement.js | /* demo/test/004-ship-controls.js */
define ([
'keypress',
'physicsjs',
'howler',
'1401/objects/sysloop',
'1401/settings',
'1401/system/renderer',
'1401/system/visualfactory',
'1401/system/piecefactory',
'1401-games/demo/modules/controls'
], function (
KEY,
PHYSICS,
HOWLER,
SYSLOOP,
SETTINGS,
RENDERER,
VISUALFACTORY,
PIECEFACTORY,
SHIPCONTROLS
) {
var DBGOUT = true;
///////////////////////////////////////////////////////////////////////////////
/** SUBMODULE TEST 004 *******************************************************\
Add rudimentary physics and ship controls
///////////////////////////////////////////////////////////////////////////////
/** MODULE DECLARATION *******************************************************/
var MOD = SYSLOOP.New("Test04");
MOD.EnableUpdate( true );
MOD.EnableInput( true );
MOD.SetHandler( 'GetInput', m_GetInput);
MOD.SetHandler( 'Start', m_Start );
MOD.SetHandler( 'Construct', m_Construct );
MOD.SetHandler( 'Update', m_Update);
///////////////////////////////////////////////////////////////////////////////
/** PRIVATE VARS *************************************************************/
var crixa; // ship piece
var crixa_inputs; // encoded controller inputs
var starfields = []; // parallax starfield layersey
var snd_pewpew; // sound instance (howler.js)
var snd_music;
///////////////////////////////////////////////////////////////////////////////
/** MODULE HANDLER FUNCTIONS *************************************************/
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Construct() {
var i, platform;
var cam = RENDERER.Viewport().WorldCam3D();
var z = cam.position.z;
var fog = new THREE.Fog(0x000000,z-100,z+50);
RENDERER.SetWorldVisualFog(fog);
/* add lights so mesh colors show */
var ambientLight = new THREE.AmbientLight(0x222222);
RENDERER.AddWorldVisual(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
RENDERER.AddWorldVisual(directionalLight);
/* make starfield */
var starBright = [
new THREE.Color( 1.0, 1.0, 1.0 ),
new THREE.Color( 0.5, 0.5, 0.7 ),
new THREE.Color( 0.3, 0.3, 0.5 )
];
var starSpec = {
parallax: 1
};
starfields = [];
for (i=0;i<3;i++) |
/* make crixa ship */
var shipSprite = VISUALFACTORY.MakeDefaultSprite();
shipSprite.SetZoom(1.0);
RENDERER.AddWorldVisual(shipSprite);
var seq = {
grid: { columns:2, rows:1, stacked:true },
sequences: [
{ name: 'flicker', framecount: 2, fps:4 }
]
};
shipSprite.DefineSequences(SETTINGS.AssetPath('resources/crixa.png'),seq);
// shipSprite.PlaySequence("flicker");
crixa = PIECEFACTORY.NewMovingPiece("crixa");
crixa.SetVisual(shipSprite);
crixa.SetPositionXYZ(0,0,0);
// add extra shooting command
crixa.Shoot = function ( bool ) {
if (bool) snd_pewpew.play();
};
// demonstration of texture validity
var textureLoaded = crixa.Visual().TextureIsLoaded();
console.log("SHIP TEXTURE LOADED TEST OK?",textureLoaded);
if (textureLoaded) {
console.log(". spritesheet dim",crixa.Visual().TextureDimensions());
console.log(". sprite dim",crixa.Visual().SpriteDimensions());
} else {
console.log(".. note textures load asynchronously, so the dimensions are not available yet...");
console.log(".. sprite class handles this automatically so you don't have to.");
}
// make sprites
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.SetZoom(1.0);
platform.position.set(0,100,100-(i*50));
RENDERER.AddWorldVisual(platform);
}
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.position.set(0,-125,100-(i*50));
platform.SetZoom(1.25);
RENDERER.AddWorldVisual(platform);
}
function do_nothing () {}
// load sound
var sfx = SETTINGS.AssetPath('resources/pewpew.ogg');
snd_pewpew = new Howl({
urls: [sfx]
});
}
/// HEAP-SAVING PRE-ALLOCATED VARIABLES /////////////////////////////////////
var x, rot, vp, layers, i, sf;
var cin;
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Start() {
RENDERER.SelectWorld3D();
SHIPCONTROLS.BindKeys();
window.DBG_Out( "TEST 04 <b>Simple Ship Movement and Control</b>" );
window.DBG_Out( "<tt>game-main include: 1401-games/demo/tests/004</tt>" );
window.DBG_Out( "Use WASDQE to move. SPACE brakes. C fires." );
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_GetInput ( interval_ms ) {
cin = crixa_inputs = SHIPCONTROLS.GetInput();
if (!!crixa_inputs.forward_acc) {
crixa.Visual().GoSequence("flicker",1);
} else {
crixa.Visual().GoSequence("flicker",0);
}
crixa.Accelerate(cin.forward_acc,cin.side_acc);
crixa.Brake(crixa_inputs.brake_lin);
crixa.AccelerateRotation(cin.rot_acc);
crixa.BrakeRotation(crixa_inputs.brake_rot);
crixa.Shoot(SHIPCONTROLS.Fire());
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var counter = 0;
var dx = 3;
function m_Update ( interval_ms ) {
vp = RENDERER.Viewport();
vp.Track(crixa.Position());
/* rotate stars */
layers = starfields.length;
for (i=0;i<starfields.length;i++){
sf = starfields[i];
sf.Track(crixa.Position());
}
counter += interval_ms;
}
///////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
return MOD;
});
| {
starSpec.color=starBright[i];
var sf = VISUALFACTORY.MakeStarField( starSpec );
starSpec.parallax *= 0.5;
sf.position.set(0,0,-100-i);
RENDERER.AddBackgroundVisual(sf);
starfields.push(sf);
} | conditional_block |
expr-match-generic-unique1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
fn | <T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool {
let actual: Box<T> = match true {
true => { expected.clone() },
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_box() {
fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool {
return *b1 == *b2;
}
test_generic::<bool, _>(box true, compare_box);
}
pub fn main() { test_box(); }
| test_generic | identifier_name |
expr-match-generic-unique1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool {
let actual: Box<T> = match true {
true => | ,
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_box() {
fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool {
return *b1 == *b2;
}
test_generic::<bool, _>(box true, compare_box);
}
pub fn main() { test_box(); }
| { expected.clone() } | conditional_block |
expr-match-generic-unique1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool {
let actual: Box<T> = match true {
true => { expected.clone() },
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_box() |
pub fn main() { test_box(); }
| {
fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool {
return *b1 == *b2;
}
test_generic::<bool, _>(box true, compare_box);
} | identifier_body |
expr-match-generic-unique1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool {
let actual: Box<T> = match true {
true => { expected.clone() }, | assert!(eq(expected, actual));
}
fn test_box() {
fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool {
return *b1 == *b2;
}
test_generic::<bool, _>(box true, compare_box);
}
pub fn main() { test_box(); } | _ => panic!("wat")
}; | random_line_split |
main-page.component.ts | import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupService } from 'app/shared/services';
import { HELP_VIEWER_LIST, HelpViewerPopupContainerComponent } from 'app/core/components/help-viewer-popup/help-viewer-popup-container.component';
import { UrlPathId } from 'app/shared/models';
@Component({
selector: 'pp-main-page',
templateUrl: './main-page.component.html',
styleUrls: ['./main-page.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MainPageComponent implements OnInit {
enableRealTime$: Observable<boolean>; | constructor(
private newUrlStateNotificationService: NewUrlStateNotificationService,
private webAppSettingDataService: WebAppSettingDataService,
private analyticsService: AnalyticsService,
private dynamicPopupService: DynamicPopupService,
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
) {}
ngOnInit() {
this.enableRealTime$ = combineLatest(
this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.isRealTimeMode())
),
this.webAppSettingDataService.useActiveThreadChart()
).pipe(
map(([isRealTimeMode, useActiveThreadChart]: boolean[]) => isRealTimeMode && useActiveThreadChart)
);
this.isAppKeyProvided$ = this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.hasValue(UrlPathId.APPLICATION))
);
this.webAppSettingDataService.getVersion().subscribe((version: string) => {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.VERSION, version);
});
}
onShowHelp($event: MouseEvent): void {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.TOGGLE_HELP_VIEWER, HELP_VIEWER_LIST.NAVBAR);
const {left, top, width, height} = ($event.target as HTMLElement).getBoundingClientRect();
this.dynamicPopupService.openPopup({
data: HELP_VIEWER_LIST.NAVBAR,
coord: {
coordX: left + width / 2,
coordY: top + height / 2
},
component: HelpViewerPopupContainerComponent
}, {
resolver: this.componentFactoryResolver,
injector: this.injector
});
}
} | isAppKeyProvided$: Observable<boolean>;
| random_line_split |
main-page.component.ts | import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupService } from 'app/shared/services';
import { HELP_VIEWER_LIST, HelpViewerPopupContainerComponent } from 'app/core/components/help-viewer-popup/help-viewer-popup-container.component';
import { UrlPathId } from 'app/shared/models';
@Component({
selector: 'pp-main-page',
templateUrl: './main-page.component.html',
styleUrls: ['./main-page.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MainPageComponent implements OnInit {
enableRealTime$: Observable<boolean>;
isAppKeyProvided$: Observable<boolean>;
constructor(
private newUrlStateNotificationService: NewUrlStateNotificationService,
private webAppSettingDataService: WebAppSettingDataService,
private analyticsService: AnalyticsService,
private dynamicPopupService: DynamicPopupService,
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
) {}
| () {
this.enableRealTime$ = combineLatest(
this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.isRealTimeMode())
),
this.webAppSettingDataService.useActiveThreadChart()
).pipe(
map(([isRealTimeMode, useActiveThreadChart]: boolean[]) => isRealTimeMode && useActiveThreadChart)
);
this.isAppKeyProvided$ = this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.hasValue(UrlPathId.APPLICATION))
);
this.webAppSettingDataService.getVersion().subscribe((version: string) => {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.VERSION, version);
});
}
onShowHelp($event: MouseEvent): void {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.TOGGLE_HELP_VIEWER, HELP_VIEWER_LIST.NAVBAR);
const {left, top, width, height} = ($event.target as HTMLElement).getBoundingClientRect();
this.dynamicPopupService.openPopup({
data: HELP_VIEWER_LIST.NAVBAR,
coord: {
coordX: left + width / 2,
coordY: top + height / 2
},
component: HelpViewerPopupContainerComponent
}, {
resolver: this.componentFactoryResolver,
injector: this.injector
});
}
}
| ngOnInit | identifier_name |
main-page.component.ts | import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupService } from 'app/shared/services';
import { HELP_VIEWER_LIST, HelpViewerPopupContainerComponent } from 'app/core/components/help-viewer-popup/help-viewer-popup-container.component';
import { UrlPathId } from 'app/shared/models';
@Component({
selector: 'pp-main-page',
templateUrl: './main-page.component.html',
styleUrls: ['./main-page.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MainPageComponent implements OnInit {
enableRealTime$: Observable<boolean>;
isAppKeyProvided$: Observable<boolean>;
constructor(
private newUrlStateNotificationService: NewUrlStateNotificationService,
private webAppSettingDataService: WebAppSettingDataService,
private analyticsService: AnalyticsService,
private dynamicPopupService: DynamicPopupService,
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
) |
ngOnInit() {
this.enableRealTime$ = combineLatest(
this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.isRealTimeMode())
),
this.webAppSettingDataService.useActiveThreadChart()
).pipe(
map(([isRealTimeMode, useActiveThreadChart]: boolean[]) => isRealTimeMode && useActiveThreadChart)
);
this.isAppKeyProvided$ = this.newUrlStateNotificationService.onUrlStateChange$.pipe(
map((urlService: NewUrlStateNotificationService) => urlService.hasValue(UrlPathId.APPLICATION))
);
this.webAppSettingDataService.getVersion().subscribe((version: string) => {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.VERSION, version);
});
}
onShowHelp($event: MouseEvent): void {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.TOGGLE_HELP_VIEWER, HELP_VIEWER_LIST.NAVBAR);
const {left, top, width, height} = ($event.target as HTMLElement).getBoundingClientRect();
this.dynamicPopupService.openPopup({
data: HELP_VIEWER_LIST.NAVBAR,
coord: {
coordX: left + width / 2,
coordY: top + height / 2
},
component: HelpViewerPopupContainerComponent
}, {
resolver: this.componentFactoryResolver,
injector: this.injector
});
}
}
| {} | identifier_body |
color.ts | import {constrainRange, loopRange} from '../../../common/number-util';
import {isEmpty} from '../../../misc/type-util';
import {
appendAlphaComponent,
ColorComponents3,
ColorComponents4,
ColorMode,
convertColorMode,
removeAlphaComponent,
} from './color-model';
export interface RgbColorObject {
r: number;
g: number;
b: number;
}
export interface RgbaColorObject {
r: number;
g: number;
b: number;
a: number;
}
const CONSTRAINT_MAP: {
[mode in ColorMode]: (
comps: ColorComponents3 | ColorComponents4,
) => ColorComponents4;
} = {
hsl: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
hsv: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
rgb: (comps) => {
return [
constrainRange(comps[0], 0, 255),
constrainRange(comps[1], 0, 255),
constrainRange(comps[2], 0, 255),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
};
function isRgbColorComponent(obj: any, key: string): boolean {
if (typeof obj !== 'object' || isEmpty(obj)) {
return false;
}
return key in obj && typeof obj[key] === 'number';
}
/**
* @hidden
*/
export class Color {
public static black(): Color {
return new Color([0, 0, 0], 'rgb');
}
public static fromObject(obj: RgbColorObject | RgbaColorObject): Color {
const comps: ColorComponents4 | ColorComponents3 =
'a' in obj ? [obj.r, obj.g, obj.b, obj.a] : [obj.r, obj.g, obj.b];
return new Color(comps, 'rgb');
}
public static toRgbaObject(color: Color): RgbaColorObject {
return color.toRgbaObject();
}
public static isRgbColorObject(obj: unknown): obj is RgbColorObject {
return (
isRgbColorComponent(obj, 'r') &&
isRgbColorComponent(obj, 'g') &&
isRgbColorComponent(obj, 'b')
);
}
public static isRgbaColorObject(obj: unknown): obj is RgbaColorObject {
return this.isRgbColorObject(obj) && isRgbColorComponent(obj, 'a');
}
public static isColorObject(
obj: unknown,
): obj is RgbColorObject | RgbaColorObject {
return this.isRgbColorObject(obj);
}
public static equals(v1: Color, v2: Color): boolean {
if (v1.mode_ !== v2.mode_) {
return false;
}
const comps1 = v1.comps_;
const comps2 = v2.comps_;
for (let i = 0; i < comps1.length; i++) {
if (comps1[i] !== comps2[i]) {
return false;
}
}
return true;
}
private comps_: ColorComponents4;
private mode_: ColorMode;
constructor(comps: ColorComponents3 | ColorComponents4, mode: ColorMode) {
this.mode_ = mode;
this.comps_ = CONSTRAINT_MAP[mode](comps);
}
public get mode(): ColorMode |
public getComponents(opt_mode?: ColorMode): ColorComponents4 {
return appendAlphaComponent(
convertColorMode(
removeAlphaComponent(this.comps_),
this.mode_,
opt_mode || this.mode_,
),
this.comps_[3],
);
}
public toRgbaObject(): RgbaColorObject {
const rgbComps = this.getComponents('rgb');
return {
r: rgbComps[0],
g: rgbComps[1],
b: rgbComps[2],
a: rgbComps[3],
};
}
}
| {
return this.mode_;
} | identifier_body |
color.ts | import {constrainRange, loopRange} from '../../../common/number-util';
import {isEmpty} from '../../../misc/type-util';
import {
appendAlphaComponent,
ColorComponents3,
ColorComponents4,
ColorMode,
convertColorMode,
removeAlphaComponent,
} from './color-model';
export interface RgbColorObject {
r: number;
g: number;
b: number;
}
export interface RgbaColorObject {
r: number;
g: number;
b: number;
a: number;
}
const CONSTRAINT_MAP: {
[mode in ColorMode]: (
comps: ColorComponents3 | ColorComponents4,
) => ColorComponents4;
} = {
hsl: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
hsv: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
rgb: (comps) => {
return [
constrainRange(comps[0], 0, 255),
constrainRange(comps[1], 0, 255),
constrainRange(comps[2], 0, 255),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
};
function isRgbColorComponent(obj: any, key: string): boolean {
if (typeof obj !== 'object' || isEmpty(obj)) {
return false;
}
return key in obj && typeof obj[key] === 'number';
}
/**
* @hidden
*/
export class Color {
public static black(): Color {
return new Color([0, 0, 0], 'rgb');
}
public static fromObject(obj: RgbColorObject | RgbaColorObject): Color {
const comps: ColorComponents4 | ColorComponents3 =
'a' in obj ? [obj.r, obj.g, obj.b, obj.a] : [obj.r, obj.g, obj.b];
return new Color(comps, 'rgb');
} |
public static isRgbColorObject(obj: unknown): obj is RgbColorObject {
return (
isRgbColorComponent(obj, 'r') &&
isRgbColorComponent(obj, 'g') &&
isRgbColorComponent(obj, 'b')
);
}
public static isRgbaColorObject(obj: unknown): obj is RgbaColorObject {
return this.isRgbColorObject(obj) && isRgbColorComponent(obj, 'a');
}
public static isColorObject(
obj: unknown,
): obj is RgbColorObject | RgbaColorObject {
return this.isRgbColorObject(obj);
}
public static equals(v1: Color, v2: Color): boolean {
if (v1.mode_ !== v2.mode_) {
return false;
}
const comps1 = v1.comps_;
const comps2 = v2.comps_;
for (let i = 0; i < comps1.length; i++) {
if (comps1[i] !== comps2[i]) {
return false;
}
}
return true;
}
private comps_: ColorComponents4;
private mode_: ColorMode;
constructor(comps: ColorComponents3 | ColorComponents4, mode: ColorMode) {
this.mode_ = mode;
this.comps_ = CONSTRAINT_MAP[mode](comps);
}
public get mode(): ColorMode {
return this.mode_;
}
public getComponents(opt_mode?: ColorMode): ColorComponents4 {
return appendAlphaComponent(
convertColorMode(
removeAlphaComponent(this.comps_),
this.mode_,
opt_mode || this.mode_,
),
this.comps_[3],
);
}
public toRgbaObject(): RgbaColorObject {
const rgbComps = this.getComponents('rgb');
return {
r: rgbComps[0],
g: rgbComps[1],
b: rgbComps[2],
a: rgbComps[3],
};
}
} |
public static toRgbaObject(color: Color): RgbaColorObject {
return color.toRgbaObject();
} | random_line_split |
color.ts | import {constrainRange, loopRange} from '../../../common/number-util';
import {isEmpty} from '../../../misc/type-util';
import {
appendAlphaComponent,
ColorComponents3,
ColorComponents4,
ColorMode,
convertColorMode,
removeAlphaComponent,
} from './color-model';
export interface RgbColorObject {
r: number;
g: number;
b: number;
}
export interface RgbaColorObject {
r: number;
g: number;
b: number;
a: number;
}
const CONSTRAINT_MAP: {
[mode in ColorMode]: (
comps: ColorComponents3 | ColorComponents4,
) => ColorComponents4;
} = {
hsl: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
hsv: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
rgb: (comps) => {
return [
constrainRange(comps[0], 0, 255),
constrainRange(comps[1], 0, 255),
constrainRange(comps[2], 0, 255),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
};
function isRgbColorComponent(obj: any, key: string): boolean {
if (typeof obj !== 'object' || isEmpty(obj)) {
return false;
}
return key in obj && typeof obj[key] === 'number';
}
/**
* @hidden
*/
export class Color {
public static black(): Color {
return new Color([0, 0, 0], 'rgb');
}
public static fromObject(obj: RgbColorObject | RgbaColorObject): Color {
const comps: ColorComponents4 | ColorComponents3 =
'a' in obj ? [obj.r, obj.g, obj.b, obj.a] : [obj.r, obj.g, obj.b];
return new Color(comps, 'rgb');
}
public static toRgbaObject(color: Color): RgbaColorObject {
return color.toRgbaObject();
}
public static isRgbColorObject(obj: unknown): obj is RgbColorObject {
return (
isRgbColorComponent(obj, 'r') &&
isRgbColorComponent(obj, 'g') &&
isRgbColorComponent(obj, 'b')
);
}
public static isRgbaColorObject(obj: unknown): obj is RgbaColorObject {
return this.isRgbColorObject(obj) && isRgbColorComponent(obj, 'a');
}
public static isColorObject(
obj: unknown,
): obj is RgbColorObject | RgbaColorObject {
return this.isRgbColorObject(obj);
}
public static equals(v1: Color, v2: Color): boolean {
if (v1.mode_ !== v2.mode_) {
return false;
}
const comps1 = v1.comps_;
const comps2 = v2.comps_;
for (let i = 0; i < comps1.length; i++) {
if (comps1[i] !== comps2[i]) |
}
return true;
}
private comps_: ColorComponents4;
private mode_: ColorMode;
constructor(comps: ColorComponents3 | ColorComponents4, mode: ColorMode) {
this.mode_ = mode;
this.comps_ = CONSTRAINT_MAP[mode](comps);
}
public get mode(): ColorMode {
return this.mode_;
}
public getComponents(opt_mode?: ColorMode): ColorComponents4 {
return appendAlphaComponent(
convertColorMode(
removeAlphaComponent(this.comps_),
this.mode_,
opt_mode || this.mode_,
),
this.comps_[3],
);
}
public toRgbaObject(): RgbaColorObject {
const rgbComps = this.getComponents('rgb');
return {
r: rgbComps[0],
g: rgbComps[1],
b: rgbComps[2],
a: rgbComps[3],
};
}
}
| {
return false;
} | conditional_block |
color.ts | import {constrainRange, loopRange} from '../../../common/number-util';
import {isEmpty} from '../../../misc/type-util';
import {
appendAlphaComponent,
ColorComponents3,
ColorComponents4,
ColorMode,
convertColorMode,
removeAlphaComponent,
} from './color-model';
export interface RgbColorObject {
r: number;
g: number;
b: number;
}
export interface RgbaColorObject {
r: number;
g: number;
b: number;
a: number;
}
const CONSTRAINT_MAP: {
[mode in ColorMode]: (
comps: ColorComponents3 | ColorComponents4,
) => ColorComponents4;
} = {
hsl: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
hsv: (comps) => {
return [
loopRange(comps[0], 360),
constrainRange(comps[1], 0, 100),
constrainRange(comps[2], 0, 100),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
rgb: (comps) => {
return [
constrainRange(comps[0], 0, 255),
constrainRange(comps[1], 0, 255),
constrainRange(comps[2], 0, 255),
constrainRange(comps[3] ?? 1, 0, 1),
];
},
};
function isRgbColorComponent(obj: any, key: string): boolean {
if (typeof obj !== 'object' || isEmpty(obj)) {
return false;
}
return key in obj && typeof obj[key] === 'number';
}
/**
* @hidden
*/
export class Color {
public static black(): Color {
return new Color([0, 0, 0], 'rgb');
}
public static fromObject(obj: RgbColorObject | RgbaColorObject): Color {
const comps: ColorComponents4 | ColorComponents3 =
'a' in obj ? [obj.r, obj.g, obj.b, obj.a] : [obj.r, obj.g, obj.b];
return new Color(comps, 'rgb');
}
public static toRgbaObject(color: Color): RgbaColorObject {
return color.toRgbaObject();
}
public static isRgbColorObject(obj: unknown): obj is RgbColorObject {
return (
isRgbColorComponent(obj, 'r') &&
isRgbColorComponent(obj, 'g') &&
isRgbColorComponent(obj, 'b')
);
}
public static isRgbaColorObject(obj: unknown): obj is RgbaColorObject {
return this.isRgbColorObject(obj) && isRgbColorComponent(obj, 'a');
}
public static isColorObject(
obj: unknown,
): obj is RgbColorObject | RgbaColorObject {
return this.isRgbColorObject(obj);
}
public static equals(v1: Color, v2: Color): boolean {
if (v1.mode_ !== v2.mode_) {
return false;
}
const comps1 = v1.comps_;
const comps2 = v2.comps_;
for (let i = 0; i < comps1.length; i++) {
if (comps1[i] !== comps2[i]) {
return false;
}
}
return true;
}
private comps_: ColorComponents4;
private mode_: ColorMode;
constructor(comps: ColorComponents3 | ColorComponents4, mode: ColorMode) {
this.mode_ = mode;
this.comps_ = CONSTRAINT_MAP[mode](comps);
}
public get mode(): ColorMode {
return this.mode_;
}
public getComponents(opt_mode?: ColorMode): ColorComponents4 {
return appendAlphaComponent(
convertColorMode(
removeAlphaComponent(this.comps_),
this.mode_,
opt_mode || this.mode_,
),
this.comps_[3],
);
}
public | (): RgbaColorObject {
const rgbComps = this.getComponents('rgb');
return {
r: rgbComps[0],
g: rgbComps[1],
b: rgbComps[2],
a: rgbComps[3],
};
}
}
| toRgbaObject | identifier_name |
a00116.js | var a00116 =
[
[ "Advertising Data Encoder", "a00118.html", null ],
[ "Debug Assert Handler", "a00119.html", null ],
[ "BLE Device Manager", "a00126.html", [
[ "Initialization", "a00126.html#lib_device_manaegerit", [
[ "Associated Events", "a00126.html#lib_device_manager_init_evt", null ],
[ "Associated Configuration Parameters", "a00126.html#lib_device_manager_init_cnfg_param", null ]
] ],
[ "Registration", "a00126.html#lib_device_manager_register", [
[ "Associated Events", "a00126.html#lib_cnxn_register_evt", null ],
[ "Associated Configuration Parameters", "a00126.html#lib_cnxn_register_cnfg_param", null ] | [ "Initialization and Set-up", "a00120.html#lib_ble_conn_params_init", null ],
[ "Shutdown", "a00120.html#lib_ble_conn_params_stop", null ],
[ "Change/Update Connection Parameters Negotiated", "a00120.html#lib_ble_conn_params_change_conn_params", null ]
] ],
[ "DTM - Direct Test Mode", "a00121.html", null ],
[ "Error Log", "a00122.html", null ],
[ "Record Access Control Point", "a00123.html", null ],
[ "Radio Notification Event Handler", "a00124.html", null ],
[ "Sensor Data Simulator", "a00125.html", null ]
]; | ] ]
] ],
[ "Connection Parameters Negotiation", "a00120.html", [
[ "Overview", "a00120.html#Overview", null ], | random_line_split |
plan-side-display.component.spec.ts | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {DebugElement} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {MatButtonModule, MatCheckboxModule, MatGridListModule, MatIconModule, MatMenuModule} from '@angular/material';
import {MatCardModule} from '@angular/material/card';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatSelectModule} from '@angular/material/select';
import {MatTableModule} from '@angular/material/table';
import {MatTabsModule} from '@angular/material/tabs';
import {By} from '@angular/platform-browser';
import {StageDetailsComponent} from '../stage-details/stage-details.component';
import {StepDetailsComponent} from '../step-details/step-details.component';
import {PlanSideDisplayComponent} from './plan-side-display.component';
describe('PlanSideDisplayComponent', () => {
let component: PlanSideDisplayComponent;
let fixture: ComponentFixture<PlanSideDisplayComponent>;
let de: DebugElement;
beforeEach(async(() => {
TestBed
.configureTestingModule({
declarations: [
PlanSideDisplayComponent,
StageDetailsComponent,
StepDetailsComponent,
],
imports: [
MatTabsModule,
MatGridListModule,
MatFormFieldModule,
MatButtonModule,
MatCheckboxModule,
MatSelectModule,
MatCardModule,
MatExpansionModule,
MatInputModule,
MatPaginatorModule,
MatTableModule,
MatGridListModule,
MatMenuModule,
MatIconModule,
],
})
.compileComponents();
fixture = TestBed.createComponent(PlanSideDisplayComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
}));
it('should render the containers', () => {
fixture.detectChanges();
const stage = de.query(By.css('app-stage-details')).nativeElement;
expect(stage).toBeTruthy();
const steps = de.query(By.css('app-step-details')).nativeElement;
expect(steps).toBeTruthy();
});
it('should render text in the app-stage-details', () => {
component.stageDetails = 'hello world';
fixture.detectChanges();
const pre = de.query(By.css('app-stage-details pre')).nativeElement;
expect(pre.textContent).toEqual('hello world'); | });
}); | random_line_split |
|
main.rs | extern crate sdl2;
extern crate rand;
extern crate tile_engine;
extern crate chrono;
extern crate dungeon_generator;
extern crate sdl2_image;
mod visualizer;
mod game;
mod unit;
mod common;
mod ai;
mod portal;
use sdl2::event::Event;
use visualizer::Visualizer;
use game::Game;
use chrono::{DateTime, UTC};
use std::time::Duration;
use sdl2_image::{INIT_PNG, INIT_JPG};
const MS_PER_UPDATE: i64 = 15;
fn | () {
// start sdl2 with everything
let ctx = sdl2::init().unwrap();
let video_ctx = ctx.video().unwrap();
let mut lag = 0;
let mut last_tick: DateTime<UTC> = UTC::now();
let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap();
// Create a window
let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() {
Ok(window) => window,
Err(err) => panic!("failed to create window: {:?}", err)
};
// Create a rendering context
let renderer = match window.renderer().build() {
Ok(renderer) => renderer,
Err(err) => panic!("failed to create renderer: {:?}", err)
};
let mut events = ctx.event_pump().unwrap();
let mut game = Game::new();
let mut visualizer = Visualizer::new(renderer);
// loop until we receive a QuitEvent
'event : loop {
for event in events.poll_iter() {
match event {
Event::Quit{..} => break 'event,
_ => game.proc_event(event),
}
}
let ms = (UTC::now() - last_tick).num_milliseconds();
last_tick = UTC::now();
lag = lag + ms;
while lag > MS_PER_UPDATE {
game.update();
lag = lag - MS_PER_UPDATE;
}
// println!("{}", 1000.0/(ms as f64));
visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64));
std::thread::sleep(Duration::from_millis(1));
}
}
| main | identifier_name |
main.rs | extern crate sdl2;
extern crate rand;
extern crate tile_engine;
extern crate chrono;
extern crate dungeon_generator;
extern crate sdl2_image;
mod visualizer;
mod game;
mod unit;
mod common;
mod ai;
mod portal;
use sdl2::event::Event;
use visualizer::Visualizer;
use game::Game;
use chrono::{DateTime, UTC};
use std::time::Duration;
use sdl2_image::{INIT_PNG, INIT_JPG};
const MS_PER_UPDATE: i64 = 15;
fn main() | {
// start sdl2 with everything
let ctx = sdl2::init().unwrap();
let video_ctx = ctx.video().unwrap();
let mut lag = 0;
let mut last_tick: DateTime<UTC> = UTC::now();
let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap();
// Create a window
let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() {
Ok(window) => window,
Err(err) => panic!("failed to create window: {:?}", err)
};
// Create a rendering context
let renderer = match window.renderer().build() {
Ok(renderer) => renderer,
Err(err) => panic!("failed to create renderer: {:?}", err)
};
let mut events = ctx.event_pump().unwrap();
let mut game = Game::new();
let mut visualizer = Visualizer::new(renderer);
// loop until we receive a QuitEvent
'event : loop {
for event in events.poll_iter() {
match event {
Event::Quit{..} => break 'event,
_ => game.proc_event(event),
}
}
let ms = (UTC::now() - last_tick).num_milliseconds();
last_tick = UTC::now();
lag = lag + ms;
while lag > MS_PER_UPDATE {
game.update();
lag = lag - MS_PER_UPDATE;
}
// println!("{}", 1000.0/(ms as f64));
visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64));
std::thread::sleep(Duration::from_millis(1));
}
} | identifier_body |
|
main.rs | extern crate sdl2;
extern crate rand;
extern crate tile_engine;
extern crate chrono;
extern crate dungeon_generator;
extern crate sdl2_image;
mod visualizer;
mod game;
mod unit;
mod common;
mod ai;
mod portal;
use sdl2::event::Event;
use visualizer::Visualizer;
use game::Game;
use chrono::{DateTime, UTC};
use std::time::Duration;
use sdl2_image::{INIT_PNG, INIT_JPG};
const MS_PER_UPDATE: i64 = 15;
fn main() {
// start sdl2 with everything
let ctx = sdl2::init().unwrap();
let video_ctx = ctx.video().unwrap();
let mut lag = 0;
let mut last_tick: DateTime<UTC> = UTC::now();
let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap();
// Create a window
let window = match video_ctx.window("Mageon", common::DEF_WINDOW_WIDTH, common::DEF_WINDOW_HEIGHT).position_centered().opengl().build() {
Ok(window) => window,
Err(err) => panic!("failed to create window: {:?}", err)
};
// Create a rendering context
let renderer = match window.renderer().build() {
Ok(renderer) => renderer,
Err(err) => panic!("failed to create renderer: {:?}", err)
};
let mut events = ctx.event_pump().unwrap();
let mut game = Game::new(); |
let mut visualizer = Visualizer::new(renderer);
// loop until we receive a QuitEvent
'event : loop {
for event in events.poll_iter() {
match event {
Event::Quit{..} => break 'event,
_ => game.proc_event(event),
}
}
let ms = (UTC::now() - last_tick).num_milliseconds();
last_tick = UTC::now();
lag = lag + ms;
while lag > MS_PER_UPDATE {
game.update();
lag = lag - MS_PER_UPDATE;
}
// println!("{}", 1000.0/(ms as f64));
visualizer.draw(&game, (lag as f64)/(MS_PER_UPDATE as f64));
std::thread::sleep(Duration::from_millis(1));
}
} | random_line_split |
|
BBSProfile.ts | import {Document, Model, Schema, Types, model} from 'mongoose'
import {IUser} from './User'
const ObjectId = Schema.Types.ObjectId
const BBSProfileSchema = new Schema({
// 用户
user: {type: ObjectId, ref: 'User', required: true},
// uid
uid: {type: String, required: true},
// 用户名
username: {type: String, required: true},
// 头像
avatar: {type: String},
// 注册时间
joinAt: {type: Date}
}, {
timestamps: true
})
export interface IBBSProfile extends Document { | uid: String,
username: String,
avatar: String,
joinAt: Date
}
export interface IBBSProfileModel extends Model<IBBSProfile> {}
export default model<IBBSProfile, IBBSProfileModel>('BBSProfile', BBSProfileSchema) | user: Types.ObjectId | IUser, | random_line_split |
ppc.manager.js | (function(){
// Manager (static)
ppc.manager = cloz(base, {
init: function(){
try {
ppc.logger.get('add', 'PPCの初期化を開始しました', 0, 'start initialization');
// 最大同時接続数を設定
ppc.user.set('connections', ppc.parser.created.get('val', 'connections'));
// 測定日時を設定
var now = (new Date()).getTime() + (new Date()).getTimezoneOffset() * 60 * 1000 + 540 * 60 * 1000;
ppc.user.set('now', now);
// 環境設定から最大測定対象数を取得
var max_illusts = Number(ppc.parser.created.get('val', 'max_illusts'));
// 最大測定対象数が測定対象上限数を上回っている場合、測定対象上限数丸める
if (max_illusts > ppc.admin.get('max_illusts')) {
ppc.user.set('illusts', ppc.admin.get('max_illusts'));
}
// 最大測定対象数が測定対象下限数を下回っている場合、測定対象下限数に丸める
if (max_illusts < ppc.admin.get('min_illusts')) {
ppc.user.set('illusts', ppc.admin.get('min_illusts'));
}
// 測定するイラスト数を設定
var illusts = ppc.user.set('illusts', ppc.parser.home.get('length', 'illust'));
// 最大測定対象数より表示されているイラストが多い場合、最大測定対象数に丸める
if (illusts > max_illusts) {
ppc.user.set('illusts', max_illusts);
}
// イラスト投稿数が0または正しく取得できなかった場合、処理を停止
if (!ppc.user.get('illusts')) {
ppc.logger.get('add', '作品投稿数が取得できませんでした', 3);
return false;
}
// 各イラストについてオブジェクトを生成し、配列に格納
var box = {}; // ID重複確認用
for (var i = 0; i < ppc.user.get('illusts'); i++) {
var id = ppc.parser.home.get('illust_id', i);
if (!isFinite(id)) {
ppc.logger.get('add', '作品のIDが取得できませんでした (index = ' + i + ')', 3);
return false;
}
ppc.logger.get('add', 'イラストのIDを取得しました => ' + id + ' (index = ' + i + ')', 0);
for (var k in box) {
if (box[k] == id) {
ppc.logger.get('add', '作品IDの競合が検出されました', 3);
return false;
}
}
box[i] = id;
var ins = cloz(ppc.illust, {
id: id,
});
ppc.illusts[i] = ins;
}
ppc.logger.get('add', 'PPCの初期化を完了しました', 0, 'end initialization');
return true;
}
catch (e) {
ppc.logger.get('error', e);
}
},
run: function(){
ppc.logger.get('add', '測定を開始しました', 0, 'start analyzing');
// タブを切り替える
ppc.parser.created.get('jq', 'tab_group').tabs({
disabled: [2],
}).tabs('option', 'active', 1);
if (!ppc.ajax.illust.get('init')) {
return false;
}
if (!ppc.ajax.illust.get('run')) {
return false;
}
return true;
},
finish: function(){
ppc.logger.get('add', '測定を完了しました', 0, 'end analyzing');
if (!this.get('_process')) {
return false;
}
return true;
},
_process: function(){
ppc.logger.get('add', 'データ処理を開始しました', 0);
try {
for (var i = 0; i < ppc.user.get('illusts'); i++) {
$html = ppc.illusts[i].get('jq');
// イラストごとにオブジェクトを継承
ppc.parser.illust.illusts[i] = cloz(ppc.parser.illust, {
$doc: $html,
$image_response: null,
});
}
// イラスト情報の登録
for (var j = 0; j < ppc.user.get('illusts'); j++) {
var illust = ppc.illusts[j],
parser = ppc.parser.illust.illusts[j];
// ID・サムネイル
var id = ppc.parser.home.get('illust_id', j),
$thumbnail = ppc.parser.home.get('$illust_thumbnail', j);
illust.set('id', id);
illust.set('$thumbnail', $thumbnail);
// タイトル
var title = parser.get('text', 'title');
illust.set('title', title);
// 総合ブックマーク数・公開ブックマーク数・非公開ブックマーク数
var $bookmarked = parser.get('jq', 'bookmarked'),
$bookmarked_total = parser.get('jq', 'bookmarked_total'),
bookmarked_total = 0,
bookmarked_public = 0,
bookmarked_private = 0;
// 1つ以上のブックマークがある場合
if ($bookmarked_total.length) {
bookmarked_total = $bookmarked_total.text().number(0);
}
// 1つ以上の公開ブックマークがある場合
if ($bookmarked.length) {
var bookmarked = $bookmarked.text().number(null);
// 公開ブックマークしかない場合
if (bookmarked.length < 3) {
bookmarked_public = bookmarked_total;
}
// 非公開ブックマークがある場合
else {
bookmarked_public = bookmarked[1].number(0);
bookmarked_private = bookmarked[2].number(0);
}
}
// 公開ブックマークがない場合
else {
bookmarked_private = bookmarked_total;
}
illust.set('bookmarked_total', bookmarked_total);
illust.set('bookmarked_public', bookmarked_public);
illust.set('bookmarked_private', bookmarked_private);
illust.set('bookmarked_public_ratio', ppc.math.get('div', bookmarked_public * 100, bookmarked_total));
// 評価回数・総合点・コメン | ting-count'),
scored = ppc.parser.home.get('illust_figures', j, 'score'),
commented = ppc.parser.home.get('illust_figures', j, 'comments'),
viewed = ppc.parser.home.get('illust_figures', j, 'views');
illust.set('rated', rated);
illust.set('scored', scored);
illust.set('commented', commented);
illust.set('viewed', viewed);
illust.set('scored_average', ppc.math.get('div', scored, rated));
illust.set('rated_ratio', ppc.math.get('div', rated * 100, viewed));
illust.set('bookmarked_ratio', ppc.math.get('div', bookmarked_total * 100, viewed));
// 投稿日時
var timestamp = parser.get('text', 'datetime'),
timestamp_a = timestamp.number(null),
datetime = new Date(timestamp_a[0], timestamp_a[1] - 1, timestamp_a[2], timestamp_a[3], timestamp_a[4], timestamp_a[5], 0),
timestamp_b = timestamp.split(' '),
date = timestamp_b[0],
time = timestamp_b[1],
milliseconds = datetime.getTime(),
interval = ppc.user.get('now') - milliseconds;
illust.set({
timestamp: timestamp,
date: date,
time: time,
milliseconds: milliseconds,
interval: interval, // ミリ秒単位の経過時間
interval_days: interval / (1000 * 60 * 60 * 24), // 日単位の経過時間
});
// HOT
var hot = ppc.math.get('div', viewed, interval / (1000 * 60 * 60 * 24));
illust.set('hot', hot);
// イメレスbadge
$image_response = parser.get('jq', 'image_response');
illust.set('$image_response', $image_response);
// タグ
$tags = parser.get('jq', 'tags');
illust.set('$tags', $tags);
// タグ数
tags_num_total = parser.get('length', 'tags_num_total');
tags_num_self = parser.get('length', 'tags_num_self');
illust.set({
tags_num_total: tags_num_total,
tags_num_self: tags_num_self,
});
// 最新ブックマーク
$bookmarked_latest = parser.get('jq', 'bookmarked_latest');
illust.set('$bookmarked_latest', $bookmarked_latest);
}
// ユーザーID(数字)・ニックネーム・投稿数
var user_name = ppc.parser.illust.illusts[0].get('text', 'user_name'),
posted = ppc.parser.home.get('text', 'posted').number(0);
ppc.user.set({
nickname: user_name,
posted: posted,
});
this.get('_calc');
}
catch (e){
ppc.logger.get('error', e);
return false;
}
ppc.logger.get('add', 'データ処理を完了しました', 0);
},
_calc: function(){
ppc.logger.get('add', '計算を開始しました');
// 各パラメータ合計
var rated_sum = ppc.math.get('sum', ppc.illusts, 'rated'),
scored_sum = ppc.math.get('sum', ppc.illusts, 'scored'),
commented_sum = ppc.math.get('sum', ppc.illusts, 'commented'),
viewed_sum = ppc.math.get('sum', ppc.illusts, 'viewed'),
bookmarked_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_total'),
bookmarked_public_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_public'),
hot_sum = ppc.math.get('sum', ppc.illusts, 'hot');
ppc.user.set({
rated_sum: rated_sum,
scored_sum: scored_sum,
commented_sum: commented_sum,
viewed_sum: viewed_sum,
bookmarked_sum: bookmarked_sum,
bookmarked_public_sum: bookmarked_public_sum,
hot_sum: hot_sum | 0,
});
try {
var now = ppc.user.get('now'),
illusts = ppc.user.get('illusts'),
followers = ppc.user.get('followers'),
my_pixiv = ppc.user.get('my_pixiv'),
total_power = 0,
pixiv_power = 0;
var index_last = illusts - 1,
interval_longest = (now - ppc.illusts[index_last].get('milliseconds')) / (1000 * 60 * 60 * 24);
var interval_average = interval_longest / illusts;
ppc.user.set({
interval_longest: interval_longest,
interval_average: interval_average.toFixed(1),
});
for (var i = 0; i < illusts; i++) {
var illust = ppc.illusts[i],
interval = illust.get('interval'),
freshment = ppc.math.get('freshment', interval_average, interval),
power = 0,
bt = illust.get('bookmarked_total'),
bpb = illust.get('bookmarked_public'),
bpr = illust.get('bookmarked_private'),
r = illust.get('rated'),
s = illust.get('scored'),
c = illust.get('commented'),
v = illust.get('viewed');
if (v) {
power = c * 10;
power += v;
power += bt * bpb * 1000 / v;
if (r) {
power += s * s / r;
}
power *= freshment;
power = Math.round(power);
total_power += power;
}
illust.set({
freshment: freshment,
power: power,
});
// Elements
var elements = [
['現在', null],
['閲覧', v],
['評価', r],
['点', s],
['ブクマ', bt],
['日', illust.get('interval_days')],
['パワー', power]
];
illust.set('elements', elements);
}
pixiv_power = ppc.math.get('pixivPower', followers, my_pixiv, total_power, hot_sum);
ppc.user.set({
total_power: Math.ceil(total_power),
pixiv_power: Math.ceil(pixiv_power),
});
}
catch (e) {
ppc.logger.get('error', e);
return false;
}
ppc.logger.get('add', '計算を完了しました');
this.get('result');
},
result: function(){
ppc.logger.get('add', '結果表示を開始しました', 0);
ppc.renderer.get('remove', '#processing,#processing-description');
if (!ppc.old.get('result')) {
return false;
}
ppc.logger.get('add', '結果表示を終了しました', 0);
},
});
})();
| ト数・閲覧数
var rated = ppc.parser.home.get('illust_figures', j, 'ra | conditional_block |
ppc.manager.js | (function(){
// Manager (static)
ppc.manager = cloz(base, {
init: function(){
try {
ppc.logger.get('add', 'PPCの初期化を開始しました', 0, 'start initialization');
// 最大同時接続数を設定
ppc.user.set('connections', ppc.parser.created.get('val', 'connections'));
// 測定日時を設定
var now = (new Date()).getTime() + (new Date()).getTimezoneOffset() * 60 * 1000 + 540 * 60 * 1000;
ppc.user.set('now', now);
// 環境設定から最大測定対象数を取得
var max_illusts = Number(ppc.parser.created.get('val', 'max_illusts'));
// 最大測定対象数が測定対象上限数を上回っている場合、測定対象上限数丸める
if (max_illusts > ppc.admin.get('max_illusts')) {
ppc.user.set('illusts', ppc.admin.get('max_illusts')); | }
// 最大測定対象数が測定対象下限数を下回っている場合、測定対象下限数に丸める
if (max_illusts < ppc.admin.get('min_illusts')) {
ppc.user.set('illusts', ppc.admin.get('min_illusts'));
}
// 測定するイラスト数を設定
var illusts = ppc.user.set('illusts', ppc.parser.home.get('length', 'illust'));
// 最大測定対象数より表示されているイラストが多い場合、最大測定対象数に丸める
if (illusts > max_illusts) {
ppc.user.set('illusts', max_illusts);
}
// イラスト投稿数が0または正しく取得できなかった場合、処理を停止
if (!ppc.user.get('illusts')) {
ppc.logger.get('add', '作品投稿数が取得できませんでした', 3);
return false;
}
// 各イラストについてオブジェクトを生成し、配列に格納
var box = {}; // ID重複確認用
for (var i = 0; i < ppc.user.get('illusts'); i++) {
var id = ppc.parser.home.get('illust_id', i);
if (!isFinite(id)) {
ppc.logger.get('add', '作品のIDが取得できませんでした (index = ' + i + ')', 3);
return false;
}
ppc.logger.get('add', 'イラストのIDを取得しました => ' + id + ' (index = ' + i + ')', 0);
for (var k in box) {
if (box[k] == id) {
ppc.logger.get('add', '作品IDの競合が検出されました', 3);
return false;
}
}
box[i] = id;
var ins = cloz(ppc.illust, {
id: id,
});
ppc.illusts[i] = ins;
}
ppc.logger.get('add', 'PPCの初期化を完了しました', 0, 'end initialization');
return true;
}
catch (e) {
ppc.logger.get('error', e);
}
},
run: function(){
ppc.logger.get('add', '測定を開始しました', 0, 'start analyzing');
// タブを切り替える
ppc.parser.created.get('jq', 'tab_group').tabs({
disabled: [2],
}).tabs('option', 'active', 1);
if (!ppc.ajax.illust.get('init')) {
return false;
}
if (!ppc.ajax.illust.get('run')) {
return false;
}
return true;
},
finish: function(){
ppc.logger.get('add', '測定を完了しました', 0, 'end analyzing');
if (!this.get('_process')) {
return false;
}
return true;
},
_process: function(){
ppc.logger.get('add', 'データ処理を開始しました', 0);
try {
for (var i = 0; i < ppc.user.get('illusts'); i++) {
$html = ppc.illusts[i].get('jq');
// イラストごとにオブジェクトを継承
ppc.parser.illust.illusts[i] = cloz(ppc.parser.illust, {
$doc: $html,
$image_response: null,
});
}
// イラスト情報の登録
for (var j = 0; j < ppc.user.get('illusts'); j++) {
var illust = ppc.illusts[j],
parser = ppc.parser.illust.illusts[j];
// ID・サムネイル
var id = ppc.parser.home.get('illust_id', j),
$thumbnail = ppc.parser.home.get('$illust_thumbnail', j);
illust.set('id', id);
illust.set('$thumbnail', $thumbnail);
// タイトル
var title = parser.get('text', 'title');
illust.set('title', title);
// 総合ブックマーク数・公開ブックマーク数・非公開ブックマーク数
var $bookmarked = parser.get('jq', 'bookmarked'),
$bookmarked_total = parser.get('jq', 'bookmarked_total'),
bookmarked_total = 0,
bookmarked_public = 0,
bookmarked_private = 0;
// 1つ以上のブックマークがある場合
if ($bookmarked_total.length) {
bookmarked_total = $bookmarked_total.text().number(0);
}
// 1つ以上の公開ブックマークがある場合
if ($bookmarked.length) {
var bookmarked = $bookmarked.text().number(null);
// 公開ブックマークしかない場合
if (bookmarked.length < 3) {
bookmarked_public = bookmarked_total;
}
// 非公開ブックマークがある場合
else {
bookmarked_public = bookmarked[1].number(0);
bookmarked_private = bookmarked[2].number(0);
}
}
// 公開ブックマークがない場合
else {
bookmarked_private = bookmarked_total;
}
illust.set('bookmarked_total', bookmarked_total);
illust.set('bookmarked_public', bookmarked_public);
illust.set('bookmarked_private', bookmarked_private);
illust.set('bookmarked_public_ratio', ppc.math.get('div', bookmarked_public * 100, bookmarked_total));
// 評価回数・総合点・コメント数・閲覧数
var rated = ppc.parser.home.get('illust_figures', j, 'rating-count'),
scored = ppc.parser.home.get('illust_figures', j, 'score'),
commented = ppc.parser.home.get('illust_figures', j, 'comments'),
viewed = ppc.parser.home.get('illust_figures', j, 'views');
illust.set('rated', rated);
illust.set('scored', scored);
illust.set('commented', commented);
illust.set('viewed', viewed);
illust.set('scored_average', ppc.math.get('div', scored, rated));
illust.set('rated_ratio', ppc.math.get('div', rated * 100, viewed));
illust.set('bookmarked_ratio', ppc.math.get('div', bookmarked_total * 100, viewed));
// 投稿日時
var timestamp = parser.get('text', 'datetime'),
timestamp_a = timestamp.number(null),
datetime = new Date(timestamp_a[0], timestamp_a[1] - 1, timestamp_a[2], timestamp_a[3], timestamp_a[4], timestamp_a[5], 0),
timestamp_b = timestamp.split(' '),
date = timestamp_b[0],
time = timestamp_b[1],
milliseconds = datetime.getTime(),
interval = ppc.user.get('now') - milliseconds;
illust.set({
timestamp: timestamp,
date: date,
time: time,
milliseconds: milliseconds,
interval: interval, // ミリ秒単位の経過時間
interval_days: interval / (1000 * 60 * 60 * 24), // 日単位の経過時間
});
// HOT
var hot = ppc.math.get('div', viewed, interval / (1000 * 60 * 60 * 24));
illust.set('hot', hot);
// イメレスbadge
$image_response = parser.get('jq', 'image_response');
illust.set('$image_response', $image_response);
// タグ
$tags = parser.get('jq', 'tags');
illust.set('$tags', $tags);
// タグ数
tags_num_total = parser.get('length', 'tags_num_total');
tags_num_self = parser.get('length', 'tags_num_self');
illust.set({
tags_num_total: tags_num_total,
tags_num_self: tags_num_self,
});
// 最新ブックマーク
$bookmarked_latest = parser.get('jq', 'bookmarked_latest');
illust.set('$bookmarked_latest', $bookmarked_latest);
}
// ユーザーID(数字)・ニックネーム・投稿数
var user_name = ppc.parser.illust.illusts[0].get('text', 'user_name'),
posted = ppc.parser.home.get('text', 'posted').number(0);
ppc.user.set({
nickname: user_name,
posted: posted,
});
this.get('_calc');
}
catch (e){
ppc.logger.get('error', e);
return false;
}
ppc.logger.get('add', 'データ処理を完了しました', 0);
},
_calc: function(){
ppc.logger.get('add', '計算を開始しました');
// 各パラメータ合計
var rated_sum = ppc.math.get('sum', ppc.illusts, 'rated'),
scored_sum = ppc.math.get('sum', ppc.illusts, 'scored'),
commented_sum = ppc.math.get('sum', ppc.illusts, 'commented'),
viewed_sum = ppc.math.get('sum', ppc.illusts, 'viewed'),
bookmarked_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_total'),
bookmarked_public_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_public'),
hot_sum = ppc.math.get('sum', ppc.illusts, 'hot');
ppc.user.set({
rated_sum: rated_sum,
scored_sum: scored_sum,
commented_sum: commented_sum,
viewed_sum: viewed_sum,
bookmarked_sum: bookmarked_sum,
bookmarked_public_sum: bookmarked_public_sum,
hot_sum: hot_sum | 0,
});
try {
var now = ppc.user.get('now'),
illusts = ppc.user.get('illusts'),
followers = ppc.user.get('followers'),
my_pixiv = ppc.user.get('my_pixiv'),
total_power = 0,
pixiv_power = 0;
var index_last = illusts - 1,
interval_longest = (now - ppc.illusts[index_last].get('milliseconds')) / (1000 * 60 * 60 * 24);
var interval_average = interval_longest / illusts;
ppc.user.set({
interval_longest: interval_longest,
interval_average: interval_average.toFixed(1),
});
for (var i = 0; i < illusts; i++) {
var illust = ppc.illusts[i],
interval = illust.get('interval'),
freshment = ppc.math.get('freshment', interval_average, interval),
power = 0,
bt = illust.get('bookmarked_total'),
bpb = illust.get('bookmarked_public'),
bpr = illust.get('bookmarked_private'),
r = illust.get('rated'),
s = illust.get('scored'),
c = illust.get('commented'),
v = illust.get('viewed');
if (v) {
power = c * 10;
power += v;
power += bt * bpb * 1000 / v;
if (r) {
power += s * s / r;
}
power *= freshment;
power = Math.round(power);
total_power += power;
}
illust.set({
freshment: freshment,
power: power,
});
// Elements
var elements = [
['現在', null],
['閲覧', v],
['評価', r],
['点', s],
['ブクマ', bt],
['日', illust.get('interval_days')],
['パワー', power]
];
illust.set('elements', elements);
}
pixiv_power = ppc.math.get('pixivPower', followers, my_pixiv, total_power, hot_sum);
ppc.user.set({
total_power: Math.ceil(total_power),
pixiv_power: Math.ceil(pixiv_power),
});
}
catch (e) {
ppc.logger.get('error', e);
return false;
}
ppc.logger.get('add', '計算を完了しました');
this.get('result');
},
result: function(){
ppc.logger.get('add', '結果表示を開始しました', 0);
ppc.renderer.get('remove', '#processing,#processing-description');
if (!ppc.old.get('result')) {
return false;
}
ppc.logger.get('add', '結果表示を終了しました', 0);
},
});
})(); | random_line_split |
|
functions.rs | use neon::prelude::*;
use neon::object::This;
use neon::result::Throw;
fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
let x = cx.argument::<JsNumber>(0)?.value();
Ok(cx.number(x + 1.0))
}
pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> {
JsFunction::new(&mut cx, add1)
}
pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)];
let null = cx.null();
f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let zero = cx.number(0.0);
let o = f.construct(&mut cx, vec![zero])?;
let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?;
let args: Vec<Handle<JsValue>> = vec![];
get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
trait CheckArgument<'a> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>;
}
impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> {
self.argument::<V>(i)
}
}
pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.check_argument::<JsString>(0)?;
cx.check_argument::<JsNumber>(1)?;
Ok(cx.undefined())
}
pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> {
panic!("zomg")
}
pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err();
panic!("this should override the RangeError")
}
pub fn | (mut cx: FunctionContext) -> JsResult<JsNumber> {
let n = cx.len();
Ok(cx.number(n))
}
pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.this().upcast())
}
pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let this = cx.this();
let this = this.downcast::<JsObject>().or_throw(&mut cx)?;
let t = cx.boolean(true);
this.set(&mut cx, "modified", t)?;
Ok(cx.undefined())
}
pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let b = cx.argument_opt(0).is_some();
Ok(cx.boolean(b))
}
pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.argument(0)?;
Ok(s)
}
pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = 0;
for _ in 1..100 {
cx.execute_scoped(|mut cx| {
let n = cx.number(1);
i += n.value() as i32;
});
}
Ok(cx.number(i))
}
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = cx.number(0);
for _ in 1..100 {
i = cx.compute_scoped(|mut cx| {
let n = cx.number(1);
Ok(cx.number((i.value() as i32) + (n.value() as i32)))
})?;
}
Ok(i)
}
pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast());
Ok(cx.try_catch(|cx| {
let _ = cx.throw(v)?;
Ok(cx.string("unreachable").upcast())
}).unwrap_or_else(|err| err))
}
pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let f: Handle<JsFunction> = cx.argument(0)?;
Ok(cx.try_catch(|cx| {
let global = cx.global();
let args: Vec<Handle<JsValue>> = vec![];
f.call(cx, global, args)
}).unwrap_or_else(|err| err))
}
pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { panic!("oh no") })
.unwrap_or_else(|err| err))
}
pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { Err(Throw) })
.unwrap_or_else(|err| err))
}
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.string("hi");
if let Err(e) = s.downcast::<JsNumber>() {
Ok(cx.string(format!("{}", e)))
} else {
panic!()
}
}
| num_arguments | identifier_name |
functions.rs | use neon::prelude::*;
use neon::object::This;
use neon::result::Throw;
fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
let x = cx.argument::<JsNumber>(0)?.value();
Ok(cx.number(x + 1.0))
}
pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> {
JsFunction::new(&mut cx, add1)
}
pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)];
let null = cx.null();
f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let zero = cx.number(0.0);
let o = f.construct(&mut cx, vec![zero])?;
let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?;
let args: Vec<Handle<JsValue>> = vec![];
get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
trait CheckArgument<'a> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>;
}
impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> {
self.argument::<V>(i)
}
}
pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.check_argument::<JsString>(0)?;
cx.check_argument::<JsNumber>(1)?;
Ok(cx.undefined())
}
pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> {
panic!("zomg")
}
pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err();
panic!("this should override the RangeError")
}
pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> {
let n = cx.len();
Ok(cx.number(n))
}
pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.this().upcast())
}
pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let this = cx.this();
let this = this.downcast::<JsObject>().or_throw(&mut cx)?;
let t = cx.boolean(true);
this.set(&mut cx, "modified", t)?;
Ok(cx.undefined())
}
pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let b = cx.argument_opt(0).is_some();
Ok(cx.boolean(b))
}
pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.argument(0)?;
Ok(s)
}
pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = 0;
for _ in 1..100 {
cx.execute_scoped(|mut cx| {
let n = cx.number(1);
i += n.value() as i32;
});
}
Ok(cx.number(i))
}
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = cx.number(0);
for _ in 1..100 {
i = cx.compute_scoped(|mut cx| {
let n = cx.number(1);
Ok(cx.number((i.value() as i32) + (n.value() as i32)))
})?;
}
Ok(i)
}
pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast());
Ok(cx.try_catch(|cx| {
let _ = cx.throw(v)?;
Ok(cx.string("unreachable").upcast())
}).unwrap_or_else(|err| err))
}
pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let f: Handle<JsFunction> = cx.argument(0)?;
Ok(cx.try_catch(|cx| {
let global = cx.global();
let args: Vec<Handle<JsValue>> = vec![];
f.call(cx, global, args)
}).unwrap_or_else(|err| err))
}
pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { panic!("oh no") })
.unwrap_or_else(|err| err))
}
pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { Err(Throw) })
.unwrap_or_else(|err| err))
}
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> | {
let s = cx.string("hi");
if let Err(e) = s.downcast::<JsNumber>() {
Ok(cx.string(format!("{}", e)))
} else {
panic!()
}
} | identifier_body |
|
functions.rs | use neon::prelude::*;
use neon::object::This;
use neon::result::Throw;
fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
let x = cx.argument::<JsNumber>(0)?.value();
Ok(cx.number(x + 1.0))
}
pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> {
JsFunction::new(&mut cx, add1)
}
pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)];
let null = cx.null();
f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let zero = cx.number(0.0);
let o = f.construct(&mut cx, vec![zero])?;
let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?;
let args: Vec<Handle<JsValue>> = vec![];
get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
trait CheckArgument<'a> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>;
}
impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> {
self.argument::<V>(i)
}
}
pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.check_argument::<JsString>(0)?;
cx.check_argument::<JsNumber>(1)?;
Ok(cx.undefined())
}
pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> {
panic!("zomg")
}
pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err();
panic!("this should override the RangeError")
}
pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> {
let n = cx.len();
Ok(cx.number(n))
}
pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.this().upcast())
}
pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let this = cx.this();
let this = this.downcast::<JsObject>().or_throw(&mut cx)?;
let t = cx.boolean(true);
this.set(&mut cx, "modified", t)?;
Ok(cx.undefined())
}
pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let b = cx.argument_opt(0).is_some();
Ok(cx.boolean(b))
}
pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.argument(0)?;
Ok(s)
}
pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = 0;
for _ in 1..100 {
cx.execute_scoped(|mut cx| {
let n = cx.number(1);
i += n.value() as i32;
});
} |
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = cx.number(0);
for _ in 1..100 {
i = cx.compute_scoped(|mut cx| {
let n = cx.number(1);
Ok(cx.number((i.value() as i32) + (n.value() as i32)))
})?;
}
Ok(i)
}
pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast());
Ok(cx.try_catch(|cx| {
let _ = cx.throw(v)?;
Ok(cx.string("unreachable").upcast())
}).unwrap_or_else(|err| err))
}
pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let f: Handle<JsFunction> = cx.argument(0)?;
Ok(cx.try_catch(|cx| {
let global = cx.global();
let args: Vec<Handle<JsValue>> = vec![];
f.call(cx, global, args)
}).unwrap_or_else(|err| err))
}
pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { panic!("oh no") })
.unwrap_or_else(|err| err))
}
pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { Err(Throw) })
.unwrap_or_else(|err| err))
}
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.string("hi");
if let Err(e) = s.downcast::<JsNumber>() {
Ok(cx.string(format!("{}", e)))
} else {
panic!()
}
} | Ok(cx.number(i))
} | random_line_split |
functions.rs | use neon::prelude::*;
use neon::object::This;
use neon::result::Throw;
fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
let x = cx.argument::<JsNumber>(0)?.value();
Ok(cx.number(x + 1.0))
}
pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> {
JsFunction::new(&mut cx, add1)
}
pub fn call_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let args: Vec<Handle<JsNumber>> = vec![cx.number(16.0)];
let null = cx.null();
f.call(&mut cx, null, args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
pub fn construct_js_function(mut cx: FunctionContext) -> JsResult<JsNumber> {
let f = cx.argument::<JsFunction>(0)?;
let zero = cx.number(0.0);
let o = f.construct(&mut cx, vec![zero])?;
let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::<JsFunction>().or_throw(&mut cx)?;
let args: Vec<Handle<JsValue>> = vec![];
get_utc_full_year_method.call(&mut cx, o.upcast::<JsValue>(), args)?.downcast::<JsNumber>().or_throw(&mut cx)
}
trait CheckArgument<'a> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V>;
}
impl<'a, T: This> CheckArgument<'a> for CallContext<'a, T> {
fn check_argument<V: Value>(&mut self, i: i32) -> JsResult<'a, V> {
self.argument::<V>(i)
}
}
pub fn check_string_and_number(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.check_argument::<JsString>(0)?;
cx.check_argument::<JsNumber>(1)?;
Ok(cx.undefined())
}
pub fn panic(_: FunctionContext) -> JsResult<JsUndefined> {
panic!("zomg")
}
pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult<JsUndefined> {
cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err();
panic!("this should override the RangeError")
}
pub fn num_arguments(mut cx: FunctionContext) -> JsResult<JsNumber> {
let n = cx.len();
Ok(cx.number(n))
}
pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.this().upcast())
}
pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let this = cx.this();
let this = this.downcast::<JsObject>().or_throw(&mut cx)?;
let t = cx.boolean(true);
this.set(&mut cx, "modified", t)?;
Ok(cx.undefined())
}
pub fn is_argument_zero_some(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let b = cx.argument_opt(0).is_some();
Ok(cx.boolean(b))
}
pub fn require_argument_zero_string(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.argument(0)?;
Ok(s)
}
pub fn execute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = 0;
for _ in 1..100 {
cx.execute_scoped(|mut cx| {
let n = cx.number(1);
i += n.value() as i32;
});
}
Ok(cx.number(i))
}
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> {
let mut i = cx.number(0);
for _ in 1..100 {
i = cx.compute_scoped(|mut cx| {
let n = cx.number(1);
Ok(cx.number((i.value() as i32) + (n.value() as i32)))
})?;
}
Ok(i)
}
pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast());
Ok(cx.try_catch(|cx| {
let _ = cx.throw(v)?;
Ok(cx.string("unreachable").upcast())
}).unwrap_or_else(|err| err))
}
pub fn call_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
let f: Handle<JsFunction> = cx.argument(0)?;
Ok(cx.try_catch(|cx| {
let global = cx.global();
let args: Vec<Handle<JsValue>> = vec![];
f.call(cx, global, args)
}).unwrap_or_else(|err| err))
}
pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { panic!("oh no") })
.unwrap_or_else(|err| err))
}
pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult<JsValue> {
Ok(cx.try_catch(|_| { Err(Throw) })
.unwrap_or_else(|err| err))
}
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.string("hi");
if let Err(e) = s.downcast::<JsNumber>() | else {
panic!()
}
}
| {
Ok(cx.string(format!("{}", e)))
} | conditional_block |
commands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { join } from 'path';
import { commands, workspace, window, Uri, ViewColumn, Range, Position } from 'vscode';
suite('commands namespace tests', () => {
test('getCommands', function (done) {
let p1 = commands.getCommands().then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(hasOneWithUnderscore);
}, done);
let p2 = commands.getCommands(true).then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(!hasOneWithUnderscore);
}, done);
Promise.all([p1, p2]).then(() => {
done();
}, done);
});
test('command with args', async function () {
let args: IArguments;
let registration = commands.registerCommand('t1', function () {
args = arguments;
});
await commands.executeCommand('t1', 'start');
registration.dispose();
assert.ok(args!);
assert.equal(args!.length, 1);
assert.equal(args![0], 'start');
});
test('editorCommand with extra args', function () {
let args: IArguments;
let registration = commands.registerTextEditorCommand('t1', function () {
args = arguments;
});
return workspace.openTextDocument(join(workspace.rootPath || '', './far.js')).then(doc => {
return window.showTextDocument(doc).then(_editor => {
return commands.executeCommand('t1', 12345, commands);
}).then(() => {
assert.ok(args);
assert.equal(args.length, 4);
assert.ok(args[2] === 12345);
assert.ok(args[3] === commands);
registration.dispose();
});
});
});
test('api-command: vscode.diff', function () {
let registration = workspace.registerTextDocumentContentProvider('sc', {
provideTextDocumentContent(uri) |
});
let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let c = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'Title', { selection: new Range(new Position(1, 1), new Position(1, 2)) }).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let d = commands.executeCommand('vscode.diff').then(() => assert.ok(false), () => assert.ok(true));
let e = commands.executeCommand('vscode.diff', 1, 2, 3).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d, e]);
});
test('api-command: vscode.open', function () {
let uri = Uri.parse(workspace.workspaceFolders![0].uri.toString() + '/image.png');
let a = commands.executeCommand('vscode.open', uri).then(() => assert.ok(true), () => assert.ok(false));
let b = commands.executeCommand('vscode.open', uri, ViewColumn.Two).then(() => assert.ok(true), () => assert.ok(false));
let c = commands.executeCommand('vscode.open').then(() => assert.ok(false), () => assert.ok(true));
let d = commands.executeCommand('vscode.open', uri, true).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d]);
});
}); | {
return `content of URI <b>${uri.toString()}</b>#${Math.random()}`;
} | identifier_body |
commands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { join } from 'path';
import { commands, workspace, window, Uri, ViewColumn, Range, Position } from 'vscode';
suite('commands namespace tests', () => {
test('getCommands', function (done) {
let p1 = commands.getCommands().then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(hasOneWithUnderscore);
}, done);
let p2 = commands.getCommands(true).then(commands => {
let hasOneWithUnderscore = false; | }
assert.ok(!hasOneWithUnderscore);
}, done);
Promise.all([p1, p2]).then(() => {
done();
}, done);
});
test('command with args', async function () {
let args: IArguments;
let registration = commands.registerCommand('t1', function () {
args = arguments;
});
await commands.executeCommand('t1', 'start');
registration.dispose();
assert.ok(args!);
assert.equal(args!.length, 1);
assert.equal(args![0], 'start');
});
test('editorCommand with extra args', function () {
let args: IArguments;
let registration = commands.registerTextEditorCommand('t1', function () {
args = arguments;
});
return workspace.openTextDocument(join(workspace.rootPath || '', './far.js')).then(doc => {
return window.showTextDocument(doc).then(_editor => {
return commands.executeCommand('t1', 12345, commands);
}).then(() => {
assert.ok(args);
assert.equal(args.length, 4);
assert.ok(args[2] === 12345);
assert.ok(args[3] === commands);
registration.dispose();
});
});
});
test('api-command: vscode.diff', function () {
let registration = workspace.registerTextDocumentContentProvider('sc', {
provideTextDocumentContent(uri) {
return `content of URI <b>${uri.toString()}</b>#${Math.random()}`;
}
});
let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let c = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'Title', { selection: new Range(new Position(1, 1), new Position(1, 2)) }).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let d = commands.executeCommand('vscode.diff').then(() => assert.ok(false), () => assert.ok(true));
let e = commands.executeCommand('vscode.diff', 1, 2, 3).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d, e]);
});
test('api-command: vscode.open', function () {
let uri = Uri.parse(workspace.workspaceFolders![0].uri.toString() + '/image.png');
let a = commands.executeCommand('vscode.open', uri).then(() => assert.ok(true), () => assert.ok(false));
let b = commands.executeCommand('vscode.open', uri, ViewColumn.Two).then(() => assert.ok(true), () => assert.ok(false));
let c = commands.executeCommand('vscode.open').then(() => assert.ok(false), () => assert.ok(true));
let d = commands.executeCommand('vscode.open', uri, true).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d]);
});
}); | for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
} | random_line_split |
commands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { join } from 'path';
import { commands, workspace, window, Uri, ViewColumn, Range, Position } from 'vscode';
suite('commands namespace tests', () => {
test('getCommands', function (done) {
let p1 = commands.getCommands().then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(hasOneWithUnderscore);
}, done);
let p2 = commands.getCommands(true).then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') |
}
assert.ok(!hasOneWithUnderscore);
}, done);
Promise.all([p1, p2]).then(() => {
done();
}, done);
});
test('command with args', async function () {
let args: IArguments;
let registration = commands.registerCommand('t1', function () {
args = arguments;
});
await commands.executeCommand('t1', 'start');
registration.dispose();
assert.ok(args!);
assert.equal(args!.length, 1);
assert.equal(args![0], 'start');
});
test('editorCommand with extra args', function () {
let args: IArguments;
let registration = commands.registerTextEditorCommand('t1', function () {
args = arguments;
});
return workspace.openTextDocument(join(workspace.rootPath || '', './far.js')).then(doc => {
return window.showTextDocument(doc).then(_editor => {
return commands.executeCommand('t1', 12345, commands);
}).then(() => {
assert.ok(args);
assert.equal(args.length, 4);
assert.ok(args[2] === 12345);
assert.ok(args[3] === commands);
registration.dispose();
});
});
});
test('api-command: vscode.diff', function () {
let registration = workspace.registerTextDocumentContentProvider('sc', {
provideTextDocumentContent(uri) {
return `content of URI <b>${uri.toString()}</b>#${Math.random()}`;
}
});
let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let c = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'Title', { selection: new Range(new Position(1, 1), new Position(1, 2)) }).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let d = commands.executeCommand('vscode.diff').then(() => assert.ok(false), () => assert.ok(true));
let e = commands.executeCommand('vscode.diff', 1, 2, 3).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d, e]);
});
test('api-command: vscode.open', function () {
let uri = Uri.parse(workspace.workspaceFolders![0].uri.toString() + '/image.png');
let a = commands.executeCommand('vscode.open', uri).then(() => assert.ok(true), () => assert.ok(false));
let b = commands.executeCommand('vscode.open', uri, ViewColumn.Two).then(() => assert.ok(true), () => assert.ok(false));
let c = commands.executeCommand('vscode.open').then(() => assert.ok(false), () => assert.ok(true));
let d = commands.executeCommand('vscode.open', uri, true).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d]);
});
}); | {
hasOneWithUnderscore = true;
break;
} | conditional_block |
commands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { join } from 'path';
import { commands, workspace, window, Uri, ViewColumn, Range, Position } from 'vscode';
suite('commands namespace tests', () => {
test('getCommands', function (done) {
let p1 = commands.getCommands().then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(hasOneWithUnderscore);
}, done);
let p2 = commands.getCommands(true).then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(!hasOneWithUnderscore);
}, done);
Promise.all([p1, p2]).then(() => {
done();
}, done);
});
test('command with args', async function () {
let args: IArguments;
let registration = commands.registerCommand('t1', function () {
args = arguments;
});
await commands.executeCommand('t1', 'start');
registration.dispose();
assert.ok(args!);
assert.equal(args!.length, 1);
assert.equal(args![0], 'start');
});
test('editorCommand with extra args', function () {
let args: IArguments;
let registration = commands.registerTextEditorCommand('t1', function () {
args = arguments;
});
return workspace.openTextDocument(join(workspace.rootPath || '', './far.js')).then(doc => {
return window.showTextDocument(doc).then(_editor => {
return commands.executeCommand('t1', 12345, commands);
}).then(() => {
assert.ok(args);
assert.equal(args.length, 4);
assert.ok(args[2] === 12345);
assert.ok(args[3] === commands);
registration.dispose();
});
});
});
test('api-command: vscode.diff', function () {
let registration = workspace.registerTextDocumentContentProvider('sc', {
| (uri) {
return `content of URI <b>${uri.toString()}</b>#${Math.random()}`;
}
});
let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let c = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'Title', { selection: new Range(new Position(1, 1), new Position(1, 2)) }).then(value => {
assert.ok(value === undefined);
registration.dispose();
});
let d = commands.executeCommand('vscode.diff').then(() => assert.ok(false), () => assert.ok(true));
let e = commands.executeCommand('vscode.diff', 1, 2, 3).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d, e]);
});
test('api-command: vscode.open', function () {
let uri = Uri.parse(workspace.workspaceFolders![0].uri.toString() + '/image.png');
let a = commands.executeCommand('vscode.open', uri).then(() => assert.ok(true), () => assert.ok(false));
let b = commands.executeCommand('vscode.open', uri, ViewColumn.Two).then(() => assert.ok(true), () => assert.ok(false));
let c = commands.executeCommand('vscode.open').then(() => assert.ok(false), () => assert.ok(true));
let d = commands.executeCommand('vscode.open', uri, true).then(() => assert.ok(false), () => assert.ok(true));
return Promise.all([a, b, c, d]);
});
}); | provideTextDocumentContent | identifier_name |
screenShare.js | 'use strict';
var SIGNALING_SERVER = 'https://112.108.40.152:443/';
var config = {
openSocket: function(config) {
console.log('s1');
/*
Firebase ver.
*/
var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , '');
var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel);
socket.channel = channel;
socket.on("child_added", function(data) {
console.log('s2');
config.onmessage && config.onmessage(data.val());
});
socket.send = function(data) {
console.log('s3');
this.push(data);
};
config.onopen && setTimeout(config.onopen, 1);
socket.onDisconnect().remove();
return socket;
/*
Socket.io ver. (Not yet)
*/
//var SIGNALING_SERVER = 'https://112.108.40.152:443/';
//
//config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
//var sender = Math.round(Math.random() * 999999999) + 999999999;
//
//io.connect(SIGNALING_SERVER).emit('new-channel', {
// channel: config.channel,
// sender: sender
//});
//
//var socket = io.connect(SIGNALING_SERVER + config.channel);
//socket.channel = config.channel;
//socket.on('connect', function () {
// if (config.callback) config.callback(socket);
//});
//
//socket.send = function (message) {
// socket.emit('message', {
// sender: sender,
// data: message
// });
//};
//
//socket.on('message', config.onmessage);
},
onRemoteStream: function(media) {
console.log('s4');
var video = media.video;
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
video.play();
},
onRoomFound: function(room) {
console.log('s5');
dualrtcUI.joinRoom({
roomToken: room.broadcaster,
joinUser: room.broadcaster
});
},
onNewParticipant: function(numberOfParticipants) {
console.log('s7');
//document.title = numberOfParticipants + ' users are viewing your screen!';
},
oniceconnectionstatechange: function(state) {
console.log('s8');
if(state == 'failed') {
alert('Failed to bypass Firewall rules.');
}
if(state == 'connected') {
alert('A user successfully received screen.');
}
}
}; // end of config
function captureUserMedia(callback, extensionAvailable) {
console.log('s9');
console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource);
var screen_constraints = {
mandatory: {
chromeMediaSource: DetectRTC.screen.chromeMediaSource,
maxWidth: screen.width > 1920 ? screen.width : 1920,
maxHeight: screen.height > 1080 ? screen.height : 1080
// minAspectRatio: 1.77
},
optional: [{ // non-official Google-only optional constraints
googTemporalLayeredScreencast: true
}, {
googLeakyBucket: true
}]
};
// try to check if extension is installed.
if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') {
DetectRTC.screen.isChromeExtensionAvailable(function(available) {
console.log('s10');
captureUserMedia(callback, available);
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) {
DetectRTC.screen.getSourceId(function(error) {
console.log('s11');
if(error && error == 'PermissionDeniedError') |
captureUserMedia(callback);
});
return;
}
if(isChrome && !DetectRTC.screen.sourceId) {
window.addEventListener('message', function (event) {
console.log('s12');
if (event.data && event.data.chromeMediaSourceId) {
var sourceId = event.data.chromeMediaSourceId;
DetectRTC.screen.sourceId = sourceId;
DetectRTC.screen.chromeMediaSource = 'desktop';
if (sourceId == 'PermissionDeniedError') {
return alert('User denied to share content of his screen.');
}
captureUserMedia(callback, true);
}
if (event.data && event.data.chromeExtensionStatus) {
warn('Screen capturing extension status is:', event.data.chromeExtensionStatus);
DetectRTC.screen.chromeMediaSource = 'screen';
captureUserMedia(callback, true);
}
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') {
screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId;
}
var constraints = {
audio: false,
video: screen_constraints
};
if(!!navigator.mozGetUserMedia) {
console.warn(Firefox_Screen_Capturing_Warning);
constraints.video = {
mozMediaSource: 'window',
mediaSource: 'window',
maxWidth: 1920,
maxHeight: 1080,
minAspectRatio: 1.77
};
}
console.log( JSON.stringify( constraints , null, '\t') );
var video = document.createElement('video');
video.setAttribute('autoplay', true);
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
getUserMedia({
video: video,
constraints: constraints,
onsuccess: function(stream) {
console.log('s13');
config.attachStream = stream;
callback && callback();
video.setAttribute('muted', true);
},
onerror: function() {
console.log('s14');
if (isChrome && location.protocol === 'http:') {
alert('Please test on HTTPS.');
} else if(isChrome) {
alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing');
}
else if(!!navigator.mozGetUserMedia) {
alert(Firefox_Screen_Capturing_Warning);
}
}
});
} // end of captureUserMedia
var dualrtcUI = dualrtc(config);
var videosContainer = document.getElementById('videos-container');
var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-');
var makeName = $('#makeName');
var joinName = $('#joinName');
var btnMakeRoom = $('#btnMakeRoom');
var btnJoinRoom = $('#btnJoinRoom');
var btnCopy = $('#btnCopy');
var divMake = $('#divMakeRoom');
var divJoin = $('#divJoinRoom');
var divScreen = $('#divScreen');
// about description
var divDescript = $('#divDescript');
var divInstallCE01 = $('#divInstallCE01');
var divInstallCE02 = $('#divInstallCE02');
var divWikiWDDM = $('#divWikiWDDM');
btnMakeRoom.click(function () {
if (makeName.val()) {
makeName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + makeName.val();
}
});
btnJoinRoom.click(function () {
if (joinName.val()) {
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + joinName.val();
}
});
btnCopy.click(function () {
makeName.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
});
divInstallCE01.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk';
});
divInstallCE02.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi';
});
divWikiWDDM.click(function () {
window.open('about:black').location.href = 'https://dualrtc-io.github.io/';
});
(function() {
if (location.hash.length <= 2) {
makeName.val(secure);
//makeName.attr('placeholder', secure);
}
else { // 방 들어왔을 때
var roomName = location.hash.substring(2, 21);
if (divMake.css('display') == 'block') $('#divMakeRoom').hide();
if (divJoin.css('display') == 'block') $('#divJoinRoom').hide();
if (divScreen.css('display') == 'none') $('#divScreen').show();
if (divDescript.css('display') == 'block') $('#divDescript').hide();
captureUserMedia(function() {
dualrtcUI.createRoom({
roomName: (roomName || 'Anonymous') + ' shared his screen with you'
});
});
}
})();
var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.';
| {
alert('PermissionDeniedError: User denied to share content of his screen.');
} | conditional_block |
screenShare.js | 'use strict';
var SIGNALING_SERVER = 'https://112.108.40.152:443/';
var config = {
openSocket: function(config) {
console.log('s1');
/*
Firebase ver.
*/
var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , '');
var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel);
socket.channel = channel;
socket.on("child_added", function(data) {
console.log('s2');
config.onmessage && config.onmessage(data.val());
});
socket.send = function(data) {
console.log('s3');
this.push(data);
};
config.onopen && setTimeout(config.onopen, 1);
socket.onDisconnect().remove();
return socket;
/*
Socket.io ver. (Not yet)
*/
//var SIGNALING_SERVER = 'https://112.108.40.152:443/';
//
//config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
//var sender = Math.round(Math.random() * 999999999) + 999999999;
//
//io.connect(SIGNALING_SERVER).emit('new-channel', {
// channel: config.channel,
// sender: sender
//});
//
//var socket = io.connect(SIGNALING_SERVER + config.channel);
//socket.channel = config.channel;
//socket.on('connect', function () {
// if (config.callback) config.callback(socket);
//});
//
//socket.send = function (message) {
// socket.emit('message', {
// sender: sender,
// data: message
// });
//};
//
//socket.on('message', config.onmessage);
},
onRemoteStream: function(media) {
console.log('s4'); | var video = media.video;
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
video.play();
},
onRoomFound: function(room) {
console.log('s5');
dualrtcUI.joinRoom({
roomToken: room.broadcaster,
joinUser: room.broadcaster
});
},
onNewParticipant: function(numberOfParticipants) {
console.log('s7');
//document.title = numberOfParticipants + ' users are viewing your screen!';
},
oniceconnectionstatechange: function(state) {
console.log('s8');
if(state == 'failed') {
alert('Failed to bypass Firewall rules.');
}
if(state == 'connected') {
alert('A user successfully received screen.');
}
}
}; // end of config
function captureUserMedia(callback, extensionAvailable) {
console.log('s9');
console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource);
var screen_constraints = {
mandatory: {
chromeMediaSource: DetectRTC.screen.chromeMediaSource,
maxWidth: screen.width > 1920 ? screen.width : 1920,
maxHeight: screen.height > 1080 ? screen.height : 1080
// minAspectRatio: 1.77
},
optional: [{ // non-official Google-only optional constraints
googTemporalLayeredScreencast: true
}, {
googLeakyBucket: true
}]
};
// try to check if extension is installed.
if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') {
DetectRTC.screen.isChromeExtensionAvailable(function(available) {
console.log('s10');
captureUserMedia(callback, available);
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) {
DetectRTC.screen.getSourceId(function(error) {
console.log('s11');
if(error && error == 'PermissionDeniedError') {
alert('PermissionDeniedError: User denied to share content of his screen.');
}
captureUserMedia(callback);
});
return;
}
if(isChrome && !DetectRTC.screen.sourceId) {
window.addEventListener('message', function (event) {
console.log('s12');
if (event.data && event.data.chromeMediaSourceId) {
var sourceId = event.data.chromeMediaSourceId;
DetectRTC.screen.sourceId = sourceId;
DetectRTC.screen.chromeMediaSource = 'desktop';
if (sourceId == 'PermissionDeniedError') {
return alert('User denied to share content of his screen.');
}
captureUserMedia(callback, true);
}
if (event.data && event.data.chromeExtensionStatus) {
warn('Screen capturing extension status is:', event.data.chromeExtensionStatus);
DetectRTC.screen.chromeMediaSource = 'screen';
captureUserMedia(callback, true);
}
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') {
screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId;
}
var constraints = {
audio: false,
video: screen_constraints
};
if(!!navigator.mozGetUserMedia) {
console.warn(Firefox_Screen_Capturing_Warning);
constraints.video = {
mozMediaSource: 'window',
mediaSource: 'window',
maxWidth: 1920,
maxHeight: 1080,
minAspectRatio: 1.77
};
}
console.log( JSON.stringify( constraints , null, '\t') );
var video = document.createElement('video');
video.setAttribute('autoplay', true);
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
getUserMedia({
video: video,
constraints: constraints,
onsuccess: function(stream) {
console.log('s13');
config.attachStream = stream;
callback && callback();
video.setAttribute('muted', true);
},
onerror: function() {
console.log('s14');
if (isChrome && location.protocol === 'http:') {
alert('Please test on HTTPS.');
} else if(isChrome) {
alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing');
}
else if(!!navigator.mozGetUserMedia) {
alert(Firefox_Screen_Capturing_Warning);
}
}
});
} // end of captureUserMedia
var dualrtcUI = dualrtc(config);
var videosContainer = document.getElementById('videos-container');
var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-');
var makeName = $('#makeName');
var joinName = $('#joinName');
var btnMakeRoom = $('#btnMakeRoom');
var btnJoinRoom = $('#btnJoinRoom');
var btnCopy = $('#btnCopy');
var divMake = $('#divMakeRoom');
var divJoin = $('#divJoinRoom');
var divScreen = $('#divScreen');
// about description
var divDescript = $('#divDescript');
var divInstallCE01 = $('#divInstallCE01');
var divInstallCE02 = $('#divInstallCE02');
var divWikiWDDM = $('#divWikiWDDM');
btnMakeRoom.click(function () {
if (makeName.val()) {
makeName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + makeName.val();
}
});
btnJoinRoom.click(function () {
if (joinName.val()) {
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + joinName.val();
}
});
btnCopy.click(function () {
makeName.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
});
divInstallCE01.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk';
});
divInstallCE02.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi';
});
divWikiWDDM.click(function () {
window.open('about:black').location.href = 'https://dualrtc-io.github.io/';
});
(function() {
if (location.hash.length <= 2) {
makeName.val(secure);
//makeName.attr('placeholder', secure);
}
else { // 방 들어왔을 때
var roomName = location.hash.substring(2, 21);
if (divMake.css('display') == 'block') $('#divMakeRoom').hide();
if (divJoin.css('display') == 'block') $('#divJoinRoom').hide();
if (divScreen.css('display') == 'none') $('#divScreen').show();
if (divDescript.css('display') == 'block') $('#divDescript').hide();
captureUserMedia(function() {
dualrtcUI.createRoom({
roomName: (roomName || 'Anonymous') + ' shared his screen with you'
});
});
}
})();
var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.'; | random_line_split |
|
screenShare.js | 'use strict';
var SIGNALING_SERVER = 'https://112.108.40.152:443/';
var config = {
openSocket: function(config) {
console.log('s1');
/*
Firebase ver.
*/
var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , '');
var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel);
socket.channel = channel;
socket.on("child_added", function(data) {
console.log('s2');
config.onmessage && config.onmessage(data.val());
});
socket.send = function(data) {
console.log('s3');
this.push(data);
};
config.onopen && setTimeout(config.onopen, 1);
socket.onDisconnect().remove();
return socket;
/*
Socket.io ver. (Not yet)
*/
//var SIGNALING_SERVER = 'https://112.108.40.152:443/';
//
//config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
//var sender = Math.round(Math.random() * 999999999) + 999999999;
//
//io.connect(SIGNALING_SERVER).emit('new-channel', {
// channel: config.channel,
// sender: sender
//});
//
//var socket = io.connect(SIGNALING_SERVER + config.channel);
//socket.channel = config.channel;
//socket.on('connect', function () {
// if (config.callback) config.callback(socket);
//});
//
//socket.send = function (message) {
// socket.emit('message', {
// sender: sender,
// data: message
// });
//};
//
//socket.on('message', config.onmessage);
},
onRemoteStream: function(media) {
console.log('s4');
var video = media.video;
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
video.play();
},
onRoomFound: function(room) {
console.log('s5');
dualrtcUI.joinRoom({
roomToken: room.broadcaster,
joinUser: room.broadcaster
});
},
onNewParticipant: function(numberOfParticipants) {
console.log('s7');
//document.title = numberOfParticipants + ' users are viewing your screen!';
},
oniceconnectionstatechange: function(state) {
console.log('s8');
if(state == 'failed') {
alert('Failed to bypass Firewall rules.');
}
if(state == 'connected') {
alert('A user successfully received screen.');
}
}
}; // end of config
function | (callback, extensionAvailable) {
console.log('s9');
console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource);
var screen_constraints = {
mandatory: {
chromeMediaSource: DetectRTC.screen.chromeMediaSource,
maxWidth: screen.width > 1920 ? screen.width : 1920,
maxHeight: screen.height > 1080 ? screen.height : 1080
// minAspectRatio: 1.77
},
optional: [{ // non-official Google-only optional constraints
googTemporalLayeredScreencast: true
}, {
googLeakyBucket: true
}]
};
// try to check if extension is installed.
if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') {
DetectRTC.screen.isChromeExtensionAvailable(function(available) {
console.log('s10');
captureUserMedia(callback, available);
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) {
DetectRTC.screen.getSourceId(function(error) {
console.log('s11');
if(error && error == 'PermissionDeniedError') {
alert('PermissionDeniedError: User denied to share content of his screen.');
}
captureUserMedia(callback);
});
return;
}
if(isChrome && !DetectRTC.screen.sourceId) {
window.addEventListener('message', function (event) {
console.log('s12');
if (event.data && event.data.chromeMediaSourceId) {
var sourceId = event.data.chromeMediaSourceId;
DetectRTC.screen.sourceId = sourceId;
DetectRTC.screen.chromeMediaSource = 'desktop';
if (sourceId == 'PermissionDeniedError') {
return alert('User denied to share content of his screen.');
}
captureUserMedia(callback, true);
}
if (event.data && event.data.chromeExtensionStatus) {
warn('Screen capturing extension status is:', event.data.chromeExtensionStatus);
DetectRTC.screen.chromeMediaSource = 'screen';
captureUserMedia(callback, true);
}
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') {
screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId;
}
var constraints = {
audio: false,
video: screen_constraints
};
if(!!navigator.mozGetUserMedia) {
console.warn(Firefox_Screen_Capturing_Warning);
constraints.video = {
mozMediaSource: 'window',
mediaSource: 'window',
maxWidth: 1920,
maxHeight: 1080,
minAspectRatio: 1.77
};
}
console.log( JSON.stringify( constraints , null, '\t') );
var video = document.createElement('video');
video.setAttribute('autoplay', true);
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
getUserMedia({
video: video,
constraints: constraints,
onsuccess: function(stream) {
console.log('s13');
config.attachStream = stream;
callback && callback();
video.setAttribute('muted', true);
},
onerror: function() {
console.log('s14');
if (isChrome && location.protocol === 'http:') {
alert('Please test on HTTPS.');
} else if(isChrome) {
alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing');
}
else if(!!navigator.mozGetUserMedia) {
alert(Firefox_Screen_Capturing_Warning);
}
}
});
} // end of captureUserMedia
var dualrtcUI = dualrtc(config);
var videosContainer = document.getElementById('videos-container');
var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-');
var makeName = $('#makeName');
var joinName = $('#joinName');
var btnMakeRoom = $('#btnMakeRoom');
var btnJoinRoom = $('#btnJoinRoom');
var btnCopy = $('#btnCopy');
var divMake = $('#divMakeRoom');
var divJoin = $('#divJoinRoom');
var divScreen = $('#divScreen');
// about description
var divDescript = $('#divDescript');
var divInstallCE01 = $('#divInstallCE01');
var divInstallCE02 = $('#divInstallCE02');
var divWikiWDDM = $('#divWikiWDDM');
btnMakeRoom.click(function () {
if (makeName.val()) {
makeName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + makeName.val();
}
});
btnJoinRoom.click(function () {
if (joinName.val()) {
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + joinName.val();
}
});
btnCopy.click(function () {
makeName.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
});
divInstallCE01.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk';
});
divInstallCE02.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi';
});
divWikiWDDM.click(function () {
window.open('about:black').location.href = 'https://dualrtc-io.github.io/';
});
(function() {
if (location.hash.length <= 2) {
makeName.val(secure);
//makeName.attr('placeholder', secure);
}
else { // 방 들어왔을 때
var roomName = location.hash.substring(2, 21);
if (divMake.css('display') == 'block') $('#divMakeRoom').hide();
if (divJoin.css('display') == 'block') $('#divJoinRoom').hide();
if (divScreen.css('display') == 'none') $('#divScreen').show();
if (divDescript.css('display') == 'block') $('#divDescript').hide();
captureUserMedia(function() {
dualrtcUI.createRoom({
roomName: (roomName || 'Anonymous') + ' shared his screen with you'
});
});
}
})();
var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.';
| captureUserMedia | identifier_name |
screenShare.js | 'use strict';
var SIGNALING_SERVER = 'https://112.108.40.152:443/';
var config = {
openSocket: function(config) {
console.log('s1');
/*
Firebase ver.
*/
var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , '');
var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel);
socket.channel = channel;
socket.on("child_added", function(data) {
console.log('s2');
config.onmessage && config.onmessage(data.val());
});
socket.send = function(data) {
console.log('s3');
this.push(data);
};
config.onopen && setTimeout(config.onopen, 1);
socket.onDisconnect().remove();
return socket;
/*
Socket.io ver. (Not yet)
*/
//var SIGNALING_SERVER = 'https://112.108.40.152:443/';
//
//config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
//var sender = Math.round(Math.random() * 999999999) + 999999999;
//
//io.connect(SIGNALING_SERVER).emit('new-channel', {
// channel: config.channel,
// sender: sender
//});
//
//var socket = io.connect(SIGNALING_SERVER + config.channel);
//socket.channel = config.channel;
//socket.on('connect', function () {
// if (config.callback) config.callback(socket);
//});
//
//socket.send = function (message) {
// socket.emit('message', {
// sender: sender,
// data: message
// });
//};
//
//socket.on('message', config.onmessage);
},
onRemoteStream: function(media) {
console.log('s4');
var video = media.video;
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
video.play();
},
onRoomFound: function(room) {
console.log('s5');
dualrtcUI.joinRoom({
roomToken: room.broadcaster,
joinUser: room.broadcaster
});
},
onNewParticipant: function(numberOfParticipants) {
console.log('s7');
//document.title = numberOfParticipants + ' users are viewing your screen!';
},
oniceconnectionstatechange: function(state) {
console.log('s8');
if(state == 'failed') {
alert('Failed to bypass Firewall rules.');
}
if(state == 'connected') {
alert('A user successfully received screen.');
}
}
}; // end of config
function captureUserMedia(callback, extensionAvailable) |
var dualrtcUI = dualrtc(config);
var videosContainer = document.getElementById('videos-container');
var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-');
var makeName = $('#makeName');
var joinName = $('#joinName');
var btnMakeRoom = $('#btnMakeRoom');
var btnJoinRoom = $('#btnJoinRoom');
var btnCopy = $('#btnCopy');
var divMake = $('#divMakeRoom');
var divJoin = $('#divJoinRoom');
var divScreen = $('#divScreen');
// about description
var divDescript = $('#divDescript');
var divInstallCE01 = $('#divInstallCE01');
var divInstallCE02 = $('#divInstallCE02');
var divWikiWDDM = $('#divWikiWDDM');
btnMakeRoom.click(function () {
if (makeName.val()) {
makeName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + makeName.val();
}
});
btnJoinRoom.click(function () {
if (joinName.val()) {
joinName.attr('disabled', true);
btnJoinRoom.attr('disabled', true);
window.open('about:black').location.href = location.href + joinName.val();
}
});
btnCopy.click(function () {
makeName.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
});
divInstallCE01.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk';
});
divInstallCE02.click(function () {
window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi';
});
divWikiWDDM.click(function () {
window.open('about:black').location.href = 'https://dualrtc-io.github.io/';
});
(function() {
if (location.hash.length <= 2) {
makeName.val(secure);
//makeName.attr('placeholder', secure);
}
else { // 방 들어왔을 때
var roomName = location.hash.substring(2, 21);
if (divMake.css('display') == 'block') $('#divMakeRoom').hide();
if (divJoin.css('display') == 'block') $('#divJoinRoom').hide();
if (divScreen.css('display') == 'none') $('#divScreen').show();
if (divDescript.css('display') == 'block') $('#divDescript').hide();
captureUserMedia(function() {
dualrtcUI.createRoom({
roomName: (roomName || 'Anonymous') + ' shared his screen with you'
});
});
}
})();
var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.';
| {
console.log('s9');
console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource);
var screen_constraints = {
mandatory: {
chromeMediaSource: DetectRTC.screen.chromeMediaSource,
maxWidth: screen.width > 1920 ? screen.width : 1920,
maxHeight: screen.height > 1080 ? screen.height : 1080
// minAspectRatio: 1.77
},
optional: [{ // non-official Google-only optional constraints
googTemporalLayeredScreencast: true
}, {
googLeakyBucket: true
}]
};
// try to check if extension is installed.
if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') {
DetectRTC.screen.isChromeExtensionAvailable(function(available) {
console.log('s10');
captureUserMedia(callback, available);
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) {
DetectRTC.screen.getSourceId(function(error) {
console.log('s11');
if(error && error == 'PermissionDeniedError') {
alert('PermissionDeniedError: User denied to share content of his screen.');
}
captureUserMedia(callback);
});
return;
}
if(isChrome && !DetectRTC.screen.sourceId) {
window.addEventListener('message', function (event) {
console.log('s12');
if (event.data && event.data.chromeMediaSourceId) {
var sourceId = event.data.chromeMediaSourceId;
DetectRTC.screen.sourceId = sourceId;
DetectRTC.screen.chromeMediaSource = 'desktop';
if (sourceId == 'PermissionDeniedError') {
return alert('User denied to share content of his screen.');
}
captureUserMedia(callback, true);
}
if (event.data && event.data.chromeExtensionStatus) {
warn('Screen capturing extension status is:', event.data.chromeExtensionStatus);
DetectRTC.screen.chromeMediaSource = 'screen';
captureUserMedia(callback, true);
}
});
return;
}
if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') {
screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId;
}
var constraints = {
audio: false,
video: screen_constraints
};
if(!!navigator.mozGetUserMedia) {
console.warn(Firefox_Screen_Capturing_Warning);
constraints.video = {
mozMediaSource: 'window',
mediaSource: 'window',
maxWidth: 1920,
maxHeight: 1080,
minAspectRatio: 1.77
};
}
console.log( JSON.stringify( constraints , null, '\t') );
var video = document.createElement('video');
video.setAttribute('autoplay', true);
video.setAttribute('controls', true);
videosContainer.insertBefore(video, videosContainer.firstChild);
getUserMedia({
video: video,
constraints: constraints,
onsuccess: function(stream) {
console.log('s13');
config.attachStream = stream;
callback && callback();
video.setAttribute('muted', true);
},
onerror: function() {
console.log('s14');
if (isChrome && location.protocol === 'http:') {
alert('Please test on HTTPS.');
} else if(isChrome) {
alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing');
}
else if(!!navigator.mozGetUserMedia) {
alert(Firefox_Screen_Capturing_Warning);
}
}
});
} // end of captureUserMedia | identifier_body |
worksheet.rs | use nickel::{Request, Response, MiddlewareResult};
use nickel::status::StatusCode;
pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
// When you need user in the future, user this stuff
// use ::auth::UserCookie;
// let user = req.get_user();
// if user.is_none() {
// return res.redirect("/login");
// }
// let user = user.unwrap();
let year = req.param("year").and_then(|y| y.parse::<i32>().ok());
if year.is_none() |
let year = year.unwrap();
let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id);
let data = WorksheetModel {
year: year,
has_activities: activities.len() > 0,
activities: activities.iter().map(|a| ActivityModel {
points: a.points,
description: a.description.clone()
}).collect()
};
res.render("templates/worksheet", &data)
}
#[derive(RustcEncodable)]
struct WorksheetModel {
year: i32,
has_activities: bool,
activities: Vec<ActivityModel>
}
#[derive(RustcEncodable)]
struct ActivityModel {
points: i32,
description: String
}
| {
res.set(StatusCode::BadRequest);
return res.send("Invalid year");
} | conditional_block |
worksheet.rs | use nickel::{Request, Response, MiddlewareResult};
use nickel::status::StatusCode;
pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
// When you need user in the future, user this stuff
// use ::auth::UserCookie;
// let user = req.get_user();
// if user.is_none() {
// return res.redirect("/login");
// }
// let user = user.unwrap();
let year = req.param("year").and_then(|y| y.parse::<i32>().ok());
if year.is_none() {
res.set(StatusCode::BadRequest);
return res.send("Invalid year");
}
let year = year.unwrap();
let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id);
let data = WorksheetModel {
year: year,
has_activities: activities.len() > 0,
activities: activities.iter().map(|a| ActivityModel {
points: a.points,
description: a.description.clone()
}).collect()
};
res.render("templates/worksheet", &data) | }
#[derive(RustcEncodable)]
struct WorksheetModel {
year: i32,
has_activities: bool,
activities: Vec<ActivityModel>
}
#[derive(RustcEncodable)]
struct ActivityModel {
points: i32,
description: String
} | random_line_split |
|
worksheet.rs | use nickel::{Request, Response, MiddlewareResult};
use nickel::status::StatusCode;
pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
// When you need user in the future, user this stuff
// use ::auth::UserCookie;
// let user = req.get_user();
// if user.is_none() {
// return res.redirect("/login");
// }
// let user = user.unwrap();
let year = req.param("year").and_then(|y| y.parse::<i32>().ok());
if year.is_none() {
res.set(StatusCode::BadRequest);
return res.send("Invalid year");
}
let year = year.unwrap();
let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id);
let data = WorksheetModel {
year: year,
has_activities: activities.len() > 0,
activities: activities.iter().map(|a| ActivityModel {
points: a.points,
description: a.description.clone()
}).collect()
};
res.render("templates/worksheet", &data)
}
#[derive(RustcEncodable)]
struct WorksheetModel {
year: i32,
has_activities: bool,
activities: Vec<ActivityModel>
}
#[derive(RustcEncodable)]
struct | {
points: i32,
description: String
}
| ActivityModel | identifier_name |
CreateFolder.js | import React, {Component} from "react/addons";
import {createFolder} from "editor/actions/TreeActions";
class CreateFolder extends Component<{}, {}, {}> {
constructor() {
super();
this.handleApply = this.handleApply.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleClose() {
this.props.onClose();
}
| (e) {
createFolder(this.props.options.get("parentId"), this.refs.nameInput.value);
}
render() {
return (
<div className="modal-dialog width-500">
<div className="modal-content">
<div className="modal-header">
<button className="close" onClick={this.handleClose} aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Create folder</h4>
</div>
<div className="modal-body">
<input type="text" className="form-control" name="folderName" ref="nameInput" autoFocus={true} />
</div>
<div className="modal-footer">
<button data-name="Cancel" type="button" className="btn btn-default" onClick={this.handleClose}>Cancel</button>
<input data-name="Apply" type="submit" onClick={this.handleApply} className="btn btn-primary" value="Apply" />
</div>
</div>
</div>
);
}
};
export default CreateFolder;
| handleApply | identifier_name |
CreateFolder.js | import React, {Component} from "react/addons";
import {createFolder} from "editor/actions/TreeActions";
class CreateFolder extends Component<{}, {}, {}> {
constructor() {
super();
this.handleApply = this.handleApply.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleClose() |
handleApply(e) {
createFolder(this.props.options.get("parentId"), this.refs.nameInput.value);
}
render() {
return (
<div className="modal-dialog width-500">
<div className="modal-content">
<div className="modal-header">
<button className="close" onClick={this.handleClose} aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Create folder</h4>
</div>
<div className="modal-body">
<input type="text" className="form-control" name="folderName" ref="nameInput" autoFocus={true} />
</div>
<div className="modal-footer">
<button data-name="Cancel" type="button" className="btn btn-default" onClick={this.handleClose}>Cancel</button>
<input data-name="Apply" type="submit" onClick={this.handleApply} className="btn btn-primary" value="Apply" />
</div>
</div>
</div>
);
}
};
export default CreateFolder;
| {
this.props.onClose();
} | identifier_body |
CreateFolder.js | import React, {Component} from "react/addons";
import {createFolder} from "editor/actions/TreeActions";
class CreateFolder extends Component<{}, {}, {}> {
constructor() {
super();
this.handleApply = this.handleApply.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleClose() {
this.props.onClose(); | }
render() {
return (
<div className="modal-dialog width-500">
<div className="modal-content">
<div className="modal-header">
<button className="close" onClick={this.handleClose} aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Create folder</h4>
</div>
<div className="modal-body">
<input type="text" className="form-control" name="folderName" ref="nameInput" autoFocus={true} />
</div>
<div className="modal-footer">
<button data-name="Cancel" type="button" className="btn btn-default" onClick={this.handleClose}>Cancel</button>
<input data-name="Apply" type="submit" onClick={this.handleApply} className="btn btn-primary" value="Apply" />
</div>
</div>
</div>
);
}
};
export default CreateFolder; | }
handleApply(e) {
createFolder(this.props.options.get("parentId"), this.refs.nameInput.value); | random_line_split |
array.rs | extern crate rand;
use std::io;
use std::f32;
use std::f64;
use std::ops::Add;
use rand::{thread_rng, Rng};
pub trait Seq<T> {
fn range(&self, start: usize, end: usize) -> &[T];
fn inverse(&self, &T) -> Option<usize>;
}
pub struct PrimeSeq {
values: Vec<u64>,
max: u64,
}
impl PrimeSeq {
pub fn new() -> PrimeSeq {
PrimeSeq { values: vec![], max: 2 }
}
}
impl Seq<u64> for PrimeSeq {
fn range(&self, start: usize, end: usize) -> &[u64] {
return &self.values[start..end];
}
fn inverse(&self, elem: &u64) -> Option<usize> {
return match self.values.binary_search(elem) {
Ok(index) => Some(index),
Err(_) => None,
}
}
}
pub fn isqrt(number: u64) -> u64 {
return (number as f64).sqrt().ceil() as u64;
}
pub fn factors(number: u64) -> Vec<u64> {
let mut result = vec![];
let mut remain = number;
let mut i = 2;
while (i <= remain) {
if remain % i == 0 {
remain /= i;
result.push(i);
}
else {
i += 1;
}
}
return result;
}
pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> {
let result = Vec::new();
for a in factors {
}
return result;
}
/**
* a and b must be sorted arrays
* returns tuple of common and non-common factors
*/
pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) {
let mut common = Vec::new();
let mut inverse = Vec::new();
let mut a_index = 0;
let mut b_index = 0;
let max_len = if a.len() > b.len() { a.len() } else { b.len() };
while a_index < a.len() && b_index < b.len() {
let a_val = a[a_index];
let b_val = b[b_index];
if (a_val == b_val) {
common.push(a_val);
a_index += 1;
b_index += 1;
}
else if (a_val < b_val) {
inverse.push(a_val);
a_index += 1;
}
else {
inverse.push(b_val);
b_index += 1;
}
}
for a_remain in a_index..a.len() {
inverse.push(a[a_remain]);
}
for b_remain in b_index..b.len() {
inverse.push(b[b_remain]);
}
return (common, inverse);
}
pub fn is_prime(number: u64) -> bool {
for i in 2..isqrt(number) {
if number % i == 0 {
return false;
}
}
return true;
}
/*
* maximum set
*/
pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> {
let mut progress = vec![0; factors.len() as usize];
let mut common = Vec::new();
let mut complete = false;
while !complete {
let mut nothing_remaining = true;
let mut lowest_index = 0;
let mut lowest = 999999999;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
nothing_remaining = false;
// check if value is lowest
let val = current_set[current_progress];
if val < lowest {
lowest_index = index;
lowest = val;
}
}
}
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= lowest) {
progress[index] += 1;
}
}
complete = nothing_remaining;
if !complete {
common.push(lowest);
}
}
return common;
}
pub fn high_freq_factors(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> {
let all_factors = maximum_factors(factors); | let mut common = Vec::new();
if (all_factors.len() == 0) {
return common;
}
let mut first = 0;
let highest = all_factors[all_factors.len() - 1];
for comp in all_factors {
if comp > 255 {
return common;
}
let mut lowest_index = 0;
let mut lowest = highest;
let mut freq = 0;
let mut have_remaining = false;
//println!("{:?} :: {:?} :: {:?}", first, progress, lowest);
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
have_remaining = true;
let val = current_set[current_progress];
if val <= lowest {
lowest_index = index;
lowest = val;
}
if val == comp {
freq += 1;
}
}
}
if !have_remaining || common.len() > limit as usize {
return common;
}
if freq > min_freq {
first += 1;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= comp) {
progress[index] += 1;
}
}
common.push(comp);
}
else {
progress[lowest_index] += 1;
}
}
return common;
}
pub fn find_primes(ps: &mut PrimeSeq, max: u64) {
let mut number = ps.max;
while number < max {
let mut isprime = true;
for i in 2..isqrt(number) {
if number % i == 0 {
isprime = false;
}
}
if isprime {
ps.values.push(number);
}
number += 1;
}
ps.max = max;
}
pub fn fib(n: u64) -> (u64, u64, u64) {
let mut count = 1;
let mut fb1 = 1;
let mut fb2 = 2;
while fb2 <= n {
count += 1;
fb2 = fb1 + fb2;
fb1 = fb2 - fb1;
}
return (count, n - fb1, fb2 - n);
}
pub fn sum(numbers: Vec<u64>) -> u64 {
let mut total = 0;
for i in numbers {
total += i;
}
return total;
}
pub fn product(numbers: &Vec<u64>) -> u64 {
let mut p = 1;
for i in numbers {
p *= i;
}
return p;
}
pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) {
let mut grid = vec![0; size * size];
let start: usize = start as usize;
for i in 0..size*size {
let number = start + i;
grid[i] = number;
}
for i in 0..size {
for j in 0..size {
print!("{}, ", grid[i * size + j])
}
println!("");
}
}
pub fn fill_sine(data: &mut [i16]) {
for t in 0..data.len() {
let fq = (t as f32) * 0.03;
let x = fq.sin() * 2500.0;
data[t] = x as i16;
}
}
pub fn fill_bits(data: &mut [i16]) {
for t in 0..data.len() {
let ts = ((t as f32) * 0.1) as i16;
let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11));
data[t] = val as i16;
}
}
pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) {
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (data.len() as f64) * 0.05;
for t in 0..data.len() {
let fq = (t as f64) * mul * 1000.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) {
let smodulo = (max % start) as f64;
let sdivide = (max / start) as f64;
let emodulo = (max % end) as f64;
let edivide = (max / end) as f64;
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0;
println!("vol {}", vol);
for t in 0..data.len() {
let fq = (t as f64) * mul * 200.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) {
let sample_min = 30000;
let sample_max = 1000000;
let mut rng = rand::thread_rng();
for s in 0..samples {
println!("filling {}/{}", s, samples);
let start = rng.gen_range(0, data.len());
let end = rng.gen_range(start, data.len());
let length = end - start;
if sample_min < length && length < sample_max {
filler(start, end, data.len(), &mut data[start..end]);
}
}
}
pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as i16;
}
}
pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as f32;
}
} | let mut progress = vec![0; factors.len() as usize]; | random_line_split |
array.rs | extern crate rand;
use std::io;
use std::f32;
use std::f64;
use std::ops::Add;
use rand::{thread_rng, Rng};
pub trait Seq<T> {
fn range(&self, start: usize, end: usize) -> &[T];
fn inverse(&self, &T) -> Option<usize>;
}
pub struct PrimeSeq {
values: Vec<u64>,
max: u64,
}
impl PrimeSeq {
pub fn new() -> PrimeSeq {
PrimeSeq { values: vec![], max: 2 }
}
}
impl Seq<u64> for PrimeSeq {
fn range(&self, start: usize, end: usize) -> &[u64] {
return &self.values[start..end];
}
fn inverse(&self, elem: &u64) -> Option<usize> {
return match self.values.binary_search(elem) {
Ok(index) => Some(index),
Err(_) => None,
}
}
}
pub fn isqrt(number: u64) -> u64 {
return (number as f64).sqrt().ceil() as u64;
}
pub fn factors(number: u64) -> Vec<u64> {
let mut result = vec![];
let mut remain = number;
let mut i = 2;
while (i <= remain) {
if remain % i == 0 {
remain /= i;
result.push(i);
}
else {
i += 1;
}
}
return result;
}
pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> {
let result = Vec::new();
for a in factors {
}
return result;
}
/**
* a and b must be sorted arrays
* returns tuple of common and non-common factors
*/
pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) {
let mut common = Vec::new();
let mut inverse = Vec::new();
let mut a_index = 0;
let mut b_index = 0;
let max_len = if a.len() > b.len() { a.len() } else { b.len() };
while a_index < a.len() && b_index < b.len() {
let a_val = a[a_index];
let b_val = b[b_index];
if (a_val == b_val) {
common.push(a_val);
a_index += 1;
b_index += 1;
}
else if (a_val < b_val) {
inverse.push(a_val);
a_index += 1;
}
else {
inverse.push(b_val);
b_index += 1;
}
}
for a_remain in a_index..a.len() {
inverse.push(a[a_remain]);
}
for b_remain in b_index..b.len() {
inverse.push(b[b_remain]);
}
return (common, inverse);
}
pub fn is_prime(number: u64) -> bool {
for i in 2..isqrt(number) {
if number % i == 0 {
return false;
}
}
return true;
}
/*
* maximum set
*/
pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> {
let mut progress = vec![0; factors.len() as usize];
let mut common = Vec::new();
let mut complete = false;
while !complete {
let mut nothing_remaining = true;
let mut lowest_index = 0;
let mut lowest = 999999999;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
nothing_remaining = false;
// check if value is lowest
let val = current_set[current_progress];
if val < lowest {
lowest_index = index;
lowest = val;
}
}
}
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= lowest) {
progress[index] += 1;
}
}
complete = nothing_remaining;
if !complete {
common.push(lowest);
}
}
return common;
}
pub fn | (factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> {
let all_factors = maximum_factors(factors);
let mut progress = vec![0; factors.len() as usize];
let mut common = Vec::new();
if (all_factors.len() == 0) {
return common;
}
let mut first = 0;
let highest = all_factors[all_factors.len() - 1];
for comp in all_factors {
if comp > 255 {
return common;
}
let mut lowest_index = 0;
let mut lowest = highest;
let mut freq = 0;
let mut have_remaining = false;
//println!("{:?} :: {:?} :: {:?}", first, progress, lowest);
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
have_remaining = true;
let val = current_set[current_progress];
if val <= lowest {
lowest_index = index;
lowest = val;
}
if val == comp {
freq += 1;
}
}
}
if !have_remaining || common.len() > limit as usize {
return common;
}
if freq > min_freq {
first += 1;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= comp) {
progress[index] += 1;
}
}
common.push(comp);
}
else {
progress[lowest_index] += 1;
}
}
return common;
}
pub fn find_primes(ps: &mut PrimeSeq, max: u64) {
let mut number = ps.max;
while number < max {
let mut isprime = true;
for i in 2..isqrt(number) {
if number % i == 0 {
isprime = false;
}
}
if isprime {
ps.values.push(number);
}
number += 1;
}
ps.max = max;
}
pub fn fib(n: u64) -> (u64, u64, u64) {
let mut count = 1;
let mut fb1 = 1;
let mut fb2 = 2;
while fb2 <= n {
count += 1;
fb2 = fb1 + fb2;
fb1 = fb2 - fb1;
}
return (count, n - fb1, fb2 - n);
}
pub fn sum(numbers: Vec<u64>) -> u64 {
let mut total = 0;
for i in numbers {
total += i;
}
return total;
}
pub fn product(numbers: &Vec<u64>) -> u64 {
let mut p = 1;
for i in numbers {
p *= i;
}
return p;
}
pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) {
let mut grid = vec![0; size * size];
let start: usize = start as usize;
for i in 0..size*size {
let number = start + i;
grid[i] = number;
}
for i in 0..size {
for j in 0..size {
print!("{}, ", grid[i * size + j])
}
println!("");
}
}
pub fn fill_sine(data: &mut [i16]) {
for t in 0..data.len() {
let fq = (t as f32) * 0.03;
let x = fq.sin() * 2500.0;
data[t] = x as i16;
}
}
pub fn fill_bits(data: &mut [i16]) {
for t in 0..data.len() {
let ts = ((t as f32) * 0.1) as i16;
let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11));
data[t] = val as i16;
}
}
pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) {
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (data.len() as f64) * 0.05;
for t in 0..data.len() {
let fq = (t as f64) * mul * 1000.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) {
let smodulo = (max % start) as f64;
let sdivide = (max / start) as f64;
let emodulo = (max % end) as f64;
let edivide = (max / end) as f64;
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0;
println!("vol {}", vol);
for t in 0..data.len() {
let fq = (t as f64) * mul * 200.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) {
let sample_min = 30000;
let sample_max = 1000000;
let mut rng = rand::thread_rng();
for s in 0..samples {
println!("filling {}/{}", s, samples);
let start = rng.gen_range(0, data.len());
let end = rng.gen_range(start, data.len());
let length = end - start;
if sample_min < length && length < sample_max {
filler(start, end, data.len(), &mut data[start..end]);
}
}
}
pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as i16;
}
}
pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as f32;
}
}
| high_freq_factors | identifier_name |
array.rs | extern crate rand;
use std::io;
use std::f32;
use std::f64;
use std::ops::Add;
use rand::{thread_rng, Rng};
pub trait Seq<T> {
fn range(&self, start: usize, end: usize) -> &[T];
fn inverse(&self, &T) -> Option<usize>;
}
pub struct PrimeSeq {
values: Vec<u64>,
max: u64,
}
impl PrimeSeq {
pub fn new() -> PrimeSeq {
PrimeSeq { values: vec![], max: 2 }
}
}
impl Seq<u64> for PrimeSeq {
fn range(&self, start: usize, end: usize) -> &[u64] {
return &self.values[start..end];
}
fn inverse(&self, elem: &u64) -> Option<usize> |
}
pub fn isqrt(number: u64) -> u64 {
return (number as f64).sqrt().ceil() as u64;
}
pub fn factors(number: u64) -> Vec<u64> {
let mut result = vec![];
let mut remain = number;
let mut i = 2;
while (i <= remain) {
if remain % i == 0 {
remain /= i;
result.push(i);
}
else {
i += 1;
}
}
return result;
}
pub fn subset_products(factors: &Vec<u64>) -> Vec<u64> {
let result = Vec::new();
for a in factors {
}
return result;
}
/**
* a and b must be sorted arrays
* returns tuple of common and non-common factors
*/
pub fn common_factors(a: &Vec<u64>, b: &Vec<u64>) -> (Vec<u64>, Vec<u64>) {
let mut common = Vec::new();
let mut inverse = Vec::new();
let mut a_index = 0;
let mut b_index = 0;
let max_len = if a.len() > b.len() { a.len() } else { b.len() };
while a_index < a.len() && b_index < b.len() {
let a_val = a[a_index];
let b_val = b[b_index];
if (a_val == b_val) {
common.push(a_val);
a_index += 1;
b_index += 1;
}
else if (a_val < b_val) {
inverse.push(a_val);
a_index += 1;
}
else {
inverse.push(b_val);
b_index += 1;
}
}
for a_remain in a_index..a.len() {
inverse.push(a[a_remain]);
}
for b_remain in b_index..b.len() {
inverse.push(b[b_remain]);
}
return (common, inverse);
}
pub fn is_prime(number: u64) -> bool {
for i in 2..isqrt(number) {
if number % i == 0 {
return false;
}
}
return true;
}
/*
* maximum set
*/
pub fn maximum_factors(factors: &Vec<Vec<u64>>) -> Vec<u64> {
let mut progress = vec![0; factors.len() as usize];
let mut common = Vec::new();
let mut complete = false;
while !complete {
let mut nothing_remaining = true;
let mut lowest_index = 0;
let mut lowest = 999999999;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
nothing_remaining = false;
// check if value is lowest
let val = current_set[current_progress];
if val < lowest {
lowest_index = index;
lowest = val;
}
}
}
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= lowest) {
progress[index] += 1;
}
}
complete = nothing_remaining;
if !complete {
common.push(lowest);
}
}
return common;
}
pub fn high_freq_factors(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> {
let all_factors = maximum_factors(factors);
let mut progress = vec![0; factors.len() as usize];
let mut common = Vec::new();
if (all_factors.len() == 0) {
return common;
}
let mut first = 0;
let highest = all_factors[all_factors.len() - 1];
for comp in all_factors {
if comp > 255 {
return common;
}
let mut lowest_index = 0;
let mut lowest = highest;
let mut freq = 0;
let mut have_remaining = false;
//println!("{:?} :: {:?} :: {:?}", first, progress, lowest);
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len()) {
have_remaining = true;
let val = current_set[current_progress];
if val <= lowest {
lowest_index = index;
lowest = val;
}
if val == comp {
freq += 1;
}
}
}
if !have_remaining || common.len() > limit as usize {
return common;
}
if freq > min_freq {
first += 1;
for index in 0..factors.len() {
let current_set = &factors[index];
let current_progress = progress[index];
if (current_progress < current_set.len() && current_set[current_progress] <= comp) {
progress[index] += 1;
}
}
common.push(comp);
}
else {
progress[lowest_index] += 1;
}
}
return common;
}
pub fn find_primes(ps: &mut PrimeSeq, max: u64) {
let mut number = ps.max;
while number < max {
let mut isprime = true;
for i in 2..isqrt(number) {
if number % i == 0 {
isprime = false;
}
}
if isprime {
ps.values.push(number);
}
number += 1;
}
ps.max = max;
}
pub fn fib(n: u64) -> (u64, u64, u64) {
let mut count = 1;
let mut fb1 = 1;
let mut fb2 = 2;
while fb2 <= n {
count += 1;
fb2 = fb1 + fb2;
fb1 = fb2 - fb1;
}
return (count, n - fb1, fb2 - n);
}
pub fn sum(numbers: Vec<u64>) -> u64 {
let mut total = 0;
for i in numbers {
total += i;
}
return total;
}
pub fn product(numbers: &Vec<u64>) -> u64 {
let mut p = 1;
for i in numbers {
p *= i;
}
return p;
}
pub fn sequence(seq: &Seq<u64>, start: u32, size: usize) {
let mut grid = vec![0; size * size];
let start: usize = start as usize;
for i in 0..size*size {
let number = start + i;
grid[i] = number;
}
for i in 0..size {
for j in 0..size {
print!("{}, ", grid[i * size + j])
}
println!("");
}
}
pub fn fill_sine(data: &mut [i16]) {
for t in 0..data.len() {
let fq = (t as f32) * 0.03;
let x = fq.sin() * 2500.0;
data[t] = x as i16;
}
}
pub fn fill_bits(data: &mut [i16]) {
for t in 0..data.len() {
let ts = ((t as f32) * 0.1) as i16;
let val = (ts | (ts >> 11 | ts >> 7)).wrapping_mul(ts & (ts >> 13 | ts >> 11));
data[t] = val as i16;
}
}
pub fn fill_wave(start: usize, end: usize, max: usize, data: &mut [f64]) {
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (data.len() as f64) * 0.05;
for t in 0..data.len() {
let fq = (t as f64) * mul * 1000.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_test(start: usize, end: usize, max: usize, data: &mut [f64]) {
let smodulo = (max % start) as f64;
let sdivide = (max / start) as f64;
let emodulo = (max % end) as f64;
let edivide = (max / end) as f64;
let mul = (f64::consts::PI * 2.0) / (data.len() as f64);
let vol = (((emodulo / edivide) * (smodulo / sdivide)).log(2.0) - 20.0) * 40.0;
println!("vol {}", vol);
for t in 0..data.len() {
let fq = (t as f64) * mul * 200.0;
let x = fq.sin() * vol;
data[t] += x as f64;
}
}
pub fn fill_with(filler: fn(usize, usize, usize, data: &mut [f64]), data: &mut [f64], samples: usize) {
let sample_min = 30000;
let sample_max = 1000000;
let mut rng = rand::thread_rng();
for s in 0..samples {
println!("filling {}/{}", s, samples);
let start = rng.gen_range(0, data.len());
let end = rng.gen_range(start, data.len());
let length = end - start;
if sample_min < length && length < sample_max {
filler(start, end, data.len(), &mut data[start..end]);
}
}
}
pub fn data_to_i16(out_data: &mut [i16], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as i16;
}
}
pub fn data_to_f32(out_data: &mut [f32], in_data: &[f64]) {
for t in 0..in_data.len() {
out_data[t] = in_data[t] as f32;
}
}
| {
return match self.values.binary_search(elem) {
Ok(index) => Some(index),
Err(_) => None,
}
} | identifier_body |
v2_deflate_serializer.rs | use super::v2_serializer::{V2SerializeError, V2Serializer};
use super::{Serializer, V2_COMPRESSED_COOKIE};
use crate::core::counter::Counter;
use crate::Histogram;
use byteorder::{BigEndian, WriteBytesExt};
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{self, Write};
use std::{self, error, fmt};
/// Errors that occur during serialization.
#[derive(Debug)]
pub enum V2DeflateSerializeError {
/// The underlying serialization failed
InternalSerializationError(V2SerializeError),
/// An i/o operation failed.
IoError(io::Error),
}
impl std::convert::From<std::io::Error> for V2DeflateSerializeError {
fn from(e: std::io::Error) -> Self {
V2DeflateSerializeError::IoError(e)
}
}
impl fmt::Display for V2DeflateSerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
V2DeflateSerializeError::IoError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
}
}
}
impl error::Error for V2DeflateSerializeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => Some(e),
V2DeflateSerializeError::IoError(e) => Some(e),
}
}
}
/// Serializer for the V2 + DEFLATE binary format.
///
/// It's called "deflate" to stay consistent with the naming used in the Java implementation, but
/// it actually uses zlib's wrapper format around plain DEFLATE.
pub struct V2DeflateSerializer {
uncompressed_buf: Vec<u8>,
compressed_buf: Vec<u8>,
v2_serializer: V2Serializer,
}
impl Default for V2DeflateSerializer {
fn default() -> Self {
Self::new()
}
}
impl V2DeflateSerializer {
/// Create a new serializer.
pub fn | () -> V2DeflateSerializer {
V2DeflateSerializer {
uncompressed_buf: Vec::new(),
compressed_buf: Vec::new(),
v2_serializer: V2Serializer::new(),
}
}
}
impl Serializer for V2DeflateSerializer {
type SerializeError = V2DeflateSerializeError;
fn serialize<T: Counter, W: Write>(
&mut self,
h: &Histogram<T>,
writer: &mut W,
) -> Result<usize, V2DeflateSerializeError> {
// TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk
// could be compressed and written to the compressed buf, possibly using an approach like
// that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055.
// This would reduce the overall buffer size needed for plain v2 serialization, and be
// more cache friendly.
self.uncompressed_buf.clear();
self.compressed_buf.clear();
// TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer
let uncompressed_len = self
.v2_serializer
.serialize(h, &mut self.uncompressed_buf)
.map_err(V2DeflateSerializeError::InternalSerializationError)?;
debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len);
// On randomized test histograms we get about 10% compression, but of course random data
// doesn't compress well. Real-world data may compress better, so let's assume a more
// optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's
// still only one more allocation the first time it's needed.
self.compressed_buf.reserve(self.uncompressed_buf.len() / 2);
self.compressed_buf
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?;
// placeholder for length
self.compressed_buf.write_u32::<BigEndian>(0)?;
// TODO pluggable compressors? configurable compression levels?
// TODO benchmark https://github.com/sile/libflate
// TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the
// data instead of shrinking it (which we cannot really predict), writing to compressed_buf
// could panic as Vec overflows its internal `usize`.
{
// TODO reuse deflate buf, or switch to lower-level flate2::Compress
let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default());
compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?;
let _ = compressor.finish()?;
}
// fill in length placeholder. Won't underflow since length is always at least 8, and won't
// overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if
// counter is u64).
let total_compressed_len = self.compressed_buf.len();
(&mut self.compressed_buf[4..8])
.write_u32::<BigEndian>((total_compressed_len as u32) - 8)?;
writer.write_all(&self.compressed_buf)?;
Ok(total_compressed_len)
}
}
| new | identifier_name |
v2_deflate_serializer.rs | use super::v2_serializer::{V2SerializeError, V2Serializer};
use super::{Serializer, V2_COMPRESSED_COOKIE};
use crate::core::counter::Counter;
use crate::Histogram;
use byteorder::{BigEndian, WriteBytesExt};
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{self, Write};
use std::{self, error, fmt};
/// Errors that occur during serialization.
#[derive(Debug)]
pub enum V2DeflateSerializeError {
/// The underlying serialization failed
InternalSerializationError(V2SerializeError),
/// An i/o operation failed.
IoError(io::Error),
}
impl std::convert::From<std::io::Error> for V2DeflateSerializeError {
fn from(e: std::io::Error) -> Self |
}
impl fmt::Display for V2DeflateSerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
V2DeflateSerializeError::IoError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
}
}
}
impl error::Error for V2DeflateSerializeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => Some(e),
V2DeflateSerializeError::IoError(e) => Some(e),
}
}
}
/// Serializer for the V2 + DEFLATE binary format.
///
/// It's called "deflate" to stay consistent with the naming used in the Java implementation, but
/// it actually uses zlib's wrapper format around plain DEFLATE.
pub struct V2DeflateSerializer {
uncompressed_buf: Vec<u8>,
compressed_buf: Vec<u8>,
v2_serializer: V2Serializer,
}
impl Default for V2DeflateSerializer {
fn default() -> Self {
Self::new()
}
}
impl V2DeflateSerializer {
/// Create a new serializer.
pub fn new() -> V2DeflateSerializer {
V2DeflateSerializer {
uncompressed_buf: Vec::new(),
compressed_buf: Vec::new(),
v2_serializer: V2Serializer::new(),
}
}
}
impl Serializer for V2DeflateSerializer {
type SerializeError = V2DeflateSerializeError;
fn serialize<T: Counter, W: Write>(
&mut self,
h: &Histogram<T>,
writer: &mut W,
) -> Result<usize, V2DeflateSerializeError> {
// TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk
// could be compressed and written to the compressed buf, possibly using an approach like
// that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055.
// This would reduce the overall buffer size needed for plain v2 serialization, and be
// more cache friendly.
self.uncompressed_buf.clear();
self.compressed_buf.clear();
// TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer
let uncompressed_len = self
.v2_serializer
.serialize(h, &mut self.uncompressed_buf)
.map_err(V2DeflateSerializeError::InternalSerializationError)?;
debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len);
// On randomized test histograms we get about 10% compression, but of course random data
// doesn't compress well. Real-world data may compress better, so let's assume a more
// optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's
// still only one more allocation the first time it's needed.
self.compressed_buf.reserve(self.uncompressed_buf.len() / 2);
self.compressed_buf
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?;
// placeholder for length
self.compressed_buf.write_u32::<BigEndian>(0)?;
// TODO pluggable compressors? configurable compression levels?
// TODO benchmark https://github.com/sile/libflate
// TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the
// data instead of shrinking it (which we cannot really predict), writing to compressed_buf
// could panic as Vec overflows its internal `usize`.
{
// TODO reuse deflate buf, or switch to lower-level flate2::Compress
let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default());
compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?;
let _ = compressor.finish()?;
}
// fill in length placeholder. Won't underflow since length is always at least 8, and won't
// overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if
// counter is u64).
let total_compressed_len = self.compressed_buf.len();
(&mut self.compressed_buf[4..8])
.write_u32::<BigEndian>((total_compressed_len as u32) - 8)?;
writer.write_all(&self.compressed_buf)?;
Ok(total_compressed_len)
}
}
| {
V2DeflateSerializeError::IoError(e)
} | identifier_body |
v2_deflate_serializer.rs | use super::v2_serializer::{V2SerializeError, V2Serializer};
use super::{Serializer, V2_COMPRESSED_COOKIE};
use crate::core::counter::Counter;
use crate::Histogram;
use byteorder::{BigEndian, WriteBytesExt};
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{self, Write};
use std::{self, error, fmt};
/// Errors that occur during serialization.
#[derive(Debug)]
pub enum V2DeflateSerializeError {
/// The underlying serialization failed
InternalSerializationError(V2SerializeError),
/// An i/o operation failed.
IoError(io::Error),
}
impl std::convert::From<std::io::Error> for V2DeflateSerializeError {
fn from(e: std::io::Error) -> Self {
V2DeflateSerializeError::IoError(e)
}
}
impl fmt::Display for V2DeflateSerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
V2DeflateSerializeError::IoError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
}
}
}
impl error::Error for V2DeflateSerializeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => Some(e),
V2DeflateSerializeError::IoError(e) => Some(e),
}
}
}
/// Serializer for the V2 + DEFLATE binary format.
///
/// It's called "deflate" to stay consistent with the naming used in the Java implementation, but
/// it actually uses zlib's wrapper format around plain DEFLATE.
pub struct V2DeflateSerializer {
uncompressed_buf: Vec<u8>,
compressed_buf: Vec<u8>,
v2_serializer: V2Serializer,
}
impl Default for V2DeflateSerializer {
fn default() -> Self {
Self::new()
}
}
impl V2DeflateSerializer {
/// Create a new serializer.
pub fn new() -> V2DeflateSerializer {
V2DeflateSerializer {
uncompressed_buf: Vec::new(),
compressed_buf: Vec::new(),
v2_serializer: V2Serializer::new(),
}
}
}
impl Serializer for V2DeflateSerializer {
type SerializeError = V2DeflateSerializeError;
fn serialize<T: Counter, W: Write>(
&mut self,
h: &Histogram<T>,
writer: &mut W,
) -> Result<usize, V2DeflateSerializeError> {
// TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk
// could be compressed and written to the compressed buf, possibly using an approach like
// that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055.
// This would reduce the overall buffer size needed for plain v2 serialization, and be
// more cache friendly.
self.uncompressed_buf.clear();
self.compressed_buf.clear();
// TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer
let uncompressed_len = self
.v2_serializer
.serialize(h, &mut self.uncompressed_buf)
.map_err(V2DeflateSerializeError::InternalSerializationError)?;
debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len);
// On randomized test histograms we get about 10% compression, but of course random data
// doesn't compress well. Real-world data may compress better, so let's assume a more
// optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's
// still only one more allocation the first time it's needed.
self.compressed_buf.reserve(self.uncompressed_buf.len() / 2);
self.compressed_buf | // TODO pluggable compressors? configurable compression levels?
// TODO benchmark https://github.com/sile/libflate
// TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the
// data instead of shrinking it (which we cannot really predict), writing to compressed_buf
// could panic as Vec overflows its internal `usize`.
{
// TODO reuse deflate buf, or switch to lower-level flate2::Compress
let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default());
compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?;
let _ = compressor.finish()?;
}
// fill in length placeholder. Won't underflow since length is always at least 8, and won't
// overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if
// counter is u64).
let total_compressed_len = self.compressed_buf.len();
(&mut self.compressed_buf[4..8])
.write_u32::<BigEndian>((total_compressed_len as u32) - 8)?;
writer.write_all(&self.compressed_buf)?;
Ok(total_compressed_len)
}
} | .write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?;
// placeholder for length
self.compressed_buf.write_u32::<BigEndian>(0)?;
| random_line_split |
v2_deflate_serializer.rs | use super::v2_serializer::{V2SerializeError, V2Serializer};
use super::{Serializer, V2_COMPRESSED_COOKIE};
use crate::core::counter::Counter;
use crate::Histogram;
use byteorder::{BigEndian, WriteBytesExt};
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{self, Write};
use std::{self, error, fmt};
/// Errors that occur during serialization.
#[derive(Debug)]
pub enum V2DeflateSerializeError {
/// The underlying serialization failed
InternalSerializationError(V2SerializeError),
/// An i/o operation failed.
IoError(io::Error),
}
impl std::convert::From<std::io::Error> for V2DeflateSerializeError {
fn from(e: std::io::Error) -> Self {
V2DeflateSerializeError::IoError(e)
}
}
impl fmt::Display for V2DeflateSerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => {
write!(f, "The underlying serialization failed: {}", e)
}
V2DeflateSerializeError::IoError(e) => |
}
}
}
impl error::Error for V2DeflateSerializeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
V2DeflateSerializeError::InternalSerializationError(e) => Some(e),
V2DeflateSerializeError::IoError(e) => Some(e),
}
}
}
/// Serializer for the V2 + DEFLATE binary format.
///
/// It's called "deflate" to stay consistent with the naming used in the Java implementation, but
/// it actually uses zlib's wrapper format around plain DEFLATE.
pub struct V2DeflateSerializer {
uncompressed_buf: Vec<u8>,
compressed_buf: Vec<u8>,
v2_serializer: V2Serializer,
}
impl Default for V2DeflateSerializer {
fn default() -> Self {
Self::new()
}
}
impl V2DeflateSerializer {
/// Create a new serializer.
pub fn new() -> V2DeflateSerializer {
V2DeflateSerializer {
uncompressed_buf: Vec::new(),
compressed_buf: Vec::new(),
v2_serializer: V2Serializer::new(),
}
}
}
impl Serializer for V2DeflateSerializer {
type SerializeError = V2DeflateSerializeError;
fn serialize<T: Counter, W: Write>(
&mut self,
h: &Histogram<T>,
writer: &mut W,
) -> Result<usize, V2DeflateSerializeError> {
// TODO benchmark serializing in chunks rather than all at once: each uncompressed v2 chunk
// could be compressed and written to the compressed buf, possibly using an approach like
// that of https://github.com/HdrHistogram/HdrHistogram_rust/issues/32#issuecomment-287583055.
// This would reduce the overall buffer size needed for plain v2 serialization, and be
// more cache friendly.
self.uncompressed_buf.clear();
self.compressed_buf.clear();
// TODO serialize directly into uncompressed_buf without the buffering inside v2_serializer
let uncompressed_len = self
.v2_serializer
.serialize(h, &mut self.uncompressed_buf)
.map_err(V2DeflateSerializeError::InternalSerializationError)?;
debug_assert_eq!(self.uncompressed_buf.len(), uncompressed_len);
// On randomized test histograms we get about 10% compression, but of course random data
// doesn't compress well. Real-world data may compress better, so let's assume a more
// optimistic 50% compression as a baseline to reserve. If we're overly optimistic that's
// still only one more allocation the first time it's needed.
self.compressed_buf.reserve(self.uncompressed_buf.len() / 2);
self.compressed_buf
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?;
// placeholder for length
self.compressed_buf.write_u32::<BigEndian>(0)?;
// TODO pluggable compressors? configurable compression levels?
// TODO benchmark https://github.com/sile/libflate
// TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the
// data instead of shrinking it (which we cannot really predict), writing to compressed_buf
// could panic as Vec overflows its internal `usize`.
{
// TODO reuse deflate buf, or switch to lower-level flate2::Compress
let mut compressor = ZlibEncoder::new(&mut self.compressed_buf, Compression::default());
compressor.write_all(&self.uncompressed_buf[0..uncompressed_len])?;
let _ = compressor.finish()?;
}
// fill in length placeholder. Won't underflow since length is always at least 8, and won't
// overflow u32 as the largest array is about 6 million entries, so about 54MiB encoded (if
// counter is u64).
let total_compressed_len = self.compressed_buf.len();
(&mut self.compressed_buf[4..8])
.write_u32::<BigEndian>((total_compressed_len as u32) - 8)?;
writer.write_all(&self.compressed_buf)?;
Ok(total_compressed_len)
}
}
| {
write!(f, "The underlying serialization failed: {}", e)
} | conditional_block |
400_nth_digit.py | # 400 Nth Digit
# Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
#
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
#
# Example 1:
#
# Input:
# 3
#
# Output:
# 3
#
# Example 2:
#
# Input:
# 11
#
# Output:
# 0
#
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
class Solution(object):
# https://www.hrwhisper.me/leetcode-contest-5-solution/
# 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。
# 剩下的直接看看是否整除啥的即可。
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
num = 9
cnt = 1
while n > num * cnt:
n -= (num * cnt)
num *= 10
cnt += 1
t = n // cnt
base = 10 ** (cnt - 1) + t
if t * cnt == n:
return (base - 1) % 10
n -= t * cnt
return int(str(base)[::-1][-n])
print(Solution(). | findNthDigit(11))
| conditional_block |
|
400_nth_digit.py | # 400 Nth Digit
# Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
#
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
#
# Example 1:
#
# Input:
# 3
#
# Output:
# 3
#
# Example 2:
#
# Input:
# 11
#
# Output:
# 0
#
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
class Solution(object):
# https://www.hrwhisper.me/leetcode-contest-5-solution/
# 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。
# 剩下的直接看看是否整除啥的即可。
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
num = 9
cnt = 1
while | n > num * cnt:
n -= (num * cnt)
num *= 10
cnt += 1
t = n // cnt
base = 10 ** (cnt - 1) + t
if t * cnt == n:
return (base - 1) % 10
n -= t * cnt
return int(str(base)[::-1][-n])
print(Solution().findNthDigit(11))
| identifier_body |
|
400_nth_digit.py | # 400 Nth Digit
# Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
#
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
#
# Example 1:
#
# Input:
# 3
#
# Output:
# 3
#
# Example 2:
#
# Input:
# 11
#
# Output:
# 0 | # https://www.hrwhisper.me/leetcode-contest-5-solution/
# 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。
# 剩下的直接看看是否整除啥的即可。
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
num = 9
cnt = 1
while n > num * cnt:
n -= (num * cnt)
num *= 10
cnt += 1
t = n // cnt
base = 10 ** (cnt - 1) + t
if t * cnt == n:
return (base - 1) % 10
n -= t * cnt
return int(str(base)[::-1][-n])
print(Solution().findNthDigit(11)) | #
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
class Solution(object): | random_line_split |
400_nth_digit.py | # 400 Nth Digit
# Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
#
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
#
# Example 1:
#
# Input:
# 3
#
# Output:
# 3
#
# Example 2:
#
# Input:
# 11
#
# Output:
# 0
#
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
class | (object):
# https://www.hrwhisper.me/leetcode-contest-5-solution/
# 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。
# 剩下的直接看看是否整除啥的即可。
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
num = 9
cnt = 1
while n > num * cnt:
n -= (num * cnt)
num *= 10
cnt += 1
t = n // cnt
base = 10 ** (cnt - 1) + t
if t * cnt == n:
return (base - 1) % 10
n -= t * cnt
return int(str(base)[::-1][-n])
print(Solution().findNthDigit(11))
| Solution | identifier_name |
index.js | import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js'
import lastDayOfMonth from '../lastDayOfMonth/index.js'
import startOfMonth from '../startOfMonth/index.js'
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
export default function getWeeksInMonth(date, options) {
if (arguments.length < 1) |
return (
differenceInCalendarWeeks(
lastDayOfMonth(date),
startOfMonth(date),
options
) + 1
)
}
| {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
} | conditional_block |
index.js | import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js'
import lastDayOfMonth from '../lastDayOfMonth/index.js'
import startOfMonth from '../startOfMonth/index.js'
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
export default function getWeeksInMonth(date, options) | {
if (arguments.length < 1) {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
}
return (
differenceInCalendarWeeks(
lastDayOfMonth(date),
startOfMonth(date),
options
) + 1
)
} | identifier_body |
|
index.js | import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js'
import lastDayOfMonth from '../lastDayOfMonth/index.js'
import startOfMonth from '../startOfMonth/index.js'
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
* | * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
export default function getWeeksInMonth(date, options) {
if (arguments.length < 1) {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
}
return (
differenceInCalendarWeeks(
lastDayOfMonth(date),
startOfMonth(date),
options
) + 1
)
} | * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options. | random_line_split |
index.js | import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js'
import lastDayOfMonth from '../lastDayOfMonth/index.js'
import startOfMonth from '../startOfMonth/index.js'
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
export default function | (date, options) {
if (arguments.length < 1) {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
}
return (
differenceInCalendarWeeks(
lastDayOfMonth(date),
startOfMonth(date),
options
) + 1
)
}
| getWeeksInMonth | identifier_name |
linear-for-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug;
pub fn | () {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_string();
let mut i: int = 0;
for c in s.as_slice().bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
// ...
i += 1;
println!("{:?}", i);
println!("{:?}", c);
}
assert_eq!(i, 11);
}
| main | identifier_name |
linear-for-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug; | pub fn main() {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_string();
let mut i: int = 0;
for c in s.as_slice().bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
// ...
i += 1;
println!("{:?}", i);
println!("{:?}", c);
}
assert_eq!(i, 11);
} | random_line_split |
|
linear-for-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug;
pub fn main() | {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_string();
let mut i: int = 0;
for c in s.as_slice().bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
if i == 4 { assert!((c == 'o' as u8)); }
// ...
i += 1;
println!("{:?}", i);
println!("{:?}", c);
}
assert_eq!(i, 11);
} | identifier_body |
|
linear-for-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug;
pub fn main() {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
let s = "hello there".to_string();
let mut i: int = 0;
for c in s.as_slice().bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 |
if i == 4 { assert!((c == 'o' as u8)); }
// ...
i += 1;
println!("{:?}", i);
println!("{:?}", c);
}
assert_eq!(i, 11);
}
| { assert!((c == 'l' as u8)); } | conditional_block |
test.rs | #![allow(unstable)]
extern crate "recursive_sync" as rs;
use rs::RMutex;
use std::thread::Thread;
use std::sync::Arc;
use std::io::timer::sleep;
use std::time::duration::Duration;
#[test]
fn recursive_test() {
let mutex = RMutex::new(0i32);
{
let mut outer_lock = mutex.lock();
{
let mut inner_lock = mutex.lock();
*inner_lock = 1;
}
*outer_lock = 2;
}
assert_eq!(*mutex.lock(), 2);
}
#[test]
fn | () {
let count = 1000;
let mutex = Arc::new(RMutex::new(0i32));
let mut guards = Vec::new();
for _ in (0..count) {
let mutex = mutex.clone();
guards.push(Thread::scoped(move || {
let mut value_ref = mutex.lock();
let value = *value_ref;
sleep(Duration::milliseconds(1));
*value_ref = value + 1;
}));
}
drop(guards);
assert_eq!(*mutex.lock(), count);
}
| test_guarding | identifier_name |
test.rs | #![allow(unstable)]
extern crate "recursive_sync" as rs;
use rs::RMutex;
use std::thread::Thread;
use std::sync::Arc;
use std::io::timer::sleep;
use std::time::duration::Duration;
#[test]
fn recursive_test() {
let mutex = RMutex::new(0i32); | let mut outer_lock = mutex.lock();
{
let mut inner_lock = mutex.lock();
*inner_lock = 1;
}
*outer_lock = 2;
}
assert_eq!(*mutex.lock(), 2);
}
#[test]
fn test_guarding() {
let count = 1000;
let mutex = Arc::new(RMutex::new(0i32));
let mut guards = Vec::new();
for _ in (0..count) {
let mutex = mutex.clone();
guards.push(Thread::scoped(move || {
let mut value_ref = mutex.lock();
let value = *value_ref;
sleep(Duration::milliseconds(1));
*value_ref = value + 1;
}));
}
drop(guards);
assert_eq!(*mutex.lock(), count);
} | { | random_line_split |
test.rs | #![allow(unstable)]
extern crate "recursive_sync" as rs;
use rs::RMutex;
use std::thread::Thread;
use std::sync::Arc;
use std::io::timer::sleep;
use std::time::duration::Duration;
#[test]
fn recursive_test() |
#[test]
fn test_guarding() {
let count = 1000;
let mutex = Arc::new(RMutex::new(0i32));
let mut guards = Vec::new();
for _ in (0..count) {
let mutex = mutex.clone();
guards.push(Thread::scoped(move || {
let mut value_ref = mutex.lock();
let value = *value_ref;
sleep(Duration::milliseconds(1));
*value_ref = value + 1;
}));
}
drop(guards);
assert_eq!(*mutex.lock(), count);
}
| {
let mutex = RMutex::new(0i32);
{
let mut outer_lock = mutex.lock();
{
let mut inner_lock = mutex.lock();
*inner_lock = 1;
}
*outer_lock = 2;
}
assert_eq!(*mutex.lock(), 2);
} | identifier_body |
table.js | // GFM table, non-standard
'use strict';
function getLine(state, line) |
function escapedSplit(str) {
var result = [],
pos = 0,
max = str.length,
ch,
escapes = 0,
lastPos = 0,
backTicked = false,
lastBackTick = 0;
ch = str.charCodeAt(pos);
while (pos < max) {
if (ch === 0x60/* ` */ && (escapes % 2 === 0)) {
backTicked = !backTicked;
lastBackTick = pos;
} else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
result.push(str.substring(lastPos, pos));
lastPos = pos + 1;
} else if (ch === 0x5c/* \ */) {
escapes++;
} else {
escapes = 0;
}
pos++;
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false;
pos = lastBackTick + 1;
}
ch = str.charCodeAt(pos);
}
result.push(str.substring(lastPos));
return result;
}
module.exports = function table(state, startLine, endLine, silent) {
var ch, lineText, pos, i, nextLine, rows, token,
aligns, t, tableLines, tbodyLines;
// should have at least three lines
if (startLine + 2 > endLine) { return false; }
nextLine = startLine + 1;
if (state.tShift[nextLine] < state.blkIndent) { return false; }
// first character of the second line should be '|' or '-'
pos = state.bMarks[nextLine] + state.tShift[nextLine];
if (pos >= state.eMarks[nextLine]) { return false; }
ch = state.src.charCodeAt(pos);
if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }
lineText = getLine(state, startLine + 1);
if (!/^[-:| ]+$/.test(lineText)) { return false; }
rows = lineText.split('|');
if (rows.length < 2) { return false; }
aligns = [];
for (i = 0; i < rows.length; i++) {
t = rows[i].trim();
if (!t) {
// allow empty columns before and after table, but not in between columns;
// e.g. allow ` |---| `, disallow ` ---||--- `
if (i === 0 || i === rows.length - 1) {
continue;
} else {
return false;
}
}
if (!/^:?-+:?$/.test(t)) { return false; }
if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {
aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');
} else if (t.charCodeAt(0) === 0x3A/* : */) {
aligns.push('left');
} else {
aligns.push('');
}
}
lineText = getLine(state, startLine).trim();
if (lineText.indexOf('|') === -1) { return false; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
if (aligns.length !== rows.length) { return false; }
if (silent) { return true; }
token = state.push('table_open', 'table', 1);
token.map = tableLines = [ startLine, 0 ];
token = state.push('thead_open', 'thead', 1);
token.map = [ startLine, startLine + 1 ];
token = state.push('tr_open', 'tr', 1);
token.map = [ startLine, startLine + 1 ];
for (i = 0; i < rows.length; i++) {
token = state.push('th_open', 'th', 1);
token.map = [ startLine, startLine + 1 ];
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i].trim();
token.map = [ startLine, startLine + 1 ];
token.children = [];
token = state.push('th_close', 'th', -1);
}
token = state.push('tr_close', 'tr', -1);
token = state.push('thead_close', 'thead', -1);
token = state.push('tbody_open', 'tbody', 1);
token.map = tbodyLines = [ startLine + 2, 0 ];
for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
if (state.tShift[nextLine] < state.blkIndent) { break; }
lineText = getLine(state, nextLine).trim();
if (lineText.indexOf('|') === -1) { break; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
// set number of columns to number of columns in header row
rows.length = aligns.length;
token = state.push('tr_open', 'tr', 1);
for (i = 0; i < rows.length; i++) {
token = state.push('td_open', 'td', 1);
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i] ? rows[i].trim() : '';
token.children = [];
token = state.push('td_close', 'td', -1);
}
token = state.push('tr_close', 'tr', -1);
}
token = state.push('tbody_close', 'tbody', -1);
token = state.push('table_close', 'table', -1);
tableLines[1] = tbodyLines[1] = nextLine;
state.line = nextLine;
return true;
};
| {
var pos = state.bMarks[line] + state.blkIndent,
max = state.eMarks[line];
return state.src.substr(pos, max - pos);
} | identifier_body |
table.js | // GFM table, non-standard
'use strict';
function getLine(state, line) {
var pos = state.bMarks[line] + state.blkIndent,
max = state.eMarks[line];
return state.src.substr(pos, max - pos);
}
function escapedSplit(str) {
var result = [],
pos = 0,
max = str.length,
ch,
escapes = 0,
lastPos = 0,
backTicked = false,
lastBackTick = 0;
ch = str.charCodeAt(pos);
while (pos < max) {
if (ch === 0x60/* ` */ && (escapes % 2 === 0)) {
backTicked = !backTicked;
lastBackTick = pos;
} else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
result.push(str.substring(lastPos, pos));
lastPos = pos + 1;
} else if (ch === 0x5c/* \ */) {
escapes++;
} else {
escapes = 0;
}
pos++;
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false;
pos = lastBackTick + 1; | }
ch = str.charCodeAt(pos);
}
result.push(str.substring(lastPos));
return result;
}
module.exports = function table(state, startLine, endLine, silent) {
var ch, lineText, pos, i, nextLine, rows, token,
aligns, t, tableLines, tbodyLines;
// should have at least three lines
if (startLine + 2 > endLine) { return false; }
nextLine = startLine + 1;
if (state.tShift[nextLine] < state.blkIndent) { return false; }
// first character of the second line should be '|' or '-'
pos = state.bMarks[nextLine] + state.tShift[nextLine];
if (pos >= state.eMarks[nextLine]) { return false; }
ch = state.src.charCodeAt(pos);
if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }
lineText = getLine(state, startLine + 1);
if (!/^[-:| ]+$/.test(lineText)) { return false; }
rows = lineText.split('|');
if (rows.length < 2) { return false; }
aligns = [];
for (i = 0; i < rows.length; i++) {
t = rows[i].trim();
if (!t) {
// allow empty columns before and after table, but not in between columns;
// e.g. allow ` |---| `, disallow ` ---||--- `
if (i === 0 || i === rows.length - 1) {
continue;
} else {
return false;
}
}
if (!/^:?-+:?$/.test(t)) { return false; }
if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {
aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');
} else if (t.charCodeAt(0) === 0x3A/* : */) {
aligns.push('left');
} else {
aligns.push('');
}
}
lineText = getLine(state, startLine).trim();
if (lineText.indexOf('|') === -1) { return false; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
if (aligns.length !== rows.length) { return false; }
if (silent) { return true; }
token = state.push('table_open', 'table', 1);
token.map = tableLines = [ startLine, 0 ];
token = state.push('thead_open', 'thead', 1);
token.map = [ startLine, startLine + 1 ];
token = state.push('tr_open', 'tr', 1);
token.map = [ startLine, startLine + 1 ];
for (i = 0; i < rows.length; i++) {
token = state.push('th_open', 'th', 1);
token.map = [ startLine, startLine + 1 ];
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i].trim();
token.map = [ startLine, startLine + 1 ];
token.children = [];
token = state.push('th_close', 'th', -1);
}
token = state.push('tr_close', 'tr', -1);
token = state.push('thead_close', 'thead', -1);
token = state.push('tbody_open', 'tbody', 1);
token.map = tbodyLines = [ startLine + 2, 0 ];
for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
if (state.tShift[nextLine] < state.blkIndent) { break; }
lineText = getLine(state, nextLine).trim();
if (lineText.indexOf('|') === -1) { break; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
// set number of columns to number of columns in header row
rows.length = aligns.length;
token = state.push('tr_open', 'tr', 1);
for (i = 0; i < rows.length; i++) {
token = state.push('td_open', 'td', 1);
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i] ? rows[i].trim() : '';
token.children = [];
token = state.push('td_close', 'td', -1);
}
token = state.push('tr_close', 'tr', -1);
}
token = state.push('tbody_close', 'tbody', -1);
token = state.push('table_close', 'table', -1);
tableLines[1] = tbodyLines[1] = nextLine;
state.line = nextLine;
return true;
}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.