content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Go | Go | use a nonexistant hostname | 431e7b65733f2eb627bf69502355a66a35121e04 | <ide><path>integration-cli/docker_cli_push_test.go
<ide> func (s *DockerTrustSuite) TestTrustedPushWithFailingServer(c *check.C) {
<ide> dockerCmd(c, "tag", "busybox", repoName)
<ide>
<ide> pushCmd := exec.Command(dockerBinary, "push", repoName)
<del> s.trustedCmdWithServer(pushCmd, "https://example.com:81/")
<add> // Using a name that doesn't resolve to an address makes this test faster
<add> s.trustedCmdWithServer(pushCmd, "https://server.invalid:81/")
<ide> out, _, err := runCommandWithOutput(pushCmd)
<ide> c.Assert(err, check.NotNil, check.Commentf("Missing error while running trusted push w/ no server"))
<ide> c.Assert(out, checker.Contains, "error contacting notary server", check.Commentf("Missing expected output on trusted push"))
<ide> func (s *DockerTrustSuite) TestTrustedPushWithoutServerAndUntrusted(c *check.C)
<ide> dockerCmd(c, "tag", "busybox", repoName)
<ide>
<ide> pushCmd := exec.Command(dockerBinary, "push", "--disable-content-trust", repoName)
<del> s.trustedCmdWithServer(pushCmd, "https://example.com/")
<add> // Using a name that doesn't resolve to an address makes this test faster
<add> s.trustedCmdWithServer(pushCmd, "https://server.invalid")
<ide> out, _, err := runCommandWithOutput(pushCmd)
<ide> c.Assert(err, check.IsNil, check.Commentf("trusted push with no server and --disable-content-trust failed: %s\n%s", err, out))
<ide> c.Assert(out, check.Not(checker.Contains), "Error establishing connection to notary repository", check.Commentf("Missing expected output on trusted push with --disable-content-trust:")) | 1 |
Python | Python | fix oldnumeric compatibility with ma | fd6d555f8e4cf04871c1c1ed71ad53e2b6009164 | <ide><path>numpy/oldnumeric/ma.py
<ide> # Incompatibility in that getmask and a.mask returns nomask
<ide> # instead of None
<ide>
<del>from numpy.core.ma import *
<del>import numpy.core.ma as nca
<add>from numpy.ma import *
<add>import numpy.ma as nca
<ide>
<ide> def repeat(a, repeats, axis=0):
<ide> return nca.repeat(a, repeats, axis) | 1 |
Javascript | Javascript | use defaulthistorypath instead of path.join | ab3c84fc25320893e65fb0f5070b5ea4896350c7 | <ide><path>test/parallel/test-repl-persistent-history.js
<ide> ActionStream.prototype.readable = true;
<ide> const UP = { name: 'up' };
<ide> const ENTER = { name: 'enter' };
<ide> const CLEAR = { ctrl: true, name: 'u' };
<add>
<add>// File paths
<add>const fixtures = common.fixturesDir;
<add>const historyFixturePath = path.join(fixtures, '.node_repl_history');
<add>const historyPath = path.join(common.tmpDir, '.fixture_copy_repl_history');
<add>const historyPathFail = path.join(common.tmpDir, '.node_repl\u0000_history');
<add>const oldHistoryPathObj = path.join(fixtures,
<add> 'old-repl-history-file-obj.json');
<add>const oldHistoryPathFaulty = path.join(fixtures,
<add> 'old-repl-history-file-faulty.json');
<add>const oldHistoryPath = path.join(fixtures, 'old-repl-history-file.json');
<add>const enoentHistoryPath = path.join(fixtures, 'enoent-repl-history-file.json');
<add>const emptyHistoryPath = path.join(fixtures, '.empty-repl-history-file');
<add>const defaultHistoryPath = path.join(common.tmpDir, '.node_repl_history');
<add>const emptyHiddenHistoryPath = path.join(fixtures,
<add> '.empty-hidden-repl-history-file');
<add>const devNullHistoryPath = path.join(common.tmpDir,
<add> '.dev-null-repl-history-file');
<ide> // Common message bits
<ide> const prompt = '> ';
<ide> const replDisabled = '\nPersistent history support disabled. Set the ' +
<ide> 'NODE_REPL_HISTORY environment\nvariable to a valid, ' +
<ide> 'user-writable path to enable.\n';
<ide> const convertMsg = '\nConverted old JSON repl history to line-separated ' +
<ide> 'history.\nThe new repl history file can be found at ' +
<del> `${path.join(common.tmpDir, '.node_repl_history')}.\n`;
<add> `${defaultHistoryPath}.\n`;
<ide> const homedirErr = '\nError: Could not get the home directory.\n' +
<ide> 'REPL session history will not be persisted.\n';
<ide> const replFailedRead = '\nError: Could not open history file.\n' +
<ide> const oldHistoryObj = '\nError: The old history file data has to be an Array' +
<ide> '.\nREPL session history will not be persisted.\n';
<ide> const sameHistoryFilePaths = '\nThe old repl history file has the same name ' +
<ide> 'and location as the new one i.e., ' +
<del> path.join(common.tmpDir, '.node_repl_history') +
<add> `${defaultHistoryPath}` +
<ide> ' and is empty.\nUsing it as is.\n';
<del>// File paths
<del>const fixtures = common.fixturesDir;
<del>const historyFixturePath = path.join(fixtures, '.node_repl_history');
<del>const historyPath = path.join(common.tmpDir, '.fixture_copy_repl_history');
<del>const historyPathFail = path.join(common.tmpDir, '.node_repl\u0000_history');
<del>const oldHistoryPathObj = path.join(fixtures,
<del> 'old-repl-history-file-obj.json');
<del>const oldHistoryPathFaulty = path.join(fixtures,
<del> 'old-repl-history-file-faulty.json');
<del>const oldHistoryPath = path.join(fixtures, 'old-repl-history-file.json');
<del>const enoentHistoryPath = path.join(fixtures, 'enoent-repl-history-file.json');
<del>const emptyHistoryPath = path.join(fixtures, '.empty-repl-history-file');
<del>const defaultHistoryPath = path.join(common.tmpDir, '.node_repl_history');
<del>const emptyHiddenHistoryPath = path.join(fixtures,
<del> '.empty-hidden-repl-history-file');
<del>const devNullHistoryPath = path.join(common.tmpDir,
<del> '.dev-null-repl-history-file');
<ide>
<ide> const tests = [
<ide> { | 1 |
Ruby | Ruby | fix open redirects in active storage | 77f2af34f91b04fa8e97b49d6f3a197c2a09c754 | <ide><path>activestorage/app/controllers/active_storage/blobs/redirect_controller.rb
<ide> class ActiveStorage::Blobs::RedirectController < ActiveStorage::BaseController
<ide>
<ide> def show
<ide> expires_in ActiveStorage.service_urls_expire_in
<del> redirect_to @blob.url(disposition: params[:disposition])
<add> redirect_to @blob.url(disposition: params[:disposition]), allow_other_host: true
<ide> end
<ide> end
<ide><path>activestorage/app/controllers/active_storage/representations/redirect_controller.rb
<ide> class ActiveStorage::Representations::RedirectController < ActiveStorage::Representations::BaseController
<ide> def show
<ide> expires_in ActiveStorage.service_urls_expire_in
<del> redirect_to @representation.url(disposition: params[:disposition])
<add> redirect_to @representation.url(disposition: params[:disposition]), allow_other_host: true
<ide> end
<ide> end
<ide><path>activestorage/test/controllers/blobs/redirect_controller_test.rb
<ide> class ActiveStorage::Blobs::ExpiringRedirectControllerTest < ActionDispatch::Int
<ide> assert_response :not_found
<ide> end
<ide> end
<add>
<add>class ActiveStorage::Blobs::RedirectControllerWithOpenRedirectTest < ActionDispatch::IntegrationTest
<add> if SERVICE_CONFIGURATIONS[:s3]
<add> test "showing existing blob stored in s3" do
<add> with_raise_on_open_redirects(:s3) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :s3
<add>
<add> get rails_storage_redirect_url(blob)
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>
<add> if SERVICE_CONFIGURATIONS[:azure]
<add> test "showing existing blob stored in azure" do
<add> with_raise_on_open_redirects(:azure) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :azure
<add>
<add> get rails_storage_redirect_url(blob)
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>
<add> if SERVICE_CONFIGURATIONS[:gcs]
<add> test "showing existing blob stored in gcs" do
<add> with_raise_on_open_redirects(:gcs) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :gcs
<add>
<add> get rails_storage_redirect_url(blob)
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>end
<ide><path>activestorage/test/controllers/representations/redirect_controller_test.rb
<ide> class ActiveStorage::Representations::RedirectControllerWithPreviewsWithStrictLo
<ide> assert_equal 100, image.height
<ide> end
<ide> end
<add>
<add>class ActiveStorage::Representations::RedirectControllerWithOpenRedirectTest < ActionDispatch::IntegrationTest
<add> if SERVICE_CONFIGURATIONS[:s3]
<add> test "showing existing variant stored in s3" do
<add> with_raise_on_open_redirects(:s3) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :s3
<add>
<add> get rails_blob_representation_url(
<add> filename: blob.filename,
<add> signed_blob_id: blob.signed_id,
<add> variation_key: ActiveStorage::Variation.encode(resize_to_limit: [100, 100]))
<add>
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>
<add> if SERVICE_CONFIGURATIONS[:azure]
<add> test "showing existing variant stored in azure" do
<add> with_raise_on_open_redirects(:azure) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :azure
<add>
<add> get rails_blob_representation_url(
<add> filename: blob.filename,
<add> signed_blob_id: blob.signed_id,
<add> variation_key: ActiveStorage::Variation.encode(resize_to_limit: [100, 100]))
<add>
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>
<add> if SERVICE_CONFIGURATIONS[:gcs]
<add> test "showing existing variant stored in gcs" do
<add> with_raise_on_open_redirects(:gcs) do
<add> blob = create_file_blob filename: "racecar.jpg", service_name: :gcs
<add>
<add> get rails_blob_representation_url(
<add> filename: blob.filename,
<add> signed_blob_id: blob.signed_id,
<add> variation_key: ActiveStorage::Variation.encode(resize_to_limit: [100, 100]))
<add>
<add> assert_redirected_to(/racecar\.jpg/)
<add> end
<add> end
<add> end
<add>end
<ide><path>activestorage/test/test_helper.rb
<ide> def without_variant_tracking(&block)
<ide> yield
<ide> ActiveStorage.track_variants = variant_tracking_was
<ide> end
<add>
<add> def with_raise_on_open_redirects(service)
<add> old_raise_on_open_redirects = ActionController::Base.raise_on_open_redirects
<add> old_service = ActiveStorage::Blob.service
<add>
<add> ActionController::Base.raise_on_open_redirects = true
<add> ActiveStorage::Blob.service = ActiveStorage::Service.configure(service, SERVICE_CONFIGURATIONS)
<add> yield
<add> ensure
<add> ActionController::Base.raise_on_open_redirects = old_raise_on_open_redirects
<add> ActiveStorage::Blob.service = old_service
<add> end
<ide> end
<ide>
<ide> require "global_id" | 5 |
Text | Text | update changelog to include hostname commit | 5d25f3232c38d6a7ed31860948058b8ec1d95656 | <ide><path>CHANGELOG.md
<ide> - Runtime: Spawn shell within upstart script
<ide> - Builder: Make sure ENV instruction within build perform a commit each time
<ide> - Runtime: Handle ip route showing mask-less IP addresses
<add>- Runtime: Add hostname to environment
<ide>
<ide> ## 0.5.2 (2013-08-08)
<ide> * Builder: Forbid certain paths within docker build ADD | 1 |
Javascript | Javascript | add strict equalities in src/core/worker.js | fb9fea2f36a341301c8f16ade9be173bd70e7c69 | <ide><path>src/core/worker.js
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide> },
<ide>
<ide> onError: function onError(status) {
<del> if (status == 404) {
<add> if (status === 404) {
<ide> var exception = new MissingPDFException('Missing PDF "' +
<ide> source.url + '".');
<ide> handler.send('MissingPDF', { exception: exception }); | 1 |
PHP | PHP | use array as is | 86d36fa12f19720c9e018db647812eb3d02ebaab | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function flatten($depth = INF)
<ide> return $this->reduce(function ($return, $item) use ($depth) {
<ide> if ($item instanceof self || is_array($item)) {
<ide> if ($depth === 1) {
<del> return $return->merge(new static($item));
<add> return $return->merge($item);
<ide> }
<ide>
<ide> return $return->merge((new static($item))->flatten($depth - 1)); | 1 |
Python | Python | allow overrides for pod_template_file | a888198c27bcdbc4538c02360c308ffcaca182fa | <ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> from airflow.utils.helpers import validate_key
<ide> from airflow.utils.state import State
<ide> from airflow.version import version as airflow_version
<add>from airflow.kubernetes.pod_generator import PodGenerator
<ide>
<ide>
<ide> class KubernetesPodOperator(BaseOperator): # pylint: disable=too-many-instance-attributes
<ide> def execute(self, context) -> Optional[str]:
<ide> config_file=self.config_file)
<ide>
<ide> self.pod = self.create_pod_request_obj()
<add> self.namespace = self.pod.metadata.namespace
<add>
<ide> self.client = client
<ide>
<ide> # Add combination of labels to uniquely identify a running pod
<ide> def create_pod_request_obj(self) -> k8s.V1Pod:
<ide>
<ide> """
<ide> if self.pod_template_file:
<del> pod = pod_generator.PodGenerator.deserialize_model_file(self.pod_template_file)
<del> elif not self.pod:
<del> pod = k8s.V1Pod(
<del> api_version="v1",
<del> kind="Pod",
<del> metadata=k8s.V1ObjectMeta(
<del> namespace=self.namespace,
<del> labels=self.labels,
<del> name=self.name,
<del> annotations=self.annotations,
<del>
<del> ),
<del> spec=k8s.V1PodSpec(
<del> node_selector=self.node_selectors,
<del> affinity=self.affinity,
<del> tolerations=self.tolerations,
<del> init_containers=self.init_containers,
<del> containers=[
<del> k8s.V1Container(
<del> image=self.image,
<del> name="base",
<del> command=self.cmds,
<del> ports=self.ports,
<del> resources=self.k8s_resources,
<del> volume_mounts=self.volume_mounts,
<del> args=self.arguments,
<del> env=self.env_vars,
<del> env_from=self.env_from,
<del> )
<del> ],
<del> image_pull_secrets=self.image_pull_secrets,
<del> service_account_name=self.service_account_name,
<del> host_network=self.hostnetwork,
<del> security_context=self.security_context,
<del> dns_policy=self.dnspolicy,
<del> scheduler_name=self.schedulername,
<del> restart_policy='Never',
<del> priority_class_name=self.priority_class_name,
<del> volumes=self.volumes,
<del> )
<del> )
<add> pod_template = pod_generator.PodGenerator.deserialize_model_file(self.pod_template_file)
<ide> else:
<del> pod = self.pod
<add> pod_template = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="name"))
<add>
<add> pod = k8s.V1Pod(
<add> api_version="v1",
<add> kind="Pod",
<add> metadata=k8s.V1ObjectMeta(
<add> namespace=self.namespace,
<add> labels=self.labels,
<add> name=self.name,
<add> annotations=self.annotations,
<add>
<add> ),
<add> spec=k8s.V1PodSpec(
<add> node_selector=self.node_selectors,
<add> affinity=self.affinity,
<add> tolerations=self.tolerations,
<add> init_containers=self.init_containers,
<add> containers=[
<add> k8s.V1Container(
<add> image=self.image,
<add> name="base",
<add> command=self.cmds,
<add> ports=self.ports,
<add> resources=self.k8s_resources,
<add> volume_mounts=self.volume_mounts,
<add> args=self.arguments,
<add> env=self.env_vars,
<add> env_from=self.env_from,
<add> )
<add> ],
<add> image_pull_secrets=self.image_pull_secrets,
<add> service_account_name=self.service_account_name,
<add> host_network=self.hostnetwork,
<add> security_context=self.security_context,
<add> dns_policy=self.dnspolicy,
<add> scheduler_name=self.schedulername,
<add> restart_policy='Never',
<add> priority_class_name=self.priority_class_name,
<add> volumes=self.volumes,
<add> )
<add> )
<add>
<add> pod = PodGenerator.reconcile_pods(pod_template, pod)
<add>
<ide> for secret in self.secrets:
<ide> pod = secret.attach_to_pod(pod)
<ide> if self.do_xcom_push:
<del> from airflow.kubernetes.pod_generator import PodGenerator
<ide> pod = PodGenerator.add_xcom_sidecar(pod)
<ide> return pod
<ide>
<ide><path>kubernetes_tests/test_kubernetes_pod_operator.py
<ide> def test_pod_template_file_system(self):
<ide> self.assertIsNotNone(result)
<ide> self.assertDictEqual(result, {"hello": "world"})
<ide>
<add> def test_pod_template_file_with_overrides_system(self):
<add> fixture = sys.path[0] + '/tests/kubernetes/basic_pod.yaml'
<add> k = KubernetesPodOperator(
<add> task_id="task" + self.get_current_task_name(),
<add> labels={"foo": "bar", "fizz": "buzz"},
<add> env_vars=[k8s.V1EnvVar(name="env_name", value="value")],
<add> in_cluster=False,
<add> pod_template_file=fixture,
<add> do_xcom_push=True
<add> )
<add>
<add> context = create_context(k)
<add> result = k.execute(context)
<add> self.assertIsNotNone(result)
<add> self.assertEqual(k.pod.metadata.labels, {'fizz': 'buzz', 'foo': 'bar'})
<add> self.assertEqual(k.pod.spec.containers[0].env, [k8s.V1EnvVar(name="env_name", value="value")])
<add> self.assertDictEqual(result, {"hello": "world"})
<add>
<ide> def test_init_container(self):
<ide> # GIVEN
<ide> volume_mounts = [k8s.V1VolumeMount(
<ide> def test_pod_template_file(
<ide> api_version: v1
<ide> kind: Pod
<ide> metadata:
<del> annotations: null
<add> annotations: {}
<ide> cluster_name: null
<ide> creation_timestamp: null
<ide> deletion_grace_period_seconds: null\
<ide> """).strip()
<ide> self.assertTrue(any(line.startswith(expected_line) for line in cm.output))
<ide>
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<del> self.assertEqual({
<del> 'apiVersion': 'v1',
<del> 'kind': 'Pod',
<del> 'metadata': {'name': ANY, 'namespace': 'mem-example'},
<del> 'spec': {
<del> 'volumes': [{'name': 'xcom', 'emptyDir': {}}],
<del> 'containers': [{
<del> 'args': ['--vm', '1', '--vm-bytes', '150M', '--vm-hang', '1'],
<del> 'command': ['stress'],
<del> 'image': 'apache/airflow:stress-2020.07.10-1.0.4',
<del> 'name': 'memory-demo-ctr',
<del> 'resources': {
<del> 'limits': {'memory': '200Mi'},
<del> 'requests': {'memory': '100Mi'}
<del> },
<del> 'volumeMounts': [{
<del> 'name': 'xcom',
<del> 'mountPath': '/airflow/xcom'
<del> }]
<del> }, {
<del> 'name': 'airflow-xcom-sidecar',
<del> 'image': "alpine",
<del> 'command': ['sh', '-c', PodDefaults.XCOM_CMD],
<del> 'volumeMounts': [
<del> {
<del> 'name': 'xcom',
<del> 'mountPath': '/airflow/xcom'
<del> }
<del> ],
<del> 'resources': {'requests': {'cpu': '1m'}},
<del> }],
<del> }
<del> }, actual_pod)
<add> expected_dict = {'apiVersion': 'v1',
<add> 'kind': 'Pod',
<add> 'metadata': {'annotations': {},
<add> 'labels': {},
<add> 'name': 'memory-demo',
<add> 'namespace': 'mem-example'},
<add> 'spec': {'affinity': {},
<add> 'containers': [{'args': ['--vm',
<add> '1',
<add> '--vm-bytes',
<add> '150M',
<add> '--vm-hang',
<add> '1'],
<add> 'command': ['stress'],
<add> 'env': [],
<add> 'envFrom': [],
<add> 'image': 'apache/airflow:stress-2020.07.10-1.0.4',
<add> 'name': 'base',
<add> 'ports': [],
<add> 'resources': {'limits': {'memory': '200Mi'},
<add> 'requests': {'memory': '100Mi'}},
<add> 'volumeMounts': [{'mountPath': '/airflow/xcom',
<add> 'name': 'xcom'}]},
<add> {'command': ['sh',
<add> '-c',
<add> 'trap "exit 0" INT; while true; do sleep '
<add> '30; done;'],
<add> 'image': 'alpine',
<add> 'name': 'airflow-xcom-sidecar',
<add> 'resources': {'requests': {'cpu': '1m'}},
<add> 'volumeMounts': [{'mountPath': '/airflow/xcom',
<add> 'name': 'xcom'}]}],
<add> 'hostNetwork': False,
<add> 'imagePullSecrets': [],
<add> 'initContainers': [],
<add> 'nodeSelector': {},
<add> 'restartPolicy': 'Never',
<add> 'securityContext': {},
<add> 'serviceAccountName': 'default',
<add> 'tolerations': [],
<add> 'volumes': [{'emptyDir': {}, 'name': 'xcom'}]}}
<add> self.assertEqual(expected_dict, actual_pod)
<ide>
<ide> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<ide> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod") | 2 |
Java | Java | restore compatibility with jackson 2.1 | 89cc8e04014f9edd314de3eb4ec0d455f771d35e | <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java
<ide> public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessa
<ide> return readJavaType(javaType, inputMessage);
<ide> }
<ide>
<add> @SuppressWarnings("deprecation")
<ide> private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
<ide> try {
<ide> if (inputMessage instanceof MappingJacksonInputMessage) {
<ide> Class<?> deserializationView = ((MappingJacksonInputMessage)inputMessage).getDeserializationView();
<ide> if (deserializationView != null) {
<ide> return this.objectMapper.readerWithView(deserializationView)
<del> .forType(javaType).readValue(inputMessage.getBody());
<add> .withType(javaType).readValue(inputMessage.getBody());
<ide> }
<ide> }
<ide> return this.objectMapper.readValue(inputMessage.getBody(), javaType); | 1 |
PHP | PHP | fix wrong docblocks parameter name | 3213f88d9738e952d519b927f3389c72a1b2bb53 | <ide><path>src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
<ide> protected function handleUserWasAuthenticated(Request $request, $throttles)
<ide> /**
<ide> * Get the failed login response instance.
<ide> *
<del> * @param \Illuminate\Http\Request $response
<add> * @param \Illuminate\Http\Request $request
<ide> * @return \Illuminate\Http\Response
<ide> */
<ide> protected function sendFailedLoginResponse(Request $request) | 1 |
Javascript | Javascript | add http2 test for method connect | 88441f6baf616e38d8e2c795f6cffa24d4d1714c | <ide><path>test/parallel/test-http2-compat-method-connect.js
<add>// Flags: --expose-http2
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>const assert = require('assert');
<add>const http2 = require('http2');
<add>
<add>const server = http2.createServer(common.mustNotCall());
<add>
<add>server.listen(0, common.mustCall(() => testMethodConnect(2)));
<add>
<add>server.once('connect', common.mustCall((req, res) => {
<add> assert.strictEqual(req.headers[':method'], 'CONNECT');
<add> res.statusCode = 405;
<add> res.end();
<add>}));
<add>
<add>function testMethodConnect(testsToRun) {
<add> if (!testsToRun) {
<add> return server.close();
<add> }
<add>
<add> const port = server.address().port;
<add> const client = http2.connect(`http://localhost:${port}`);
<add> const req = client.request({
<add> ':method': 'CONNECT',
<add> ':authority': `localhost:${port}`
<add> });
<add>
<add> req.on('response', common.mustCall((headers) => {
<add> assert.strictEqual(headers[':status'], 405);
<add> }));
<add> req.resume();
<add> req.on('end', common.mustCall(() => {
<add> client.destroy();
<add> testMethodConnect(testsToRun - 1);
<add> }));
<add> req.end();
<add>} | 1 |
PHP | PHP | add support for releasing ironmq messages | 1f58d8a3a6972eecb5bd88a4d713ee53c425cee9 | <ide><path>src/Illuminate/Queue/Jobs/IronJob.php
<ide> public function delete()
<ide> */
<ide> public function release($delay = 0)
<ide> {
<del> //
<add> $this->iron->releaseMessage($this->queue, $this->job->id);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | allow calls to the api without auth | ef39ab0e206398594581391f738618ae00d1bb09 | <ide><path>api-server/server/boot/donate.js
<ide> const log = debug('fcc:boot:donate');
<ide>
<ide> export default function donateBoot(app, done) {
<ide> let stripe = false;
<add> const { User } = app.models;
<ide> const api = app.loopback.Router();
<ide> const hooks = app.loopback.Router();
<ide> const donateRouter = app.loopback.Router();
<ide> export default function donateBoot(app, done) {
<ide> });
<ide> }
<ide>
<add> const fccUser = user
<add> ? Promise.resolve(user)
<add> : new Promise((resolve, reject) =>
<add> User.findOrCreate(
<add> { where: { email } },
<add> { email },
<add> (err, instance, isNew) => {
<add> log('createing a new donating user instance: ', isNew);
<add> if (err) {
<add> return reject(err);
<add> }
<add> return resolve(instance);
<add> }
<add> )
<add> );
<add>
<ide> let donatingUser = {};
<ide> let donation = {
<ide> email,
<ide> export default function donateBoot(app, done) {
<ide> });
<ide> };
<ide>
<del> return Promise.resolve(user)
<add> return Promise.resolve(fccUser)
<ide> .then(nonDonatingUser => {
<ide> const { isDonating } = nonDonatingUser;
<del> if (isDonating) {
<add> if (isDonating && duration !== 'onetime') {
<ide> throw {
<del> message: `User already has active donation(s).`,
<add> message: `User already has active recurring donation(s).`,
<ide> type: 'AlreadyDonatingError'
<ide> };
<ide> }
<ide><path>api-server/server/middlewares/csurf.js
<ide> export default function() {
<ide> });
<ide> return function csrf(req, res, next) {
<ide> const { path } = req;
<del> if (/^\/hooks\/update-paypal$|^\/hooks\/update-stripe$/.test(path)) {
<add> if (
<add> // eslint-disable-next-line max-len
<add> /^\/hooks\/update-paypal$|^\/hooks\/update-stripe$|^\/donate\/charge-stripe$/.test(
<add> path
<add> )
<add> ) {
<ide> return next();
<ide> }
<ide> return protection(req, res, next);
<ide><path>api-server/server/middlewares/request-authorization.js
<ide> const unsubscribedRE = /^\/unsubscribed\//;
<ide> const unsubscribeRE = /^\/u\/|^\/unsubscribe\/|^\/ue\//;
<ide> const updateHooksRE = /^\/hooks\/update-paypal$|^\/hooks\/update-stripe$/;
<ide>
<add>// note: this would be replaced by webhooks later
<add>const donateRE = /^\/donate\/charge-stripe$/;
<add>
<ide> const _whiteListREs = [
<ide> authRE,
<ide> confirmEmailRE,
<ide> const _whiteListREs = [
<ide> statusRE,
<ide> unsubscribedRE,
<ide> unsubscribeRE,
<del> updateHooksRE
<add> updateHooksRE,
<add> donateRE
<ide> ];
<ide>
<ide> export function isWhiteListedPath(path, whiteListREs = _whiteListREs) { | 3 |
Javascript | Javascript | remove unused msg parameter in debug_agent | 5bd1642dd1797b6f1c016dfbaf6cf3c96075ac79 | <ide><path>lib/_debug_agent.js
<ide> function Client(agent, socket) {
<ide> }
<ide> util.inherits(Client, Transform);
<ide>
<del>Client.prototype.destroy = function destroy(msg) {
<add>Client.prototype.destroy = function destroy() {
<ide> this.socket.destroy();
<ide>
<ide> this.emit('close'); | 1 |
PHP | PHP | add missing type to param in docblock | e689ae9869bf264b9fcc8aac4b006a256798f693 | <ide><path>src/Illuminate/Http/Resources/MergeValue.php
<ide> class MergeValue
<ide> /**
<ide> * Create new merge value instance.
<ide> *
<del> * @param \Illuminate\Support\Collection|array $data
<add> * @param \Illuminate\Support\Collection|JsonSerializable|array $data
<ide> * @return void
<ide> */
<ide> public function __construct($data) | 1 |
Java | Java | restore response after beforecommit action errors | 08e9372ded3c36255389727465158007daae34f4 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java
<ide> public boolean isCommitted() {
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<ide> public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
<del> // Write as Mono if possible as an optimization hint to Reactor Netty
<del> // ChannelSendOperator not necessary for Mono
<add> // For Mono we can avoid ChannelSendOperator and Reactor Netty is more optimized for Mono.
<add> // We must resolve value first however, for a chance to handle potential error.
<ide> if (body instanceof Mono) {
<del> return ((Mono<? extends DataBuffer>) body).flatMap(buffer ->
<del> doCommit(() -> writeWithInternal(Mono.just(buffer)))
<del> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release))
<del> .doOnError(t -> this.getHeaders().clearContentHeaders());
<add> return ((Mono<? extends DataBuffer>) body)
<add> .flatMap(buffer -> doCommit(() ->
<add> writeWithInternal(Mono.fromCallable(() -> buffer)
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release))))
<add> .doOnError(t -> getHeaders().clearContentHeaders());
<add> }
<add> else {
<add> return new ChannelSendOperator<>(body, inner -> doCommit(() -> writeWithInternal(inner)))
<add> .doOnError(t -> getHeaders().clearContentHeaders());
<ide> }
<del> return new ChannelSendOperator<>(body, inner -> doCommit(() -> writeWithInternal(inner)))
<del> .doOnError(t -> this.getHeaders().clearContentHeaders());
<ide> }
<ide>
<ide> @Override
<ide> public final Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
<ide> return new ChannelSendOperator<>(body, inner -> doCommit(() -> writeAndFlushWithInternal(inner)))
<del> .doOnError(t -> this.getHeaders().clearContentHeaders());
<add> .doOnError(t -> getHeaders().clearContentHeaders());
<ide> }
<ide>
<ide> @Override
<ide> protected Mono<Void> doCommit(@Nullable Supplier<? extends Mono<Void>> writeActi
<ide> if (!this.state.compareAndSet(State.NEW, State.COMMITTING)) {
<ide> return Mono.empty();
<ide> }
<del> this.commitActions.add(() ->
<del> Mono.fromRunnable(() -> {
<del> applyStatusCode();
<del> applyHeaders();
<del> applyCookies();
<del> this.state.set(State.COMMITTED);
<del> }));
<del> if (writeAction != null) {
<del> this.commitActions.add(writeAction);
<add>
<add> Flux<Void> allActions = Flux.empty();
<add>
<add> if (!this.commitActions.isEmpty()) {
<add> allActions = Flux.concat(Flux.fromIterable(this.commitActions).map(Supplier::get))
<add> .doOnError(ex -> {
<add> if (this.state.compareAndSet(State.COMMITTING, State.NEW)) {
<add> getHeaders().clearContentHeaders();
<add> }
<add> });
<ide> }
<del> Flux<Void> commit = Flux.empty();
<del> for (Supplier<? extends Mono<Void>> action : this.commitActions) {
<del> commit = commit.concatWith(action.get());
<add>
<add> allActions = allActions.concatWith(Mono.fromRunnable(() -> {
<add> applyStatusCode();
<add> applyHeaders();
<add> applyCookies();
<add> this.state.set(State.COMMITTED);
<add> }));
<add>
<add> if (writeAction != null) {
<add> allActions = allActions.concatWith(writeAction.get());
<ide> }
<del> return commit.then();
<add>
<add> return allActions.then();
<ide> }
<ide>
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<add>import java.util.function.Consumer;
<add>import java.util.function.Supplier;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<add>import reactor.test.StepVerifier;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DefaultDataBuffer;
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> /**
<add> * Unit tests for {@link AbstractServerHttpRequest}.
<add> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Sebastien Deleuze
<ide> * @author Brian Clozel
<ide> */
<ide> public class ServerHttpResponseTests {
<ide>
<ide> @Test
<del> void writeWith() throws Exception {
<add> void writeWith() {
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block();
<ide>
<ide> void writeWith() throws Exception {
<ide> }
<ide>
<ide> @Test // SPR-14952
<del> void writeAndFlushWithFluxOfDefaultDataBuffer() throws Exception {
<add> void writeAndFlushWithFluxOfDefaultDataBuffer() {
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> Flux<Flux<DefaultDataBuffer>> flux = Flux.just(Flux.just(wrap("foo")));
<ide> response.writeAndFlushWith(flux).block();
<ide> void writeAndFlushWithFluxOfDefaultDataBuffer() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> void writeWithFluxError() throws Exception {
<add> void writeWithFluxError() {
<ide> IllegalStateException error = new IllegalStateException("boo");
<ide> writeWithError(Flux.error(error));
<ide> }
<ide>
<ide> @Test
<del> void writeWithMonoError() throws Exception {
<add> void writeWithMonoError() {
<ide> IllegalStateException error = new IllegalStateException("boo");
<ide> writeWithError(Mono.error(error));
<ide> }
<ide>
<del> void writeWithError(Publisher<DataBuffer> body) throws Exception {
<add> void writeWithError(Publisher<DataBuffer> body) {
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> HttpHeaders headers = response.getHeaders();
<ide> headers.setContentType(MediaType.APPLICATION_JSON);
<ide> void writeWithError(Publisher<DataBuffer> body) throws Exception {
<ide> }
<ide>
<ide> @Test
<del> void setComplete() throws Exception {
<add> void setComplete() {
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> response.setComplete().block();
<ide>
<ide> void setComplete() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> void beforeCommitWithComplete() throws Exception {
<add> void beforeCommitWithComplete() {
<ide> ResponseCookie cookie = ResponseCookie.from("ID", "123").build();
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> response.beforeCommit(() -> Mono.fromRunnable(() -> response.getCookies().add(cookie.getName(), cookie)));
<ide> void beforeCommitWithComplete() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> void beforeCommitActionWithSetComplete() throws Exception {
<add> void beforeCommitActionWithSetComplete() {
<ide> ResponseCookie cookie = ResponseCookie.from("ID", "123").build();
<ide> TestServerHttpResponse response = new TestServerHttpResponse();
<ide> response.beforeCommit(() -> {
<ide> void beforeCommitActionWithSetComplete() throws Exception {
<ide> assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie);
<ide> }
<ide>
<add> @Test // gh-24186
<add> void beforeCommitErrorShouldLeaveResponseNotCommitted() {
<add>
<add> Consumer<Supplier<Mono<Void>>> tester = preCommitAction -> {
<add> TestServerHttpResponse response = new TestServerHttpResponse();
<add> response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
<add> response.getHeaders().setContentLength(3);
<add> response.beforeCommit(preCommitAction);
<add>
<add> StepVerifier.create(response.writeWith(Flux.just(wrap("body"))))
<add> .expectErrorMessage("Max sessions")
<add> .verify();
<add>
<add> assertThat(response.statusCodeWritten).isFalse();
<add> assertThat(response.headersWritten).isFalse();
<add> assertThat(response.cookiesWritten).isFalse();
<add> assertThat(response.isCommitted()).isFalse();
<add> assertThat(response.getHeaders()).isEmpty();
<add> };
<add>
<add> tester.accept(() -> Mono.error(new IllegalStateException("Max sessions")));
<add> tester.accept(() -> {
<add> throw new IllegalStateException("Max sessions");
<add> });
<add> }
<add>
<ide>
<ide> private DefaultDataBuffer wrap(String a) {
<ide> return new DefaultDataBufferFactory().wrap(ByteBuffer.wrap(a.getBytes(StandardCharsets.UTF_8))); | 2 |
Java | Java | add support for rcttext under flatuiimplementation | 5c2f536e9a914f9d60915d3dae69fefd001027b7 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/AbstractDrawCommand.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * Base class for all DrawCommands. Becomes immutable once it has its bounds set. Until then, a
<add> * subclass is able to mutate any of its properties (e.g. updating Layout in DrawTextLayout).
<add> *
<add> * The idea is to be able to reuse unmodified objects when we build up DrawCommands before we ship
<add> * them to UI thread, but we can only do that if DrawCommands are immutable.
<add> */
<add>/* package */ abstract class AbstractDrawCommand implements DrawCommand, Cloneable {
<add>
<add> private float mLeft;
<add> private float mTop;
<add> private float mRight;
<add> private float mBottom;
<add> private boolean mFrozen;
<add>
<add> /**
<add> * Updates boundaries of the AbstractDrawCommand and freezes it.
<add> * Will return a frozen copy if the current AbstractDrawCommand cannot be mutated.
<add> */
<add> public final AbstractDrawCommand updateBoundsAndFreeze(
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> if (mFrozen) {
<add> // see if we can reuse it
<add> if (boundsMatch(left, top, right, bottom)) {
<add> return this;
<add> }
<add>
<add> try {
<add> AbstractDrawCommand copy = (AbstractDrawCommand) clone();
<add> copy.setBounds(left, top, right, bottom);
<add> return copy;
<add> } catch (CloneNotSupportedException e) {
<add> // This should not happen since AbstractDrawCommand implements Cloneable
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> setBounds(left, top, right, bottom);
<add> mFrozen = true;
<add> return this;
<add> }
<add>
<add> /**
<add> * Returns whether this object was frozen and thus cannot be mutated.
<add> */
<add> public final boolean isFrozen() {
<add> return mFrozen;
<add> }
<add>
<add> /**
<add> * Left position of this DrawCommand relative to the hosting View.
<add> */
<add> public final float getLeft() {
<add> return mLeft;
<add> }
<add>
<add> /**
<add> * Top position of this DrawCommand relative to the hosting View.
<add> */
<add> public final float getTop() {
<add> return mTop;
<add> }
<add>
<add> /**
<add> * Right position of this DrawCommand relative to the hosting View.
<add> */
<add> public final float getRight() {
<add> return mRight;
<add> }
<add>
<add> /**
<add> * Bottom position of this DrawCommand relative to the hosting View.
<add> */
<add> public final float getBottom() {
<add> return mBottom;
<add> }
<add>
<add> /**
<add> * Updates boundaries of this DrawCommand.
<add> */
<add> private void setBounds(float left, float top, float right, float bottom) {
<add> mLeft = left;
<add> mTop = top;
<add> mRight = right;
<add> mBottom = bottom;
<add> }
<add>
<add> /**
<add> * Returns true if boundaries match and don't need to be updated. False otherwise.
<add> */
<add> private boolean boundsMatch(float left, float top, float right, float bottom) {
<add> return mLeft == left && mTop == top && mRight == right && mBottom == bottom;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawCommand.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.graphics.Canvas;
<add>
<add>/**
<add> * DrawCommand is an inteface that shadow nodes need to implement to do the drawing.
<add> * Instaces of DrawCommand are created in background thread and passed to UI thread.
<add> * Once a DrawCommand is shared with UI thread, it can no longer be mutated in background thread.
<add> */
<add>public interface DrawCommand {
<add> // used by StateBuilder, FlatViewGroup and FlatShadowNode
<add> /* package */ static final DrawCommand[] EMPTY_ARRAY = new DrawCommand[0];
<add>
<add> /**
<add> * Performs drawing into the given canvas.
<add> *
<add> * @param canvas The canvas to draw into
<add> */
<add> public void draw(Canvas canvas);
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawTextLayout.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.graphics.Canvas;
<add>import android.text.Layout;
<add>
<add>/**
<add> * DrawTextLayout is a DrawCommand that draw {@link Layout}.
<add> */
<add>/* package */ final class DrawTextLayout extends AbstractDrawCommand {
<add>
<add> private Layout mLayout;
<add>
<add> /* package */ DrawTextLayout(Layout layout) {
<add> mLayout = layout;
<add> }
<add>
<add> /**
<add> * Assigns a new {@link Layout} to draw.
<add> */
<add> public void setLayout(Layout layout) {
<add> mLayout = layout;
<add> }
<add>
<add> @Override
<add> public void draw(Canvas canvas) {
<add> float left = getLeft();
<add> float top = getTop();
<add>
<add> canvas.translate(left, top);
<add> mLayout.draw(canvas);
<add> canvas.translate(-left, -top);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatNativeViewHierarchyManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.view.View;
<add>import android.view.View.MeasureSpec;
<add>
<add>import com.facebook.react.uimanager.NativeViewHierarchyManager;
<add>import com.facebook.react.uimanager.SizeMonitoringFrameLayout;
<add>import com.facebook.react.uimanager.ThemedReactContext;
<add>import com.facebook.react.uimanager.ViewManagerRegistry;
<add>
<add>/**
<add> * FlatNativeViewHierarchyManager is the only class that performs View manipulations. All of this
<add> * class methods can only be called from UI thread by {@link FlatUIViewOperationQueue}.
<add> */
<add>/* package */ final class FlatNativeViewHierarchyManager extends NativeViewHierarchyManager {
<add>
<add> /* package */ FlatNativeViewHierarchyManager(ViewManagerRegistry viewManagers) {
<add> super(viewManagers);
<add> }
<add>
<add> @Override
<add> public void addRootView(
<add> int tag,
<add> SizeMonitoringFrameLayout view,
<add> ThemedReactContext themedContext) {
<add> FlatViewGroup root = new FlatViewGroup(themedContext);
<add> view.addView(root);
<add>
<add> addRootViewGroup(tag, root, themedContext);
<add> }
<add>
<add> /**
<add> * Assigns new DrawCommands to a FlatViewGroup specified by a reactTag.
<add> *
<add> * @param reactTag reactTag to lookup FlatViewGroup by
<add> * @param drawCommands new draw commands to execute during the drawing.
<add> */
<add> /* package */ void updateMountState(int reactTag, DrawCommand[] drawCommands) {
<add> FlatViewGroup view = (FlatViewGroup) resolveView(reactTag);
<add> view.mountDrawCommands(drawCommands);
<add> }
<add>
<add> /**
<add> * Updates View bounds, possibly re-measuring and re-layouting it if the size changed.
<add> *
<add> * @param reactTag reactTag to lookup a View by
<add> * @param left left coordinate relative to parent
<add> * @param top top coordinate relative to parent
<add> * @param right right coordinate relative to parent
<add> * @param bottom bottom coordinate relative to parent
<add> */
<add> /* package */ void updateViewBounds(int reactTag, int left, int top, int right, int bottom) {
<add> View view = resolveView(reactTag);
<add> int width = right - left;
<add> int height = bottom - top;
<add> if (view.getWidth() != width || view.getHeight() != height) {
<add> // size changed, we need to measure and layout the View
<add> view.measure(
<add> MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
<add> MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
<add> view.layout(left, top, right, bottom);
<add> } else {
<add> // same size, only location changed, there is a faster route.
<add> view.offsetLeftAndRight(left - view.getLeft());
<add> view.offsetTopAndBottom(top - view.getTop());
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatRootShadowNode.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * Root node of the shadow node hierarchy. Currently, the only node that can actually map to a View.
<add> */
<add>/* package */ final class FlatRootShadowNode extends FlatShadowNode {
<add>
<add> private DrawCommand[] mDrawCommands = DrawCommand.EMPTY_ARRAY;
<add>
<add> private int mViewLeft;
<add> private int mViewTop;
<add> private int mViewRight;
<add> private int mViewBottom;
<add>
<add> @Override
<add> public int getScreenX() {
<add> return mViewLeft;
<add> }
<add>
<add> @Override
<add> public int getScreenY() {
<add> return mViewTop;
<add> }
<add>
<add> @Override
<add> public int getScreenWidth() {
<add> return mViewRight - mViewLeft;
<add> }
<add>
<add> @Override
<add> public int getScreenHeight() {
<add> return mViewBottom - mViewTop;
<add> }
<add>
<add> /**
<add> * Returns an array of DrawCommands to perform during the View's draw pass.
<add> */
<add> /* package */ DrawCommand[] getDrawCommands() {
<add> return mDrawCommands;
<add> }
<add>
<add> /**
<add> * Sets an array of DrawCommands to perform during the View's draw pass. StateBuilder uses old
<add> * draw commands to compare to new draw commands and see if the View neds to be redrawn.
<add> */
<add> /* package */ void setDrawCommands(DrawCommand[] drawCommands) {
<add> mDrawCommands = drawCommands;
<add> }
<add>
<add> /**
<add> * Sets boundaries of the View that this node maps to relative to the parent left/top coordinate.
<add> */
<add> /* package */ void setViewBounds(int left, int top, int right, int bottom) {
<add> mViewLeft = left;
<add> mViewTop = top;
<add> mViewRight = right;
<add> mViewBottom = bottom;
<add> }
<add>
<add> /**
<add> * Left position of the View this node maps to relative to the parent View.
<add> */
<add> /* package */ int getViewLeft() {
<add> return mViewLeft;
<add> }
<add>
<add> /**
<add> * Top position of the View this node maps to relative to the parent View.
<add> */
<add> /* package */ int getViewTop() {
<add> return mViewTop;
<add> }
<add>
<add> /**
<add> * Right position of the View this node maps to relative to the parent View.
<add> */
<add> /* package */ int getViewRight() {
<add> return mViewRight;
<add> }
<add>
<add> /**
<add> * Bottom position of the View this node maps to relative to the parent View.
<add> */
<add> /* package */ int getViewBottom() {
<add> return mViewBottom;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import com.facebook.react.uimanager.LayoutShadowNode;
<add>
<add>/**
<add> * FlatShadowNode is a base class for all shadow node used in FlatUIImplementation. It extends
<add> * {@link LayoutShadowNode} by adding an ability to prepare DrawCommands off the UI thread.
<add> */
<add>/* package */ class FlatShadowNode extends LayoutShadowNode {
<add>
<add> /**
<add> * Collects DrawCommands produced by this FlatShadoNode.
<add> */
<add> protected void collectState(
<add> StateBuilder stateBuilder,
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> // do nothing yet.
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatTextShadowNode.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.text.SpannableStringBuilder;
<add>
<add>import com.facebook.react.uimanager.ReactShadowNode;
<add>
<add>/**
<add> * Base class for RCTVirtualText and RCTRawText.
<add> */
<add>/* package */ abstract class FlatTextShadowNode extends FlatShadowNode {
<add>
<add> /**
<add> * Recursively visits FlatTextShadowNode and its children,
<add> * appending text to SpannableStringBuilder.
<add> */
<add> protected abstract void collectText(SpannableStringBuilder builder);
<add>
<add> /**
<add> * Recursively visits FlatTextShadowNode and its children,
<add> * applying spans to SpannableStringBuilder.
<add> */
<add> protected abstract void applySpans(SpannableStringBuilder builder);
<add>
<add> /**
<add> * Propagates changes up to RCTText without dirtying current node.
<add> */
<add> protected void notifyChanged(boolean shouldRemeasure) {
<add> ReactShadowNode parent = getParent();
<add> if (parent instanceof FlatTextShadowNode) {
<add> ((FlatTextShadowNode) parent).notifyChanged(shouldRemeasure);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isVirtual() {
<add> return true;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java
<ide>
<ide> package com.facebook.react.flat;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> import javax.annotation.Nullable;
<ide> */
<ide> public class FlatUIImplementation extends UIImplementation {
<ide>
<del> public FlatUIImplementation(
<add> private final StateBuilder mStateBuilder;
<add>
<add> public static FlatUIImplementation createInstance(
<ide> ReactApplicationContext reactContext,
<ide> List<ViewManager> viewManagers) {
<del> this(reactContext, new ViewManagerRegistry(viewManagers));
<add>
<add> viewManagers = new ArrayList<ViewManager>(viewManagers);
<add> viewManagers.add(new RCTViewManager());
<add> viewManagers.add(new RCTTextManager());
<add> viewManagers.add(new RCTRawTextManager());
<add> viewManagers.add(new RCTVirtualTextManager());
<add>
<add> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers);
<add> FlatNativeViewHierarchyManager nativeViewHierarchyManager = new FlatNativeViewHierarchyManager(
<add> viewManagerRegistry);
<add> FlatUIViewOperationQueue operationsQueue = new FlatUIViewOperationQueue(
<add> reactContext,
<add> nativeViewHierarchyManager);
<add> return new FlatUIImplementation(viewManagerRegistry, operationsQueue);
<ide> }
<ide>
<ide> private FlatUIImplementation(
<del> ReactApplicationContext reactContext,
<del> ViewManagerRegistry viewManagers) {
<del> super(
<del> viewManagers,
<del> new UIViewOperationQueue(
<del> reactContext,
<del> new NativeViewHierarchyManager(viewManagers)));
<add> ViewManagerRegistry viewManagers,
<add> FlatUIViewOperationQueue operationsQueue) {
<add> super(viewManagers, operationsQueue);
<add> mStateBuilder = new StateBuilder(operationsQueue);
<add> }
<add>
<add> @Override
<add> protected ReactShadowNode createRootShadowNode() {
<add> return new FlatRootShadowNode();
<ide> }
<ide>
<ide> @Override
<ide> protected void applyUpdatesRecursive(
<ide> float absoluteX,
<ide> float absoluteY,
<ide> EventDispatcher eventDispatcher) {
<del> markNodeLayoutSeen(cssNode);
<del> }
<del>
<del> private void markNodeLayoutSeen(CSSNode node) {
<del> if (node.hasNewLayout()) {
<del> node.markLayoutSeen();
<del> }
<del>
<del> for (int i = 0, childCount = node.getChildCount(); i != childCount; ++i) {
<del> markNodeLayoutSeen(node.getChildAt(i));
<del> }
<add> mStateBuilder.applyUpdates((FlatRootShadowNode) cssNode);
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIViewOperationQueue.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import com.facebook.react.bridge.ReactApplicationContext;
<add>import com.facebook.react.uimanager.UIViewOperationQueue;
<add>
<add>/**
<add> * FlatUIViewOperationQueue extends {@link UIViewOperationQueue} to add
<add> * FlatUIImplementation-specific methods that need to run in UI thread.
<add> */
<add>/* package */ final class FlatUIViewOperationQueue extends UIViewOperationQueue {
<add>
<add> private final FlatNativeViewHierarchyManager mNativeViewHierarchyManager;
<add>
<add> /**
<add> * UIOperation that updates DrawCommands for a View defined by reactTag.
<add> */
<add> private final class UpdateMountState implements UIOperation {
<add>
<add> private final int mReactTag;
<add> private final DrawCommand[] mDrawCommands;
<add>
<add> private UpdateMountState(int reactTag, DrawCommand[] drawCommands) {
<add> mReactTag = reactTag;
<add> mDrawCommands = drawCommands;
<add> }
<add>
<add> @Override
<add> public void execute() {
<add> mNativeViewHierarchyManager.updateMountState(mReactTag, mDrawCommands);
<add> }
<add> }
<add>
<add> /**
<add> * UIOperation that updates View bounds for a View defined by reactTag.
<add> */
<add> private final class UpdateViewBounds implements UIOperation {
<add>
<add> private final int mReactTag;
<add> private final int mLeft;
<add> private final int mTop;
<add> private final int mRight;
<add> private final int mBottom;
<add>
<add> private UpdateViewBounds(int reactTag, int left, int top, int right, int bottom) {
<add> mReactTag = reactTag;
<add> mLeft = left;
<add> mTop = top;
<add> mRight = right;
<add> mBottom = bottom;
<add> }
<add>
<add> @Override
<add> public void execute() {
<add> mNativeViewHierarchyManager.updateViewBounds(mReactTag, mLeft, mTop, mRight, mBottom);
<add> }
<add> }
<add>
<add> public FlatUIViewOperationQueue(
<add> ReactApplicationContext reactContext,
<add> FlatNativeViewHierarchyManager nativeViewHierarchyManager) {
<add> super(reactContext, nativeViewHierarchyManager);
<add>
<add> mNativeViewHierarchyManager = nativeViewHierarchyManager;
<add> }
<add>
<add> /**
<add> * Enqueues a new UIOperation that will update DrawCommands for a View defined by reactTag.
<add> */
<add> public void enqueueUpdateMountState(int reactTag, DrawCommand[] drawCommands) {
<add> enqueueUIOperation(new UpdateMountState(reactTag, drawCommands));
<add> }
<add>
<add> /**
<add> * Enqueues a new UIOperation that will update View bounds for a View defined by reactTag.
<add> */
<add> public void enqueueUpdateViewBounds(int reactTag, int left, int top, int right, int bottom) {
<add> enqueueUIOperation(new UpdateViewBounds(reactTag, left, top, right, bottom));
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatViewGroup.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.content.Context;
<add>import android.graphics.Canvas;
<add>import android.view.ViewGroup;
<add>
<add>/**
<add> * A view that FlatShadowNode hierarchy maps to. Performs drawing by iterating over
<add> * array of DrawCommands, executing them one by one.
<add> */
<add>/* package */ final class FlatViewGroup extends ViewGroup {
<add>
<add> private DrawCommand[] mDrawCommands = DrawCommand.EMPTY_ARRAY;
<add>
<add> /* package */ FlatViewGroup(Context context) {
<add> super(context);
<add> }
<add>
<add> @Override
<add> public void dispatchDraw(Canvas canvas) {
<add> super.dispatchDraw(canvas);
<add>
<add> for (DrawCommand drawCommand : mDrawCommands) {
<add> drawCommand.draw(canvas);
<add> }
<add> }
<add>
<add> @Override
<add> protected void onLayout(boolean changed, int l, int t, int r, int b) {
<add> // nothing to do here
<add> }
<add>
<add> /* package */ void mountDrawCommands(DrawCommand[] drawCommands) {
<add> mDrawCommands = drawCommands;
<add> invalidate();
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FontStylingSpan.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import android.graphics.Typeface;
<add>import android.text.TextPaint;
<add>import android.text.style.MetricAffectingSpan;
<add>
<add>/* package */ final class FontStylingSpan extends MetricAffectingSpan {
<add> // text property
<add> private final double mTextColor;
<add> private final int mBackgroundColor;
<add>
<add> // font properties
<add> private final int mFontSize;
<add> private final int mFontStyle;
<add> private final int mFontWeight;
<add> private final @Nullable String mFontFamily;
<add>
<add> FontStylingSpan(
<add> double textColor,
<add> int backgroundColor,
<add> int fontSize,
<add> int fontStyle,
<add> int fontWeight,
<add> @Nullable String fontFamily) {
<add> mTextColor = textColor;
<add> mBackgroundColor = backgroundColor;
<add> mFontSize = fontSize;
<add> mFontStyle = fontStyle;
<add> mFontWeight = fontWeight;
<add> mFontFamily = fontFamily;
<add> }
<add>
<add> @Override
<add> public void updateDrawState(TextPaint ds) {
<add> if (!Double.isNaN(mTextColor)) {
<add> ds.setColor((int) mTextColor);
<add> }
<add>
<add> ds.bgColor = mBackgroundColor;
<add> updateMeasureState(ds);
<add> }
<add>
<add> @Override
<add> public void updateMeasureState(TextPaint ds) {
<add> if (mFontSize != -1) {
<add> ds.setTextSize(mFontSize);
<add> }
<add>
<add> updateTypeface(ds);
<add> }
<add>
<add> private int getNewStyle(int oldStyle) {
<add> int newStyle = oldStyle;
<add> if (mFontStyle != -1) {
<add> newStyle = (newStyle & ~Typeface.ITALIC) | mFontStyle;
<add> }
<add>
<add> if (mFontWeight != -1) {
<add> newStyle = (newStyle & ~Typeface.BOLD) | mFontWeight;
<add> }
<add>
<add> return newStyle;
<add> }
<add>
<add> private void updateTypeface(TextPaint ds) {
<add> Typeface typeface = ds.getTypeface();
<add>
<add> int oldStyle = (typeface == null) ? 0 : typeface.getStyle();
<add> int newStyle = getNewStyle(oldStyle);
<add>
<add> if (oldStyle == newStyle && mFontFamily == null) {
<add> // nothing to do
<add> return;
<add> }
<add>
<add> // TODO: optimize this part (implemented in a followup patch)
<add>
<add> if (mFontFamily != null) {
<add> // efficient in API 21+
<add> typeface = Typeface.create(mFontFamily, newStyle);
<add> } else {
<add> // efficient in API 16+
<add> typeface = Typeface.create(typeface, newStyle);
<add> }
<add>
<add> ds.setTypeface(typeface);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTRawText.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import android.text.SpannableStringBuilder;
<add>
<add>import com.facebook.react.uimanager.ReactProp;
<add>
<add>/**
<add> * RCTRawText is a FlatTextShadowNode that can only contain raw text (but not styling).
<add> */
<add>/* package */ class RCTRawText extends FlatTextShadowNode {
<add>
<add> private @Nullable String mText;
<add>
<add> @Override
<add> protected void collectText(SpannableStringBuilder builder) {
<add> if (mText != null) {
<add> builder.append(mText);
<add> }
<add>
<add> // RCTRawText cannot have any children, so no recursive calls needed.
<add> }
<add>
<add> @Override
<add> protected void applySpans(SpannableStringBuilder builder) {
<add> // no spans and no children so nothing to do here.
<add> }
<add>
<add> @ReactProp(name = "text")
<add> public void setText(@Nullable String text) {
<add> mText = text;
<add> notifyChanged(true);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTRawTextManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * ViewManager that creates instances of RCTRawText.
<add> */
<add>/* package */ final class RCTRawTextManager extends VirtualViewManager<RCTRawText> {
<add>
<add> @Override
<add> public String getName() {
<add> return "RCTRawText";
<add> }
<add>
<add> @Override
<add> public RCTRawText createShadowNodeInstance() {
<add> return new RCTRawText();
<add> }
<add>
<add> @Override
<add> public Class<RCTRawText> getShadowNodeClass() {
<add> return RCTRawText.class;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTText.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import android.text.BoringLayout;
<add>import android.text.Layout;
<add>import android.text.SpannableStringBuilder;
<add>import android.text.StaticLayout;
<add>import android.text.TextPaint;
<add>import android.text.TextUtils;
<add>
<add>import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.MeasureOutput;
<add>import com.facebook.react.uimanager.PixelUtil;
<add>import com.facebook.react.uimanager.ReactProp;
<add>import com.facebook.react.uimanager.ViewDefaults;
<add>import com.facebook.react.uimanager.ViewProps;
<add>
<add>/**
<add> * RCTText is a top-level node for text. It extends {@link RCTVirtualText} because it can contain
<add> * styling information, but has the following differences:
<add> *
<add> * a) RCTText is not a virtual node, and can be measured and laid out.
<add> * b) when no font size is specified, a font size of ViewDefaults#FONT_SIZE_SP is assumed.
<add> */
<add>/* package */ final class RCTText extends RCTVirtualText implements CSSNode.MeasureFunction {
<add>
<add> private static final boolean INCLUDE_PADDING = true;
<add> private static final TextPaint PAINT = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
<add>
<add> // this is optional, and helps saving a few BoringLayout.Metrics allocations during measure().
<add> private static @Nullable BoringLayout.Metrics sBoringLayoutMetrics;
<add>
<add> private @Nullable CharSequence mText;
<add> private @Nullable DrawTextLayout mDrawCommand;
<add> private @Nullable BoringLayout.Metrics mBoringLayoutMetrics;
<add> private float mSpacingMult = 1.0f;
<add> private float mSpacingAdd = 0.0f;
<add>
<add> public RCTText() {
<add> setMeasureFunction(this);
<add> }
<add>
<add> @Override
<add> public boolean isVirtual() {
<add> return false;
<add> }
<add>
<add> @Override
<add> public boolean isVirtualAnchor() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void measure(CSSNode node, float width, MeasureOutput measureOutput) {
<add> CharSequence text = getText();
<add>
<add> if (TextUtils.isEmpty(text)) {
<add> // to indicate that we don't have anything to display
<add> mText = null;
<add> measureOutput.width = 0;
<add> measureOutput.height = 0;
<add> return;
<add> }
<add>
<add> mText = text;
<add>
<add> BoringLayout.Metrics metrics = BoringLayout.isBoring(text, PAINT, sBoringLayoutMetrics);
<add> if (metrics != null) {
<add> sBoringLayoutMetrics = mBoringLayoutMetrics;
<add> if (sBoringLayoutMetrics != null) {
<add> // make sure it's always empty, reported metrics can be incorrect otherwise
<add> sBoringLayoutMetrics.top = 0;
<add> sBoringLayoutMetrics.ascent = 0;
<add> sBoringLayoutMetrics.descent = 0;
<add> sBoringLayoutMetrics.bottom = 0;
<add> sBoringLayoutMetrics.leading = 0;
<add> }
<add>
<add> mBoringLayoutMetrics = metrics;
<add>
<add> float measuredWidth = (float) metrics.width;
<add> if (Float.isNaN(width) || measuredWidth <= width) {
<add> measureOutput.width = measuredWidth;
<add> measureOutput.height = getMetricsHeight(metrics, INCLUDE_PADDING);
<add>
<add> // to indicate that text layout was not created during the measure pass
<add> mDrawCommand = null;
<add>
<add> return;
<add> }
<add>
<add> // width < measuredWidth -> more that a single line -> not boring
<add> }
<add>
<add> int maximumWidth = Float.isNaN(width) ? Integer.MAX_VALUE : (int) width;
<add>
<add> // at this point we need to create a StaticLayout to measure the text
<add> StaticLayout layout = new StaticLayout(
<add> text,
<add> PAINT,
<add> maximumWidth,
<add> Layout.Alignment.ALIGN_NORMAL,
<add> mSpacingMult,
<add> mSpacingAdd,
<add> INCLUDE_PADDING);
<add>
<add> // determine how wide we actually are
<add> float maxLineWidth = 0;
<add> int lineCount = layout.getLineCount();
<add> for (int i = 0; i != lineCount; ++i) {
<add> maxLineWidth = Math.max(maxLineWidth, layout.getLineMax(i));
<add> }
<add>
<add> measureOutput.width = maxLineWidth;
<add> measureOutput.height = layout.getHeight();
<add>
<add> if (mDrawCommand != null && !mDrawCommand.isFrozen()) {
<add> mDrawCommand.setLayout(layout);
<add> } else {
<add> mDrawCommand = new DrawTextLayout(layout);
<add> }
<add> }
<add>
<add> @Override
<add> protected void collectState(
<add> StateBuilder stateBuilder,
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> super.collectState(stateBuilder, left, top, right, bottom);
<add>
<add> if (mText == null) {
<add> // nothing to draw (empty text).
<add> return;
<add> }
<add>
<add> if (mDrawCommand == null) {
<add> // Layout was not created during the measure pass, must be Boring, create it now
<add> mDrawCommand = new DrawTextLayout(new BoringLayout(
<add> mText,
<add> PAINT,
<add> Integer.MAX_VALUE, // fits one line so don't care about the width
<add> Layout.Alignment.ALIGN_NORMAL,
<add> mSpacingMult,
<add> mSpacingAdd,
<add> mBoringLayoutMetrics,
<add> INCLUDE_PADDING));
<add> }
<add>
<add> mDrawCommand = (DrawTextLayout) mDrawCommand.updateBoundsAndFreeze(left, top, right, bottom);
<add> stateBuilder.addDrawCommand(mDrawCommand);
<add> }
<add>
<add> @ReactProp(name = ViewProps.LINE_HEIGHT, defaultDouble = Double.NaN)
<add> public void setLineHeight(double lineHeight) {
<add> if (Double.isNaN(lineHeight)) {
<add> mSpacingMult = 1.0f;
<add> mSpacingAdd = 0.0f;
<add> } else {
<add> mSpacingMult = 0.0f;
<add> mSpacingAdd = PixelUtil.toPixelFromSP((float) lineHeight);
<add> }
<add> notifyChanged(true);
<add> }
<add>
<add> @Override
<add> protected int getDefaultFontSize() {
<add> // top-level <Text /> should always specify font size.
<add> return fontSizeFromSp(ViewDefaults.FONT_SIZE_SP);
<add> }
<add>
<add> @Override
<add> protected void notifyChanged(boolean shouldRemeasure) {
<add> // Future patch: should only recreate Layout if shouldRemeasure is false
<add> dirty();
<add> }
<add>
<add> /**
<add> * Returns a new CharSequence that includes all the text and styling information to create Layout.
<add> */
<add> private CharSequence getText() {
<add> SpannableStringBuilder sb = new SpannableStringBuilder();
<add> collectText(sb);
<add> applySpans(sb);
<add> return sb;
<add> }
<add>
<add> /**
<add> * Returns measured line height according to an includePadding flag.
<add> */
<add> private static int getMetricsHeight(BoringLayout.Metrics metrics, boolean includePadding) {
<add> if (includePadding) {
<add> return metrics.bottom - metrics.top;
<add> } else {
<add> return metrics.descent - metrics.ascent;
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTTextManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * ViewManager that creates instances of RCTText.
<add> */
<add>/* package */ final class RCTTextManager extends VirtualViewManager<RCTText> {
<add>
<add> @Override
<add> public String getName() {
<add> return "RCTText";
<add> }
<add>
<add> @Override
<add> public RCTText createShadowNodeInstance() {
<add> return new RCTText();
<add> }
<add>
<add> @Override
<add> public Class<RCTText> getShadowNodeClass() {
<add> return RCTText.class;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTView.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * Dummy implementation of RCTView.
<add> */
<add>/* package */ final class RCTView extends FlatShadowNode {
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTViewManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * ViewManager that creates instances of RCTView.
<add> */
<add>/* package */ final class RCTViewManager extends VirtualViewManager<RCTView> {
<add>
<add> @Override
<add> public String getName() {
<add> return "RCTView";
<add> }
<add>
<add> @Override
<add> public RCTView createShadowNodeInstance() {
<add> return new RCTView();
<add> }
<add>
<add> @Override
<add> public Class<RCTView> getShadowNodeClass() {
<add> return RCTView.class;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTVirtualText.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import android.graphics.Typeface;
<add>import android.text.Spannable;
<add>import android.text.SpannableStringBuilder;
<add>
<add>import com.facebook.react.uimanager.PixelUtil;
<add>import com.facebook.react.uimanager.ReactProp;
<add>import com.facebook.react.uimanager.ViewProps;
<add>
<add>/**
<add> * RCTVirtualText is a {@link FlatTextShadowNode} that can contain font styling information.
<add> */
<add>/* package */ class RCTVirtualText extends FlatTextShadowNode {
<add>
<add> private static final String BOLD = "bold";
<add> private static final String ITALIC = "italic";
<add> private static final String NORMAL = "normal";
<add>
<add> // TODO: cache CustomStyleSpan and move remove these values from here
<add> // (implemented in a followup patch)
<add> private double mTextColor = Double.NaN;
<add> private int mBgColor;
<add> private int mFontSize = getDefaultFontSize();
<add> private int mFontStyle = -1; // -1, Typeface.NORMAL or Typeface.ITALIC
<add> private int mFontWeight = -1; // -1, Typeface.NORMAL or Typeface.BOLD
<add> private @Nullable String mFontFamily;
<add>
<add> // these 2 are only used between collectText() and applySpans() calls.
<add> private int mTextBegin;
<add> private int mTextEnd;
<add>
<add> @Override
<add> protected void collectText(SpannableStringBuilder builder) {
<add> int childCount = getChildCount();
<add>
<add> mTextBegin = builder.length();
<add> for (int i = 0; i < childCount; ++i) {
<add> FlatTextShadowNode child = (FlatTextShadowNode) getChildAt(i);
<add> child.collectText(builder);
<add> }
<add> mTextEnd = builder.length();
<add> }
<add>
<add> @Override
<add> protected void applySpans(SpannableStringBuilder builder) {
<add> if (mTextBegin == mTextEnd) {
<add> return;
<add> }
<add>
<add> builder.setSpan(
<add> // Future patch: cache last custom style span with a frozen flag
<add> new FontStylingSpan(mTextColor, mBgColor, mFontSize, mFontStyle, mFontWeight, mFontFamily),
<add> mTextBegin,
<add> mTextEnd,
<add> Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
<add>
<add> int childCount = getChildCount();
<add>
<add> for (int i = 0; i < childCount; ++i) {
<add> FlatTextShadowNode child = (FlatTextShadowNode) getChildAt(i);
<add> child.applySpans(builder);
<add> }
<add> }
<add>
<add> @ReactProp(name = ViewProps.FONT_SIZE, defaultFloat = Float.NaN)
<add> public void setFontSize(float fontSizeSp) {
<add> final int fontSize;
<add> if (Float.isNaN(fontSizeSp)) {
<add> fontSize = getDefaultFontSize();
<add> } else {
<add> fontSize = fontSizeFromSp(fontSizeSp);
<add> }
<add>
<add> if (mFontSize != fontSize) {
<add> mFontSize = fontSize;
<add> notifyChanged(true);
<add> }
<add> }
<add>
<add> @ReactProp(name = ViewProps.COLOR, defaultDouble = Double.NaN)
<add> public void setColor(double textColor) {
<add> if (mTextColor != textColor) {
<add> mTextColor = textColor;
<add> notifyChanged(false);
<add> }
<add> }
<add>
<add> @ReactProp(name = ViewProps.BACKGROUND_COLOR)
<add> public void setBackgroundColor(int backgroundColor) {
<add> if (mBgColor != backgroundColor) {
<add> mBgColor = backgroundColor;
<add> notifyChanged(false);
<add> }
<add> }
<add>
<add> @ReactProp(name = ViewProps.FONT_FAMILY)
<add> public void setFontFamily(@Nullable String fontFamily) {
<add> mFontFamily = fontFamily;
<add> notifyChanged(true);
<add> }
<add>
<add> @ReactProp(name = ViewProps.FONT_WEIGHT)
<add> public void setFontWeight(@Nullable String fontWeightString) {
<add> final int fontWeight;
<add> if (fontWeightString == null) {
<add> fontWeight = -1;
<add> } else if (BOLD.equals(fontWeightString)) {
<add> fontWeight = Typeface.BOLD;
<add> } else if (NORMAL.equals(fontWeightString)) {
<add> fontWeight = Typeface.NORMAL;
<add> } else {
<add> int fontWeightNumeric = parseNumericFontWeight(fontWeightString);
<add> if (fontWeightNumeric == -1) {
<add> throw new RuntimeException("invalid font weight " + fontWeightString);
<add> }
<add> fontWeight = fontWeightNumeric >= 500 ? Typeface.BOLD : Typeface.NORMAL;
<add> }
<add>
<add> if (mFontWeight != fontWeight) {
<add> mFontWeight = fontWeight;
<add> notifyChanged(true);
<add> }
<add> }
<add>
<add> @ReactProp(name = ViewProps.FONT_STYLE)
<add> public void setFontStyle(@Nullable String fontStyleString) {
<add> final int fontStyle;
<add> if (fontStyleString == null) {
<add> fontStyle = -1;
<add> } else if (ITALIC.equals(fontStyleString)) {
<add> fontStyle = Typeface.ITALIC;
<add> } else if (NORMAL.equals(fontStyleString)) {
<add> fontStyle = Typeface.NORMAL;
<add> } else {
<add> throw new RuntimeException("invalid font style " + fontStyleString);
<add> }
<add>
<add> if (mFontStyle != fontStyle) {
<add> mFontStyle = fontStyle;
<add> notifyChanged(true);
<add> }
<add> }
<add>
<add> protected int getDefaultFontSize() {
<add> return -1;
<add> }
<add>
<add> /* package */ static int fontSizeFromSp(float sp) {
<add> return (int) Math.ceil(PixelUtil.toPixelFromSP(sp));
<add> }
<add>
<add> /**
<add> * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise
<add> * return the weight.
<add> */
<add> private static int parseNumericFontWeight(String fontWeightString) {
<add> // This should be much faster than using regex to verify input and Integer.parseInt
<add> return fontWeightString.length() == 3 && fontWeightString.endsWith("00")
<add> && fontWeightString.charAt(0) <= '9' && fontWeightString.charAt(0) >= '1' ?
<add> 100 * (fontWeightString.charAt(0) - '0') : -1;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTVirtualTextManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>/**
<add> * ViewManager that creates instances of RCTVirtualText.
<add> */
<add>/* package */ final class RCTVirtualTextManager extends VirtualViewManager<RCTVirtualText> {
<add>
<add> @Override
<add> public String getName() {
<add> return "RCTVirtualText";
<add> }
<add>
<add> @Override
<add> public RCTVirtualText createShadowNodeInstance() {
<add> return new RCTVirtualText();
<add> }
<add>
<add> @Override
<add> public Class<RCTVirtualText> getShadowNodeClass() {
<add> return RCTVirtualText.class;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/StateBuilder.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import java.util.ArrayDeque;
<add>
<add>/**
<add> * Shadow node hierarchy by itself cannot display UI, it is only a representation of what UI should
<add> * be from JavaScript perspective. StateBuilder is a helper class that can walk the shadow node tree
<add> * and collect information that can then be passed to UI thread and applied to a hierarchy of Views
<add> * that Android finally can display.
<add> */
<add>/* package */ final class StateBuilder {
<add>
<add> private final FlatUIViewOperationQueue mOperationsQueue;
<add>
<add> // DrawCommands
<add> private final ArrayDeque<DrawCommand> mDrawCommands = new ArrayDeque<>();
<add> private DrawCommand[] mPreviousDrawCommands = DrawCommand.EMPTY_ARRAY;
<add> private int mPreviousDrawCommandsIndex;
<add>
<add> /* package */ StateBuilder(FlatUIViewOperationQueue operationsQueue) {
<add> mOperationsQueue = operationsQueue;
<add> }
<add>
<add> /**
<add> * Given a root of the laid-out shadow node hierarchy, walks the tree and generates an array of
<add> * DrawCommands that will then mount in UI thread to a root FlatViewGroup so that it can draw.
<add> */
<add> /* package*/ void applyUpdates(FlatRootShadowNode node) {
<add> collectStateAndUpdateViewBounds(node, 0, 0);
<add> }
<add>
<add> /**
<add> * Adds a DrawCommand for current mountable node.
<add> */
<add> /* package */ void addDrawCommand(AbstractDrawCommand drawCommand) {
<add> if (mPreviousDrawCommandsIndex < mPreviousDrawCommands.length &&
<add> mPreviousDrawCommands[mPreviousDrawCommandsIndex] == drawCommand) {
<add> ++mPreviousDrawCommandsIndex;
<add> } else {
<add> mPreviousDrawCommandsIndex = mPreviousDrawCommands.length + 1;
<add> }
<add>
<add> mDrawCommands.addLast(drawCommand);
<add> }
<add>
<add> /**
<add> * Updates boundaries of a View that a give nodes maps to.
<add> */
<add> private void updateViewBounds(
<add> FlatRootShadowNode node,
<add> int tag,
<add> float leftInParent,
<add> float topInParent,
<add> float rightInParent,
<add> float bottomInParent) {
<add> int viewLeft = Math.round(leftInParent);
<add> int viewTop = Math.round(topInParent);
<add> int viewRight = Math.round(rightInParent);
<add> int viewBottom = Math.round(bottomInParent);
<add>
<add> if (node.getViewLeft() == viewLeft && node.getViewTop() == viewTop &&
<add> node.getViewRight() == viewRight && node.getViewBottom() == viewBottom) {
<add> // nothing changed.
<add> return;
<add> }
<add>
<add> // this will optionally measure and layout the View this node maps to.
<add> node.setViewBounds(viewLeft, viewTop, viewRight, viewBottom);
<add> mOperationsQueue.enqueueUpdateViewBounds(tag, viewLeft, viewTop, viewRight, viewBottom);
<add> }
<add>
<add> /**
<add> * Collects state (DrawCommands) for a given node that will mount to a View.
<add> */
<add> private void collectStateForMountableNode(
<add> FlatRootShadowNode node,
<add> int tag,
<add> float width,
<add> float height) {
<add> // save
<add> int d = mDrawCommands.size();
<add> DrawCommand[] previousDrawCommands = mPreviousDrawCommands;
<add> int previousDrawCommandsIndex = mPreviousDrawCommandsIndex;
<add>
<add> // reset
<add> mPreviousDrawCommands = node.getDrawCommands();
<add> mPreviousDrawCommandsIndex = 0;
<add>
<add> collectStateRecursively(node, 0, 0, width, height);
<add>
<add> if (mPreviousDrawCommandsIndex != mPreviousDrawCommands.length) {
<add> // DrawCommands changes, need to re-mount them and re-draw the View.
<add> DrawCommand[] drawCommands = extractDrawCommands(d);
<add> node.setDrawCommands(drawCommands);
<add>
<add> mOperationsQueue.enqueueUpdateMountState(tag, drawCommands);
<add> }
<add>
<add> // restore
<add> mPreviousDrawCommandsIndex = previousDrawCommandsIndex;
<add> mPreviousDrawCommands = previousDrawCommands;
<add> }
<add>
<add> /**
<add> * Returns all DrawCommands collectes so far starting from a given index.
<add> */
<add> private DrawCommand[] extractDrawCommands(int lowerBound) {
<add> int upperBound = mDrawCommands.size();
<add> int size = upperBound - lowerBound;
<add> if (size == 0) {
<add> // avoid allocating empty array
<add> return DrawCommand.EMPTY_ARRAY;
<add> }
<add>
<add> DrawCommand[] drawCommands = new DrawCommand[size];
<add> for (int i = 0; i < size; ++i) {
<add> drawCommands[i] = mDrawCommands.pollFirst();
<add> }
<add>
<add> return drawCommands;
<add> }
<add>
<add> /**
<add> * Recursively walks node tree from a given node and collects DrawCommands.
<add> */
<add> private void collectStateRecursively(
<add> FlatShadowNode node,
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> if (node.hasNewLayout()) {
<add> node.markLayoutSeen();
<add> }
<add>
<add> node.collectState(this, left, top, right, bottom);
<add>
<add> for (int i = 0, childCount = node.getChildCount(); i != childCount; ++i) {
<add> FlatShadowNode child = (FlatShadowNode) node.getChildAt(i);
<add>
<add> float childLeft = left + child.getLayoutX();
<add> float childTop = top + child.getLayoutY();
<add> float childRight = childLeft + child.getLayoutWidth();
<add> float childBottom = childTop + child.getLayoutHeight();
<add> collectStateRecursively(child, childLeft, childTop, childRight, childBottom);
<add> }
<add> }
<add>
<add> /**
<add> * Collects state and updates View boundaries for a given root node.
<add> */
<add> private void collectStateAndUpdateViewBounds(
<add> FlatRootShadowNode node,
<add> float parentLeft,
<add> float parentTop) {
<add> int tag = node.getReactTag();
<add>
<add> float width = node.getLayoutWidth();
<add> float height = node.getLayoutHeight();
<add>
<add> float left = parentLeft + node.getLayoutX();
<add> float top = parentTop + node.getLayoutY();
<add> float right = left + width;
<add> float bottom = top + height;
<add>
<add> collectStateForMountableNode(node, tag, width, height);
<add>
<add> updateViewBounds(node, tag, left, top, right, bottom);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/VirtualViewManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.view.View;
<add>
<add>import com.facebook.react.uimanager.ThemedReactContext;
<add>import com.facebook.react.uimanager.ViewManager;
<add>
<add>/**
<add> * Base class to ViewManagers that don't map to a View.
<add> */
<add>abstract class VirtualViewManager<C extends FlatShadowNode> extends ViewManager<View, C> {
<add> @Override
<add> protected View createViewInstance(ThemedReactContext reactContext) {
<add> throw new RuntimeException(getName() + " doesn't map to a View");
<add> }
<add>
<add> @Override
<add> public void updateExtraData(View root, Object extraData) {
<add> }
<add>} | 21 |
PHP | PHP | fix a couple of failing tests | 64f34b75a23bea07c896a0c1d11d5864f30ffa0c | <ide><path>lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php
<ide> public function testStringConditionsParsing() {
<ide> $expected = " WHERE SUM(`Post`.`comments_count`) > 500";
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
<del> $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
<add> $date = date('Y-m-d H:i');
<add> $result = $this->Dbo->conditions("(Post.created < '" . $date . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
<add> $expected = " WHERE (`Post`.`created` < '" . $date . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->Dbo->conditions("score BETWEEN 90.1 AND 95.7");
<ide> public function testStringConditionsParsing() {
<ide> $expected = " WHERE `Aro`.`rght` = `Aro`.`lft` + 1.1";
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
<del> $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
<add> $date = date('Y-m-d H:i:s');
<add> $result = $this->Dbo->conditions("(Post.created < '" . $date . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
<add> $expected = " WHERE (`Post`.`created` < '" . $date . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->Dbo->conditions('Sportstaette.sportstaette LIKE "%ru%" AND Sportstaette.sportstaettenart_id = 2'); | 1 |
Text | Text | add chinese version of chapter rendertargets | 34771f527b6ac72d6948623a23e2662a6bdb55b9 | <ide><path>threejs/lessons/zh_cn/threejs-rendertargets.md
<add>Title: Three.js 渲染目标
<add>Description: 如何渲染到纹理
<add>TOC: 渲染目标
<add>
<add>在three.js中,渲染目标大体上指的是可以被渲染的纹理。当它被渲染之后,你可以像使用其他纹理一样使用它。
<add>
<add>让我们举个简单的例子。我们将从[the article on responsiveness](threejs-responsive.html)开始。
<add>
<add>渲染到渲染目标基本上跟通常的渲染一样。首先我们创建一个 `WebGLRenderTarget`。
<add>
<add>```js
<add>const rtWidth = 512;
<add>const rtHeight = 512;
<add>const renderTarget = new THREE.WebGLRenderTarget(rtWidth, rtHeight);
<add>```
<add>
<add>然后我们需要一个 `Camera` 和一个 `Scene`
<add>
<add>```js
<add>const rtFov = 75;
<add>const rtAspect = rtWidth / rtHeight;
<add>const rtNear = 0.1;
<add>const rtFar = 5;
<add>const rtCamera = new THREE.PerspectiveCamera(rtFov, rtAspect, rtNear, rtFar);
<add>rtCamera.position.z = 2;
<add>
<add>const rtScene = new THREE.Scene();
<add>rtScene.background = new THREE.Color('red');
<add>```
<add>
<add>注意我们设置长宽比(aspect)是相对渲染目标而言的,不是画布(canvas)。
<add>正确的长宽比取决于我们要渲染的对象。在本例,我们要将渲染目标的纹理用在方块的一个面,基于方块的面我们设置长宽比为1.0。
<add>
<add>我们将需要的东西添加到场景中。在本例我们使用灯光和三个方块[from the previous article](threejs-responsive.html)。
<add>
<add>```js
<add>{
<add> const color = 0xFFFFFF;
<add> const intensity = 1;
<add> const light = new THREE.DirectionalLight(color, intensity);
<add> light.position.set(-1, 2, 4);
<add>* rtScene.add(light);
<add>}
<add>
<add>const boxWidth = 1;
<add>const boxHeight = 1;
<add>const boxDepth = 1;
<add>const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
<add>
<add>function makeInstance(geometry, color, x) {
<add> const material = new THREE.MeshPhongMaterial({color});
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add>* rtScene.add(cube);
<add>
<add> cube.position.x = x;
<add>
<add> return cube;
<add>}
<add>
<add>*const rtCubes = [
<add> makeInstance(geometry, 0x44aa88, 0),
<add> makeInstance(geometry, 0x8844aa, -2),
<add> makeInstance(geometry, 0xaa8844, 2),
<add>];
<add>```
<add>
<add>在上个例子中的 `Scene` 和 `Camera` 保持不变,我们将在画布中继续使用它们,只需要添加渲染的物体。
<add>
<add>让我们添加使用了渲染目标纹理的方块。
<add>
<add>```js
<add>const material = new THREE.MeshPhongMaterial({
<add> map: renderTarget.texture,
<add>});
<add>const cube = new THREE.Mesh(geometry, material);
<add>scene.add(cube);
<add>```
<add>
<add>现在在渲染的时候,我们首先将渲染目标的场景(rtScene),渲染到渲染目标(注:这里有点绕,需要结合代码理解)。
<add>
<add>```js
<add>function render(time) {
<add> time *= 0.001;
<add>
<add> ...
<add>
<add> // rotate all the cubes in the render target scene
<add> rtCubes.forEach((cube, ndx) => {
<add> const speed = 1 + ndx * .1;
<add> const rot = time * speed;
<add> cube.rotation.x = rot;
<add> cube.rotation.y = rot;
<add> });
<add>
<add> // draw render target scene to render target
<add> renderer.setRenderTarget(renderTarget);
<add> renderer.render(rtScene, rtCamera);
<add> renderer.setRenderTarget(null);
<add>```
<add>
<add>然后我们在画布中,渲染使用了渲染目标纹理的方块的场景。
<add>
<add>```js
<add> // rotate the cube in the scene
<add> cube.rotation.x = time;
<add> cube.rotation.y = time * 1.1;
<add>
<add> // render the scene to the canvas
<add> renderer.render(scene, camera);
<add>```
<add>
<add>就是这样啦
<add>
<add>{{{example url="../threejs-render-target.html" }}}
<add>
<add>方块是红色的,这是因为我们设置了 `rtScene` 的 `background` 为红色,所以渲染目标的纹理所处的背景为红色。
<add>
<add>渲染目标可以用在各种各样的物体上。[Shadows](threejs-shadows.html)用了渲染目标,[Picking can use a render target](threejs-picking.html),多种效果[post processing effects](threejs-post-processing.html)需要用到渲染目标。
<add>渲染汽车的后视镜,或者3D场景中的监控实时画面,都可能用到渲染目标。
<add>
<add>关于 `WebGLRenderTarget` 的笔记。
<add>
<add>* 默认情况下 `WebGLRenderTarget` 会创建两个纹理。 颜色纹理和深度/模版纹理。如果你不需要深度或者模版纹理,你可以通过可选设置取消创建。例如:
<add>
<add> ```js
<add> const rt = new THREE.WebGLRenderTarget(width, height, {
<add> depthBuffer: false,
<add> stencilBuffer: false,
<add> });
<add> ```
<add>
<add>* 你可能需要改变渲染目标的尺寸
<add>
<add> 在上面的例子,我们创建了固定尺寸512X512的渲染目标。对于像后处理,你通常需要创建跟画布一样尺寸的渲染目标。在我们的代码中意味着,当我们改变画布的尺寸,会同时更新渲染目标尺寸,和渲染目标中正在使用的摄像机。例如:
<add>
<add> function render(time) {
<add> time *= 0.001;
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add>
<add> + renderTarget.setSize(canvas.width, canvas.height);
<add> + rtCamera.aspect = camera.aspect;
<add> + rtCamera.updateProjectionMatrix();
<add> } | 1 |
Text | Text | add breaking change from 5f3f25a1 | c5b32f14d577384c3a4c01d1af16628cdfacc808 | <ide><path>CHANGELOG.md
<ide> Closes #8803
<ide> Closes #6910
<ide> Closes #5402
<ide>
<add>- **$compile:** due to [5f3f25a1](https://github.com/angular/angular.js/commit/5f3f25a1a6f9d4f2a66e2700df3b9c5606f1c255),
<ide>
<add>The returned value from directive controller constructors are now ignored, and only the constructed
<add>instance itself will be attached to the node's expando. This change is necessary in order to ensure
<add>that it's possible to bind properties to the controller's instance before the actual constructor is
<add>invoked, as a convenience to developers.
<add>
<add>In the past, the following would have worked:
<add>
<add>```js
<add>angular.module("myApp", []).
<add> directive("myDirective", function() {
<add> return {
<add> controller: function($scope) {
<add> return {
<add> doAThing: function() { $scope.thingDone = true; },
<add> undoAThing: function() { $scope.thingDone = false; }
<add> };
<add> },
<add> link: function(scope, element, attrs, ctrl) {
<add> ctrl.doAThing();
<add> }
<add> };
<add> });
<add>```
<add>
<add>However now, the reference to `doAThing()` will be undefined, because the return value of the controller's constructor is ignored. In order to work around this, one can opt for several strategies, including the use of `_.extend()` or `merge()` like routines, like so:
<add>
<add>```js
<add>angular.module("myApp", []).
<add> directive("myDirective", function() {
<add> return {
<add> controller: function($scope) {
<add> _.extend(this, {
<add> doAThing: function() { $scope.thingDone = true; },
<add> undoAThing: function() { $scope.thingDone = false; }
<add> });
<add> },
<add> link: function(scope, element, attrs, ctrl) {
<add> ctrl.doAThing();
<add> }
<add> };
<add> });
<add>```
<ide>
<ide> <a name="1.2.23"></a>
<ide> # 1.2.23 superficial-malady (2014-08-22) | 1 |
Text | Text | fix a typo | 842e19bbeb9a595995770f4dba952483c8e4789a | <ide><path>README.md
<ide> Code is under the [BSD 2 Clause (NetBSD) license](https://github.com/Homebrew/ho
<ide> Documentation is under the [Creative Commons Attribution license](https://creativecommons.org/licenses/by/4.0/).
<ide>
<ide> ## Donations
<del>Homebrew is a non-profit project run entirely by unpaid volunteers. We need your funds to pay for software, hardware and hosting around continous integration and future improvements to the project. Every donation will be spent on making Homebrew better for our users.
<add>Homebrew is a non-profit project run entirely by unpaid volunteers. We need your funds to pay for software, hardware and hosting around continuous integration and future improvements to the project. Every donation will be spent on making Homebrew better for our users.
<ide>
<ide> Homebrew is a member of the [Software Freedom Conservancy](http://sfconservancy.org) which provides us with an ability to receive tax-deductible, Homebrew earmarked donations (and [many other services](http://sfconservancy.org/members/services/)). Software Freedom Conservancy, Inc. is a 501(c)(3) organization incorporated in New York, and donations made to it are fully tax-deductible to the extent permitted by law.
<ide> | 1 |
Javascript | Javascript | remove react.error and react.warn | 8d413bf2c3679befe8c6b56733b7c6f6e467ec07 | <ide><path>packages/react/src/React.js
<ide> import {
<ide> jsxWithValidationDynamic,
<ide> } from './ReactElementValidator';
<ide> import ReactSharedInternals from './ReactSharedInternals';
<del>import {error, warn} from './withComponentStack';
<ide> import createEvent from 'shared/createEventComponent';
<ide> import {enableJSXTransformAPI, enableFlareAPI} from 'shared/ReactFeatureFlags';
<ide> const React = {
<ide> const React = {
<ide> lazy,
<ide> memo,
<ide>
<del> error,
<del> warn,
<del>
<ide> useCallback,
<ide> useContext,
<ide> useEffect,
<ide><path>packages/react/src/__tests__/withComponentStack-test.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @emails react-core
<del> */
<del>
<del>'use strict';
<del>
<del>function normalizeCodeLocInfo(str) {
<del> return str && str.replace(/at .+?:\d+/g, 'at **');
<del>}
<del>
<del>function expectHelper(spy, prefix, ...expectedArgs) {
<del> const expectedStack = expectedArgs.pop();
<del>
<del> expect(spy).toHaveBeenCalledTimes(1);
<del>
<del> const actualArgs = spy.calls.mostRecent().args;
<del>
<del> let actualStack = undefined;
<del> if (expectedStack !== undefined) {
<del> actualStack = actualArgs.pop();
<del> expect(normalizeCodeLocInfo(actualStack)).toBe(expectedStack);
<del> }
<del>
<del> expect(actualArgs).toHaveLength(expectedArgs.length);
<del> actualArgs.forEach((actualArg, index) => {
<del> const expectedArg = expectedArgs[index];
<del> expect(actualArg).toBe(
<del> index === 0 ? `${prefix}: ${expectedArg}` : expectedArg,
<del> );
<del> });
<del>}
<del>
<del>function expectMessageAndStack(...expectedArgs) {
<del> expectHelper(console.error, 'error', ...expectedArgs);
<del> expectHelper(console.warn, 'warn', ...expectedArgs);
<del>}
<del>
<del>describe('withComponentStack', () => {
<del> let React = null;
<del> let ReactTestRenderer = null;
<del> let error = null;
<del> let warn = null;
<del>
<del> beforeEach(() => {
<del> jest.resetModules();
<del>
<del> React = require('react');
<del> ReactTestRenderer = require('react-test-renderer');
<del>
<del> error = React.error;
<del> warn = React.warn;
<del>
<del> spyOnDevAndProd(console, 'error');
<del> spyOnDevAndProd(console, 'warn');
<del> });
<del>
<del> if (!__DEV__) {
<del> it('does nothing in production mode', () => {
<del> error('error');
<del> warn('warning');
<del>
<del> expect(console.error).toHaveBeenCalledTimes(0);
<del> expect(console.warn).toHaveBeenCalledTimes(0);
<del> });
<del> }
<del>
<del> if (__DEV__) {
<del> it('does not include component stack when called outside of render', () => {
<del> error('error: logged outside of render');
<del> warn('warn: logged outside of render');
<del> expectMessageAndStack('logged outside of render', undefined);
<del> });
<del>
<del> it('should support multiple args', () => {
<del> function Component() {
<del> error('error: number:', 123, 'boolean:', true);
<del> warn('warn: number:', 123, 'boolean:', true);
<del> return null;
<del> }
<del>
<del> ReactTestRenderer.create(<Component />);
<del>
<del> expectMessageAndStack(
<del> 'number:',
<del> 123,
<del> 'boolean:',
<del> true,
<del> '\n in Component (at **)',
<del> );
<del> });
<del>
<del> it('includes component stack when called from a render method', () => {
<del> class Parent extends React.Component {
<del> render() {
<del> return <Child />;
<del> }
<del> }
<del>
<del> function Child() {
<del> error('error: logged in child render method');
<del> warn('warn: logged in child render method');
<del> return null;
<del> }
<del>
<del> ReactTestRenderer.create(<Parent />);
<del>
<del> expectMessageAndStack(
<del> 'logged in child render method',
<del> '\n in Child (at **)' + '\n in Parent (at **)',
<del> );
<del> });
<del>
<del> it('includes component stack when called from a render phase lifecycle method', () => {
<del> function Parent() {
<del> return <Child />;
<del> }
<del>
<del> class Child extends React.Component {
<del> UNSAFE_componentWillMount() {
<del> error('error: logged in child cWM lifecycle');
<del> warn('warn: logged in child cWM lifecycle');
<del> }
<del> render() {
<del> return null;
<del> }
<del> }
<del>
<del> ReactTestRenderer.create(<Parent />);
<del>
<del> expectMessageAndStack(
<del> 'logged in child cWM lifecycle',
<del> '\n in Child (at **)' + '\n in Parent (at **)',
<del> );
<del> });
<del>
<del> it('includes component stack when called from a commit phase lifecycle method', () => {
<del> function Parent() {
<del> return <Child />;
<del> }
<del>
<del> class Child extends React.Component {
<del> componentDidMount() {
<del> error('error: logged in child cDM lifecycle');
<del> warn('warn: logged in child cDM lifecycle');
<del> }
<del> render() {
<del> return null;
<del> }
<del> }
<del>
<del> ReactTestRenderer.create(<Parent />);
<del>
<del> expectMessageAndStack(
<del> 'logged in child cDM lifecycle',
<del> '\n in Child (at **)' + '\n in Parent (at **)',
<del> );
<del> });
<del>
<del> it('includes component stack when called from a passive effect handler', () => {
<del> class Parent extends React.Component {
<del> render() {
<del> return <Child />;
<del> }
<del> }
<del>
<del> function Child() {
<del> React.useEffect(() => {
<del> error('error: logged in child render method');
<del> warn('warn: logged in child render method');
<del> });
<del> return null;
<del> }
<del> ReactTestRenderer.act(() => {
<del> ReactTestRenderer.create(<Parent />);
<del> });
<del>
<del> expectMessageAndStack(
<del> 'logged in child render method',
<del> '\n in Child (at **)' + '\n in Parent (at **)',
<del> );
<del> });
<del> }
<del>});
<ide><path>packages/react/src/withComponentStack.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>
<del>function noop() {}
<del>
<del>let error = noop;
<del>let warn = noop;
<del>if (__DEV__) {
<del> const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
<del>
<del> error = function() {
<del> const stack = ReactDebugCurrentFrame.getStackAddendum();
<del> if (stack !== '') {
<del> const length = arguments.length;
<del> const args = new Array(length + 1);
<del> for (let i = 0; i < length; i++) {
<del> args[i] = arguments[i];
<del> }
<del> args[length] = stack;
<del> console.error.apply(console, args);
<del> } else {
<del> console.error.apply(console, arguments);
<del> }
<del> };
<del>
<del> warn = function() {
<del> const stack = ReactDebugCurrentFrame.getStackAddendum();
<del> if (stack !== '') {
<del> const length = arguments.length;
<del> const args = new Array(length + 1);
<del> for (let i = 0; i < length; i++) {
<del> args[i] = arguments[i];
<del> }
<del> args[length] = stack;
<del> console.warn.apply(console, args);
<del> } else {
<del> console.warn.apply(console, arguments);
<del> }
<del> };
<del>}
<del>
<del>export {error, warn}; | 3 |
Python | Python | enable openmp compiler option for msvc | 91b3f1c12ffed962aff185441e61a2c2638a5127 | <ide><path>setup.py
<ide> # which is really known only after finalize_options
<ide> # http://stackoverflow.com/questions/724664/python-distutils-how-to-get-a-compiler-that-is-going-to-be-used
<ide> compile_options = {
<del> 'msvc': ['/Ox', '/EHsc'],
<add> 'msvc': ['/Ox', '/EHsc', '/openmp'],
<ide> 'mingw32' : ['-O3', '-Wno-strict-prototypes', '-Wno-unused-function'],
<ide> 'other' : ['-O3', '-Wno-strict-prototypes', '-Wno-unused-function']
<ide> } | 1 |
Text | Text | add the advisory=rc metadata | daedbc60d61387cb284b871145b672006da1b6de | <ide><path>docs/reference/commandline/node_inspect.md
<ide> title = "node inspect"
<ide> description = "The node inspect command description and usage"
<ide> keywords = ["node, inspect"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/node_ls.md
<ide> title = "node ls"
<ide> description = "The node ls command description and usage"
<ide> keywords = ["node, list"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/node_rm.md
<ide> title = "node rm"
<ide> description = "The node rm command description and usage"
<ide> keywords = ["node, remove"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/node_tasks.md
<ide> title = "node tasks"
<ide> description = "The node tasks command description and usage"
<ide> keywords = ["node, tasks"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/node_update.md
<ide> title = "node update"
<ide> description = "The node update command description and usage"
<ide> keywords = ["resources, update, dynamically"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_create.md
<ide> title = "service create"
<ide> description = "The service create command description and usage"
<ide> keywords = ["service, create"]
<del>
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_inspect.md
<ide> title = "service inspect"
<ide> description = "The service inspect command description and usage"
<ide> keywords = ["service, inspect"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_ls.md
<ide> title = "service ls"
<ide> description = "The service ls command description and usage"
<ide> keywords = ["service, ls"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_rm.md
<ide> title = "service rm"
<ide> description = "The service rm command description and usage"
<ide> keywords = ["service, rm"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_scale.md
<ide> title = "service scale"
<ide> description = "The service scale command description and usage"
<ide> keywords = ["service, scale"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_tasks.md
<ide> title = "service tasks"
<ide> description = "The service tasks command description and usage"
<ide> keywords = ["service, tasks"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/service_update.md
<ide> title = "service update"
<ide> description = "The service update command description and usage"
<ide> keywords = ["service, update"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/swarm_init.md
<ide> title = "swarm init"
<ide> description = "The swarm init command description and usage"
<ide> keywords = ["swarm, init"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/swarm_join.md
<ide> title = "swarm join"
<ide> description = "The swarm join command description and usage"
<ide> keywords = ["swarm, join"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/swarm_leave.md
<ide> title = "swarm leave"
<ide> description = "The swarm leave command description and usage"
<ide> keywords = ["swarm, leave"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++
<ide><path>docs/reference/commandline/swarm_update.md
<ide> title = "swarm update"
<ide> description = "The swarm update command description and usage"
<ide> keywords = ["swarm, update"]
<add>advisory = "rc"
<ide> [menu.main]
<ide> parent = "smn_cli"
<ide> +++ | 16 |
Javascript | Javascript | add dependencies when using loadmodule | b362c227b7a534ed74ee0e2a7432286a5a01d160 | <ide><path>lib/dependencies/LoaderPlugin.js
<ide> LoaderPlugin.prototype.apply = function(compiler) {
<ide> var dep = new LoaderDependency(request);
<ide> compilation.addModuleDependencies(module, [[dep]], true, "lm", false, function(err, module) {
<ide> if(err) return callback(err);
<del>
<add>
<ide> if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
<ide> var map = dep.module._source.map();
<ide> var source = dep.module._source.source();
<add> if(dep.module.fileDependencies) {
<add> dep.module.fileDependencies.forEach(function(dep) {
<add> loaderContext.addDependency(dep);
<add> });
<add> }
<add> if(dep.module.contextDependencies) {
<add> dep.module.contextDependencies.forEach(function(dep) {
<add> loaderContext.addContextDependency(dep);
<add> });
<add> }
<ide> return callback(null, source, map, dep.module);
<ide> });
<ide> }; | 1 |
Python | Python | add broadcasting test | d5622a4176b8780bfaff9d434248bfee57b2c950 | <ide><path>numpy/core/tests/test_einsum.py
<ide> def check_einsum_sums(self, dtype, do_opt=False):
<ide> # singleton dimensions broadcast (gh-10343)
<ide> p = np.ones((10,2))
<ide> q = np.ones((1,2))
<del> assert_array_equal(np.einsum('ti,ti->i', p, q, optimize=True),
<del> np.einsum('ti,ti->i', p, q, optimize=False))
<del> assert_array_equal(np.einsum('ti,ti->i', p, q, optimize=True),
<add> assert_array_equal(np.einsum('ij,ij->j', p, q, optimize=True),
<add> np.einsum('ij,ij->j', p, q, optimize=False))
<add> assert_array_equal(np.einsum('ij,ij->j', p, q, optimize=True),
<ide> [10.] * 2)
<ide>
<add> p = np.ones((1, 5))
<add> q = np.ones((5, 5))
<add> for optimize in (True, False):
<add> assert_array_equal(np.einsum("...ij,...jk->...ik", p, p,
<add> optimize=optimize),
<add> np.einsum("...ij,...jk->...ik", p, q,
<add> optimize=optimize))
<add> assert_array_equal(np.einsum("...ij,...jk->...ik", p, q,
<add> optimize=optimize),
<add> np.full((1, 5), 5))
<add>
<ide> def test_einsum_sums_int8(self):
<ide> self.check_einsum_sums('i1')
<ide> | 1 |
Text | Text | clarify purpose of state property in es6 classes | 60760eb915d699eab0e688effbb4134698f81624 | <ide><path>docs/docs/05-reusable-components.md
<ide> class HelloMessage extends React.Component {
<ide> ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
<ide> ```
<ide>
<del>The API is similar to `React.createClass` with the exception of `getInitialState`. Instead of providing a separate `getInitialState` method, you set up your own `state` property in the constructor.
<add>The API is similar to `React.createClass` with the exception of `getInitialState`. Instead of providing a separate `getInitialState` method, you set up your own `state` property in the constructor. Just like the return value of `getInitialState`, the value you assign to `this.state` will be used as the initial state for your component.
<ide>
<ide> Another difference is that `propTypes` and `defaultProps` are defined as properties on the constructor instead of in the class body.
<ide> | 1 |
Go | Go | fix flaky testupdaterestartpolicy on windows | f43683d60dc6d33c7e5569b24b46d2608a11d865 | <ide><path>integration-cli/docker_cli_update_test.go
<ide> func (s *DockerSuite) TestUpdateRestartPolicy(c *check.C) {
<ide> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "sh", "-c", "sleep 1 && false")
<ide> timeout := 60 * time.Second
<ide> if daemonPlatform == "windows" {
<del> timeout = 150 * time.Second
<add> timeout = 180 * time.Second
<ide> }
<ide>
<ide> id := strings.TrimSpace(string(out)) | 1 |
Javascript | Javascript | dump string values in jsc heap capture | 348a8078bc698f5c22006b94ee283dc5c84e76b0 | <ide><path>local-cli/server/middleware/heapCaptureMiddleware.js
<ide> function getSourceMapForUrl(url, onFailure, onSuccess) {
<ide> return;
<ide> }
<ide>
<add> if (url === 'assets://default_bundle') {
<add> onFailure('Don\'t know how to symbolicate in-app bundle, please load from server');
<add> return;
<add> }
<add>
<ide> const parsedUrl = urlLib.parse(url);
<ide> const options = {
<ide> host: 'localhost', | 1 |
PHP | PHP | fix error in previous commit | 388b20dd9d4555c60aaddafb18f87e50c3d17563 | <ide><path>lib/Cake/Model/Model.php
<ide> public function saveAssociated($data = null, $options = array()) {
<ide> $return = array();
<ide> $validates = true;
<ide> foreach ($data as $association => $values) {
<del> if (isset($associations[$association]) && $associations[$association] === 'belongsTo') {
<add> $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
<add> if (isset($associations[$association]) && $associations[$association] === 'belongsTo' && $notEmpty) {
<ide> $validates = $this->{$association}->create(null) !== null;
<ide> $saved = false;
<ide> if ($validates) {
<ide> public function saveAssociated($data = null, $options = array()) {
<ide> if (!$validates) {
<ide> break;
<ide> }
<del> if (isset($associations[$association])) {
<add> $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
<add> if (isset($associations[$association]) && $notEmpty) {
<ide> $type = $associations[$association];
<ide> $key = $this->{$type}[$association]['foreignKey'];
<ide> switch ($type) {
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveAssociatedHasManyEmpty() {
<ide> $this->loadFixtures('Article', 'Comment');
<ide> $TestModel = new Article();
<ide> $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array();
<add> $TestModel->validate = $TestModel->Comment->validate = array('user_id' => array('notEmpty' => array('rule' => 'notEmpty', 'required' => true)));
<add>
<add> //empty hasMany data is ignored in save
<ide> $result = $TestModel->saveAssociated(array(
<del> 'Article' => array('title' => 'title', 'author_id' => 1),
<add> 'Article' => array('title' => 'title', 'user_id' => 1),
<ide> 'Comment' => array()
<ide> ), array('validate' => true));
<ide> $this->assertTrue($result);
<add>
<add> $result = $TestModel->saveAssociated(array(
<add> 'Article' => array('title' => 'title', 'user_id' => 1),
<add> 'Comment' => array()
<add> ), array('validate' => true, 'atomic' => false));
<add> $this->assertEquals(array('Article' => true), $result);
<add>
<add> //empty primary data is not ignored
<add> $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true));
<add> $this->assertFalse($result);
<add>
<add> $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true, 'atomic' => false));
<add> $this->assertEquals(array('Article' => false), $result);
<add>
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | transform response data on error | 98d489558e6ac0829d9eb8e6ca3a4d6800fd7a7a | <ide><path>lib/core/dispatchRequest.js
<ide> module.exports = function dispatchRequest(config) {
<ide> );
<ide>
<ide> return response;
<add> }, function onRejected(error) {
<add> // Transform response data
<add> if (error && error.response) {
<add> error.response.data = transformData(
<add> error.response.data,
<add> error.response.headers,
<add> config.transformResponse
<add> );
<add> }
<add>
<add> return Promise.reject(error);
<ide> });
<ide> };
<ide><path>test/specs/requests.spec.js
<ide> describe('requests', function () {
<ide> });
<ide> });
<ide>
<add> // https://github.com/mzabriskie/axios/issues/378
<add> it('should return JSON when rejecting', function (done) {
<add> var response;
<add>
<add> axios('/api/account/signup', {
<add> username: null,
<add> password: null
<add> }, {
<add> method: 'post',
<add> headers: {
<add> 'Accept': 'application/json'
<add> }
<add> })
<add> .catch(function (error) {
<add> response = error.response;
<add> });
<add>
<add> getAjaxRequest().then(function (request) {
<add> request.respondWith({
<add> status: 400,
<add> statusText: 'Bad Request',
<add> responseText: '{"error": "BAD USERNAME", "code": 1}'
<add> });
<add>
<add> setTimeout(function () {
<add> expect(typeof response.data).toEqual('object');
<add> // expect(response.data.error).toEqual('BAD USERNAME');
<add> // expect(response.data.code).toEqual(1);
<add> done();
<add> });
<add> });
<add> });
<add>
<ide> it('should make cross domian http request', function (done) {
<ide> var response;
<ide> | 2 |
Python | Python | resolve duplicate error for ipaddressfield. closes | b6c4d8c25a3df5f470943d28d401e24eddcc1df9 | <ide><path>rest_framework/utils/field_mapping.py
<ide> def get_field_kwargs(field_name, model_field):
<ide> if validator is not validators.validate_slug
<ide> ]
<ide>
<add> # IPAddressField do not need to include the 'validate_ipv46_address' argument,
<add> if isinstance(model_field, models.GenericIPAddressField):
<add> validator_kwarg = [
<add> validator for validator in validator_kwarg
<add> if validator is not validators.validate_ipv46_address
<add> ]
<add>
<ide> if getattr(model_field, 'unique', False):
<ide> validator = UniqueValidator(queryset=model_field.model._default_manager)
<ide> validator_kwarg.append(validator) | 1 |
Javascript | Javascript | update imports in ember-routing package tests | 18ad953303c6a73caad687de375499a4f22d8ed2 | <ide><path>packages/ember-routing/tests/location/auto_location_test.js
<del>import { get } from 'ember-metal/property_get';
<del>import run from 'ember-metal/run_loop';
<del>import assign from 'ember-metal/assign';
<del>import AutoLocation from 'ember-routing/location/auto_location';
<add>import { get, run, assign } from 'ember-metal';
<add>import AutoLocation from '../../location/auto_location';
<ide> import {
<ide> getHistoryPath,
<ide> getHashPath
<del>} from 'ember-routing/location/auto_location';
<del>import HistoryLocation from 'ember-routing/location/history_location';
<del>import HashLocation from 'ember-routing/location/hash_location';
<del>import NoneLocation from 'ember-routing/location/none_location';
<add>} from '../../location/auto_location';
<add>import HistoryLocation from '../../location/history_location';
<add>import HashLocation from '../../location/hash_location';
<add>import NoneLocation from '../../location/none_location';
<ide> import { buildOwner } from 'internal-test-helpers';
<ide> import { OWNER } from 'container';
<ide>
<ide><path>packages/ember-routing/tests/location/hash_location_test.js
<del>import { get } from 'ember-metal/property_get';
<del>import run from 'ember-metal/run_loop';
<del>import HashLocation from 'ember-routing/location/hash_location';
<add>import { get, run } from 'ember-metal';
<add>import HashLocation from '../../location/hash_location';
<ide>
<ide> let HashTestLocation, location;
<ide>
<ide><path>packages/ember-routing/tests/location/history_location_test.js
<del>import { set } from 'ember-metal/property_set';
<del>import run from 'ember-metal/run_loop';
<del>import HistoryLocation from 'ember-routing/location/history_location';
<add>import { set, run } from 'ember-metal';
<add>import HistoryLocation from '../../location/history_location';
<ide>
<ide> let FakeHistory, HistoryTestLocation, location;
<ide>
<ide><path>packages/ember-routing/tests/location/none_location_test.js
<del>import { set } from 'ember-metal/property_set';
<del>import run from 'ember-metal/run_loop';
<del>import NoneLocation from 'ember-routing/location/none_location';
<add>import { set, run } from 'ember-metal';
<add>import NoneLocation from '../../location/none_location';
<ide>
<ide> let NoneTestLocation, location;
<ide>
<ide><path>packages/ember-routing/tests/location/util_test.js
<del>import assign from 'ember-metal/assign';
<add>import { assign } from 'ember-metal';
<ide> import {
<ide> replacePath,
<ide> getPath,
<ide> getQuery,
<ide> getFullPath
<del>} from 'ember-routing/location/util';
<add>} from '../../location/util';
<ide> import {
<ide> supportsHistory,
<ide> supportsHashChange
<del>} from 'ember-routing/location/util';
<add>} from '../../location/util';
<ide>
<ide> function mockBrowserLocation(overrides) {
<ide> return assign({
<ide><path>packages/ember-routing/tests/system/controller_for_test.js
<del>import Ember from 'ember-metal/core'; // A
<del>import { get } from 'ember-metal/property_get';
<del>import run from 'ember-metal/run_loop';
<del>import Namespace from 'ember-runtime/system/namespace';
<del>import { classify } from 'ember-runtime/system/string';
<del>import Controller from 'ember-runtime/controllers/controller';
<del>import controllerFor from 'ember-routing/system/controller_for';
<del>import generateController from 'ember-routing/system/generate_controller';
<del>import {
<del> generateControllerFactory
<del>} from 'ember-routing/system/generate_controller';
<add>import { get, run } from 'ember-metal'; // A
<add>import { Namespace, String as StringUtils, Controller } from 'ember-runtime';
<add>import controllerFor from '../../system/controller_for';
<add>import generateController from '../../system/generate_controller';
<ide> import { buildOwner } from 'internal-test-helpers';
<ide>
<ide> function buildInstance(namespace) {
<ide> function resolverFor(namespace) {
<ide> if (name === 'basic') {
<ide> name = '';
<ide> }
<del> let className = classify(name) + classify(type);
<add> let className = StringUtils.classify(name) + StringUtils.classify(type);
<ide> let factory = get(namespace, className);
<ide>
<ide> if (factory) { return factory; }
<ide> QUnit.module('Ember.generateController', {
<ide> }
<ide> });
<ide>
<del>QUnit.test('generateController and generateControllerFactory are properties on the root namespace', function() {
<del> equal(Ember.generateController, generateController, 'should export generateController');
<del> equal(Ember.generateControllerFactory, generateControllerFactory, 'should export generateControllerFactory');
<del>});
<del>
<ide> QUnit.test('generateController should create Ember.Controller', function() {
<ide> let controller = generateController(appInstance, 'home');
<ide>
<ide><path>packages/ember-routing/tests/system/dsl_test.js
<del>import EmberRouter from 'ember-routing/system/router';
<add>import EmberRouter from '../../system/router';
<ide> import { setOwner } from 'container';
<ide> import { buildOwner } from 'internal-test-helpers';
<ide>
<ide><path>packages/ember-routing/tests/system/route_test.js
<del>import { runDestroy } from 'internal-test-helpers';
<del>import Service from 'ember-runtime/system/service';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import EmberRoute from 'ember-routing/system/route';
<del>import inject from 'ember-runtime/inject';
<del>import { buildOwner } from 'internal-test-helpers';
<add>import { runDestroy, buildOwner } from 'internal-test-helpers';
<add>import {
<add> Service,
<add> Object as EmberObject,
<add> inject
<add>} from 'ember-runtime';
<add>import EmberRoute from '../../system/route';
<ide> import { setOwner } from 'container';
<ide>
<ide> let route, routeOne, routeTwo, lookupHash;
<ide><path>packages/ember-routing/tests/system/router_test.js
<del>import HashLocation from 'ember-routing/location/hash_location';
<del>import HistoryLocation from 'ember-routing/location/history_location';
<del>import AutoLocation from 'ember-routing/location/auto_location';
<del>import NoneLocation from 'ember-routing/location/none_location';
<del>import Router, { triggerEvent } from 'ember-routing/system/router';
<add>import HashLocation from '../../location/hash_location';
<add>import HistoryLocation from '../../location/history_location';
<add>import AutoLocation from '../../location/auto_location';
<add>import NoneLocation from '../../location/none_location';
<add>import Router, { triggerEvent } from '../../system/router';
<ide> import { runDestroy, buildOwner } from 'internal-test-helpers';
<ide> import { setOwner } from 'container';
<ide>
<ide><path>packages/ember-routing/tests/utils_test.js
<ide> import {
<ide> normalizeControllerQueryParams
<del>} from 'ember-routing/utils';
<add>} from '../utils';
<ide>
<ide>
<ide> QUnit.module('Routing query parameter utils - normalizeControllerQueryParams'); | 10 |
Text | Text | add global fashion group as an airflow user | c70d8f59c38541f4b02cacca0d57d5368a72ef5c | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [GameWisp](https://gamewisp.com) [[@tjbiii](https://github.com/TJBIII) & [@theryanwalls](https://github.com/theryanwalls)]
<ide> 1. [Gentner Lab](http://github.com/gentnerlab) [[@neuromusic](https://github.com/neuromusic)]
<ide> 1. [Glassdoor](https://github.com/Glassdoor) [[@syvineckruyk](https://github.com/syvineckruyk)]
<add>1. [Global Fashion Group](http://global-fashion-group.com) [[@GFG](https://github.com/GFG)]
<ide> 1. [GovTech GDS](https://gds-gov.tech) [[@chrissng](https://github.com/chrissng) & [@datagovsg](https://github.com/datagovsg)]
<ide> 1. [Grand Rounds](https://www.grandrounds.com/) [[@richddr](https://github.com/richddr), [@timz1290](https://github.com/timz1290), [@wenever](https://github.com/@wenever), & [@runongirlrunon](https://github.com/runongirlrunon)]
<ide> 1. [Groupalia](http://es.groupalia.com) [[@jesusfcr](https://github.com/jesusfcr)] | 1 |
Mixed | Python | add negation ~ operator to permissions composition | 2daf6f13414f1a5d363b5bc4a2ce3ba294a7766c | <ide><path>docs/api-guide/permissions.md
<ide> Provided they inherit from `rest_framework.permissions.BasePermission`, permissi
<ide> }
<ide> return Response(content)
<ide>
<del>__Note:__ it only supports & -and- and | -or-.
<add>__Note:__ it supports & (and), | (or) and ~ (not).
<ide>
<ide> ---
<ide>
<ide><path>rest_framework/permissions.py
<ide> def __rand__(self, other):
<ide> def __ror__(self, other):
<ide> return OperandHolder(OR, other, self)
<ide>
<add> def __invert__(self):
<add> return SingleOperandHolder(NOT, self)
<add>
<add>
<add>class SingleOperandHolder(OperationHolderMixin):
<add> def __init__(self, operator_class, op1_class):
<add> self.operator_class = operator_class
<add> self.op1_class = op1_class
<add>
<add> def __call__(self, *args, **kwargs):
<add> op1 = self.op1_class(*args, **kwargs)
<add> return self.operator_class(op1)
<add>
<ide>
<ide> class OperandHolder(OperationHolderMixin):
<ide> def __init__(self, operator_class, op1_class, op2_class):
<ide> def has_object_permission(self, request, view, obj):
<ide> )
<ide>
<ide>
<add>class NOT:
<add> def __init__(self, op1):
<add> self.op1 = op1
<add>
<add> def has_permission(self, request, view):
<add> return not self.op1.has_permission(request, view)
<add>
<add> def has_object_permission(self, request, view, obj):
<add> return not self.op1.has_object_permission(request, view, obj)
<add>
<add>
<ide> class BasePermissionMetaclass(OperationHolderMixin, type):
<ide> pass
<ide>
<ide><path>tests/test_permissions.py
<ide> def test_or_true(self):
<ide> composed_perm = permissions.IsAuthenticated | permissions.AllowAny
<ide> assert composed_perm().has_permission(request, None) is True
<ide>
<del> def test_several_levels(self):
<add> def test_not_false(self):
<add> request = factory.get('/1', format='json')
<add> request.user = AnonymousUser()
<add> composed_perm = ~permissions.IsAuthenticated
<add> assert composed_perm().has_permission(request, None) is True
<add>
<add> def test_not_true(self):
<add> request = factory.get('/1', format='json')
<add> request.user = self.user
<add> composed_perm = ~permissions.AllowAny
<add> assert composed_perm().has_permission(request, None) is False
<add>
<add> def test_several_levels_without_negation(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = self.user
<ide> composed_perm = (
<ide> def test_several_levels(self):
<ide> )
<ide> assert composed_perm().has_permission(request, None) is True
<ide>
<add> def test_several_levels_and_precedence_with_negation(self):
<add> request = factory.get('/1', format='json')
<add> request.user = self.user
<add> composed_perm = (
<add> permissions.IsAuthenticated &
<add> ~ permissions.IsAdminUser &
<add> permissions.IsAuthenticated &
<add> ~(permissions.IsAdminUser & permissions.IsAdminUser)
<add> )
<add> assert composed_perm().has_permission(request, None) is True
<add>
<ide> def test_several_levels_and_precedence(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = self.user | 3 |
Text | Text | add opensignal to inthewild.md | 04b8adf69deac5e91a4ffa1fa2be9c0c1431f386 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [OneFineStay](https://www.onefinestay.com) [[@slangwald](https://github.com/slangwald)]
<ide> 1. [Open Knowledge International](https://okfn.org) [@vitorbaptista](https://github.com/vitorbaptista)
<ide> 1. [OpenSlate](https://openslate.com) [@marcusianlevine](https://github.com/marcusianlevine)
<add>1. [Opensignal](https://www.opensignal.com) [@harrisjoseph](https://github.com/harrisjoseph)
<ide> 1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@fhoda](https://github.com/fhoda), [@ianstanton](https://github.com/ianstanton), [@nilaybhatt](https://github.com/NilayBhatt),[@hiteshrd](https://github.com/hiteshrd)]
<ide> 1. [OrangeBank](https://www.orangebank.fr/) [[@HamzaBoukraa](https://github.com/HamzaBoukraa)]
<ide> 1. [Outcome Health](https://www.outcomehealth.com/) [[@mikethoun](https://github.com/mikethoun), [@rolandotribo](https://github.com/rolandotribo)] | 1 |
Javascript | Javascript | avoid double calls to $templatecache.put | 8c3a42cd684245b08054d9c987db80a399837954 | <ide><path>src/ng/templateRequest.js
<ide> function $TemplateRequestProvider() {
<ide>
<ide> return $http.get(tpl, httpOptions)
<ide> .then(function(response) {
<del> var html = response.data;
<ide> self.totalPendingRequests--;
<del> $templateCache.put(tpl, html);
<del> return html;
<add> return response.data;
<ide> }, handleError);
<ide>
<ide> function handleError(resp) {
<ide><path>test/ng/templateRequestSpec.js
<ide> describe('$templateRequest', function() {
<ide> expect(content).toBe('<div>abc</div>');
<ide> }));
<ide>
<del> it('should cache the request using $templateCache to prevent extra downloads',
<del> inject(function($rootScope, $templateRequest, $templateCache) {
<add> it('should cache the request to prevent extra downloads',
<add> inject(function($rootScope, $templateRequest, $httpBackend) {
<ide>
<del> $templateCache.put('tpl.html', 'matias');
<add> $httpBackend.expectGET('tpl.html').respond('matias');
<ide>
<del> var content;
<del> $templateRequest('tpl.html').then(function(html) { content = html; });
<add> var content = [];
<add> function tplRequestCb(html) {
<add> content.push(html);
<add> }
<ide>
<add> $templateRequest('tpl.html').then(tplRequestCb);
<add> $httpBackend.flush();
<add>
<add> $templateRequest('tpl.html').then(tplRequestCb);
<ide> $rootScope.$digest();
<del> expect(content).toBe('matias');
<add>
<add> expect(content[0]).toBe('matias');
<add> expect(content[1]).toBe('matias');
<ide> }));
<ide>
<ide> it('should throw an error when the template is not found', | 2 |
Java | Java | improve determinism of groupby.testunsubscribe | 1cc2f6aebaa6138cca414c5b10a41f8dc974b010 | <ide><path>rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
<ide> public void onNext(String outputMessage) {
<ide> // sentEvents will go until 'eventCounter' hits 20 and then unsubscribes
<ide> // which means it will also send (but ignore) the 19/20 events for the other group
<ide> // It will not however send all 100 events.
<del> assertEquals(39, sentEventCounter.get(), 2);
<del> // gave it a delta of 2 so the threading/unsubscription race has wiggle
<add> assertEquals(39, sentEventCounter.get(), 10);
<add> // gave it a delta of 10 to account for the threading/unsubscription race condition which can vary depending on a machines performance, thread-scheduler, etc
<ide> }
<ide>
<ide> private static class Event { | 1 |
Java | Java | use the reactor netty websocketserverspec | 0520ee0fb62464687b74e7ad3bc234c30baa3732 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/ReactorNettyRequestUpgradeStrategy.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.netty.http.server.HttpServerResponse;
<add>import reactor.netty.http.server.WebsocketServerSpec;
<ide>
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.http.server.reactive.AbstractServerHttpResponse;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<del>import org.springframework.web.reactive.socket.adapter.NettyWebSocketSessionSupport;
<ide> import org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> */
<ide> public class ReactorNettyRequestUpgradeStrategy implements RequestUpgradeStrategy {
<ide>
<del> private int maxFramePayloadLength = NettyWebSocketSessionSupport.DEFAULT_FRAME_MAX_SIZE;
<add> private final Supplier<WebsocketServerSpec.Builder> specBuilderSupplier;
<ide>
<del> private boolean handlePing = false;
<add> @Nullable
<add> private Integer maxFramePayloadLength;
<ide>
<add> @Nullable
<add> private Boolean handlePing;
<add>
<add>
<add> /**
<add> * Create an instances with a default {@link WebsocketServerSpec.Builder}.
<add> * @since 5.2.6
<add> */
<add> public ReactorNettyRequestUpgradeStrategy() {
<add> this(WebsocketServerSpec.builder());
<add> }
<add>
<add>
<add> /**
<add> * Create an instance with a pre-configured {@link WebsocketServerSpec.Builder}
<add> * to use for WebSocket upgrades.
<add> * @since 5.2.6
<add> */
<add> public ReactorNettyRequestUpgradeStrategy(Supplier<WebsocketServerSpec.Builder> builderSupplier) {
<add> Assert.notNull(builderSupplier, "WebsocketServerSpec.Builder is required");
<add> this.specBuilderSupplier = builderSupplier;
<add> }
<add>
<add>
<add> /**
<add> * Build an instance of {@code WebsocketServerSpec} that reflects the current
<add> * configuration. This can be used to check the configured parameters except
<add> * for sub-protocols which depend on the {@link WebSocketHandler} that is used
<add> * for a given upgrade.
<add> * @since 5.2.6
<add> */
<add> public WebsocketServerSpec getWebsocketServerSpec() {
<add> return buildSpec(null);
<add> }
<add>
<add> private WebsocketServerSpec buildSpec(@Nullable String subProtocol) {
<add> WebsocketServerSpec.Builder builder = this.specBuilderSupplier.get();
<add> if (subProtocol != null) {
<add> builder.protocols(subProtocol);
<add> }
<add> if (this.maxFramePayloadLength != null) {
<add> builder.maxFramePayloadLength(this.maxFramePayloadLength);
<add> }
<add> if (this.handlePing != null) {
<add> builder.handlePing(this.handlePing);
<add> }
<add> return builder.build();
<add> }
<ide>
<ide> /**
<ide> * Configure the maximum allowable frame payload length. Setting this value
<ide> public class ReactorNettyRequestUpgradeStrategy implements RequestUpgradeStrateg
<ide> * <p>By default set to 65536 (64K).
<ide> * @param maxFramePayloadLength the max length for frames.
<ide> * @since 5.1
<add> * @deprecated as of 5.2.6 in favor of providing a supplier of
<add> * {@link WebsocketServerSpec.Builder} wiht a constructor argument.
<ide> */
<add> @Deprecated
<ide> public void setMaxFramePayloadLength(Integer maxFramePayloadLength) {
<ide> this.maxFramePayloadLength = maxFramePayloadLength;
<ide> }
<ide>
<ide> /**
<ide> * Return the configured max length for frames.
<ide> * @since 5.1
<add> * @deprecated as of 5.2.6 in favor of {@link #getWebsocketServerSpec()}
<ide> */
<add> @Deprecated
<ide> public int getMaxFramePayloadLength() {
<del> return this.maxFramePayloadLength;
<add> return getWebsocketServerSpec().maxFramePayloadLength();
<ide> }
<ide>
<ide> /**
<ide> public int getMaxFramePayloadLength() {
<ide> * frames will be passed through to the {@link WebSocketHandler}.
<ide> * @param handlePing whether to let Ping frames through for handling
<ide> * @since 5.2.4
<add> * @deprecated as of 5.2.6 in favor of providing a supplier of
<add> * {@link WebsocketServerSpec.Builder} wiht a constructor argument.
<ide> */
<add> @Deprecated
<ide> public void setHandlePing(boolean handlePing) {
<ide> this.handlePing = handlePing;
<ide> }
<ide>
<ide> /**
<ide> * Return the configured {@link #setHandlePing(boolean)}.
<ide> * @since 5.2.4
<add> * @deprecated as of 5.2.6 in favor of {@link #getWebsocketServerSpec()}
<ide> */
<add> @Deprecated
<ide> public boolean getHandlePing() {
<del> return this.handlePing;
<add> return getWebsocketServerSpec().handlePing();
<ide> }
<ide>
<ide>
<ide> @Override
<del> @SuppressWarnings("deprecation")
<ide> public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
<ide> @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
<ide>
<ide> ServerHttpResponse response = exchange.getResponse();
<ide> HttpServerResponse reactorResponse = getNativeResponse(response);
<ide> HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
<ide> NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory();
<add> URI uri = exchange.getRequest().getURI();
<ide>
<ide> // Trigger WebFlux preCommit actions and upgrade
<ide> return response.setComplete()
<del> .then(Mono.defer(() -> reactorResponse.sendWebsocket(
<del> subProtocol,
<del> this.maxFramePayloadLength,
<del> this.handlePing,
<del> (in, out) -> {
<del> ReactorNettyWebSocketSession session =
<del> new ReactorNettyWebSocketSession(
<del> in, out, handshakeInfo, bufferFactory, this.maxFramePayloadLength);
<del> URI uri = exchange.getRequest().getURI();
<del> return handler.handle(session).checkpoint(uri + " [ReactorNettyRequestUpgradeStrategy]");
<del> })));
<add> .then(Mono.defer(() -> {
<add> WebsocketServerSpec spec = buildSpec(subProtocol);
<add> return reactorResponse.sendWebsocket((in, out) -> {
<add> ReactorNettyWebSocketSession session =
<add> new ReactorNettyWebSocketSession(
<add> in, out, handshakeInfo, bufferFactory, spec.maxFramePayloadLength());
<add> return handler.handle(session).checkpoint(uri + " [ReactorNettyRequestUpgradeStrategy]");
<add> }, spec);
<add> }));
<ide> }
<ide>
<ide> private static HttpServerResponse getNativeResponse(ServerHttpResponse response) { | 1 |
Python | Python | improve type hinting for celery provider | 5bb228d841585cd1780c15f6175c6d64cd98aeab | <ide><path>airflow/providers/celery/sensors/celery_queue.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<add>from typing import Any, Dict, Optional
<add>
<ide> from celery.app import control
<ide>
<ide> from airflow.sensors.base_sensor_operator import BaseSensorOperator
<ide> class CeleryQueueSensor(BaseSensorOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self,
<del> celery_queue,
<del> target_task_id=None,
<add> celery_queue: str,
<add> target_task_id: Optional[str] = None,
<ide> *args,
<del> **kwargs):
<add> **kwargs) -> None:
<ide>
<ide> super().__init__(*args, **kwargs)
<ide> self.celery_queue = celery_queue
<ide> self.target_task_id = target_task_id
<ide>
<del> def _check_task_id(self, context):
<add> def _check_task_id(self, context: Dict[str, Any]) -> bool:
<ide> """
<ide> Gets the returned Celery result from the Airflow task
<ide> ID provided to the sensor, and returns True if the
<ide> def _check_task_id(self, context):
<ide> celery_result = ti.xcom_pull(task_ids=self.target_task_id)
<ide> return celery_result.ready()
<ide>
<del> def poke(self, context):
<add> def poke(self, context: Dict[str, Any]) -> bool:
<ide>
<ide> if self.target_task_id:
<ide> return self._check_task_id(context) | 1 |
Javascript | Javascript | add _allkeys descriptor for object.keys behavior | 78d3d30d5684b26773bb2c46b8a972908e110cf3 | <ide><path>src/core/core.config.js
<ide> export default class Config {
<ide> * @param {object[]} scopes
<ide> * @param {object} [context]
<ide> * @param {string[]} [prefixes]
<del> * @param {{scriptable: boolean, indexable: boolean}} [descriptorDefaults]
<add> * @param {{scriptable: boolean, indexable: boolean, allKeys?: boolean}} [descriptorDefaults]
<ide> */
<ide> createResolver(scopes, context, prefixes = [''], descriptorDefaults) {
<ide> const {resolver} = getResolver(this._resolverCache, scopes, prefixes);
<ide><path>src/core/core.plugins.js
<ide> function createDescriptors(chart, plugins, options, all) {
<ide> function pluginOpts(config, plugin, opts, context) {
<ide> const keys = config.pluginScopeKeys(plugin);
<ide> const scopes = config.getOptionScopes(opts, keys);
<del> return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false});
<add> return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});
<ide> }
<ide><path>src/helpers/helpers.config.js
<ide> export function _createResolver(scopes, prefixes = [''], rootScopes = scopes, fa
<ide> * @param {object} proxy - The Proxy returned by `_createResolver`
<ide> * @param {object} context - Context object for scriptable/indexable options
<ide> * @param {object} [subProxy] - The proxy provided for scriptable options
<del> * @param {{scriptable: boolean, indexable: boolean}} [descriptorDefaults] - Defaults for descriptors
<add> * @param {{scriptable: boolean, indexable: boolean, allKeys?: boolean}} [descriptorDefaults] - Defaults for descriptors
<ide> * @private
<ide> */
<ide> export function _attachContext(proxy, context, subProxy, descriptorDefaults) {
<ide> export function _attachContext(proxy, context, subProxy, descriptorDefaults) {
<ide> * Also used by Object.hasOwnProperty.
<ide> */
<ide> getOwnPropertyDescriptor(target, prop) {
<del> return Reflect.getOwnPropertyDescriptor(proxy, prop);
<add> return target._descriptors.allKeys
<add> ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined
<add> : Reflect.getOwnPropertyDescriptor(proxy, prop);
<ide> },
<ide>
<ide> /**
<ide> export function _attachContext(proxy, context, subProxy, descriptorDefaults) {
<ide> * @private
<ide> */
<ide> export function _descriptors(proxy, defaults = {scriptable: true, indexable: true}) {
<del> const {_scriptable = defaults.scriptable, _indexable = defaults.indexable} = proxy;
<add> const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;
<ide> return {
<add> allKeys: _allKeys,
<ide> scriptable: _scriptable,
<ide> indexable: _indexable,
<ide> isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,
<ide><path>test/specs/core.plugin.tests.js
<ide> describe('Chart.plugins', function() {
<ide> chart.notifyPlugins('hook');
<ide>
<ide> expect(plugin.hook).toHaveBeenCalled();
<del> expect(plugin.hook.calls.first().args[2]).toEqualOptions({a: 42});
<add> expect(Object.keys(plugin.hook.calls.first().args[2])).toEqual(['a']);
<add> expect(plugin.hook.calls.first().args[2]).toEqual(jasmine.objectContaining({a: 42}));
<ide>
<ide> Chart.unregister(plugin);
<ide> }); | 4 |
Python | Python | make zeropadding2d optionally asymmetric | 169c0896d6b7a9109b4fc462d24674e9b350a5e5 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def temporal_padding(x, padding=1):
<ide> return tf.pad(x, pattern)
<ide>
<ide>
<add>def asymmetric_temporal_padding(x, left_pad=1, right_pad=1):
<add> '''Pad the middle dimension of a 3D tensor
<add> with "left_pad" zeros left and "right_pad" right.
<add> '''
<add> pattern = [[0, 0], [left_pad, right_pad], [0, 0]]
<add> return tf.pad(x, pattern)
<add>
<add>
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pads the 2nd and 3rd dimensions of a 4D tensor
<ide> with "padding[0]" and "padding[1]" (resp.) zeros left and right.
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> return tf.pad(x, pattern)
<ide>
<ide>
<add>def asymmetric_spatial_2d_padding(x, top_pad=1, bottom_pad=1, left_pad=1, right_pad=1, dim_ordering=_IMAGE_DIM_ORDERING):
<add> '''Pad the rows and columns of a 4D tensor
<add> with "top_pad", "bottom_pad", "left_pad", "right_pad" (resp.) zeros rows on top, bottom; cols on left, right.
<add> '''
<add> if dim_ordering == 'th':
<add> pattern = [[0, 0],
<add> [0, 0],
<add> [top_pad, bottom_pad],
<add> [left_pad, right_pad]]
<add> else:
<add> pattern = [[0, 0],
<add> [top_pad, bottom_pad],
<add> [left_pad, right_pad],
<add> [0, 0]]
<add> return tf.pad(x, pattern)
<add>
<add>
<ide> def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pads 5D tensor with zeros for the depth, height, width dimension with
<ide> "padding[0]", "padding[1]" and "padding[2]" (resp.) zeros left and right
<ide><path>keras/backend/theano_backend.py
<ide> def temporal_padding(x, padding=1):
<ide> return T.set_subtensor(output[:, padding:x.shape[1] + padding, :], x)
<ide>
<ide>
<add>def asymmetric_temporal_padding(x, left_pad=1, right_pad=1):
<add> '''Pad the middle dimension of a 3D tensor
<add> with "left_pad" zeros left and "right_pad" right.
<add>
<add> Apologies for the inane API, but Theano makes this
<add> really hard.
<add> '''
<add> input_shape = x.shape
<add> output_shape = (input_shape[0],
<add> input_shape[1] + left_pad + right_pad,
<add> input_shape[2])
<add> output = T.zeros(output_shape)
<add> return T.set_subtensor(output[:, left_pad:x.shape[1] + left_pad, :], x)
<add>
<add>
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pad the 2nd and 3rd dimensions of a 4D tensor
<ide> with "padding[0]" and "padding[1]" (resp.) zeros left and right.
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> return T.set_subtensor(output[indices], x)
<ide>
<ide>
<add>def asymmetric_spatial_2d_padding(x, top_pad=1, bottom_pad=1, left_pad=1, right_pad=1, dim_ordering=_IMAGE_DIM_ORDERING):
<add> '''Pad the rows and columns of a 4D tensor
<add> with "top_pad", "bottom_pad", "left_pad", "right_pad" (resp.) zeros rows on top, bottom; cols on left, right.
<add> '''
<add> input_shape = x.shape
<add> if dim_ordering == 'th':
<add> output_shape = (input_shape[0],
<add> input_shape[1],
<add> input_shape[2] + top_pad + bottom_pad,
<add> input_shape[3] + left_pad + right_pad)
<add> output = T.zeros(output_shape)
<add> indices = (slice(None),
<add> slice(None),
<add> slice(top_pad, input_shape[2] + top_pad),
<add> slice(left_pad, input_shape[3] + left_pad))
<add>
<add> elif dim_ordering == 'tf':
<add> output_shape = (input_shape[0],
<add> input_shape[1] + top_pad + bottom_pad,
<add> input_shape[2] + left_pad + right_pad,
<add> input_shape[3])
<add> print(output_shape)
<add> output = T.zeros(output_shape)
<add> indices = (slice(None),
<add> slice(top_pad, input_shape[1] + top_pad),
<add> slice(left_pad, input_shape[2] + left_pad),
<add> slice(None))
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> return T.set_subtensor(output[indices], x)
<add>
<add>
<ide> def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pad the 2nd, 3rd and 4th dimensions of a 5D tensor
<ide> with "padding[0]", "padding[1]" and "padding[2]" (resp.) zeros left and right.
<ide><path>keras/layers/convolutional.py
<ide> class ZeroPadding1D(Layer):
<ide> '''Zero-padding layer for 1D input (e.g. temporal sequence).
<ide>
<ide> # Arguments
<del> padding: int
<add> padding: int or tuple of int (length 2) or dictionary
<add> For symmetric padding: int
<ide> How many zeros to add at the beginning and end of
<ide> the padding dimension (axis 1).
<add> For asymmetric padding: tuple of int (length 2)
<add> How many zeros to add at the beginning and at the end of
<add> the padding dimension '(left_pad, right_pad)' or
<add> '{'left_pad': left_pad, 'right_pad': right_pad}'.
<add> If any key is missing, default value of 0 will be used for the missing key.
<ide>
<ide> # Input shape
<ide> 3D tensor with shape (samples, axis_to_pad, features)
<ide> class ZeroPadding1D(Layer):
<ide> def __init__(self, padding=1, **kwargs):
<ide> super(ZeroPadding1D, self).__init__(**kwargs)
<ide> self.padding = padding
<add>
<add> if isinstance(padding, int):
<add> self.left_pad = padding
<add> self.right_pad = padding
<add> elif isinstance(padding, dict):
<add> if set(padding.keys()) <= {'left_pad', 'right_pad'}:
<add> self.left_pad = padding.get('left_pad', 0)
<add> self.right_pad = padding.get('right_pad', 0)
<add> else:
<add> raise ValueError('Unexpected key is found in the padding argument. '
<add> 'Keys have to be in {"left_pad", "right_pad"}')
<add> else:
<add> padding = tuple(padding)
<add> self.left_pad = padding[0]
<add> self.right_pad = padding[1]
<ide> self.input_spec = [InputSpec(ndim=3)]
<ide>
<ide> def get_output_shape_for(self, input_shape):
<del> length = input_shape[1] + self.padding * 2 if input_shape[1] is not None else None
<add> length = input_shape[1] + self.left_pad + self.right_pad if input_shape[1] is not None else None
<ide> return (input_shape[0],
<ide> length,
<ide> input_shape[2])
<ide>
<ide> def call(self, x, mask=None):
<del> return K.temporal_padding(x, padding=self.padding)
<add> return K.asymmetric_temporal_padding(x, left_pad=self.left_pad, right_pad=self.right_pad)
<ide>
<ide> def get_config(self):
<ide> config = {'padding': self.padding}
<ide> class ZeroPadding2D(Layer):
<ide> '''Zero-padding layer for 2D input (e.g. picture).
<ide>
<ide> # Arguments
<del> padding: tuple of int (length 2)
<add> padding: tuple of int (length 2) or tuple of int (length 4) or dictionary
<add> For symmetric padding tuple of int (length 2)
<ide> How many zeros to add at the beginning and end of
<del> the 2 padding dimensions (axis 3 and 4).
<add> the 2 padding dimensions (rows and cols).
<add> For asymmetric padding tuple of int (length 4)
<add> How many zeros to add at the beginning and at the end of
<add> the 2 padding dimensions (rows and cols).
<add> '(top_pad, bottom_pad, left_pad, right_pad)' or
<add> '{'top_pad': top_pad, 'bottom_pad': bottom_pad, 'left_pad': left_pad, 'right_pad': right_pad}'
<add> If any key is missing, default value of 0 will be used for the missing key.
<ide> dim_ordering: 'th' or 'tf'.
<ide> In 'th' mode, the channels dimension (the depth)
<ide> is at index 1, in 'tf' mode is it at index 3.
<ide> class ZeroPadding2D(Layer):
<ide>
<ide> # Input shape
<ide> 4D tensor with shape:
<del> (samples, depth, first_axis_to_pad, second_axis_to_pad)
<add> `(samples, channels, rows, cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, rows, cols, channels)` if dim_ordering='tf'.
<ide>
<ide> # Output shape
<ide> 4D tensor with shape:
<del> (samples, depth, first_padded_axis, second_padded_axis)
<add> `(samples, channels, padded_rows, padded_cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, padded_rows, padded_cols, channels)` if dim_ordering='tf'.
<ide> '''
<ide>
<del> def __init__(self, padding=(1, 1), dim_ordering='default', **kwargs):
<add> def __init__(self,
<add> padding=(1, 1),
<add> dim_ordering='default',
<add> **kwargs):
<ide> super(ZeroPadding2D, self).__init__(**kwargs)
<ide> if dim_ordering == 'default':
<ide> dim_ordering = K.image_dim_ordering()
<del> self.padding = tuple(padding)
<add>
<add> self.padding = padding
<add> try:
<add> if set(padding.keys()) <= {'top_pad', 'bottom_pad', 'left_pad', 'right_pad'}:
<add> self.top_pad = padding.get('top_pad', 0)
<add> self.bottom_pad = padding.get('bottom_pad', 0)
<add> self.left_pad = padding.get('left_pad', 0)
<add> self.right_pad = padding.get('right_pad', 0)
<add> else:
<add> raise ValueError('Unexpected key is found in the padding argument. '
<add> 'Keys have to be in {"top_pad", "bottom_pad", "left_pad", "right_pad"}')
<add> except AttributeError:
<add> padding = tuple(padding)
<add> if len(padding) == 2:
<add> self.top_pad = padding[0]
<add> self.bottom_pad = padding[0]
<add> self.left_pad = padding[1]
<add> self.right_pad = padding[1]
<add> elif len(padding) == 4:
<add> self.top_pad = padding[0]
<add> self.bottom_pad = padding[1]
<add> self.left_pad = padding[2]
<add> self.right_pad = padding[3]
<add> else:
<add> raise TypeError('padding should be tuple of int of length 2 or 4, or dict')
<add>
<ide> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
<ide> self.dim_ordering = dim_ordering
<ide> self.input_spec = [InputSpec(ndim=4)]
<ide>
<ide> def get_output_shape_for(self, input_shape):
<ide> if self.dim_ordering == 'th':
<del> width = input_shape[2] + 2 * self.padding[0] if input_shape[2] is not None else None
<del> height = input_shape[3] + 2 * self.padding[1] if input_shape[3] is not None else None
<add> rows = input_shape[2] + self.top_pad + self.bottom_pad if input_shape[2] is not None else None
<add> cols = input_shape[3] + self.left_pad + self.right_pad if input_shape[3] is not None else None
<ide> return (input_shape[0],
<ide> input_shape[1],
<del> width,
<del> height)
<add> rows,
<add> cols)
<ide> elif self.dim_ordering == 'tf':
<del> width = input_shape[1] + 2 * self.padding[0] if input_shape[1] is not None else None
<del> height = input_shape[2] + 2 * self.padding[1] if input_shape[2] is not None else None
<add> rows = input_shape[1] + self.top_pad + self.bottom_pad if input_shape[1] is not None else None
<add> cols = input_shape[2] + self.left_pad + self.right_pad if input_shape[2] is not None else None
<ide> return (input_shape[0],
<del> width,
<del> height,
<add> rows,
<add> cols,
<ide> input_shape[3])
<ide> else:
<ide> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<ide>
<ide> def call(self, x, mask=None):
<del> return K.spatial_2d_padding(x, padding=self.padding,
<del> dim_ordering=self.dim_ordering)
<add> return K.asymmetric_spatial_2d_padding(x,
<add> top_pad=self.top_pad,
<add> bottom_pad=self.bottom_pad,
<add> left_pad=self.left_pad,
<add> right_pad=self.right_pad,
<add> dim_ordering=self.dim_ordering)
<ide>
<ide> def get_config(self):
<ide> config = {'padding': self.padding}
<ide><path>tests/keras/layers/test_convolutional.py
<ide> def test_averagepooling_3d():
<ide> input_shape=(3, 4, 11, 12, 10))
<ide>
<ide>
<add>@keras_test
<add>def test_zero_padding_1d():
<add> nb_samples = 2
<add> input_dim = 2
<add> nb_steps = 11
<add> input = np.ones((nb_samples, nb_steps, input_dim))
<add>
<add> # basic test
<add> layer_test(convolutional.ZeroPadding1D,
<add> kwargs={'padding': 2},
<add> input_shape=input.shape)
<add> layer_test(convolutional.ZeroPadding1D,
<add> kwargs={'padding': (1, 2)},
<add> input_shape=input.shape)
<add> layer_test(convolutional.ZeroPadding1D,
<add> kwargs={'padding': {'left_pad': 1, 'right_pad': 2}},
<add> input_shape=input.shape)
<add>
<add> # correctness test
<add> layer = convolutional.ZeroPadding1D(padding=2)
<add> layer.set_input(K.variable(input), shape=input.shape)
<add>
<add> out = K.eval(layer.output)
<add> for offset in [0, 1, -1, -2]:
<add> assert_allclose(out[:, offset, :], 0.)
<add> assert_allclose(out[:, 2:-2, :], 1.)
<add>
<add> layer = convolutional.ZeroPadding1D(padding=(1, 2))
<add> layer.set_input(K.variable(input), shape=input.shape)
<add>
<add> out = K.eval(layer.output)
<add> for left_offset in [0]:
<add> assert_allclose(out[:, left_offset, :], 0.)
<add> for right_offset in [-1, -2]:
<add> assert_allclose(out[:, right_offset, :], 0.)
<add> assert_allclose(out[:, 1:-2, :], 1.)
<add> layer.get_config()
<add>
<add>
<ide> @keras_test
<ide> def test_zero_padding_2d():
<ide> nb_samples = 2
<ide> stack_size = 2
<ide> input_nb_row = 11
<ide> input_nb_col = 12
<add> dim_ordering = K.image_dim_ordering()
<add> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
<ide>
<del> input = np.ones((nb_samples, input_nb_row, input_nb_col, stack_size))
<add> if dim_ordering == 'tf':
<add> input = np.ones((nb_samples, input_nb_row, input_nb_col, stack_size))
<add> elif dim_ordering == 'th':
<add> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<ide>
<ide> # basic test
<ide> layer_test(convolutional.ZeroPadding2D,
<ide> kwargs={'padding': (2, 2)},
<ide> input_shape=input.shape)
<add> layer_test(convolutional.ZeroPadding2D,
<add> kwargs={'padding': (1, 2, 3, 4)},
<add> input_shape=input.shape)
<add> layer_test(convolutional.ZeroPadding2D,
<add> kwargs={'padding': {'top_pad': 1, 'bottom_pad': 2, 'left_pad': 3, 'right_pad': 4}},
<add> input_shape=input.shape)
<ide>
<ide> # correctness test
<ide> layer = convolutional.ZeroPadding2D(padding=(2, 2))
<ide> layer.set_input(K.variable(input), shape=input.shape)
<ide>
<ide> out = K.eval(layer.output)
<del> for offset in [0, 1, -1, -2]:
<del> assert_allclose(out[:, offset, :, :], 0.)
<del> assert_allclose(out[:, :, offset, :], 0.)
<del> assert_allclose(out[:, 2:-2, 2:-2, :], 1.)
<add> if dim_ordering == 'tf':
<add> for offset in [0, 1, -1, -2]:
<add> assert_allclose(out[:, offset, :, :], 0.)
<add> assert_allclose(out[:, :, offset, :], 0.)
<add> assert_allclose(out[:, 2:-2, 2:-2, :], 1.)
<add> elif dim_ordering == 'th':
<add> for offset in [0, 1, -1, -2]:
<add> assert_allclose(out[:, :, offset, :], 0.)
<add> assert_allclose(out[:, :, :, offset], 0.)
<add> assert_allclose(out[:, 2:-2, 2:-2, :], 1.)
<add>
<add> layer = convolutional.ZeroPadding2D(padding=(1, 2, 3, 4))
<add> layer.set_input(K.variable(input), shape=input.shape)
<add>
<add> out = K.eval(layer.output)
<add> if dim_ordering == 'tf':
<add> for top_offset in [0]:
<add> assert_allclose(out[:, top_offset, :, :], 0.)
<add> for bottom_offset in [-1, -2]:
<add> assert_allclose(out[:, bottom_offset, :, :], 0.)
<add> for left_offset in [0, 1, 2]:
<add> assert_allclose(out[:, :, left_offset, :], 0.)
<add> for right_offset in [-1, -2, -3, -4]:
<add> assert_allclose(out[:, :, right_offset, :], 0.)
<add> assert_allclose(out[:, 1:-2, 3:-4, :], 1.)
<add> elif dim_ordering == 'th':
<add> for top_offset in [0]:
<add> assert_allclose(out[:, :, top_offset, :], 0.)
<add> for bottom_offset in [-1, -2]:
<add> assert_allclose(out[:, :, bottom_offset, :], 0.)
<add> for left_offset in [0, 1, 2]:
<add> assert_allclose(out[:, :, :, left_offset], 0.)
<add> for right_offset in [-1, -2, -3, -4]:
<add> assert_allclose(out[:, :, :, right_offset], 0.)
<add> assert_allclose(out[:, :, 1:-2, 3:-4], 1.)
<ide> layer.get_config()
<ide>
<ide> | 4 |
Ruby | Ruby | remove homebrew_prefix/bin from path | bcf0d6f2450cdea84a32f9a844307804f542fc21 | <ide><path>Library/Homebrew/build.rb
<ide> def install f
<ide>
<ide> if superenv?
<ide> ENV.deps = keg_only_deps.map(&:to_s)
<add> ENV.all_deps = f.recursive_deps.map(&:to_s)
<ide> ENV.x11 = f.recursive_requirements.detect{|rq| rq.class == X11Dependency }
<ide> ENV.setup_build_environment
<ide> f.recursive_requirements.each { |rq| rq.modify_build_environment }
<ide><path>Library/Homebrew/cmd/sh.rb
<ide> def sh
<ide> ENV.deps = Formula.installed.select{|f| f.keg_only? and f.opt_prefix.directory? }.map(&:name)
<ide> end
<ide> ENV.setup_build_environment
<add> if superenv?
<add> # superenv stopped adding brew's bin but generally user's will want it
<add> ENV['PATH'] = ENV['PATH'].split(':').insert(1, "#{HOMEBREW_PREFIX}/bin").join(':')
<add> end
<ide> ENV['PS1'] = 'brew \[\033[1;32m\]\w\[\033[0m\]$ '
<ide> ENV['VERBOSE'] = '1'
<ide> ENV['HOMEBREW_LOG'] = '1'
<ide><path>Library/Homebrew/superenv.rb
<ide> def superenv?
<ide>
<ide> class << ENV
<ide> attr :deps, true
<add> attr :all_deps, true # above is just keg-only-deps
<ide> attr :x11, true
<ide> alias_method :x11?, :x11
<ide>
<ide> def determine_path
<ide> paths << "#{MacSystem.xcode43_developer_dir}/usr/bin"
<ide> paths << "#{MacSystem.xcode43_developer_dir}/Toolchains/XcodeDefault.xctoolchain/usr/bin"
<ide> end
<del> paths += deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/bin" }
<del> paths << HOMEBREW_PREFIX/:bin
<add> paths += all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/bin" }
<ide> paths << "#{MacSystem.x11_prefix}/bin" if x11?
<ide> paths += %w{/usr/bin /bin /usr/sbin /sbin}
<ide> paths.to_path_s
<ide> def + value
<ide> ENV.prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin'
<ide> else
<ide> ENV.deps = []
<add> ENV.all_deps = []
<ide> end
<ide>
<ide> | 3 |
Ruby | Ruby | handle leading spaces in protocol while sanitizing | e7e4deec117154d34db1b18341c00c497e65e089 | <ide><path>actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
<ide> def process_attributes_for(node, options)
<ide>
<ide> def contains_bad_protocols?(attr_name, value)
<ide> uri_attributes.include?(attr_name) &&
<del> (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase))
<add> (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase.strip))
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/template/html-scanner/sanitizer_test.rb
<ide> def test_should_flag_bad_protocols
<ide> assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
<ide> end
<ide> end
<del>
<add>
<ide> def test_should_accept_good_protocols_ignoring_case
<ide> sanitizer = HTML::WhiteListSanitizer.new
<ide> HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
<ide> assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good")
<ide> end
<ide> end
<ide>
<add> def test_should_accept_good_protocols_ignoring_space
<add> sanitizer = HTML::WhiteListSanitizer.new
<add> HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
<add> assert !sanitizer.send(:contains_bad_protocols?, 'src', " #{proto}://good")
<add> end
<add> end
<add>
<ide> def test_should_accept_good_protocols
<ide> sanitizer = HTML::WhiteListSanitizer.new
<ide> HTML::WhiteListSanitizer.allowed_protocols.each do |proto| | 2 |
Ruby | Ruby | add nodoc to some private constants [ci skip] | 4128e70791ca09c405deda15764e5c09e6c0a12a | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def signed_or_encrypted
<ide> # to the Message{Encryptor,Verifier} allows us to handle the
<ide> # (de)serialization step within the cookie jar, which gives us the
<ide> # opportunity to detect and migrate legacy cookies.
<del> module VerifyAndUpgradeLegacySignedMessage
<add> module VerifyAndUpgradeLegacySignedMessage # :nodoc:
<ide> def initialize(*args)
<ide> super
<ide> @legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token], serializer: ActiveSupport::MessageEncryptor::NullSerializer)
<ide> def []=(name, options)
<ide> end
<ide> end
<ide>
<del> class JsonSerializer
<add> class JsonSerializer # :nodoc:
<ide> def self.load(value)
<ide> ActiveSupport::JSON.decode(value)
<ide> end
<ide> def self.dump(value)
<ide> end
<ide> end
<ide>
<del> module SerializedCookieJars
<add> module SerializedCookieJars # :nodoc:
<ide> MARSHAL_SIGNATURE = "\x04\x08".freeze
<ide>
<ide> protected | 1 |
Text | Text | move api docs to apiv1.13 | cf513185b0803ac02bbd8cef05e3372e7fc3b269 | <ide><path>docs/sources/reference/api/docker_remote_api.md
<ide> page_keywords: API, Docker, rcli, REST, documentation
<ide> encoded (JSON) string with credentials:
<ide> `{'username': string, 'password': string, 'email': string, 'serveraddress' : string}`
<ide>
<del>The current version of the API is v1.12
<add>The current version of the API is v1.13
<ide>
<ide> Calling `/images/<name>/insert` is the same as calling
<ide> `/v1.12/images/<name>/insert`.
<ide>
<ide> You can still call an old version of the API using
<ide> `/v1.12/images/<name>/insert`.
<ide>
<add>## v1.13
<add>
<add>### Full Documentation
<add>
<add>[*Docker Remote API v1.13*](/reference/api/docker_remote_api_v1.13/)
<add>
<add>### What's new
<add>
<add>**New!**
<add>`Sockets` parameter added to the `/info` endpoint listing all the sockets the
<add>daemon is configured to listen on.
<add>
<ide> ## v1.12
<ide>
<ide> ### Full Documentation
<ide><path>docs/sources/reference/api/docker_remote_api_v1.11.md
<ide> Display system-wide information
<ide> "NGoroutines":21,
<ide> "NEventsListener":0,
<ide> "InitPath":"/usr/bin/docker",
<del> "Sockets":["unix:///var/run/docker.sock"],
<ide> "IndexServerAddress":["https://index.docker.io/v1/"],
<ide> "MemoryLimit":true,
<ide> "SwapLimit":false,
<ide><path>docs/sources/reference/api/docker_remote_api_v1.12.md
<ide> Display system-wide information
<ide> {
<ide> "Containers":11,
<ide> "Images":16,
<add> "Driver":"btrfs",
<add> "ExecutionDriver":"native-0.1",
<add> "KernelVersion":"3.12.0-1-amd64"
<ide> "Debug":false,
<ide> "NFd": 11,
<ide> "NGoroutines":21,
<add> "NEventsListener":0,
<add> "InitPath":"/usr/bin/docker",
<add> "IndexServerAddress":["https://index.docker.io/v1/"],
<ide> "MemoryLimit":true,
<ide> "SwapLimit":false,
<ide> "IPv4Forwarding":true
<ide><path>docs/sources/reference/api/docker_remote_api_v1.13.md
<add>page_title: Remote API v1.12
<add>page_description: API Documentation for Docker
<add>page_keywords: API, Docker, rcli, REST, documentation
<add>
<add># Docker Remote API v1.13
<add>
<add>## 1. Brief introduction
<add>
<add> - The Remote API has replaced `rcli`.
<add> - The daemon listens on `unix:///var/run/docker.sock` but you can
<add> [*Bind Docker to another host/port or a Unix socket*](
<add> /use/basics/#bind-docker).
<add> - The API tends to be REST, but for some complex commands, like `attach`
<add> or `pull`, the HTTP connection is hijacked to transport `STDOUT`,
<add> `STDIN` and `STDERR`.
<add>
<add># 2. Endpoints
<add>
<add>## 2.1 Containers
<add>
<add>### List containers
<add>
<add>`GET /containers/json`
<add>
<add>List containers
<add>
<add> **Example request**:
<add>
<add> GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> [
<add> {
<add> "Id": "8dfafdbc3a40",
<add> "Image": "base:latest",
<add> "Command": "echo 1",
<add> "Created": 1367854155,
<add> "Status": "Exit 0",
<add> "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}],
<add> "SizeRw":12288,
<add> "SizeRootFs":0
<add> },
<add> {
<add> "Id": "9cd87474be90",
<add> "Image": "base:latest",
<add> "Command": "echo 222222",
<add> "Created": 1367854155,
<add> "Status": "Exit 0",
<add> "Ports":[],
<add> "SizeRw":12288,
<add> "SizeRootFs":0
<add> },
<add> {
<add> "Id": "3176a2479c92",
<add> "Image": "base:latest",
<add> "Command": "echo 3333333333333333",
<add> "Created": 1367854154,
<add> "Status": "Exit 0",
<add> "Ports":[],
<add> "SizeRw":12288,
<add> "SizeRootFs":0
<add> },
<add> {
<add> "Id": "4cb07b47f9fb",
<add> "Image": "base:latest",
<add> "Command": "echo 444444444444444444444444444444444",
<add> "Created": 1367854152,
<add> "Status": "Exit 0",
<add> "Ports":[],
<add> "SizeRw":12288,
<add> "SizeRootFs":0
<add> }
<add> ]
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **all** – 1/True/true or 0/False/false, Show all containers.
<add> Only running containers are shown by default
<add> - **limit** – Show `limit` last created
<add> containers, include non-running ones.
<add> - **since** – Show only containers created since Id, include
<add> non-running ones.
<add> - **before** – Show only containers created before Id, include
<add> non-running ones.
<add> - **size** – 1/True/true or 0/False/false, Show the containers
<add> sizes
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **400** – bad parameter
<add> - **500** – server error
<add>
<add>### Create a container
<add>
<add>`POST /containers/create`
<add>
<add>Create a container
<add>
<add> **Example request**:
<add>
<add> POST /containers/create HTTP/1.1
<add> Content-Type: application/json
<add>
<add> {
<add> "Hostname":"",
<add> "User":"",
<add> "Memory":0,
<add> "MemorySwap":0,
<add> "AttachStdin":false,
<add> "AttachStdout":true,
<add> "AttachStderr":true,
<add> "PortSpecs":null,
<add> "Tty":false,
<add> "OpenStdin":false,
<add> "StdinOnce":false,
<add> "Env":null,
<add> "Cmd":[
<add> "date"
<add> ],
<add> "Image":"base",
<add> "Volumes":{
<add> "/tmp": {}
<add> },
<add> "WorkingDir":"",
<add> "DisableNetwork": false,
<add> "ExposedPorts":{
<add> "22/tcp": {}
<add> }
<add> }
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 201 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "Id":"e90e34656806"
<add> "Warnings":[]
<add> }
<add>
<add> Json Parameters:
<add>
<add>
<add>
<add> - **config** – the container's configuration
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **name** – Assign the specified name to the container. Must
<add> match `/?[a-zA-Z0-9_-]+`.
<add>
<add> Status Codes:
<add>
<add> - **201** – no error
<add> - **404** – no such container
<add> - **406** – impossible to attach (container not running)
<add> - **500** – server error
<add>
<add>### Inspect a container
<add>
<add>`GET /containers/(id)/json`
<add>
<add>Return low-level information on the container `id`
<add>
<add>
<add> **Example request**:
<add>
<add> GET /containers/4fa6e0f0c678/json HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2",
<add> "Created": "2013-05-07T14:51:42.041847+02:00",
<add> "Path": "date",
<add> "Args": [],
<add> "Config": {
<add> "Hostname": "4fa6e0f0c678",
<add> "User": "",
<add> "Memory": 0,
<add> "MemorySwap": 0,
<add> "AttachStdin": false,
<add> "AttachStdout": true,
<add> "AttachStderr": true,
<add> "PortSpecs": null,
<add> "Tty": false,
<add> "OpenStdin": false,
<add> "StdinOnce": false,
<add> "Env": null,
<add> "Cmd": [
<add> "date"
<add> ],
<add> "Dns": null,
<add> "Image": "base",
<add> "Volumes": {},
<add> "VolumesFrom": "",
<add> "WorkingDir":""
<add>
<add> },
<add> "State": {
<add> "Running": false,
<add> "Pid": 0,
<add> "ExitCode": 0,
<add> "StartedAt": "2013-05-07T14:51:42.087658+02:01360",
<add> "Ghost": false
<add> },
<add> "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc",
<add> "NetworkSettings": {
<add> "IpAddress": "",
<add> "IpPrefixLen": 0,
<add> "Gateway": "",
<add> "Bridge": "",
<add> "PortMapping": null
<add> },
<add> "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker",
<add> "ResolvConfPath": "/etc/resolv.conf",
<add> "Volumes": {},
<add> "HostConfig": {
<add> "Binds": null,
<add> "ContainerIDFile": "",
<add> "LxcConf": [],
<add> "Privileged": false,
<add> "PortBindings": {
<add> "80/tcp": [
<add> {
<add> "HostIp": "0.0.0.0",
<add> "HostPort": "49153"
<add> }
<add> ]
<add> },
<add> "Links": null,
<add> "PublishAllPorts": false
<add> }
<add> }
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### List processes running inside a container
<add>
<add>`GET /containers/(id)/top`
<add>
<add>List processes running inside the container `id`
<add>
<add> **Example request**:
<add>
<add> GET /containers/4fa6e0f0c678/top HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "Titles":[
<add> "USER",
<add> "PID",
<add> "%CPU",
<add> "%MEM",
<add> "VSZ",
<add> "RSS",
<add> "TTY",
<add> "STAT",
<add> "START",
<add> "TIME",
<add> "COMMAND"
<add> ],
<add> "Processes":[
<add> ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"],
<add> ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"]
<add> ]
<add> }
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **ps_args** – ps arguments to use (eg. aux)
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Get container logs
<add>
<add>`GET /containers/(id)/logs`
<add>
<add>Get stdout and stderr logs from the container ``id``
<add>
<add> **Example request**:
<add>
<add> GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/vnd.docker.raw-stream
<add>
<add> {{ STREAM }}
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **follow** – 1/True/true or 0/False/false, return stream.
<add> Default false
<add> - **stdout** – 1/True/true or 0/False/false, if logs=true, return
<add> stdout log. Default false
<add> - **stderr** – 1/True/true or 0/False/false, if logs=true, return
<add> stderr log. Default false
<add> - **timestamps** – 1/True/true or 0/False/false, if logs=true, print
<add> timestamps for every log line. Default false
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Inspect changes on a container's filesystem
<add>
<add>`GET /containers/(id)/changes`
<add>
<add>Inspect changes on container `id`'s filesystem
<add>
<add> **Example request**:
<add>
<add> GET /containers/4fa6e0f0c678/changes HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> [
<add> {
<add> "Path":"/dev",
<add> "Kind":0
<add> },
<add> {
<add> "Path":"/dev/kmsg",
<add> "Kind":1
<add> },
<add> {
<add> "Path":"/test",
<add> "Kind":1
<add> }
<add> ]
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Export a container
<add>
<add>`GET /containers/(id)/export`
<add>
<add>Export the contents of container `id`
<add>
<add> **Example request**:
<add>
<add> GET /containers/4fa6e0f0c678/export HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/octet-stream
<add>
<add> {{ STREAM }}
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Start a container
<add>
<add>`POST /containers/(id)/start`
<add>
<add>Start the container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/(id)/start HTTP/1.1
<add> Content-Type: application/json
<add>
<add> {
<add> "Binds":["/tmp:/tmp"],
<add> "Links":["redis3:redis"],
<add> "LxcConf":{"lxc.utsname":"docker"},
<add> "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] },
<add> "PublishAllPorts":false,
<add> "Privileged":false,
<add> "Dns": ["8.8.8.8"],
<add> "VolumesFrom": ["parent", "other:ro"]
<add> }
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 204 No Content
<add> Content-Type: text/plain
<add>
<add> Json Parameters:
<add>
<add>
<add>
<add> - **hostConfig** – the container's host configuration (optional)
<add>
<add> Status Codes:
<add>
<add> - **204** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Stop a container
<add>
<add>`POST /containers/(id)/stop`
<add>
<add>Stop the container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/e90e34656806/stop?t=5 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 204 OK
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **t** – number of seconds to wait before killing the container
<add>
<add> Status Codes:
<add>
<add> - **204** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Restart a container
<add>
<add>`POST /containers/(id)/restart`
<add>
<add>Restart the container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/e90e34656806/restart?t=5 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 204 OK
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **t** – number of seconds to wait before killing the container
<add>
<add> Status Codes:
<add>
<add> - **204** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Kill a container
<add>
<add>`POST /containers/(id)/kill`
<add>
<add>Kill the container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/e90e34656806/kill HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 204 OK
<add>
<add> Query Parameters
<add>
<add> - **signal** - Signal to send to the container: integer or string like "SIGINT".
<add> When not set, SIGKILL is assumed and the call will waits for the container to exit.
<add>
<add> Status Codes:
<add>
<add> - **204** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Attach to a container
<add>
<add>`POST /containers/(id)/attach`
<add>
<add>Attach to the container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/vnd.docker.raw-stream
<add>
<add> {{ STREAM }}
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **logs** – 1/True/true or 0/False/false, return logs. Default
<add> false
<add> - **stream** – 1/True/true or 0/False/false, return stream.
<add> Default false
<add> - **stdin** – 1/True/true or 0/False/false, if stream=true, attach
<add> to stdin. Default false
<add> - **stdout** – 1/True/true or 0/False/false, if logs=true, return
<add> stdout log, if stream=true, attach to stdout. Default false
<add> - **stderr** – 1/True/true or 0/False/false, if logs=true, return
<add> stderr log, if stream=true, attach to stderr. Default false
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **400** – bad parameter
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add> **Stream details**:
<add>
<add> When using the TTY setting is enabled in
<add> [`POST /containers/create`
<add> ](../docker_remote_api_v1.9/#post--containers-create "POST /containers/create"),
<add> the stream is the raw data from the process PTY and client's stdin.
<add> When the TTY is disabled, then the stream is multiplexed to separate
<add> stdout and stderr.
<add>
<add> The format is a **Header** and a **Payload** (frame).
<add>
<add> **HEADER**
<add>
<add> The header will contain the information on which stream write the
<add> stream (stdout or stderr). It also contain the size of the
<add> associated frame encoded on the last 4 bytes (uint32).
<add>
<add> It is encoded on the first 8 bytes like this:
<add>
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add>
<add> `STREAM_TYPE` can be:
<add>
<add> - 0: stdin (will be writen on stdout)
<add> - 1: stdout
<add> - 2: stderr
<add>
<add> `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of
<add> the uint32 size encoded as big endian.
<add>
<add> **PAYLOAD**
<add>
<add> The payload is the raw stream.
<add>
<add> **IMPLEMENTATION**
<add>
<add> The simplest way to implement the Attach protocol is the following:
<add>
<add> 1. Read 8 bytes
<add> 2. chose stdout or stderr depending on the first byte
<add> 3. Extract the frame size from the last 4 byets
<add> 4. Read the extracted size and output it on the correct output
<add> 5. Goto 1)
<add>
<add>### Wait a container
<add>
<add>`POST /containers/(id)/wait`
<add>
<add>Block until container `id` stops, then returns the exit code
<add>
<add> **Example request**:
<add>
<add> POST /containers/16253994b7c4/wait HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"StatusCode":0}
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Remove a container
<add>
<add>`DELETE /containers/(id)`
<add>
<add>Remove the container `id` from the filesystem
<add>
<add> **Example request**:
<add>
<add> DELETE /containers/16253994b7c4?v=1 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 204 OK
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **v** – 1/True/true or 0/False/false, Remove the volumes
<add> associated to the container. Default false
<add> - **force** – 1/True/true or 0/False/false, Removes the container
<add> even if it was running. Default false
<add>
<add> Status Codes:
<add>
<add> - **204** – no error
<add> - **400** – bad parameter
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Copy files or folders from a container
<add>
<add>`POST /containers/(id)/copy`
<add>
<add>Copy files or folders of container `id`
<add>
<add> **Example request**:
<add>
<add> POST /containers/4fa6e0f0c678/copy HTTP/1.1
<add> Content-Type: application/json
<add>
<add> {
<add> "Resource":"test.txt"
<add> }
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/octet-stream
<add>
<add> {{ STREAM }}
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>## 2.2 Images
<add>
<add>### List Images
<add>
<add>`GET /images/json`
<add>
<add>**Example request**:
<add>
<add> GET /images/json?all=0 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> [
<add> {
<add> "RepoTags": [
<add> "ubuntu:12.04",
<add> "ubuntu:precise",
<add> "ubuntu:latest"
<add> ],
<add> "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c",
<add> "Created": 1365714795,
<add> "Size": 131506275,
<add> "VirtualSize": 131506275
<add> },
<add> {
<add> "RepoTags": [
<add> "ubuntu:12.10",
<add> "ubuntu:quantal"
<add> ],
<add> "ParentId": "27cf784147099545",
<add> "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc",
<add> "Created": 1364102658,
<add> "Size": 24653,
<add> "VirtualSize": 180116135
<add> }
<add> ]
<add>
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **all** – 1/True/true or 0/False/false, default false
<add> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list.
<add>
<add>
<add>
<add>### Create an image
<add>
<add>`POST /images/create`
<add>
<add>Create an image, either by pull it from the registry or by importing it
<add>
<add> **Example request**:
<add>
<add> POST /images/create?fromImage=base HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"status":"Pulling..."}
<add> {"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}}
<add> {"error":"Invalid..."}
<add> ...
<add>
<add> When using this endpoint to pull an image from the registry, the
<add> `X-Registry-Auth` header can be used to include
<add> a base64-encoded AuthConfig object.
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **fromImage** – name of the image to pull
<add> - **fromSrc** – source to import, - means stdin
<add> - **repo** – repository
<add> - **tag** – tag
<add> - **registry** – the registry to pull from
<add>
<add> Request Headers:
<add>
<add>
<add>
<add> - **X-Registry-Auth** – base64-encoded AuthConfig object
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Insert a file in an image
<add>
<add>`POST /images/(name)/insert`
<add>
<add>Insert a file from `url` in the image `name` at `path`
<add>
<add> **Example request**:
<add>
<add> POST /images/test/insert?path=/usr&url=myurl HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"status":"Inserting..."}
<add> {"status":"Inserting", "progress":"1/? (n/a)", "progressDetail":{"current":1}}
<add> {"error":"Invalid..."}
<add> ...
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Inspect an image
<add>
<add>`GET /images/(name)/json`
<add>
<add>Return low-level information on the image `name`
<add>
<add> **Example request**:
<add>
<add> GET /images/base/json HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "Created":"2013-03-23T22:24:18.818426-07:00",
<add> "Container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0",
<add> "ContainerConfig":
<add> {
<add> "Hostname":"",
<add> "User":"",
<add> "Memory":0,
<add> "MemorySwap":0,
<add> "AttachStdin":false,
<add> "AttachStdout":false,
<add> "AttachStderr":false,
<add> "PortSpecs":null,
<add> "Tty":true,
<add> "OpenStdin":true,
<add> "StdinOnce":false,
<add> "Env":null,
<add> "Cmd": ["/bin/bash"]
<add> ,"Dns":null,
<add> "Image":"base",
<add> "Volumes":null,
<add> "VolumesFrom":"",
<add> "WorkingDir":""
<add> },
<add> "Id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc",
<add> "Parent":"27cf784147099545",
<add> "Size": 6824592
<add> }
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such image
<add> - **500** – server error
<add>
<add>### Get the history of an image
<add>
<add>`GET /images/(name)/history`
<add>
<add>Return the history of the image `name`
<add>
<add> **Example request**:
<add>
<add> GET /images/base/history HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> [
<add> {
<add> "Id":"b750fe79269d",
<add> "Created":1364102658,
<add> "CreatedBy":"/bin/bash"
<add> },
<add> {
<add> "Id":"27cf78414709",
<add> "Created":1364068391,
<add> "CreatedBy":""
<add> }
<add> ]
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such image
<add> - **500** – server error
<add>
<add>### Push an image on the registry
<add>
<add>`POST /images/(name)/push`
<add>
<add>Push the image `name` on the registry
<add>
<add> **Example request**:
<add>
<add> POST /images/test/push HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"status":"Pushing..."}
<add> {"status":"Pushing", "progress":"1/? (n/a)", "progressDetail":{"current":1}}}
<add> {"error":"Invalid..."}
<add> ...
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **registry** – the registry you wan to push, optional
<add>
<add> Request Headers:
<add>
<add>
<add>
<add> - **X-Registry-Auth** – include a base64-encoded AuthConfig
<add> object.
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such image
<add> - **500** – server error
<add>
<add>### Tag an image into a repository
<add>
<add>`POST /images/(name)/tag`
<add>
<add>Tag the image `name` into a repository
<add>
<add> **Example request**:
<add>
<add> POST /images/test/tag?repo=myrepo&force=0 HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 201 OK
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **repo** – The repository to tag in
<add> - **force** – 1/True/true or 0/False/false, default false
<add>
<add> Status Codes:
<add>
<add> - **201** – no error
<add> - **400** – bad parameter
<add> - **404** – no such image
<add> - **409** – conflict
<add> - **500** – server error
<add>
<add>### Remove an image
<add>
<add>`DELETE /images/(name)`
<add>
<add>Remove the image `name` from the filesystem
<add>
<add> **Example request**:
<add>
<add> DELETE /images/test HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-type: application/json
<add>
<add> [
<add> {"Untagged":"3e2f21a89f"},
<add> {"Deleted":"3e2f21a89f"},
<add> {"Deleted":"53b4f83ac9"}
<add> ]
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **force** – 1/True/true or 0/False/false, default false
<add> - **noprune** – 1/True/true or 0/False/false, default false
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **404** – no such image
<add> - **409** – conflict
<add> - **500** – server error
<add>
<add>### Search images
<add>
<add>`GET /images/search`
<add>
<add>Search for an image on [Docker Hub](https://hub.docker.com).
<add>
<add>> **Note**:
<add>> The response keys have changed from API v1.6 to reflect the JSON
<add>> sent by the registry server to the docker daemon's request.
<add>
<add> **Example request**:
<add>
<add> GET /images/search?term=sshd HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> [
<add> {
<add> "description": "",
<add> "is_official": false,
<add> "is_automated": false,
<add> "name": "wma55/u1210sshd",
<add> "star_count": 0
<add> },
<add> {
<add> "description": "",
<add> "is_official": false,
<add> "is_automated": false,
<add> "name": "jdswinbank/sshd",
<add> "star_count": 0
<add> },
<add> {
<add> "description": "",
<add> "is_official": false,
<add> "is_automated": false,
<add> "name": "vgauthier/sshd",
<add> "star_count": 0
<add> }
<add> ...
<add> ]
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **term** – term to search
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>## 2.3 Misc
<add>
<add>### Build an image from Dockerfile via stdin
<add>
<add>`POST /build`
<add>
<add>Build an image from Dockerfile via stdin
<add>
<add> **Example request**:
<add>
<add> POST /build HTTP/1.1
<add>
<add> {{ STREAM }}
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"stream":"Step 1..."}
<add> {"stream":"..."}
<add> {"error":"Error...", "errorDetail":{"code": 123, "message": "Error..."}}
<add>
<add> The stream must be a tar archive compressed with one of the
<add> following algorithms: identity (no compression), gzip, bzip2, xz.
<add>
<add> The archive must include a file called `Dockerfile`
<add> at its root. It may include any number of other files,
<add> which will be accessible in the build context (See the [*ADD build
<add> command*](/reference/builder/#dockerbuilder)).
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **t** – repository name (and optionally a tag) to be applied to
<add> the resulting image in case of success
<add> - **q** – suppress verbose build output
<add> - **nocache** – do not use the cache when building the image
<add> - **rm** - remove intermediate containers after a successful build (default behavior)
<add> - **forcerm - always remove intermediate containers (includes rm)
<add>
<add> Request Headers:
<add>
<add>
<add>
<add> - **Content-type** – should be set to
<add> `"application/tar"`.
<add> - **X-Registry-Config** – base64-encoded ConfigFile object
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Check auth configuration
<add>
<add>`POST /auth`
<add>
<add>Get the default username and email
<add>
<add> **Example request**:
<add>
<add> POST /auth HTTP/1.1
<add> Content-Type: application/json
<add>
<add> {
<add> "username":"hannibal",
<add> "password:"xxxx",
<add> "email":"hannibal@a-team.com",
<add> "serveraddress":"https://index.docker.io/v1/"
<add> }
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **204** – no error
<add> - **500** – server error
<add>
<add>### Display system-wide information
<add>
<add>`GET /info`
<add>
<add>Display system-wide information
<add>
<add> **Example request**:
<add>
<add> GET /info HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "Containers":11,
<add> "Images":16,
<add> "Driver":"btrfs",
<add> "ExecutionDriver":"native-0.1",
<add> "KernelVersion":"3.12.0-1-amd64"
<add> "Debug":false,
<add> "NFd": 11,
<add> "NGoroutines":21,
<add> "NEventsListener":0,
<add> "InitPath":"/usr/bin/docker",
<add> "Sockets":["unix:///var/run/docker.sock"],
<add> "IndexServerAddress":["https://index.docker.io/v1/"],
<add> "MemoryLimit":true,
<add> "SwapLimit":false,
<add> "IPv4Forwarding":true
<add> }
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Show the docker version information
<add>
<add>`GET /version`
<add>
<add>Show the docker version information
<add>
<add> **Example request**:
<add>
<add> GET /version HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {
<add> "ApiVersion":"1.12",
<add> "Version":"0.2.2",
<add> "GitCommit":"5a2a5cc+CHANGES",
<add> "GoVersion":"go1.0.3"
<add> }
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Ping the docker server
<add>
<add>`GET /_ping`
<add>
<add>Ping the docker server
<add>
<add> **Example request**:
<add>
<add> GET /_ping HTTP/1.1
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add>
<add> OK
<add>
<add> Status Codes:
<add>
<add> - **200** - no error
<add> - **500** - server error
<add>
<add>### Create a new image from a container's changes
<add>
<add>`POST /commit`
<add>
<add>Create a new image from a container's changes
<add>
<add> **Example request**:
<add>
<add> POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1
<add> Content-Type: application/json
<add>
<add> {
<add> "Hostname":"",
<add> "User":"",
<add> "Memory":0,
<add> "MemorySwap":0,
<add> "AttachStdin":false,
<add> "AttachStdout":true,
<add> "AttachStderr":true,
<add> "PortSpecs":null,
<add> "Tty":false,
<add> "OpenStdin":false,
<add> "StdinOnce":false,
<add> "Env":null,
<add> "Cmd":[
<add> "date"
<add> ],
<add> "Volumes":{
<add> "/tmp": {}
<add> },
<add> "WorkingDir":"",
<add> "DisableNetwork": false,
<add> "ExposedPorts":{
<add> "22/tcp": {}
<add> }
<add> }
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 201 OK
<add> Content-Type: application/vnd.docker.raw-stream
<add>
<add> {"Id":"596069db4bf5"}
<add>
<add> Json Parameters:
<add>
<add>
<add>
<add> - **config** - the container's configuration
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **container** – source container
<add> - **repo** – repository
<add> - **tag** – tag
<add> - **m** – commit message
<add> - **author** – author (eg. "John Hannibal Smith
<add> <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>")
<add>
<add> Status Codes:
<add>
<add> - **201** – no error
<add> - **404** – no such container
<add> - **500** – server error
<add>
<add>### Monitor Docker's events
<add>
<add>`GET /events`
<add>
<add>Get events from docker, either in real time via streaming, or
<add>via polling (using since)
<add>
<add> **Example request**:
<add>
<add> GET /events?since=1374067924
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/json
<add>
<add> {"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924}
<add> {"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924}
<add> {"status":"stop","id":"dfdf82bd3881","from":"base:latest","time":1374067966}
<add> {"status":"destroy","id":"dfdf82bd3881","from":"base:latest","time":1374067970}
<add>
<add> Query Parameters:
<add>
<add>
<add>
<add> - **since** – timestamp used for polling
<add> - **until** – timestamp used for polling
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Get a tarball containing all images and tags in a repository
<add>
<add>`GET /images/(name)/get`
<add>
<add>Get a tarball containing all images and metadata for the repository
<add>specified by `name`.
<add>
<add> **Example request**
<add>
<add> GET /images/ubuntu/get
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add> Content-Type: application/x-tar
<add>
<add> Binary data stream
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add>### Load a tarball with a set of images and tags into docker
<add>
<add>`POST /images/load`
<add>
<add>Load a set of images and tags into the docker repository.
<add>
<add> **Example request**
<add>
<add> POST /images/load
<add>
<add> Tarball in body
<add>
<add> **Example response**:
<add>
<add> HTTP/1.1 200 OK
<add>
<add> Status Codes:
<add>
<add> - **200** – no error
<add> - **500** – server error
<add>
<add># 3. Going further
<add>
<add>## 3.1 Inside `docker run`
<add>
<add>Here are the steps of `docker run`:
<add>
<add>- Create the container
<add>
<add>- If the status code is 404, it means the image doesn't exists:
<add> - Try to pull it
<add> - Then retry to create the container
<add>
<add>- Start the container
<add>
<add>- If you are not in detached mode:
<add> - Attach to the container, using logs=1 (to have stdout and
<add> stderr from the container's start) and stream=1
<add>
<add>- If in detached mode or only stdin is attached:
<add> - Display the container's id
<add>
<add>## 3.2 Hijacking
<add>
<add>In this version of the API, /attach, uses hijacking to transport stdin,
<add>stdout and stderr on the same socket. This might change in the future.
<add>
<add>## 3.3 CORS Requests
<add>
<add>To enable cross origin requests to the remote api add the flag
<add>"–api-enable-cors" when running docker in daemon mode.
<add>
<add> $ docker -d -H="192.168.1.9:2375" --api-enable-cors | 4 |
Ruby | Ruby | use more generic cflags when building bottles | c71f883fa8a6a5bd2f9a42207e1fd1476c2a44b8 | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def gcc_4_0_1
<ide> self['CC'] = '/usr/bin/gcc-4.0'
<ide> self['CXX'] = '/usr/bin/g++-4.0'
<ide> replace_in_cflags '-O4', '-O3'
<del> set_cpu_cflags 'nocona -mssse3', :core => 'prescott'
<add> set_cpu_cflags 'nocona -mssse3', :core => 'prescott', :bottle => 'generic'
<ide> @compiler = :gcc
<ide> end
<ide> alias_method :gcc_4_0, :gcc_4_0_1
<ide> def gcc args = {}
<ide> self['CC'] = gcc_path.exist? ? gcc_path : HOMEBREW_PREFIX+'bin/gcc-4.2'
<ide> self['CXX'] = gxx_path.exist? ? gxx_path : HOMEBREW_PREFIX+'bin/g++-4.2'
<ide> replace_in_cflags '-O4', '-O3'
<del> set_cpu_cflags 'core2 -msse4', :penryn => 'core2 -msse4.1', :core2 => 'core2', :core => 'prescott'
<add> set_cpu_cflags 'core2 -msse4', :penryn => 'core2 -msse4.1', :core2 => 'core2', :core => 'prescott', :bottle => 'generic'
<ide> @compiler = :gcc
<ide>
<ide> raise "GCC could not be found" if not File.exist? ENV['CC'] \
<ide> def set_cpu_cflags default, map = {}
<ide> remove_from_cflags %r{( -Xclang \S+)+}
<ide> remove_from_cflags %r{-mssse3}
<ide> remove_from_cflags %r{-msse4(\.\d)?}
<add> append_to_cflags xarch
<ide> # Don't set -msse3 and older flags because -march does that for us
<del> append_to_cflags xarch + '-march=' + map.fetch(Hardware.intel_family, default)
<add> if ARGV.build_bottle?
<add> if map.has_key?(:bottle)
<add> append_to_cflags '-mtune=' + map.fetch(:bottle)
<add> end
<add> else
<add> append_to_cflags '-march=' + map.fetch(Hardware.intel_family, default)
<add> end
<ide> end
<ide>
<ide> # actually c-compiler, so cc would be a better name | 1 |
PHP | PHP | remove the upgrade tool | 7b6c4ad750a9c851938eb3bd0a3104c9ef9f2c25 | <ide><path>src/Command/UpgradeCommand.php
<del><?php
<del>declare(strict_types=1);
<del>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 4.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Command;
<del>
<del>use Cake\Console\Arguments;
<del>use Cake\Console\Command;
<del>use Cake\Console\ConsoleIo;
<del>use Cake\Console\ConsoleOptionParser;
<del>use Cake\Core\Configure;
<del>use RecursiveDirectoryIterator;
<del>use RecursiveIteratorIterator;
<del>use RecursiveRegexIterator;
<del>use RegexIterator;
<del>
<del>/**
<del> * Upgrade 3.x application to 4.0.
<del> */
<del>class UpgradeCommand extends Command
<del>{
<del> /**
<del> * Is git used
<del> *
<del> * @var bool
<del> */
<del> protected $git = false;
<del>
<del> /**
<del> * App/plugin path.
<del> *
<del> * @var string
<del> */
<del> protected $path = '';
<del>
<del> /**
<del> * Arguments
<del> *
<del> * @var \Cake\Console\Arguments
<del> */
<del> protected $args;
<del>
<del> /**
<del> * Console IO
<del> *
<del> * @var \Cake\Console\ConsoleIo
<del> */
<del> protected $io;
<del>
<del> /**
<del> * Holds info of file types to move.
<del> *
<del> * @var array
<del> */
<del> protected $types = [
<del> 'templates' => [
<del> 'regex' => '#/Template/\.$#',
<del> 'from' => '/Template',
<del> 'to' => '/../templates',
<del> ],
<del> 'locales' => [
<del> 'regex' => '#/Locale/\.$#',
<del> 'from' => '/Locale',
<del> 'to' => '/../resources/locales',
<del> ],
<del> ];
<del>
<del> /**
<del> * Execute.
<del> *
<del> * @param \Cake\Console\Arguments $args The command arguments.
<del> * @param \Cake\Console\ConsoleIo $io The console io
<del> * @return int|null
<del> */
<del> public function execute(Arguments $args, ConsoleIo $io): ?int
<del> {
<del> $this->io = $io;
<del> $this->args = $args;
<del>
<del> $path = (string)$args->getOption('path');
<del> if ($path) {
<del> $this->path = rtrim($path, '/') . DIRECTORY_SEPARATOR;
<del> } else {
<del> $this->path = APP;
<del> }
<del>
<del> $this->git = is_dir($this->path . '.git');
<del>
<del> switch ($args->getArgument('type')) {
<del> case 'templates':
<del> $this->processTemplates();
<del> break;
<del> case 'locales':
<del> $this->processLocales();
<del> break;
<del> }
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * Move templates to new location and rename to .php
<del> *
<del> * @return void
<del> */
<del> protected function processTemplates(): void
<del> {
<del> if (is_dir($this->path . 'src/Template')) {
<del> $this->rename(
<del> $this->path . 'src/Template',
<del> $this->path . 'templates'
<del> );
<del> $this->renameSubFolders($this->path . 'templates');
<del> $this->changeExt($this->path . 'templates');
<del> }
<del>
<del> foreach ((array)Configure::read('App.paths.plugins') as $path) {
<del> $this->moveDir($path, 'templates');
<del> $this->changeExt($path);
<del> }
<del> }
<del>
<del> /**
<del> * Move locale files to new location.
<del> *
<del> * @return void
<del> */
<del> protected function processLocales(): void
<del> {
<del> if (is_dir($this->path . 'src/Locale')) {
<del> $this->rename(
<del> $this->path . 'src/Locale',
<del> $this->path . 'resources/locales'
<del> );
<del> }
<del>
<del> foreach ((array)Configure::read('App.paths.plugins') as $path) {
<del> $this->moveDir($path, 'locales');
<del> }
<del> }
<del>
<del> /**
<del> * Recursively move directories.
<del> *
<del> * @param string $path Path
<del> * @param string $type Type
<del> * @return void
<del> */
<del> protected function moveDir(string $path, string $type): void
<del> {
<del> $info = $this->types[$type];
<del>
<del> $dirIter = new RecursiveDirectoryIterator(
<del> $path,
<del> RecursiveDirectoryIterator::UNIX_PATHS
<del> );
<del> $iterIter = new RecursiveIteratorIterator($dirIter);
<del> $templateDirs = new RegexIterator(
<del> $iterIter,
<del> $info['regex'],
<del> RecursiveRegexIterator::REPLACE
<del> );
<del>
<del> foreach ($templateDirs as $key => $val) {
<del> $this->rename(
<del> $val . $info['from'],
<del> $val . $info['to']
<del> );
<del>
<del> if ($type === 'templates') {
<del> $this->renameSubFolders($val . '/../templates');
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * Rename Layout, Element, Cell, Plugin to layout, element, cell, plugin
<del> * respectively.
<del> *
<del> * @param string $path Path.
<del> * @return void
<del> */
<del> protected function renameSubFolders(string $path): void
<del> {
<del> $dirIter = new RecursiveDirectoryIterator(
<del> $path,
<del> RecursiveDirectoryIterator::UNIX_PATHS
<del> );
<del> $iterIter = new RecursiveIteratorIterator($dirIter);
<del>
<del> $folders = ['Layout', 'Element', 'Cell', 'Email', 'Plugin', 'Flash'];
<del>
<del> foreach ($folders as $folder) {
<del> $templateDirs = new RegexIterator(
<del> $iterIter,
<del> '#/' . $folder . '/\.$#',
<del> RecursiveRegexIterator::SPLIT
<del> );
<del>
<del> foreach ($templateDirs as $key => $val) {
<del> $this->rename(
<del> $val[0] . '/' . $folder,
<del> $val[0] . '/' . strtolower($folder)
<del> );
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * Recursively change template extension to .php
<del> *
<del> * @param string $path Path
<del> * @return void
<del> */
<del> protected function changeExt(string $path): void
<del> {
<del> $dirIter = new RecursiveDirectoryIterator(
<del> $path,
<del> RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::UNIX_PATHS
<del> );
<del> $iterIter = new RecursiveIteratorIterator($dirIter);
<del> $templates = new RegexIterator(
<del> $iterIter,
<del> '/\.ctp$/i',
<del> RecursiveRegexIterator::REPLACE
<del> );
<del>
<del> foreach ($templates as $key => $val) {
<del> $this->rename($val . '.ctp', $val . '.php');
<del> }
<del> }
<del>
<del> /**
<del> * Rename file or directory
<del> *
<del> * @param string $source Source path.
<del> * @param string $dest Destination path.
<del> * @return void
<del> */
<del> protected function rename(string $source, string $dest): void
<del> {
<del> $this->io->out("Move $source to $dest");
<del>
<del> if ($this->args->getOption('dry-run')) {
<del> return;
<del> }
<del>
<del> $parent = dirname($dest);
<del> if (!is_dir($parent)) {
<del> $old = umask(0);
<del> mkdir($parent, 0755, true);
<del> umask($old);
<del> }
<del>
<del> if ($this->git) {
<del> exec("git mv $source $dest");
<del> } else {
<del> rename($source, $dest);
<del> }
<del> }
<del>
<del> /**
<del> * Gets the option parser instance and configures it.
<del> *
<del> * @param \Cake\Console\ConsoleOptionParser $parser The parser to build
<del> * @return \Cake\Console\ConsoleOptionParser
<del> */
<del> protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
<del> {
<del> $parser
<del> ->addArgument('type', [
<del> 'choices' => ['templates', 'locales'],
<del> 'required' => true,
<del> 'help' => 'Specify file type to move.',
<del> ])
<del> ->addOption('path', [
<del> 'help' => 'App/plugin path',
<del> ])
<del> ->addOption('dry-run', [
<del> 'help' => 'Dry run.',
<del> 'boolean' => true,
<del> ]);
<del>
<del> return $parser;
<del> }
<del>}
<ide><path>tests/TestCase/Command/UpgradeCommandTest.php
<del><?php
<del>declare(strict_types=1);
<del>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 4.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\Command;
<del>
<del>use Cake\Core\Configure;
<del>use Cake\TestSuite\ConsoleIntegrationTestTrait;
<del>use Cake\TestSuite\TestCase;
<del>use org\bovigo\vfs\vfsStream;
<del>use org\bovigo\vfs\visitor\vfsStreamStructureVisitor;
<del>
<del>/**
<del> * UpgradeCommand test.
<del> */
<del>class UpgradeCommandTest extends TestCase
<del>{
<del> use ConsoleIntegrationTestTrait;
<del>
<del> protected $dirStructure = [
<del> 'forTemplate' => [
<del> 'src' => [
<del> 'Template' => [
<del> 'Email' => ['html' => ['def.php' => '']],
<del> 'Element' => [
<del> 'Flash' => ['default.ctp' => ''],
<del> 'foo.ctp' => '',
<del> ],
<del> 'Layout' => ['default.ctp' => ''],
<del> 'Cell' => [
<del> 'MyCell' => ['display.ctp' => ''],
<del> ],
<del> 'Plugin' => [
<del> 'TestPlugin' => [
<del> 'Layout' => ['Email' => ['text.php' => '']],
<del> 'Element' => ['bar.ctp' => ''],
<del> 'Posts' => ['index.ctp' => ''],
<del> ],
<del> ],
<del> 'Pages' => [
<del> 'home.ctp' => '',
<del> ],
<del> ],
<del> ],
<del> 'plugins' => [
<del> 'TestPlugin' => [
<del> 'src' => [
<del> // This is ensure "src/Cell" does not get renamed.
<del> 'Cell' => [
<del> 'TestPluginCell.php' => '',
<del> ],
<del> 'Template' => [
<del> 'Element' => [
<del> 'foo.ctp' => '',
<del> ],
<del> 'Layout' => [
<del> 'plugin.ctp' => '',
<del> 'Email' => ['html.php' => ''],
<del> ],
<del> 'Cell' => [
<del> 'TestPluginCell' => ['bar.ctp' => ''],
<del> ],
<del> ],
<del> ],
<del> ],
<del> 'PluginWithoutTemplates' => [
<del> 'src' => [],
<del> ],
<del> ],
<del> ],
<del> 'forLocale' => [
<del> 'src' => [
<del> 'Locale' => [
<del> 'default.pot' => '',
<del> 'en' => [
<del> 'default.po' => '',
<del> ],
<del> ],
<del> ],
<del> 'plugins' => [
<del> 'TestVendor' => [
<del> 'TestPlugin' => [
<del> 'src' => [
<del> 'Locale' => [
<del> 'default.pot' => '',
<del> 'fr' => [
<del> 'default.po' => '',
<del> ],
<del> ],
<del> ],
<del> ],
<del> ],
<del> 'TestPluginWithLocale' => [
<del> 'src' => [],
<del> ],
<del> ],
<del> ],
<del> ];
<del>
<del> /**
<del> * pluginPaths
<del> *
<del> * @var array
<del> */
<del> protected $pluginPaths = [];
<del>
<del> /**
<del> * localePaths
<del> *
<del> * @var array
<del> */
<del> protected $localePaths = [];
<del>
<del> /**
<del> * Namespace
<del> *
<del> * @var string
<del> */
<del> protected $namespace = '';
<del>
<del> /**
<del> * setup method
<del> *
<del> * @return void
<del> */
<del> public function setUp(): void
<del> {
<del> parent::setUp();
<del>
<del> $this->useCommandRunner(true);
<del>
<del> $this->fs = vfsStream::setup('root');
<del>
<del> $this->pluginPaths = Configure::read('App.paths.plugins');
<del> Configure::write('App.paths.plugins', [$this->fs->url() . '/plugins'], true);
<del>
<del> $this->localePaths = Configure::read('App.paths.locales');
<del> Configure::write('App.paths.locales', [$this->fs->url() . '/src/Locale'], true);
<del>
<del> $this->namespace = Configure::read('App.namespace');
<del> Configure::write('App.namespace', 'TestApp');
<del> }
<del>
<del> /**
<del> * tearDown
<del> *
<del> * @return void
<del> */
<del> public function tearDown(): void
<del> {
<del> Configure::write('App.paths.plugins', $this->pluginPaths);
<del> Configure::write('App.paths.locales', $this->localePaths);
<del> Configure::write('App.namespace', $this->namespace);
<del> }
<del>
<del> /**
<del> * testUpgradeTemplate
<del> *
<del> * @return void
<del> */
<del> public function testUpgradeTemplate()
<del> {
<del> vfsStream::create($this->dirStructure['forTemplate']);
<del>
<del> $this->exec('upgrade templates --path ' . $this->fs->url());
<del>
<del> $ds = [
<del> 'src' => [],
<del> 'templates' => [
<del> 'email' => ['html' => ['def.php' => '']],
<del> 'element' => [
<del> 'flash' => ['default.php' => ''],
<del> 'foo.php' => '',
<del> ],
<del> 'layout' => ['default.php' => ''],
<del> 'cell' => [
<del> 'MyCell' => ['display.php' => ''],
<del> ],
<del> 'plugin' => [
<del> 'TestPlugin' => [
<del> 'layout' => ['email' => ['text.php' => '']],
<del> 'element' => ['bar.php' => ''],
<del> 'Posts' => ['index.php' => ''],
<del> ],
<del> ],
<del> 'Pages' => [
<del> 'home.php' => '',
<del> ],
<del> ],
<del> 'plugins' => [
<del> 'TestPlugin' => [
<del> 'src' => [
<del> // This is ensure "src/Cell" does not get renamed.
<del> 'Cell' => [
<del> 'TestPluginCell.php' => '',
<del> ],
<del> ],
<del> 'templates' => [
<del> 'element' => [
<del> 'foo.php' => '',
<del> ],
<del> 'layout' => [
<del> 'plugin.php' => '',
<del> 'email' => ['html.php' => ''],
<del> ],
<del> 'cell' => [
<del> 'TestPluginCell' => ['bar.php' => ''],
<del> ],
<del> ],
<del> ],
<del> 'PluginWithoutTemplates' => [
<del> 'src' => [],
<del> ],
<del> ],
<del> ];
<del>
<del> $this->assertEquals(
<del> ['root' => $ds],
<del> vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure()
<del> );
<del> }
<del>
<del> /**
<del> * testUpgradeLocale
<del> *
<del> * @return void
<del> */
<del> public function testUpgradeLocale()
<del> {
<del> vfsStream::create($this->dirStructure['forLocale']);
<del>
<del> $this->exec('upgrade locales --path ' . $this->fs->url());
<del>
<del> $ds = [
<del> 'src' => [],
<del> 'resources' => [
<del> 'locales' => [
<del> 'default.pot' => '',
<del> 'en' => [
<del> 'default.po' => '',
<del> ],
<del> ],
<del> ],
<del> 'plugins' => [
<del> 'TestVendor' => [
<del> 'TestPlugin' => [
<del> 'src' => [],
<del> 'resources' => [
<del> 'locales' => [
<del> 'default.pot' => '',
<del> 'fr' => [
<del> 'default.po' => '',
<del> ],
<del> ],
<del> ],
<del> ],
<del> ],
<del> 'TestPluginWithLocale' => [
<del> 'src' => [],
<del> ],
<del> ],
<del> ];
<del>
<del> $this->assertEquals(
<del> ['root' => $ds],
<del> vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure()
<del> );
<del> }
<del>} | 2 |
Ruby | Ruby | truncate output to 1mb | 7312b4a1a43c77c819b5d02db574572d6d6e4656 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide>
<ide> module Homebrew
<ide> EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt"
<add> BYTES_IN_1_MEGABYTE = 1024*1024
<ide>
<ide> def homebrew_git_repo tap=nil
<ide> if tap
<ide> def test_bot
<ide> if output.respond_to?(:force_encoding) && !output.valid_encoding?
<ide> output.force_encoding(Encoding::UTF_8)
<ide> end
<del> output = REXML::CData.new output.delete("\000\a\b\e\f")
<add> output = output.delete("\000\a\b\e\f")
<add> if output.bytesize > BYTES_IN_1_MEGABYTE
<add> output = "truncated output to 1MB:\n" \
<add> + output.slice(-BYTES_IN_1_MEGABYTE, BYTES_IN_1_MEGABYTE)
<add> end
<add> output = REXML::CData.new output
<ide> if step.passed?
<ide> system_out = testcase.add_element 'system-out'
<ide> system_out.text = output | 1 |
Java | Java | remove double lookup of uimanager | 8c013173f80d60eb6bced8930280caab8bc08ee2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java
<ide> private static UIManager getUIManager(
<ide> @UIManagerType int uiManagerType,
<ide> boolean returnNullIfCatalystIsInactive) {
<ide> if (context.isBridgeless()) {
<del> @Nullable
<del> UIManager uiManager =
<del> context.getJSIModule(JSIModuleType.UIManager) != null
<del> ? (UIManager) context.getJSIModule(JSIModuleType.UIManager)
<del> : null;
<add> @Nullable UIManager uiManager = (UIManager) context.getJSIModule(JSIModuleType.UIManager);
<ide> if (uiManager == null) {
<ide> ReactSoftException.logSoftException(
<ide> "UIManagerHelper", | 1 |
Go | Go | allow initial response | f033ce3ee9ee055612acacde537687e41865e14f | <ide><path>utils/resumablerequestreader.go
<ide> func ResumableRequestReader(c *http.Client, r *http.Request, maxfail uint32, tot
<ide> return &resumableRequestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize}
<ide> }
<ide>
<add>func ResumableRequestReaderWithInitialResponse(c *http.Client, r *http.Request, maxfail uint32, totalsize int64, initialResponse *http.Response) io.ReadCloser {
<add> return &resumableRequestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize, currentResponse: initialResponse}
<add>}
<add>
<ide> func (r *resumableRequestReader) Read(p []byte) (n int, err error) {
<ide> if r.client == nil || r.request == nil {
<ide> return 0, fmt.Errorf("client and request can't be nil\n") | 1 |
Python | Python | remove redundant parentheses | 78119182faaa5489aa3ec152808f132686b87df9 | <ide><path>airflow/www/views.py
<ide> def _mark_dagrun_state_as_failed(self, dag_id, execution_date, confirmed, origin
<ide>
<ide> response = self.render_template(
<ide> 'airflow/confirm.html',
<del> message=("Here's the list of task instances you are about to mark as failed"),
<add> message="Here's the list of task instances you are about to mark as failed",
<ide> details=details)
<ide>
<ide> return response
<ide> def _mark_dagrun_state_as_success(self, dag_id, execution_date, confirmed, origi
<ide>
<ide> response = self.render_template(
<ide> 'airflow/confirm.html',
<del> message=("Here's the list of task instances you are about to mark as success"),
<add> message="Here's the list of task instances you are about to mark as success",
<ide> details=details)
<ide>
<ide> return response | 1 |
Javascript | Javascript | pass secureprotocol through on tls.server creation | d0e84b0088a865ed59afd4854b40a3eaf864928b | <ide><path>lib/tls.js
<ide> function Server(/* [options], listener */) {
<ide> key: self.key,
<ide> cert: self.cert,
<ide> ca: self.ca,
<add> secureProtocol: self.secureProtocol,
<ide> crl: self.crl
<ide> });
<ide> //creds.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA');
<ide> Server.prototype.setOptions = function(options) {
<ide> if (options.key) this.key = options.key;
<ide> if (options.cert) this.cert = options.cert;
<ide> if (options.ca) this.ca = options.ca;
<add> if (options.secureProtocol) this.secureProtocol = options.secureProtocol;
<ide> if (options.crl) this.crl = options.crl;
<ide> };
<ide> | 1 |
Python | Python | update docstrings and types | c675746ca2ffbe13c06751cd30168c55b7d372fc | <ide><path>spacy/gold/batchers.py
<ide> def configure_minibatch_by_words(
<ide>
<ide>
<ide> @registry.batchers("batch_by_sequence.v1")
<del>def configure_minibatch(size: Sizing, get_length=None) -> BatcherT:
<add>def configure_minibatch(
<add> size: Sizing, get_length: Optional[Callable[[ItemT], int]] = None
<add>) -> BatcherT:
<ide> optionals = {"get_length": get_length} if get_length is not None else {}
<ide> return partial(minibatch, size=size, **optionals)
<ide>
<ide> def minibatch_by_words(
<ide> """Create minibatches of roughly a given number of words. If any examples
<ide> are longer than the specified batch length, they will appear in a batch by
<ide> themselves, or be discarded if discard_oversize=True.
<del> The argument 'docs' can be a list of strings, Doc's or Example's. """
<add> The argument 'docs' can be a list of strings, Docs or Examples.
<add> """
<ide> if isinstance(size, int):
<ide> size_ = itertools.repeat(size)
<ide> elif isinstance(size, List):
<ide><path>spacy/gold/corpus.py
<ide> def __call__(self, nlp: "Language") -> Iterator[Example]:
<ide> """Yield examples from the data.
<ide>
<ide> nlp (Language): The current nlp object.
<del> loc (Path): The file or directory to read from.
<ide> YIELDS (Example): The examples.
<ide>
<ide> DOCS: https://spacy.io/api/corpus#call | 2 |
Go | Go | use real root with 0701 perms | 7f5e39bd4f92ce6fcf9946aa8ccea91815c321c2 | <ide><path>daemon/container_operations_unix.go
<ide> func (daemon *Daemon) setupContainerMountsRoot(c *container.Container) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> return idtools.MkdirAllAndChown(p, 0700, daemon.idMapping.RootPair())
<add> return idtools.MkdirAllAndChown(p, 0701, idtools.CurrentIdentity())
<ide> }
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide> }
<ide> ctr.RWLayer = rwLayer
<ide>
<del> rootIDs := daemon.idMapping.RootPair()
<del>
<del> if err := idtools.MkdirAndChown(ctr.Root, 0700, rootIDs); err != nil {
<add> if err := idtools.MkdirAndChown(ctr.Root, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<del> if err := idtools.MkdirAndChown(ctr.CheckpointDir(), 0700, rootIDs); err != nil {
<add> if err := idtools.MkdirAndChown(ctr.CheckpointDir(), 0700, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>daemon/daemon.go
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> }
<ide>
<ide> daemonRepo := filepath.Join(config.Root, "containers")
<del> if err := idtools.MkdirAllAndChown(daemonRepo, 0700, rootIDs); err != nil {
<add> if err := idtools.MkdirAllAndChown(daemonRepo, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>daemon/daemon_unix.go
<ide> func setupRemappedRoot(config *config.Config) (*idtools.IdentityMapping, error)
<ide> return &idtools.IdentityMapping{}, nil
<ide> }
<ide>
<del>func setupDaemonRoot(config *config.Config, rootDir string, rootIdentity idtools.Identity) error {
<add>func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools.Identity) error {
<ide> config.Root = rootDir
<ide> // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
<ide> // so that syscalls executing as non-root, operating on subdirectories of the graph root
<ide> func setupDaemonRoot(config *config.Config, rootDir string, rootIdentity idtools
<ide> // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
<ide> // `chdir()` to work for containers namespaced to that uid/gid)
<ide> if config.RemappedRoot != "" {
<del> config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootIdentity.UID, rootIdentity.GID))
<add> id := idtools.CurrentIdentity()
<add> // First make sure the current root dir has the correct perms.
<add> if err := idtools.MkdirAllAndChown(config.Root, 0701, id); err != nil {
<add> return errors.Wrapf(err, "could not create or set daemon root permissions: %s", config.Root)
<add> }
<add>
<add> config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", remappedRoot.UID, remappedRoot.GID))
<ide> logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
<ide> // Create the root directory if it doesn't exist
<del> if err := idtools.MkdirAllAndChown(config.Root, 0700, rootIdentity); err != nil {
<add> if err := idtools.MkdirAllAndChown(config.Root, 0701, id); err != nil {
<ide> return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
<ide> }
<ide> // we also need to verify that any pre-existing directories in the path to
<ide> func setupDaemonRoot(config *config.Config, rootDir string, rootIdentity idtools
<ide> if dirPath == "/" {
<ide> break
<ide> }
<del> if !idtools.CanAccess(dirPath, rootIdentity) {
<add> if !idtools.CanAccess(dirPath, remappedRoot) {
<ide> return fmt.Errorf("a subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories", config.Root)
<ide> }
<ide> }
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> locker: locker.New(),
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, err
<del> }
<add> currentID := idtools.CurrentIdentity()
<ide> // Create the root aufs driver dir
<del> if err := idtools.MkdirAllAndChown(root, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(root, 0701, currentID); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> // Populate the dir structure
<ide> for _, p := range paths {
<del> if err := idtools.MkdirAllAndChown(path.Join(root, p), 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(path.Join(root, p), 0701, currentID); err != nil {
<ide> return nil, err
<ide> }
<ide> }
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, graphdriver.ErrPrerequisites
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, err
<del> }
<del> if err := idtools.MkdirAllAndChown(home, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(home, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err := idtools.MkdirAllAndChown(subvolumes, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(subvolumes, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return err
<ide> }
<ide> if parent == "" {
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
<ide> if err := d.setStorageSize(path.Join(subvolumes, id), driver); err != nil {
<ide> return err
<ide> }
<del> if err := idtools.MkdirAllAndChown(quotas, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(quotas, 0700, idtools.CurrentIdentity()); err != nil {
<ide> return err
<ide> }
<ide> if err := ioutil.WriteFile(path.Join(quotas, id), []byte(fmt.Sprint(driver.options.size)), 0644); err != nil {
<ide><path>daemon/graphdriver/fuse-overlayfs/fuseoverlayfs.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, graphdriver.ErrNotSupported
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, err
<del> }
<del> // Create the driver home dir
<del> if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> }
<ide> root := idtools.Identity{UID: rootUID, GID: rootGID}
<ide>
<del> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
<add> currentID := idtools.CurrentIdentity()
<add> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0701, currentID); err != nil {
<ide> return err
<ide> }
<del> if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
<add> if err := idtools.MkdirAndChown(dir, 0701, currentID); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> return nil
<ide> }
<ide>
<del> if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0700, root); err != nil {
<add> if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0701, currentID); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> logrus.WithField("storage-driver", "overlay").Warn(overlayutils.ErrDTypeNotSupported("overlay", backingFs))
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, err
<del> }
<ide> // Create the driver home dir
<del> if err := idtools.MkdirAllAndChown(home, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(home, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> }
<ide> root := idtools.Identity{UID: rootUID, GID: rootGID}
<ide>
<del> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
<add> currentID := idtools.CurrentIdentity()
<add> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0701, currentID); err != nil {
<ide> return err
<ide> }
<del> if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
<add> if err := idtools.MkdirAndChown(dir, 0701, currentID); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide>
<ide> // Toplevel images are just a "root" dir
<ide> if parent == "" {
<add> // This must be 0755 otherwise unprivileged users will in the container will not be able to read / in the container
<ide> return idtools.MkdirAndChown(path.Join(dir, "root"), 0755, root)
<ide> }
<ide>
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
<ide> return err
<ide> }
<del> return ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666)
<add> return ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0600)
<ide> }
<ide>
<ide> // Otherwise, copy the upper and the lower-id from the parent
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> return err
<ide> }
<ide>
<del> if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
<add> if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0600); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> logger.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, err
<del> }
<del> // Create the driver home dir
<del> if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
<ide> return err
<ide> }
<ide> root := idtools.Identity{UID: rootUID, GID: rootGID}
<add> current := idtools.CurrentIdentity()
<ide>
<del> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
<add> if err := idtools.MkdirAllAndChown(path.Dir(dir), 0701, current); err != nil {
<ide> return err
<ide> }
<del> if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
<add> if err := idtools.MkdirAndChown(dir, 0701, current); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>daemon/graphdriver/vfs/driver.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, err
<ide> }
<ide>
<del> rootIDs := d.idMapping.RootPair()
<del> if err := idtools.MkdirAllAndChown(home, 0700, rootIDs); err != nil {
<add> if err := idtools.MkdirAllAndChown(home, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
<ide> func (d *Driver) create(id, parent string, size uint64) error {
<ide> dir := d.dir(id)
<ide> rootIDs := d.idMapping.RootPair()
<del> if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0700, rootIDs); err != nil {
<add> if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0701, idtools.CurrentIdentity()); err != nil {
<ide> return err
<ide> }
<ide> if err := idtools.MkdirAndChown(dir, 0755, rootIDs); err != nil {
<ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func Init(base string, opt []string, uidMaps, gidMaps []idtools.IDMap) (graphdri
<ide> return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName)
<ide> }
<ide>
<del> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<del> if err != nil {
<del> return nil, fmt.Errorf("Failed to get root uid/guid: %v", err)
<del> }
<del> if err := idtools.MkdirAllAndChown(base, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
<add> if err := idtools.MkdirAllAndChown(base, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, fmt.Errorf("Failed to create '%s': %v", base, err)
<ide> }
<ide>
<ide><path>volume/local/local.go
<ide> type activeMount struct {
<ide> func New(scope string, rootIdentity idtools.Identity) (*Root, error) {
<ide> rootDirectory := filepath.Join(scope, volumesPathName)
<ide>
<del> if err := idtools.MkdirAllAndChown(rootDirectory, 0700, rootIdentity); err != nil {
<add> if err := idtools.MkdirAllAndChown(rootDirectory, 0701, idtools.CurrentIdentity()); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error
<ide> }
<ide>
<ide> path := r.DataPath(name)
<add> volRoot := filepath.Dir(path)
<add> // Root dir does not need to be accessed by the remapped root
<add> if err := idtools.MkdirAllAndChown(volRoot, 0701, idtools.CurrentIdentity()); err != nil {
<add> return nil, errors.Wrapf(errdefs.System(err), "error while creating volume root path '%s'", volRoot)
<add> }
<add>
<add> // Remapped root does need access to the data path
<ide> if err := idtools.MkdirAllAndChown(path, 0755, r.rootIdentity); err != nil {
<del> return nil, errors.Wrapf(errdefs.System(err), "error while creating volume path '%s'", path)
<add> return nil, errors.Wrapf(errdefs.System(err), "error while creating volume data path '%s'", path)
<ide> }
<ide>
<ide> var err error | 12 |
Mixed | Javascript | fix spawning from preload scripts | 360e8c842a25df0ccf8d64dbba94cc83ae66a4a1 | <ide><path>doc/api/worker_threads.md
<ide> Calling `unref()` on a worker allows the thread to exit if this is the only
<ide> active handle in the event system. If the worker is already `unref()`ed calling
<ide> `unref()` again has no effect.
<ide>
<add>## Notes
<add>
<add>### Launching worker threads from preload scripts
<add>
<add>Take care when launching worker threads from preload scripts (scripts loaded
<add>and run using the `-r` command line flag). Unless the `execArgv` option is
<add>explicitly set, new Worker threads automatically inherit the command line flags
<add>from the running process and will preload the same preload scripts as the main
<add>thread. If the preload script unconditionally launches a worker thread, every
<add>thread spawned will spawn another until the application crashes.
<add>
<ide> [Addons worker support]: addons.md#addons_worker_support
<ide> [ECMAScript module loader]: esm.md#esm_data_imports
<ide> [HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
<ide><path>lib/internal/main/worker_thread.js
<ide> port.on('message', (message) => {
<ide> initializeCJSLoader();
<ide> initializeESMLoader();
<ide>
<del> const CJSLoader = require('internal/modules/cjs/loader');
<del> assert(!CJSLoader.hasLoadedAnyUserCJSModule);
<del> loadPreloadModules();
<del> initializeFrozenIntrinsics();
<ide> if (argv !== undefined) {
<ide> ArrayPrototypePushApply(process.argv, argv);
<ide> }
<ide> port.on('message', (message) => {
<ide> };
<ide> workerIo.sharedCwdCounter = cwdCounter;
<ide>
<add> const CJSLoader = require('internal/modules/cjs/loader');
<add> assert(!CJSLoader.hasLoadedAnyUserCJSModule);
<add> loadPreloadModules();
<add> initializeFrozenIntrinsics();
<add>
<ide> if (!hasStdin)
<ide> process.stdin.push(null);
<ide>
<ide><path>test/fixtures/worker-preload.js
<add>const {
<add> Worker,
<add> workerData,
<add> threadId
<add>} = require('worker_threads');
<add>
<add>if (threadId < 2) {
<add> new Worker('1 + 1', { eval: true });
<add>}
<ide><path>test/parallel/test-preload-worker.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<add>const worker = fixtures.path('worker-preload.js');
<add>const { exec } = require('child_process');
<add>const kNodeBinary = process.argv[0];
<add>
<add>
<add>exec(`"${kNodeBinary}" -r "${worker}" -pe "1+1"`, common.mustSucceed()); | 4 |
Javascript | Javascript | remove null sibling | 80d39d8b5733d4ab22033aaf8b805de723e28fd1 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> function detachFiber(fiber: Fiber) {
<ide> // get GC:ed but we don't know which for sure which parent is the current
<ide> // one so we'll settle for GC:ing the subtree of this child. This child
<ide> // itself will be GC:ed when the parent updates the next time.
<add> // Note: we cannot null out sibling here, otherwise it can cause issues
<add> // with findDOMNode and how it requires the sibling field to carry out
<add> // traversal in a later effect. See PR #16820.
<ide> fiber.alternate = null;
<ide> fiber.child = null;
<ide> fiber.dependencies = null;
<ide> function detachFiber(fiber: Fiber) {
<ide> fiber.memoizedState = null;
<ide> fiber.pendingProps = null;
<ide> fiber.return = null;
<del> fiber.sibling = null;
<ide> fiber.stateNode = null;
<ide> fiber.updateQueue = null;
<ide> if (__DEV__) {
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js
<ide> function detachFiber(fiber: Fiber) {
<ide> // get GC:ed but we don't know which for sure which parent is the current
<ide> // one so we'll settle for GC:ing the subtree of this child. This child
<ide> // itself will be GC:ed when the parent updates the next time.
<add> // Note: we cannot null out sibling here, otherwise it can cause issues
<add> // with findDOMNode and how it requires the sibling field to carry out
<add> // traversal in a later effect. See PR #16820.
<ide> fiber.alternate = null;
<ide> fiber.child = null;
<ide> fiber.dependencies = null;
<ide> function detachFiber(fiber: Fiber) {
<ide> fiber.memoizedState = null;
<ide> fiber.pendingProps = null;
<ide> fiber.return = null;
<del> fiber.sibling = null;
<ide> fiber.stateNode = null;
<ide> fiber.updateQueue = null;
<ide> if (__DEV__) { | 2 |
Javascript | Javascript | verify order of error in h2 server stream | e03bcb126152fdef68c8509e7e95a2b4b4e93fd9 | <ide><path>test/parallel/test-http2-error-order.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const assert = require('assert');
<add>const { createServer, connect } = require('http2');
<add>
<add>const messages = [];
<add>const expected = [
<add> 'Stream:created',
<add> 'Stream:error',
<add> 'Stream:close',
<add> 'Request:error'
<add>];
<add>
<add>const server = createServer();
<add>
<add>server.on('stream', (stream) => {
<add> messages.push('Stream:created');
<add> stream
<add> .on('close', () => messages.push('Stream:close'))
<add> .on('error', (err) => messages.push('Stream:error'))
<add> .respondWithFile('dont exist');
<add>});
<add>
<add>server.listen(0);
<add>
<add>const client = connect(`http://localhost:${server.address().port}`);
<add>const req = client.request();
<add>
<add>req.on('response', common.mustNotCall());
<add>
<add>req.on('error', () => {
<add> messages.push('Request:error');
<add> client.close();
<add>});
<add>
<add>client.on('close', common.mustCall(() => {
<add> assert.deepStrictEqual(messages, expected);
<add> server.close();
<add>})); | 1 |
Javascript | Javascript | add openssl 3.0 checks to tls-passphrase | f00c2435922a33f9d866846d0b5d12691b148348 | <ide><path>test/parallel/test-tls-passphrase.js
<ide> server.listen(0, common.mustCall(function() {
<ide> })).unref();
<ide>
<ide> const errMessagePassword = common.hasOpenSSL3 ?
<del> /processing error/ : /bad decrypt/;
<add> /Error: PEM_read_bio_PrivateKey/ : /bad decrypt/;
<ide>
<ide> // Missing passphrase
<ide> assert.throws(function() {
<ide> assert.throws(function() {
<ide> });
<ide> }, errMessagePassword);
<ide>
<del>const errMessageDecrypt = /bad decrypt/;
<add>const errMessageDecrypt = common.hasOpenSSL3 ?
<add> /Error: PEM_read_bio_PrivateKey/ : /bad decrypt/;
<ide>
<ide> // Invalid passphrase
<ide> assert.throws(function() { | 1 |
Text | Text | add me-br to who uses airflow list | c328871a0415431f6753a3b9718238b847925f54 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Mercadoni](https://www.mercadoni.com.co) [[@demorenoc](https://github.com/demorenoc)]
<ide> 1. [Mercari](http://www.mercari.com/) [[@yu-iskw](https://github.com/yu-iskw)]
<ide> 1. [MFG Labs](https://github.com/MfgLabs)
<add>1. [Ministry of Economy of Brazil](https://www.gov.br/economia/) [[@nitaibezerra](https://github.com/nitaibezerra), [@vitorbellini](https://github.com/vitorbellini)]
<ide> 1. [MiNODES](https://www.minodes.com) [[@dice89](https://github.com/dice89), [@diazcelsa](https://github.com/diazcelsa)]
<ide> 1. [Modernizing Medicine](https://www.modmed.com/)[[@kehv1n](https://github.com/kehv1n), [@dalupus](https://github.com/dalupus)]
<ide> 1. [Movember](https://movember.com) | 1 |
PHP | PHP | environment() | 9149adac43f02be1fe12513e3613853bcd72d860 | <ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testSingleProviderCanProvideMultipleDeferredServices()
<ide> $this->assertEquals('foobar', $app->make('bar'));
<ide> }
<ide>
<add>
<add> public function testEnvironment()
<add> {
<add> $app = new Application;
<add> $app['env'] = 'foo';
<add>
<add> $this->assertEquals('foo', $app->environment());
<add>
<add> $this->assertTrue($app->environment('foo'));
<add> $this->assertTrue($app->environment('foo', 'bar'));
<add> $this->assertTrue($app->environment(['foo', 'bar']));
<add>
<add> $this->assertFalse($app->environment('qux'));
<add> $this->assertFalse($app->environment('qux', 'bar'));
<add> $this->assertFalse($app->environment(['qux', 'bar']));
<add> }
<add>
<ide> }
<ide>
<ide> class ApplicationCustomExceptionHandlerStub extends Illuminate\Foundation\Application { | 1 |
Text | Text | remove duplicates repo from acceptable formula doc | 251270e9a3311fccc1b6c56a74cb2cecdfffb4a2 | <ide><path>docs/Acceptable-Formulae.md
<ide> There are exceptions:
<ide> | openssl | macOS's openssl is deprecated & outdated |
<ide> | libxml2 | Historically, macOS's libxml2 has been buggy |
<ide>
<del>We also maintain [a tap](https://github.com/Homebrew/homebrew-dupes) that
<del>contains many duplicates not otherwise found in Homebrew.
<del>
<ide> ### We don’t like tools that upgrade themselves
<ide> Software that can upgrade itself does not integrate well with Homebrew's own
<ide> upgrade functionality. | 1 |
Ruby | Ruby | remove unused variables to avoid warnings | b1f8ba138360cd67994d4134f57abca74f8528bc | <ide><path>actionpack/test/template/date_helper_test.rb
<ide> def test_date_select_with_nil_and_blank_and_discard_month
<ide> def test_date_select_with_nil_and_blank_and_discard_year
<ide> @post = Post.new
<ide>
<del> start_year = Time.now.year-5
<del> end_year = Time.now.year+5
<del>
<ide> expected = '<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="1" />' + "\n"
<ide>
<ide> expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} | 1 |
Python | Python | remove double bias | 94ff2d6ee8280c5595b92c1128c0f18e44925e56 | <ide><path>src/transformers/modeling_albert.py
<ide> def forward(self, hidden_states):
<ide> hidden_states = self.LayerNorm(hidden_states)
<ide> hidden_states = self.decoder(hidden_states)
<ide>
<del> prediction_scores = hidden_states + self.bias
<add> prediction_scores = hidden_states
<ide>
<ide> return prediction_scores
<ide>
<ide><path>src/transformers/modeling_bert.py
<ide> def __init__(self, config):
<ide>
<ide> def forward(self, hidden_states):
<ide> hidden_states = self.transform(hidden_states)
<del> hidden_states = self.decoder(hidden_states) + self.bias
<add> hidden_states = self.decoder(hidden_states)
<ide> return hidden_states
<ide>
<ide>
<ide><path>src/transformers/modeling_roberta.py
<ide> def forward(self, features, **kwargs):
<ide> x = self.layer_norm(x)
<ide>
<ide> # project back to size of vocabulary with bias
<del> x = self.decoder(x) + self.bias
<add> x = self.decoder(x)
<ide>
<ide> return x
<ide> | 3 |
PHP | PHP | add core namespace | af1ed62ba8b9c3b432829739f76934fd0119a11d | <ide><path>src/Command/HelpCommand.php
<ide> protected function asText($io, $commands)
<ide> foreach ($invert as $class => $names) {
<ide> $prefixedName = $this->findPrefixedName($names);
<ide> if (!$prefixedName) {
<del> $prefixed['[app]'][] = $this->getShortestName($names);
<add> $prefix = preg_match('#^Cake\\\\(Command|Shell)\\\\#', $class) ? '[core]' : '[app]';
<add> $prefixed[$prefix][] = $this->getShortestName($names);
<ide> continue;
<ide> }
<ide> | 1 |
Java | Java | simplify oss enums | c5186aeb461a6eafa582b0acba1b3cebfb83550b | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/AccessibilityDelegateUtil.java
<ide> public class AccessibilityDelegateUtil {
<ide> */
<ide>
<ide> public enum AccessibilityRole {
<del> NONE(null),
<del> BUTTON("android.widget.Button"),
<del> LINK("android.widget.ViewGroup"),
<del> SEARCH("android.widget.EditText"),
<del> IMAGE("android.widget.ImageView"),
<del> IMAGEBUTTON("android.widget.ImageView"),
<del> KEYBOARDKEY("android.inputmethodservice.Keyboard$Key"),
<del> TEXT("android.widget.ViewGroup"),
<del> ADJUSTABLE("android.widget.SeekBar"),
<del> SUMMARY("android.widget.ViewGroup"),
<del> HEADER("android.widget.ViewGroup");
<del>
<del> @Nullable private final String mValue;
<del>
<del> AccessibilityRole(String type) {
<del> mValue = type;
<del> }
<del>
<del> @Nullable
<del> public String getValue() {
<del> return mValue;
<add> NONE,
<add> BUTTON,
<add> LINK,
<add> SEARCH,
<add> IMAGE,
<add> IMAGEBUTTON,
<add> KEYBOARDKEY,
<add> TEXT,
<add> ADJUSTABLE,
<add> SUMMARY,
<add> HEADER;
<add>
<add> public static String getValue(AccessibilityRole role) {
<add> switch (role) {
<add> case NONE:
<add> return null;
<add> case BUTTON:
<add> return "android.widget.Button";
<add> case LINK:
<add> return "android.widget.ViewGroup";
<add> case SEARCH:
<add> return "android.widget.EditText";
<add> case IMAGE:
<add> return "android.widget.ImageView";
<add> case IMAGEBUTTON:
<add> return "android.widget.ImageView";
<add> case KEYBOARDKEY:
<add> return "android.inputmethodservice.Keyboard$Key";
<add> case TEXT:
<add> return "android.widget.ViewGroup";
<add> case ADJUSTABLE:
<add> return "android.widget.SeekBar";
<add> case SUMMARY:
<add> return "android.widget.ViewGroup";
<add> case HEADER:
<add> return "android.widget.ViewGroup";
<add> default:
<add> throw new IllegalArgumentException("Invalid accessibility role value: " + role);
<add> }
<ide> }
<ide>
<del> public static AccessibilityRole fromValue(String value) {
<add> public static AccessibilityRole fromValue(@Nullable String value) {
<ide> for (AccessibilityRole role : AccessibilityRole.values()) {
<ide> if (role.name().equalsIgnoreCase(value)) {
<ide> return role;
<ide> public static void setRole(AccessibilityNodeInfoCompat nodeInfo, AccessibilityRo
<ide> if (role == null) {
<ide> role = AccessibilityRole.NONE;
<ide> }
<del> nodeInfo.setClassName(role.getValue());
<add> nodeInfo.setClassName(AccessibilityRole.getValue(role));
<ide> if (Locale.getDefault().getLanguage().equals(new Locale("en").getLanguage())) {
<ide> if (role.equals(AccessibilityRole.LINK)) {
<ide> nodeInfo.setRoleDescription(context.getString(R.string.link_description));
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java
<ide> "phasedRegistrationNames",
<ide> MapBuilder.of("bubbled", "onSelect", "captured", "onSelectCapture")))
<ide> .put(
<del> TouchEventType.START.getJSEventName(),
<add> TouchEventType.getJSEventName(TouchEventType.START),
<ide> MapBuilder.of(
<ide> "phasedRegistrationNames",
<ide> MapBuilder.of(
<ide> "captured",
<ide> "onTouchStartCapture")))
<ide> .put(
<del> TouchEventType.MOVE.getJSEventName(),
<add> TouchEventType.getJSEventName(TouchEventType.MOVE),
<ide> MapBuilder.of(
<ide> "phasedRegistrationNames",
<ide> MapBuilder.of(
<ide> "captured",
<ide> "onTouchMoveCapture")))
<ide> .put(
<del> TouchEventType.END.getJSEventName(),
<add> TouchEventType.getJSEventName(TouchEventType.END),
<ide> MapBuilder.of(
<ide> "phasedRegistrationNames",
<ide> MapBuilder.of(
<ide> "captured",
<ide> "onTouchEndCapture")))
<ide> .put(
<del> TouchEventType.CANCEL.getJSEventName(),
<add> TouchEventType.getJSEventName(TouchEventType.CANCEL),
<ide> MapBuilder.of(
<ide> "phasedRegistrationNames",
<ide> MapBuilder.of(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEvent.java
<ide> public void onDispose() {
<ide>
<ide> @Override
<ide> public String getEventName() {
<del> return Assertions.assertNotNull(mTouchEventType).getJSEventName();
<add> return TouchEventType.getJSEventName(Assertions.assertNotNull(mTouchEventType));
<ide> }
<ide>
<ide> @Override
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventType.java
<ide> * Touch event types that JS module RCTEventEmitter can understand
<ide> */
<ide> public enum TouchEventType {
<del> START("topTouchStart"),
<del> END("topTouchEnd"),
<del> MOVE("topTouchMove"),
<del> CANCEL("topTouchCancel");
<add> START,
<add> END,
<add> MOVE,
<add> CANCEL;
<ide>
<del> private final String mJSEventName;
<del>
<del> TouchEventType(String jsEventName) {
<del> mJSEventName = jsEventName;
<del> }
<del>
<del> public String getJSEventName() {
<del> return mJSEventName;
<add> public static String getJSEventName(TouchEventType type) {
<add> switch (type) {
<add> case START:
<add> return "topTouchStart";
<add> case END:
<add> return "topTouchEnd";
<add> case MOVE:
<add> return "topTouchMove";
<add> case CANCEL:
<add> return "topTouchCancel";
<add> default:
<add> throw new IllegalArgumentException("Unexpected type " + type);
<add> }
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchesHelper.java
<ide> public static void sendTouchEvent(
<ide> }
<ide>
<ide> rctEventEmitter.receiveTouches(
<del> type.getJSEventName(),
<add> TouchEventType.getJSEventName(type),
<ide> pointers,
<ide> changedIndices);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AnimatedPropertyType.java
<ide> * view creation.
<ide> */
<ide> /* package */ enum AnimatedPropertyType {
<del> OPACITY("opacity"),
<del> SCALE_X("scaleX"),
<del> SCALE_Y("scaleY"),
<del> SCALE_XY("scaleXY");
<del>
<del> private final String mName;
<del>
<del> private AnimatedPropertyType(String name) {
<del> mName = name;
<del> }
<add> OPACITY,
<add> SCALE_X,
<add> SCALE_Y,
<add> SCALE_XY;
<ide>
<ide> public static AnimatedPropertyType fromString(String name) {
<del> for (AnimatedPropertyType property : AnimatedPropertyType.values()) {
<del> if (property.toString().equalsIgnoreCase(name)) {
<del> return property;
<del> }
<add> switch (name) {
<add> case "opacity":
<add> return OPACITY;
<add> case "scaleX":
<add> return SCALE_X;
<add> case "scaleY":
<add> return SCALE_Y;
<add> case "scaleXY":
<add> return SCALE_XY;
<add> default:
<add> throw new IllegalArgumentException("Unsupported animated property: " + name);
<ide> }
<del> throw new IllegalArgumentException("Unsupported animated property : " + name);
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> return mName;
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/InterpolatorType.java
<ide> * Enum representing the different interpolators that can be used in layout animation configuration.
<ide> */
<ide> /* package */ enum InterpolatorType {
<del> LINEAR("linear"),
<del> EASE_IN("easeIn"),
<del> EASE_OUT("easeOut"),
<del> EASE_IN_EASE_OUT("easeInEaseOut"),
<del> SPRING("spring");
<del>
<del> private final String mName;
<del>
<del> private InterpolatorType(String name) {
<del> mName = name;
<del> }
<add> LINEAR,
<add> EASE_IN,
<add> EASE_OUT,
<add> EASE_IN_EASE_OUT,
<add> SPRING;
<ide>
<ide> public static InterpolatorType fromString(String name) {
<del> for (InterpolatorType type : InterpolatorType.values()) {
<del> if (type.toString().equalsIgnoreCase(name)) {
<del> return type;
<del> }
<add> switch (name.toLowerCase()) {
<add> case "linear":
<add> return LINEAR;
<add> case "easein":
<add> return EASE_IN;
<add> case "easeout":
<add> return EASE_OUT;
<add> case "easeineaseout":
<add> return EASE_IN_EASE_OUT;
<add> case "spring":
<add> return SPRING;
<add> default:
<add> throw new IllegalArgumentException("Unsupported interpolation type : " + name);
<ide> }
<del> throw new IllegalArgumentException("Unsupported interpolation type : " + name);
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> return mName;
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java
<ide> public void initializeFromConfig(final @Nullable ReadableMap config) {
<ide>
<ide> mShouldAnimateLayout = false;
<ide> int globalDuration = config.hasKey("duration") ? config.getInt("duration") : 0;
<del> if (config.hasKey(LayoutAnimationType.CREATE.toString())) {
<add> if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.CREATE))) {
<ide> mLayoutCreateAnimation.initializeFromConfig(
<del> config.getMap(LayoutAnimationType.CREATE.toString()), globalDuration);
<add> config.getMap(LayoutAnimationType.toString(LayoutAnimationType.CREATE)), globalDuration);
<ide> mShouldAnimateLayout = true;
<ide> }
<del> if (config.hasKey(LayoutAnimationType.UPDATE.toString())) {
<add> if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.UPDATE))) {
<ide> mLayoutUpdateAnimation.initializeFromConfig(
<del> config.getMap(LayoutAnimationType.UPDATE.toString()), globalDuration);
<add> config.getMap(LayoutAnimationType.toString(LayoutAnimationType.UPDATE)), globalDuration);
<ide> mShouldAnimateLayout = true;
<ide> }
<del> if (config.hasKey(LayoutAnimationType.DELETE.toString())) {
<add> if (config.hasKey(LayoutAnimationType.toString(LayoutAnimationType.DELETE))) {
<ide> mLayoutDeleteAnimation.initializeFromConfig(
<del> config.getMap(LayoutAnimationType.DELETE.toString()), globalDuration);
<add> config.getMap(LayoutAnimationType.toString(LayoutAnimationType.DELETE)), globalDuration);
<ide> mShouldAnimateLayout = true;
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationType.java
<ide> * Enum representing the different animation type that can be specified in layout animation config.
<ide> */
<ide> /* package */ enum LayoutAnimationType {
<del> CREATE("create"),
<del> UPDATE("update"),
<del> DELETE("delete");
<add> CREATE,
<add> UPDATE,
<add> DELETE;
<ide>
<del> private final String mName;
<del>
<del> private LayoutAnimationType(String name) {
<del> mName = name;
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> return mName;
<add> public static String toString(LayoutAnimationType type) {
<add> switch (type) {
<add> case CREATE:
<add> return "create";
<add> case UPDATE:
<add> return "update";
<add> case DELETE:
<add> return "delete";
<add> default:
<add> throw new IllegalArgumentException("Unsupported LayoutAnimationType: " + type);
<add> }
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java
<ide> public void scrollToEnd(
<ide>
<ide> public static Map<String, Object> createExportedCustomDirectEventTypeConstants() {
<ide> return MapBuilder.<String, Object>builder()
<del> .put(ScrollEventType.SCROLL.getJSEventName(), MapBuilder.of("registrationName", "onScroll"))
<del> .put(ScrollEventType.BEGIN_DRAG.getJSEventName(), MapBuilder.of("registrationName", "onScrollBeginDrag"))
<del> .put(ScrollEventType.END_DRAG.getJSEventName(), MapBuilder.of("registrationName", "onScrollEndDrag"))
<del> .put(ScrollEventType.MOMENTUM_BEGIN.getJSEventName(), MapBuilder.of("registrationName", "onMomentumScrollBegin"))
<del> .put(ScrollEventType.MOMENTUM_END.getJSEventName(), MapBuilder.of("registrationName", "onMomentumScrollEnd"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.SCROLL), MapBuilder.of("registrationName", "onScroll"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.BEGIN_DRAG), MapBuilder.of("registrationName", "onScrollBeginDrag"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.END_DRAG), MapBuilder.of("registrationName", "onScrollEndDrag"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_BEGIN), MapBuilder.of("registrationName", "onMomentumScrollBegin"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_END), MapBuilder.of("registrationName", "onMomentumScrollEnd"))
<ide> .build();
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java
<ide> private void init(
<ide>
<ide> @Override
<ide> public String getEventName() {
<del> return Assertions.assertNotNull(mScrollEventType).getJSEventName();
<add> return ScrollEventType.getJSEventName(Assertions.assertNotNull(mScrollEventType));
<ide> }
<ide>
<ide> @Override
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEventType.java
<ide> * Scroll event types that JS module RCTEventEmitter can understand
<ide> */
<ide> public enum ScrollEventType {
<del> BEGIN_DRAG("topScrollBeginDrag"),
<del> END_DRAG("topScrollEndDrag"),
<del> SCROLL("topScroll"),
<del> MOMENTUM_BEGIN("topMomentumScrollBegin"),
<del> MOMENTUM_END("topMomentumScrollEnd");
<add> BEGIN_DRAG,
<add> END_DRAG,
<add> SCROLL,
<add> MOMENTUM_BEGIN,
<add> MOMENTUM_END;
<ide>
<del> private final String mJSEventName;
<del>
<del> ScrollEventType(String jsEventName) {
<del> mJSEventName = jsEventName;
<del> }
<del>
<del> public String getJSEventName() {
<del> return mJSEventName;
<add> public static String getJSEventName(ScrollEventType type) {
<add> switch (type) {
<add> case BEGIN_DRAG:
<add> return "topScrollBeginDrag";
<add> case END_DRAG:
<add> return "topScrollEndDrag";
<add> case SCROLL:
<add> return "topScroll";
<add> case MOMENTUM_BEGIN:
<add> return "topMomentumScrollBegin";
<add> case MOMENTUM_END:
<add> return "topMomentumScrollEnd";
<add> default:
<add> throw new IllegalArgumentException("Unsupported ScrollEventType: " + type);
<add> }
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
<ide> @Override
<ide> public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
<ide> return MapBuilder.<String, Object>builder()
<del> .put(ScrollEventType.SCROLL.getJSEventName(), MapBuilder.of("registrationName", "onScroll"))
<add> .put(ScrollEventType.getJSEventName(ScrollEventType.SCROLL), MapBuilder.of("registrationName", "onScroll"))
<ide> .build();
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java
<ide> public class ReactViewBackgroundDrawable extends Drawable {
<ide> // 0 == 0x00000000, all bits set to 0.
<ide> private static final int ALL_BITS_UNSET = 0;
<ide>
<del> private static enum BorderStyle {
<add> private enum BorderStyle {
<ide> SOLID,
<ide> DASHED,
<ide> DOTTED;
<ide>
<del> public @Nullable PathEffect getPathEffect(float borderWidth) {
<del> switch (this) {
<add> public static @Nullable PathEffect getPathEffect(BorderStyle style, float borderWidth) {
<add> switch (style) {
<ide> case SOLID:
<ide> return null;
<ide>
<ide> public float getBorderWidthOrDefaultTo(final float defaultValue, final int spaci
<ide> */
<ide> private void updatePathEffect() {
<ide> mPathEffectForBorderStyle = mBorderStyle != null
<del> ? mBorderStyle.getPathEffect(getFullBorderWidth())
<add> ? BorderStyle.getPathEffect(mBorderStyle, getFullBorderWidth())
<ide> : null;
<ide>
<ide> mPaint.setPathEffect(mPathEffectForBorderStyle); | 14 |
Javascript | Javascript | fix comment typo, thanks @aurelioderosa | bb3fff9ac2c7c8b07809219305d7f86d282fd84f | <ide><path>src/offset.js
<ide> jQuery.fn.extend({
<ide> elem = this[ 0 ],
<ide> parentOffset = { top: 0, left: 0 };
<ide>
<del> // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
<add> // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
<ide> if ( jQuery.css( elem, "position" ) === "fixed" ) {
<ide> // We assume that getBoundingClientRect is available when computed position is fixed
<ide> offset = elem.getBoundingClientRect(); | 1 |
Text | Text | update version references in the readme | fcd4be393365a480654aace0e4c0996bfe612ba6 | <ide><path>README.md
<ide> The fastest way to get started is to serve JavaScript from the CDN (also availab
<ide>
<ide> ```html
<ide> <!-- The core React library -->
<del><script src="http://fb.me/react-0.11.2.js"></script>
<add><script src="http://fb.me/react-0.12.0.js"></script>
<ide> <!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<del><script src="http://fb.me/JSXTransformer-0.11.2.js"></script>
<add><script src="http://fb.me/JSXTransformer-0.12.0.js"></script>
<ide> ```
<ide>
<del>We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.11.2.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
<add>We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.12.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
<ide>
<ide> If you'd like to use [bower](http://bower.io), it's as easy as:
<ide> | 1 |
Ruby | Ruby | add predicate methods to tab to match buildoptions | f1cf62a4b5997fd86153d1c66963418bae46368c | <ide><path>Library/Homebrew/tab.rb
<ide> def self.dummy_tab f=nil
<ide>
<ide> def with? name
<ide> if options.include? "with-#{name}"
<del> used_options.include? "with-#{name}"
<add> include? "with-#{name}"
<ide> elsif options.include? "without-#{name}"
<del> not used_options.include? "without-#{name}"
<add> not include? "without-#{name}"
<ide> else
<ide> false
<ide> end
<ide> def include? opt
<ide> end
<ide>
<ide> def universal?
<del> used_options.include? "universal"
<add> include?("universal")
<add> end
<add>
<add> def cxx11?
<add> include?("c++11")
<add> end
<add>
<add> def build_32_bit?
<add> include?("32-bit")
<ide> end
<ide>
<ide> def used_options | 1 |
Go | Go | remove solaris files | 1589cc0a85396e2768bfe9e558c7c2100dc3bc87 | <ide><path>cmd/dockerd/config_solaris.go
<del>package main
<del>
<del>import (
<del> "github.com/docker/docker/daemon/config"
<del> "github.com/spf13/pflag"
<del>)
<del>
<del>// installConfigFlags adds flags to the pflag.FlagSet to configure the daemon
<del>func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) {
<del> // First handle install flags which are consistent cross-platform
<del> installCommonConfigFlags(conf, flags)
<del>
<del> // Then install flags common to unix platforms
<del> installUnixConfigFlags(conf, flags)
<del>}
<ide><path>container/state_solaris.go
<del>package container
<del>
<del>// setFromExitStatus is a platform specific helper function to set the state
<del>// based on the ExitStatus structure.
<del>func (s *State) setFromExitStatus(exitStatus *ExitStatus) {
<del> s.ExitCodeValue = exitStatus.ExitCode
<del>}
<ide><path>daemon/cluster/listen_addr_linux.go
<del>// +build linux
<del>
<ide> package cluster
<ide>
<ide> import (
<ide><path>daemon/cluster/listen_addr_solaris.go
<del>package cluster
<del>
<del>import (
<del> "bufio"
<del> "fmt"
<del> "net"
<del> "os/exec"
<del> "strings"
<del>)
<del>
<del>func (c *Cluster) resolveSystemAddr() (net.IP, error) {
<del> defRouteCmd := "/usr/sbin/ipadm show-addr -p -o addr " +
<del> "`/usr/sbin/route get default | /usr/bin/grep interface | " +
<del> "/usr/bin/awk '{print $2}'`"
<del> out, err := exec.Command("/usr/bin/bash", "-c", defRouteCmd).Output()
<del> if err != nil {
<del> return nil, fmt.Errorf("cannot get default route: %v", err)
<del> }
<del>
<del> defInterface := strings.SplitN(string(out), "/", 2)
<del> defInterfaceIP := net.ParseIP(defInterface[0])
<del>
<del> return defInterfaceIP, nil
<del>}
<del>
<del>func listSystemIPs() []net.IP {
<del> var systemAddrs []net.IP
<del> cmd := exec.Command("/usr/sbin/ipadm", "show-addr", "-p", "-o", "addr")
<del> cmdReader, err := cmd.StdoutPipe()
<del> if err != nil {
<del> return nil
<del> }
<del>
<del> if err := cmd.Start(); err != nil {
<del> return nil
<del> }
<del>
<del> scanner := bufio.NewScanner(cmdReader)
<del> go func() {
<del> for scanner.Scan() {
<del> text := scanner.Text()
<del> nameAddrPair := strings.SplitN(text, "/", 2)
<del> // Let go of loopback interfaces and docker interfaces
<del> systemAddrs = append(systemAddrs, net.ParseIP(nameAddrPair[0]))
<del> }
<del> }()
<del>
<del> if err := scanner.Err(); err != nil {
<del> fmt.Printf("scan underwent err: %+v\n", err)
<del> }
<del>
<del> if err := cmd.Wait(); err != nil {
<del> fmt.Printf("run command wait: %+v\n", err)
<del> }
<del>
<del> return systemAddrs
<del>}
<ide><path>daemon/config/config_solaris.go
<del>package config
<del>
<del>// Config defines the configuration of a docker daemon.
<del>// These are the configuration settings that you pass
<del>// to the docker daemon when you launch it with say: `docker -d -e lxc`
<del>type Config struct {
<del> CommonConfig
<del>
<del> // These fields are common to all unix platforms.
<del> CommonUnixConfig
<del>}
<del>
<del>// BridgeConfig stores all the bridge driver specific
<del>// configuration.
<del>type BridgeConfig struct {
<del> commonBridgeConfig
<del>
<del> // Fields below here are platform specific.
<del> commonUnixBridgeConfig
<del>}
<del>
<del>// IsSwarmCompatible defines if swarm mode can be enabled in this config
<del>func (conf *Config) IsSwarmCompatible() error {
<del> return nil
<del>}
<del>
<del>// ValidatePlatformConfig checks if any platform-specific configuration settings are invalid.
<del>func (conf *Config) ValidatePlatformConfig() error {
<del> return nil
<del>}
<ide><path>daemon/exec_solaris.go
<del>package daemon
<del>
<del>import (
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/daemon/exec"
<del> specs "github.com/opencontainers/runtime-spec/specs-go"
<del>)
<del>
<del>func (daemon *Daemon) execSetPlatformOpt(_ *container.Container, _ *exec.Config, _ *specs.Process) error {
<del> return nil
<del>}
<add><path>daemon/inspect_linux.go
<del><path>daemon/inspect_unix.go
<del>// +build !windows
<del>
<ide> package daemon
<ide>
<ide> import (
<ide><path>daemon/inspect_solaris.go
<del>package daemon
<del>
<del>import (
<del> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/api/types/backend"
<del> "github.com/docker/docker/api/types/versions/v1p19"
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/daemon/exec"
<del>)
<del>
<del>// This sets platform-specific fields
<del>func setPlatformSpecificContainerFields(container *container.Container, contJSONBase *types.ContainerJSONBase) *types.ContainerJSONBase {
<del> return contJSONBase
<del>}
<del>
<del>// containerInspectPre120 get containers for pre 1.20 APIs.
<del>func (daemon *Daemon) containerInspectPre120(name string) (*v1p19.ContainerJSON, error) {
<del> return &v1p19.ContainerJSON{}, nil
<del>}
<del>
<del>func inspectExecProcessConfig(e *exec.Config) *backend.ExecProcessConfig {
<del> return &backend.ExecProcessConfig{
<del> Tty: e.Tty,
<del> Entrypoint: e.Entrypoint,
<del> Arguments: e.Args,
<del> }
<del>}
<add><path>daemon/listeners/listeners_linux.go
<del><path>daemon/listeners/listeners_unix.go
<del>// +build !windows
<del>
<ide> package listeners
<ide>
<ide> import (
<ide><path>daemon/listeners/listeners_solaris.go
<del>package listeners
<del>
<del>import (
<del> "crypto/tls"
<del> "fmt"
<del> "net"
<del> "os"
<del>
<del> "github.com/docker/go-connections/sockets"
<del> "github.com/sirupsen/logrus"
<del>)
<del>
<del>// Init creates new listeners for the server.
<del>func Init(proto, addr, socketGroup string, tlsConfig *tls.Config) (ls []net.Listener, err error) {
<del> switch proto {
<del> case "tcp":
<del> l, err := sockets.NewTCPSocket(addr, tlsConfig)
<del> if err != nil {
<del> return nil, err
<del> }
<del> ls = append(ls, l)
<del> case "unix":
<del> gid, err := lookupGID(socketGroup)
<del> if err != nil {
<del> if socketGroup != "" {
<del> if socketGroup != defaultSocketGroup {
<del> return nil, err
<del> }
<del> logrus.Warnf("could not change group %s to %s: %v", addr, defaultSocketGroup, err)
<del> }
<del> gid = os.Getgid()
<del> }
<del> l, err := sockets.NewUnixSocket(addr, gid)
<del> if err != nil {
<del> return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
<del> }
<del> ls = append(ls, l)
<del> default:
<del> return nil, fmt.Errorf("Invalid protocol format: %q", proto)
<del> }
<del>
<del> return
<del>}
<ide><path>daemon/monitor_solaris.go
<del>package daemon
<del>
<del>import (
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/libcontainerd"
<del>)
<del>
<del>// postRunProcessing perfoms any processing needed on the container after it has stopped.
<del>func (daemon *Daemon) postRunProcessing(_ *container.Container, _ libcontainerd.EventInfo) error {
<del> return nil
<del>}
<ide><path>daemon/update_linux.go
<del>// +build linux
<del>
<ide> package daemon
<ide>
<ide> import (
<ide><path>daemon/update_solaris.go
<del>package daemon
<del>
<del>import (
<del> "github.com/docker/docker/api/types/container"
<del> "github.com/docker/docker/libcontainerd"
<del>)
<del>
<del>func toContainerdResources(resources container.Resources) libcontainerd.Resources {
<del> var r libcontainerd.Resources
<del> return r
<del>}
<ide><path>daemon/update_windows.go
<del>// +build windows
<del>
<ide> package daemon
<ide>
<ide> import (
<ide><path>plugin/manager_linux.go
<del>// +build linux
<del>
<ide> package plugin
<ide>
<ide> import (
<ide><path>plugin/manager_solaris.go
<del>package plugin
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/plugin/v2"
<del> specs "github.com/opencontainers/runtime-spec/specs-go"
<del>)
<del>
<del>func (pm *Manager) enable(p *v2.Plugin, c *controller, force bool) error {
<del> return fmt.Errorf("Not implemented")
<del>}
<del>
<del>func (pm *Manager) initSpec(p *v2.Plugin) (*specs.Spec, error) {
<del> return nil, fmt.Errorf("Not implemented")
<del>}
<del>
<del>func (pm *Manager) disable(p *v2.Plugin, c *controller) error {
<del> return fmt.Errorf("Not implemented")
<del>}
<del>
<del>func (pm *Manager) restore(p *v2.Plugin) error {
<del> return fmt.Errorf("Not implemented")
<del>}
<del>
<del>// Shutdown plugins
<del>func (pm *Manager) Shutdown() {
<del>}
<del>
<del>func setupRoot(root string) error { return nil }
<ide><path>plugin/manager_windows.go
<del>// +build windows
<del>
<ide> package plugin
<ide>
<ide> import ( | 17 |
Javascript | Javascript | return the property we're actually setting | 1def646e099fc0e4d209fef06a75e5003ad479f2 | <ide><path>src/text-editor.js
<ide> class TextEditor {
<ide> this.update({enableKeyboardInput: enabled})
<ide> }
<ide>
<del> isKeyboardInputEnabled () { return this.keyboardInputEnabled }
<add> isKeyboardInputEnabled () { return this.enableKeyboardInput }
<ide>
<ide> onDidChangeMini (callback) {
<ide> return this.emitter.on('did-change-mini', callback) | 1 |
PHP | PHP | add missing widgets to registry | 3e20412d588ab0ee38190733042b13d7080a8aa4 | <ide><path>src/View/Input/InputRegistry.php
<ide> class InputRegistry {
<ide> * @var array
<ide> */
<ide> protected $_widgets = [
<add> 'button' => ['Cake\View\Input\Button'],
<ide> 'checkbox' => ['Cake\View\Input\Checkbox'],
<add> 'file' => ['Cake\View\Input\File'],
<ide> 'label' => ['Cake\View\Input\Label'],
<ide> 'multicheckbox' => ['Cake\View\Input\MultiCheckbox', 'label'],
<ide> 'radio' => ['Cake\View\Input\Radio', 'label'],
<ide> 'select' => ['Cake\View\Input\SelectBox'],
<add> 'textarea' => ['Cake\View\Input\Textarea'],
<ide> '_default' => ['Cake\View\Input\Basic'],
<ide> ];
<ide> | 1 |
Python | Python | add test for 'python -mnumpy.f2py' | c3b7ed0f1cee6c1a9a24a48fdafba20117dfac2a | <ide><path>numpy/tests/test_scripts.py
<ide> def try_f2py_commands(cmds):
<ide> success = try_f2py_commands(f2py_cmds)
<ide> msg = "Warning: not all of %s, %s, and %s are found in path" % f2py_cmds
<ide> assert_(success == 3, msg)
<add>
<add>def test_pep338():
<add> f2py_cmd = [sys.executable, '-mnumpy.f2py', '-v']
<add> code, stdout, stderr = run_command(f2py_cmd)
<add> assert_equal(stdout.strip(), b'2') | 1 |
Go | Go | remove newline string | 2b51d1a167055834df331fb23c6cd373ebc06211 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) UnmountDevice(hash string) error {
<ide> defer devices.Unlock()
<ide>
<ide> if info.mountCount == 0 {
<del> return fmt.Errorf("UnmountDevice: device not-mounted id %s\n", hash)
<add> return fmt.Errorf("UnmountDevice: device not-mounted id %s", hash)
<ide> }
<ide>
<ide> info.mountCount-- | 1 |
Python | Python | fix gptneo onnx export | e86c02ea90bcab48555e4f16b180d7f7a5f93cf5 | <ide><path>src/transformers/models/gpt_neo/configuration_gpt_neo.py
<ide>
<ide> from ... import PreTrainedTokenizer, TensorType, is_torch_available
<ide> from ...configuration_utils import PretrainedConfig
<del>from ...onnx import OnnxConfigWithPast, PatchingSpec
<add>from ...onnx import OnnxConfigWithPast
<ide> from ...utils import logging
<ide>
<ide>
<ide> def custom_get_block_length_and_num_blocks(seq_length, window_size):
<ide>
<ide>
<ide> class GPTNeoOnnxConfig(OnnxConfigWithPast):
<del> def __init__(self, config: PretrainedConfig, task: str = "default", use_past: bool = False):
<del> if is_torch_available():
<del> import torch
<del>
<del> from .modeling_gpt_neo import GPTNeoAttentionMixin
<del>
<del> patching_specs = [
<del> PatchingSpec(torch.Tensor, name="unfold", custom_op=custom_unfold),
<del> PatchingSpec(
<del> GPTNeoAttentionMixin,
<del> name="_get_block_length_and_num_blocks",
<del> custom_op=custom_get_block_length_and_num_blocks,
<del> op_wrapper=staticmethod,
<del> ),
<del> ]
<del>
<del> super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
<del>
<del> self._num_local_attention = len([type_ for type_ in self._config.attention_layers if type_ == "local"])
<del> self._key_values_dynamic_axis = []
<del> for i in range(self._config.num_layers):
<del> if self._config.attention_layers[i] == "local":
<del> self._key_values_dynamic_axis.append({0: "batch", 1: "sequence"})
<del> else:
<del> self._key_values_dynamic_axis.append({0: "batch", 2: "sequence"})
<del> self._key_values_dynamic_axis.append({0: "batch", 2: "sequence"})
<del>
<del> @property
<del> def _number_key_values(self):
<del> return (self._config.num_layers * 2) - self._num_local_attention
<del>
<ide> @property
<ide> def inputs(self) -> Mapping[str, Mapping[int, str]]:
<ide> common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
<ide> if self.use_past:
<ide> for i in range(self._config.num_layers):
<del> if self._config.attention_layers[i] == "local":
<del> common_inputs[f"past_key_values.{i}.key_value"] = {0: "batch", 1: "sequence"}
<del> else:
<del> common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "sequence"}
<del> common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "sequence"}
<add> common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence"}
<add> common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence"}
<ide>
<del> common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
<add> common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
<add> else:
<add> common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
<ide>
<ide> return common_inputs
<ide>
<ide> def outputs(self) -> Mapping[str, Mapping[int, str]]:
<ide> common_outputs = super().outputs
<ide> if self.use_past:
<ide> for i in range(self._config.num_layers):
<del> if self._config.attention_layers[i] == "local":
<del> common_outputs[f"present.{i}.key_value"] = {0: "batch", 1: "sequence"}
<del> else:
<del> common_outputs[f"present.{i}.key"] = {0: "batch", 2: "sequence"}
<del> common_outputs[f"present.{i}.value"] = {0: "batch", 2: "sequence"}
<add> common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
<add> common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
<add>
<add> return common_outputs
<add>
<ide> return common_outputs
<ide>
<ide> def generate_dummy_inputs(
<ide> def generate_dummy_inputs(
<ide> # We need to order the input in the way they appears in the forward()
<ide> ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
<ide>
<del> batch = common_inputs["input_ids"].shape[0]
<del> past_shapes = {
<del> "global": (batch, self._config.num_heads, 1, self._config.hidden_size // self._config.num_attention_heads),
<del> "local": (batch, 1, self._config.hidden_size),
<del> }
<del>
<ide> # Need to add the past_keys
<ide> if self.use_past:
<ide> if not is_torch_available():
<ide> raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
<ide> else:
<ide> import torch
<ide>
<del> ordered_inputs["past_key_values"] = []
<del> for i in range(self._config.num_layers):
<del> attention_type = self._config.attention_layers[i]
<del> if attention_type == "global":
<del> ordered_inputs["past_key_values"].append(
<del> (
<del> torch.zeros(past_shapes[attention_type]),
<del> torch.zeros(past_shapes[attention_type]),
<del> )
<del> )
<del> else:
<del> ordered_inputs["past_key_values"].append((torch.zeros(past_shapes[attention_type]),))
<add> batch = common_inputs["input_ids"].shape[0]
<add> past_shape = (batch, self._config.num_heads, 1, self._config.hidden_size // self._config.num_heads)
<add> ordered_inputs["past_key_values"] = [
<add> (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self._config.num_layers)
<add> ]
<ide>
<ide> ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
<ide> if self.use_past:
<ide> ordered_inputs["attention_mask"] = torch.cat(
<del> [ordered_inputs["attention_mask"], torch.zeros(batch, 1)], dim=1
<add> [ordered_inputs["attention_mask"], torch.ones(batch, 1)], dim=1
<ide> )
<ide>
<ide> return ordered_inputs
<ide> def flatten_output_collection_property(name: str, field: Iterable[Any]) -> Dict[
<ide> if name in ["present", "past_key_values"]:
<ide> flatten_output = {}
<ide> for idx, t in enumerate(field):
<del> if len(t) == 1:
<del> flatten_output[f"{name}.{idx}.key_value"] = t[0]
<del> else:
<del> flatten_output[f"{name}.{idx}.key"] = t[0]
<del> flatten_output[f"{name}.{idx}.value"] = t[1]
<add> flatten_output[f"{name}.{idx}.key"] = t[0]
<add> flatten_output[f"{name}.{idx}.value"] = t[1]
<ide>
<ide> return flatten_output
<ide> | 1 |
Javascript | Javascript | fix timing issues in atom-application-test | c861abc2a9472582c9d2f2e9727d662451d4f58d | <ide><path>spec/main-process/atom-application.test.js
<ide> describe('AtomApplication', function () {
<ide> await windowFocusedPromise(window)
<ide>
<ide> const cursorRow = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getCursorBufferPosition().row)
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getCursorBufferPosition().row)
<ide> })
<ide> })
<ide>
<ide> describe('AtomApplication', function () {
<ide> await windowFocusedPromise(window)
<ide>
<ide> const cursorPosition = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getCursorBufferPosition())
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getCursorBufferPosition())
<ide> })
<ide> })
<ide>
<ide> describe('AtomApplication', function () {
<ide> await windowFocusedPromise(window)
<ide>
<ide> const openedPath = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getPath())
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getPath())
<ide> })
<ide> })
<ide>
<ide> describe('AtomApplication', function () {
<ide>
<ide> let activeEditorPath
<ide> activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getPath())
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getPath())
<ide> })
<ide> })
<ide> assert.equal(activeEditorPath, path.join(dirAPath, 'new-file'))
<ide> describe('AtomApplication', function () {
<ide>
<ide> let activeEditorPath
<ide> activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getPath())
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getPath())
<ide> })
<ide> })
<ide> assert.equal(activeEditorPath, path.join(dirAPath, 'new-file'))
<ide> describe('AtomApplication', function () {
<ide> const atomApplication = buildAtomApplication()
<ide> const window1 = atomApplication.launch(parseCommandLine([path.join(tempDirPath, 'new-file')]))
<ide> await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> textEditor.insertText('Hello World!')
<del> sendBackToMainProcess(null)
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) {
<add> textEditor.insertText('Hello World!')
<add> sendBackToMainProcess(null)
<add> }
<ide> })
<ide> })
<ide> window1.close()
<ide> await window1.closedPromise
<ide>
<ide> const window2 = atomApplication.launch(parseCommandLine([path.join(tempDirPath)]))
<ide> const window2Text = await evalInWebContents(window2.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (textEditor) {
<del> sendBackToMainProcess(textEditor.getText())
<add> atom.workspace.observeActivePaneItem(function (textEditor) {
<add> if (textEditor) sendBackToMainProcess(textEditor.getText())
<ide> })
<ide> })
<ide>
<ide> describe('AtomApplication', function () {
<ide> const window = atomApplication.launch(parseCommandLine([newFilePath]))
<ide> await windowFocusedPromise(window)
<ide> const {editorTitle, editorText} = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (editor) {
<del> sendBackToMainProcess({editorTitle: editor.getTitle(), editorText: editor.getText()})
<add> atom.workspace.observeActivePaneItem(function (editor) {
<add> if (editor) sendBackToMainProcess({editorTitle: editor.getTitle(), editorText: editor.getText()})
<ide> })
<ide> })
<ide> assert.equal(editorTitle, path.basename(newFilePath))
<ide> describe('AtomApplication', function () {
<ide> const window = atomApplication.launch(parseCommandLine([newRemoteFilePath]))
<ide> await windowFocusedPromise(window)
<ide> const {projectPaths, editorTitle, editorText} = await evalInWebContents(window.browserWindow.webContents, function (sendBackToMainProcess) {
<del> atom.workspace.onDidChangeActivePaneItem(function (editor) {
<del> sendBackToMainProcess({
<del> projectPaths: atom.project.getPaths(),
<del> editorTitle: editor.getTitle(),
<del> editorText: editor.getText()
<del> })
<add> atom.workspace.observeActivePaneItem(function (editor) {
<add> if (editor) {
<add> sendBackToMainProcess({
<add> projectPaths: atom.project.getPaths(),
<add> editorTitle: editor.getTitle(),
<add> editorText: editor.getText()
<add> })
<add> }
<ide> })
<ide> })
<ide> assert.deepEqual(projectPaths, [newRemoteFilePath])
<ide> describe('AtomApplication', function () {
<ide> })
<ide>
<ide> it('reopens any previously opened windows when launched with no path', async function () {
<add> const tempDirPath1 = makeTempDir()
<add> const tempDirPath2 = makeTempDir()
<add>
<ide> const atomApplication1 = buildAtomApplication()
<del> const app1Window1 = atomApplication1.launch(parseCommandLine([makeTempDir()]))
<del> await windowFocusedPromise(app1Window1)
<del> const app1Window2 = atomApplication1.launch(parseCommandLine([makeTempDir()]))
<del> await windowFocusedPromise(app1Window2)
<add> const app1Window1 = atomApplication1.launch(parseCommandLine([tempDirPath1]))
<add> await app1Window1.loadedPromise
<add> const app1Window2 = atomApplication1.launch(parseCommandLine([tempDirPath2]))
<add> await app1Window2.loadedPromise
<ide>
<ide> const atomApplication2 = buildAtomApplication()
<ide> const [app2Window1, app2Window2] = atomApplication2.launch(parseCommandLine([]))
<del> await windowFocusedPromise(app2Window1)
<del> await windowFocusedPromise(app2Window2)
<del> assert.deepEqual(await getTreeViewRootDirectories(app2Window1), await getTreeViewRootDirectories(app1Window1))
<del> assert.deepEqual(await getTreeViewRootDirectories(app2Window2), await getTreeViewRootDirectories(app1Window2))
<add> await app2Window1.loadedPromise
<add> await app2Window2.loadedPromise
<add>
<add> assert.deepEqual(await getTreeViewRootDirectories(app2Window1), [tempDirPath1])
<add> assert.deepEqual(await getTreeViewRootDirectories(app2Window2), [tempDirPath2])
<ide> })
<ide>
<ide> it('does not reopen any previously opened windows when launched with no path and `core.restorePreviousWindowsOnStart` is false', async function () { | 1 |
Ruby | Ruby | add failing test for link_tags when streaming | f303eb289569bbb0a689ea51d4161f73fb6fdf3d | <ide><path>actionview/test/template/asset_tag_helper_test.rb
<ide> require "action_dispatch"
<ide> ActionView::Template::Types.delegate_to Mime
<ide>
<add>module AssetTagHelperTestHelpers
<add> def with_preload_links_header(new_preload_links_header = true)
<add> original_preload_links_header = ActionView::Helpers::AssetTagHelper.preload_links_header
<add> ActionView::Helpers::AssetTagHelper.preload_links_header = new_preload_links_header
<add>
<add> yield
<add> ensure
<add> ActionView::Helpers::AssetTagHelper.preload_links_header = original_preload_links_header
<add> end
<add>end
<add>
<ide> class AssetTagHelperTest < ActionView::TestCase
<ide> tests ActionView::Helpers::AssetTagHelper
<ide>
<add> include AssetTagHelperTestHelpers
<add>
<ide> attr_reader :request, :response
<ide>
<ide> class FakeRequest
<ide> def test_caching_image_path_with_caching_and_proc_asset_host_using_request
<ide> assert_equal "http://localhost/images/xml.png", image_path("xml.png")
<ide> end
<ide> end
<del>
<del> private
<del> def with_preload_links_header(new_preload_links_header = true)
<del> original_preload_links_header = ActionView::Helpers::AssetTagHelper.preload_links_header
<del> ActionView::Helpers::AssetTagHelper.preload_links_header = new_preload_links_header
<del>
<del> yield
<del> ensure
<del> ActionView::Helpers::AssetTagHelper.preload_links_header = original_preload_links_header
<del> end
<ide> end
<ide>
<ide> class AssetTagHelperNonVhostTest < ActionView::TestCase
<ide> def test_javascript_include_tag_without_request
<ide> end
<ide> end
<ide>
<add>class AssetTagHelperWithStreamingRequest < ActionView::TestCase
<add> tests ActionView::Helpers::AssetTagHelper
<add>
<add> include AssetTagHelperTestHelpers
<add>
<add> def setup
<add> super
<add> response.sending!
<add> end
<add>
<add> def test_stylesheet_link_tag_with_streaming
<add> with_preload_links_header do
<add> assert_dom_equal(
<add> %(<link rel="stylesheet" href="/stylesheets/foo.css" />),
<add> stylesheet_link_tag("foo.css")
<add> )
<add> end
<add> end
<add>
<add> def test_javascript_include_tag_with_streaming
<add> with_preload_links_header do
<add> assert_dom_equal %(<script src="/javascripts/foo.js"></script>), javascript_include_tag("foo.js")
<add> end
<add> end
<add>end
<add>
<ide> class AssetUrlHelperControllerTest < ActionView::TestCase
<ide> tests ActionView::Helpers::AssetUrlHelper
<ide> | 1 |
PHP | PHP | use signature to define name | 41472b79dbe1d7eda67357632944984555cf858c | <ide><path>app/Console/Commands/Inspire.php
<ide> class Inspire extends Command
<ide> {
<ide> /**
<del> * The console command name.
<add> * The name and signature of the console command.
<ide> *
<ide> * @var string
<ide> */
<del> protected $name = 'inspire';
<add> protected $signature = 'inspire';
<ide>
<ide> /**
<ide> * The console command description. | 1 |
Ruby | Ruby | push precision to type objects | 22c27ae31f1b7c3a4e3b5cbcb4571c6be5e527e8 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def initialize_type_map(m) # :nodoc:
<ide> m.register_type %r(int)i, Type::Integer.new
<ide> m.register_type(%r(decimal)i) do |sql_type|
<ide> scale = extract_scale(sql_type)
<add> precision = extract_precision(sql_type)
<ide>
<ide> if scale == 0
<del> Type::Integer.new
<add> Type::Integer.new(precision: precision)
<ide> else
<del> Type::Decimal.new(scale: scale)
<add> Type::Decimal.new(precision: precision, scale: scale)
<ide> end
<ide> end
<ide> end
<ide> def extract_scale(sql_type) # :nodoc:
<ide> end
<ide> end
<ide>
<add> def extract_precision(sql_type) # :nodoc:
<add> $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
<add> end
<add>
<ide> def translate_exception_class(e, sql)
<ide> message = "#{e.class.name}: #{e.message}: #{sql}"
<ide> @logger.error message if @logger
<ide><path>activerecord/lib/active_record/connection_adapters/column.rb
<ide> module Format
<ide> ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
<ide> end
<ide>
<del> attr_reader :name, :default, :cast_type, :limit, :null, :sql_type, :precision, :default_function
<add> attr_reader :name, :default, :cast_type, :limit, :null, :sql_type, :default_function
<ide> attr_accessor :primary, :coder
<ide>
<ide> alias :encoded? :coder
<ide>
<del> delegate :type, :scale, :klass, :text?, :number?, :binary?, :type_cast_for_write, to: :cast_type
<add> delegate :type, :precision, :scale, :klass, :text?, :number?, :binary?, :type_cast_for_write, to: :cast_type
<ide>
<ide> # Instantiates a new column in the table.
<ide> #
<ide> def initialize(name, default, cast_type, sql_type = nil, null = true)
<ide> @sql_type = sql_type
<ide> @null = null
<ide> @limit = extract_limit(sql_type)
<del> @precision = extract_precision(sql_type)
<ide> @default = extract_default(default)
<ide> @default_function = nil
<ide> @primary = nil
<ide> def extract_default(default)
<ide> end
<ide>
<ide> private
<del> delegate :extract_precision, to: :cast_type
<del>
<ide> def extract_limit(sql_type)
<ide> $1.to_i if sql_type =~ /\((.*)\)/
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def get_oid_type(oid, fmod, column_name, sql_type = '')
<ide> }
<ide> end
<ide>
<add> OID_FOR_DECIMAL_TREATED_AS_INT = 23 # :nodoc:
<add>
<ide> def normalize_oid_type(ftype, fmod)
<ide> # The type for the numeric depends on the width of the field,
<ide> # so we'll do something special here.
<ide> def normalize_oid_type(ftype, fmod)
<ide> # places after decimal = fmod - 4 & 0xffff
<ide> # places before decimal = (fmod - 4) >> 16 & 0xffff
<ide> if ftype == 1700 && (fmod - 4 & 0xffff).zero?
<del> 23
<add> OID_FOR_DECIMAL_TREATED_AS_INT
<ide> else
<ide> ftype
<ide> end
<ide> def initialize_type_map(m)
<ide> m.register_type 'bool', Type::Boolean.new
<ide> m.register_type 'bit', OID::Bit.new
<ide> m.alias_type 'varbit', 'bit'
<del> m.register_type 'timestamp', OID::DateTime.new
<ide> m.alias_type 'timestamptz', 'timestamp'
<ide> m.register_type 'date', OID::Date.new
<ide> m.register_type 'time', OID::Time.new
<ide> def initialize_type_map(m)
<ide> m.alias_type 'lseg', 'varchar'
<ide> m.alias_type 'box', 'varchar'
<ide>
<add> m.register_type 'timestamp' do |_, sql_type|
<add> precision = extract_precision(sql_type)
<add> OID::DateTime.new(precision: precision)
<add> end
<add>
<ide> m.register_type 'numeric' do |_, sql_type|
<add> precision = extract_precision(sql_type)
<ide> scale = extract_scale(sql_type)
<del> OID::Decimal.new(scale: scale)
<add> OID::Decimal.new(precision: precision, scale: scale)
<add> end
<add>
<add> m.register_type OID_FOR_DECIMAL_TREATED_AS_INT do |_, sql_type|
<add> precision = extract_precision(sql_type)
<add> OID::Integer.new(precision: precision)
<ide> end
<ide>
<ide> load_additional_types(m)
<ide><path>activerecord/lib/active_record/connection_adapters/type/date_time.rb
<ide> def type
<ide> :datetime
<ide> end
<ide>
<del> def extract_precision(sql_type)
<del> $1.to_i if sql_type =~ /\((\d+)\)/
<del> end
<del>
<ide> private
<ide>
<ide> def cast_value(string)
<ide><path>activerecord/lib/active_record/connection_adapters/type/numeric.rb
<ide> def type_cast_for_write(value)
<ide> else super
<ide> end
<ide> end
<del>
<del> def extract_precision(sql_type)
<del> $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/type/value.rb
<ide> module ActiveRecord
<ide> module ConnectionAdapters
<ide> module Type
<ide> class Value # :nodoc:
<del> attr_reader :scale
<add> attr_reader :precision, :scale
<ide>
<ide> def initialize(options = {})
<del> options.assert_valid_keys(:scale)
<add> options.assert_valid_keys(:precision, :scale)
<add> @precision = options[:precision]
<ide> @scale = options[:scale]
<ide> end
<ide>
<ide> def type; end
<ide>
<del> def extract_precision(sql_type); end
<del>
<ide> def type_cast(value)
<ide> cast_value(value) unless value.nil?
<ide> end | 6 |
Go | Go | add newline to promote/demote message | 3386e3570a1251bbea5302d8b8e639aaf68436c3 | <ide><path>api/client/node/demote.go
<ide> func runDemote(dockerCli *client.DockerCli, flags *pflag.FlagSet, args []string)
<ide> }); err != nil {
<ide> return err
<ide> }
<del> fmt.Fprintf(dockerCli.Out(), "Manager %s demoted in the swarm.", id)
<add> fmt.Fprintf(dockerCli.Out(), "Manager %s demoted in the swarm.\n", id)
<ide> }
<ide>
<ide> return nil
<ide><path>api/client/node/promote.go
<ide> func runPromote(dockerCli *client.DockerCli, flags *pflag.FlagSet, args []string
<ide> }); err != nil {
<ide> return err
<ide> }
<del> fmt.Fprintf(dockerCli.Out(), "Node %s promoted to a manager in the swarm.", id)
<add> fmt.Fprintf(dockerCli.Out(), "Node %s promoted to a manager in the swarm.\n", id)
<ide> }
<ide>
<ide> return nil | 2 |
Go | Go | add a check for invalid/junk messages | 2fb14185cb34c65020af18b8d7439a8c9ecf747b | <ide><path>libnetwork/resolver.go
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> err error
<ide> )
<ide>
<add> if query == nil || len(query.Question) == 0 {
<add> return
<add> }
<ide> name := query.Question[0].Name
<ide> if query.Question[0].Qtype == dns.TypeA {
<ide> resp, err = r.handleIPv4Query(name, query) | 1 |
Ruby | Ruby | fix version error for prerelease macos | 7a40f1bf0abe181499b4addcfd4d6a6041726a32 | <ide><path>Library/Homebrew/os/mac.rb
<ide> module Mac
<ide> # This can be compared to numerics, strings, or symbols
<ide> # using the standard Ruby Comparable methods.
<ide> def version
<del> @version ||= Version.from_symbol(full_version.to_sym)
<add> @version ||= full_version.strip_patch
<ide> end
<ide>
<ide> # This can be compared to numerics, strings, or symbols | 1 |
PHP | PHP | use mock to avoid throwing error to stderr | 4bc401eee6ea5683006421060470677c1b69afd8 | <ide><path>tests/TestCase/Shell/SchemaCacheShellTest.php
<ide> public function testBuildInvalidConnection()
<ide> {
<ide> $this->expectException(StopException::class);
<ide>
<del> $shell = new SchemaCacheShell(new ConsoleIo());
<add> $io = $this->getMockBuilder(ConsoleIo::class)->getMock();
<add> $shell = new SchemaCacheShell($io);
<ide> $shell->params['connection'] = 'derpy-derp';
<ide> $shell->build('articles');
<ide> }
<ide> public function testClearInvalidConnection()
<ide> {
<ide> $this->expectException(StopException::class);
<ide>
<del> $shell = new SchemaCacheShell(new ConsoleIo());
<add> $io = $this->getMockBuilder(ConsoleIo::class)->getMock();
<add> $shell = new SchemaCacheShell($io);
<ide> $shell->params['connection'] = 'derpy-derp';
<ide> $shell->clear('articles');
<ide> } | 1 |
Javascript | Javascript | add another edge case | 5ebcd2187c9ce059dd20224e6f6f3c697527954b | <ide><path>packages/ember-metal/tests/observer_test.js
<ide> testBoth("observers added/removed during changeProperties should do the right th
<ide> var addedAfterFirstChangeObserver = new Observer();
<ide> var addedAfterLastChangeObserver = new Observer();
<ide> var removedBeforeFirstChangeObserver = new Observer();
<add> var removedBeforeLastChangeObserver = new Observer();
<ide> var removedAfterLastChangeObserver = new Observer();
<ide> removedBeforeFirstChangeObserver.add();
<add> removedBeforeLastChangeObserver.add();
<ide> removedAfterLastChangeObserver.add();
<ide> Ember.changeProperties(function () {
<ide> removedBeforeFirstChangeObserver.remove();
<ide> testBoth("observers added/removed during changeProperties should do the right th
<ide> equal(addedBeforeFirstChangeObserver.didChangeCount, 0, 'addObserver called before the first change is deferred');
<ide>
<ide> addedAfterFirstChangeObserver.add();
<add> removedBeforeLastChangeObserver.remove();
<ide>
<ide> set(obj, 'foo', 2);
<ide>
<ide> testBoth("observers added/removed during changeProperties should do the right th
<ide> equal(addedAfterFirstChangeObserver.didChangeCount, 1, 'addObserver called after the first change sees 1');
<ide> equal(addedAfterLastChangeObserver.willChangeCount, 0, 'addBeforeObserver called after the last change sees none');
<ide> equal(addedAfterLastChangeObserver.didChangeCount, 0, 'addObserver called after the last change sees none');
<add> equal(removedBeforeLastChangeObserver.willChangeCount, 1, 'removeBeforeObserver called before the last change still sees 1');
<add> equal(removedBeforeLastChangeObserver.didChangeCount, 1, 'removeObserver called before the last change still sees 1');
<ide> equal(removedAfterLastChangeObserver.willChangeCount, 1, 'removeBeforeObserver called after the last change still sees 1');
<ide> equal(removedAfterLastChangeObserver.didChangeCount, 1, 'removeObserver called after the last change still sees 1');
<ide> }); | 1 |
Javascript | Javascript | remove unused variable | 23bb5986d4c97dde538622283864b3eed23493d8 | <ide><path>src/node.js
<ide> // If we were spawned with env NODE_CHANNEL_FD then load that up and
<ide> // start parsing data from that stream.
<ide> if (process.env.NODE_CHANNEL_FD) {
<del> var fd = parseInt(process.env.NODE_CHANNEL_FD);
<del> assert(fd >= 0);
<add> assert(parseInt(process.env.NODE_CHANNEL_FD) >= 0);
<ide> var cp = NativeModule.require('child_process');
<ide>
<ide> // Load tcp_wrap to avoid situation where we might immediately receive
<ide> // a message.
<ide> // FIXME is this really necessary?
<ide> process.binding('tcp_wrap')
<ide>
<del> cp._forkChild(fd);
<add> cp._forkChild();
<ide> assert(process.send);
<ide> }
<ide> } | 1 |
Javascript | Javascript | expand test case for unknown file open flags | a5aa7c17138ba811324526c1178f6a5b4a094acb | <ide><path>test/parallel/test-fs-open-flags.js
<ide> assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL);
<ide> .forEach(function(flags) {
<ide> assert.throws(function() { fs._stringToFlags(flags); });
<ide> });
<add>
<add>assert.throws(
<add> () => fs._stringToFlags({}),
<add> /Unknown file open flag: \[object Object\]/
<add>);
<add>
<add>assert.throws(
<add> () => fs._stringToFlags(true),
<add> /Unknown file open flag: true/
<add>);
<add>
<add>assert.throws(
<add> () => fs._stringToFlags(null),
<add> /Unknown file open flag: null/
<add>); | 1 |
Javascript | Javascript | add test for non-integer delay timers | 8e60b4523cc9097aad81e0dbbc6d24617c279e66 | <ide><path>test/simple/test-timers-non-integer-delay.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>/*
<add> * This test makes sure that non-integer timer delays do not make the process
<add> * hang. See https://github.com/joyent/node/issues/8065 and
<add> * https://github.com/joyent/node/issues/8068 which have been fixed by
<add> * https://github.com/joyent/node/pull/8073.
<add> *
<add> * If the process hangs, this test will make the tests suite timeout,
<add> * otherwise it will exit very quickly (after 50 timers with a short delay
<add> * fire).
<add> *
<add> * We have to set at least several timers with a non-integer delay to
<add> * reproduce the issue. Sometimes, a timer with a non-integer delay will
<add> * expire correctly. 50 timers has always been more than enough to reproduce
<add> * it 100%.
<add> */
<add>
<add>var assert = require('assert');
<add>
<add>var TIMEOUT_DELAY = 1.1;
<add>var NB_TIMEOUTS_FIRED = 50;
<add>
<add>var nbTimeoutFired = 0;
<add>var interval = setInterval(function() {
<add> ++nbTimeoutFired;
<add> if (nbTimeoutFired === NB_TIMEOUTS_FIRED) {
<add> clearInterval(interval);
<add> process.exit(0);
<add> }
<add>}, TIMEOUT_DELAY); | 1 |
Mixed | Ruby | put coffee-rails in top-level of generated gemfile | 940da7d9cbb39bc9589031df62e26edfc0c1f8bc | <ide><path>railties/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Allow vanilla apps to render CoffeeScript templates in production
<add>
<add> Vanilla apps already render CoffeeScript templates in development and test
<add> environments. With this change, the production behavior matches that of
<add> the other environments.
<add>
<add> Effectively, this meant moving coffee-rails (and the JavaScript runtime on
<add> which it is dependent) from the :assets group to the top-level of the
<add> generated Gemfile.
<add>
<add> *Gabe Kopley*
<add>
<ide> * `Rails.version` now returns an instance of `Gem::Version`
<ide>
<ide> *Charlie Somerville*
<ide><path>railties/lib/rails/generators/app_base.rb
<ide> def assets_gemfile_entry
<ide> return if options[:skip_sprockets]
<ide>
<ide> gemfile = if options.dev? || options.edge?
<del> <<-GEMFILE
<add> <<-GEMFILE.gsub(/^ {12}/, '')
<ide> # Gems used only for assets and not required
<ide> # in production environments by default.
<ide> group :assets do
<ide> gem 'sprockets-rails', github: 'rails/sprockets-rails'
<ide> gem 'sass-rails', github: 'rails/sass-rails'
<del> gem 'coffee-rails', github: 'rails/coffee-rails'
<del>
<del> # See https://github.com/sstephenson/execjs#readme for more supported runtimes
<del> #{javascript_runtime_gemfile_entry}
<add> #{coffee_gemfile_entry if options[:skip_javascript]}
<add> #{javascript_runtime_gemfile_entry(2) if options[:skip_javascript]}
<ide> gem 'uglifier', '>= 1.0.3'
<ide> end
<ide> GEMFILE
<ide> else
<del> <<-GEMFILE
<add> <<-GEMFILE.gsub(/^ {12}/, '')
<ide> # Gems used only for assets and not required
<ide> # in production environments by default.
<ide> group :assets do
<ide> gem 'sass-rails', '~> 4.0.0.beta1'
<del> gem 'coffee-rails', '~> 4.0.0.beta1'
<del>
<del> # See https://github.com/sstephenson/execjs#readme for more supported runtimes
<del> #{javascript_runtime_gemfile_entry}
<add> #{coffee_gemfile_entry if options[:skip_javascript]}
<add> #{javascript_runtime_gemfile_entry(2) if options[:skip_javascript]}
<ide> gem 'uglifier', '>= 1.0.3'
<ide> end
<ide> GEMFILE
<ide> def assets_gemfile_entry
<ide> gemfile.strip_heredoc.gsub(/^[ \t]*$/, '')
<ide> end
<ide>
<add> def coffee_gemfile_entry
<add> if options.dev? || options.edge?
<add> "gem 'coffee-rails', github: 'rails/coffee-rails'"
<add> else
<add> "gem 'coffee-rails', '~> 4.0.0.beta1'"
<add> end
<add> end
<add>
<ide> def javascript_gemfile_entry
<ide> args = {'jquery' => ", github: 'rails/jquery-rails'"}
<ide>
<ide> unless options[:skip_javascript]
<del> <<-GEMFILE.strip_heredoc
<add> <<-GEMFILE.gsub(/^ {12}/, '').strip_heredoc
<add> #{javascript_runtime_gemfile_entry}
<add> # Use CoffeeScript for .js.coffee assets and views
<add> #{coffee_gemfile_entry}
<add>
<ide> gem '#{options[:javascript]}-rails'#{args[options[:javascript]]}
<ide>
<ide> # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
<ide> def javascript_gemfile_entry
<ide> end
<ide> end
<ide>
<del> def javascript_runtime_gemfile_entry
<del> if defined?(JRUBY_VERSION)
<del> "gem 'therubyrhino'\n"
<add> def javascript_runtime_gemfile_entry(n_spaces=0)
<add> runtime = if defined?(JRUBY_VERSION)
<add> "gem 'therubyrhino'"
<ide> else
<del> "# gem 'therubyracer', platforms: :ruby\n"
<add> "# gem 'therubyracer', platforms: :ruby"
<ide> end
<add> <<-GEMFILE.gsub(/^ {10}/, '')
<add> # See https://github.com/sstephenson/execjs#readme for more supported runtimes
<add> #{" "*n_spaces}#{runtime}
<add> GEMFILE
<ide> end
<ide>
<ide> def bundle_command(command)
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_generator_if_skip_sprockets_is_given
<ide> end
<ide> assert_file "Gemfile" do |content|
<ide> assert_no_match(/sass-rails/, content)
<del> assert_no_match(/coffee-rails/, content)
<ide> assert_no_match(/uglifier/, content)
<add> assert_match(/coffee-rails/, content)
<ide> end
<ide> assert_file "config/environments/development.rb" do |content|
<ide> assert_no_match(/config\.assets\.debug = true/, content)
<ide> def test_javascript_is_skipped_if_required
<ide> assert_file "app/assets/javascripts/application.js" do |contents|
<ide> assert_no_match %r{^//=\s+require\s}, contents
<ide> end
<add> assert_file "Gemfile" do |content|
<add> assert_match(/coffee-rails/, content)
<add> end
<ide> end
<ide>
<ide> def test_inclusion_of_debugger | 3 |
Ruby | Ruby | convert \r\n to \n | a1afc7726b3f9a59eb2dbc21fbd7aa59927cc889 | <ide><path>activemodel/lib/active_model/validations/comparability.rb
<del># frozen_string_literal: true
<del>
<del>module ActiveModel
<del> module Validations
<del> module Comparability #:nodoc:
<del> COMPARE_CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
<del> equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
<del> other_than: :!= }.freeze
<del>
<del> def option_value(record, option_value)
<del> case option_value
<del> when Proc
<del> option_value.call(record)
<del> when Symbol
<del> record.send(option_value)
<del> else
<del> option_value
<del> end
<del> end
<del>
<del> def error_options(value, option_value)
<del> options.except(*COMPARE_CHECKS.keys).merge!(
<del> count: option_value,
<del> value: value
<del> )
<del> end
<del>
<del> def error_value(record, option_value)
<del> case option_value
<del> when Proc
<del> option_value(record, option_value)
<del> else
<del> option_value
<del> end
<del> end
<del> end
<del> end
<del>end
<add># frozen_string_literal: true
<add>
<add>module ActiveModel
<add> module Validations
<add> module Comparability #:nodoc:
<add> COMPARE_CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
<add> equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
<add> other_than: :!= }.freeze
<add>
<add> def option_value(record, option_value)
<add> case option_value
<add> when Proc
<add> option_value.call(record)
<add> when Symbol
<add> record.send(option_value)
<add> else
<add> option_value
<add> end
<add> end
<add>
<add> def error_options(value, option_value)
<add> options.except(*COMPARE_CHECKS.keys).merge!(
<add> count: option_value,
<add> value: value
<add> )
<add> end
<add>
<add> def error_value(record, option_value)
<add> case option_value
<add> when Proc
<add> option_value(record, option_value)
<add> else
<add> option_value
<add> end
<add> end
<add> end
<add> end
<add>end | 1 |
Javascript | Javascript | remove message from strictequal assertions | f565bbb193c90a974ad1500b86047b834d58606d | <ide><path>test/parallel/test-http-response-readable.js
<ide> const testServer = new http.Server(function(req, res) {
<ide>
<ide> testServer.listen(0, function() {
<ide> http.get({ port: this.address().port }, function(res) {
<del> assert.strictEqual(res.readable, true, 'res.readable initially true');
<add> assert.strictEqual(res.readable, true);
<ide> res.on('end', function() {
<del> assert.strictEqual(res.readable, false,
<del> 'res.readable set to false after end');
<add> assert.strictEqual(res.readable, false);
<ide> testServer.close();
<ide> });
<ide> res.resume(); | 1 |
Text | Text | add solution to hint stub (mongodb model.findbyid) | e2a00798f8379d2f381a4fecf66e161be50ea22f | <ide><path>guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id/index.md
<ide> ---
<ide> title: Use model.findById() to Search Your Database By _id
<ide> ---
<del>## Use model.findById() to Search Your Database By _id
<add># Use model.findById() to Search Your Database By _id
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>## Solutions
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add><details><summary>Solution #1 (Click to Show/Hide)</summary>
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>Code for `myApp.js`
<add>
<add>```javascript
<add>/** 1) Install & Set up mongoose */
<add>const mongoose = require('mongoose');
<add>mongoose.connect(process.env.MONGO_URI);
<add>
<add>/** 2) Create a 'Person' Model */
<add>var personSchema = new mongoose.Schema({
<add> name: String,
<add> age: Number,
<add> favoriteFoods: [String]
<add>});
<add>
<add>/** 3) Create and Save a Person */
<add>var Person = mongoose.model('Person', personSchema);
<add>
<add>var createAndSavePerson = function(done) {
<add> var janeFonda = new Person({name: "Jane Fonda", age: 84, favoriteFoods: ["vodka", "air"]});
<add>
<add> janeFonda.save(function(err, data) {
<add> if (err) return console.error(err);
<add> done(null, data)
<add> });
<add>};
<add>
<add>/** 4) Create many People with `Model.create()` */
<add>var arrayOfPeople = [
<add> {name: "Frankie", age: 74, favoriteFoods: ["Del Taco"]},
<add> {name: "Sol", age: 76, favoriteFoods: ["roast chicken"]},
<add> {name: "Robert", age: 78, favoriteFoods: ["wine"]}
<add>];
<add>var createManyPeople = function(arrayOfPeople, done) {
<add> Person.create(arrayOfPeople, function (err, people) {
<add> if (err) return console.log(err);
<add> done(null, people);
<add> });
<add>};
<add>
<add>/** 5) Use `Model.find()` */
<add>var findPeopleByName = function(personName, done) {
<add> Person.find({name: personName}, function (err, personFound) {
<add> if (err) return console.log(err);
<add> done(null, personFound);
<add> });
<add>};
<add>
<add>/** 6) Use `Model.findOne()` */
<add>var findOneByFood = function(food, done) {
<add> Person.findOne({favoriteFoods: food}, function (err, data) {
<add> if (err) return console.log(err);
<add> done(null, data);
<add> });
<add>};
<add>
<add>/** 7) Use `Model.findById()` */
<add>var findPersonById = function(personId, done) {
<add> Person.findById(personId, function (err, data) {
<add> if (err) return console.log(err);
<add> done(null, data);
<add> });
<add>};
<add>```
<add></details> | 1 |
PHP | PHP | use header() function | 153094586e49be5d7176eba991f6cb20aa31bfd6 | <ide><path>src/Illuminate/Http/Response.php
<ide> public function setContent($content)
<ide> // from routes that will be automatically transformed to their JSON form.
<ide> if ($this->shouldBeJson($content))
<ide> {
<del> $this->headers->set('Content-Type', 'application/json');
<add> $this->header('Content-Type', 'application/json');
<ide>
<ide> $content = $this->morphToJson($content);
<ide> } | 1 |
PHP | PHP | remove non-portable data type from mysql | b6b8d8398011537f6459412ace37dcdff0ad0423 | <ide><path>lib/Cake/Model/Datasource/Database/Mysql.php
<ide> class Mysql extends DboSource {
<ide> 'biginteger' => array('name' => 'bigint', 'limit' => '20'),
<ide> 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
<ide> 'float' => array('name' => 'float', 'formatter' => 'floatval'),
<del> 'numeric' => array('name' => 'decimal', 'formatter' => 'floatval'),
<ide> 'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
<ide> 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
<ide> 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), | 1 |
Ruby | Ruby | improve documentation coverage and markup | 64092de25727c1943807bf5345107d90428135a0 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> module ActionMailer #:nodoc:
<ide> #
<ide> # These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
<ide> #
<del> # * <tt>template_root</tt> - template root determines the base from which template references will be made.
<add> # * <tt>template_root</tt> - Determines the base from which template references will be made.
<ide> #
<ide> # * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
<ide> # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
<ide> #
<del> # * <tt>smtp_settings</tt> - Allows detailed configuration for :smtp delivery method:
<add> # * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
<ide> # * <tt>:address</tt> Allows you to use a remote mail server. Just change it from its default "localhost" setting.
<ide> # * <tt>:port</tt> On the off chance that your mail server doesn't run on port 25, you can change it.
<ide> # * <tt>:domain</tt> If you need to specify a HELO domain, you can do it here.
<ide> # * <tt>:user_name</tt> If your mail server requires authentication, set the username in this setting.
<ide> # * <tt>:password</tt> If your mail server requires authentication, set the password in this setting.
<ide> # * <tt>:authentication</tt> If your mail server requires authentication, you need to specify the authentication type here.
<del> # This is a symbol and one of :plain, :login, :cram_md5
<add> # This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>
<ide> #
<del> # * <tt>sendmail_settings</tt> - Allows you to override options for the :sendmail delivery method
<add> # * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method
<ide> # * <tt>:location</tt> The location of the sendmail executable, defaults to "/usr/sbin/sendmail"
<ide> # * <tt>:arguments</tt> The command line arguments
<ide> # * <tt>raise_delivery_errors</tt> - whether or not errors should be raised if the email fails to be delivered.
<ide> #
<del> # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
<add> # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.
<ide> #
<ide> # * <tt>perform_deliveries</tt> - Determines whether deliver_* methods are actually carried out. By default they are,
<ide> # but this can be turned off to help functional testing.
<ide> #
<del> # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
<add> # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
<ide> # for unit and functional testing.
<ide> #
<ide> # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
<ide><path>actionpack/lib/action_controller/base.rb
<ide> class Base
<ide> @@resources_path_names = { :new => 'new', :edit => 'edit' }
<ide> cattr_accessor :resources_path_names
<ide>
<del> # Sets the token parameter name for RequestForgery. Calling #protect_from_forgery sets it to :authenticity_token by default
<add> # Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
<add> # sets it to <tt>:authenticity_token</tt> by default.
<ide> cattr_accessor :request_forgery_protection_token
<ide>
<ide> # Indicates whether or not optimise the generated named
<ide> def process(request, response, method = :perform_action, *arguments) #:nodoc:
<ide> # * <tt>:host</tt> -- overrides the default (current) host if provided.
<ide> # * <tt>:protocol</tt> -- overrides the default (current) protocol if provided.
<ide> # * <tt>:port</tt> -- optionally specify the port to connect to.
<del> # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if :password is also present).
<del> # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if :user is also present).
<add> # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
<add> # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
<ide> # * <tt>:skip_relative_url_root</tt> -- if true, the url is not constructed using the relative_url_root of the request so the path
<ide> # will include the web server relative installation directory.
<ide> #
<ide> def process(request, response, method = :perform_action, *arguments) #:nodoc:
<ide> # url_for :controller => 'posts', :action => nil
<ide> #
<ide> # If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
<del> # :overwrite_params options. Say for your posts you have different views for showing and printing them.
<add> # <tt>:overwrite_params</tt> options. Say for your posts you have different views for showing and printing them.
<ide> # Then, in the show view, you get the URL for the print view like this
<ide> #
<ide> # url_for :overwrite_params => { :action => 'print' }
<ide> def append_view_path(path)
<ide> # # placed in "app/views/layouts/special.r(html|xml)"
<ide> # render :text => "Hi there!", :layout => "special"
<ide> #
<del> # The :text option can also accept a Proc object, which can be used to manually control the page generation. This should
<add> # The <tt>:text</tt> option can also accept a Proc object, which can be used to manually control the page generation. This should
<ide> # generally be avoided, as it violates the separation between code and content, and because almost everything that can be
<ide> # done with this method can also be done more cleanly using one of the other rendering methods, most notably templates.
<ide> #
<ide> def append_view_path(path)
<ide> #
<ide> # === Rendering with status and location headers
<ide> #
<del> # All renders take the :status and :location options and turn them into headers. They can even be used together:
<add> # All renders take the <tt>:status</tt> and <tt>:location</tt> options and turn them into headers. They can even be used together:
<ide> #
<ide> # render :xml => post.to_xml, :status => :created, :location => post_url(post)
<ide> def render(options = nil, extra_options = {}, &block) #:doc:
<ide><path>actionpack/lib/action_controller/cookies.rb
<ide> module ActionController #:nodoc:
<del> # Cookies are read and written through ActionController#cookies. The cookies being read are what were received along with the request,
<del> # the cookies being written are what will be sent out with the response. Cookies are read by value (so you won't get the cookie object
<del> # itself back -- just the value it holds). Examples for writing:
<add> # Cookies are read and written through ActionController#cookies.
<ide> #
<del> # cookies[:user_name] = "david" # => Will set a simple session cookie
<add> # The cookies being read are the ones received along with the request, the cookies
<add> # being written will be sent out with the response. Reading a cookie does not get
<add> # the cookie object itself back, just the value it holds.
<add> #
<add> # Examples for writing:
<add> #
<add> # # Sets a simple session cookie.
<add> # cookies[:user_name] = "david"
<add> #
<add> # # Sets a cookie that expires in 1 hour.
<ide> # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }
<del> # # => Will set a cookie that expires in 1 hour
<ide> #
<ide> # Examples for reading:
<ide> #
<ide> # cookies[:user_name] # => "david"
<del> # cookies.size # => 2
<add> # cookies.size # => 2
<ide> #
<ide> # Example for deleting:
<ide> #
<ide> # cookies.delete :user_name
<ide> #
<del> # All the option symbols for setting cookies are:
<add> # The option symbols for setting cookies are:
<ide> #
<del> # * <tt>value</tt> - the cookie's value or list of values (as an array).
<del> # * <tt>path</tt> - the path for which this cookie applies. Defaults to the root of the application.
<del> # * <tt>domain</tt> - the domain for which this cookie applies.
<del> # * <tt>expires</tt> - the time at which this cookie expires, as a +Time+ object.
<del> # * <tt>secure</tt> - whether this cookie is a secure cookie or not (default to false).
<del> # Secure cookies are only transmitted to HTTPS servers.
<del> # * <tt>http_only</tt> - whether this cookie is accessible via scripting or only HTTP (defaults to false).
<del>
<add> # * <tt>:value</tt> - The cookie's value or list of values (as an array).
<add> # * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
<add> # of the application.
<add> # * <tt>:domain</tt> - The domain for which this cookie applies.
<add> # * <tt>:expires</tt> - The time at which this cookie expires, as a Time object.
<add> # * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers.
<add> # Default is +false+.
<add> # * <tt>:http_only</tt> - Whether this cookie is accessible via scripting or
<add> # only HTTP. Defaults to +false+.
<ide> module Cookies
<ide> def self.included(base)
<ide> base.helper_method :cookies
<ide> def initialize(controller)
<ide> update(@cookies)
<ide> end
<ide>
<del> # Returns the value of the cookie by +name+ -- or nil if no such cookie exists. You set new cookies using cookies[]=
<del> # (for simple name/value cookies without options).
<add> # Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
<ide> def [](name)
<ide> cookie = @cookies[name.to_s]
<ide> if cookie && cookie.respond_to?(:value)
<ide> cookie.size > 1 ? cookie.value : cookie.value[0]
<ide> end
<ide> end
<ide>
<add> # Sets the cookie named +name+. The second argument may be the very cookie
<add> # value, or a hash of options as documented above.
<ide> def []=(name, options)
<ide> if options.is_a?(Hash)
<ide> options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
<ide> def []=(name, options)
<ide> end
<ide>
<ide> # Removes the cookie on the client machine by setting the value to an empty string
<del> # and setting its expiration date into the past. Like []=, you can pass in an options
<del> # hash to delete cookies with extra data such as a +path+.
<add> # and setting its expiration date into the past. Like <tt>[]=</tt>, you can pass in
<add> # an options hash to delete cookies with extra data such as a <tt>:path</tt>.
<ide> def delete(name, options = {})
<ide> options.stringify_keys!
<ide> set_cookie(options.merge("name" => name.to_s, "value" => "", "expires" => Time.at(0)))
<ide> end
<ide>
<ide> private
<add> # Builds a CGI::Cookie object and adds the cookie to the response headers.
<add> #
<add> # The path of the cookie defaults to "/" if there's none in +options+, and
<add> # everything is passed to the CGI::Cookie constructor.
<ide> def set_cookie(options) #:doc:
<ide> options["path"] = "/" unless options["path"]
<ide> cookie = CGI::Cookie.new(options)
<ide><path>actionpack/lib/action_controller/filters.rb
<ide> def self.included(base)
<ide> # end
<ide> #
<ide> # To use a filter object with around_filter, pass an object responding
<del> # to :filter or both :before and :after. With a filter method, yield to
<del> # the block as above:
<add> # to <tt>:filter</tt> or both <tt>:before</tt> and <tt>:after</tt>. With a
<add> # filter method, yield to the block as above:
<ide> #
<ide> # around_filter BenchmarkingFilter
<ide> #
<ide> def self.included(base)
<ide> # == Filter conditions
<ide> #
<ide> # Filters may be limited to specific actions by declaring the actions to
<del> # include or exclude. Both options accept single actions (:only => :index)
<del> # or arrays of actions (:except => [:foo, :bar]).
<add> # include or exclude. Both options accept single actions
<add> # (<tt>:only => :index</tt>) or arrays of actions
<add> # (<tt>:except => [:foo, :bar]</tt>).
<ide> #
<ide> # class Journal < ActionController::Base
<ide> # # Require authentication for edit and delete.
<ide><path>actionpack/lib/action_controller/helpers.rb
<ide> def helper(*args, &block)
<ide> # Declare a controller method as a helper. For example, the following
<ide> # makes the +current_user+ controller method available to the view:
<ide> # class ApplicationController < ActionController::Base
<del> # helper_method :current_user
<add> # helper_method :current_user, :logged_in?
<add> #
<ide> # def current_user
<del> # @current_user ||= User.find(session[:user])
<add> # @current_user ||= User.find_by_id(session[:user])
<ide> # end
<add> #
<add> # def logged_in?
<add> # current_user != nil
<add> # end
<ide> # end
<add> #
<add> # In a view:
<add> # <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
<ide> def helper_method(*methods)
<ide> methods.flatten.each do |method|
<ide> master_helper_module.module_eval <<-end_eval
<ide><path>actionpack/lib/action_controller/polymorphic_routes.rb
<ide> module ActionController
<ide> # * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
<ide> # <tt>url_for(@article)</tt>;
<ide> # * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
<del> # <tt>form_for(@article)</tt> without having to specify :url parameter for the form
<add> # <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
<ide> # action;
<ide> # * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
<ide> # <tt>redirect_to(post)</tt> in your controllers;
<ide><path>actionpack/lib/action_controller/request.rb
<ide> class AbstractRequest
<ide> # such as { 'RAILS_ENV' => 'production' }.
<ide> attr_reader :env
<ide>
<del> # The true HTTP request method as a lowercase symbol, such as :get.
<add> # The true HTTP request method as a lowercase symbol, such as <tt>:get</tt>.
<ide> # UnknownHttpMethod is raised for invalid methods not listed in ACCEPTED_HTTP_METHODS.
<ide> def request_method
<ide> @request_method ||= begin
<ide> def request_method
<ide> end
<ide> end
<ide>
<del> # The HTTP request method as a lowercase symbol, such as :get.
<del> # Note, HEAD is returned as :get since the two are functionally
<add> # The HTTP request method as a lowercase symbol, such as <tt>:get</tt>.
<add> # Note, HEAD is returned as <tt>:get</tt> since the two are functionally
<ide> # equivalent from the application's perspective.
<ide> def method
<ide> request_method == :head ? :get : request_method
<ide> end
<ide>
<del> # Is this a GET (or HEAD) request? Equivalent to request.method == :get
<add> # Is this a GET (or HEAD) request? Equivalent to <tt>request.method == :get</tt>.
<ide> def get?
<ide> method == :get
<ide> end
<ide>
<del> # Is this a POST request? Equivalent to request.method == :post
<add> # Is this a POST request? Equivalent to <tt>request.method == :post</tt>.
<ide> def post?
<ide> request_method == :post
<ide> end
<ide>
<del> # Is this a PUT request? Equivalent to request.method == :put
<add> # Is this a PUT request? Equivalent to <tt>request.method == :put</tt>.
<ide> def put?
<ide> request_method == :put
<ide> end
<ide>
<del> # Is this a DELETE request? Equivalent to request.method == :delete
<add> # Is this a DELETE request? Equivalent to <tt>request.method == :delete</tt>.
<ide> def delete?
<ide> request_method == :delete
<ide> end
<ide>
<del> # Is this a HEAD request? request.method sees HEAD as :get, so check the
<del> # HTTP method directly.
<add> # Is this a HEAD request? <tt>request.method</tt> sees HEAD as <tt>:get</tt>,
<add> # so check the HTTP method directly.
<ide> def head?
<ide> request_method == :head
<ide> end
<ide><path>actionpack/lib/action_controller/request_forgery_protection.rb
<ide> def verifiable_request_format?
<ide> request.format.html? || request.format.js?
<ide> end
<ide>
<del> # Sets the token value for the current session. Pass a :secret option in #protect_from_forgery to add a custom salt to the hash.
<add> # Sets the token value for the current session. Pass a <tt>:secret</tt> option
<add> # in +protect_from_forgery+ to add a custom salt to the hash.
<ide> def form_authenticity_token
<ide> @form_authenticity_token ||= if request_forgery_protection_options[:secret]
<ide> authenticity_token_from_session_id
<ide><path>actionpack/lib/action_controller/rescue.rb
<ide> def process_with_exception(request, response, exception) #:nodoc:
<ide> # Rescue exceptions raised in controller actions.
<ide> #
<ide> # <tt>rescue_from</tt> receives a series of exception classes or class
<del> # names, and a trailing :with option with the name of a method or a Proc
<del> # object to be called to handle them. Alternatively a block can be given.
<add> # names, and a trailing <tt>:with</tt> option with the name of a method
<add> # or a Proc object to be called to handle them. Alternatively a block can
<add> # be given.
<ide> #
<ide> # Handlers that take one argument will be called with the exception, so
<ide> # that the exception can be inspected when dealing with it.
<ide> #
<ide> # Handlers are inherited. They are searched from right to left, from
<ide> # bottom to top, and up the hierarchy. The handler of the first class for
<del> # which exception.is_a?(klass) holds true is the one invoked, if any.
<add> # which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
<add> # any.
<ide> #
<del> # class ApplicationController < ActionController::Base
<del> # rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
<del> # rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
<add> # class ApplicationController < ActionController::Base
<add> # rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
<add> # rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
<ide> #
<del> # rescue_from 'MyAppError::Base' do |exception|
<del> # render :xml => exception, :status => 500
<del> # end
<del> #
<del> # protected
<del> # def deny_access
<del> # ...
<add> # rescue_from 'MyAppError::Base' do |exception|
<add> # render :xml => exception, :status => 500
<ide> # end
<ide> #
<del> # def show_errors(exception)
<del> # exception.record.new_record? ? ...
<del> # end
<del> # end
<add> # protected
<add> # def deny_access
<add> # ...
<add> # end
<add> #
<add> # def show_errors(exception)
<add> # exception.record.new_record? ? ...
<add> # end
<add> # end
<ide> def rescue_from(*klasses, &block)
<ide> options = klasses.extract_options!
<ide> unless options.has_key?(:with)
<ide><path>actionpack/lib/action_controller/resources.rb
<ide> def initialize(entity, options)
<ide> # * <tt>:collection</tt> - add named routes for other actions that operate on the collection.
<ide> # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt>
<ide> # or <tt>:any</tt> if the method does not matter. These routes map to a URL like /messages/rss, with a route of rss_messages_url.
<del> # * <tt>:member</tt> - same as :collection, but for actions that operate on a specific member.
<del> # * <tt>:new</tt> - same as :collection, but for actions that operate on the new resource action.
<add> # * <tt>:member</tt> - same as <tt>:collection</tt>, but for actions that operate on a specific member.
<add> # * <tt>:new</tt> - same as <tt>:collection</tt>, but for actions that operate on the new resource action.
<ide> # * <tt>:controller</tt> - specify the controller name for the routes.
<ide> # * <tt>:singular</tt> - specify the singular name used in the member routes.
<ide> # * <tt>:requirements</tt> - set custom routing parameter requirements.
<del> # * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the :method value for the method-specific routes.
<add> # * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the <tt>:method</tt> value for the method-specific routes.
<ide> # * <tt>:as</tt> - specify a different resource name to use in the URL path. For example:
<ide> # # products_path == '/productos'
<ide> # map.resources :products, :as => 'productos' do |product|
<ide> def initialize(entity, options)
<ide> # end
<ide> #
<ide> # * <tt>:has_one</tt> - specify nested resources, this is a shorthand for mapping singleton resources beneath the current.
<del> # * <tt>:has_many</tt> - same has :has_one, but for plural resources.
<add> # * <tt>:has_many</tt> - same has <tt>:has_one</tt>, but for plural resources.
<ide> #
<ide> # You may directly specify the routing association with has_one and has_many like:
<ide> #
<ide> def initialize(entity, options)
<ide> # article.resources :comments
<ide> # end
<ide> #
<del> # The comment resources work the same, but must now include a value for :article_id.
<add> # The comment resources work the same, but must now include a value for <tt>:article_id</tt>.
<ide> #
<ide> # article_comments_url(@article)
<ide> # article_comment_url(@article, @comment)
<ide> def initialize(entity, options)
<ide> # map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_'
<ide> # map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_'
<ide> #
<del> # You may also use :name_prefix to override the generic named routes in a nested resource:
<add> # You may also use <tt>:name_prefix</tt> to override the generic named routes in a nested resource:
<ide> #
<ide> # map.resources :articles do |article|
<ide> # article.resources :comments, :name_prefix => nil
<ide> def resources(*entities, &block)
<ide> #
<ide> # See map.resources for general conventions. These are the main differences:
<ide> # * A singular name is given to map.resource. The default controller name is still taken from the plural name.
<del> # * To specify a custom plural name, use the :plural option. There is no :singular option.
<add> # * To specify a custom plural name, use the <tt>:plural</tt> option. There is no <tt>:singular</tt> option.
<ide> # * No default index route is created for the singleton resource controller.
<ide> # * When nesting singleton resources, only the singular name is used as the path prefix (example: 'account/messages/1')
<ide> #
<ide><path>actionpack/lib/action_controller/routing.rb
<ide> module ActionController
<ide> # map.connect ':controller/:action/:id'
<ide> #
<ide> # This route states that it expects requests to consist of a
<del> # :controller followed by an :action that in turn is fed some :id.
<add> # <tt>:controller</tt> followed by an <tt>:action</tt> that in turn is fed
<add> # some <tt>:id</tt>.
<ide> #
<ide> # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end up
<ide> # with:
<ide> module ActionController
<ide> # Think of creating routes as drawing a map for your requests. The map tells
<ide> # them where to go based on some predefined pattern:
<ide> #
<del> # ActionController::Routing::Routes.draw do |map|
<del> # Pattern 1 tells some request to go to one place
<del> # Pattern 2 tell them to go to another
<del> # ...
<del> # end
<add> # ActionController::Routing::Routes.draw do |map|
<add> # Pattern 1 tells some request to go to one place
<add> # Pattern 2 tell them to go to another
<add> # ...
<add> # end
<ide> #
<ide> # The following symbols are special:
<ide> #
<ide> module ActionController
<ide> # Within blocks, the empty pattern is at the highest priority.
<ide> # In practice this works out nicely:
<ide> #
<del> # ActionController::Routing::Routes.draw do |map|
<del> # map.with_options :controller => 'blog' do |blog|
<del> # blog.show '', :action => 'list'
<del> # end
<del> # map.connect ':controller/:action/:view'
<del> # end
<add> # ActionController::Routing::Routes.draw do |map|
<add> # map.with_options :controller => 'blog' do |blog|
<add> # blog.show '', :action => 'list'
<add> # end
<add> # map.connect ':controller/:action/:view'
<add> # end
<ide> #
<ide> # In this case, invoking blog controller (with an URL like '/blog/')
<ide> # without parameters will activate the 'list' action by default.
<ide> module ActionController
<ide> # Hash at the end of your mapping to set any default parameters.
<ide> #
<ide> # Example:
<del> # ActionController::Routing:Routes.draw do |map|
<del> # map.connect ':controller/:action/:id', :controller => 'blog'
<del> # end
<add> #
<add> # ActionController::Routing:Routes.draw do |map|
<add> # map.connect ':controller/:action/:id', :controller => 'blog'
<add> # end
<ide> #
<ide> # This sets up +blog+ as the default controller if no other is specified.
<ide> # This means visiting '/' would invoke the blog controller.
<ide> module ActionController
<ide> # for the full URL and +name_of_route_path+ for the URI path.
<ide> #
<ide> # Example:
<add> #
<ide> # # In routes.rb
<ide> # map.login 'login', :controller => 'accounts', :action => 'login'
<ide> #
<ide> module ActionController
<ide> #
<ide> # Routes can generate pretty URLs. For example:
<ide> #
<del> # map.connect 'articles/:year/:month/:day',
<del> # :controller => 'articles',
<del> # :action => 'find_by_date',
<del> # :year => /\d{4}/,
<del> # :month => /\d{1,2}/,
<del> # :day => /\d{1,2}/
<add> # map.connect 'articles/:year/:month/:day',
<add> # :controller => 'articles',
<add> # :action => 'find_by_date',
<add> # :year => /\d{4}/,
<add> # :month => /\d{1,2}/,
<add> # :day => /\d{1,2}/
<add> #
<add> # Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
<add> # maps to
<ide> #
<del> # # Using the route above, the url below maps to:
<del> # # params = {:year => '2005', :month => '11', :day => '06'}
<del> # # http://localhost:3000/articles/2005/11/06
<add> # params = {:year => '2005', :month => '11', :day => '06'}
<ide> #
<ide> # == Regular Expressions and parameters
<ide> # You can specify a regular expression to define a format for a parameter.
<ide> #
<del> # map.geocode 'geocode/:postalcode', :controller => 'geocode',
<del> # :action => 'show', :postalcode => /\d{5}(-\d{4})?/
<add> # map.geocode 'geocode/:postalcode', :controller => 'geocode',
<add> # :action => 'show', :postalcode => /\d{5}(-\d{4})?/
<ide> #
<ide> # or, more formally:
<ide> #
<ide> module ActionController
<ide> #
<ide> # Specifying <tt>*[string]</tt> as part of a rule like:
<ide> #
<del> # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
<add> # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
<ide> #
<ide> # will glob all remaining parts of the route that were not recognized earlier. This idiom
<ide> # must appear at the end of the path. The globbed values are in <tt>params[:path]</tt> in
<ide> module ActionController
<ide> #
<ide> # You can reload routes if you feel you must:
<ide> #
<del> # ActionController::Routing::Routes.reload
<add> # ActionController::Routing::Routes.reload
<ide> #
<ide> # This will clear all named routes and reload routes.rb if the file has been modified from
<ide> # last load. To absolutely force reloading, use +reload!+.
<ide> module ActionController
<ide> #
<ide> # === +assert_routing+
<ide> #
<del> # def test_movie_route_properly_splits
<del> # opts = {:controller => "plugin", :action => "checkout", :id => "2"}
<del> # assert_routing "plugin/checkout/2", opts
<del> # end
<add> # def test_movie_route_properly_splits
<add> # opts = {:controller => "plugin", :action => "checkout", :id => "2"}
<add> # assert_routing "plugin/checkout/2", opts
<add> # end
<ide> #
<ide> # +assert_routing+ lets you test whether or not the route properly resolves into options.
<ide> #
<ide> # === +assert_recognizes+
<ide> #
<del> # def test_route_has_options
<del> # opts = {:controller => "plugin", :action => "show", :id => "12"}
<del> # assert_recognizes opts, "/plugins/show/12"
<del> # end
<add> # def test_route_has_options
<add> # opts = {:controller => "plugin", :action => "show", :id => "12"}
<add> # assert_recognizes opts, "/plugins/show/12"
<add> # end
<ide> #
<ide> # Note the subtle difference between the two: +assert_routing+ tests that
<ide> # a URL fits options while +assert_recognizes+ tests that a URL
<ide> # breaks into parameters properly.
<ide> #
<ide> # In tests you can simply pass the URL or named route to +get+ or +post+.
<ide> #
<del> # def send_to_jail
<del> # get '/jail'
<del> # assert_response :success
<del> # assert_template "jail/front"
<del> # end
<add> # def send_to_jail
<add> # get '/jail'
<add> # assert_response :success
<add> # assert_template "jail/front"
<add> # end
<ide> #
<del> # def goes_to_login
<del> # get login_url
<del> # #...
<del> # end
<add> # def goes_to_login
<add> # get login_url
<add> # #...
<add> # end
<ide> #
<ide> # == View a list of all your routes
<ide> #
<ide><path>actionpack/lib/action_controller/routing/builder.rb
<ide> def assign_route_options(segments, defaults, requirements)
<ide> route_requirements
<ide> end
<ide>
<del> # Assign default options, such as 'index' as a default for :action. This
<add> # Assign default options, such as 'index' as a default for <tt>:action</tt>. This
<ide> # method must be run *after* user supplied requirements and defaults have
<ide> # been applied to the segments.
<ide> def assign_default_route_options(segments)
<ide> def build(path, options)
<ide> end
<ide>
<ide> # Routes cannot use the current string interpolation method
<del> # if there are user-supplied :requirements as the interpolation
<add> # if there are user-supplied <tt>:requirements</tt> as the interpolation
<ide> # code won't raise RoutingErrors when generating
<ide> if options.key?(:requirements) || route.requirements.keys.to_set != Routing::ALLOWED_REQUIREMENTS_FOR_OPTIMISATION
<ide> route.optimise = false
<ide><path>actionpack/lib/action_controller/routing/optimisations.rb
<ide> module ActionController
<ide> module Routing
<ide> # Much of the slow performance from routes comes from the
<del> # complexity of expiry, :requirements matching, defaults providing
<add> # complexity of expiry, <tt>:requirements</tt> matching, defaults providing
<ide> # and figuring out which url pattern to use. With named routes
<ide> # we can avoid the expense of finding the right route. So if
<ide> # they've provided the right number of arguments, and have no
<del> # :requirements, we can just build up a string and return it.
<add> # <tt>:requirements</tt>, we can just build up a string and return it.
<ide> #
<ide> # To support building optimisations for other common cases, the
<ide> # generation code is separated into several classes
<ide> def source_code
<ide> end
<ide> end
<ide>
<del> # Temporarily disabled :url optimisation pending proper solution to
<add> # Temporarily disabled <tt>:url</tt> optimisation pending proper solution to
<ide> # Issues around request.host etc.
<ide> def applicable?
<ide> true
<ide> end
<ide> end
<ide>
<del> # Given a route:
<del> # map.person '/people/:id'
<add> # Given a route
<ide> #
<del> # If the user calls person_url(@person), we can simply
<add> # map.person '/people/:id'
<add> #
<add> # If the user calls <tt>person_url(@person)</tt>, we can simply
<ide> # return a string like "/people/#{@person.to_param}"
<del> # rather than triggering the expensive logic in url_for
<add> # rather than triggering the expensive logic in +url_for+.
<ide> class PositionalArguments < Optimiser
<ide> def guard_condition
<ide> number_of_arguments = route.segment_keys.size
<ide> def generation_code
<ide>
<ide> elements << '#{request.relative_url_root if request.relative_url_root}'
<ide>
<del> # The last entry in route.segments appears to # *always* be a
<add> # The last entry in <tt>route.segments</tt> appears to *always* be a
<ide> # 'divider segment' for '/' but we have assertions to ensure that
<ide> # we don't include the trailing slashes, so skip them.
<ide> (route.segments.size == 1 ? route.segments : route.segments[0..-2]).each do |segment|
<ide> def generation_code
<ide> super.insert(-2, '?#{args.last.to_query}')
<ide> end
<ide>
<del> # To avoid generating http://localhost/?host=foo.example.com we
<add> # To avoid generating "http://localhost/?host=foo.example.com" we
<ide> # can't use this optimisation on routes without any segments
<ide> def applicable?
<ide> super && route.segment_keys.size > 0
<ide><path>actionpack/lib/action_controller/routing/route.rb
<ide> def append_query_string(path, hash, query_keys=nil)
<ide> # those that were not used to generate a particular route. The extra
<ide> # keys also do not include those recalled from the prior request, nor
<ide> # do they include any keys that were implied in the route (like a
<del> # :controller that is required, but not explicitly used in the text of
<del> # the route.)
<add> # <tt>:controller</tt> that is required, but not explicitly used in the
<add> # text of the route.)
<ide> def extra_keys(hash, recall={})
<ide> (hash || {}).keys.map { |k| k.to_sym } - (recall || {}).keys - significant_keys
<ide> end
<ide><path>actionpack/lib/action_controller/session/cookie_store.rb
<ide> # TamperedWithCookie is raised if the data integrity check fails.
<ide> #
<ide> # A message digest is included with the cookie to ensure data integrity:
<del># a user cannot alter his user_id without knowing the secret key included in
<add># a user cannot alter his +user_id+ without knowing the secret key included in
<ide> # the hash. New apps are generated with a pregenerated secret in
<ide> # config/environment.rb. Set your own for old apps you're upgrading.
<ide> #
<ide> # Session options:
<del># :secret An application-wide key string or block returning a string
<del># called per generated digest. The block is called with the
<del># CGI::Session instance as an argument. It's important that the
<del># secret is not vulnerable to a dictionary attack. Therefore,
<del># you should choose a secret consisting of random numbers and
<del># letters and more than 30 characters.
<ide> #
<del># Example: :secret => '449fe2e7daee471bffae2fd8dc02313d'
<del># :secret => Proc.new { User.current_user.secret_key }
<add># * <tt>:secret</tt>: An application-wide key string or block returning a string
<add># called per generated digest. The block is called with the CGI::Session
<add># instance as an argument. It's important that the secret is not vulnerable to
<add># a dictionary attack. Therefore, you should choose a secret consisting of
<add># random numbers and letters and more than 30 characters. Examples:
<ide> #
<del># :digest The message digest algorithm used to verify session integrity
<del># defaults to 'SHA1' but may be any digest provided by OpenSSL,
<del># such as 'MD5', 'RIPEMD160', 'SHA256', etc.
<add># :secret => '449fe2e7daee471bffae2fd8dc02313d'
<add># :secret => Proc.new { User.current_user.secret_key }
<add>#
<add># * <tt>:digest</tt>: The message digest algorithm used to verify session
<add># integrity defaults to 'SHA1' but may be any digest provided by OpenSSL,
<add># such as 'MD5', 'RIPEMD160', 'SHA256', etc.
<ide> #
<ide> # To generate a secret key for an existing application, run
<del># `rake secret` and set the key in config/environment.rb
<add># `rake secret` and set the key in config/environment.rb.
<ide> #
<ide> # Note that changing digest or secret invalidates all existing sessions!
<ide> class CGI::Session::CookieStore
<ide><path>actionpack/lib/action_controller/session_management.rb
<ide> def self.included(base)
<ide> end
<ide>
<ide> module ClassMethods
<del> # Set the session store to be used for keeping the session data between requests. By default, sessions are stored
<del> # in browser cookies (:cookie_store), but you can also specify one of the other included stores
<del> # (:active_record_store, :p_store, drb_store, :mem_cache_store, or :memory_store) or your own custom class.
<add> # Set the session store to be used for keeping the session data between requests.
<add> # By default, sessions are stored in browser cookies (<tt>:cookie_store</tt>),
<add> # but you can also specify one of the other included stores (<tt>:active_record_store</tt>,
<add> # <tt>:p_store</tt>, <tt>:drb_store</tt>, <tt>:mem_cache_store</tt>, or
<add> # <tt>:memory_store</tt>) or your own custom class.
<ide> def session_store=(store)
<ide> ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:database_manager] =
<ide> store.is_a?(Symbol) ? CGI::Session.const_get(store == :drb_store ? "DRbStore" : store.to_s.camelize) : store
<ide><path>actionpack/lib/action_controller/streaming.rb
<ide> module Streaming
<ide> # it feasible to send even large files.
<ide> #
<ide> # Be careful to sanitize the path parameter if it coming from a web
<del> # page. send_file(params[:path]) allows a malicious user to
<add> # page. <tt>send_file(params[:path])</tt> allows a malicious user to
<ide> # download any file on your server.
<ide> #
<ide> # Options:
<ide> # * <tt>:filename</tt> - suggests a filename for the browser to use.
<del> # Defaults to File.basename(path).
<add> # Defaults to <tt>File.basename(path)</tt>.
<ide> # * <tt>:type</tt> - specifies an HTTP content type.
<ide> # Defaults to 'application/octet-stream'.
<ide> # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
<ide> # Valid values are 'inline' and 'attachment' (default).
<del> # * <tt>:stream</tt> - whether to send the file to the user agent as it is read (true)
<del> # or to read the entire file before sending (false). Defaults to true.
<add> # * <tt>:stream</tt> - whether to send the file to the user agent as it is read (+true+)
<add> # or to read the entire file before sending (+false+). Defaults to +true+.
<ide> # * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
<ide> # Defaults to 4096.
<ide> # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
<del> # * <tt>:url_based_filename</tt> - set to true if you want the browser guess the filename from
<add> # * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
<ide> # the URL, which is necessary for i18n filenames on certain browsers
<del> # (setting :filename overrides this option).
<add> # (setting <tt>:filename</tt> overrides this option).
<ide> #
<ide> # The default Content-Type and Content-Disposition headers are
<ide> # set to download arbitrary binary files in as many browsers as
<ide> # possible. IE versions 4, 5, 5.5, and 6 are all known to have
<ide> # a variety of quirks (especially when downloading over SSL).
<ide> #
<ide> # Simple download:
<add> #
<ide> # send_file '/path/to.zip'
<ide> #
<ide> # Show a JPEG in the browser:
<add> #
<ide> # send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
<ide> #
<ide> # Show a 404 page in the browser:
<add> #
<ide> # send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404
<ide> #
<ide> # Read about the other Content-* HTTP headers if you'd like to
<del> # provide the user with more information (such as Content-Description).
<del> # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
<add> # provide the user with more information (such as Content-Description) in
<add> # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
<ide> #
<ide> # Also be aware that the document may be cached by proxies and browsers.
<ide> # The Pragma and Cache-Control headers declare how the file may be cached
<ide> def send_file(path, options = {}) #:doc:
<ide> # and specify whether to show data inline or download as an attachment.
<ide> #
<ide> # Options:
<del> # * <tt>:filename</tt> - Suggests a filename for the browser to use.
<add> # * <tt>:filename</tt> - suggests a filename for the browser to use.
<ide> # * <tt>:type</tt> - specifies an HTTP content type.
<ide> # Defaults to 'application/octet-stream'.
<ide> # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
<ide> # Valid values are 'inline' and 'attachment' (default).
<ide> # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
<ide> #
<ide> # Generic data download:
<add> #
<ide> # send_data buffer
<ide> #
<ide> # Download a dynamically-generated tarball:
<add> #
<ide> # send_data generate_tgz('dir'), :filename => 'dir.tgz'
<ide> #
<ide> # Display an image Active Record in the browser:
<add> #
<ide> # send_data image.data, :type => image.content_type, :disposition => 'inline'
<ide> #
<ide> # See +send_file+ for more information on HTTP Content-* headers and caching.
<ide><path>actionpack/lib/action_controller/test_process.rb
<ide> def url_encoded_request_parameters
<ide> # A refactoring of TestResponse to allow the same behavior to be applied
<ide> # to the "real" CgiResponse class in integration tests.
<ide> module TestResponseBehavior #:nodoc:
<del> # the response code of the request
<add> # The response code of the request
<ide> def response_code
<ide> headers['Status'][0,3].to_i rescue 0
<ide> end
<ide>
<del> # returns a String to ensure compatibility with Net::HTTPResponse
<add> # Returns a String to ensure compatibility with Net::HTTPResponse
<ide> def code
<ide> headers['Status'].to_s.split(' ')[0]
<ide> end
<ide> def message
<ide> headers['Status'].to_s.split(' ',2)[1]
<ide> end
<ide>
<del> # was the response successful?
<add> # Was the response successful?
<ide> def success?
<ide> response_code == 200
<ide> end
<ide>
<del> # was the URL not found?
<add> # Was the URL not found?
<ide> def missing?
<ide> response_code == 404
<ide> end
<ide>
<del> # were we redirected?
<add> # Were we redirected?
<ide> def redirect?
<ide> (300..399).include?(response_code)
<ide> end
<ide>
<del> # was there a server-side error?
<add> # Was there a server-side error?
<ide> def error?
<ide> (500..599).include?(response_code)
<ide> end
<ide>
<ide> alias_method :server_error?, :error?
<ide>
<del> # returns the redirection location or nil
<add> # Returns the redirection location or nil
<ide> def redirect_url
<ide> headers['Location']
<ide> end
<ide>
<del> # does the redirect location match this regexp pattern?
<add> # Does the redirect location match this regexp pattern?
<ide> def redirect_url_match?( pattern )
<ide> return false if redirect_url.nil?
<ide> p = Regexp.new(pattern) if pattern.class == String
<ide> def redirect_url_match?( pattern )
<ide> p.match(redirect_url) != nil
<ide> end
<ide>
<del> # returns the template path of the file which was used to
<add> # Returns the template path of the file which was used to
<ide> # render this response (or nil)
<ide> def rendered_file(with_controller=false)
<ide> unless template.first_render.nil?
<ide> def rendered_file(with_controller=false)
<ide> end
<ide> end
<ide>
<del> # was this template rendered by a file?
<add> # Was this template rendered by a file?
<ide> def rendered_with_file?
<ide> !rendered_file.nil?
<ide> end
<ide>
<del> # a shortcut to the flash (or an empty hash if no flash.. hey! that rhymes!)
<add> # A shortcut to the flash. Returns an empyt hash if no session flash exists.
<ide> def flash
<ide> session['flash'] || {}
<ide> end
<ide>
<del> # do we have a flash?
<add> # Do we have a flash?
<ide> def has_flash?
<ide> !session['flash'].empty?
<ide> end
<ide>
<del> # do we have a flash that has contents?
<add> # Do we have a flash that has contents?
<ide> def has_flash_with_contents?
<ide> !flash.empty?
<ide> end
<ide>
<del> # does the specified flash object exist?
<add> # Does the specified flash object exist?
<ide> def has_flash_object?(name=nil)
<ide> !flash[name].nil?
<ide> end
<ide>
<del> # does the specified object exist in the session?
<add> # Does the specified object exist in the session?
<ide> def has_session_object?(name=nil)
<ide> !session[name].nil?
<ide> end
<ide>
<del> # a shortcut to the template.assigns
<add> # A shortcut to the template.assigns
<ide> def template_objects
<ide> template.assigns || {}
<ide> end
<ide>
<del> # does the specified template object exist?
<add> # Does the specified template object exist?
<ide> def has_template_object?(name=nil)
<ide> !template_objects[name].nil?
<ide> end
<ide>
<ide> # Returns the response cookies, converted to a Hash of (name => CGI::Cookie) pairs
<del> # Example:
<ide> #
<del> # assert_equal ['AuthorOfNewPage'], r.cookies['author'].value
<add> # assert_equal ['AuthorOfNewPage'], r.cookies['author'].value
<ide> def cookies
<ide> headers['cookie'].inject({}) { |hash, cookie| hash[cookie.name] = cookie; hash }
<ide> end
<ide> def method_missing(selector, *args)
<ide> return super
<ide> end
<ide>
<del> # Shortcut for ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type). Example:
<add> # Shortcut for <tt>ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type)</tt>:
<add> #
<ide> # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
<ide> #
<del> # To upload binary files on Windows, pass :binary as the last parameter. This will not affect other platforms.
<add> # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
<add> # This will not affect other platforms:
<add> #
<ide> # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
<ide> def fixture_file_upload(path, mime_type = nil, binary = false)
<ide> ActionController::TestUploadedFile.new(
<ide> def fixture_file_upload(path, mime_type = nil, binary = false)
<ide> # with a new RouteSet instance.
<ide> #
<ide> # The new instance is yielded to the passed block. Typically the block
<del> # will create some routes using map.draw { map.connect ... }:
<add> # will create some routes using <tt>map.draw { map.connect ... }</tt>:
<ide> #
<del> # with_routing do |set|
<del> # set.draw do |map|
<del> # map.connect ':controller/:action/:id'
<del> # assert_equal(
<del> # ['/content/10/show', {}],
<del> # map.generate(:controller => 'content', :id => 10, :action => 'show')
<del> # end
<del> # end
<del> # end
<add> # with_routing do |set|
<add> # set.draw do |map|
<add> # map.connect ':controller/:action/:id'
<add> # assert_equal(
<add> # ['/content/10/show', {}],
<add> # map.generate(:controller => 'content', :id => 10, :action => 'show')
<add> # end
<add> # end
<add> # end
<ide> #
<ide> def with_routing
<ide> real_routes = ActionController::Routing::Routes
<ide><path>actionpack/lib/action_controller/url_rewriter.rb
<ide> module ActionController
<ide> # In addition to providing +url_for+, named routes are also accessible after
<ide> # including UrlWriter.
<ide> module UrlWriter
<del> # The default options for urls written by this writer. Typically a :host pair
<del> # is provided.
<add> # The default options for urls written by this writer. Typically a <tt>:host</tt>
<add> # pair is provided.
<ide> mattr_accessor :default_url_options
<ide> self.default_url_options = {}
<ide>
<ide> def self.included(base) #:nodoc:
<ide> # Generate a url based on the options provided, default_url_options and the
<ide> # routes defined in routes.rb. The following options are supported:
<ide> #
<del> # * <tt>:only_path</tt> If true, the relative url is returned. Defaults to false.
<add> # * <tt>:only_path</tt> If true, the relative url is returned. Defaults to +false+.
<ide> # * <tt>:protocol</tt> The protocol to connect to. Defaults to 'http'.
<del> # * <tt>:host</tt> Specifies the host the link should be targetted at. If <tt>:only_path</tt> is false, this option must be
<del> # provided either explicitly, or via default_url_options.
<add> # * <tt>:host</tt> Specifies the host the link should be targetted at.
<add> # If <tt>:only_path</tt> is false, this option must be
<add> # provided either explicitly, or via +default_url_options+.
<ide> # * <tt>:port</tt> Optionally specify the port to connect to.
<ide> # * <tt>:anchor</tt> An anchor name to be appended to the path.
<del> # * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the relative_url_root set in <tt>ActionController::AbstractRequest.relative_url_root</tt>.
<add> # * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the
<add> # +relative_url_root+ set in ActionController::AbstractRequest.relative_url_root.
<ide> # * <tt>:trailing_slash</tt> If true, adds a trailing slash, as in "/archive/2009/"
<ide> #
<del> # Any other key(:controller, :action, etc...) given to <tt>url_for</tt> is forwarded to the Routes module.
<add> # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
<add> # +url_for+ is forwarded to the Routes module.
<ide> #
<ide> # Examples:
<ide> #
<ide><path>actionpack/lib/action_view/base.rb
<ide> def file_public?(template_path)#:nodoc:
<ide> template_path.split('/').last[0,1] != '_'
<ide> end
<ide>
<del> # symbolized version of the :format parameter of the request, or :html by default.
<add> # Returns a symbolized version of the <tt>:format</tt> parameter of the request,
<add> # or <tt>:html</tt> by default.
<ide> #
<del> # EXCEPTION: If the :format parameter is not set, the Accept header will be examined for
<add> # EXCEPTION: If the <tt>:format</tt> parameter is not set, the Accept header will be examined for
<ide> # whether it contains the JavaScript mime type as its first priority. If that's the case,
<ide> # it will be used. This ensures that Ajax applications can use the same URL to support both
<ide> # JavaScript and non-JavaScript users.
<ide><path>actionpack/lib/action_view/helpers/active_record_helper.rb
<ide> class Base
<ide> end
<ide>
<ide> module Helpers
<del> # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the form
<add> # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+
<ide> # method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This
<ide> # is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form.
<del> # In that case, it's better to use the input method and the specialized form methods in link:classes/ActionView/Helpers/FormHelper.html
<add> # In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html
<ide> module ActiveRecordHelper
<del> # Returns a default input tag for the type of object returned by the method. For example, let's say you have a model
<del> # that has an attribute +title+ of type VARCHAR column, and this instance holds "Hello World":
<del> # input("post", "title") =>
<del> # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
<add> # Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt>
<add> # has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World":
<add> #
<add> # input("post", "title")
<add> # # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
<ide> def input(record_name, method, options = {})
<ide> InstanceTag.new(record_name, method, self).to_tag(options)
<ide> end
<ide>
<del> # Returns an entire form with all needed input tags for a specified Active Record object. For example, let's say you
<del> # have a table model <tt>Post</tt> with attributes named <tt>title</tt> of type <tt>VARCHAR</tt> and <tt>body</tt> of type <tt>TEXT</tt>:
<add> # Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt>
<add> # has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then
<add> #
<ide> # form("post")
<del> # That line would yield a form like the following:
<del> # <form action='/post/create' method='post'>
<del> # <p>
<del> # <label for="post_title">Title</label><br />
<del> # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
<del> # </p>
<del> # <p>
<del> # <label for="post_body">Body</label><br />
<del> # <textarea cols="40" id="post_body" name="post[body]" rows="20">
<del> # </textarea>
<del> # </p>
<del> # <input type='submit' value='Create' />
<del> # </form>
<add> #
<add> # would yield a form like the following (modulus formatting):
<add> #
<add> # <form action='/posts/create' method='post'>
<add> # <p>
<add> # <label for="post_title">Title</label><br />
<add> # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
<add> # </p>
<add> # <p>
<add> # <label for="post_body">Body</label><br />
<add> # <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
<add> # </p>
<add> # <input name="commit" type="submit" value="Create" />
<add> # </form>
<ide> #
<ide> # It's possible to specialize the form builder by using a different action name and by supplying another
<del> # block renderer. For example, let's say you have a model <tt>Entry</tt> with an attribute <tt>message</tt> of type <tt>VARCHAR</tt>:
<add> # block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then
<add> #
<add> # form("entry",
<add> # :action => "sign",
<add> # :input_block => Proc.new { |record, column|
<add> # "#{column.human_name}: #{input(record, column.name)}<br />"
<add> # })
<ide> #
<del> # form("entry", :action => "sign", :input_block =>
<del> # Proc.new { |record, column| "#{column.human_name}: #{input(record, column.name)}<br />" }) =>
<add> # would yield a form like the following (modulus formatting):
<ide> #
<del> # <form action='/post/sign' method='post'>
<del> # Message:
<del> # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /><br />
<del> # <input type='submit' value='Sign' />
<del> # </form>
<add> # <form action="/entries/sign" method="post">
<add> # Message:
<add> # <input id="entry_message" name="entry[message]" size="30" type="text" /><br />
<add> # <input name="commit" type="submit" value="Sign" />
<add> # </form>
<ide> #
<ide> # It's also possible to add additional content to the form by giving it a block, such as:
<ide> #
<ide> def input(record_name, method, options = {})
<ide> #
<ide> # The following options are available:
<ide> #
<del> # * <tt>action</tt> - the action used when submitting the form (default: create if a new record, otherwise update)
<del> # * <tt>input_block</tt> - specialize the output using a different block, see above
<del> # * <tt>method</tt> - the method used when submitting the form (default: post)
<del> # * <tt>multipart</tt> - whether to change the enctype of the form to multipart/form-date, used when uploading a file (default: false)
<del> # * <tt>submit_value</tt> - the text of the submit button (default: Create if a new record, otherwise Update)
<add> # * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+).
<add> # * <tt>:input_block</tt> - Specialize the output using a different block, see above.
<add> # * <tt>:method</tt> - The method used when submitting the form (default: +post+).
<add> # * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+).
<add> # * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update").
<ide> def form(record_name, options = {})
<ide> record = instance_variable_get("@#{record_name}")
<ide>
<ide> def form(record_name, options = {})
<ide> # Returns a string containing the error message attached to the +method+ on the +object+ if one exists.
<ide> # This error message is wrapped in a <tt>DIV</tt> tag, which can be extended to include a +prepend_text+ and/or +append_text+
<ide> # (to properly explain the error), and a +css_class+ to style it accordingly. +object+ should either be the name of an instance variable or
<del> # the actual object. As an example, let's say you have a model
<del> # +post+ that has an error message on the +title+ attribute:
<add> # the actual object. As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute:
<ide> #
<del> # <%= error_message_on "post", "title" %> =>
<del> # <div class="formError">can't be empty</div>
<add> # <%= error_message_on "post", "title" %>
<add> # # => <div class="formError">can't be empty</div>
<ide> #
<del> # <%= error_message_on @post, "title" %> =>
<del> # <div class="formError">can't be empty</div>
<add> # <%= error_message_on @post, "title" %>
<add> # # => <div class="formError">can't be empty</div>
<ide> #
<del> # <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %> =>
<del> # <div class="inputError">Title simply can't be empty (or it won't work).</div>
<add> # <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %>
<add> # # => <div class="inputError">Title simply can't be empty (or it won't work).</div>
<ide> def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError")
<ide> if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) &&
<ide> (errors = obj.errors.on(method))
<ide> def error_message_on(object, method, prepend_text = "", append_text = "", css_cl
<ide> #
<ide> # This <tt>DIV</tt> can be tailored by the following options:
<ide> #
<del> # * <tt>header_tag</tt> - Used for the header of the error div (default: h2)
<del> # * <tt>id</tt> - The id of the error div (default: errorExplanation)
<del> # * <tt>class</tt> - The class of the error div (default: errorExplanation)
<del> # * <tt>object</tt> - The object (or array of objects) for which to display errors, if you need to escape the instance variable convention
<del> # * <tt>object_name</tt> - The object name to use in the header, or any text that you prefer. If <tt>object_name</tt> is not set, the name of the first object will be used.
<del> # * <tt>header_message</tt> - The message in the header of the error div. Pass +nil+ or an empty string to avoid the header message altogether. (default: X errors prohibited this object from being saved)
<del> # * <tt>message</tt> - The explanation message after the header message and before the error list. Pass +nil+ or an empty string to avoid the explanation message altogether. (default: There were problems with the following fields:)
<add> # * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2").
<add> # * <tt>:id</tt> - The id of the error div (default: "errorExplanation").
<add> # * <tt>:class</tt> - The class of the error div (default: "errorExplanation").
<add> # * <tt>:object</tt> - The object (or array of objects) for which to display errors,
<add> # if you need to escape the instance variable convention.
<add> # * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer.
<add> # If <tt>:object_name</tt> is not set, the name of the first object will be used.
<add> # * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+
<add> # or an empty string to avoid the header message altogether. (Default: "X errors
<add> # prohibited this object from being saved").
<add> # * <tt>:message</tt> - The explanation message after the header message and before
<add> # the error list. Pass +nil+ or an empty string to avoid the explanation message
<add> # altogether. (Default: "There were problems with the following fields:").
<ide> #
<del> # To specify the display for one object, you simply provide its name as a parameter. For example, for the +User+ model:
<add> # To specify the display for one object, you simply provide its name as a parameter.
<add> # For example, for the <tt>@user</tt> model:
<ide> #
<ide> # error_messages_for 'user'
<ide> #
<del> # To specify more than one object, you simply list them; optionally, you can add an extra +object_name+ parameter, which
<del> # will be the name used in the header message.
<add> # To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which
<add> # will be the name used in the header message:
<ide> #
<ide> # error_messages_for 'user_common', 'user', :object_name => 'user'
<ide> #
<del> # If the objects cannot be located as instance variables, you can add an extra +object+ paremeter which gives the actual
<del> # object (or array of objects to use)
<add> # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> paremeter which gives the actual
<add> # object (or array of objects to use):
<ide> #
<ide> # error_messages_for 'user', :object => @question.user
<ide> #
<ide> # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
<del> # you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors
<add> # you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt>
<ide> # instance yourself and set it up. View the source of this method to see how easy it is.
<ide> def error_messages_for(*params)
<ide> options = params.extract_options!.symbolize_keys
<ide><path>actionpack/lib/action_view/helpers/asset_tag_helper.rb
<ide> def javascript_path(source)
<ide> # current page or you can pass the full path relative to your document
<ide> # root. To include the Prototype and Scriptaculous javascript libraries in
<ide> # your application, pass <tt>:defaults</tt> as the source. When using
<del> # :defaults, if an <tt>application.js</tt> file exists in your public
<add> # <tt>:defaults</tt>, if an application.js file exists in your public
<ide> # javascripts directory, it will be included as well. You can modify the
<ide> # html attributes of the script tag by passing a hash as the last argument.
<ide> #
<ide> def stylesheet_path(source)
<ide> # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
<ide> # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
<ide> #
<del> # You can also include all styles in the stylesheet directory using :all as the source:
<add> # You can also include all styles in the stylesheet directory using <tt>:all</tt> as the source:
<ide> #
<ide> # stylesheet_link_tag :all # =>
<ide> # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb
<ide> def time_ago_in_words(from_time, include_seconds = false)
<ide>
<ide> # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
<ide> # +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash,
<del> # which accepts all the keys that each of the individual select builders do (like :use_month_numbers for select_month) as well as a range of
<add> # which accepts all the keys that each of the individual select builders do (like <tt>:use_month_numbers</tt> for select_month) as well as a range of
<ide> # discard options. The discard options are <tt>:discard_year</tt>, <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll
<ide> # drop the respective select. Discarding the month select will also automatically discard the day select. It's also possible to explicitly
<ide> # set the order of the tags using the <tt>:order</tt> option with an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in
<ide> # the desired order. Symbols may be omitted and the respective select is not included.
<ide> #
<del> # Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of :year, :month, :day, :hour, :minute, and :second.
<add> # Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt>, and <tt>:second</tt>.
<ide> #
<del> # Passing :disabled => true as part of the +options+ will make elements inaccessible for change.
<add> # Passing <tt>:disabled => true</tt> as part of the +options+ will make elements inaccessible for change.
<ide> #
<del> # If anything is passed in the html_options hash it will be applied to every select tag in the set.
<add> # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
<ide> #
<ide> # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
<ide> #
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> module FormHelper
<ide> # Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base,
<ide> # like FormOptionHelper#collection_select and DateHelper#datetime_select.
<ide> #
<del> # HTML attributes for the form tag can be given as :html => {...}. For example:
<add> # HTML attributes for the form tag can be given as <tt>:html => {...}</tt>. For example:
<ide> #
<ide> # <% form_for :person, @person, :html => {:id => 'person_form'} do |f| %>
<ide> # ...
<ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb
<ide> module FormOptionsHelper
<ide> # This allows the user to submit a form page more than once with the expected results of creating multiple records.
<ide> # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
<ide> #
<del> # By default, post.person_id is the selected option. Specify :selected => value to use a different selection
<del> # or :selected => nil to leave all options unselected.
<add> # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection
<add> # or <tt>:selected => nil</tt> to leave all options unselected.
<ide> def select(object, method, choices, options = {}, html_options = {})
<ide> InstanceTag.new(object, method, self, nil, options.delete(:object)).to_select_tag(choices, options, html_options)
<ide> end
<ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb
<ide> def radio_button_tag(name, value, checked = false, options = {})
<ide> # submit_tag nil, :class => "form_submit"
<ide> # # => <input class="form_submit" name="commit" type="submit" />
<ide> #
<del> # submit_tag "Edit", :disable_with => "Editing...", :class => 'edit-button'
<del> # # => <input class="edit-button" disable_with="Editing..." name="commit" type="submit" value="Edit" />
<add> # submit_tag "Edit", :disable_with => "Editing...", :class => "edit-button"
<add> # # => <input class="edit-button" onclick="this.disabled=true;this.value='Editing...';this.form.submit();"
<add> # # name="commit" type="submit" value="Edit" />
<ide> def submit_tag(value = "Save changes", options = {})
<ide> options.stringify_keys!
<ide>
<ide><path>actionpack/lib/action_view/helpers/prototype_helper.rb
<ide> def link_to_remote(name, options = {}, html_options = nil)
<ide> link_to_function(name, remote_function(options), html_options || options.delete(:html))
<ide> end
<ide>
<del> # Periodically calls the specified url (<tt>options[:url]</tt>) every
<add> # Periodically calls the specified url (<tt>options[:url]</tt>) every
<ide> # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to
<del> # update a specified div (<tt>options[:update]</tt>) with the results
<del> # of the remote call. The options for specifying the target with :url
<add> # update a specified div (<tt>options[:update]</tt>) with the results
<add> # of the remote call. The options for specifying the target with <tt>:url</tt>
<ide> # and defining callbacks is the same as link_to_remote.
<ide> # Examples:
<ide> # # Call get_averages and put its results in 'avg' every 10 seconds
<ide> def periodically_call_remote(options = {})
<ide> # though it's using JavaScript to serialize the form elements, the form
<ide> # submission will work just like a regular submission as viewed by the
<ide> # receiving side (all elements available in <tt>params</tt>). The options for
<del> # specifying the target with :url and defining callbacks is the same as
<del> # link_to_remote.
<add> # specifying the target with <tt>:url</tt> and defining callbacks is the same as
<add> # +link_to_remote+.
<ide> #
<ide> # A "fall-through" target for browsers that doesn't do JavaScript can be
<del> # specified with the :action/:method options on :html.
<add> # specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>.
<ide> #
<ide> # Example:
<ide> # # Generates:
<ide> def periodically_call_remote(options = {})
<ide> # form_remote_tag :html => { :action =>
<ide> # url_for(:controller => "some", :action => "place") }
<ide> #
<del> # The Hash passed to the :html key is equivalent to the options (2nd)
<add> # The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd)
<ide> # argument in the FormTagHelper.form_tag method.
<ide> #
<ide> # By default the fall-through action is the same as the one specified in
<del> # the :url (and the default method is :post).
<add> # the <tt>:url</tt> (and the default method is <tt>:post</tt>).
<ide> #
<ide> # form_remote_tag also takes a block, like form_tag:
<ide> # # Generates:
<ide> def submit_to_remote(name, value, options = {})
<ide> end
<ide>
<ide> # Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function
<del> # that form_remote_tag can call in :complete to evaluate a multiple
<del> # update return document using update_element_function calls.
<add> # that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple
<add> # update return document using +update_element_function+ calls.
<ide> def evaluate_remote_response
<ide> "eval(request.responseText)"
<ide> end
<ide><path>actionpack/lib/action_view/helpers/sanitize_helper.rb
<ide> def self.included(base)
<ide> base.extend(ClassMethods)
<ide> end
<ide>
<del> # This #sanitize helper will html encode all tags and strip all attributes that aren't specifically allowed.
<add> # This +sanitize+ helper will html encode all tags and strip all attributes that aren't specifically allowed.
<ide> # It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any
<ide> # tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out
<ide> # the extensive test suite.
<ide> #
<ide> # <%= sanitize @article.body %>
<ide> #
<ide> # You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the
<del> # available options. You can add tags/attributes for single uses of #sanitize by passing either the :attributes or :tags options:
<add> # available options. You can add tags/attributes for single uses of +sanitize+ by passing either the <tt>:attributes</tt> or <tt>:tags</tt> options:
<ide> #
<ide> # Normal Use
<ide> #
<ide><path>actionpack/lib/action_view/helpers/scriptaculous_helper.rb
<ide> module ScriptaculousHelper
<ide> # This would fade the element that was dropped on the drop receiving
<ide> # element.
<ide> #
<del> # For toggling visual effects, you can use :toggle_appear, :toggle_slide, and
<del> # :toggle_blind which will alternate between appear/fade, slidedown/slideup, and
<add> # For toggling visual effects, you can use <tt>:toggle_appear</tt>, <tt>:toggle_slide</tt>, and
<add> # <tt>:toggle_blind</tt> which will alternate between appear/fade, slidedown/slideup, and
<ide> # blinddown/blindup respectively.
<ide> #
<ide> # You can change the behaviour with various options, see
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb
<ide> module UrlHelper
<ide> # instead of the fully qualified URL like http://example.com/controller/action.
<ide> #
<ide> # When called from a view, url_for returns an HTML escaped url. If you
<del> # need an unescaped url, pass :escape => false in the +options+.
<add> # need an unescaped url, pass <tt>:escape => false</tt> in the +options+.
<ide> #
<ide> # ==== Options
<ide> # * <tt>:anchor</tt> -- specifies the anchor name to be appended to the path.
<ide> module UrlHelper
<ide> # is currently not recommended since it breaks caching.
<ide> # * <tt>:host</tt> -- overrides the default (current) host if provided
<ide> # * <tt>:protocol</tt> -- overrides the default (current) protocol if provided
<del> # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if :password is also present)
<del> # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if :user is also present)
<add> # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present)
<add> # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present)
<ide> # * <tt>:escape</tt> -- Determines whether the returned URL will be HTML escaped or not (<tt>true</tt> by default)
<ide> #
<ide> # ==== Relying on named routes
<ide> def url_for(options = {})
<ide> # create an HTML form and immediately submit the form for processing using
<ide> # the HTTP verb specified. Useful for having links perform a POST operation
<ide> # in dangerous actions like deleting a record (which search bots can follow
<del> # while spidering your site). Supported verbs are :post, :delete and :put.
<add> # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
<ide> # Note that if the user has JavaScript disabled, the request will fall back
<ide> # to using GET. If you are relying on the POST behavior, you should check
<ide> # for it in your controller's action by using the request object's methods
<del> # for post?, delete? or put?.
<add> # for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
<ide> # * The +html_options+ will accept a hash of html attributes for the link tag.
<ide> #
<ide> # Note that if the user has JavaScript disabled, the request will fall back
<del> # to using GET. If :href=>'#' is used and the user has JavaScript disabled
<add> # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript disabled
<ide> # clicking the link will have no effect. If you are relying on the POST
<ide> # behavior, your should check for it in your controller's action by using the
<del> # request object's methods for post?, delete? or put?.
<add> # request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
<ide> #
<ide> # You can mix and match the +html_options+ with the exception of
<del> # :popup and :method which will raise an ActionView::ActionViewError
<add> # <tt>:popup</tt> and <tt>:method</tt> which will raise an ActionView::ActionViewError
<ide> # exception.
<ide> #
<ide> # ==== Examples
<ide><path>actionpack/lib/action_view/partials.rb
<ide> module ActionView
<ide> # Title: <%= chief.name %>
<ide> # </div>
<ide> #
<del> # As you can see, the :locals hash is shared between both the partial and its layout.
<add> # As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
<ide> module Partials
<ide> private
<ide> def render_partial(partial_path, object_assigns = nil, local_assigns = {}) #:nodoc:
<ide><path>activemodel/lib/active_model/validations.rb
<ide> module ClassMethods
<ide> DEFAULT_VALIDATION_OPTIONS = { :on => :save, :allow_nil => false, :allow_blank => false, :message => nil }.freeze
<ide>
<ide> # Adds a validation method or block to the class. This is useful when
<del> # overriding the #validate instance method becomes too unwieldly and
<add> # overriding the +validate+ instance method becomes too unwieldly and
<ide> # you're looking for more descriptive declaration of your validations.
<ide> #
<ide> # This can be done with a symbol pointing to a method:
<ide> module ClassMethods
<ide> # end
<ide> # end
<ide> #
<del> # This usage applies to #validate_on_create and #validate_on_update as well.
<del>
<add> # This usage applies to +validate_on_create+ and +validate_on_update as well+.
<add> #
<ide> # Validates each attribute against a block.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> module ClassMethods
<ide> # end
<ide> #
<ide> # Options:
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>allow_nil</tt> - Skip validation if attribute is nil.
<del> # * <tt>allow_blank</tt> - Skip validation if attribute is blank.
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
<add> # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_each(*attrs)
<ide> options = attrs.extract_options!.symbolize_keys
<ide><path>activemodel/lib/active_model/validations/acceptance.rb
<ide> module ClassMethods
<ide> # validates_acceptance_of :eula, :message => "must be abided"
<ide> # end
<ide> #
<del> # If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
<del> # performed only if terms_of_service is not nil and by default on save.
<add> # If the database column does not exist, the <tt>:terms_of_service</tt> attribute is entirely virtual. This check is
<add> # performed only if <tt>:terms_of_service</tt> is not +nil+ and by default on save.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "must be accepted")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
<del> # * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
<del> # makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database
<del> # column, since the attribute is typecast from "1" to <tt>true</tt> before validation.
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "must be accepted")
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+. (default is +true+)
<add> # * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
<add> # makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
<add> # column, since the attribute is typecasted from "1" to +true+ before validation.
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # method, proc or string should return or evaluate to a true or false value.
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<del> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_acceptance_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
<ide> configuration.update(attr_names.extract_options!)
<ide><path>activemodel/lib/active_model/validations/associated.rb
<ide> module ClassMethods
<ide> # ...this would specify a circular dependency and cause infinite recursion.
<ide> #
<ide> # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
<del> # is both present and guaranteed to be valid, you also need to use validates_presence_of.
<add> # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is invalid")
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is invalid")
<add> # * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_associated(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
<ide><path>activemodel/lib/active_model/validations/confirmation.rb
<ide> module ClassMethods
<ide> #
<ide> # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
<ide> # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
<del> # only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
<add> # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
<ide> # check for the confirmation attribute:
<ide> #
<ide> # validates_presence_of :password_confirmation, :if => :password_changed?
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation")
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # method, proc or string should return or evaluate to a true or false value.
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<del> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_confirmation_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
<ide> configuration.update(attr_names.extract_options!)
<ide><path>activemodel/lib/active_model/validations/exclusion.rb
<ide> module ClassMethods
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "is reserved")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved")
<add> # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
<add> # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_exclusion_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
<ide><path>activemodel/lib/active_model/validations/format.rb
<ide> module ClassMethods
<ide> # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
<ide> # end
<ide> #
<del> # Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
<add> # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
<ide> #
<ide> # A regular expression must be provided or else an exception will be raised.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is invalid")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is invalid")
<add> # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
<add> # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
<add> # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!)
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_format_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
<ide><path>activemodel/lib/active_model/validations/inclusion.rb
<ide> module ClassMethods
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>in</tt> - An enumerable object of available items
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "is not included in the list")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:in</tt> - An enumerable object of available items
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list")
<add> # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is null (default is: +false+)
<add> # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_inclusion_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
<ide><path>activemodel/lib/active_model/validations/length.rb
<ide> module ClassMethods
<ide> # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
<ide> #
<ide> # class Person < ActiveRecord::Base
<del> # validates_length_of :first_name, :maximum=>30
<del> # validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
<add> # validates_length_of :first_name, :maximum => 30
<add> # validates_length_of :last_name, :maximum => 30, :message => "less than %d if you don't mind"
<ide> # validates_length_of :fax, :in => 7..32, :allow_nil => true
<ide> # validates_length_of :phone, :in => 7..32, :allow_blank => true
<ide> # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
<del> # validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
<del> # validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
<add> # validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least %d character"
<add> # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %d characters... don't play me."
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>minimum</tt> - The minimum size of the attribute
<del> # * <tt>maximum</tt> - The maximum size of the attribute
<del> # * <tt>is</tt> - The exact size of the attribute
<del> # * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
<del> # * <tt>in</tt> - A synonym(or alias) for :within
<del> # * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
<del> # * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
<del> #
<del> # * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
<del> # * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
<del> # * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
<del> # * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:minimum</tt> - The minimum size of the attribute
<add> # * <tt>:maximum</tt> - The maximum size of the attribute
<add> # * <tt>:is</tt> - The exact size of the attribute
<add> # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute
<add> # * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>
<add> # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
<add> # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
<add> # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
<add> # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
<add> # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
<add> # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>:too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # method, proc or string should return or evaluate to a true or false value.
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<del> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_length_of(*attrs)
<ide> # Merge given options with defaults.
<ide> options = {
<ide><path>activemodel/lib/active_model/validations/numericality.rb
<ide> module ClassMethods
<ide>
<ide> # Validates whether the value of the specified attribute is numeric by trying to convert it to
<ide> # a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
<del> # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is set to true).
<add> # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is true).
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # validates_numericality_of :value, :on => :create
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is not a number")
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
<del> # * <tt>allow_nil</tt> Skip validation if attribute is nil (default is false). Notice that for fixnum and float columns empty strings are converted to nil
<del> # * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
<del> # * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
<del> # * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
<del> # * <tt>less_than</tt> Specifies the value must be less than the supplied value
<del> # * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
<del> # * <tt>odd</tt> Specifies the value must be an odd number
<del> # * <tt>even</tt> Specifies the value must be an even number
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is not a number")
<add> # * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is +false+)
<add> # * <tt>:allow_nil</tt> Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+
<add> # * <tt>:greater_than</tt> Specifies the value must be greater than the supplied value
<add> # * <tt>:greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
<add> # * <tt>:equal_to</tt> Specifies the value must be equal to the supplied value
<add> # * <tt>:less_than</tt> Specifies the value must be less than the supplied value
<add> # * <tt>:less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
<add> # * <tt>:odd</tt> Specifies the value must be an odd number
<add> # * <tt>:even</tt> Specifies the value must be an even number
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_numericality_of(*attr_names)
<ide> configuration = { :on => :save, :only_integer => false, :allow_nil => false }
<ide><path>activemodel/lib/active_model/validations/presence.rb
<ide> module ClassMethods
<ide> # validates_presence_of :first_name
<ide> # end
<ide> #
<del> # The first_name attribute must be in the object and it cannot be blank.
<add> # The +first_name+ attribute must be in the object and it cannot be blank.
<ide> #
<del> # If you want to validate the presence of a boolean field (where the real values are true and false),
<del> # you will want to use validates_inclusion_of :field_name, :in => [true, false]
<del> # This is due to the way Object#blank? handles boolean values. false.blank? # => true
<add> # If you want to validate the presence of a boolean field (where the real values are +true+ and +false+),
<add> # you will want to use
<add> #
<add> # validates_inclusion_of :field_name, :in => [true, false]
<add> #
<add> # This is due to the way Object#blank? handles boolean values:
<add> #
<add> # false.blank? # => true
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "can't be blank")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "can't be blank")
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> #
<ide> def validates_presence_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save }
<ide> configuration.update(attr_names.extract_options!)
<ide><path>activemodel/lib/active_model/validations/uniqueness.rb
<ide> module ClassMethods
<ide> # unique index on the field. See +add_index+ for more information.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
<del> # * <tt>scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
<del> # * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (false by default).
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken")
<add> # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
<add> # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+false+ by default).
<add> # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
<add> # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_uniqueness_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken] }
<ide><path>activerecord/lib/active_record/associations/association_proxy.rb
<ide> def method_missing(method, *args)
<ide> end
<ide> end
<ide>
<add> # Loads the target if needed and returns it.
<add> #
<add> # This method is abstract in the sense that it relies on +find_target+,
<add> # which is expected to be provided by descendants.
<add> #
<add> # If the target is already loaded it is just returned. Thus, you can call
<add> # +load_target+ unconditionally to get the target.
<add> #
<add> # ActiveRecord::RecordNotFound is rescued within the method, and it is
<add> # not reraised. The proxy is reset and +nil+ is the return value.
<ide> def load_target
<ide> return nil unless defined?(@loaded)
<ide>
<ide><path>activerecord/lib/active_record/base.rb
<ide> class ActiveRecordError < StandardError
<ide> class SubclassNotFound < ActiveRecordError #:nodoc:
<ide> end
<ide>
<del> # Raised when object assigned to association is of incorrect type.
<add> # Raised when an object assigned to an association has an incorrect type.
<ide> #
<del> # Example:
<del> #
<del> # class Ticket < ActiveRecord::Base
<del> # has_many :patches
<del> # end
<del> #
<del> # class Patch < ActiveRecord::Base
<del> # belongs_to :ticket
<del> # end
<add> # class Ticket < ActiveRecord::Base
<add> # has_many :patches
<add> # end
<ide> #
<del> # and somewhere in the code:
<add> # class Patch < ActiveRecord::Base
<add> # belongs_to :ticket
<add> # end
<ide> #
<del> # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
<del> # @ticket.save
<add> # # Comments are not patches, this assignment raises AssociationTypeMismatch.
<add> # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
<ide> class AssociationTypeMismatch < ActiveRecordError
<ide> end
<ide>
<ide> class RecordNotSaved < ActiveRecordError
<ide> class StatementInvalid < ActiveRecordError
<ide> end
<ide>
<del> # Raised when number of bind variables in statement given to :condition key (for example, when using +find+ method)
<add> # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
<ide> # does not match number of expected variables.
<ide> #
<del> # Example:
<add> # For example, in
<ide> #
<del> # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
<add> # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
<ide> #
<del> # in example above two placeholders are given but only one variable to fill them.
<add> # two placeholders are given but only one variable to fill them.
<ide> class PreparedStatementInvalid < ActiveRecordError
<ide> end
<ide>
<ide> class DangerousAttributeError < ActiveRecordError
<ide> end
<ide>
<ide> # Raised when you've tried to access a column which wasn't
<del> # loaded by your finder. Typically this is because :select
<del> # has been specified
<add> # loaded by your finder. Typically this is because <tt>:select</tt>
<add> # has been specified.
<ide> class MissingAttributeError < NoMethodError
<ide> end
<ide>
<ide> def initialize(errors)
<ide> # # Uses an integer of seconds to hold the length of the song
<ide> #
<ide> # def length=(minutes)
<del> # write_attribute(:length, minutes * 60)
<add> # write_attribute(:length, minutes.to_i * 60)
<ide> # end
<ide> #
<ide> # def length
<ide> def initialize(errors)
<ide> #
<ide> # It's even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount
<ide> # is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is
<del> # actually Person.find_by_user_name(user_name, options). So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
<add> # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
<ide> #
<ide> # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
<ide> # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
<ide> class << self # Class methods
<ide> # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned.
<ide> # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
<ide> # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
<del> # or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s).
<add> # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
<ide> # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
<del> # Pass :readonly => false to override.
<add> # Pass <tt>:readonly => false</tt> to override.
<ide> # * <tt>:include</tt>: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
<ide> # to already defined associations. See eager loading under Associations.
<ide> # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
<ide> class << self # Class methods
<ide> # of a database view).
<ide> # * <tt>:readonly</tt>: Mark the returned records read-only so they cannot be saved or updated.
<ide> # * <tt>:lock</tt>: An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
<del> # :lock => true gives connection's default exclusive lock, usually "FOR UPDATE".
<add> # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
<ide> #
<ide> # Examples for find by id:
<ide> # Person.find(1) # returns the object for ID = 1
<ide> class << self # Class methods
<ide> # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
<ide> #
<ide> # Note that returned records may not be in the same order as the ids you
<del> # provide since database rows are unordered. Give an explicit :order
<add> # provide since database rows are unordered. Give an explicit <tt>:order</tt>
<ide> # to ensure the results are sorted.
<ide> #
<ide> # Examples for find first:
<ide> def destroy(id)
<ide> # +updates+ A String of column and value pairs that will be set on any records that match conditions
<ide> # +conditions+ An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
<ide> # See conditions in the intro for more info.
<del> # +options+ Additional options are :limit and/or :order, see the examples for usage.
<add> # +options+ Additional options are <tt>:limit</tt> and/or <tt>:order</tt>, see the examples for usage.
<ide> #
<ide> # ==== Examples
<ide> #
<ide> def add_group!(sql, group, scope = :auto)
<ide> end
<ide> end
<ide>
<del> # The optional scope argument is for the current :find scope.
<add> # The optional scope argument is for the current <tt>:find</tt> scope.
<ide> def add_limit!(sql, options, scope = :auto)
<ide> scope = scope(:find) if :auto == scope
<ide>
<ide> def add_limit!(sql, options, scope = :auto)
<ide> connection.add_limit_offset!(sql, options)
<ide> end
<ide>
<del> # The optional scope argument is for the current :find scope.
<del> # The :lock option has precedence over a scoped :lock.
<add> # The optional scope argument is for the current <tt>:find</tt> scope.
<add> # The <tt>:lock</tt> option has precedence over a scoped <tt>:lock</tt>.
<ide> def add_lock!(sql, options, scope = :auto)
<ide> scope = scope(:find) if :auto == scope
<ide> options = options.reverse_merge(:lock => scope[:lock]) if scope
<ide> connection.add_lock!(sql, options)
<ide> end
<ide>
<del> # The optional scope argument is for the current :find scope.
<add> # The optional scope argument is for the current <tt>:find</tt> scope.
<ide> def add_joins!(sql, options, scope = :auto)
<ide> scope = scope(:find) if :auto == scope
<ide> [(scope && scope[:joins]), options[:joins]].each do |join|
<ide> def add_joins!(sql, options, scope = :auto)
<ide> end
<ide>
<ide> # Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed.
<del> # The optional scope argument is for the current :find scope.
<add> # The optional scope argument is for the current <tt>:find</tt> scope.
<ide> def add_conditions!(sql, conditions, scope = :auto)
<ide> scope = scope(:find) if :auto == scope
<ide> conditions = [conditions]
<ide> def define_attr_method(name, value=nil, &block)
<ide>
<ide> protected
<ide> # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
<del> # method_name may be :find or :create. :find parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
<del> # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. :create parameters are an attributes hash.
<add> # method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
<add> # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. <tt>:create</tt> parameters are an attributes hash.
<ide> #
<ide> # class Article < ActiveRecord::Base
<ide> # def self.create_with_scope
<ide> def define_attr_method(name, value=nil, &block)
<ide> # end
<ide> #
<ide> # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
<del> # :conditions and :include options in :find, which are merged.
<add> # <tt>:conditions</tt> and <tt>:include</tt> options in <tt>:find</tt>, which are merged.
<ide> #
<ide> # class Article < ActiveRecord::Base
<ide> # def self.find_with_scope
<ide> def clone
<ide> record
<ide> end
<ide>
<del> # Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to
<add> # Returns an instance of the specified +klass+ with the attributes of the current record. This is mostly useful in relation to
<ide> # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record
<del> # identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company)
<add> # identification in Action Pack to allow, say, <tt>Client < Company</tt> to do something like render <tt>:partial => @client.becomes(Company)</tt>
<ide> # to render that instance using the companies/company partial instead of clients/client.
<ide> #
<ide> # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either
<ide><path>activerecord/lib/active_record/calculations.rb
<ide> module ClassMethods
<ide> # Count operates using three different approaches.
<ide> #
<ide> # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
<del> # * Count using column : By passing a column name to count, it will return a count of all the rows for the model with supplied column present
<add> # * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
<ide> # * Count using options will find the row count matched by the options used.
<ide> #
<ide> # The third approach, count using options, accepts an option hash as the only parameter. The options are:
<ide> #
<ide> # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
<ide> # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
<del> # or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s).
<add> # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
<ide> # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
<del> # Pass :readonly => false to override.
<add> # Pass <tt>:readonly => false</tt> to override.
<ide> # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
<ide> # to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
<ide> # See eager loading under Associations.
<ide> module ClassMethods
<ide> # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
<ide> # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
<ide> #
<del> # Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.
<add> # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
<ide> def count(*args)
<ide> calculate(:count, *construct_count_options_from_args(*args))
<ide> end
<ide> def sum(column_name, options = {})
<ide> end
<ide>
<ide> # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
<del> # Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.
<add> # Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
<ide> #
<ide> # There are two basic forms of output:
<ide> # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
<del> # * Grouped values: This returns an ordered hash of the values and groups them by the :group option. It takes either a column name, or the name
<add> # * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name
<ide> # of a belongs_to association.
<ide> #
<ide> # values = Person.maximum(:age, :group => 'last_name')
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
<ide> def connection
<ide> end
<ide>
<ide> # Establishes the connection to the database. Accepts a hash as input where
<del> # the :adapter key must be specified with the name of a database adapter (in lower-case)
<add> # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
<ide> # example for regular databases (MySQL, Postgresql, etc):
<ide> #
<ide> # ActiveRecord::Base.establish_connection(
<ide> def connection
<ide> # )
<ide> #
<ide> # Also accepts keys as strings (for parsing from yaml for example):
<add> #
<ide> # ActiveRecord::Base.establish_connection(
<ide> # "adapter" => "sqlite",
<ide> # "database" => "path/to/dbfile"
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def [](name)
<ide> # TableDefinition#timestamps that'll add created_at and updated_at as datetimes.
<ide> #
<ide> # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
<del> # column if the :polymorphic option is supplied. If :polymorphic is a hash of options, these will be
<del> # used when creating the _type column. So what can be written like this:
<add> # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be
<add> # used when creating the <tt>_type</tt> column. So what can be written like this:
<ide> #
<ide> # create_table :taggings do |t|
<ide> # t.integer :tag_id, :tagger_id, :taggable_id
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def columns(table_name, name = nil) end
<ide> # The +options+ hash can include the following keys:
<ide> # [<tt>:id</tt>]
<ide> # Whether to automatically add a primary key column. Defaults to true.
<del> # Join tables for has_and_belongs_to_many should set :id => false.
<add> # Join tables for +has_and_belongs_to_many+ should set <tt>:id => false</tt>.
<ide> # [<tt>:primary_key</tt>]
<ide> # The name of the primary key, if one is to be added automatically.
<ide> # Defaults to +id+.
<ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def recreate_database(name) #:nodoc:
<ide> create_database(name)
<ide> end
<ide>
<del> # Create a new MySQL database with optional :charset and :collation.
<add> # Create a new MySQL database with optional <tt>:charset</tt> and <tt>:collation</tt>.
<ide> # Charset defaults to utf8.
<ide> #
<ide> # Example:
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> module ConnectionAdapters
<ide> # * <tt>:username</tt> -- Defaults to nothing
<ide> # * <tt>:password</tt> -- Defaults to nothing
<ide> # * <tt>:database</tt> -- The name of the database. No default, must be provided.
<del> # * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the :schema_order option.
<add> # * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
<ide> # * <tt>:encoding</tt> -- An optional client encoding that is used in a SET client_encoding TO <encoding> call on the connection.
<ide> # * <tt>:min_messages</tt> -- An optional client min messages that is used in a SET client_min_messages TO <min_messages> call on the connection.
<ide> # * <tt>:allow_concurrency</tt> -- If true, use async query methods so Ruby threads don't deadlock; otherwise, use blocking query methods.
<ide> def recreate_database(name) #:nodoc:
<ide> create_database(name)
<ide> end
<ide>
<del> # Create a new PostgreSQL database. Options include :owner, :template,
<del> # :encoding, :tablespace, and :connection_limit (note that MySQL uses
<del> # :charset while PostgreSQL uses :encoding).
<add> # Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
<add> # <tt>:encoding</tt>, <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
<add> # <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
<ide> #
<ide> # Example:
<ide> # create_database config[:database], config
<ide><path>activerecord/lib/active_record/locking/pessimistic.rb
<ide> module Locking
<ide> # Locking::Pessimistic provides support for row-level locking using
<ide> # SELECT ... FOR UPDATE and other lock types.
<ide> #
<del> # Pass :lock => true to ActiveRecord::Base.find to obtain an exclusive
<add> # Pass <tt>:lock => true</tt> to ActiveRecord::Base.find to obtain an exclusive
<ide> # lock on the selected rows:
<ide> # # select * from accounts where id=1 for update
<ide> # Account.find(1, :lock => true)
<ide> #
<del> # Pass :lock => 'some locking clause' to give a database-specific locking clause
<add> # Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
<ide> # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'.
<ide> #
<ide> # Example:
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def initialize(name)
<ide> # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ to +new_name+.
<ide> # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column to the table called +table_name+
<ide> # named +column_name+ specified to be one of the following types:
<del> # :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time,
<del> # :date, :binary, :boolean. A default value can be specified by passing an
<del> # +options+ hash like { :default => 11 }. Other options include :limit and :null (e.g. { :limit => 50, :null => false })
<add> # <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
<add> # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be specified by passing an
<add> # +options+ hash like <tt>{ :default => 11 }</tt>. Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g. <tt>{ :limit => 50, :null => false }</tt>)
<ide> # -- see ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
<ide> # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames a column but keeps the type and content.
<ide> # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes the column to a different type using the same
<ide> # parameters as add_column.
<ide> # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named +column_name+ from the table called +table_name+.
<ide> # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index with the name of the column. Other options include
<del> # :name and :unique (e.g. { :name => "users_name_index", :unique => true }).
<add> # <tt>:name</tt> and <tt>:unique</tt> (e.g. <tt>{ :name => "users_name_index", :unique => true }</tt>).
<ide> # * <tt>remove_index(table_name, index_name)</tt>: Removes the index specified by +index_name+.
<ide> #
<ide> # == Irreversible transformations
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def reflect_on_aggregation(aggregation)
<ide> end
<ide>
<ide> # Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a
<del> # certain association type, pass in the symbol (:has_many, :has_one, :belongs_to) for that as the first parameter.
<add> # certain association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>, <tt>:belongs_to</tt>) for that as the first parameter.
<ide> # Example:
<ide> #
<ide> # Account.reflect_on_all_associations # returns an array of all associations
<ide> def macro
<ide>
<ide> # Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
<ide> # <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
<del>
<ide> def options
<ide> @options
<ide> end
<ide>
<del> # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the +Money+
<del> # class and <tt>has_many :clients</tt> returns the +Client+ class.
<add> # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
<add> # class and <tt>has_many :clients</tt> returns the Client class.
<ide> def klass
<ide> @klass ||= class_name.constantize
<ide> end
<ide> def through_reflection
<ide> @through_reflection ||= options[:through] ? active_record.reflect_on_association(options[:through]) : false
<ide> end
<ide>
<del> # Gets an array of possible :through source reflection names
<add> # Gets an array of possible <tt>:through</tt> source reflection names:
<ide> #
<del> # [singularized, pluralized]
<add> # [:singularized, :pluralized]
<ide> #
<ide> def source_reflection_names
<ide> @source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
<ide> end
<ide>
<del> # Gets the source of the through reflection. It checks both a singularized and pluralized form for :belongs_to or :has_many.
<del> # (The :tags association on Tagging below)
<add> # Gets the source of the through reflection. It checks both a singularized and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
<add> # (The <tt>:tags</tt> association on Tagging below.)
<ide> #
<ide> # class Post
<ide> # has_many :tags, :through => :taggings
<ide><path>activerecord/lib/active_record/serialization.rb
<ide> def initialize(record, options = {})
<ide> end
<ide>
<ide> # To replicate the behavior in ActiveRecord#attributes,
<del> # :except takes precedence over :only. If :only is not set
<add> # <tt>:except</tt> takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
<ide> # for a N level model but is set for the N+1 level models,
<del> # then because :except is set to a default value, the second
<del> # level model can have both :except and :only set. So if
<del> # :only is set, always delete :except.
<add> # then because <tt>:except</tt> is set to a default value, the second
<add> # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
<add> # <tt>:only</tt> is set, always delete <tt>:except</tt>.
<ide> def serializable_attribute_names
<ide> attribute_names = @record.attribute_names
<ide>
<ide> def serializable_names
<ide> serializable_attribute_names + serializable_method_names
<ide> end
<ide>
<del> # Add associations specified via the :includes option.
<add> # Add associations specified via the <tt>:includes</tt> option.
<ide> # Expects a block that takes as arguments:
<ide> # +association+ - name of the association
<ide> # +records+ - the association record(s) to be serialized
<ide><path>activerecord/lib/active_record/serializers/json_serializer.rb
<ide> def self.included(base)
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true}
<ide> #
<del> # The :only and :except options can be used to limit the attributes
<del> # included, and work similar to the #attributes method. For example:
<add> # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
<add> # included, and work similar to the +attributes+ method. For example:
<ide> #
<ide> # konata.to_json(:only => [ :id, :name ])
<ide> # # => {"id": 1, "name": "Konata Izumi"}
<ide> #
<ide> # konata.to_json(:except => [ :id, :created_at, :age ])
<ide> # # => {"name": "Konata Izumi", "awesome": true}
<ide> #
<del> # To include any methods on the model, use :methods.
<add> # To include any methods on the model, use <tt>:methods</tt>.
<ide> #
<ide> # konata.to_json(:methods => :permalink)
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true,
<ide> # "permalink": "1-konata-izumi"}
<ide> #
<del> # To include associations, use :include.
<add> # To include associations, use <tt>:include</tt>.
<ide> #
<ide> # konata.to_json(:include => :posts)
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide><path>activerecord/lib/active_record/serializers/xml_serializer.rb
<ide> module ActiveRecord #:nodoc:
<ide> module Serialization
<ide> # Builds an XML document to represent the model. Some configuration is
<ide> # available through +options+. However more complicated cases should
<del> # override ActiveRecord's to_xml method.
<add> # override ActiveRecord::Base#to_xml.
<ide> #
<ide> # By default the generated XML document will include the processing
<ide> # instruction and all the object's attributes. For example:
<ide> module Serialization
<ide> # <last-read type="date">2004-04-15</last-read>
<ide> # </topic>
<ide> #
<del> # This behavior can be controlled with :only, :except,
<del> # :skip_instruct, :skip_types and :dasherize. The :only and
<del> # :except options are the same as for the #attributes method.
<del> # The default is to dasherize all column names, to disable this,
<del> # set :dasherize to false. To not have the column type included
<del> # in the XML output, set :skip_types to true.
<add> # This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
<add> # <tt>:skip_instruct</tt>, <tt>:skip_types</tt> and <tt>:dasherize</tt>.
<add> # The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
<add> # +attributes+ method. The default is to dasherize all column names, but you
<add> # can disable this setting <tt>:dasherize</tt> to +false+. To not have the
<add> # column type included in the XML output set <tt>:skip_types</tt> to +true+.
<ide> #
<ide> # For instance:
<ide> #
<ide> module Serialization
<ide> # <last-read type="date">2004-04-15</last-read>
<ide> # </topic>
<ide> #
<del> # To include first level associations use :include
<add> # To include first level associations use <tt>:include</tt>:
<ide> #
<ide> # firm.to_xml :include => [ :account, :clients ]
<ide> #
<ide> module Serialization
<ide> # </account>
<ide> # </firm>
<ide> #
<del> # To include any methods on the object(s) being called use :methods
<add> # To include any methods on the model being called use <tt>:methods</tt>:
<ide> #
<ide> # firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
<ide> #
<ide> module Serialization
<ide> # <real-earnings>5</real-earnings>
<ide> # </firm>
<ide> #
<del> # To call any Procs on the object(s) use :procs. The Procs
<del> # are passed a modified version of the options hash that was
<del> # given to #to_xml.
<add> # To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
<add> # modified version of the options hash that was given to +to_xml+:
<ide> #
<ide> # proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
<ide> # firm.to_xml :procs => [ proc ]
<ide> module Serialization
<ide> # <abc>def</abc>
<ide> # </firm>
<ide> #
<del> # Alternatively, you can yield the builder object as part of the to_xml call:
<add> # Alternatively, you can yield the builder object as part of the +to_xml+ call:
<ide> #
<ide> # firm.to_xml do |xml|
<ide> # xml.creator do
<ide> module Serialization
<ide> # </creator>
<ide> # </firm>
<ide> #
<del> # You can override the to_xml method in your ActiveRecord::Base
<del> # subclasses if you need to. The general form of doing this is:
<add> # As noted above, you may override +to_xml+ in your ActiveRecord::Base
<add> # subclasses to have complete control about what's generated. The general
<add> # form of doing this is:
<ide> #
<ide> # class IHaveMyOwnXML < ActiveRecord::Base
<ide> # def to_xml(options = {})
<ide><path>activerecord/lib/active_record/validations.rb
<ide> def size
<ide> alias_method :count, :size
<ide> alias_method :length, :size
<ide>
<del> # Return an XML representation of this error object.
<add> # Returns an XML representation of this error object.
<ide> #
<ide> # class Company < ActiveRecord::Base
<ide> # validates_presence_of :name, :address, :email
<ide> def to_xml(options={})
<ide> # person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
<ide> # person.save # => true (and person is now saved in the database)
<ide> #
<del> # An +Errors+ object is automatically created for every Active Record.
<add> # An Errors object is automatically created for every Active Record.
<ide> #
<ide> # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
<ide> module Validations
<ide> def self.included(base) # :nodoc:
<ide>
<ide> # All of the following validations are defined in the class scope of the model that you're interested in validating.
<ide> # They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use
<del> # these over the low-level calls to validate and validate_on_create when possible.
<add> # these over the low-level calls to +validate+ and +validate_on_create+ when possible.
<ide> module ClassMethods
<ide> DEFAULT_VALIDATION_OPTIONS = {
<ide> :on => :save,
<ide> module ClassMethods
<ide> # end
<ide> #
<ide> # Options:
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>allow_nil</tt> - Skip validation if attribute is nil.
<del> # * <tt>allow_blank</tt> - Skip validation if attribute is blank.
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
<add> # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_each(*attrs)
<ide> options = attrs.extract_options!.symbolize_keys
<ide> def validates_each(*attrs)
<ide> #
<ide> # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
<ide> # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
<del> # only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
<add> # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
<ide> # check for the confirmation attribute:
<ide> #
<ide> # validates_presence_of :password_confirmation, :if => :password_changed?
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_confirmation_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
<ide> def validates_confirmation_of(*attr_names)
<ide> # validates_acceptance_of :eula, :message => "must be abided"
<ide> # end
<ide> #
<del> # If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
<del> # performed only if terms_of_service is not nil and by default on save.
<add> # If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
<add> # performed only if +terms_of_service+ is not +nil+ and by default on save.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "must be accepted")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
<del> # * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
<del> # makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database
<del> # column, since the attribute is typecast from "1" to <tt>true</tt> before validation.
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "must be accepted").
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
<add> # * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
<add> # makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
<add> # column, since the attribute is typecast from "1" to +true+ before validation.
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_acceptance_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
<ide> def validates_acceptance_of(*attr_names)
<ide> # This is due to the way Object#blank? handles boolean values. false.blank? # => true
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "can't be blank")
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<add> # * <tt>message</tt> - A custom error message (default is: "can't be blank").
<add> # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<ide> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<ide> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_presence_of(*attr_names)
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>minimum</tt> - The minimum size of the attribute
<del> # * <tt>maximum</tt> - The maximum size of the attribute
<del> # * <tt>is</tt> - The exact size of the attribute
<del> # * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
<del> # * <tt>in</tt> - A synonym(or alias) for :within
<del> # * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
<del> # * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
<del> #
<del> # * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
<del> # * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
<del> # * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
<del> # * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message
<del> # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:minimum</tt> - The minimum size of the attribute.
<add> # * <tt>:maximum</tt> - The maximum size of the attribute.
<add> # * <tt>:is</tt> - The exact size of the attribute.
<add> # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
<add> # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
<add> # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
<add> # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
<add> #
<add> # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)").
<add> # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)").
<add> # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)").
<add> # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_length_of(*attrs)
<ide> # Merge given options with defaults.
<ide> def validates_length_of(*attrs)
<ide> # unique index on the field. See +add_index+ for more information.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
<del> # * <tt>scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
<del> # * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default).
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
<add> # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
<add> # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+false+ by default).
<add> # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
<add> # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_uniqueness_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken], :case_sensitive => true }
<ide> def validates_uniqueness_of(*attr_names)
<ide> # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
<ide> # end
<ide> #
<del> # Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
<add> # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
<ide> #
<ide> # A regular expression must be provided or else an exception will be raised.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is invalid")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is invalid").
<add> # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
<add> # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
<add> # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
<add> # * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_format_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
<ide> def validates_format_of(*attr_names)
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>in</tt> - An enumerable object of available items
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "is not included in the list")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:in</tt> - An enumerable object of available items.
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
<add> # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
<add> # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_inclusion_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
<ide> def validates_inclusion_of(*attr_names)
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
<del> # * <tt>message</tt> - Specifies a custom error message (default is: "is reserved")
<del> # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
<del> # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
<add> # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
<add> # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
<add> # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_exclusion_of(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
<ide> def validates_exclusion_of(*attr_names)
<ide> # validates_associated :book
<ide> # end
<ide> #
<del> # ...this would specify a circular dependency and cause infinite recursion.
<add> # this would specify a circular dependency and cause infinite recursion.
<ide> #
<ide> # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
<del> # is both present and guaranteed to be valid, you also need to use validates_presence_of.
<add> # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is invalid")
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is invalid")
<add> # * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_associated(*attr_names)
<ide> configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
<ide> def validates_associated(*attr_names)
<ide> # end
<ide> #
<ide> # Configuration options:
<del> # * <tt>message</tt> - A custom error message (default is: "is not a number")
<del> # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
<del> # * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
<del> # * <tt>allow_nil</tt> Skip validation if attribute is nil (default is false). Notice that for fixnum and float columns empty strings are converted to nil
<del> # * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
<del> # * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
<del> # * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
<del> # * <tt>less_than</tt> Specifies the value must be less than the supplied value
<del> # * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
<del> # * <tt>odd</tt> Specifies the value must be an odd number
<del> # * <tt>even</tt> Specifies the value must be an even number
<del> # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
<add> # * <tt>:message</tt> - A custom error message (default is: "is not a number").
<add> # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
<add> # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
<add> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
<add> # * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
<add> # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
<add> # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
<add> # * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
<add> # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
<add> # * <tt>:odd</tt> - Specifies the value must be an odd number.
<add> # * <tt>:even</tt> - Specifies the value must be an even number.
<add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<del> # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
<add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_numericality_of(*attr_names)
<ide> configuration = { :on => :save, :only_integer => false, :allow_nil => false }
<ide> def update_attribute_with_validation_skipping(name, value)
<ide> save(false)
<ide> end
<ide>
<del> # Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.
<add> # Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
<ide> def valid?
<ide> errors.clear
<ide>
<ide> def errors
<ide> end
<ide>
<ide> protected
<del> # Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes.
<add> # Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
<ide> def validate #:doc:
<ide> end
<ide>
<ide><path>activeresource/lib/active_resource/base.rb
<ide> def create(attributes = {})
<ide> # The first argument is considered to be the scope of the query. That is, how many
<ide> # resources are returned from the request. It can be one of the following.
<ide> #
<del> # +:one+:: Returns a single resource.
<del> # +:first+:: Returns the first resource found.
<del> # +:all+:: Returns every resource that matches the request.
<add> # * <tt>:one</tt>: Returns a single resource.
<add> # * <tt>:first</tt>: Returns the first resource found.
<add> # * <tt>:all</tt>: Returns every resource that matches the request.
<ide> #
<ide> # ==== Options
<del> # +from+:: Sets the path or custom method that resources will be fetched from.
<del> # +params+:: Sets query and prefix (nested URL) parameters.
<add> #
<add> # * +from+: Sets the path or custom method that resources will be fetched from.
<add> # * +params+: Sets query and prefix (nested URL) parameters.
<ide> #
<ide> # ==== Examples
<ide> # Person.find(1)
<ide><path>activeresource/lib/active_resource/connection.rb
<ide> def post(path, body = '', headers = {})
<ide> end
<ide>
<ide> # Execute a HEAD request.
<del> # Used to ...
<del> def head(path, headers= {})
<add> # Used to obtain meta-information about resources, such as whether they exist and their size (via response headers).
<add> def head(path, headers = {})
<ide> request(:head, path, build_request_headers(headers))
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/cache.rb
<ide> def threadsafe!
<ide> self
<ide> end
<ide>
<del> # Pass :force => true to force a cache miss.
<add> # Pass <tt>:force => true</tt> to force a cache miss.
<ide> def fetch(key, options = {})
<ide> @logger_off = true
<ide> if !options[:force] && value = read(key, options)
<ide><path>activesupport/lib/active_support/core_ext/array/conversions.rb
<ide> def to_formatted_s(format = :default)
<ide> end
<ide> end
<ide>
<del> # Returns a string that represents this array in XML by sending
<del> # <tt>to_xml</tt> to each element.
<add> # Returns a string that represents this array in XML by sending +to_xml+
<add> # to each element. Active Record collections delegate their representation
<add> # in XML to this method.
<ide> #
<del> # All elements are expected to respond to <tt>to_xml</tt>, if any of
<del> # them does not an exception is raised.
<add> # All elements are expected to respond to +to_xml+, if any of them does
<add> # not an exception is raised.
<ide> #
<ide> # The root node reflects the class name of the first element in plural
<del> # if all elements belong to the same type and that's not <tt>Hash</tt>.
<del> # Otherwise the root element is "records".
<add> # if all elements belong to the same type and that's not Hash:
<ide> #
<del> # Root children have as node name the one of the root singularized.
<add> # customer.projects.to_xml
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <projects type="array">
<add> # <project>
<add> # <amount type="decimal">20000.0</amount>
<add> # <customer-id type="integer">1567</customer-id>
<add> # <deal-date type="date">2008-04-09</deal-date>
<add> # ...
<add> # </project>
<add> # <project>
<add> # <amount type="decimal">57230.0</amount>
<add> # <customer-id type="integer">1567</customer-id>
<add> # <deal-date type="date">2008-04-15</deal-date>
<add> # ...
<add> # </project>
<add> # </projects>
<add> #
<add> # Otherwise the root element is "records":
<ide> #
<ide> # [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
<ide> #
<ide> def to_formatted_s(format = :default)
<ide> # </record>
<ide> # </records>
<ide> #
<add> # If the collection is empty the root element is "nil-classes" by default:
<add> #
<add> # [].to_xml
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <nil-classes type="array"/>
<add> #
<add> # To ensure a meaningful root element use the <tt>:root</tt> option:
<add> #
<add> # customer_with_no_projects.projects.to_xml(:root => "projects")
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <projects type="array"/>
<add> #
<add> # By default root children have as node name the one of the root
<add> # singularized. You can change it with the <tt>:children</tt> option.
<add> #
<ide> # The +options+ hash is passed downwards:
<ide> #
<del> # [Message.find(:first)].to_xml(:skip_types => true)
<add> # Message.all.to_xml(:skip_types => true)
<ide> #
<ide> # <?xml version="1.0" encoding="UTF-8"?>
<ide> # <messages>
<ide><path>activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
<ide> # Extends the class object with class and instance accessors for class attributes,
<ide> # just like the native attr* accessors for instance attributes.
<del>class Class # :nodoc:
<add>#
<add># class Person
<add># cattr_accessor :hair_colors
<add># end
<add>#
<add># Person.hair_colors = [:brown, :black, :blonde, :red]
<add>class Class
<ide> def cattr_reader(*syms)
<ide> syms.flatten.each do |sym|
<ide> next if sym.is_a?(Hash)
<ide><path>activesupport/lib/active_support/core_ext/date/calculations.rb
<ide> def minus_with_duration(other) #:nodoc:
<ide> end
<ide>
<ide> # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
<del> # any of these keys: :years, :months, :weeks, :days.
<add> # any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
<ide> def advance(options)
<ide> d = self
<ide> d = d >> options.delete(:years) * 12 if options[:years]
<ide><path>activesupport/lib/active_support/core_ext/date_time/calculations.rb
<ide> def change(options)
<ide> )
<ide> end
<ide>
<del> # Uses Date to provide precise Time calculations for years, months, and days. The +options+ parameter takes a hash with
<del> # any of these keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds.
<add> # Uses Date to provide precise Time calculations for years, months, and days.
<add> # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
<add> # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
<add> # <tt>:minutes</tt>, <tt>:seconds</tt>.
<ide> def advance(options)
<ide> d = to_date.advance(options)
<ide> datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
<ide><path>activesupport/lib/active_support/core_ext/enumerable.rb
<ide> module Enumerable
<ide> # Example:
<ide> #
<ide> # latest_transcripts.group_by(&:day).each do |day, transcripts|
<del> # p "#{day} -> #{transcripts.map(&:class) * ', '}"
<add> # p "#{day} -> #{transcripts.map(&:class).join(', ')}"
<ide> # end
<ide> # "2006-03-01 -> Transcript"
<ide> # "2006-02-28 -> Transcript"
<ide> def group_by
<ide>
<ide> # Calculates a sum from the elements. Examples:
<ide> #
<del> # payments.sum { |p| p.price * p.tax_rate }
<del> # payments.sum(&:price)
<add> # payments.sum { |p| p.price * p.tax_rate }
<add> # payments.sum(&:price)
<ide> #
<del> # This is instead of
<add> # The latter is a shortcut for:
<ide> #
<del> # payments.inject { |sum, p| sum + p.price }
<add> # payments.inject { |sum, p| sum + p.price }
<ide> #
<del> # Also calculates sums without the use of a block:
<add> # It can also calculate the sum without the use of a block.
<ide> #
<del> # [5, 15, 10].sum # => 30
<add> # [5, 15, 10].sum # => 30
<add> # ["foo", "bar"].sum # => "foobar"
<add> # [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
<ide> #
<del> # The default identity (sum of an empty list) is zero.
<del> # However, you can override this default:
<add> # The default sum of an empty list is zero. You can override this default:
<ide> #
<del> # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
<add> # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
<ide> #
<ide> def sum(identity = 0, &block)
<ide> return identity unless size > 0
<ide><path>activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
<ide> module Hash #:nodoc:
<ide> # options.reverse_merge! :size => 25, :velocity => 10
<ide> # end
<ide> #
<del> # The default :size and :velocity is only set if the +options+ passed in doesn't already have those keys set.
<add> # The default <tt>:size</tt> and <tt>:velocity</tt> is only set if the +options+ passed in doesn't already have those keys set.
<ide> module ReverseMerge
<ide> # Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
<ide> def reverse_merge(other_hash)
<ide><path>activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
<ide> # Extends the module object with module and instance accessors for class attributes,
<ide> # just like the native attr* accessors for instance attributes.
<del>class Module # :nodoc:
<add>#
<add># module AppConfiguration
<add># mattr_accessor :google_api_key
<add># self.google_api_key = "123456789"
<add>#
<add># mattr_accessor :paypal_url
<add># self.paypal_url = "www.sandbox.paypal.com"
<add># end
<add>#
<add># AppConfiguration.google_api_key = "overriding the api key!"
<add>class Module
<ide> def mattr_reader(*syms)
<ide> syms.each do |sym|
<ide> next if sym.is_a?(Hash)
<ide><path>activesupport/lib/active_support/core_ext/module/delegation.rb
<ide> class Module
<ide> # Provides a delegate class method to easily expose contained objects' methods
<ide> # as your own. Pass one or more methods (specified as symbols or strings)
<del> # and the name of the target object as the final :to option (also a symbol
<del> # or string). At least one method and the :to option are required.
<add> # and the name of the target object as the final <tt>:to</tt> option (also a symbol
<add> # or string). At least one method and the <tt>:to</tt> option are required.
<ide> #
<ide> # Delegation is particularly useful with Active Record associations:
<ide> #
<ide> class Module
<ide> # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
<ide> #
<ide> # Multiple delegates to the same target are allowed:
<add> #
<ide> # class Foo < ActiveRecord::Base
<ide> # belongs_to :greeter
<ide> # delegate :hello, :goodbye, :to => :greeter
<ide> class Module
<ide> # Foo.new.goodbye # => "goodbye"
<ide> #
<ide> # Methods can be delegated to instance variables, class variables, or constants
<del> # by providing the variable as a symbol:
<add> # by providing them as a symbols:
<add> #
<ide> # class Foo
<ide> # CONSTANT_ARRAY = [0,1,2,3]
<ide> # @@class_array = [4,5,6,7]
<ide><path>activesupport/lib/active_support/core_ext/range/include_range.rb
<ide> def self.included(base) #:nodoc:
<ide> base.alias_method_chain :include?, :range
<ide> end
<ide>
<add> # Extends the default Range#include? to support range comparisons.
<add> # (1..5).include?(1..5) # => true
<add> # (1..5).include?(2..3) # => true
<add> # (1..5).include?(2..6) # => false
<add> #
<add> # The native Range#include? behavior is untouched.
<add> # ("a".."f").include?("c") # => true
<add> # (5..9).include?(11) # => false
<ide> def include_with_range?(value)
<ide> if value.is_a?(::Range)
<ide> operator = exclude_end? ? :< : :<=
<ide><path>activesupport/lib/active_support/core_ext/range/overlaps.rb
<ide> module CoreExtensions #:nodoc:
<ide> module Range #:nodoc:
<ide> # Check if Ranges overlap.
<ide> module Overlaps
<add> # Compare two ranges and see if they overlap eachother
<add> # (1..5).overlaps?(4..6) # => true
<add> # (1..5).overlaps?(7..9) # => false
<ide> def overlaps?(other)
<ide> include?(other.first) || other.include?(first)
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=
<ide> ::DateTime.civil(year, month, day, hour, min, sec, offset)
<ide> end
<ide>
<del> # wraps class method time_with_datetime_fallback with utc_or_local == :utc
<add> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
<ide> def utc_time(*args)
<ide> time_with_datetime_fallback(:utc, *args)
<ide> end
<ide>
<del> # wraps class method time_with_datetime_fallback with utc_or_local == :local
<add> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
<ide> def local_time(*args)
<ide> time_with_datetime_fallback(:local, *args)
<ide> end
<ide> def change(options)
<ide> )
<ide> end
<ide>
<del> # Uses Date to provide precise Time calculations for years, months, and days. The +options+ parameter takes a hash with
<del> # any of these keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds.
<add> # Uses Date to provide precise Time calculations for years, months, and days.
<add> # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
<add> # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
<add> # <tt>:minutes</tt>, <tt>:seconds</tt>.
<ide> def advance(options)
<ide> d = to_date.advance(options)
<ide> time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
<ide><path>activesupport/lib/active_support/inflector.rb
<ide> def uncountable(*words)
<ide> (@uncountables << words).flatten!
<ide> end
<ide>
<del> # Clears the loaded inflections within a given scope (default is :all). Give the scope as a symbol of the inflection type,
<del> # the options are: :plurals, :singulars, :uncountables
<add> # Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
<add> # Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
<add> # <tt>:singulars</tt>, <tt>:uncountables</tt>.
<ide> #
<ide> # Examples:
<ide> # clear :all
<ide> def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
<ide> underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
<ide> end
<ide>
<del> # Constantize tries to find a declared constant with the name specified
<del> # in the string. It raises a NameError when the name is not in CamelCase
<del> # or is not initialized.
<add> # Tries to find a constant with the name specified in the argument string:
<ide> #
<del> # Examples
<del> # "Module".constantize #=> Module
<del> # "Class".constantize #=> Class
<add> # "Module".constantize # => Module
<add> # "Test::Unit".constantize # => Test::Unit
<add> #
<add> # The name is assumed to be the one of a top-level constant, no matter whether
<add> # it starts with "::" or not. No lexical context is taken into account:
<add> #
<add> # C = 'outside'
<add> # module M
<add> # C = 'inside'
<add> # C # => 'inside'
<add> # "C".constantize # => 'outside', same as ::C
<add> # end
<add> #
<add> # NameError is raised when the name is not in CamelCase or the constant is
<add> # unknown.
<ide> def constantize(camel_cased_word)
<ide> unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
<ide> raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
<ide><path>activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb
<ide> def capitalize(str)
<ide> # passing strings to databases and validations.
<ide> #
<ide> # * <tt>str</tt> - The string to perform normalization on.
<del> # * <tt>form</tt> - The form you want to normalize in. Should be one of the following: :c, :kc, :d or :kd.
<add> # * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
<add> # <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
<add> # ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM.
<ide> def normalize(str, form=ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM)
<ide> # See http://www.unicode.org/reports/tr15, Table 1
<ide> codepoints = u_unpack(str)
<ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> def rfc2822
<ide> end
<ide> alias_method :rfc822, :rfc2822
<ide>
<del> # :db format outputs time in UTC; all others output time in local. Uses TimeWithZone's strftime, so %Z and %z work correctly
<add> # <tt>:db</tt> format outputs time in UTC; all others output time in local.
<add> # Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
<ide> def to_s(format = :default)
<ide> return utc.to_s(format) if format == :db
<ide> if formatter = ::Time::DATE_FORMATS[format]
<ide> def to_s(format = :default)
<ide> end
<ide> end
<ide>
<del> # Replaces %Z and %z directives with #zone and #formatted_offset, respectively, before passing to
<add> # Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
<ide> # Time#strftime, so that zone information is correct
<ide> def strftime(format)
<ide> format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false))
<ide> def +(other)
<ide> result.in_time_zone(time_zone)
<ide> end
<ide>
<del> # If a time-like object is passed in, compare it with #utc
<del> # Else if wrapped #time is a DateTime, use DateTime#ago instead of #-
<del> # Otherwise, just pass on to method missing
<add> # If a time-like object is passed in, compare it with +utc+.
<add> # Else if wrapped +time+ is a DateTime, use DateTime#ago instead of DateTime#-.
<add> # Otherwise, just pass on to +method_missing+.
<ide> def -(other)
<ide> if other.acts_like?(:time)
<ide> utc - other
<ide> def to_i
<ide> alias_method :hash, :to_i
<ide> alias_method :tv_sec, :to_i
<ide>
<del> # A TimeWithZone acts like a Time, so just return self
<add> # A TimeWithZone acts like a Time, so just return +self+.
<ide> def to_time
<ide> self
<ide> end
<ide><path>railties/lib/initializer.rb
<ide> def plugins=(plugins)
<ide> attr_accessor :plugin_loader
<ide>
<ide> # Enables or disables plugin reloading. You can get around this setting per plugin.
<del> # If #reload_plugins? == false, add this to your plugin's init.rb to make it reloadable:
<add> # If <tt>reload_plugins?</tt> is false, add this to your plugin's init.rb to make it reloadable:
<ide> #
<ide> # Dependencies.load_once_paths.delete lib_path
<ide> #
<del> # If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
<add> # If <tt>reload_plugins?</tt> is true, add this to your plugin's init.rb to only load it once:
<ide> #
<ide> # Dependencies.load_once_paths << lib_path
<ide> # | 75 |
Javascript | Javascript | fix basisfile.transcodeimage parameters | 4ef5ee3f8830286caf753aada75f5f43f7275e4f | <ide><path>examples/js/loaders/BasisTextureLoader.js
<ide> THREE.BasisTextureLoader.BasisWorker = function () {
<ide> 0,
<ide> mip,
<ide> config.format,
<del> hasAlpha,
<del> 0
<add> 0,
<add> hasAlpha
<ide> );
<ide>
<ide> if ( ! status ) {
<ide><path>examples/jsm/loaders/BasisTextureLoader.js
<ide> BasisTextureLoader.BasisWorker = function () {
<ide> 0,
<ide> mip,
<ide> config.format,
<del> hasAlpha,
<del> 0
<add> 0,
<add> hasAlpha
<ide> );
<ide>
<ide> if ( ! status ) { | 2 |
Javascript | Javascript | remove `catch` from scheduler build | 18d7574ae297a24d53fe418e9008e969c29ffba2 | <ide><path>packages/scheduler/src/forks/SchedulerDOM.js
<ide> const performWorkUntilDeadline = () => {
<ide> // the message event.
<ide> deadline = currentTime + yieldInterval;
<ide> const hasTimeRemaining = true;
<add>
<add> // If a scheduler task throws, exit the current browser task so the
<add> // error can be observed.
<add> //
<add> // Intentionally not using a try-catch, since that makes some debugging
<add> // techniques harder. Instead, if `scheduledHostCallback` errors, then
<add> // `hasMoreWork` will remain true, and we'll continue the work loop.
<add> let hasMoreWork = true;
<ide> try {
<del> const hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
<del> if (!hasMoreWork) {
<del> isMessageLoopRunning = false;
<del> scheduledHostCallback = null;
<del> } else {
<add> hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
<add> } finally {
<add> if (hasMoreWork) {
<ide> // If there's more work, schedule the next message event at the end
<ide> // of the preceding one.
<ide> port.postMessage(null);
<add> } else {
<add> isMessageLoopRunning = false;
<add> scheduledHostCallback = null;
<ide> }
<del> } catch (error) {
<del> // If a scheduler task throws, exit the current browser task so the
<del> // error can be observed.
<del> port.postMessage(null);
<del> throw error;
<ide> }
<ide> } else {
<ide> isMessageLoopRunning = false;
<ide><path>packages/scheduler/src/forks/SchedulerPostTaskOnly.js
<ide> const performWorkUntilDeadline = () => {
<ide> // the message event.
<ide> deadline = currentTime + yieldInterval;
<ide> const hasTimeRemaining = true;
<add>
<add> // If a scheduler task throws, exit the current browser task so the
<add> // error can be observed.
<add> //
<add> // Intentionally not using a try-catch, since that makes some debugging
<add> // techniques harder. Instead, if `scheduledHostCallback` errors, then
<add> // `hasMoreWork` will remain true, and we'll continue the work loop.
<add> let hasMoreWork = true;
<ide> try {
<del> const hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
<del> if (!hasMoreWork) {
<add> hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
<add> } finally {
<add> if (hasMoreWork) {
<add> // If there's more work, schedule the next browser task at the end of
<add> // the preceding one.
<add> postTask(performWorkUntilDeadline);
<add> } else {
<ide> isTaskLoopRunning = false;
<ide> scheduledHostCallback = null;
<del> } else {
<del> // If there's more work, schedule the next message event at the end
<del> // of the preceding one.
<del> postTask(performWorkUntilDeadline);
<ide> }
<del> } catch (error) {
<del> // If a scheduler task throws, exit the current browser task so the
<del> // error can be observed.
<del> postTask(performWorkUntilDeadline);
<del> throw error;
<ide> }
<ide> } else {
<ide> isTaskLoopRunning = false; | 2 |
PHP | PHP | remove unused code | e63c63f6e3aa26ba0a977191749ca7c76d56b5eb | <ide><path>src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php
<ide> public function compileDropColumn(Blueprint $blueprint, Fluent $command)
<ide> */
<ide> public function compileDropPrimary(Blueprint $blueprint, Fluent $command)
<ide> {
<del> $table = $blueprint->getTable();
<del>
<ide> $table = $this->wrapTable($blueprint);
<ide>
<ide> return "alter table {$table} drop constraint {$command->index}"; | 1 |
Javascript | Javascript | use polling to reliably watch challenges | cba35969f0c2052e6005bb82cc65bfae805e160b | <ide><path>client/plugins/fcc-source-challenges/gatsby-node.js
<ide> exports.sourceNodes = function sourceChallengesSourceNodes(
<ide> const { createNode } = actions;
<ide> const watcher = chokidar.watch(curriculumPath, {
<ide> ignored: /(^|[\/\\])\../,
<del> persistent: true
<add> persistent: true,
<add> usePolling: true
<ide> });
<ide>
<ide> watcher.on('ready', sourceAndCreateNodes).on('change', filePath => | 1 |
Text | Text | clarify partial local variable naming | 4d433f8d21972d738f625bb4e41065e179ea01a8 | <ide><path>guides/source/layouts_and_rendering.md
<ide> To pass a local variable to a partial in only specific cases use the `local_assi
<ide>
<ide> This way it is possible to use the partial without the need to declare all local variables.
<ide>
<del>Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the `:object` option:
<add>Every partial also has a local variable with the same name as the partial (minus the leading underscore). You can pass an object in to this local variable via the `:object` option:
<ide>
<ide> ```erb
<ide> <%= render partial: "customer", object: @new_customer %> | 1 |
Python | Python | set default steps to 300k. | 01c3a4f3f34c2636d4108be35df31ac5f240a23b | <ide><path>official/transformer/v2/misc.py
<ide> def define_transformer_flags():
<ide> flags_core.define_device(tpu=True)
<ide>
<ide> flags.DEFINE_integer(
<del> name='train_steps', short_name='ts', default=None,
<add> name='train_steps', short_name='ts', default=300000,
<ide> help=flags_core.help_wrap('The number of steps used to train.'))
<ide> flags.DEFINE_integer(
<ide> name='steps_between_evals', short_name='sbe', default=1000, | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.