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
Text
Text
fix typos in texture article
45a32b784f787facb555062d0d263629b479eec0
<ide><path>threejs/lessons/threejs-textures.md <ide> Title: Three.js Textures <del>Description: Using Textures in three.js <add>Description: Using textures in three.js <ide> <ide> This article is one in a series of articles about three.js. <ide> The first article was [about three.js fundamentals](threejs-fundamentals.html). <ide> If you haven't read that yet you might want to start there. <ide> <ide> Textures are a kind of large topic in Three.js and <ide> I'm not 100% sure at what level to explain them but I will try. <del>There are many topics and many of them inter-relate so it's hard to explain <add>There are many topics and many of them interrelate so it's hard to explain <ide> them all at once. Here's quick table of contents for this article. <ide> <ide> <ul> <ide> <li><a href="#hello">Hello Texture</a></li> <del><li><a href="#six">6 Textures, a different one on each face of a cube</a></li> <del><li><a href="#loading">Loading Textures</a></li> <add><li><a href="#six">6 textures, a different one on each face of a cube</a></li> <add><li><a href="#loading">Loading textures</a></li> <ide> <ul> <del> <li><a href="#easy">The Easy Way</a></li> <add> <li><a href="#easy">The easy way</a></li> <ide> <li><a href="#wait1">Waiting for a texture to load</a></li> <ide> <li><a href="#waitmany">Waiting for multiple textures to load</a></li> <ide> <li><a href="#cors">Loading textures from other origins</a></li> <ide> </ul> <del><li><a href="#memory">Memory Usage</a></li> <add><li><a href="#memory">Memory usage</a></li> <ide> <li><a href="#format">JPG vs PNG</a></li> <del><li><a href="#filtering-and-mips">Filtering and Mips</a></li> <add><li><a href="#filtering-and-mips">Filtering and mips</a></li> <ide> <li><a href="#uvmanipulation">Repeating, offseting, rotating, wrapping</a></li> <ide> </ul> <ide> <ide> Note that we're using `MeshBasicMaterial` so no need for any lights. <ide> <ide> ## <a name="six"></a> 6 Textures, a different one on each face of a cube <ide> <del>How about 6 textures, one on each face of a cube? <add>How about 6 textures, one on each face of a cube? <ide> <ide> <div class="threejs_center"> <ide> <div> <ide> It works! <ide> <ide> {{{example url="../threejs-textured-cube-6-textures.html" }}} <ide> <del>It should be noted though that by default the only Geometry that supports multiple <add>It should be noted though that by default the only geometry that supports multiple <ide> materials is the `BoxGeometry` and `BoxBufferGeometry`. For other cases you will <ide> need to build or load custom geometry and/or modify texture coordinates. It's far <del>more common to use a [Texture Atlas](https://en.wikipedia.org/wiki/Texture_atlas) <add>more common to use a [Texture Atlas](https://en.wikipedia.org/wiki/Texture_atlas) <ide> if you want to allow multiple images on a single <ide> geometry. <ide> <ide> What are texture coordinates? They are data added to each vertex of a piece of geometry <del>that specify what part of the texture corresponds to that specific vertex. <add>that specify what part of the texture corresponds to that specific vertex. <ide> We'll go over them when we start building custom geometry. <ide> <ide> ## <a name="loading"></a> Loading Textures <ide> <ide> ### <a name="easy"></a> The Easy Way <ide> <del>Most of the code on this site uses the easiest method of loading textures. <del>We create a `TextureLoader` and then call its [`load`](TextureLoader.load) method. <add>Most of the code on this site uses the easiest method of loading textures. <add>We create a `TextureLoader` and then call its [`load`](TextureLoader.load) method. <ide> This returns a `Texture` object. <ide> <ide> ```js <ide> const texture = loader.load('resources/images/flower-1.jpg'); <ide> ``` <ide> <ide> It's important to note that using this method our texture will be transparent until <del>the image is loaded asychronously by three.js at which point it will update the texture <add>the image is loaded asynchronously by three.js at which point it will update the texture <ide> with the downloaded image. <ide> <ide> This has the big advantage that we don't have to wait for the texture to load and our <ide> the loading bar. <ide> <ide> {{{example url="../threejs-textured-cube-wait-for-all-textures.html" }}} <ide> <del>## <a name="cors"></a> Loading textures from other origins. <add>## <a name="cors"></a> Loading textures from other origins <ide> <ide> To use images from other servers those servers need to send the correct headers. <del>If they don't you can not use the images in three.js and will get an error. <add>If they don't you cannot use the images in three.js and will get an error. <ide> If you run the server providing the images make sure it <ide> [sends the correct headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). <del>If you don't control the server hosting the images and it does not send the <add>If you don't control the server hosting the images and it does not send the <ide> permission headers then you can't use the images from that server. <ide> <ide> For example [imgur](https://imgur.com), [flickr](https://flickr.com), and <ide> hosted on their servers in three.js. Most other websites do not. <ide> ## <a name="memory"></a> Memory Usage <ide> <ide> Textures are often the part of a three.js app that use the most memory. It's important to understand <del>that *in general*, textures take `width * height * 4 * 1.33` bytes of memory. <add>that *in general*, textures take `width * height * 4 * 1.33` bytes of memory. <ide> <ide> Notice that says nothing about compression. I can make a .jpg image and set its compression super <ide> high. For example let's say I was making a scene of a house. Inside the house there is a table <ide> and I decide to put this wood texture on the top surface of the table <ide> <ide> <div class="threejs_center"><img class="border" src="resources/images/compressed-but-large-wood-texture.jpg" align="center" style="width: 300px"></div> <ide> <del>That image is only 157k so it will download relatively quickly but [it is actually <del>3024 x 3761 pixels in size](resources/images/compressed-but-large-wood-texture.jpg). <add>That image is only 157k so it will download relatively quickly but [it is actually <add>3024 x 3761 pixels in size](resources/images/compressed-but-large-wood-texture.jpg). <ide> Following the equation above that's <ide> <ide> 3024 * 3761 * 4 * 1.33 = 60505764.5 <ide> <del>That image will take **60 MEG OF MEMORY!** in three.js. <add>That image will take **60 MEG OF MEMORY!** in three.js. <ide> A few textures like that and you'll be out of memory. <ide> <del>I bring this up because it's important to know that using textures has a hidden cost. <del>In order for three.js to use the texture it has to hand it off to the GPU and the <add>I bring this up because it's important to know that using textures has a hidden cost. <add>In order for three.js to use the texture it has to hand it off to the GPU and the <ide> GPU *in general* requires the texture data to be uncompressed. <ide> <del>The moral of the story is make your textures small in dimensions not just small <del>in file size. Small in file size = fast to download. Small in dimesions = takes <add>The moral of the story is make your textures small in dimensions not just small <add>in file size. Small in file size = fast to download. Small in dimesions = takes <ide> less memory. How small should you make them? <ide> As small as you can and still look as good as you need them to look. <ide> <ide> ## <a name="format"></a> JPG vs PNG <ide> <del>This is pretty much the same as regular HTML in that JPGs have lossy compression, <del>PNGs have lossless compression so PNGs are generally slower to download. <add>This is pretty much the same as regular HTML in that JPGs have lossy compression, <add>PNGs have lossless compression so PNGs are generally slower to download. <ide> But, PNGs support transparency. PNGs are also probably the appropriate format <del>for non-image data like normal maps, and other kinds of non-image maps which we'll go over later. <add>for non-image data like normal maps, and other kinds of non-image maps which we'll go over later. <ide> <ide> It's important to remember that a JPG doesn't use <ide> less memory than a PNG in WebGL. See above. <ide> to make those 1 or 2 pixels. That would be a very slow operation. GPUs solve thi <ide> using mipmaps. <ide> <ide> Mips are copies of the texture, each one half as wide and half as tall as the previous <del>mip where the pixels have been blended to make the next smaller mip. Mips are created <del>until we get all the way to a 1x1 pixel mip. For the image above all of the mips would <add>mip where the pixels have been blended to make the next smaller mip. Mips are created <add>until we get all the way to a 1x1 pixel mip. For the image above all of the mips would <ide> end up being something like this <ide> <ide> <div class="threejs_center"><img src="resources/images/mipmap-low-res-enlarged.png" align="center"></div> <ide> Now, when the cube is drawn so small that it's only 1 or 2 pixels large the GPU <ide> to use just the smallest or next to smallest mip level to decide what color to make the <ide> tiny cube. <ide> <del>In three you can choose what happens both what happens when the texture is drawn <add>In three you can choose what happens both when the texture is drawn <ide> larger than its original size and what happens when it's drawn smaller than its <ide> original size. <ide> <ide> you set the [`texture.minFilter`](Texture.minFilter) property to one of 6 values <ide> <ide> * `THREE.NearestFilter` <ide> <del> same as above. Choose the closest pixel in the texture <add> same as above, choose the closest pixel in the texture <ide> <ide> * `THREE.LinearFilter` <ide> <del> same as above, Choose 4 pixels from the texture and blend them <add> same as above, choose 4 pixels from the texture and blend them <ide> <ide> * `THREE.NearestMipMapNearestFilter` <ide> <del> choose the appropriate mip then choose one pixel. <add> choose the appropriate mip then choose one pixel <ide> <ide> * `THREE.NearestMipMapLinearFilter` <ide> <del> choose 2 mips, choose one pixel from each, blend the 2 pixels. <add> choose 2 mips, choose one pixel from each, blend the 2 pixels <ide> <ide> * `THREE.LinearMipMapNearestFilter` <ide> <del> chose the appropriate mip then choose 4 pixels and blend them. <add> chose the appropriate mip then choose 4 pixels and blend them <ide> <ide> * `THREE.LinearMipMapLinearFilter` <ide> <del> choose 2 mips, choose 4 pixels from each and blend all 8 into 1 pixel. <add> choose 2 mips, choose 4 pixels from each and blend all 8 into 1 pixel <ide> <ide> Here's an example showing all 6 settings <ide> <ide> <div class="spread"> <ide> <div data-diagram="filterModes" style=" <del> height: 450px; <add> height: 450px; <ide> position: relative; <ide> "> <ide> <div style=" <ide> Here's an example showing all 6 settings <ide> <ide> One thing to notice is the top left and top middle using `NearestFilter` and `LinearFilter` <ide> don't use the mips. Because of that they flicker in the distance because the GPU is <del>picking pixels from the original texture. On the left just one pixel is chosen and <add>picking pixels from the original texture. On the left just one pixel is chosen and <ide> in the middle 4 are chosen and blended but it's not enough come up with a good <ide> representative color. The other 4 strips do better with the bottom right, <ide> `LinearMipMapLinearFilter` being best. <ide> <ide> If you click the picture above it will toggle between the texture we've been using above <del>and a texture where every mip level is a different color. <add>and a texture where every mip level is a different color. <ide> <ide> <div class="threejs_center"> <ide> <div data-texture-diagram="differentColoredMips"></div> <ide> They can be set to one of: <ide> <ide> * `THREE.ClampToEdgeWrapping` <ide> <del> The last pixel on each edge is repeated forever <add> the last pixel on each edge is repeated forever <ide> <ide> * `THREE.RepeatWrapping` <ide> <del> The texture is repeated <add> the texture is repeated <ide> <ide> * `THREE.MirroredRepeatWrapping` <ide> <del> The texture is mirrored and repeated. <add> the texture is mirrored and repeated <ide> <ide> For example to turn on wrapping in both directions: <ide> <ide> someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically); <ide> ``` <ide> <ide> Offseting the texture can be done by setting the `offset` property. Textures <del>are offset with units where 1 unit = 1 texture size. On other words 0 = no offset <add>are offset with units where 1 unit = 1 texture size. On other words 0 = no offset <ide> and 1 = offset one full texture amount. <ide> <ide> ```js <ide> const xOffset = .5; // offset by half the texture <del>const yOffset = .25; // offset by 1/2 the texture <del>someTexture.offset.set(xOffset, yOffset);` <add>const yOffset = .25; // offset by 1/4 the texture <add>someTexture.offset.set(xOffset, yOffset); <ide> ``` <ide> <del>Rotating the texture can be set by setting `rotation` property in radians <add>Rotating the texture can be set by setting the `rotation` property in radians <ide> as well as the `center` property for choosing the center of rotation. <ide> It defaults to 0,0 which rotates from the bottom left corner. Like offset <ide> these units are in texture size so setting them to `.5, .5` would rotate <ide> around the center of the texture. <ide> <ide> ```js <ide> someTexture.center.set(.5, .5); <del>someTexture.rotation = THREE.Math.degToRad(45); <add>someTexture.rotation = THREE.Math.degToRad(45); <ide> ``` <ide> <ide> Let's modify the top sample above to play with these values <ide> gui.add(new DegRadHelper(texture, 'rotation'), 'value', -360, 360) <ide> ``` <ide> <ide> The last thing to note about the example is that if you change `wrapS` or <del>`wrapT` on the texture you must also set [`texture.needsUpdate`](Texture.needsUpdate) <add>`wrapT` on the texture you must also set [`texture.needsUpdate`](Texture.needsUpdate) <ide> so three.js knows to apply those settings. The other settings are automatically applied. <ide> <ide> {{{example url="../threejs-textured-cube-adjust.html" }}} <ide> to materials. <ide> For now let's move on to [lights](threejs-lights.html). <ide> <ide> <!-- <del>alpha <add>alpha <ide> ao <ide> env <ide> light <ide> roughness <ide> font-family: monospace; <ide> font-size: small; <ide> text-shadow: <del> -1px -1px 0 #000, <add> -1px -1px 0 #000, <ide> 1px -1px 0 #000, <ide> -1px 1px 0 #000, <ide> 1px 1px 0 #000;
1
PHP
PHP
add sanctum cookie endpoint to default cors paths
aa6d3660114c93e537a52e0ba3c03071a7f3e67f
<ide><path>config/cors.php <ide> | <ide> */ <ide> <del> 'paths' => ['api/*'], <add> 'paths' => ['api/*', 'sanctum/csrf-cookie'], <ide> <ide> 'allowed_methods' => ['*'], <ide>
1
Python
Python
fix cloudstack lb tests, gogrid tests and s3 tests
da0a40e003a88883d1e33b97499fbb6ef1eecef5
<ide><path>libcloud/test/__init__.py <ide> def __init__(self, *args, **kwargs): <ide> unittest.TestCase.__init__(self, '__init__') <ide> super(MockHttp, self).__init__(*args, **kwargs) <ide> <del> def _get_request(self, method, url, body=None, headers=None, raw=False, stream=False): <add> def _get_request(self, method, url, body=None, headers=None): <ide> # Find a method we can use for this request <ide> parsed = urlparse.urlparse(url) <ide> _, _, path, _, query, _ = parsed <ide> def _get_request(self, method, url, body=None, headers=None, raw=False, stream=F <ide> if self.test and isinstance(self.test, LibcloudTestCase): <ide> self.test._add_visited_url(url=url) <ide> self.test._add_executed_mock_method(method_name=meth_name) <del> <ide> return meth(method, url, body, headers) <ide> <ide> def request(self, method, url, body=None, headers=None, raw=False, stream=False): <ide><path>libcloud/test/common/test_cloudstack.py <ide> def test_signature_algorithm(self): <ide> self.assertEqual(connection._make_signature(params), b(case[1])) <ide> <ide> <del>class CloudStackMockHttp(MockHttp): <add>class CloudStackMockHttp(MockHttp, unittest.TestCase): <ide> <ide> ERROR_TEXT = 'ERROR TEXT' <ide> <ide><path>libcloud/test/loadbalancer/test_cloudstack.py <ide> def test_balancer_list_members(self): <ide> self.assertEqual(member.balancer, balancer) <ide> <ide> <del>class CloudStackMockHttp(MockHttp): <add>class CloudStackMockHttp(MockHttp, unittest.TestCase): <ide> fixtures = LoadBalancerFileFixtures('cloudstack') <ide> fixture_tag = 'default' <ide> <ide><path>libcloud/test/loadbalancer/test_gogrid.py <ide> def test_balancer_detach_member(self): <ide> self.assertTrue(ret2) <ide> <ide> <del>class GoGridLBMockHttp(MockHttp): <add>class GoGridLBMockHttp(MockHttp, unittest.TestCase): <ide> fixtures = LoadBalancerFileFixtures('gogrid') <ide> <ide> def _api_grid_loadbalancer_list(self, method, url, body, headers): <ide><path>libcloud/test/storage/test_s3.py <ide> def _foo_bar_container_foo_bar_object_NOT_FOUND(self, method, url, body, <ide> headers, <ide> httplib.responses[httplib.OK]) <ide> <del> def _foo_bar_container_foo_bar_object(self, method, url, body, headers): <add> def _foo_bar_container_foo_bar_object_DELETE(self, method, url, body, headers): <ide> # test_delete_object <ide> return (httplib.NO_CONTENT, <ide> body, <ide> def test_delete_object_not_found(self): <ide> self.fail('Exception was not thrown') <ide> <ide> def test_delete_object_success(self): <add> self.mock_response_klass.type = 'DELETE' <ide> container = Container(name='foo_bar_container', extra={}, <ide> driver=self.driver) <ide> obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None,
5
Ruby
Ruby
ask the strexp for the ast
eabe504cdfa11b580c614d6bd501eb7cc60f485d
<ide><path>actionpack/lib/action_dispatch/journey/path/pattern.rb <ide> class Pattern # :nodoc: <ide> attr_reader :spec, :requirements, :anchored <ide> <ide> def initialize(strexp) <del> parser = Journey::Parser.new <del> <ide> @anchored = true <ide> <ide> case strexp <ide> when String <add> parser = Journey::Parser.new <ide> @spec = parser.parse(strexp) <ide> @requirements = {} <ide> @separators = "/.?" <ide> when Router::Strexp <del> @spec = parser.parse(strexp.path) <add> @spec = strexp.ast <ide> @requirements = strexp.requirements <ide> @separators = strexp.separators.join <ide> @anchored = strexp.anchor <ide><path>actionpack/lib/action_dispatch/journey/router/strexp.rb <ide> def initialize(path, requirements, separators, anchor = true) <ide> @anchor = anchor <ide> end <ide> <add> def ast <add> parser = Journey::Parser.new <add> parser.parse path <add> end <add> <ide> def names <ide> @path.scan(/:\w+/).map { |s| s.tr(':', '') } <ide> end
2
Ruby
Ruby
fix regex location
0321acf9bee02903ccb0db7d8b2ff39da26100bf
<ide><path>Library/Homebrew/brew_doctor.rb <ide> def check_for_config_scripts <ide> paths = ENV['PATH'].split(':').collect{|p| File.expand_path p} <ide> paths.each do |p| <ide> next if ['/usr/bin', '/usr/sbin', '/usr/X11/bin', "#{HOMEBREW_PREFIX}/bin", "#{HOMEBREW_PREFIX}/sbin"].include? p <del> next if %r[^(#{real_cellar.to_s}|#{HOMEBREW_CELLAR.to_s})] =~ p <add> next if p =~ %r[^(#{real_cellar.to_s}|#{HOMEBREW_CELLAR.to_s})] <ide> <ide> configs = Dir["#{p}/*-config"] <ide> # puts "#{p}\n #{configs * ' '}" unless configs.empty?
1
Go
Go
add images testcase
832f39c2ed53fc4a91265798198273044448bc7f
<ide><path>image/image_test.go <ide> package image <ide> <ide> import ( <ide> "encoding/json" <add> "runtime" <ide> "sort" <ide> "strings" <ide> "testing" <ide> func TestMarshalKeyOrder(t *testing.T) { <ide> } <ide> } <ide> <add>func TestImage(t *testing.T) { <add> cid := "50a16564e727" <add> config := &container.Config{ <add> Hostname: "hostname", <add> Domainname: "domain", <add> User: "root", <add> } <add> platform := runtime.GOOS <add> <add> img := &Image{ <add> V1Image: V1Image{ <add> Config: config, <add> }, <add> computedID: ID(cid), <add> } <add> <add> assert.Equal(t, cid, img.ImageID()) <add> assert.Equal(t, cid, img.ID().String()) <add> assert.Equal(t, platform, img.Platform()) <add> assert.Equal(t, config, img.RunConfig()) <add>} <add> <add>func TestImagePlatformNotEmpty(t *testing.T) { <add> platform := "platform" <add> img := &Image{ <add> V1Image: V1Image{ <add> OS: platform, <add> }, <add> OSVersion: "osversion", <add> } <add> assert.Equal(t, platform, img.Platform()) <add>} <add> <ide> func TestNewChildImageFromImageWithRootFS(t *testing.T) { <ide> rootFS := NewRootFS() <ide> rootFS.Append(layer.DiffID("ba5e"))
1
Ruby
Ruby
remove redundant eos
52de5aa9847d700b63c70ec75c1a98dc848c43e4
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_xcode_up_to_date <ide> Xcode can be updated from <ide> https://developer.apple.com/downloads <ide> EOS <del> EOS <ide> end <ide> end <ide> else
1
Python
Python
add the psutil version to the -v and -h tag
94a7cc57cad2511244ac5cac9d615c2bf6dfbbf2
<ide><path>glances/glances.py <ide> def displayProcess(self, processcount, processlist, sortedby='', log_count=0): <ide> _("Compute data..."), 15) <ide> return 6 <ide> <add> # Display the processes list <ide> proc_num = min(screen_y - self.term_h + <ide> self.process_y - log_count + 5, <ide> len(processlist)) <ide> def client_get(self): <ide> <ide> <ide> def printVersion(): <del> print(_("Glances version") + (" ") + __version__) <add> print(_("Glances version") + (" ") + __version__ + _(" with PsUtil ") + psutil.__version__) <ide> <ide> <ide> def printSyntax():
1
Text
Text
fix spelling of "loader"
83ac8b67de897b15a6e5aedad054605989cdf61d
<ide><path>README.md <ide> that include your webpack.config.js and relevant files are more likely to receiv <ide> <ide> If you have discovered a bug or have a feature suggestion, feel free to create an issue on Github. <ide> <del>If you create a lodaer or plugin, please consider open sourcing it, putting it <add>If you create a loader or plugin, please consider open sourcing it, putting it <ide> on NPM and following the `x-loader`, `x-plugin` convention. <ide> <ide> You are also welcome to correct any spelling mistakes or any language issues.
1
Text
Text
fix tensorflow_models keras_nlp link
1308ecdc81a942f60af1092597cc5ac2ea7a0766
<ide><path>official/nlp/keras_nlp/contributing.md <ide> Patches to KerasNLP are welcome! <ide> <ide> The source-of-truth repository lives under <del>[TF Model Garden NLP](https://github.com/tensorflow/models/official/nlp/keras_nlp), <add>[TF Model Garden NLP](https://github.com/tensorflow/models/tree/master/official/nlp/keras_nlp), <ide> and is mirrored as a read-only repository under <ide> [keras-team/keras-nlp](https://github.com/keras-team/keras-nlp). <ide> Contributions should be made as PRs to the TF Model Garden repository.
1
Javascript
Javascript
remove redundant check of rli.rine.length
6b5a34cdf30827a0e64c49008b4bcdb55738bc9b
<ide><path>lib/repl.js <ide> function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) { <ide> <ide> rli.line = ''; <ide> <del> if (!(self.bufferedCommand && self.bufferedCommand.length > 0) && <del> rli.line.length === 0) { <add> if (!(self.bufferedCommand && self.bufferedCommand.length > 0)) { <ide> rli.output.write('(^C again to quit)\n'); <ide> sawSIGINT = true; <ide> }
1
Python
Python
remove unnecssary logging in experimental api
790bc784435646c043d8def7096917a4ce0a62f7
<ide><path>airflow/www/api/experimental/endpoints.py <ide> def trigger_dag(dag_id): <ide> try: <ide> execution_date = timezone.parse(execution_date) <ide> except ValueError: <add> log.error("Given execution date could not be identified as a date.") <ide> error_message = ( <ide> f'Given execution date, {execution_date}, could not be identified as a date. ' <ide> f'Example date format: 2015-11-16T14:34:15+00:00' <ide> ) <del> log.error(error_message) <ide> response = jsonify({'error': error_message}) <ide> response.status_code = 400 <ide> <ide> def task_instance_info(dag_id, execution_date, task_id): <ide> try: <ide> execution_date = timezone.parse(execution_date) <ide> except ValueError: <add> log.error("Given execution date could not be identified as a date.") <ide> error_message = ( <ide> f'Given execution date, {execution_date}, could not be identified as a date. ' <ide> f'Example date format: 2015-11-16T14:34:15+00:00' <ide> ) <del> log.error(error_message) <ide> response = jsonify({'error': error_message}) <ide> response.status_code = 400 <ide> <ide> def dag_run_status(dag_id, execution_date): <ide> try: <ide> execution_date = timezone.parse(execution_date) <ide> except ValueError: <add> log.error("Given execution date could not be identified as a date.") <ide> error_message = ( <ide> f'Given execution date, {execution_date}, could not be identified as a date. ' <ide> f'Example date format: 2015-11-16T14:34:15+00:00' <ide> ) <del> log.error(error_message) <ide> response = jsonify({'error': error_message}) <ide> response.status_code = 400 <ide> <ide> def get_lineage(dag_id: str, execution_date: str): <ide> try: <ide> execution_dt = timezone.parse(execution_date) <ide> except ValueError: <add> log.error("Given execution date could not be identified as a date.") <ide> error_message = ( <ide> f'Given execution date, {execution_date}, could not be identified as a date. ' <ide> f'Example date format: 2015-11-16T14:34:15+00:00' <ide> ) <del> log.error(error_message) <ide> response = jsonify({'error': error_message}) <ide> response.status_code = 400 <ide>
1
Javascript
Javascript
remove visiblitysupport mixin
8639e0e55bfd2d275c14da8e017fcab03c5d250e
<ide><path>packages/ember-glimmer/lib/component.js <ide> const Component = CoreView.extend( <ide> @public <ide> @since 1.13.0 <ide> */ <add> <add> /** <add> If `false`, the view will appear hidden in DOM. <add> <add> @property isVisible <add> @type Boolean <add> @default null <add> @public <add> */ <ide> } <ide> ); <ide> <ide><path>packages/ember-views/lib/mixins/visibility_support.js <del>/** <del> @module ember <del> @submodule ember-views <del>*/ <del>import { <del> Mixin, <del> observer, <del> get, <del> run <del>} from 'ember-metal'; <del> <del>function K() { return this; } <del> <del>/** <del> @class VisibilitySupport <del> @namespace Ember <del> @public <del>*/ <del>export default Mixin.create({ <del> /** <del> If `false`, the view will appear hidden in DOM. <del> <del> @property isVisible <del> @type Boolean <del> @default null <del> @public <del> */ <del> isVisible: true, <del> <del> becameVisible: K, <del> becameHidden: K, <del> <del> /** <del> When the view's `isVisible` property changes, toggle the visibility <del> element of the actual DOM element. <del> <del> @method _isVisibleDidChange <del> @private <del> */ <del> _isVisibleDidChange: observer('isVisible', function() { <del> if (this._isVisible === get(this, 'isVisible')) { return ; } <del> run.scheduleOnce('render', this, this._toggleVisibility); <del> }), <del> <del> _toggleVisibility() { <del> let $el = this.$(); <del> let isVisible = get(this, 'isVisible'); <del> <del> if (this._isVisible === isVisible) { return ; } <del> <del> // It's important to keep these in sync, even if we don't yet have <del> // an element in the DOM to manipulate: <del> this._isVisible = isVisible; <del> <del> if (!$el) { return; } <del> <del> $el.toggle(isVisible); <del> <del> if (this._isAncestorHidden()) { return; } <del> <del> if (isVisible) { <del> this._notifyBecameVisible(); <del> } else { <del> this._notifyBecameHidden(); <del> } <del> }, <del> <del> _notifyBecameVisible() { <del> this.trigger('becameVisible'); <del> let childViews = this.childViews; <del> for (let i = 0; i < childViews.length; i++) { <del> let view = childViews[i]; <del> let isVisible = get(view, 'isVisible'); <del> if (isVisible || isVisible === null) { <del> view._notifyBecameVisible(); <del> } <del> } <del> }, <del> <del> _notifyBecameHidden() { <del> this.trigger('becameHidden'); <del> let childViews = this.childViews; <del> for (let i = 0; i < childViews.length; i++) { <del> let view = childViews[i]; <del> let isVisible = get(view, 'isVisible'); <del> if (isVisible || isVisible === null) { <del> view._notifyBecameHidden(); <del> } <del> } <del> }, <del> <del> _isAncestorHidden() { <del> let parent = this.parentView; <del> while (parent) { <del> if (get(parent, 'isVisible') === false) { return true; } <del> parent = parent.parentView; <del> } <del> return false; <del> } <del>}); <ide><path>packages/ember-views/lib/views/core_view.js <del>import { get } from 'ember-metal'; <del> <ide> import { <ide> Object as EmberObject, <ide> Evented, <ide> const CoreView = EmberObject.extend(Evented, ActionHandler, { <ide> this._dispatching = null; <ide> this._destroyingSubtreeForView = null; <ide> this._isDispatchingAttrs = false; <del> this._isVisible = false; <ide> this.element = null; <ide> this._env = null; <del> this._isVisible = get(this, 'isVisible'); <ide> <ide> if (!this.renderer) { <ide> throw new Error(`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`); <ide><path>packages/ember-views/lib/views/view.js <ide> import CoreView from './core_view'; <ide> import ViewChildViewsSupport from '../mixins/child_views_support'; <ide> import ViewStateSupport from '../mixins/view_state_support'; <ide> import ClassNamesSupport from '../mixins/class_names_support'; <del>import VisibilitySupport from '../mixins/visibility_support'; <ide> import ViewMixin from '../mixins/view_support'; <ide> <ide> /** <ide> import ViewMixin from '../mixins/view_support'; <ide> @uses Ember.ViewChildViewsSupport <ide> @uses Ember.ClassNamesSupport <ide> @uses Ember.AttributeBindingsSupport <del> @uses Ember.VisibilitySupport <ide> @public <ide> */ <ide> // jscs:disable validateIndentation <ide> var View = CoreView.extend( <ide> ViewChildViewsSupport, <ide> ViewStateSupport, <ide> ClassNamesSupport, <del> VisibilitySupport, <ide> ViewMixin); <ide> <ide> // jscs:enable validateIndentation
4
Python
Python
skip broken tests
3f0707b2fe78bc690793783a63a37b31d124fe90
<ide><path>tests/models/owlvit/test_modeling_owlvit.py <ide> def prepare_img(): <ide> <ide> @require_vision <ide> @require_torch <add>@unittest.skip("These tests are broken, fix me Alara") <ide> class OwlViTModelIntegrationTest(unittest.TestCase): <del> # @slow <add> @slow <ide> def test_inference(self): <ide> model_name = "google/owlvit-base-patch32" <ide> model = OwlViTModel.from_pretrained(model_name).to(torch_device)
1
Javascript
Javascript
add strokeopacity to unitless css properties
96126e9ff4934cefe11542a5fb4402cfca3b7684
<ide><path>src/browser/ui/dom/CSSProperty.js <ide> */ <ide> var isUnitlessNumber = { <ide> columnCount: true, <del> fillOpacity: true, <ide> flex: true, <ide> flexGrow: true, <ide> flexShrink: true, <ide> var isUnitlessNumber = { <ide> orphans: true, <ide> widows: true, <ide> zIndex: true, <del> zoom: true <add> zoom: true, <add> <add> // SVG-related properties <add> fillOpacity: true, <add> strokeOpacity: true <ide> }; <ide> <ide> /**
1
Python
Python
update doc for revision and token
24476722696de88e78fe00bd192da8b416b8b2bd
<ide><path>src/transformers/configuration_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], <ide> proxies (`Dict[str, str]`, *optional*): <ide> A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', <ide> 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. <del> use_auth_token (`str` or *bool*, *optional*): <del> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated <del> when running `huggingface-cli login` (stored in `~/.huggingface`). <add> use_auth_token (`str` or `bool`, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use <add> the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). <ide> revision (`str`, *optional*, defaults to `"main"`): <ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <ide> identifier allowed by git. <add> <add> <Tip> <add> <add> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". <add> <add> </Tip> <add> <ide> return_unused_kwargs (`bool`, *optional*, defaults to `False`): <ide> If `False`, then this function returns just the final configuration object. <ide> <ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], <ide> values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled <ide> by the `return_unused_kwargs` keyword parameter. <ide> <del> <Tip> <del> <del> Passing `use_auth_token=True` is required when you want to use a private model. <del> <del> </Tip> <del> <ide> Returns: <ide> [`PretrainedConfig`]: The configuration object instantiated from this pretrained model. <ide> <ide><path>src/transformers/feature_extraction_utils.py <ide> def from_pretrained( <ide> proxies (`Dict[str, str]`, *optional*): <ide> A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', <ide> 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. <del> use_auth_token (`str` or *bool*, *optional*): <del> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated <del> when running `huggingface-cli login` (stored in `~/.huggingface`). <add> use_auth_token (`str` or `bool`, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use <add> the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). <ide> revision (`str`, *optional*, defaults to `"main"`): <ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <ide> identifier allowed by git. <add> <add> <add> <Tip> <add> <add> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". <add> <add> </Tip> <add> <ide> return_unused_kwargs (`bool`, *optional*, defaults to `False`): <ide> If `False`, then this function returns just the final feature extractor object. If `True`, then this <ide> functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary <ide> def from_pretrained( <ide> loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is <ide> controlled by the `return_unused_kwargs` keyword parameter. <ide> <del> <Tip> <del> <del> Passing `use_auth_token=True` is required when you want to use a private model. <del> <del> </Tip> <del> <ide> Returns: <ide> A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]. <ide> <ide><path>src/transformers/modeling_flax_utils.py <ide> def from_pretrained( <ide> 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. <ide> local_files_only(`bool`, *optional*, defaults to `False`): <ide> Whether or not to only look at local files (i.e., do not try to download the model). <add> use_auth_token (`str` or `bool`, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use <add> the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). <ide> revision (`str`, *optional*, defaults to `"main"`): <ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <ide> identifier allowed by git. <add> <add> <add> <Tip> <add> <add> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". <add> <add> </Tip> <add> <ide> subfolder (`str`, *optional*, defaults to `""`): <ide> In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can <ide> specify the folder name here. <ide><path>src/transformers/modeling_tf_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> dictionary containing missing keys, unexpected keys and error messages. <ide> local_files_only(`bool`, *optional*, defaults to `False`): <ide> Whether or not to only look at local files (e.g., not try doanloading the model). <del> use_auth_token (`str` or *bool*, *optional*): <del> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated <del> when running `huggingface-cli login` (stored in `~/.huggingface`). <add> use_auth_token (`str` or `bool`, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use <add> the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). <ide> revision (`str`, *optional*, defaults to `"main"`): <ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <ide> identifier allowed by git. <add> <add> <add> <Tip> <add> <add> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". <add> <add> </Tip> <add> <ide> mirror (`str`, *optional*): <ide> Mirror source to accelerate downloads in China. If you are from China and have an accessibility <ide> problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute <ide> will be passed to the underlying model's `__init__` function. <ide> <del> <Tip> <del> <del> Passing `use_auth_token=True` is required when you want to use a private model. <del> <del> </Tip> <del> <ide> Examples: <ide> <ide> ```python <ide><path>src/transformers/modeling_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P <ide> Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. <ide> local_files_only(`bool`, *optional*, defaults to `False`): <ide> Whether or not to only look at local files (i.e., do not try to download the model). <del> use_auth_token (`str` or *bool*, *optional*): <del> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated <del> when running `huggingface-cli login` (stored in `~/.huggingface`). <add> use_auth_token (`str` or `bool`, *optional*): <add> The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use <add> the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). <ide> revision (`str`, *optional*, defaults to `"main"`): <ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a <ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any <ide> identifier allowed by git. <add> <add> <add> <Tip> <add> <add> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". <add> <add> </Tip> <add> <ide> mirror (`str`, *optional*): <ide> Mirror source to accelerate downloads in China. If you are from China and have an accessibility <ide> problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. <ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P <ide> <ide> <Tip> <ide> <del> Passing `use_auth_token=True`` is required when you want to use a private model. <del> <del> </Tip> <del> <del> <Tip> <del> <ide> Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to <ide> use this method in a firewalled environment. <ide>
5
PHP
PHP
add __serialize()/__unserialize() magic methods
9697c130c698f985ea953b3325f29e3aaae42ba9
<ide><path>src/Collection/Collection.php <ide> public function serialize(): string <ide> return serialize($this->buffered()); <ide> } <ide> <add> /** <add> * Returns an array for serializing this of this object. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <add> { <add> return $this->buffered()->toArray(); <add> } <add> <ide> /** <ide> * Unserializes the passed string and rebuilds the Collection instance <ide> * <ide> public function unserialize($collection): void <ide> $this->__construct(unserialize($collection)); <ide> } <ide> <add> /** <add> * Rebuilds the Collection instance. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->__construct($data); <add> } <add> <ide> /** <ide> * {@inheritDoc} <ide> * <ide><path>src/Collection/Iterator/BufferedIterator.php <ide> public function serialize(): string <ide> return serialize($this->_buffer); <ide> } <ide> <add> /** <add> * Magic method used for serializing the iterator instance. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <add> { <add> if (!$this->_finished) { <add> $this->count(); <add> } <add> <add> return iterator_to_array($this->_buffer); <add> } <add> <ide> /** <ide> * Unserializes the passed string and rebuilds the BufferedIterator instance <ide> * <ide> public function unserialize($buffer): void <ide> $this->_started = true; <ide> $this->_finished = true; <ide> } <add> <add> /** <add> * Magic method used to rebuild the iterator instance. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->__construct([]); <add> <add> foreach ($data as $value) { <add> $this->_buffer->push($value); <add> } <add> <add> $this->_started = true; <add> $this->_finished = true; <add> } <ide> } <ide><path>src/Collection/Iterator/ZipIterator.php <ide> public function serialize(): string <ide> return serialize($this->_iterators); <ide> } <ide> <add> /** <add> * Magic method used for serializing the iterator instance. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <add> { <add> return $this->_iterators; <add> } <add> <ide> /** <ide> * Unserializes the passed string and rebuilds the ZipIterator instance <ide> * <ide> public function unserialize($iterators): void <ide> $this->attachIterator($it); <ide> } <ide> } <add> <add> /** <add> * Magic method used to rebuild the iterator instance. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> parent::__construct(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_NUMERIC); <add> <add> $this->_iterators = $data; <add> foreach ($this->_iterators as $it) { <add> $this->attachIterator($it); <add> } <add> } <ide> } <ide><path>src/Log/Engine/BaseLog.php <ide> protected function _format(string $message, array $context = []): string <ide> } <ide> <ide> if (is_object($value)) { <del> if (method_exists($value, '__toString')) { <del> $replacements['{' . $key . '}'] = (string)$value; <add> if (method_exists($value, 'toArray')) { <add> $replacements['{' . $key . '}'] = json_encode($value->toArray(), JSON_UNESCAPED_UNICODE); <ide> continue; <ide> } <ide> <del> if (method_exists($value, 'toArray')) { <del> $replacements['{' . $key . '}'] = json_encode($value->toArray(), JSON_UNESCAPED_UNICODE); <add> if (method_exists($value, '__serialize')) { <add> $replacements['{' . $key . '}'] = serialize($value); <add> continue; <add> } <add> <add> if (method_exists($value, '__toString')) { <add> $replacements['{' . $key . '}'] = (string)$value; <ide> continue; <ide> } <ide> <ide><path>src/Mailer/Email.php <ide> public function createFromArray(array $config) <ide> * @return string <ide> */ <ide> public function serialize(): string <add> { <add> $array = $this->__serialize(); <add> <add> return serialize($array); <add> } <add> <add> /** <add> * Magic method used for serializing the Email object. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <ide> { <ide> $array = $this->jsonSerialize(); <ide> array_walk_recursive($array, function (&$item, $key): void { <ide> public function serialize(): string <ide> } <ide> }); <ide> <del> return serialize($array); <add> return $array; <ide> } <ide> <ide> /** <ide> public function unserialize($data): void <ide> $this->createFromArray(unserialize($data)); <ide> } <ide> <add> /** <add> * Magic method used to rebuild the Email object. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->createFromArray($data); <add> } <add> <ide> /** <ide> * Proxy all static method calls (for methods provided by StaticConfigTrait) to Mailer. <ide> * <ide><path>src/Mailer/Message.php <ide> public function createFromArray(array $config) <ide> * @return string <ide> */ <ide> public function serialize(): string <add> { <add> $array = $this->__serialize(); <add> <add> return serialize($array); <add> } <add> <add> /** <add> * Magic method used for serializing the Message object. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <ide> { <ide> $array = $this->jsonSerialize(); <ide> array_walk_recursive($array, function (&$item, $key): void { <ide> public function serialize(): string <ide> } <ide> }); <ide> <del> return serialize($array); <add> return $array; <ide> } <ide> <ide> /** <ide> public function unserialize($data) <ide> <ide> $this->createFromArray($array); <ide> } <add> <add> /** <add> * Magic method used to rebuild the Message object. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->createFromArray($data); <add> } <ide> } <ide><path>src/ORM/ResultSet.php <ide> public function first() <ide> * @return string Serialized object <ide> */ <ide> public function serialize(): string <add> { <add> return serialize($this->__serialize()); <add> } <add> <add> /** <add> * Serializes a resultset. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <ide> { <ide> if (!$this->_useBuffering) { <ide> $msg = 'You cannot serialize an un-buffered ResultSet. ' <ide> public function serialize(): string <ide> } <ide> <ide> if ($this->_results instanceof SplFixedArray) { <del> return serialize($this->_results->toArray()); <add> return $this->_results->toArray(); <ide> } <ide> <del> return serialize($this->_results); <add> return $this->_results; <ide> } <ide> <ide> /** <ide> public function serialize(): string <ide> */ <ide> public function unserialize($serialized) <ide> { <del> $results = (array)(unserialize($serialized) ?: []); <del> $this->_results = SplFixedArray::fromArray($results); <add> $this->__unserialize((array)(unserialize($serialized) ?: [])); <add> } <add> <add> /** <add> * Unserializes a resultset. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->_results = SplFixedArray::fromArray($data); <ide> $this->_useBuffering = true; <ide> $this->_count = $this->_results->count(); <ide> } <ide><path>src/View/ViewBuilder.php <ide> public function serialize(): string <ide> return serialize($array); <ide> } <ide> <add> /** <add> * Magic method used for serializing the view builder object. <add> * <add> * @return array <add> */ <add> public function __serialize(): array <add> { <add> return $this->jsonSerialize(); <add> } <add> <ide> /** <ide> * Unserializes the view builder object. <ide> * <ide> public function unserialize($data): void <ide> { <ide> $this->createFromArray(unserialize($data)); <ide> } <add> <add> /** <add> * Magic method used to rebuild the view builder object. <add> * <add> * @param array $data Data array. <add> * @return void <add> */ <add> public function __unserialize(array $data): void <add> { <add> $this->createFromArray($data); <add> } <ide> } <ide><path>tests/TestCase/Collection/Iterator/BufferedIteratorTest.php <ide> public function testBufferPartial() <ide> } <ide> $this->assertEquals([1, 2, 3], $result); <ide> } <add> <add> /** <add> * Testing serialize and unserialize features. <add> * <add> * @return void <add> */ <add> public function testSerialization() <add> { <add> $items = new ArrayObject([ <add> 'a' => 1, <add> 'b' => 2, <add> 'c' => 3, <add> ]); <add> $expected = (array)$items; <add> <add> $iterator = new BufferedIterator($items); <add> <add> $serialized = serialize($iterator); <add> $outcome = unserialize($serialized); <add> $this->assertEquals($expected, $outcome->toArray()); <add> } <ide> }
9
Ruby
Ruby
remove unecessary require in test_helper
e1f1213c8b59a413b0c2b9581d10dbf36d0be49b
<ide><path>activestorage/test/test_helper.rb <ide> ActiveJob::Base.queue_adapter = :test <ide> ActiveJob::Base.logger = nil <ide> <del>require "active_storage" <del> <ide> # Filter out Minitest backtrace while allowing backtrace from other libraries <ide> # to be shown. <ide> Minitest.backtrace_filter = Minitest::BacktraceFilter.new
1
PHP
PHP
apply fixes from styleci
dc68fb490d6557d33414ce22a5a38ad0ee3e5bda
<ide><path>tests/Database/DatabaseEloquentMorphToTest.php <ide> public function relation() <ide> class EloquentMorphToRelatedStub extends Model <ide> { <ide> public $table = 'eloquent_morph_to_related_stubs'; <del>} <ide>\ No newline at end of file <add>}
1
Ruby
Ruby
add block support to button_tag helper
829de9d98e59f9b083ed96a9031cd9841c83ae47
<ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb <ide> def submit_tag(value = "Save changes", options = {}) <ide> # <tt>reset</tt>button or a generic button which can be used in <ide> # JavaScript, for example. You can use the button tag as a regular <ide> # submit tag but it isn't supported in legacy browsers. However, <del> # button tag allows richer labels such as images and emphasis. <add> # the button tag allows richer labels such as images and emphasis, <add> # so this helper will also accept a block. <ide> # <ide> # ==== Options <ide> # * <tt>:confirm => 'question?'</tt> - If present, the <ide> def submit_tag(value = "Save changes", options = {}) <ide> # button_tag <ide> # # => <button name="button" type="submit">Button</button> <ide> # <del> # button_tag "<strong>Ask me!</strong>", :type => 'button' <add> # button_tag(:type => 'button') do <add> # content_tag(:strong, 'Ask me!') <add> # end <ide> # # => <button name="button" type="button"> <ide> # <strong>Ask me!</strong> <ide> # </button> <ide> def submit_tag(value = "Save changes", options = {}) <ide> # # => <button data-disable-with="Please wait..." name="button" <ide> # type="submit">Checkout</button> <ide> # <del> def button_tag(label = "Button", options = {}) <add> def button_tag(content_or_options = nil, options = nil, &block) <add> options = content_or_options if block_given? && content_or_options.is_a?(Hash) <add> options ||= {} <ide> options.stringify_keys! <ide> <ide> if disable_with = options.delete("disable_with") <ide> def button_tag(label = "Button", options = {}) <ide> <ide> options.reverse_merge! 'name' => 'button', 'type' => 'submit' <ide> <del> content_tag :button, label, { "type" => options.delete("type") }.update(options) <add> content_tag :button, content_or_options || 'Button', options, &block <ide> end <ide> <ide> # Displays an image which when clicked will submit the form. <ide><path>actionpack/test/template/form_tag_helper_test.rb <ide> def test_button_tag_escape_content <ide> ) <ide> end <ide> <add> def test_button_tag_with_block <add> assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' }) <add> end <add> <add> def test_button_tag_with_block_and_options <add> output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') } <add> assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output) <add> end <add> <ide> def test_image_submit_tag_with_confirmation <ide> assert_dom_equal( <ide> %(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
2
Python
Python
upgrade gyp to r1034
ee2c12d48e52c066c74fd646d6a38e880b0bfa0a
<ide><path>tools/gyp/pylib/gyp/MSVSNew.py <ide> def NameThenGuid(a, b): <ide> sln_root = os.path.split(self.path)[0] <ide> for e in all_entries: <ide> relative_path = gyp.common.RelativePath(e.path, sln_root) <add> # msbuild does not accept an empty folder_name. <add> # use '.' in case relative_path is empty. <add> folder_name = relative_path.replace('/', '\\') or '.' <ide> f.write('Project("%s") = "%s", "%s", "%s"\r\n' % ( <ide> e.entry_type_guid, # Entry type GUID <ide> e.name, # Folder name <del> relative_path.replace('/', '\\'), # Folder name (again) <add> folder_name, # Folder name (again) <ide> e.get_guid(), # Entry GUID <ide> )) <ide> <ide><path>tools/gyp/pylib/gyp/generator/dump_dependency_json.py <ide> def CalculateVariables(default_variables, params): <ide> default_variables['OS'] = generator_flags.get('os', 'linux') <ide> <ide> <add>def CalculateGeneratorInputInfo(params): <add> """Calculate the generator specific info that gets fed to input (called by <add> gyp).""" <add> generator_flags = params.get('generator_flags', {}) <add> if generator_flags.get('adjust_static_libraries', False): <add> global generator_wants_static_library_dependencies_adjusted <add> generator_wants_static_library_dependencies_adjusted = True <add> <add> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> # Map of target -> list of targets it depends on. <ide> edges = {} <ide><path>tools/gyp/pylib/gyp/generator/make.py <ide> 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/geni', <ide> 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen', <ide> 'PRODUCT_DIR': '$(builddir)', <del> 'LIB_DIR': '$(obj).$(TOOLSET)', <ide> 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. <ide> 'RULE_INPUT_PATH': '$(abspath $<)', <ide> 'RULE_INPUT_EXT': '$(suffix $<)', <ide> def CalculateVariables(default_variables, params): <ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') <ide> default_variables.setdefault('SHARED_LIB_DIR', <ide> generator_default_variables['PRODUCT_DIR']) <add> default_variables.setdefault('LIB_DIR', <add> generator_default_variables['PRODUCT_DIR']) <ide> <ide> # Copy additional generator configuration data from Xcode, which is shared <ide> # by the Mac Make generator. <ide> def CalculateVariables(default_variables, params): <ide> default_variables.setdefault('OS', 'linux') <ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') <ide> default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') <add> default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)') <ide> <ide> <ide> def CalculateGeneratorInputInfo(params): <ide> def ensure_directory_exists(path): <ide> # <ide> # This will allow make to invoke N linker processes as specified in -jN. <ide> FLOCK ?= %(flock)s $(builddir)/linker.lock <del>LINK ?= $(FLOCK) $(CXX) <ide> <add>%(make_global_settings)s <add> <add>LINK ?= $(FLOCK) $(CXX) <ide> CC.target ?= $(CC) <ide> CFLAGS.target ?= $(CFLAGS) <ide> CXX.target ?= $(CXX) <ide> def GetExecutablePath(self): <ide> else: <ide> return self._GetStandaloneBinaryPath() <ide> <add> def _SdkPath(self): <add> sdk_root = 'macosx10.5' <add> if 'SDKROOT' in self._Settings(): <add> sdk_root = self._Settings()['SDKROOT'] <add> if sdk_root.startswith('macosx'): <add> sdk_root = 'MacOSX' + sdk_root[len('macosx'):] <add> return '/Developer/SDKs/%s.sdk' % sdk_root <add> <ide> def GetCflags(self, configname): <ide> """Returns flags that need to be added to .c, .cc, .m, and .mm <ide> compilations.""" <ide> def GetCflags(self, configname): <ide> self.configname = configname <ide> cflags = [] <ide> <del> sdk_root = 'Mac10.5' <add> sdk_root = self._SdkPath() <ide> if 'SDKROOT' in self._Settings(): <del> sdk_root = self._Settings()['SDKROOT'] <del> cflags.append('-isysroot /Developer/SDKs/%s.sdk' % sdk_root) <del> sdk_root_dir = '/Developer/SDKs/%s.sdk' % sdk_root <add> cflags.append('-isysroot %s' % sdk_root) <ide> <ide> if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'): <ide> cflags.append('-fasm-blocks') <ide> def GetCflags(self, configname): <ide> <ide> self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s') <ide> <del> dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf') <del> if dbg_format == 'none': <del> pass <del> elif dbg_format == 'dwarf': <del> cflags.append('-gdwarf-2') <del> elif dbg_format == 'stabs': <del> raise NotImplementedError('stabs debug format is not supported yet.') <del> elif dbg_format == 'dwarf-with-dsym': <del> # TODO(thakis): this is needed for mac_breakpad chromium builds, but not <del> # for regular chromium builds. <del> # -gdwarf-2 as well, but needs to invoke dsymutil after linking too: <del> # dsymutil build/Default/TestAppGyp.app/Contents/MacOS/TestAppGyp \ <del> # -o build/Default/TestAppGyp.app.dSYM <del> raise NotImplementedError('dsym debug format is not supported yet.') <del> else: <del> raise NotImplementedError('Unknown debug format %s' % dbg_format) <add> if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'): <add> dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf') <add> if dbg_format == 'dwarf': <add> cflags.append('-gdwarf-2') <add> elif dbg_format == 'stabs': <add> raise NotImplementedError('stabs debug format is not supported yet.') <add> elif dbg_format == 'dwarf-with-dsym': <add> # TODO(thakis): this is needed for mac_breakpad chromium builds, but not <add> # for regular chromium builds. <add> # -gdwarf-2 as well, but needs to invoke dsymutil after linking too: <add> # dsymutil build/Default/TestAppGyp.app/Contents/MacOS/TestAppGyp \ <add> # -o build/Default/TestAppGyp.app.dSYM <add> raise NotImplementedError('dsym debug format is not supported yet.') <add> else: <add> raise NotImplementedError('Unknown debug format %s' % dbg_format) <ide> <ide> if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'): <ide> cflags.append('-fvisibility=hidden') <ide> def GetCflags(self, configname): <ide> self._WarnUnimplemented('ARCHS') <ide> self._WarnUnimplemented('COPY_PHASE_STRIP') <ide> self._WarnUnimplemented('DEPLOYMENT_POSTPROCESSING') <add> self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS') <add> self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS') <add> self._WarnUnimplemented('GCC_ENABLE_OBJC_GC') <ide> self._WarnUnimplemented('INFOPLIST_PREPROCESS') <ide> self._WarnUnimplemented('INFOPLIST_PREPROCESSOR_DEFINITIONS') <ide> self._WarnUnimplemented('STRIPFLAGS') <ide> def GetCflags(self, configname): <ide> config = self.spec['configurations'][self.configname] <ide> framework_dirs = config.get('mac_framework_dirs', []) <ide> for directory in framework_dirs: <del> cflags.append('-F ' + os.path.join(sdk_root_dir, directory)) <add> cflags.append('-F ' + os.path.join(sdk_root, directory)) <ide> <ide> self.configname = None <ide> return cflags <ide> def AbsolutifyPrefix(flag, prefix): <ide> ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') <ide> self._Appendf( <ide> ldflags, 'MACOSX_DEPLOYMENT_TARGET', '-mmacosx-version-min=%s') <del> self._Appendf( <del> ldflags, 'SDKROOT', '-isysroot /Developer/SDKs/%s.sdk') <add> if 'SDKROOT' in self._Settings(): <add> ldflags.append('-isysroot ' + self._SdkPath()) <ide> <ide> for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): <ide> ldflags.append('-L' + library_path) <ide> def AbsolutifyPrefix(flag, prefix): <ide> # TODO: Do not hardcode arch. Supporting fat binaries will be annoying. <ide> ldflags.append('-arch i386') <ide> <del> # Xcode adds the product directory by default. It writes static libraries <del> # into the product directory. So add both. <del> ldflags.append('-L' + generator_default_variables['LIB_DIR']) <add> # Xcode adds the product directory by default. <ide> ldflags.append('-L' + generator_default_variables['PRODUCT_DIR']) <ide> <ide> install_name = self.GetPerTargetSetting('LD_DYLIB_INSTALL_NAME') <ide> def AbsolutifyPrefix(flag, prefix): <ide> self.configname = None <ide> return ldflags <ide> <add> def GetPerTargetSettings(self): <add> """Gets a list of all the per-target settings. This will only fetch keys <add> whose values are the same across all configurations.""" <add> first_pass = True <add> result = {} <add> for configname in sorted(self.xcode_settings.keys()): <add> if first_pass: <add> result = dict(self.xcode_settings[configname]) <add> first_pass = False <add> else: <add> for key, value in self.xcode_settings[configname].iteritems(): <add> if key not in result: <add> continue <add> elif result[key] != value: <add> del result[key] <add> return result <add> <ide> def GetPerTargetSetting(self, setting, default=None): <ide> """Tries to get xcode_settings.setting from spec. Assumes that the setting <ide> has the same value in all configurations and throws otherwise.""" <ide> def WriteMacInfoPlist(self, info_plist, bundle_deps, spec): <ide> path = generator_default_variables['PRODUCT_DIR'] <ide> dest_plist = os.path.join(path, self.xcode_settings.GetBundlePlistPath()) <ide> dest_plist = QuoteSpaces(dest_plist) <del> self.WriteXcodeEnv(dest_plist, spec) # plists can contain envvars. <add> extra_settings = self.xcode_settings.GetPerTargetSettings() <add> # plists can contain envvars and substitute them into the file.. <add> self.WriteXcodeEnv(dest_plist, spec, additional_settings=extra_settings) <ide> self.WriteDoCmd([dest_plist], [info_plist], 'mac_tool,,,copy-info-plist', <ide> part_of_all=True) <ide> bundle_deps.append(dest_plist) <ide> def ComputeOutputBasename(self, spec): <ide> return target_prefix + target + target_ext <ide> <ide> <add> def _InstallImmediately(self): <add> return self.toolset == 'target' and self.flavor == 'mac' and self.type in ( <add> 'static_library', 'executable', 'shared_library', 'loadable_module') <add> <add> <ide> def ComputeOutput(self, spec): <ide> """Return the 'output' (full output path) of a gyp spec. <ide> <ide> def ComputeOutput(self, spec): <ide> return '' # Doesn't have any output. <ide> <ide> path = os.path.join('$(obj).' + self.toolset, self.path) <del> if self.type == 'executable': <add> if self.type == 'executable' or self._InstallImmediately(): <ide> path = '$(builddir)' <ide> path = spec.get('product_dir', path) <ide> return os.path.join(path, self.ComputeOutputBasename(spec)) <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> # After the framework is built, package it. Needs to happen before <ide> # postbuilds, since postbuilds depend on this. <ide> if self.type in ('shared_library', 'loadable_module'): <del> self.WriteLn('\t@$(call do_cmd,mac_package_framework,0,0,%s)' % <add> self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % <ide> self.xcode_settings.GetFrameworkVersion()) <ide> <ide> # Bundle postbuilds can depend on the whole bundle, so run them after <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> if postbuilds: <ide> assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' <ide> 'on the bundle, not the binary (target \'%s\')' % self.target) <add> assert 'product_dir' not in spec, ('Postbuilds do not work with ' <add> 'custom product_dir') <ide> self.WriteXcodeEnv(self.output_binary, spec) # For postbuilds <ide> postbuilds = [EscapeShellArgument(p) for p in postbuilds] <ide> self.WriteLn('%s: builddir := $(abs_builddir)' % self.output_binary) <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> file_desc = 'executable' <ide> install_path = self._InstallableTargetInstallPath() <ide> installable_deps = [self.output] <del> if self.is_mac_bundle: <del> # Bundles are created in their install_path location immediately. <add> if self.flavor == 'mac' and not 'product_dir' in spec: <add> # On mac, products are created in install_path immediately. <ide> assert install_path == self.output, '%s != %s' % ( <ide> install_path, self.output) <ide> <ide> def DepsToModules(deps, prefix, suffix): <ide> modules.append(filename[len(prefix):-len(suffix)]) <ide> return modules <ide> <add> # Retrieve the default value of 'SHARED_LIB_SUFFIX' <add> params = {'flavor': 'linux'} <add> default_variables = {} <add> CalculateVariables(default_variables, params) <add> <ide> self.WriteList( <ide> DepsToModules(link_deps, <ide> generator_default_variables['SHARED_LIB_PREFIX'], <del> generator_default_variables['SHARED_LIB_SUFFIX']), <add> default_variables['SHARED_LIB_SUFFIX']), <ide> 'LOCAL_SHARED_LIBRARIES') <ide> self.WriteList( <ide> DepsToModules(link_deps, <ide> def GetXcodeEnv(self, spec, target_relative_path=False): <ide> for a full list.""" <ide> if self.flavor != 'mac': return {} <ide> <add> built_products_dir = generator_default_variables['PRODUCT_DIR'] <ide> def StripProductDir(s): <del> product_dir = generator_default_variables['PRODUCT_DIR'] <del> assert s.startswith(product_dir), s <del> return s[len(product_dir) + 1:] <add> assert s.startswith(built_products_dir), s <add> return s[len(built_products_dir) + 1:] <ide> <ide> product_name = spec.get('product_name', self.output) <ide> <del> # Some postbuilds try to read a build output file at <del> # ""${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}". Static libraries end up <del> # "$(obj).target", so <del> # BUILT_PRODUCTS_DIR is $(builddir) <del> # FULL_PRODUCT_NAME is $(out).target/path/to/lib.a <del> # Since $(obj) contains out/Debug already, the postbuild <del> # would get out/Debug/out/Debug/obj.target/path/to/lib.a. To prevent this, <del> # remove the "out/Debug" prefix from $(obj). <del> if product_name.startswith('$(obj)'): <del> product_name = ( <del> '$(subst $(builddir)/,,$(obj))' + product_name[len('$(obj)'):]) <add> if self._InstallImmediately(): <add> if product_name.startswith(built_products_dir): <add> product_name = StripProductDir(product_name) <ide> <del> built_products_dir = generator_default_variables['PRODUCT_DIR'] <ide> srcroot = self.path <ide> if target_relative_path: <ide> built_products_dir = os.path.relpath(built_products_dir, srcroot) <ide> def StripProductDir(s): <ide> } <ide> if self.type in ('executable', 'shared_library'): <ide> env['EXECUTABLE_NAME'] = os.path.basename(self.output_binary) <del> if self.type in ('executable', 'shared_library', 'loadable_module'): <add> if self.type in ( <add> 'executable', 'static_library', 'shared_library', 'loadable_module'): <ide> env['EXECUTABLE_PATH'] = self.xcode_settings.GetExecutablePath() <ide> if self.is_mac_bundle: <ide> env['CONTENTS_FOLDER_PATH'] = \ <ide> self.xcode_settings.GetBundleContentsFolderPath() <add> env['UNLOCALIZED_RESOURCES_FOLDER_PATH'] = \ <add> self.xcode_settings.GetBundleResourceFolder() <ide> env['INFOPLIST_PATH'] = self.xcode_settings.GetBundlePlistPath() <ide> <ide> # TODO(thakis): Remove this. <ide> def StripProductDir(s): <ide> return env <ide> <ide> <del> def WriteXcodeEnv(self, target, spec, target_relative_path=False): <del> env = self.GetXcodeEnv(spec, target_relative_path) <del> # For <del> # foo := a\ b <del> # the escaped space does the right thing. For <del> # export foo := a\ b <del> # it does not -- the backslash is written to the env as literal character. <del> # Hence, unescape all spaces here. <add> def WriteXcodeEnv(self, <add> target, <add> spec, <add> target_relative_path=False, <add> additional_settings={}): <add> env = additional_settings <add> env.update(self.GetXcodeEnv(spec, target_relative_path)) <add> <add> # Keys whose values will not have $(builddir) replaced with $(abs_builddir). <add> # These have special substitution rules in some cases; see above in <add> # GetXcodeEnv() for the full rationale. <add> keys_to_not_absolutify = ('PRODUCT_NAME', 'FULL_PRODUCT_NAME') <add> <add> # Perform some transformations that are required to mimic Xcode behavior. <ide> for k in env: <add> # Values that are not strings but are, for example, lists or tuples such <add> # as LDFLAGS or CFLAGS, should not be written out because they are <add> # not needed and it's undefined how multi-valued keys should be written. <add> if not isinstance(env[k], str): <add> continue <add> <add> # For <add> # foo := a\ b <add> # the escaped space does the right thing. For <add> # export foo := a\ b <add> # it does not -- the backslash is written to the env as literal character. <add> # Hence, unescape all spaces here. <ide> v = env[k].replace(r'\ ', ' ') <add> <add> # Xcode works purely with absolute paths. When writing env variables to <add> # mimic its usage, replace $(builddir) with $(abs_builddir). <add> if k not in keys_to_not_absolutify: <add> v = v.replace('$(builddir)', '$(abs_builddir)') <add> <ide> self.WriteLn('%s: export %s := %s' % (target, k, v)) <ide> <ide> <ide> def CalculateMakefilePath(build_file, base_name): <ide> }) <ide> header_params.update(RunSystemTests(flavor)) <ide> <add> build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) <add> make_global_settings_dict = data[build_file].get('make_global_settings', {}) <add> make_global_settings = '' <add> for key, value in make_global_settings_dict: <add> if value[0] != '$': <add> value = '$(abspath %s)' % value <add> if key == 'LINK': <add> make_global_settings += '%s ?= $(FLOCK) %s\n' % (key, value) <add> elif key in ['CC', 'CXX']: <add> make_global_settings += ( <add> 'ifneq (,$(filter $(origin %s), undefined default))\n' % key) <add> # Let gyp-time envvars win over global settings. <add> if key in os.environ: <add> value = os.environ[key] <add> make_global_settings += ' %s = %s\n' % (key, value) <add> make_global_settings += 'endif\n' <add> else: <add> make_global_settings += '%s ?= %s\n' % (key, value) <add> header_params['make_global_settings'] = make_global_settings <add> <ide> ensure_directory_exists(makefile_path) <ide> root_makefile = open(makefile_path, 'w') <ide> root_makefile.write(SHARED_HEADER % header_params) <ide> def CalculateMakefilePath(build_file, base_name): <ide> for qualified_target in target_list: <ide> build_file, target, toolset = gyp.common.ParseQualifiedTarget( <ide> qualified_target) <add> <add> this_make_global_settings = data[build_file].get('make_global_settings', {}) <add> assert make_global_settings_dict == this_make_global_settings, ( <add> "make_global_settings needs to be the same for all targets.") <add> <ide> build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) <ide> included_files = data[build_file]['included_files'] <ide> for included_file in included_files: <ide><path>tools/gyp/pylib/gyp/generator/msvs.py <ide> # of the warnings. <ide> <ide> # TODO(jeanluc) I had: 'LIB_DIR': '$(OutDir)lib', <del> #'LIB_DIR': '$(OutDir)/lib', <add> 'LIB_DIR': '$(OutDir)/lib', <ide> 'RULE_INPUT_ROOT': '$(InputName)', <ide> 'RULE_INPUT_EXT': '$(InputExt)', <ide> 'RULE_INPUT_NAME': '$(InputFileName)', <ide> def _GenerateExternalRules(rules, output_dir, spec, <ide> 'IntDir=$(IntDir)', <ide> '-j', '${NUMBER_OF_PROCESSORS_PLUS_1}', <ide> '-f', filename] <del> <del> # Currently this weird argument munging is used to duplicate the way a <del> # python script would need to be run as part of the chrome tree. <del> # Eventually we should add some sort of rule_default option to set this <del> # per project. For now the behavior chrome needs is the default. <del> mcs = rule.get('msvs_cygwin_shell') <del> if mcs is None: <del> mcs = int(spec.get('msvs_cygwin_shell', 1)) <del> elif isinstance(mcs, str): <del> mcs = int(mcs) <del> quote_cmd = int(rule.get('msvs_quote_cmd', 1)) <del> cmd = _BuildCommandLineForRuleRaw(spec, cmd, mcs, False, quote_cmd) <add> cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True) <ide> # Insert makefile as 0'th input, so it gets the action attached there, <ide> # as this is easier to understand from in the IDE. <ide> all_inputs = list(all_inputs) <ide> def _GetOutputFilePathAndTool(spec): <ide> # TODO(jeanluc) If we want to avoid the MSB8012 warnings in <ide> # VisualStudio 2010, we will have to change the value of $(OutDir) <ide> # to contain the \lib suffix, rather than doing it as below. <del> 'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)\\', '.lib'), <add> 'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)\\lib\\', '.lib'), <ide> 'dummy_executable': ('VCLinkerTool', 'Link', '$(IntDir)\\', '.junk'), <ide> } <ide> output_file_props = output_file_map.get(spec['type']) <ide> def _GetMSBuildSources(spec, sources, exclusions, extension_to_rule_name, <ide> <ide> def _AddSources2(spec, sources, exclusions, grouped_sources, <ide> extension_to_rule_name, sources_handled_by_action): <add> extensions_excluded_from_precompile = [] <ide> for source in sources: <ide> if isinstance(source, MSVSProject.Filter): <ide> _AddSources2(spec, source.contents, exclusions, grouped_sources, <ide> def _AddSources2(spec, sources, exclusions, grouped_sources, <ide> for config_name, configuration in spec['configurations'].iteritems(): <ide> precompiled_source = configuration.get('msvs_precompiled_source', '') <ide> precompiled_source = _FixPath(precompiled_source) <add> if not extensions_excluded_from_precompile: <add> # If the precompiled header is generated by a C source, we must <add> # not try to use it for C++ sources, and vice versa. <add> basename, extension = os.path.splitext(precompiled_source) <add> if extension == '.c': <add> extensions_excluded_from_precompile = ['.cc', '.cpp', '.cxx'] <add> else: <add> extensions_excluded_from_precompile = ['.c'] <add> <ide> if precompiled_source == source: <ide> condition = _GetConfigurationCondition(config_name, configuration) <ide> detail.append(['PrecompiledHeader', <ide> {'Condition': condition}, <ide> 'Create' <ide> ]) <add> else: <add> # Turn off precompiled header usage for source files of a <add> # different type than the file that generated the <add> # precompiled header. <add> for extension in extensions_excluded_from_precompile: <add> if source.endswith(extension): <add> detail.append(['PrecompiledHeader', '']) <add> detail.append(['ForcedIncludeFiles', '']) <add> <ide> group, element = _MapFileToMsBuildSourceType(source, <ide> extension_to_rule_name) <ide> grouped_sources[group].append([element, {'Include': source}] + detail) <ide><path>tools/gyp/pylib/gyp/generator/ninja.py <ide> 'STATIC_LIB_SUFFIX': '.a', <ide> 'SHARED_LIB_PREFIX': 'lib', <ide> 'SHARED_LIB_SUFFIX': '.so', <del> # TODO: intermediate dir should *not* be shared between different targets. <del> # Unfortunately, whatever we provide here gets written into many different <del> # places within the gyp spec so it's difficult to make it target-specific. <del> # Apparently we've made it this far with one global path for the make build <del> # we're safe for now. <del> 'INTERMEDIATE_DIR': '$b/geni', <del> 'SHARED_INTERMEDIATE_DIR': '$b/gen', <del> 'PRODUCT_DIR': '$b', <del> 'SHARED_LIB_DIR': '$b/lib', <del> 'LIB_DIR': '$b', <add> <add> # Gyp expects the following variables to be expandable by the build <add> # system to the appropriate locations. Ninja prefers paths to be <add> # known at compile time. To resolve this, introduce special <add> # variables starting with $! (which begin with a $ so gyp knows it <add> # should be treated as a path, but is otherwise an invalid <add> # ninja/shell variable) that are passed to gyp here but expanded <add> # before writing out into the target .ninja files; see <add> # ExpandSpecial. <add> 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', <add> 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', <add> 'PRODUCT_DIR': '$!PRODUCT_DIR', <add> 'SHARED_LIB_DIR': '$!PRODUCT_DIR/lib', <add> 'LIB_DIR': '', <ide> <ide> # Special variables that may be used by gyp 'rule' targets. <ide> # We generate definitions for these variables on the fly when processing a <ide> 'RULE_INPUT_NAME': '$name', <ide> } <ide> <del>NINJA_BASE = """\ <del>builddir = %(builddir)s <del># Short alias for builddir. <del>b = %(builddir)s <del> <del>cc = %(cc)s <del>cxx = %(cxx)s <del> <del>rule cc <del> depfile = $out.d <del> description = CC $out <del> command = $cc -MMD -MF $out.d $defines $includes $cflags $cflags_c $ <del> -c $in -o $out <del> <del>rule cxx <del> depfile = $out.d <del> description = CXX $out <del> command = $cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc $ <del> -c $in -o $out <del> <del>rule alink <del> description = AR $out <del> command = rm -f $out && ar rcsT $out $in <del> <del>rule solink <del> description = SOLINK $out <del> command = g++ -Wl,--threads -Wl,--thread-count=4 $ <del> -shared $ldflags -o $out -Wl,-soname=$soname $ <del> -Wl,--whole-archive $in -Wl,--no-whole-archive $libs <del> <del>rule link <del> description = LINK $out <del> command = g++ -Wl,--threads -Wl,--thread-count=4 $ <del> $ldflags -o $out -Wl,-rpath=\$$ORIGIN/lib $ <del> -Wl,--start-group $in -Wl,--end-group $libs <del> <del>rule stamp <del> description = STAMP $out <del> command = touch $out <del> <del>rule copy <del> description = COPY $in $out <del> command = ln -f $in $out 2>/dev/null || cp -af $in $out <del> <del>""" <add># TODO: enable cross compiling once we figure out: <add># - how to not build extra host objects in the non-cross-compile case. <add># - how to decide what the host compiler is (should not just be $cc). <add># - need ld_host as well. <add>generator_supports_multiple_toolsets = False <ide> <ide> <ide> def StripPrefix(arg, prefix): <ide> def MaybeQuoteShellArgument(arg): <ide> return arg <ide> <ide> <add>def InvertRelativePath(path): <add> """Given a relative path like foo/bar, return the inverse relative path: <add> the path from the relative path back to the origin dir. <add> <add> E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) <add> should always produce the empty string.""" <add> <add> if not path: <add> return path <add> # Only need to handle relative paths into subdirectories for now. <add> assert '..' not in path, path <add> depth = len(path.split('/')) <add> return '/'.join(['..'] * depth) <add> <add> <ide> # A small discourse on paths as used within the Ninja build: <add># All files we produce (both at gyp and at build time) appear in the <add># build directory (e.g. out/Debug). <ide> # <ide> # Paths within a given .gyp file are always relative to the directory <ide> # containing the .gyp file. Call these "gyp paths". This includes <ide> # sources as well as the starting directory a given gyp rule/action <del># expects to be run from. We call this directory "base_dir" within <del># the per-.gyp-file NinjaWriter code. <add># expects to be run from. We call the path from the source root to <add># the gyp file the "base directory" within the per-.gyp-file <add># NinjaWriter code. <ide> # <del># All paths as written into the .ninja files are relative to the root <del># of the tree. Call these paths "ninja paths". We set up the ninja <del># variable "$b" to be the path to the root of the build output, <del># e.g. out/Debug/. All files we produce (both at gyp and at build <del># time) appear in that output directory. <add># All paths as written into the .ninja files are relative to the build <add># directory. Call these paths "ninja paths". <ide> # <ide> # We translate between these two notions of paths with two helper <ide> # functions: <ide> def MaybeQuoteShellArgument(arg): <ide> # to the input file name as well as the output target name. <ide> <ide> class NinjaWriter: <del> def __init__(self, target_outputs, base_dir, output_file): <add> def __init__(self, target_outputs, base_dir, build_dir, output_file): <add> """ <add> base_dir: path from source root to directory containing this gyp file, <add> by gyp semantics, all input paths are relative to this <add> build_dir: path from source root to build output <add> """ <add> <ide> self.target_outputs = target_outputs <del> # The root-relative path to the source .gyp file; by gyp <del> # semantics, all input paths are relative to this. <ide> self.base_dir = base_dir <add> self.build_dir = build_dir <ide> self.ninja = ninja_syntax.Writer(output_file) <ide> <add> # Relative path from build output dir to base dir. <add> self.build_to_base = os.path.join(InvertRelativePath(build_dir), base_dir) <add> # Relative path from base dir to build dir. <add> self.base_to_build = os.path.join(InvertRelativePath(base_dir), build_dir) <add> <add> def ExpandSpecial(self, path, product_dir=None): <add> """Expand specials like $!PRODUCT_DIR in |path|. <add> <add> If |product_dir| is None, assumes the cwd is already the product <add> dir. Otherwise, |product_dir| is the relative path to the product <add> dir. <add> """ <add> <add> PRODUCT_DIR = '$!PRODUCT_DIR' <add> if PRODUCT_DIR in path: <add> if product_dir: <add> path = path.replace(PRODUCT_DIR, product_dir) <add> else: <add> path = path.replace(PRODUCT_DIR + '/', '') <add> path = path.replace(PRODUCT_DIR, '.') <add> <add> INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' <add> if INTERMEDIATE_DIR in path: <add> int_dir = self.GypPathToUniqueOutput('gen') <add> # GypPathToUniqueOutput generates a path relative to the product dir, <add> # so insert product_dir in front if it is provided. <add> path = path.replace(INTERMEDIATE_DIR, <add> os.path.join(product_dir or '', int_dir)) <add> <add> return path <add> <ide> def GypPathToNinja(self, path): <ide> """Translate a gyp path to a ninja path. <ide> <ide> See the above discourse on path conversions.""" <del> if path.startswith('$'): <del> # If the path contains a reference to a ninja variable, we know <del> # it's already relative to the source root. <del> return path <del> return os.path.normpath(os.path.join(self.base_dir, path)) <add> if path.startswith('$!'): <add> return self.ExpandSpecial(path) <add> assert '$' not in path, path <add> return os.path.normpath(os.path.join(self.build_to_base, path)) <ide> <del> def GypPathToUniqueOutput(self, path, qualified=False): <add> def GypPathToUniqueOutput(self, path, qualified=True): <ide> """Translate a gyp path to a ninja path for writing output. <ide> <ide> If qualified is True, qualify the resulting filename with the name <ide> def GypPathToUniqueOutput(self, path, qualified=False): <ide> <ide> See the above discourse on path conversions.""" <ide> <del> # It may seem strange to discard components of the path, but we are just <del> # attempting to produce a known-unique output filename; we don't want to <del> # reuse any global directory. <del> genvars = generator_default_variables <del> assert not genvars['SHARED_INTERMEDIATE_DIR'].startswith( <del> genvars['INTERMEDIATE_DIR']) <del> path = StripPrefix(path, genvars['INTERMEDIATE_DIR']) <del> path = StripPrefix(path, genvars['SHARED_INTERMEDIATE_DIR']) <del> path = StripPrefix(path, '/') <del> assert not path.startswith('$') <add> path = self.ExpandSpecial(path) <add> assert not path.startswith('$'), path <ide> <ide> # Translate the path following this scheme: <ide> # Input: foo/bar.gyp, target targ, references baz/out.o <del> # Output: $b/obj/foo/baz/targ.out.o (if qualified) <del> # $b/obj/foo/baz/out.o (otherwise) <add> # Output: obj/foo/baz/targ.out.o (if qualified) <add> # obj/foo/baz/out.o (otherwise) <add> # (and obj.host instead of obj for cross-compiles) <ide> # <ide> # Why this scheme and not some other one? <ide> # 1) for a given input, you can compute all derived outputs by matching <ide> # its path, even if the input is brought via a gyp file with '..'. <ide> # 2) simple files like libraries and stamps have a simple filename. <add> <add> obj = 'obj' <add> if self.toolset != 'target': <add> obj += '.' + self.toolset <add> <ide> path_dir, path_basename = os.path.split(path) <ide> if qualified: <ide> path_basename = self.name + '.' + path_basename <del> return os.path.normpath(os.path.join('$b/obj', self.base_dir, path_dir, <add> return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, <ide> path_basename)) <ide> <ide> def StampPath(self, name): <ide> """Return a path for a stamp file with a particular name. <ide> <ide> Stamp files are used to collapse a dependency on a bunch of files <ide> into a single file.""" <del> return self.GypPathToUniqueOutput(name + '.stamp', qualified=True) <add> return self.GypPathToUniqueOutput(name + '.stamp') <ide> <ide> def WriteSpec(self, spec, config): <ide> """The main entry point for NinjaWriter: write the build rules for a spec. <ide> def WriteSpec(self, spec, config): <ide> return None <ide> <ide> self.name = spec['target_name'] <add> self.toolset = spec['toolset'] <ide> <ide> # Compute predepends for all rules. <ide> # prebuild is the dependencies this target depends on before <ide> def WriteSpec(self, spec, config): <ide> link_deps = self.WriteSources(config, sources, <ide> sources_predepends or prebuild) <ide> # Some actions/rules output 'sources' that are already object files. <del> link_deps += [f for f in sources if f.endswith('.o')] <add> link_deps += [self.GypPathToNinja(f) for f in sources if f.endswith('.o')] <ide> <ide> # The final output of our target depends on the last output of the <ide> # above steps. <add> output = None <ide> final_deps = link_deps or sources_predepends or prebuild <ide> if final_deps: <del> return self.WriteTarget(spec, config, final_deps) <add> output = self.WriteTarget(spec, config, final_deps) <add> if self.name != output and self.toolset == 'target': <add> # Write a short name to build this target. This benefits both the <add> # "build chrome" case as well as the gyp tests, which expect to be <add> # able to run actions and build libraries by their short name. <add> self.ninja.build(self.name, 'phony', output) <add> return output <ide> <ide> def WriteActionsRulesCopies(self, spec, extra_sources, prebuild): <ide> """Write out the Actions, Rules, and Copies steps. Return any outputs <ide> def WriteActionsRulesCopies(self, spec, extra_sources, prebuild): <ide> <ide> return outputs <ide> <add> def GenerateDescription(self, verb, message, fallback): <add> """Generate and return a description of a build step. <add> <add> |verb| is the short summary, e.g. ACTION or RULE. <add> |message| is a hand-written description, or None if not available. <add> |fallback| is the gyp-level name of the step, usable as a fallback. <add> """ <add> if self.toolset != 'target': <add> verb += '(%s)' % self.toolset <add> if message: <add> return '%s %s' % (verb, self.ExpandSpecial(message)) <add> else: <add> return '%s %s: %s' % (verb, self.name, fallback) <add> <ide> def WriteActions(self, actions, extra_sources, prebuild): <ide> all_outputs = [] <ide> for action in actions: <ide> # First write out a rule for the action. <ide> name = action['action_name'] <del> if 'message' in action: <del> description = 'ACTION ' + action['message'] <del> else: <del> description = 'ACTION %s: %s' % (self.name, action['action_name']) <add> description = self.GenerateDescription('ACTION', <add> action.get('message', None), <add> name) <ide> rule_name = self.WriteNewNinjaRule(name, action['action'], description) <ide> <ide> inputs = [self.GypPathToNinja(i) for i in action['inputs']] <ide> def WriteRules(self, rules, extra_sources, prebuild): <ide> # First write out a rule for the rule action. <ide> name = rule['rule_name'] <ide> args = rule['action'] <del> if 'message' in rule: <del> description = 'RULE ' + rule['message'] <del> else: <del> description = 'RULE %s: %s $source' % (self.name, name) <add> description = self.GenerateDescription('RULE', <add> rule.get('message', None), <add> '%s $source' % name) <ide> rule_name = self.WriteNewNinjaRule(name, args, description) <ide> <ide> # TODO: if the command references the outputs directly, we should <ide> def WriteRules(self, rules, extra_sources, prebuild): <ide> for source in rule.get('rule_sources', []): <ide> basename = os.path.basename(source) <ide> root, ext = os.path.splitext(basename) <del> source = self.GypPathToNinja(source) <ide> <add> # Gather the list of outputs, expanding $vars if possible. <ide> outputs = [] <ide> for output in rule['outputs']: <ide> outputs.append(output.replace('$root', root)) <ide> <add> if int(rule.get('process_outputs_as_sources', False)): <add> extra_sources += outputs <add> <ide> extra_bindings = [] <ide> for var in needed_variables: <ide> if var == 'root': <ide> extra_bindings.append(('root', root)) <ide> elif var == 'source': <del> extra_bindings.append(('source', source)) <add> # '$source' is a parameter to the rule action, which means <add> # it shouldn't be converted to a Ninja path. But we don't <add> # want $!PRODUCT_DIR in there either. <add> source_expanded = self.ExpandSpecial(source, self.base_to_build) <add> extra_bindings.append(('source', source_expanded)) <ide> elif var == 'ext': <ide> extra_bindings.append(('ext', ext)) <ide> elif var == 'name': <ide> def WriteRules(self, rules, extra_sources, prebuild): <ide> assert var == None, repr(var) <ide> <ide> inputs = map(self.GypPathToNinja, rule.get('inputs', [])) <del> self.ninja.build(outputs, rule_name, source, <add> outputs = map(self.GypPathToNinja, outputs) <add> self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), <ide> implicit=inputs, <ide> order_only=prebuild, <ide> variables=extra_bindings) <ide> <del> if int(rule.get('process_outputs_as_sources', False)): <del> extra_sources += outputs <del> <ide> all_outputs.extend(outputs) <ide> <ide> return all_outputs <ide> def WriteCopies(self, copies, prebuild): <ide> <ide> def WriteSources(self, config, sources, predepends): <ide> """Write build rules to compile all of |sources|.""" <add> if self.toolset == 'host': <add> self.ninja.variable('cc', '$cc_host') <add> self.ninja.variable('cxx', '$cxx_host') <add> <ide> self.WriteVariableList('defines', <ide> ['-D' + MaybeQuoteShellArgument(ninja_syntax.escape(d)) <ide> for d in config.get('defines', [])]) <ide> def WriteSources(self, config, sources, predepends): <ide> # TODO: should we assert here on unexpected extensions? <ide> continue <ide> input = self.GypPathToNinja(source) <del> output = self.GypPathToUniqueOutput(filename + '.o', qualified=True) <add> output = self.GypPathToUniqueOutput(filename + '.o') <ide> self.ninja.build(output, command, input, <ide> order_only=predepends) <ide> outputs.append(output) <ide> self.ninja.newline() <ide> return outputs <ide> <ide> def WriteTarget(self, spec, config, final_deps): <add> if spec['type'] == 'none': <add> # This target doesn't have any explicit final output, but is instead <add> # used for its effects before the final output (e.g. copies steps). <add> # Reuse the existing output if it's easy. <add> if len(final_deps) == 1: <add> return final_deps[0] <add> # Otherwise, fall through to writing out a stamp file. <add> <ide> output = self.ComputeOutput(spec) <ide> <ide> output_uses_linker = spec['type'] in ('executable', 'loadable_module', <ide> def WriteTarget(self, spec, config, final_deps): <ide> else: <ide> # TODO: Chrome-specific HACK. Chrome runs this lastchange rule on <ide> # every build, but we don't want to rebuild when it runs. <del> if 'lastchange.stamp' not in input: <add> if 'lastchange' not in input: <ide> implicit_deps.add(input) <ide> final_deps.extend(list(extra_deps)) <ide> command_map = { <ide> def WriteTarget(self, spec, config, final_deps): <ide> <ide> if output_uses_linker: <ide> self.WriteVariableList('ldflags', <del> gyp.common.uniquer(config.get('ldflags', []))) <add> gyp.common.uniquer(map(self.ExpandSpecial, <add> config.get('ldflags', [])))) <ide> self.WriteVariableList('libs', <del> gyp.common.uniquer(spec.get('libraries', []))) <add> gyp.common.uniquer(map(self.ExpandSpecial, <add> spec.get('libraries', [])))) <ide> <ide> extra_bindings = [] <ide> if command == 'solink': <ide> def WriteTarget(self, spec, config, final_deps): <ide> implicit=list(implicit_deps), <ide> variables=extra_bindings) <ide> <del> # Write a short name to build this target. This benefits both the <del> # "build chrome" case as well as the gyp tests, which expect to be <del> # able to run actions and build libraries by their short name. <del> self.ninja.build(self.name, 'phony', output) <del> <ide> return output <ide> <ide> def ComputeOutputFileName(self, spec): <ide> def ComputeOutput(self, spec): <ide> <ide> if 'product_dir' in spec: <ide> path = os.path.join(spec['product_dir'], filename) <del> return path <add> return self.ExpandSpecial(path) <ide> <ide> # Executables and loadable modules go into the output root, <ide> # libraries go into shared library dir, and everything else <ide> # goes into the normal place. <ide> if spec['type'] in ('executable', 'loadable_module'): <del> return os.path.join('$b', filename) <add> return filename <ide> elif spec['type'] == 'shared_library': <del> return os.path.join('$b/lib', filename) <add> libdir = 'lib' <add> if self.toolset != 'target': <add> libdir = 'lib/%s' % self.toolset <add> return os.path.join(libdir, filename) <ide> else: <del> return self.GypPathToUniqueOutput(filename) <add> return self.GypPathToUniqueOutput(filename, qualified=False) <ide> <ide> def WriteVariableList(self, var, values): <ide> if values is None: <ide> def WriteNewNinjaRule(self, name, args, description): <ide> # TODO: we shouldn't need to qualify names; we do it because <ide> # currently the ninja rule namespace is global, but it really <ide> # should be scoped to the subninja. <del> rule_name = ('%s.%s' % (self.name, name)).replace(' ', '_') <add> rule_name = self.name <add> if self.toolset == 'target': <add> rule_name += '.' + self.toolset <add> rule_name += '.' + name <add> rule_name = rule_name.replace(' ', '_') <ide> <del> cd = '' <ide> args = args[:] <del> if self.base_dir: <del> # gyp dictates that commands are run from the base directory. <del> # cd into the directory before running, and adjust all paths in <del> # the arguments point to the proper locations. <del> cd = 'cd %s; ' % self.base_dir <del> cdup = '../' * len(self.base_dir.split('/')) <del> for i, arg in enumerate(args): <del> arg = arg.replace('$b', cdup + '$b') <del> arg = arg.replace('$source', cdup + '$source') <del> args[i] = arg <add> <add> # gyp dictates that commands are run from the base directory. <add> # cd into the directory before running, and adjust paths in <add> # the arguments to point to the proper locations. <add> cd = 'cd %s; ' % self.build_to_base <add> args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] <ide> <ide> command = cd + gyp.common.EncodePOSIXShellList(args) <ide> self.ninja.rule(rule_name, command, description) <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> # e.g. "out/Debug" <ide> builddir = os.path.join(generator_flags.get('output_dir', 'out'), config_name) <ide> <del> master_ninja = OpenOutput(os.path.join(options.toplevel_dir, builddir, <del> 'build.ninja')) <del> master_ninja.write(NINJA_BASE % { <del> 'builddir': builddir, <del> 'cc': os.environ.get('CC', 'gcc'), <del> 'cxx': os.environ.get('CXX', 'g++'), <del> }) <add> master_ninja = ninja_syntax.Writer( <add> OpenOutput(os.path.join(options.toplevel_dir, builddir, 'build.ninja')), <add> width=120) <add> <add> # TODO: compute cc/cxx/ld/etc. by command-line arguments and system tests. <add> master_ninja.variable('cc', os.environ.get('CC', 'gcc')) <add> master_ninja.variable('cxx', os.environ.get('CXX', 'g++')) <add> master_ninja.variable('ld', '$cxx -Wl,--threads -Wl,--thread-count=4') <add> master_ninja.variable('cc_host', '$cc') <add> master_ninja.variable('cxx_host', '$cxx') <add> master_ninja.newline() <add> <add> master_ninja.rule( <add> 'cc', <add> description='CC $out', <add> command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' <add> '-c $in -o $out'), <add> depfile='$out.d') <add> master_ninja.rule( <add> 'cxx', <add> description='CXX $out', <add> command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' <add> '-c $in -o $out'), <add> depfile='$out.d') <add> master_ninja.rule( <add> 'alink', <add> description='AR $out', <add> command='rm -f $out && ar rcsT $out $in') <add> master_ninja.rule( <add> 'solink', <add> description='SOLINK $out', <add> command=('$ld -shared $ldflags -o $out -Wl,-soname=$soname ' <add> '-Wl,--whole-archive $in -Wl,--no-whole-archive $libs')) <add> master_ninja.rule( <add> 'link', <add> description='LINK $out', <add> command=('$ld $ldflags -o $out -Wl,-rpath=\$$ORIGIN/lib ' <add> '-Wl,--start-group $in -Wl,--end-group $libs')) <add> master_ninja.rule( <add> 'stamp', <add> description='STAMP $out', <add> command='touch $out') <add> master_ninja.rule( <add> 'copy', <add> description='COPY $in $out', <add> command='ln -f $in $out 2>/dev/null || cp -af $in $out') <add> master_ninja.newline() <ide> <ide> all_targets = set() <ide> for build_file in params['build_files']: <ide> for target in gyp.common.AllTargets(target_list, target_dicts, build_file): <ide> all_targets.add(target) <ide> all_outputs = set() <ide> <del> subninjas = set() <ide> target_outputs = {} <ide> for qualified_target in target_list: <ide> # qualified_target is like: third_party/icu/icu.gyp:icui18n#target <del> build_file, target, _ = gyp.common.ParseQualifiedTarget(qualified_target) <add> build_file, name, toolset = \ <add> gyp.common.ParseQualifiedTarget(qualified_target) <ide> <ide> # TODO: what is options.depth and how is it different than <ide> # options.toplevel_dir? <ide> build_file = gyp.common.RelativePath(build_file, options.depth) <ide> <ide> base_path = os.path.dirname(build_file) <del> output_file = os.path.join(builddir, 'obj', base_path, target + '.ninja') <add> obj = 'obj' <add> if toolset != 'target': <add> obj += '.' + toolset <add> output_file = os.path.join(obj, base_path, name + '.ninja') <ide> spec = target_dicts[qualified_target] <ide> config = spec['configurations'][config_name] <ide> <del> writer = NinjaWriter(target_outputs, base_path, <add> writer = NinjaWriter(target_outputs, base_path, builddir, <ide> OpenOutput(os.path.join(options.toplevel_dir, <add> builddir, <ide> output_file))) <del> subninjas.add(output_file) <add> master_ninja.subninja(output_file) <ide> <ide> output = writer.WriteSpec(spec, config) <ide> if output: <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> if qualified_target in all_targets: <ide> all_outputs.add(output) <ide> <del> for ninja in subninjas: <del> print >>master_ninja, 'subninja', ninja <del> <ide> if all_outputs: <del> print >>master_ninja, 'build all: phony ||' + ' '.join(all_outputs) <del> <del> master_ninja.close() <add> master_ninja.build('all', 'phony', list(all_outputs)) <ide><path>tools/gyp/pylib/gyp/input.py <ide> def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, <ide> target_dict['dependencies_original'] = target_dict.get( <ide> 'dependencies', [])[:] <ide> <add> # A static library should not depend on another static library unless <add> # the dependency relationship is "hard," which should only be done when <add> # a dependent relies on some side effect other than just the build <add> # product, like a rule or action output. Further, if a target has a <add> # non-hard dependency, but that dependency exports a hard dependency, <add> # the non-hard dependency can safely be removed, but the exported hard <add> # dependency must be added to the target to keep the same dependency <add> # ordering. <add> dependencies = \ <add> dependency_nodes[target].DirectAndImportedDependencies(targets) <ide> index = 0 <del> while index < len(target_dict['dependencies']): <del> dependency = target_dict['dependencies'][index] <add> while index < len(dependencies): <add> dependency = dependencies[index] <ide> dependency_dict = targets[dependency] <del> if dependency_dict['type'] == 'static_library' and \ <del> (not 'hard_dependency' in dependency_dict or \ <del> not dependency_dict['hard_dependency']): <del> # A static library should not depend on another static library unless <del> # the dependency relationship is "hard," which should only be done <del> # when a dependent relies on some side effect other than just the <del> # build product, like a rule or action output. Take the dependency <del> # out of the list, and don't increment index because the next <del> # dependency to analyze will shift into the index formerly occupied <del> # by the one being removed. <del> del target_dict['dependencies'][index] <add> <add> # Remove every non-hard static library dependency and remove every <add> # non-static library dependency that isn't a direct dependency. <add> if (dependency_dict['type'] == 'static_library' and \ <add> not dependency_dict.get('hard_dependency', False)) or \ <add> (dependency_dict['type'] != 'static_library' and \ <add> not dependency in target_dict['dependencies']): <add> # Take the dependency out of the list, and don't increment index <add> # because the next dependency to analyze will shift into the index <add> # formerly occupied by the one being removed. <add> del dependencies[index] <ide> else: <ide> index = index + 1 <ide> <del> # If the dependencies list is empty, it's not needed, so unhook it. <del> if len(target_dict['dependencies']) == 0: <add> # Update the dependencies. If the dependencies list is empty, it's not <add> # needed, so unhook it. <add> if len(dependencies) > 0: <add> target_dict['dependencies'] = dependencies <add> else: <ide> del target_dict['dependencies'] <ide> <ide> elif target_type in linkable_types: <ide><path>tools/gyp/pylib/gyp/ninja_syntax.py <ide> def build(self, outputs, rule, inputs=None, implicit=None, order_only=None, <ide> <ide> return outputs <ide> <add> def include(self, path): <add> self._line('include %s' % path) <add> <add> def subninja(self, path): <add> self._line('subninja %s' % path) <add> <ide> def _line(self, text, indent=0): <ide> """Write 'text' word-wrapped at self.width characters.""" <ide> leading_space = ' ' * indent
7
PHP
PHP
support universal routes
395236d6433597ca414e710a6900156e7119779b
<ide><path>laravel/routing/router.php <ide> class Router { <ide> '/(:any?)' => '(?:/([a-zA-Z0-9\.\-_%]+)', <ide> ); <ide> <add> /** <add> * An array of HTTP request methods. <add> * <add> * @var array <add> */ <add> public static $methods = array('GET', 'POST', 'PUT', 'DELETE'); <add> <ide> /** <ide> * Register a route with the router. <ide> * <ide> class Router { <ide> * </code> <ide> * <ide> * @param string|array $route <del> * @param string $action <add> * @param mixed $action <ide> * @return void <ide> */ <ide> public static function register($route, $action) <ide> { <ide> foreach ((array) $route as $uri) <ide> { <add> if (starts_with($uri, '*')) <add> { <add> static::universal(substr($uri, 2), $action); <add> <add> continue; <add> } <add> <ide> // If the action is a string, it is a pointer to a controller, so we <ide> // need to add it to the action array as a "uses" clause, which will <ide> // indicate to the route to call the controller when the route is <ide> public static function register($route, $action) <ide> } <ide> } <ide> <add> /** <add> * Register a route for all HTTP verbs. <add> * <add> * @param string $route <add> * @param mixed $action <add> * @return void <add> */ <add> protected static function universal($route, $action) <add> { <add> $count = count(static::$methods); <add> <add> $routes = array_fill(0, $count, $route); <add> <add> // When registering a universal route, we'll iterate through all of the <add> // verbs supported by the router and prepend each one of the URIs with <add> // one of the request verbs, then we'll register the routes. <add> for ($i = 0; $i < $count; $i++) <add> { <add> $routes[$i] = static::$methods[$i].' '.$routes[$i]; <add> } <add> <add> static::register($routes, $action); <add> } <add> <ide> /** <ide> * Find a route by the route's assigned name. <ide> *
1
Ruby
Ruby
move sandbox check to extend/os
9c2293a08e00e8c417df7a173b0aa13322352a59
<ide><path>Library/Homebrew/extend/os/mac/sandbox.rb <add># typed: strict <add># frozen_string_literal: true <add> <add>class Sandbox <add> sig { returns(T::Boolean) } <add> def self.available? <add> File.executable?(SANDBOX_EXEC) <add> end <add>end <ide><path>Library/Homebrew/extend/os/sandbox.rb <add># typed: strict <add># frozen_string_literal: true <add> <add>require "extend/os/mac/sandbox" if OS.mac? <ide><path>Library/Homebrew/sandbox.rb <ide> class Sandbox <ide> <ide> sig { returns(T::Boolean) } <ide> def self.available? <del> OS.mac? && File.executable?(SANDBOX_EXEC) <add> false <ide> end <ide> <ide> sig { void } <ide> def dump <ide> end <ide> private_constant :SandboxProfile <ide> end <add> <add>require "extend/os/sandbox"
3
Javascript
Javascript
fix typo in partialevaluator_gettextcontent
318b286da3021bcd44895530eb828ae89add4a27
<ide><path>src/evaluator.js <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> return queue; <ide> }, <ide> <del> getTextContent: function partialEvaluatorGetIRQueue( <add> getTextContent: function PartialEvaluator_getTextContent( <ide> stream, resources, state) { <ide> var bidiTexts; <ide> var kSpaceFactor = 0.35;
1
Javascript
Javascript
move require of http2 to after crypto check
94840fdb9db2a624bb3e071c462f2a8607a995bd
<ide><path>test/parallel/test-heapdump-http2.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const { recordState } = require('../common/heap'); <del>const http2 = require('http2'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <add>const http2 = require('http2'); <ide> <ide> { <ide> const state = recordState();
1
Text
Text
fix copy typo
281ad204524f6ad9943902a6a909bb56bfc3d06b
<ide><path>docs/06-Polar-Area-Chart.md <ide> Some properties are specified as arrays. The first value applies to the first ba <ide> <ide> Property | Type | Usage <ide> --- | --- | --- <del>data | `Array<Number>` | The data to plot as bars <add>data | `Array<Number>` | The data to plot as arcs <ide> label | `String` | The label for the dataset which appears in the legend and tooltips <ide> backgroundColor | `Array<Color>` | The fill color of the arcs. See [Colors](#chart-configuration-colors) <ide> borderColor | `Array<Color>` | Arc border color
1
Ruby
Ruby
handle nil req_dependency
4ca9831da6c1b16f7ea28e32c7c21cf37845c26d
<ide><path>Library/Homebrew/formula_installer.rb <ide> def expand_requirements <ide> <ide> if (req.optional? || req.recommended?) && build.without?(req) <ide> Requirement.prune <del> elsif req.build? && use_default_formula && req_dependency.installed? <add> elsif req.build? && use_default_formula && req_dependency&.installed? <ide> Requirement.prune <ide> elsif install_requirement_formula?(req_dependency, req, install_bottle_for_dependent) <ide> deps.unshift(req_dependency)
1
Python
Python
use typevar for setupmethod()
8796b2a784bc45fcc6865cd80b2cba0601448727
<ide><path>src/flask/scaffold.py <ide> # a singleton sentinel value for parameter defaults <ide> _sentinel = object() <ide> <add>F = t.TypeVar("F", bound=t.Callable[..., t.Any]) <ide> <del>def setupmethod(f: t.Callable) -> t.Callable: <add> <add>def setupmethod(f: F) -> F: <ide> """Wraps a method so that it performs a check in debug mode if the <ide> first request was already handled. <ide> """ <ide> def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any: <ide> ) <ide> return f(self, *args, **kwargs) <ide> <del> return update_wrapper(wrapper_func, f) <add> return t.cast(F, update_wrapper(wrapper_func, f)) <ide> <ide> <ide> class Scaffold:
1
PHP
PHP
guess ability name for authorizeforuser
d3f083a892e753bf4bd68e6dd1d30ffcb0fcbadd
<ide><path>src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php <ide> trait AuthorizesRequests <ide> public function authorize($ability, $arguments = []) <ide> { <ide> if (func_num_args() === 1) { <del> $arguments = $ability; <del> <del> $ability = debug_backtrace(false, 2)[1]['function']; <add> list($arguments, $ability) = [$ability, $this->guessAbilityName()]; <ide> } <ide> <ide> if (! app(Gate::class)->check($ability, $arguments)) { <ide> public function authorize($ability, $arguments = []) <ide> */ <ide> public function authorizeForUser($user, $abiility, $arguments = []) <ide> { <add> if (func_num_args() === 2) { <add> list($arguments, $ability) = [$ability, $this->guessAbilityName()]; <add> } <add> <ide> $result = app(Gate::class)->forUser($user)->check($ability, $arguments); <ide> <ide> if (! $result) { <ide> throw $this->createGateUnauthorizedException($ability, $arguments); <ide> } <ide> } <ide> <add> /** <add> * Guesses the ability's name from the original method name. <add> * <add> * @return string <add> */ <add> protected function guessAbilityName() <add> { <add> return debug_backtrace(false, 3)[2]['function']; <add> } <add> <ide> /** <ide> * Throw an unauthorized exception based on gate results. <ide> *
1
Javascript
Javascript
fix regression in posix.normalize
a0adf56855f59a301d9a1f69b4267ced4fd4cf03
<ide><path>lib/path.js <ide> function isPathSeparator(code) { <ide> return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; <ide> } <ide> <add>function isPosixPathSeparator(code) { <add> return code === CHAR_FORWARD_SLASH; <add>} <add> <ide> function isWindowsDeviceRoot(code) { <ide> return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || <ide> code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z; <ide> } <ide> <ide> // Resolves . and .. elements in a path with directory names <del>function normalizeString(path, allowAboveRoot, separator) { <add>function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { <ide> var res = ''; <ide> var lastSegmentLength = 0; <ide> var lastSlash = -1; <ide> const win32 = { <ide> // fails) <ide> <ide> // Normalize the tail path <del> resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\'); <add> resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', <add> isPathSeparator); <ide> <ide> return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || <ide> '.'; <ide> const win32 = { <ide> } <ide> <ide> var tail; <del> if (rootEnd < len) <del> tail = normalizeString(path.slice(rootEnd), !isAbsolute, '\\'); <del> else <add> if (rootEnd < len) { <add> tail = normalizeString(path.slice(rootEnd), !isAbsolute, '\\', <add> isPathSeparator); <add> } else { <ide> tail = ''; <add> } <ide> if (tail.length === 0 && !isAbsolute) <ide> tail = '.'; <ide> if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) <ide> const posix = { <ide> // handle relative paths to be safe (might happen when process.cwd() fails) <ide> <ide> // Normalize the path <del> resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/'); <add> resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', <add> isPosixPathSeparator); <ide> <ide> if (resolvedAbsolute) { <ide> if (resolvedPath.length > 0) <ide> const posix = { <ide> path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; <ide> <ide> // Normalize the path <del> path = normalizeString(path, !isAbsolute, '/'); <add> path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); <ide> <ide> if (path.length === 0 && !isAbsolute) <ide> path = '.'; <ide><path>test/parallel/test-path-normalize.js <ide> assert.strictEqual( <ide> path.win32.normalize('../.../../foobar/../../../bar/../../baz'), <ide> '..\\..\\..\\..\\baz' <ide> ); <add>assert.strictEqual(path.win32.normalize('foo/bar\\baz'), 'foo\\bar\\baz'); <ide> <ide> assert.strictEqual(path.posix.normalize('./fixtures///b/../b/c.js'), <ide> 'fixtures/b/c.js'); <ide> assert.strictEqual( <ide> path.posix.normalize('../.../../foobar/../../../bar/../../baz'), <ide> '../../../../baz' <ide> ); <add>assert.strictEqual(path.posix.normalize('foo/bar\\baz'), 'foo/bar\\baz');
2
Ruby
Ruby
remove unnecessary dup in expire_page
a4515b60e316d52a6ac2902886b117588702e20b
<ide><path>actionpack/lib/action_controller/caching/pages.rb <ide> def expire_page(options = {}) <ide> <ide> if options.is_a?(Hash) <ide> if options[:action].is_a?(Array) <del> options[:action].dup.each do |action| <add> options[:action].each do |action| <ide> self.class.expire_page(url_for(options.merge(:only_path => true, :action => action))) <ide> end <ide> else
1
Ruby
Ruby
move ld64 into sharedenvextension
48dde74503d61b6b9702aea0705202635124d93b
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def fortran <ide> set_cpu_flags(flags) <ide> end <ide> <add> # ld64 is a newer linker provided for Xcode 2.5 <add> def ld64 <add> ld64 = Formula.factory('ld64') <add> self['LD'] = ld64.bin/'ld' <add> append "LDFLAGS", "-B#{ld64.bin.to_s+"/"}" <add> end <add> <ide> def warn_about_non_apple_gcc(gcc) <ide> opoo "Experimental support for non-Apple GCC enabled. Some builds may fail!" <ide> <ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def make_jobs <ide> Hardware::CPU.cores <ide> end <ide> end <del> <del> # ld64 is a newer linker provided for Xcode 2.5 <del> def ld64 <del> ld64 = Formula.factory('ld64') <del> self['LD'] = ld64.bin/'ld' <del> append "LDFLAGS", "-B#{ld64.bin.to_s+"/"}" <del> end <ide> end
2
Ruby
Ruby
fix long line
11de7de49d272af4f75c5289b28dfce7b735312c
<ide><path>Library/Homebrew/rubocops/text.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> problem "Formulae should not depend on both OpenSSL and LibreSSL (even optionally)." <ide> end <ide> <del> if depends_on?("veclibfort") || depends_on?("lapack") <del> problem "Formulae should use OpenBLAS as the default serial linear algebra library." if formula_tap == "homebrew-core" <add> if formula_tap == "homebrew-core" && (depends_on?("veclibfort") || depends_on?("lapack")) <add> problem "Formulae should use OpenBLAS as the default serial linear algebra library." <ide> end <ide> <ide> if method_called_ever?(body_node, :virtualenv_create) ||
1
Text
Text
update chinese translation of basic html and html5
3857e8d77958906beeb5ca1303149c308587d1dc
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/applied-visual-design/decrease-the-opacity-of-an-element.chinese.md <ide> localeTitle: 降低元素的不透明度 <ide> <ide> ```yml <ide> tests: <del> - text: 您的代码应通过选择<code>links</code>类将锚点标记上的<code>opacity</code>属性设置为0.7。 <add> - text: 您的代码应通过选择<code>links</code>类将 <code>a</code> 标记上的<code>opacity</code>属性设置为0.7。 <ide> testString: 'assert.approximately(parseFloat($(".links").css("opacity")), 0.7, 0.1, "Your code should set the <code>opacity</code> property to 0.7 on the anchor tags by selecting the class of <code>links</code>.");' <ide> <ide> ``` <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/add-a-submit-button-to-a-form.chinese.md <ide> id: bad87fee1348bd9aedd08830 <ide> title: Add a Submit Button to a Form <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 向表单添加提交按钮 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cp2Nkhz' <add>forumTopicId: 16627 <add>localeTitle: 给表单添加提交按钮 <ide> --- <ide> <ide> ## Description <del><section id="description">我们在表单中添加一个<code>submit</code>按钮。单击此按钮会将表单中的数据发送到您使用表单的<code>action</code>属性指定的URL。这是一个示例提交按钮: <code>&lt;button type=&quot;submit&quot;&gt;this button submits the form&lt;/button&gt;</code> </section> <add><section id='description'> <add>让我们来给表单添加一个<code>submit</code>提交按钮,当点击提交按钮时,表单中的数据将会被发送到<code>action</code>属性指定的 URL 上。 <add>例如: <add><code>&#60;button type="submit"&#62;this button submits the form&#60;/button&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">添加一个按钮作为<code>form</code>元素的最后一个元素,其类型为<code>submit</code> ,并且“Submit”作为其文本。 </section> <add><section id='instructions'> <add>在表单的底部创建一个<code>button</code>按钮,按钮的<code>type</code>属性值为<code>submit</code>,文本为<code>提交</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 你的表单里面应该有一个按钮。 <del> testString: 'assert($("form").children("button").length > 0, "Your form should have a button inside it.");' <del> - text: 您的提交按钮应该具有要<code>submit</code>的属性<code>type</code> 。 <del> testString: 'assert($("button").attr("type") === "submit", "Your submit button should have the attribute <code>type</code> set to <code>submit</code>.");' <del> - text: 您的提交按钮应该只有“提交”文本。 <del> testString: 'assert($("button").text().match(/^\s*submit\s*$/gi), "Your submit button should only have the text "Submit".");' <del> - text: 确保您的<code>button</code>元素有一个结束标记。 <del> testString: 'assert(code.match(/<\/button>/g) && code.match(/<button/g) && code.match(/<\/button>/g).length === code.match(/<button/g).length, "Make sure your <code>button</code> element has a closing tag.");' <add> - text: '表单内部应该有一个按钮。' <add> testString: assert($("form").children("button").length > 0, '表单内部应该有一个按钮。'); <add> - text: '按钮的<code>type</code>属性值应该为<code>submit</code>。' <add> testString: assert($("button").attr("type") === "submit"); <add> - text: '提交按钮的文本应该为<code>提交</code>。' <add> testString: assert($("button").text().match(/^\s*提交\s*$/gi)); <add> - text: '确保按钮有结束标记。' <add> testString: assert(code.match(/<\/button>/g) && code.match(/<button/g) && code.match(/<\/button>/g).length === code.match(/<button/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add> <p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的橘猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层面</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>祛跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <form action="/submit-cat-photo"> <del> <input type="text" placeholder="cat photo URL"> <add> <input type="text" placeholder="猫咪图片地址"> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <del> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del><h2>CatPhotoApp</h2> <del><main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <del> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <del> </ul> <del> <p>Top 3 things cats hate:</p> <del> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <del> </ol> <del> <form action="/submit-cat-photo"> <del> <input type="text" placeholder="cat photo URL"> <del> <button type="submit">Submit</button> <del> </form> <del></main> <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.chinese.md <ide> id: bad87fee1348bd9aedf08812 <ide> title: Add Images to Your Website <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 添加图片到您的网站 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/c8EbJf2' <add>forumTopicId: 16640 <add>localeTitle: 给网站添加图片 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用<code>img</code>元素将图像添加到网站,并使用<code>src</code>属性指向特定图像的URL。这方面的一个例子是: <code>&lt;img src=&quot;https://www.your-image-source.com/your-image.jpg&quot;&gt;</code>请注意, <code>img</code>元素是自动关闭的。所有<code>img</code>元素都<strong>必须</strong>具有<code>alt</code>属性。 <code>alt</code>属性中的文本用于屏幕阅读器以提高可访问性,并在图像无法加载时显示。注意:如果图像纯粹是装饰性的,则使用空的<code>alt</code>属性是最佳做法。理想情况下,除非需要,否则<code>alt</code>属性不应包含特殊字符。让我们在上面的<code>img</code>示例中添加一个<code>alt</code>属性: <code>&lt;img src=&quot;https://www.your-image-source.com/your-image.jpg&quot; alt=&quot;Author standing on a beach with two thumbs up.&quot;&gt;</code> </section> <add><section id='description'> <add>用<code>img</code>元素来为你的网站添加图片,其中<code>src</code>属性指向一个图片的地址。 <add>例如: <add><code>&#60img src="https://www.your-image-source.com/your-image.jpg"&#62</code> <add>注意:<code>img</code>元素是没有结束标记的。 <add>所有的<code>img</code>元素必须有<code>alt</code>属性,<code>alt</code>属性的文本是当图片无法加载时显示的替代文本,这对于通过屏幕阅读器来浏览网页的用户非常重要。 <add>注意:如果图片是纯装饰性的,用一个空的<code>alt</code>是最佳实践。 <add>理想情况下,<code>alt</code>属性不应该包含特殊字符,除非必要。 <add>让我们给上面例子的<code>img</code>添加<code>alt</code>属性。 <add><code>&#60img src="https://www.your-image-source.com/your-image.jpg" alt="作者站在沙滩上竖起两个大拇指"&#62</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">让我们尝试将图像添加到我们的网站:在<code>h2</code>元素之前插入<code>img</code>标记。现在设置<code>src</code>属性,使其指向此URL: <code>https://bit.ly/fcc-relaxing-cat</code> : <code>https://bit.ly/fcc-relaxing-cat</code>最后不要忘记为您的图像添加<code>alt</code>文字。 </section> <add><section id='instructions'> <add>让我们给网站添加图片: <add>在<code>h2</code>元素前,插入一个<code>img</code>元素 <add>现在设置<code>src</code>属性指向这个地址: <add><code>https://bit.ly/fcc-relaxing-cat</code> <add>最后不要忘记给图片添加一个<code>alt</code>文本。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的页面应该有一个图像元素。 <del> testString: 'assert($("img").length > 0, "Your page should have an image element.");' <del> - text: 您的图像应具有指向小猫图像的<code>src</code>属性。 <del> testString: 'assert(new RegExp("\/\/bit.ly\/fcc-relaxing-cat|\/\/s3.amazonaws.com\/freecodecamp\/relaxing-cat.jpg", "gi").test($("img").attr("src")), "Your image should have a <code>src</code> attribute that points to the kitten image.");' <del> - text: 您的图片元素<strong>必须</strong>具有<code>alt</code>属性。 <del> testString: 'assert(code.match(/alt\s*?=\s*?(\"|\").*(\"|\")/), "Your image element <strong>must</strong> have an <code>alt</code> attribute.");' <add> - text: '网页应该有一张图片。' <add> testString: assert($("img").length > 0); <add> - text: '图片 src 属性应该为 https://bit.ly/fcc-relaxing-cat。' <add> testString: assert(/^https:\/\/bit\.ly\/fcc-relaxing-cat$/i.test($("img").attr("src"))); <add> - text: '图片必须有<code>alt</code>属性。' <add> testString: assert(code.match(/alt\s*?=\s*?(\"|\').*(\"|\')/)); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会囤老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.chinese.md <ide> id: bad87fee1348bd9aedf08830 <ide> title: Add Placeholder Text to a Text Field <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 将占位符文本添加到文本字段 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cKdJDhg' <add>forumTopicId: 16647 <add>localeTitle: 给输入框添加占位符文本 <ide> --- <ide> <ide> ## Description <del><section id="description">占位符文本是在用户输入任何内容之前在<code>input</code>元素中显示的内容。您可以像这样创建占位符文本: <code>&lt;input type=&quot;text&quot; placeholder=&quot;this is placeholder text&quot;&gt;</code> </section> <add><section id='description'> <add><code>Placeholder</code>占位符是用户在<code>input</code>输入框中输入任何东西前的预定义文本。 <add>你可以像这样创建一个占位符: <add><code>&#60;input type="text" placeholder="this is placeholder text"&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将文本<code>input</code>的<code>placeholder</code>值设置为“cat photo URL”。 </section> <add><section id='instructions'> <add>把<code>input</code>输入框的<code>placeholder</code>占位符文本设置为 “猫咪图片地址”。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 将<code>placeholder</code>属性添加到现有文本<code>input</code>元素。 <del> testString: 'assert($("input[placeholder]").length > 0, "Add a <code>placeholder</code> attribute to the existing text <code>input</code> element.");' <del> - text: 将占位符属性的值设置为“cat photo URL”。 <del> testString: 'assert($("input") && $("input").attr("placeholder") && $("input").attr("placeholder").match(/cat\s+photo\s+URL/gi), "Set the value of your placeholder attribute to "cat photo URL".");' <del> - text: 完成的<code>input</code>元素应该具有有效的语法。 <del> testString: 'assert($("input[type=text]").length > 0 && code.match(/<input((\s+\w+(\s*=\s*(?:".*?"|".*?"|[\^"">\s]+))?)+\s*|\s*)\/?>/gi), "The finished <code>input</code> element should have valid syntax.");' <del> <add> - text: '给现有的<code>input</code>输入框添加一个<code>placeholder</code>属性。' <add> testString: assert($("input[placeholder]").length > 0); <add> - text: '设置<code>placeholder</code>属性的值为 ”猫咪图片地址“。' <add> testString: assert($("input") && $("input").attr("placeholder") && $("input").attr("placeholder").match(/猫咪图片地址/gi)); <add> - text: '<code>input</code>输入框的语法必须正确。' <add> testString: 'assert($("input[type=text]").length > 0 && code.match(/<input((\s+\w+(\s*=\s*(?:".*?"|''.*?''|[\^''">\s]+))?)+\s*|\s*)\/?>/gi));' <ide> ``` <ide> <ide> </section> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <input type="text"> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/check-radio-buttons-and-checkboxes-by-default.chinese.md <ide> id: bad87fee1348bd9aedd08835 <ide> title: Check Radio Buttons and Checkboxes by Default <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 默认情况下检查单选按钮和复选框 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cWk3Qh6' <add>forumTopicId: 301094 <add>localeTitle: 给单选按钮和复选框添加默认选中项 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用<code>checked</code>属性设置默认情况下要选中的复选框或单选按钮。为此,只需将“checked”一词添加到input元素的内部即可。例如: <code>&lt;input type=&quot;radio&quot; name=&quot;test-name&quot; checked&gt;</code> </section> <add><section id='description'> <add>如果想设置某个单选按钮或多选按钮默认被选中,只需给<code>input</code>元素添加 "checked" 属性。 例如: <add><code>&#60;input type="radio" name="test-name" checked&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">默认情况下,设置第一个<code>radio buttons</code>和第一个<code>checkboxes</code> 。 </section> <add><section id='instructions'> <add>把第一个<code>radio button</code>和第一个<code>checkbox</code>都设置为默认选中。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 默认情况下,应检查表单上的第一个单选按钮。 <del> testString: 'assert($("input[type="radio"]").prop("checked"), "Your first radio button on your form should be checked by default.");' <del> - text: 默认情况下,应检查表单上的第一个复选框。 <del> testString: 'assert($("input[type="checkbox"]").prop("checked"), "Your first checkbox on your form should be checked by default.");' <add> - text: '表单的第一个单选按钮应该被默认选中。' <add> testString: assert($('input[type="radio"]').prop("checked")); <add> - text: '表单的第一个多选按钮应该被默认选中。' <add> testString: assert($('input[type="checkbox"]').prop("checked")); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <form action="/submit-cat-photo"> <del> <label><input type="radio" name="indoor-outdoor"> Indoor</label> <del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br> <del> <label><input type="checkbox" name="personality"> Loving</label> <del> <label><input type="checkbox" name="personality"> Lazy</label> <del> <label><input type="checkbox" name="personality"> Energetic</label><br> <del> <input type="text" placeholder="cat photo URL" required> <del> <button type="submit">Submit</button> <add> <label><input type="radio" name="indoor-outdoor">室内</label> <add> <label><input type="radio" name="indoor-outdoor">室外</label><br> <add> <label><input type="checkbox" name="personality">忠诚</label> <add> <label><input type="checkbox" name="personality">懒惰</label> <add> <label><input type="checkbox" name="personality">积极</label><br> <add> <input type="text" placeholder="猫咪图片地址" required> <add> <button type="submit">提交</button> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/comment-out-html.chinese.md <ide> id: bad87fee1348bd9aedf08804 <ide> title: Comment out HTML <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 评论HTML <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cGyGbca' <add>forumTopicId: 16782 <add>localeTitle: 给 HTML 添加注释 <ide> --- <ide> <ide> ## Description <del><section id="description">请记住,为了开始评论,您需要使用<code>&lt;!--</code>并结束评论,您需要使用<code>--&gt;</code>这里您需要在<code>h2</code>元素开始之前结束评论。 </section> <add><section id='description'> <add>记住:注释的开始标记是<code>&#60;!--</code>,结束标记是<code>--&#62;</code>。 <add>现在你需要在<code>h2</code>元素前终止注释。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">注释掉你的<code>h1</code>元素和你的<code>p</code>元素,但不是你的<code>h2</code>元素。 </section> <add><section id='instructions'> <add>任务:注释掉<code>h1</code>元素和<code>p</code>元素,保留<code>h2</code>元素。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 注释掉你的<code>h1</code>元素,使其在你的页面上不可见。 <del> testString: 'assert(($("h1").length === 0), "Comment out your <code>h1</code> element so that it is not visible on your page.");' <del> - text: 保持<code>h2</code>元素取消注释,以便在页面上显示。 <del> testString: 'assert(($("h2").length > 0), "Leave your <code>h2</code> element uncommented so that it is visible on your page.");' <del> - text: 注释掉你的<code>p</code>元素,使其在你的页面上不可见。 <del> testString: 'assert(($("p").length === 0), "Comment out your <code>p</code> element so that it is not visible on your page.");' <del> - text: 请务必使用<code>--&gt;</code>关闭每条评论。 <del> testString: 'assert(code.match(/[^fc]-->/g).length > 1, "Be sure to close each of your comments with <code>--&#62;</code>.");' <del> - text: 请勿更改代码中<code>h1</code> <code>h2</code>或<code>p</code>的顺序。 <del> testString: 'assert((code.match(/<([a-z0-9]){1,2}>/g)[0]==="<h1>" && code.match(/<([a-z0-9]){1,2}>/g)[1]==="<h2>" && code.match(/<([a-z0-9]){1,2}>/g)[2]==="<p>") , "Do not change the order of the <code>h1</code> <code>h2</code> or <code>p</code> in the code.");' <add> - text: '注释掉<code>h1</code>元素,这样它就从网页上消失了。' <add> testString: assert(($("h1").length === 0)); <add> - text: '<code>h2</code>元素保持原样,这样网页上还能看到它。' <add> testString: assert(($("h2").length > 0)); <add> - text: '注释掉<code>p</code>元素,这样它就从网页上消失了。' <add> testString: assert(($("p").length === 0)); <add> - text: '确保每一个注释都以<code>--&#62;</code>结尾。' <add> testString: assert(code.match(/[^fc]-->/g).length > 1); <add> - text: '不要更改<code>h1</code>元素、<code>h2</code> 元素、<code>p</code>元素的顺序。' <add> testString: assert((code.match(/<([a-z0-9]){1,2}>/g)[0]==="<h1>" && code.match(/<([a-z0-9]){1,2}>/g)[1]==="<h2>" && code.match(/<([a-z0-9]){1,2}>/g)[2]==="<p>")); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> <h2>CatPhotoApp</h2> <ide> <del><p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <add><p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <ide> --> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-a-bulleted-unordered-list.chinese.md <ide> id: bad87fee1348bd9aedf08827 <ide> title: Create a Bulleted Unordered List <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 创建项目符号无序列表 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cDKVPuv' <add>forumTopicId: 16814 <add>localeTitle: 创建一个无序列表 <ide> --- <ide> <ide> ## Description <del><section id="description"> HTML具有用于创建<code>unordered lists</code>或项目符号样式列表的特殊元素。无序列表以开头<code>&lt;ul&gt;</code>元素开头,后跟任意数量的<code>&lt;li&gt;</code>元素。最后,无序列表以<code>&lt;/ul&gt;</code>结尾例如: <blockquote> &lt;UL&gt; <br> &lt;LI&gt;乳&lt;/ LI&gt; <br> &lt;LI&gt;干酪&lt;/ LI&gt; <br> &lt;/ UL&gt; </blockquote>会创建一个“牛奶”和“奶酪”的子弹点样式列表。 </section> <add><section id='description'> <add>HTML 有一个特定的元素用于创建无序列表<code>unordered lists(缩写 ul)</code>。 <add>无序列表以<code>&#60;ul&#62;</code>开始,中间包含一个或多个<code>&#60;li&#62;</code>元素,最后以<code>&#60;/ul&#62;</code>结尾。 <add>例如: <add> <add>```html <add><ul> <add> <li>牛奶</li> <add> <li>奶酪</li> <add></ul> <add>``` <add> <add>将会创建一个包含牛奶和奶酪的无序列表。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">删除最后两个<code>p</code>元素,并在页面底部创建猫喜爱的三件事的无序列表。 </section> <add><section id='instructions'> <add>删除页面底部的两个<code>p</code>元素,然后在底部创建一个无序列表,其中包含你认为猫咪最喜欢的三件东西。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 创建一个<code>ul</code>元素。 <del> testString: 'assert($("ul").length > 0, "Create a <code>ul</code> element.");' <del> - text: 你的<code>ul</code>元素中应该有三个<code>li</code>元素。 <del> testString: 'assert($("ul li").length > 2, "You should have three <code>li</code> elements within your <code>ul</code> element.");' <del> - text: 确保你的<code>ul</code>元素有一个结束标记。 <del> testString: 'assert(code.match(/<\/ul>/gi) && code.match(/<ul/gi) && code.match(/<\/ul>/gi).length === code.match(/<ul/gi).length, "Make sure your <code>ul</code> element has a closing tag.");' <del> - text: 确保您的<code>li</code>元素具有结束标记。 <del> testString: 'assert(code.match(/<\/li>/gi) && code.match(/<li[\s>]/gi) && code.match(/<\/li>/gi).length === code.match(/<li[\s>]/gi).length, "Make sure your <code>li</code> elements have closing tags.");' <del> - text: 确保您的<code>li</code>元素不包含任何空字符串或者只有空格。 <del> testString: assert($("ul li").filter((_, item) => !$(item).text().trim()).length === 0, 'Make sure your <code>li</code> elements don\’t contain an empty string or only white-space.'); <add> - text: '创建一个<code>ul</code>无序列表。' <add> testString: assert($("ul").length > 0); <add> - text: '你应该在<code>ul</code>无序列表中添加三个<code>li</code>条目。' <add> testString: assert($("ul li").length > 2); <add> - text: '确保<code>ul</code>无序列表有结束标记。' <add> testString: assert(code.match(/<\/ul>/gi) && code.match(/<ul/gi) && code.match(/<\/ul>/gi).length === code.match(/<ul/gi).length); <add> - text: '确保每个<code>li</code>条目都有结束标记。' <add> testString: assert(code.match(/<\/li>/gi) && code.match(/<li[\s>]/gi) && code.match(/<\/li>/gi).length === code.match(/<li[\s>]/gi).length); <add> <ide> ``` <ide> <ide> </section> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del><h2>CatPhotoApp</h2> <del><main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. <del> Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. <del> <ul> <del> <li>milk</li> <del> <li>food</li> <del> <li>toys</li> <del> </ul> <del></main> <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-a-form-element.chinese.md <ide> id: bad87fee1348bd9aede08830 <ide> title: Create a Form Element <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 创建表单元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cmQ3Kfa' <add>forumTopicId: 16817 <add>localeTitle: 创建一个表单 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用纯HTML来构建实际将数据提交到服务器的Web表单。您可以通过在<code>form</code>元素上指定操作来执行此操作。例如: <code>&lt;form action=&quot;/url-where-you-want-to-submit-form-data&quot;&gt;&lt;/form&gt;</code> </section> <add><section id='description'> <add>如果想使用 HTML 向服务器提交数据,可以给<code>form</code>添加<code>action</code>属性。 <add>例如: <add><code>&#60;form action="/url-where-you-want-to-submit-form-data"&#62;&#60;/form&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将文本字段嵌套在<code>form</code>元素中,并将<code>action=&quot;/submit-cat-photo&quot;</code>属性添加到表单元素中。 </section> <add><section id='instructions'> <add>在<code>input</code>输入框外层创建一个<code>form</code>表单,然后设置表单的<code>action</code>属性为<code>"/submit-cat-photo"</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 将文本输入元素嵌套在<code>form</code>元素中。 <del> testString: 'assert($("form") && $("form").children("input") && $("form").children("input").length > 0, "Nest your text input element within a <code>form</code> element.");' <del> - text: 确保您的<code>form</code>具有设置为<code>/submit-cat-photo</code>的<code>action</code>属性 <del> testString: 'assert($("form").attr("action") === "/submit-cat-photo", "Make sure your <code>form</code> has an <code>action</code> attribute which is set to <code>/submit-cat-photo</code>");' <del> - text: 确保您的<code>form</code>元素具有格式良好的打开和关闭标记。 <del> testString: 'assert(code.match(/<\/form>/g) && code.match(/<form [^<]*>/g) && code.match(/<\/form>/g).length === code.match(/<form [^<]*>/g).length, "Make sure your <code>form</code> element has well-formed open and close tags.");' <add> - text: '在<code>input</code>输入框外层创建一个<code>form</code>表单。' <add> testString: assert($("form") && $("form").children("input") && $("form").children("input").length > 0); <add> - text: '确保表单的<code>action</code>属性为<code>"/submit-cat-photo"</code>。' <add> testString: assert($("form").attr("action") === "/submit-cat-photo"); <add> - text: '确保表单有开始标记和结束标记。' <add> testString: assert(code.match(/<\/form>/g) && code.match(/<form [^<]*>/g) && code.match(/<\/form>/g).length === code.match(/<form [^<]*>/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <del> <input type="text" placeholder="cat photo URL"> <add> <input type="text" placeholder="猫咪图片地址"> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-a-set-of-checkboxes.chinese.md <ide> id: bad87fee1348bd9aedf08835 <ide> title: Create a Set of Checkboxes <ide> challengeType: 0 <del>videoUrl: '' <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cqrkJsp' <add>forumTopicId: 16821 <ide> localeTitle: 创建一组复选框 <ide> --- <ide> <ide> ## Description <del><section id="description">表单通常使用<code>checkboxes</code>来表示可能有多个答案的问题。复选框是一种类型的<code>input</code>您的每一个复选框可以嵌套自身的内<code>label</code>元素。通过将<code>input</code>元素包装在<code>label</code>元素内部,它将自动将复选框输入与其周围的标签元素相关联。所有相关的复选框输入应具有相同的<code>name</code>属性。通过在<code>label</code>元素上设置<code>for</code>属性以匹配关联<code>input</code>元素的<code>id</code>属性,最佳做法是明确定义复选框<code>input</code>与其对应<code>label</code>之间的关系。这是一个复选框的示例: <code>&lt;label for=&quot;loving&quot;&gt;&lt;input id=&quot;loving&quot; type=&quot;checkbox&quot; name=&quot;personality&quot;&gt; Loving&lt;/label&gt;</code> </section> <add><section id='description'> <add><code>checkboxes</code>(复选框)就好比多项选择题,正确答案有多个。 <add>复选框是<code>input</code>选择框的另一种类型。 <add>每一个复选框都应该嵌套在它自己的<code>label</code>(标签)元素中。 <add>所有关联的复选框应该拥有相同的<code>name</code>属性。 <add>最佳实践是在<code>label</code>元素上设置<code>for</code>属性,让其值与复选框的<code>id</code>属性值相等,这样就在<code>label</code>元素和它的子元素复选框之间创建了一种链接关系。例如: <add>下面是一个复选框的例子: <add><code>&#60;label for="loving"&#62;&#60;input id="loving" type="checkbox" name="personality"&#62; Loving&#60;/label&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在表单中添加一组三个复选框。每个复选框应嵌套在自己的<code>label</code>元素中。这三者都应该分享<code>personality</code>的<code>name</code>属性。 </section> <add><section id='instructions'> <add>给表单添加三个复选框,每个复选框都被嵌套进<code>label</code>元素中,并且它的<code>name</code>属性均为<code>personality</code>,它们的内容可以随意指定。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的页面应该有三个复选框元素。 <del> testString: 'assert($("input[type="checkbox"]").length > 2, "Your page should have three checkbox elements.");' <del> - text: 三个复选框元素中的每一个都应嵌套在自己的<code>label</code>元素中。 <del> testString: 'assert($("label > input[type="checkbox"]:only-child").length > 2, "Each of your three checkbox elements should be nested in its own <code>label</code> element.");' <del> - text: 确保每个<code>label</code>元素都有一个结束标记。 <del> testString: 'assert(code.match(/<\/label>/g) && code.match(/<label/g) && code.match(/<\/label>/g).length === code.match(/<label/g).length, "Make sure each of your <code>label</code> elements has a closing tag.");' <del> - text: 为您的复选框提供<code>personality</code>的<code>name</code>属性。 <del> testString: 'assert($("label > input[type="checkbox"]").filter("[name="personality"]").length > 2, "Give your checkboxes the <code>name</code> attribute of <code>personality</code>.");' <add> - text: '表单应该有三个复选框。' <add> testString: assert($('input[type="checkbox"]').length > 2); <add> - text: '每个复选框都应该被嵌套进<code>label</code>元素中。' <add> testString: 'assert($(''label > input[type="checkbox"]:only-child'').length > 2);' <add> - text: '确保<code>label</code>元素有结束标记。' <add> testString: assert(code.match(/<\/label>/g) && code.match(/<label/g) && code.match(/<\/label>/g).length === code.match(/<label/g).length); <add> - text: '设置复选框的<code>name</code>属性均为<code>personality</code>。' <add> testString: assert($('label > input[type="checkbox"]').filter("[name='personality']").length > 2); <add> - text: '每个复选框都应该在 <code>form</code> 标签内。' <add> testString: assert($('label').parent().get(0).tagName.match('FORM')); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <form action="/submit-cat-photo"> <del> <label for="indoor"><input id="indoor" type="radio" name="indoor-outdoor"> Indoor</label> <del> <label for="outdoor"><input id="outdoor" type="radio" name="indoor-outdoor"> Outdoor</label><br> <del> <input type="text" placeholder="cat photo URL" required> <del> <button type="submit">Submit</button> <add> <label for="indoor"><input id="indoor" type="radio" name="indoor-outdoor">室内</label> <add> <label for="outdoor"><input id="outdoor" type="radio" name="indoor-outdoor">室外</label><br> <add> <input type="text" placeholder="猫咪图片地址" required> <add> <button type="submit">提交</button> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <add> <add> <ide> </div> <ide> <ide> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-a-set-of-radio-buttons.chinese.md <ide> id: bad87fee1348bd9aedf08834 <ide> title: Create a Set of Radio Buttons <ide> challengeType: 0 <del>videoUrl: '' <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cNWKvuR' <add>forumTopicId: 16822 <ide> localeTitle: 创建一组单选按钮 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用<code>radio buttons</code>来解决您希望用户仅从多个选项中给出一个答案的问题。单选按钮是一种<code>input</code> 。每个单选按钮都可以嵌套在自己的<code>label</code>元素中。通过将<code>input</code>元素包装在<code>label</code>元素内部,它将自动将单选按钮输入与其周围的标签元素相关联。所有相关的单选按钮应具有相同的<code>name</code>属性以创建单选按钮组。通过创建无线电组,选择任何单个单选按钮将自动取消选择同一组内的其他按钮,确保用户只提供一个答案。这是一个单选按钮的示例: <blockquote> &lt;标签&gt; <br> &lt;input type =“radio”name =“indoor-outdoor”&gt;室内<br> &lt;/标签&gt; </blockquote>最佳做法是在<code>label</code>元素上设置<code>for</code>属性,其值与<code>input</code>元素的<code>id</code>属性值相匹配。这允许辅助技术在标签和子<code>input</code>元素之间创建链接关系。例如: <blockquote> &lt;label for =“室内”&gt; <br> &lt;input id =“indoor”type =“radio”name =“indoor-outdoor”&gt;室内<br> &lt;/标签&gt; </blockquote></section> <add><section id='description'> <add><code>radio buttons</code>(单选按钮)就好比单项选择题,正确答案只有一个。 <add>单选按钮是<code>input</code>选择框的一种类型。 <add>每一个单选按钮都应该嵌套在它自己的<code>label</code>(标签)元素中。 <add>所有关联的单选按钮应该拥有相同的<code>name</code>属性。 <add>下面是一个单选按钮的例子: <add> <add>```html <add><label> <add> <input type="radio" name="indoor-outdoor">Indoor <add></label> <add>``` <add> <add>最佳实践是在<code>label</code>元素上设置for属性,让其值与单选按钮的<code>id</code>属性值相等,这样就在<code>label</code>元素和它的子元素单选按钮之间创建了一种链接关系。例如: <add> <add>```html <add><label for="indoor"> <add> <input id="indoor" type="radio" name="indoor-outdoor">Indoor <add></label> <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在表单中添加一对单选按钮,每个按钮都嵌套在自己的标签元素中。一个应该有<code>indoor</code>选择,另一个应该可以选择<code>outdoor</code> 。两者都应该共享<code>indoor-outdoor</code>的<code>name</code>属性来创建一个无线电组。 </section> <add><section id='instructions'> <add>给表单添加两个单选按钮,一个叫<code>indoor</code>,另一个叫<code>outdoor</code>,单选按钮的 <code>name</code> 为 <code>indoor-outdoor</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的页面应该有两个单选按钮元素。 <del> testString: 'assert($("input[type="radio"]").length > 1, "Your page should have two radio button elements.");' <del> - text: 为您的单选按钮提供<code>indoor-outdoor</code>的<code>name</code>属性。 <del> testString: 'assert($("label > input[type="radio"]").filter("[name="indoor-outdoor"]").length > 1, "Give your radio buttons the <code>name</code> attribute of <code>indoor-outdoor</code>.");' <del> - text: 两个单选按钮元素中的每一个都应嵌套在自己的<code>label</code>元素中。 <del> testString: 'assert($("label > input[type="radio"]:only-child").length > 1, "Each of your two radio button elements should be nested in its own <code>label</code> element.");' <del> - text: 确保每个<code>label</code>元素都有一个结束标记。 <del> testString: 'assert((code.match(/<\/label>/g) && code.match(/<label/g) && code.match(/<\/label>/g).length === code.match(/<label/g).length), "Make sure each of your <code>label</code> elements has a closing tag.");' <del> - text: 您的一个单选按钮应该是<code>indoor</code>标签。 <del> testString: 'assert($("label").text().match(/indoor/gi), "One of your radio buttons should have the label <code>indoor</code>.");' <del> - text: 您的一个单选按钮应该是<code>outdoor</code>标签。 <del> testString: 'assert($("label").text().match(/outdoor/gi), "One of your radio buttons should have the label <code>outdoor</code>.");' <del> - text: 应在<code>form</code>标记中添加每个单选按钮元素。 <del> testString: 'assert($("label").parent().get(0).tagName.match("FORM"), "Each of your radio button elements should be added within the <code>form</code> tag.");' <add> - text: '页面上应该有两个单选按钮元素。' <add> testString: assert($('input[type="radio"]').length > 1); <add> - text: '设置单选按钮的<code>name</code>属性为<code>indoor-outdoor</code>。' <add> testString: assert($('label > input[type="radio"]').filter("[name='indoor-outdoor']").length > 1); <add> - text: '每一个单选按钮都应该嵌套进它自己的<code>label</code>元素中。' <add> testString: 'assert($(''label > input[type="radio"]:only-child'').length > 1);' <add> - text: '每一个<code>label</code>元素都有结束标记。' <add> testString: assert((code.match(/<\/label>/g) && code.match(/<label/g) && code.match(/<\/label>/g).length === code.match(/<label/g).length)); <add> - text: '其中一个<code>label</code>元素的文本为<code>indoor</code>。' <add> testString: assert($("label").text().match(/indoor/gi)); <add> - text: '其中一个<code>label</code>元素的文本为<code>outdoor</code>。' <add> testString: assert($("label").text().match(/outdoor/gi)); <add> - text: '所有的单选按钮都应该包含在<code>form</code>表单中。' <add> testString: assert($("label").parent().get(0).tagName.match('FORM')); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <form action="/submit-cat-photo"> <del> <input type="text" placeholder="cat photo URL" required> <del> <button type="submit">Submit</button> <add> <input type="text" placeholder="猫咪图片地址" required> <add> <button type="submit">提交</button> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-a-text-field.chinese.md <ide> id: bad87fee1348bd9aedf08829 <ide> title: Create a Text Field <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 创建文本字段 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/c2EVnf6' <add>forumTopicId: 16823 <add>localeTitle: 创建一个输入框 <ide> --- <ide> <ide> ## Description <del><section id="description">现在让我们创建一个Web表单。输入元素是从用户获取输入的便捷方式。您可以创建如下文本输入: <code>&lt;input type=&quot;text&quot;&gt;</code>请注意, <code>input</code>元素是自动关闭的。 </section> <add><section id='description'> <add>现在让我们来创建一个<code>form</code>表单。 <add><code>input</code>输入框可以让你轻松获得用户的输入。 <add>你可以像这样创建一个文本输入框: <add><code>&#60;input type="text"&#62;</code> <add>注意:<code>input</code>输入框是没有结束标记的。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在列表下创建<code>text</code>类型的<code>input</code>元素。 </section> <add><section id='instructions'> <add>在列表下面创建一个<code>type</code>属性为<code>text</code>的<code>input</code>输入框。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的应用应具有<code>text</code>类型的<code>input</code>元素。 <del> testString: 'assert($("input[type=text]").length > 0, "Your app should have an <code>input</code> element of type <code>text</code>.");' <add> - text: '网页中有一个<code>type</code>属性为<code>text</code>的<code>input</code>输入框。' <add> testString: assert($("input[type=text]").length > 0); <ide> <ide> ``` <ide> <ide> tests: <ide> <h2>CatPhotoApp</h2> <ide> <main> <ide> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <del> <del> <add> <add> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/create-an-ordered-list.chinese.md <ide> id: bad87fee1348bd9aedf08828 <ide> title: Create an Ordered List <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 创建有序列表 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cQ3B8TM' <add>forumTopicId: 16824 <add>localeTitle: 创建一个有序列表 <ide> --- <ide> <ide> ## Description <del><section id="description"> HTML还有另一个用于创建<code>ordered lists</code>或编号列表的特殊元素。有序列表以开头<code>&lt;ol&gt;</code>元素开头,后跟任意数量的<code>&lt;li&gt;</code>元素。最后,有序列表以<code>&lt;/ol&gt;</code>结尾例如: <blockquote> &lt;OL&gt; <br> &lt;LI&gt;加菲尔德&lt;/ LI&gt; <br> &lt;LI&gt;西尔威斯特&lt;/ LI&gt; <br> &lt;/醇&gt; </blockquote>将创建一个编号列表“加菲猫”和“西尔维斯特”。 </section> <add><section id='description'> <add>HTML 有一个特定的元素用于创建有序列表<code>ordered lists(缩写 ol)</code>。 <add>有序列表以<code>&#60;ol&#62;</code>开始,中间包含一个或多个<code>&#60;li&#62;</code>元素,最后以<code>&#60;/ol&#62;</code>结尾。 <add> <add>例如: <add> <add>```html <add><ol> <add> <li>加菲猫</li> <add> <li>哆啦A梦</li> <add></ol> <add>``` <add> <add>将会创建一个包含加菲猫和哆啦A梦的有序列表。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">创建猫最讨厌的前三件事的有序列表。 </section> <add><section id='instructions'> <add>创建一个有序列表,内容是猫咪最讨厌的三件东西,内容可以任意指定。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 你应该有一个“猫讨厌的三件事”的有序列表: <del> testString: 'assert((/Top 3 things cats hate:/i).test($("ol").prev().text()), "You should have an ordered list for "Top 3 things cats hate:"");' <del> - text: 你应该有一个无序的列表“猫爱的东西:” <del> testString: 'assert((/Things cats love:/i).test($("ul").prev().text()), "You should have an unordered list for "Things cats love:"");' <del> - text: 你应该只有一个<code>ul</code>元素。 <del> testString: 'assert.equal($("ul").length, 1, "You should have only one <code>ul</code> element.");' <del> - text: 你应该只有一个<code>ol</code>元素。 <del> testString: 'assert.equal($("ol").length, 1, "You should have only one <code>ol</code> element.");' <del> - text: 你的<code>ul</code>元素中应该有三个<code>li</code>元素。 <del> testString: 'assert.equal($("ul li").length, 3, "You should have three <code>li</code> elements within your <code>ul</code> element.");' <del> - text: 你的<code>ol</code>元素中应该有三个<code>li</code>元素。 <del> testString: 'assert.equal($("ol li").length, 3, "You should have three <code>li</code> elements within your <code>ol</code> element.");' <del> - text: 确保你的<code>ul</code>元素有一个结束标记。 <del> testString: 'assert(code.match(/<\/ul>/g) && code.match(/<\/ul>/g).length === code.match(/<ul>/g).length, "Make sure your <code>ul</code> element has a closing tag.");' <del> - text: 确保您的<code>ol</code>元素具有结束标记。 <del> testString: 'assert(code.match(/<\/ol>/g) && code.match(/<\/ol>/g).length === code.match(/<ol>/g).length, "Make sure your <code>ol</code> element has a closing tag.");' <del> - text: '' <del> testString: 'assert(code.match(/<\/li>/g) && code.match(/<li>/g) && code.match(/<\/li>/g).length === code.match(/<li>/g).length, "Make sure your <code>li</code> element has a closing tag.");' <add> - text: '页面应该有一个无序列表,内容是猫咪最喜欢的三件东西。' <add> testString: assert((/猫咪最喜欢的三件东西:/i).test($("ul").prev().text())); <add> - text: '页面应该有一个有序列表,内容是猫咪最讨厌的三件东西。' <add> testString: assert((/猫咪最讨厌的三件东西:/i).test($("ol").prev().text())); <add> - text: '页面应该只有一个<code>ul</code>元素。' <add> testString: assert.equal($("ul").length, 1); <add> - text: '页面应该只有一个<code>ol</code>元素。' <add> testString: assert.equal($("ol").length, 1); <add> - text: '<code>ul</code>无序列表应该包含3个<code>li</code>条目。' <add> testString: assert.equal($("ul li").length, 3); <add> - text: '<code>ol</code>有序列表应该包含3个<code>li</code>元素。' <add> testString: assert.equal($("ol li").length, 3); <add> - text: '确保<code>ul</code>无序列表有结束标记。' <add> testString: assert(code.match(/<\/ul>/g) && code.match(/<\/ul>/g).length === code.match(/<ul>/g).length); <add> - text: '确保<code>ol</code>有序列表有结束标记。' <add> testString: assert(code.match(/<\/ol>/g) && code.match(/<\/ol>/g).length === code.match(/<ol>/g).length); <add> - text: '确保每个<code>li</code>条目都有结束标记。' <add> testString: assert(code.match(/<\/li>/g) && code.match(/<li>/g) && code.match(/<\/li>/g).length === code.match(/<li>/g).length); <add> - text: '无序列表里的 <code>li</code> 元素不应该为空。' <add> testString: $('ul li').each((i, val) => assert(val.textContent.replace(/\s/g, ''))); <add> - text: '有序列表里的 <code>li</code> 元素不应该为空。' <add> testString: $('ol li').each((i, val) => assert(!!val.textContent.replace(/\s/g, ''))); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <del> <add> <p>猫咪最讨厌的三件东西:</p> <add> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/declare-the-doctype-of-an-html-document.chinese.md <ide> id: 587d78aa367417b2b2512aed <ide> title: Declare the Doctype of an HTML Document <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 声明HTML文档的Doctype <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cra98AJ' <add>forumTopicId: 301095 <add>localeTitle: 声明 HTML 的文档类型 <ide> --- <ide> <ide> ## Description <del><section id="description">到目前为止,挑战涵盖了特定的HTML元素及其用途。但是,有一些元素可以为页面提供整体结构,并且应该包含在每个HTML文档中。在文档的顶部,您需要告诉浏览器您的页面使用的HTML版本。 HTML是一种不断发展的语言,并定期更新。大多数主流浏览器都支持最新的规范,即HTML5。但是,较旧的网页可能使用该语言的先前版本。您可以通过在第一行添加<code>&lt;!DOCTYPE ...&gt;</code>标记告诉浏览器此信息,其中“ <code>...</code> ”部分是HTML的版本。对于HTML5,您使用<code>&lt;!DOCTYPE html&gt;</code> 。的<code>!</code>和大写<code>DOCTYPE</code>很重要,特别是对于旧版浏览器。 <code>html</code>不区分大小写。接下来,HTML代码的其余部分需要包装在<code>html</code>标记中。开头<code>&lt;html&gt;</code>直接位于<code>&lt;!DOCTYPE html&gt;</code>行下方,结束<code>&lt;/html&gt;</code>位于页面末尾。这是页面结构的一个例子: <blockquote> &lt;!DOCTYPE html&gt; <br> &lt;HTML&gt; <br> &lt;! - 你的HTML代码在这里 - &gt; <br> &lt;/ HTML&gt; </blockquote></section> <add><section id='description'> <add>到目前为止,我们学习了一些特定的 HTML 标签,还有一些标签是用来组成网页的总体结构,并且它们在每个 HTML 文档中都能看到。 <add>在文档的顶部,你需要告诉浏览器你的网页用的 HTML 哪个版本。 HTML 是一个不停进化的语言,大部分浏览器都支持 HTML 的最新标准,也就是 HTML5。但是一些陈旧的网页可能使用的是 HTML 的旧版本。 <add>你可以通过<code>&lt;!DOCTYPE ...&gt;</code>来告诉浏览器你使用的是 HTML 的哪个版本,"<code>...</code>" 部分就是版本的数字信息。<code>&lt;!DOCTYPE html&gt;</code>对应的就是 HTML5。 <add><code>!</code>和大写的<code>DOCTYPE</code>是很重要的,特别是对于老的浏览器。但<code>html</code>大写小写都可以。 <add>所有的 HTML 代码都必须位于<code>html</code>标签中。其中<code>&lt;html&gt;</code>位于<code>&lt;!DOCTYPE html&gt;</code>的后面,<code>&lt;/html&gt;</code>位于网页的结尾。 <add>这是网页结构一个例子: <add> <add>```html <add><!DOCTYPE html> <add><html> <add> <!-- Your HTML code goes here --> <add></html> <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在代码编辑器中将HTML5的<code>DOCTYPE</code>标记添加到空白HTML文档的顶部。在它下面,添加包含<code>h1</code>元素的开始和结束<code>html</code>标记。标题可以包含任何文本。 </section> <add><section id='instructions'> <add>在代码编辑器的顶部添加一个<code>DOCTYPE(文档类型)</code>为 HTML5 的声明,然后添加一个<code>html</code>元素,再添加一个<code>h1</code>元素,标题的文本可以随意填。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的代码应包含<code>&lt;!DOCTYPE html&gt;</code>标记。 <del> testString: 'assert(code.match(/<!DOCTYPE\s+?html\s*?>/gi), "Your code should include a <code>&lt;!DOCTYPE html&gt;</code> tag.");' <del> - text: 应该有一个<code>html</code>元素。 <del> testString: 'assert($("html").length == 1, "There should be one <code>html</code> element.");' <del> - text: <code>html</code>标签应该包含一个<code>h1</code>元素。 <del> testString: 'assert(code.match(/<html>\s*?<h1>\s*?.*?\s*?<\/h1>\s*?<\/html>/gi), "The <code>html</code> tags should wrap around one <code>h1</code> element.");' <add> - text: '网页中应该包含<code>&lt;!DOCTYPE html&gt;</code>标签。' <add> testString: assert(code.match(/<!DOCTYPE\s+?html\s*?>/gi)); <add> - text: '网页中只有一个<code>html</code>元素。' <add> testString: assert($('html').length == 1); <add> - text: '<code>h1</code>元素应该位于<code>html</code>元素内部。' <add> testString: assert(code.match(/<html>\s*?<h1>\s*?.*?\s*?<\/h1>\s*?<\/html>/gi)); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/define-the-head-and-body-of-an-html-document.chinese.md <ide> id: 587d78aa367417b2b2512aec <ide> title: Define the Head and Body of an HTML Document <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 定义HTML文档的头部和正文 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cra9bfP' <add>forumTopicId: 301096 <add>localeTitle: 定义 HTML 文档的 head 和 body <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用<code>head</code>和<code>body</code>元素在<code>html</code>标记内的HTML文档中添加其他级别的组织。任何包含有关您网页信息的标记都会显示在<code>head</code>标记中。然后,任何带有页面内容(为用户显示的内容)的标记都会进入<code>body</code>标签。元数据元素(例如<code>link</code> , <code>meta</code> , <code>title</code>和<code>style</code> )通常位于<code>head</code>元素内。这是页面布局的示例: <blockquote> &lt;!DOCTYPE html&gt; <br> &lt;HTML&gt; <br> &lt;HEAD&gt; <br> &lt;! - 元数据元素 - &gt; <br> &lt;/ HEAD&gt; <br> &lt;BODY&gt; <br> &lt;! - 页面内容 - &gt; <br> &lt;/ BODY&gt; <br> &lt;/ HTML&gt; </blockquote></section> <add><section id='description'> <add><code>html</code>的结构主要分为两大部分:<code>head</code>、<code>body</code>。关于网页的描述都应该放入<code>head</code>标签,网页的内容都应该放入<code>body</code>标签。 <add>比如<code>link</code>、<code>meta</code>、<code>title</code>和<code>style</code>都应该放入<code>head</code>标签。 <add>这是网页布局的一个例子: <add> <add>```html <add><!DOCTYPE html> <add><html> <add> <head> <add> <!-- metadata elements --> <add> </head> <add> <body> <add> <!-- page contents --> <add> </body> <add></html> <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">编辑标记,以便有<code>head</code>和<code>body</code> 。 <code>head</code>元素应该只包含<code>title</code> , <code>body</code>元素应该只包含<code>h1</code>和<code>p</code> 。 </section> <add><section id='instructions'> <add>给网页添加<code>head</code>和<code>body</code>,<code>head</code>元素应该包含<code>title</code>,<code>body</code>元素应该包含<code>h1</code>和<code>p</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 页面上应该只有一个<code>head</code>元素。 <del> testString: 'assert($("head").length == 1, "There should be only one <code>head</code> element on the page.");' <del> - text: 页面上应该只有一个<code>body</code>元素。 <del> testString: 'assert($("body").length == 1, "There should be only one <code>body</code> element on the page.");' <del> - text: <code>head</code>元素应该是<code>html</code>元素的子元素。 <del> testString: 'assert($("html").children("head").length == 1, "The <code>head</code> element should be a child of the <code>html</code> element.");' <del> - text: <code>body</code>元素应该是<code>html</code>元素的子元素。 <del> testString: 'assert($("html").children("body").length == 1, "The <code>body</code> element should be a child of the <code>html</code> element.");' <del> - text: <code>head</code>元素应该包围<code>title</code>元素。 <del> testString: 'assert(code.match(/<head>\s*?<title>\s*?.*?\s*?<\/title>\s*?<\/head>/gi), "The <code>head</code> element should wrap around the <code>title</code> element.");' <del> - text: <code>body</code>元素应该环绕<code>h1</code>和<code>p</code>元素。 <del> testString: 'assert($("body").children("h1").length == 1 && $("body").children("p").length == 1, "The <code>body</code> element should wrap around both the <code>h1</code> and <code>p</code> elements.");' <add> - text: '网页应该只有一个<code>head</code>元素。' <add> testString: assert($('head').length == 1); <add> - text: '网页应该只有一个<code>body</code>元素。' <add> testString: assert($('body').length == 1); <add> - text: '<code>head</code>应该是<code>html</code>的子元素。' <add> testString: assert($('html').children('head').length == 1); <add> - text: '<code>body</code>应该是<code>html</code>的子元素。' <add> testString: assert($('html').children('body').length == 1); <add> - text: '<code>title</code>应该是<code>head</code>的子元素。' <add> testString: assert(code.match(/<head>\s*?<title>\s*?.*?\s*?<\/title>\s*?<\/head>/gi)); <add> - text: '<code>h1</code>和<code>p</code>都应该是<code>body</code>的子元素。' <add> testString: assert($('body').children('h1').length == 1 && $('body').children('p').length == 1); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <!DOCTYPE html> <ide> <html> <del> <title>The best page ever</title> <del> <del> <h1>The best page ever</h1> <del> <p>Cat ipsum dolor sit amet, jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed. Go into a room to decide you didn't want to be in there anyway. I like big cats and i can not lie kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Meow i could pee on this if i had the energy for slap owner's face at 5am until human fills food dish yet scamper. Knock dish off table head butt cant eat out of my own dish scratch the furniture. Make meme, make cute face. Sleep in the bathroom sink chase laser but pee in the shoe. Paw at your fat belly licks your face and eat grass, throw it back up kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <del></html> <del> <add> <title>世上最萌的猫咪</title> <add> <add> <h1>世上最萌的猫咪</h1> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。 在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <add></html> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/delete-html-elements.chinese.md <ide> id: bad87fed1348bd9aedf08833 <ide> title: Delete HTML Elements <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 删除HTML元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/ckK73C9' <add>forumTopicId: 17559 <add>localeTitle: 删除 HTML 元素 <ide> --- <ide> <ide> ## Description <del><section id="description">我们的手机没有太多的垂直空间。让我们删除不必要的元素,以便我们开始构建CatPhotoApp。 </section> <add><section id='description'> <add>手机的屏幕空间是有限的。 <add>让我们删除不必要的元素,开始设计我们的CatPhotoApp。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">删除你的<code>h1</code>元素,以便我们简化视图。 </section> <add><section id='instructions'> <add>任务:删除<code>h1</code>元素以简化视图。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 删除你的<code>h1</code>元素。 <del> testString: 'assert(!code.match(/<h1>/gi) && !code.match(/<\/h1>/gi), "Delete your <code>h1</code> element.");' <del> - text: 将<code>h2</code>元素留在页面上。 <del> testString: 'assert(code.match(/<h2>[\w\W]*<\/h2>/gi), "Leave your <code>h2</code> element on the page.");' <del> - text: 将<code>p</code>元素留在页面上。 <del> testString: 'assert(code.match(/<p>[\w\W]*<\/p>/gi), "Leave your <code>p</code> element on the page.");' <add> - text: '删除<code>h1</code>元素。' <add> testString: assert(($("h1").length == 0)); <add> - text: '保留<code>h2</code>元素。' <add> testString: assert(($("h2").length > 0)); <add> - text: '保留<code>p</code>元素。' <add> testString: assert(($("p").length > 0)); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> <h2>CatPhotoApp</h2> <ide> <del><p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <add><p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/fill-in-the-blank-with-placeholder-text.chinese.md <ide> id: bad87fee1348bd9aedf08833 <ide> title: Fill in the Blank with Placeholder Text <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用占位符文本填充空白 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cgR7Dc7' <add>forumTopicId: 18178 <add>localeTitle: 用占位符文本填充空白 <ide> --- <ide> <ide> ## Description <del><section id="description"> Web开发人员传统上使用<code>lorem ipsum text</code>作为占位符文本。 “lorem ipsum”文字是从古罗马的西塞罗(Cicero of Ancient Rome)的着名文章中随机剪下来的。自16世纪以来,Lorem ipsum文本被排版人员用作占位符文本,这种传统在网上继续存在。好吧,5个世纪足够长了。由于我们正在构建CatPhotoApp,因此我们使用名为<code>kitty ipsum text</code> 。 </section> <add><section id='description'> <add>Web 开发者通常用<a href='https://baike.baidu.com/item/Lorem%20ipsum/3684081'>lorem ipsum text</a>来做占位符,占位符就是占着位置的一些文字,没有实际意义。 <add>为什么叫<code>lorem ipsum text</code>呢?是因为<code>lorem ipsum</code>是古罗马西塞罗谚语的前两个单词。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">用这个kitty ipsum文本的前几个单词替换你的<code>p</code>元素里面的文字: <code>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</code> </section> <add><section id='instructions'> <add>把<code>p</code>元素的内容更换为:<code>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</code> <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 你的<code>p</code>元素应该包含所提供的<code>kitty ipsum text</code>的前几个单词。 <del> testString: 'assert.isTrue((/Kitty(\s)+ipsum/gi).test($("p").text()), "Your <code>p</code> element should contain the first few words of the provided <code>kitty ipsum text</code>.");' <add> - text: '<code>p</code>元素的内容必须包含<code>Monkey code</code>。' <add> testString: assert.isTrue((/Kitty(\s)+ipsum/gi).test($("p").text())); <ide> <ide> ``` <ide> <ide> tests: <ide> <h2>CatPhotoApp</h2> <ide> <ide> <p>Hello Paragraph</p> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.chinese.md <ide> id: bad87fee1348bd9aedf0887a <ide> title: Headline with the h2 Element <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 标题与h2元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gqf3' <add>forumTopicId: 18196 <add>localeTitle: 用 h2 元素代表副标题 <ide> --- <ide> <ide> ## Description <del><section id="description">在接下来的几节课中,我们将逐个构建一个HTML5猫照片网络应用程序。您将在此步骤中添加的<code>h2</code>元素将向网页添加第二级标题。此元素告诉浏览器您的网站结构。 <code>h1</code>元素通常用于主标题,而<code>h2</code>元素通常用于子标题。还有<code>h3</code> , <code>h4</code> , <code>h5</code>和<code>h6</code>元素表示不同级别的副标题。 </section> <add><section id='description'> <add>在接下来的几节课里,我们将会由浅入深地制作一个 CatPhotoApp。 <add>这节课将会引入<code>h2</code>元素。 <add>这些元素用来告诉浏览器,网站的结构是什么样子。<code>h1</code>元素通常被用作主标题,<code>h2</code>元素通常被用作副标题,还有<code>h3</code>、<code>h4</code>、<code>h5</code>、<code>h6</code>元素,它们分别用作不同级别的标题。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">添加<code>h2</code>标签,上面写着“CatPhotoApp”创建第二个HTML <code>element</code>你的“Hello World”的<code>h1</code>元素。 </section> <add><section id='instructions'> <add>在<code>h1</code>元素下面创建一个<code>h2</code>元素,元素内容为:<code>CatPhotoApp</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 创建一个<code>h2</code>元素。 <del> testString: 'assert(($("h2").length > 0), "Create an <code>h2</code> element.");' <del> - text: 确保您的<code>h2</code>元素具有结束标记。 <del> testString: 'assert(code.match(/<\/h2>/g) && code.match(/<\/h2>/g).length === code.match(/<h2>/g).length, "Make sure your <code>h2</code> element has a closing tag.");' <del> - text: 您的<code>h2</code>元素应该包含文本“CatPhotoApp”。 <del> testString: 'assert.isTrue((/cat(\s)?photo(\s)?app/gi).test($("h2").text()), "Your <code>h2</code> element should have the text "CatPhotoApp".");' <del> - text: 你的<code>h1</code>元素应该有“Hello World”文本。 <del> testString: 'assert.isTrue((/hello(\s)+world/gi).test($("h1").text()), "Your <code>h1</code> element should have the text "Hello World".");' <add> - text: '创建一个<code>h2</code>元素。' <add> testString: assert(($("h2").length > 0)); <add> - text: '<code>h2</code>元素应该有结束标记。' <add> testString: assert(code.match(/<\/h2>/g) && code.match(/<\/h2>/g).length === code.match(/<h2>/g).length); <add> - text: '<code>h2</code>元素的内容应为:<code>CatPhotoApp</code>。' <add> testString: assert.isTrue((/CatPhotoApp/gi).test($("h2").text())); <add> - text: '<code>h1</code>元素的内容应为:<code>Hello World</code>。' <add> testString: assert.isTrue((/hello(\s)+world/gi).test($("h1").text())); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> ```html <ide> <h1>Hello World</h1> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element.chinese.md <ide> id: bad87fee1348bd9aedf08801 <ide> title: Inform with the Paragraph Element <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 通知段落元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/ceZ7DtN' <add>forumTopicId: 18202 <add>localeTitle: 用 p 元素代表段落 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>p</code>元素是网站上段落文本的首选元素。 <code>p</code>是“段落”的缩写。你可以创建一个这样的段落元素: <code>&lt;p&gt;I&#39;m ap tag!&lt;/p&gt;</code> </section> <add><section id='description'> <add><code>p</code>是<code>paragraph</code>的缩写,通常用来创建一个段落,就和你写作文一样。 <add>你可以像这样创建一个段落: <add><code>&#60;p&#62;I'm a p tag!&#60;/p&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在<code>h2</code>元素下面创建一个<code>p</code>元素,并为其指定文本“Hello Paragraph”。 </section> <add><section id='instructions'> <add>在<code>h2</code>元素下面新增一个<code>p</code>元素,元素内容是:<code>Hello Paragraph</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 创建一个<code>p</code>元素。 <del> testString: 'assert(($("p").length > 0), "Create a <code>p</code> element.");' <del> - text: 你的<code>p</code>元素应该有文本“Hello Paragraph”。 <del> testString: 'assert.isTrue((/hello(\s)+paragraph/gi).test($("p").text()), "Your <code>p</code> element should have the text "Hello Paragraph".");' <del> - text: 确保您的<code>p</code>元素具有结束标记。 <del> testString: 'assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length, "Make sure your <code>p</code> element has a closing tag.");' <add> - text: '创建一个<code>p</code>元素。' <add> testString: assert(($("p").length > 0)); <add> - text: '<code>p</code>元素的内容应为:<code>Hello Paragraph</code>。' <add> testString: assert.isTrue((/hello(\s)+paragraph/gi).test($("p").text())); <add> - text: '<code>p</code>元素应该有结束标记。' <add> testString: assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h1>Hello World</h1> <ide> <h2>CatPhotoApp</h2> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.chinese.md <ide> id: bad87fee1348bd9aecf08801 <ide> title: Introduction to HTML5 Elements <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: HTML5元素简介 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cBkZGpt7' <add>forumTopicId: 301097 <add>localeTitle: HTML5 元素介绍 <ide> --- <ide> <ide> ## Description <del><section id="description"> HTML5引入了更具描述性的HTML标记。这些包括<code>header</code> , <code>footer</code> , <code>nav</code> , <code>video</code> , <code>article</code> , <code>section</code>和其他。这些标签使您的HTML更易于阅读,并且还有助于搜索引擎优化(SEO)和可访问性。 <code>main</code> HTML5标记可帮助搜索引擎和其他开发人员找到您网页的主要内容。 <strong>注意</strong> <br> “应用可访问性”部分介绍了许多新的HTML5标记及其优点。 </section> <add><section id='description'> <add>HTML5 引入了很多更具描述性的 HTML 元素,例如:<code>header</code>、<code>footer</code>、<code>nav</code>、<code>video</code>、<code>article</code>、<code>section</code>等等。 <add>这些元素让 HTML 更易读,同时有助于搜索引擎优化和无障碍访问。 <add><code>main</code>元素让搜索引擎和开发者瞬间就能找到网页的主要内容。 <add>举个栗子, 下面的 <code>main</code> 元素嵌套了两个子元素: <add> <add>```html <add><main> <add> <h1>Hello World</h1> <add> <p>Hello Paragraph</p> <add></main> <add>``` <add> <add><strong>提示:</strong>在后面的应用无障碍课程中我们会接触到更多新的 HTML5 元素,以及明白它们的用处。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">创建第二个<code>p</code>现有的后件<code>p</code>具有以下的小猫存有文本元素: <code>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</code>用开头和关闭<code>main</code>标签包装段落。 </section> <add><section id='instructions'> <add>在现有的段落下创建一个新的段落,段落内容为:<code>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</code> <add>在第一个段落前添加<code>&#60main&#62</code>,在第二个段落后添加<code>&#60/main&#62</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 使用Kitty Ipsum文本需要2个<code>p</code>元素。 <del> testString: 'assert($("p").length > 1, "You need 2 <code>p</code> elements with Kitty Ipsum text.");' <del> - text: 确保每个<code>p</code>元素都有一个结束标记。 <del> testString: 'assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length, "Make sure each of your <code>p</code> elements has a closing tag.");' <del> - text: 你的<code>p</code>元素应该包含所提供的额外<code>kitty ipsum text</code>的前几个单词。 <del> testString: 'assert.isTrue((/Purr\s+jump\s+eat/gi).test($("p").text()), "Your <code>p</code> element should contain the first few words of the provided additional <code>kitty ipsum text</code>.");' <del> - text: 您的代码应该有一个<code>main</code>元素。 <del> testString: 'assert($("main").length === 1, "Your code should have one <code>main</code> element.");' <del> - text: <code>main</code>元素应该有两个段落元素作为子元素。 <del> testString: 'assert($("main").children("p").length === 2, "The <code>main</code> element should have two paragraph elements as children.");' <del> - text: 开头<code>main</code>标记应位于第一个段落标记之前。 <del> testString: 'assert(code.match(/<main>\s*?<p>/g), "The opening <code>main</code> tag should come before the first paragraph tag.");' <del> - text: 结束<code>main</code>标记应该在第二个结束段标记之后。 <del> testString: 'assert(code.match(/<\/p>\s*?<\/main>/g), "The closing <code>main</code> tag should come after the second closing paragraph tag.");' <add> - text: '页面中应该有两个段落。' <add> testString: assert($("p").length > 1, '页面中应该有两个段落。'); <add> - text: '确保每个段落都有结束标记。' <add> testString: assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length); <add> - text: '新建的段落应该包含关键词:猫咪。' <add> testString: assert.isTrue((/猫咪/).test($("p").text())); <add> - text: '代码中应该包含<code>main</code>元素。' <add> testString: assert($('main').length === 1); <add> - text: '<code>main</code>元素应有两个 <code>p</code>元素作为它的子元素。' <add> testString: assert($("main").children("p").length === 2); <add> - text: '开始标记<code><main></code>应位于第一个段落之前。' <add> testString: assert(code.match(/<main>\s*?<p>/g)); <add> - text: '结束标记<code></main></code>应位于第二段落之后。' <add> testString: assert(code.match(/<\/p>\s*?<\/main>/g)); <ide> <ide> ``` <ide> <ide> tests: <ide> <div id='html-seed'> <ide> <ide> ```html <del><h2>CatPhotoApp</h2> <del> <del><p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <add><h2>猫咪</h2> <ide> <add><p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.chinese.md <ide> id: bad87fee1348bd9aedf08816 <ide> title: Link to External Pages with Anchor Elements <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 链接到具有锚元素的外部页面 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/c8EkncB' <add>forumTopicId: 18226 <add>localeTitle: 用 a 实现网页间的跳转 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以使用<code>anchor</code>元素链接到网页外部的内容。 <code>anchor</code>元素需要一个名为<code>href</code>属性的目标Web地址。他们还需要锚文本。这是一个例子: <code>&lt;a href=&quot;https://freecodecamp.org&quot;&gt;this links to freecodecamp.org&lt;/a&gt;</code>然后你的浏览器会显示文本<strong>“这个链接到freecodecamp.org”</strong>作为你可以点击的链接。该链接将带您到网址<strong>https://www.freecodecamp.org</strong> 。 </section> <add><section id='description'> <add>你可以用 <code>a</code>(Anchor,简写 a)来实现网页间的跳转。 <add><code>a</code> 需要一个<code>href</code>属性指向目的地,它还需要有 <code>a</code> 文本,例如: <add><code>&#60;a href="https://freecodecamp.org">传送至 freecodecamp.org&#60;/a&#62;</code> <add>然后你的浏览器会显示一个可以点击的文本,点击该文本就会跳转到<code>https://freecodecamp.org</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">创建一个链接到<code>http://freecatphotoapp.com</code> <code>a</code>元素,并将“猫照片”作为其<code>anchor text</code> 。 </section> <add><section id='instructions'> <add>创建一个 <code>a</code>,它的<code>href</code>属性为<code>http://freecatphotoapp.com</code> ,它的文本为<code>cat photos</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 你<code>a</code>元素应该有“猫照片”的<code>anchor text</code> 。 <del> testString: 'assert((/cat photos/gi).test($("a").text()), "Your <code>a</code> element should have the <code>anchor text</code> of "cat photos".");' <del> - text: '你需要一个链接到<code>http://freecatphotoapp .com</code> <code>a</code>元素' <del> testString: 'assert(/http:\/\/(www\.)?freecatphotoapp\.com/gi.test($("a").attr("href")), "You need an <code>a</code> element that links to <code>http&#58;//freecatphotoapp<wbr>.com</code>");' <del> - text: 确保您<code>a</code>元素具有结束标记。 <del> testString: 'assert(code.match(/<\/a>/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length, "Make sure your <code>a</code> element has a closing tag.");' <add> - text: '<code>a</code>元素的 <code>a</code> 文本应为:<code>cat photos</code>。' <add> testString: assert((/cat photos/gi).test($("a").text())); <add> - text: '<code>a</code>元素的<code>href</code>属性应为:"<code>http&#58;//freecatphotoapp<wbr>.com</code>"。' <add> testString: 'assert(/http:\/\/(www\.)?freecatphotoapp\.com/gi.test($("a").attr("href")));' <add> - text: '确保<code>a</code>元素有结束标记。' <add> testString: assert(code.match(/<\/a>/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <del> <del> <del> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add> <add> <add> <add> <img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/link-to-internal-sections-of-a-page-with-anchor-elements.chinese.md <ide> id: bad88fee1348bd9aedf08816 <ide> title: Link to Internal Sections of a Page with Anchor Elements <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 链接到具有锚元素的页面的内部部分 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cyrDRUL' <add>forumTopicId: 301098 <add>localeTitle: 用 a 实现网页内部跳转 <ide> --- <ide> <ide> ## Description <del><section id="description">锚元素还可用于创建内部链接以跳转到网页中的不同部分。要创建内部链接,请将链接的<code>href</code>属性分配给哈希符号<code>#</code>加上要在内部链接到的元素的<code>id</code>属性值,通常在页面的下方。然后,您需要将相同的<code>id</code>属性添加到要链接的元素。 <code>id</code>是唯一描述元素的属性。下面是内部锚链接及其目标元素的示例: <blockquote> &lt;a href=&quot;#contacts-header&quot;&gt;通讯录&lt;/a&gt; <br> ... <br> &lt;h2 id =“contacts-header”&gt;通讯录&lt;/ h2&gt; </blockquote>当用户单击“联系人”链接时,他们将被带到具有“ <b>联系人”</b>标题元素的网页部分。 </section> <add><section id='description'> <add><code>a</code> 元素还可以用来实现页面内不同区域的跳转,只需要把<code>a</code>元素的<code>href</code>值设置为井号<code>#</code>加欲跳转区域对应的<code>id</code>值即可。<code>id</code>是描述网页元素的一个属性,它的值在整个页面中唯一。 <add>下面是用来创建内部 <code>a</code> 的例子: <add> <add>```html <add><a href="#contacts-header">Contacts</a> <add>... <add><h2 id="contacts-header">Contacts</h2> <add>``` <add> <add>当用户点击了<code>Contacts</code>链接,页面就会跳转到网页的<b>Contacts</b>区域。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">通过将<code>href</code>属性更改为“#footer”并将文本从“cat photos”更改为“Jump to Bottom”,将外部链接更改为内部链接。从锚标记中删除<code>target=&quot;_blank&quot;</code>属性,因为这会导致链接的文档在新窗口选项卡中打开。然后将值为“footer”的<code>id</code>属性添加到页面底部的<code>&lt;footer&gt;</code>元素。 </section> <add><section id='instructions'> <add>通过修改<code>href</code>属性为<code>#footer</code>来更改外部链接为内部链接,同时修改文本<code>cat photos</code>为<code>Jump to Bottom</code>。 <add>移除 target="_blank" 属性,它会使得链接在新标签页中打开。 <add>然后添加一个<code>&lt;footer&gt;</code>元素,它的<code>id</code>值为<code>footer</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的页面上应该只有一个锚标记。 <del> testString: 'assert($("a").length == 1, "There should be only one anchor tag on your page.");' <del> - text: 页面上应该只有一个<code>footer</code>标记。 <del> testString: 'assert($("footer").length == 1, "There should be only one <code>footer</code> tag on your page.");' <del> - text: '<code>a</code>标签的<code>href</code>属性应设置为“#footer”。' <del> testString: 'assert($("a").eq(0).attr("href") == "#footer", "The <code>a</code> tag should have an <code>href</code> attribute set to "#footer".");' <del> - text: <code>a</code>标签不应具有<code>target</code>属性 <del> testString: 'assert(typeof $("a").eq(0).attr("target") == typeof undefined || $("a").eq(0).attr("target") == true, "The <code>a</code> tag should not have a <code>target</code> attribute");' <del> - text: <code>a</code>文本应该是“跳到底部”。 <del> testString: 'assert($("a").eq(0).text().match(/Jump to Bottom/gi), "The <code>a</code> text should be "Jump to Bottom".");' <del> - text: <code>footer</code>标记的<code>id</code>属性应设置为“footer”。 <del> testString: 'assert($("footer").eq(0).attr("id") == "footer", "The <code>footer</code> tag should have an <code>id</code> attribute set to "footer".");' <add> - text: '页面中应该只有一个 <code>a</code> 。' <add> testString: assert($('a').length == 1); <add> - text: '页面中应该只有一个<code>footer</code>元素。' <add> testString: assert($('footer').length == 1); <add> - text: '<code>a</code> 的<code>href</code>属性应为 "#footer"。' <add> testString: assert($('a').eq(0).attr('href') == "#footer"); <add> - text: '<code>a</code> 不应该有<code>target</code>属性。' <add> testString: assert(typeof $('a').eq(0).attr('target') == typeof undefined || $('a').eq(0).attr('target') == true); <add> - text: '<code>a</code> 的文本应为<code>Jump to Bottom</code>。' <add> testString: assert($('a').eq(0).text().match(/Jump to Bottom/gi)); <add> - text: '<code>footer</code>元素的<code>id</code>属性应为 "footer"。' <add> testString: assert($('footer').eq(0).attr('id') == "footer"); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <add> <ide> <a href="http://freecatphotoapp.com" target="_blank">cat photos</a> <del> <del> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <del> <p>Meowwww loved it, hated it, loved it, hated it yet spill litter box, scratch at owner, destroy all furniture, especially couch or lay on arms while you're using the keyboard. Missing until dinner time toy mouse squeak roll over. With tail in the air lounge in doorway. Man running from cops stops to pet cats, goes to jail.</p> <del> <p>Intently stare at the same spot poop in the plant pot but kitten is playing with dead mouse. Get video posted to internet for chasing red dot leave fur on owners clothes meow to be let out and mesmerizing birds leave fur on owners clothes or favor packaging over toy so purr for no reason. Meow to be let out play time intently sniff hand run outside as soon as door open yet destroy couch.</p> <del> <add> <add> <img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。 养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。 在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。 在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。 养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <add> <ide> </main> <del> <add> <ide> <footer>Copyright Cat Photo App</footer> <del> <ide> ``` <ide> <ide> </div> <ide> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/make-dead-links-using-the-hash-symbol.chinese.md <ide> id: bad87fee1348bd9aedf08817 <ide> title: Make Dead Links Using the Hash Symbol <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用哈希符号制作死链接 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cMdkytL' <add>forumTopicId: 18230 <add>localeTitle: '用 # 号来创建链接占位符' <ide> --- <ide> <ide> ## Description <del><section id="description">有时你想添加<code>a</code>元素到你的网站,你知道他们会链接之前。当您使用<code>JavaScript</code>更改链接的行为时,这也很方便,我们将在稍后了解。 </section> <add><section id='description'> <add>有时你想为网站添加一个 <code>a</code>,但如果你还不确定要将它链接到哪儿,这时可以使用链接占位符。 <add>在后面的课程中我们会学到:如何轻松通过<code>JavaScript</code>更改链接指向的地址。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <code>href</code>属性的当前值是指向“http://freecatphotoapp.com”的链接。将<code>href</code>属性值替换为<code>#</code> (也称为哈希符号)以创建死链接。例如: <code>href=&quot;#&quot;</code> </section> <add><section id='instructions'> <add><code>href</code>属性的当前值是指向 "http://freecatphotoapp.com",将<code>href</code>属性的值替换为<code>#</code>,就可以创建固定链接。 <add>例如: <code>href="#"</code> <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您<code>a</code>元素应该是一个死链接, <code>href</code>属性的值设置为“#”。 <del> testString: 'assert($("a").attr("href") === "#", "Your <code>a</code> element should be a dead link with the value of the <code>href</code> attribute set to "#".");' <add> - text: '<code>a</code> 的<code>href</code>属性应为 "#"。' <add> testString: assert($("a").attr("href") === "#"); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="http://freecatphotoapp.com" target="_blank">cat photos</a>.</p> <del> <del> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add> <p>点击这里可以获取更多<a href="http://freecatphotoapp.com" target="_blank">猫咪图片</a>。</p> <add> <add> <img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.chinese.md <ide> id: bad87fee1348bd9aede08817 <ide> title: Nest an Anchor Element within a Paragraph <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 在段落中嵌入锚元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cb6k8Cb' <add>forumTopicId: 18244 <add>localeTitle: 将 a 嵌套在段落中 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以在其他文本元素中嵌套链接。 <blockquote> &lt;P&gt; <br>这是一个&lt;a target=&quot;_blank&quot; href=&quot;http://freecodecamp.org&quot;&gt; freecodecamp.org &lt;/a&gt;的链接供您关注。 <br> &lt;/ p&gt; </blockquote>让我们分解示例:普通文本包含在<code>p</code>元素中: <br> <code>&lt;p&gt; Here&#39;s a ... for you to follow. &lt;/p&gt;</code>接下来是<code>anchor</code>元素<code>&lt;a&gt;</code> (需要结束标记<code>&lt;/a&gt;</code> ): <br> <code>&lt;a&gt; ... &lt;/a&gt;</code> <code>target</code>是一个锚标记属性,指定打开链接的位置,值<code>&quot;_blank&quot;</code>指定在新标签中打开链接<code>href</code>是一个锚标记属性,其中包含URL地址链接: <br> <code>&lt;a href=&quot;http://freecodecamp.org&quot;&gt; ... &lt;/a&gt;</code>在名为<code>anchor text</code>的锚元素中,文本<strong>“链接到freecodecamp.org”</strong>将显示一个单击的链接: <br> <code>&lt;a href=&quot; ... &quot;&gt;link to freecodecamp.org&lt;/a&gt;</code>示例的最终输出如下所示: <br><p>这是<a target="_blank" href="http://freecodecamp.org">freecodecamp.org</a>的<a target="_blank" href="http://freecodecamp.org">链接</a>供您关注。 </p></section> <add><section id='description'> <add> <add>你可以在其他文本元素内嵌套链接。 <add> <add>```html <add><p> <add> Here's a <a target="_blank" href="http://freecodecamp.org"> link to freecodecamp.org</a> for you to follow. <add></p> <add>``` <add> <add>让我们来分解这个例子: <add>通常,文本是被包裹在<code>p</code>段落内:<br><code>&#60;p&#62; Here's a ... for you to follow. &#60;/p&#62;</code> <add>接下来是<code>anchor</code> <code>a</code> <code>&#60;a&#62;</code>(需要结束标记 <code>&#60;/a&#62;</code>):<br> <code>&#60;a&#62; ... &#60;/a&#62;</code> <add><code>target</code>是 <code>a</code> 的一个属性,用来指定链接的打开方式。属性值 <code>"_blank"</code> 的意思是链接会在新标签页打开。 <add><code>href</code>是 <code>a</code> 的另一个属性:用来指定链接的 URL:<br><code>&#60;a href="https://freecodecamp.org"> ... &#60;/a&#62;</code> <add> <code>a</code> 元素内的文本:<strong>"link to freecodecamp.org"</strong>,会显示为一个可以点击的链接:<br> <code>&#60;a href=" ... "&#62;link to freecodecamp.org&#60;/a&#62;</code> <add>例子的最后输出将会是这样:<br><p>Here's a <a target="_blank" href="http://freecodecamp.one"> link to freecodecamp.org</a> for you to follow.</p> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">现在,鸟巢现有的<code>a</code>新元素内<code>p</code>元(刚过现有的<code>main</code>元素)。新段落的文本应显示“查看更多猫照片”,其中“猫照片”是一个链接,其余文本是纯文本。 </section> <add><section id='instructions'> <add> <add>用一个段落(<code>p</code>)标签来包裹<code>main</code>元素里的<code>a</code>节点。新段落的文本为:“View more cat photos”,其中 "cat photos" 是一个链接,其余是纯文本。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '您需要一个链接到“http://freecatphotoapp.com” <code>a</code>元素。' <del> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").length > 0 || $("a[href=\"http://www.freecatphotoapp.com\"]").length > 0), "You need an <code>a</code> element that links to "http://freecatphotoapp.com".");' <del> - text: 你<code>a</code>元素应该有“猫照片”的锚文本 <del> testString: 'assert($("a").text().match(/cat\sphotos/gi), "Your <code>a</code> element should have the anchor text of "cat photos"");' <del> - text: 创建一个新的<code>p</code>周围的元素<code>a</code>元素。 HTML代码中应至少包含3个<code>p</code>标签。 <del> testString: 'assert($("p") && $("p").length > 2, "Create a new <code>p</code> element around your <code>a</code> element. There should be at least 3 total <code>p</code> tags in your HTML code.");' <del> - text: 您<code>a</code>元素应嵌套在新的<code>p</code>元素中。 <del> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().is("p") || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().is("p")), "Your <code>a</code> element should be nested within your new <code>p</code> element.");' <del> - text: 你的<code>p</code>元素应该有“查看更多”文本(后面有一个空格)。 <del> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi) || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi)), "Your <code>p</code> element should have the text "View more " (with a space after it).");' <del> - text: 您的<code>a</code>元素<em>不</em>应该有文字“查看更多”。 <del> testString: 'assert(!$("a").text().match(/View\smore/gi), "Your <code>a</code> element should <em>not</em> have the text "View more".");' <del> - text: 确保每个<code>p</code>元素都有一个结束标记。 <del> testString: 'assert(code.match(/<\/p>/g) && code.match(/<p/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length, "Make sure each of your <code>p</code> elements has a closing tag.");' <del> - text: 确保每个的<code>a</code>元素具有一个结束标记。 <del> testString: 'assert(code.match(/<\/a>/g) && code.match(/<a/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length, "Make sure each of your <code>a</code> elements has a closing tag.");' <add> - text: '你需要一个指向 "http://freecatphotoapp.com" 的 <code>a</code> 。' <add> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").length > 0 || $("a[href=\"http://www.freecatphotoapp.com\"]").length > 0));' <add> - text: '<code>a</code> 的文本应为:cat photos。' <add> testString: assert($("a").text().match(/cat\sphotos/gi)); <add> - text: '在 <code>a</code> 的外部创建一个新段落,这样页面就有 3 个段落了。' <add> testString: assert($("p") && $("p").length > 2); <add> - text: '<code>a</code> 应嵌套在新段落内。' <add> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().is("p") || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().is("p")));' <add> - text: '段落应该包含文本 View more(记得 more 后面有一个空格)。' <add> testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi) || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi)));' <add> - text: '<code>a</code> 不应该包含文本 View more。' <add> testString: assert(!$("a").text().match(/View\smore/gi)); <add> - text: '确保每个段落有结束标记。' <add> testString: assert(code.match(/<\/p>/g) && code.match(/<p/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length); <add> - text: '确保每个段落有结束标记。' <add> testString: assert(code.match(/<\/a>/g) && code.match(/<a/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <add> <ide> <a href="http://freecatphotoapp.com" target="_blank">cat photos</a> <del> <del> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add> <add> <img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-many-elements-within-a-single-div-element.chinese.md <ide> id: bad87fee1348bd9aede08835 <ide> title: Nest Many Elements within a Single div Element <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 在单个div元素中嵌套许多元素 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cNW4kC3' <add>forumTopicId: 18246 <add>localeTitle: 元素嵌套 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>div</code>元素也称为除法元素,是其他元素的通用容器。 <code>div</code>元素可能是所有人中最常用的HTML元素。就像任何其他非自闭元素一样,您可以使用<code>&lt;div&gt;</code>打开<code>div</code>元素,然后使用<code>&lt;/div&gt;</code>其关闭到另一行。 </section> <add><section id='description'> <add><code>div</code>元素,也叫 Content Division Element(内容划分元素)元素,是一个包裹其他元素的通用容器。 <add>它也是 HTML 中出现频率最高的元素。 <add>和其他普通元素一样,你可以用<code>&#60;div&#62;</code>来标记一个<code>div</code>元素的开始,用<code>&#60;/div&#62;</code>来标记一个<code>div</code>元素的结束。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">嵌套你的“猫喜欢的东西”和“猫讨厌的东西”列出了一个<code>div</code>元素。提示:尝试将您的开始<code>div</code>标记放在“Things cats love” <code>p</code>元素上方,并将结束的<code>div</code>标记放在结束的<code>ol</code>标记之后,这样两个列表都在一个<code>div</code> 。 </section> <add><section id='instructions'> <add>把无序列表、有序列表和段落都嵌套进同一个<code>div</code>元素。 <add>提示:你可以在第一个<code>&#60p&#62</code>之前插入<code>div</code>开始标记,在<code>&#60/ol&#62</code>之后插入<code>div</code>结束标记,这样,所有的列表都位于<code>div</code>之内。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 将<code>p</code>元素嵌套在<code>div</code>元素中。 <del> testString: 'assert($("div").children("p").length > 1, "Nest your <code>p</code> elements inside your <code>div</code> element.");' <del> - text: 将您的<code>ul</code>元素<code>div</code>元素中。 <del> testString: 'assert($("div").children("ul").length > 0, "Nest your <code>ul</code> element inside your <code>div</code> element.");' <del> - text: 将您的<code>ol</code>元素<code>div</code>元素中。 <del> testString: 'assert($("div").children("ol").length > 0, "Nest your <code>ol</code> element inside your <code>div</code> element.");' <del> - text: 确保你的<code>div</code>元素有一个结束标记。 <del> testString: 'assert(code.match(/<\/div>/g) && code.match(/<\/div>/g).length === code.match(/<div>/g).length, "Make sure your <code>div</code> element has a closing tag.");' <add> - text: '把所有的<code>p</code>元素嵌入<code>div</code>元素中。' <add> testString: assert($("div").children("p").length > 1); <add> - text: '把<code>ul</code>元素嵌入<code>div</code>元素中。' <add> testString: assert($("div").children("ul").length > 0); <add> - text: '把<code>ol</code>元素嵌入<code>div</code>元素中。' <add> testString: assert($("div").children("ol").length > 0); <add> - text: '确保<code>div</code>元素有结束标记。' <add> testString: assert(code.match(/<\/div>/g) && code.match(/<\/div>/g).length === code.match(/<div>/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <del> <add> <ide> <form action="/submit-cat-photo"> <del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label> <del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br> <del> <label><input type="checkbox" name="personality" checked> Loving</label> <del> <label><input type="checkbox" name="personality"> Lazy</label> <del> <label><input type="checkbox" name="personality"> Energetic</label><br> <del> <input type="text" placeholder="cat photo URL" required> <del> <button type="submit">Submit</button> <add> <label><input type="radio" name="indoor-outdoor">室内</label> <add> <label><input type="radio" name="indoor-outdoor">室外</label><br> <add> <label><input type="checkbox" name="personality">忠诚</label> <add> <label><input type="checkbox" name="personality">懒惰</label> <add> <label><input type="checkbox" name="personality">积极</label><br> <add> <input type="text" placeholder="猫咪图片地址" required> <add> <button type="submit">提交</button> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/say-hello-to-html-elements.chinese.md <ide> id: bd7123c8c441eddfaeb5bdef <ide> title: Say Hello to HTML Elements <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 向HTML Elements说你好 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cE8Gpt2' <add>forumTopicId: 18276 <add>localeTitle: 向 HTML 元素问好 <ide> --- <ide> <ide> ## Description <del><section id="description">欢迎来到freeCodeCamp的HTML编码挑战。这些将逐步引导您完成Web开发。首先,您将首先使用HTML构建一个简单的网页。您可以在<code>code editor</code>编辑<code>code</code> ,该<code>code editor</code>嵌入到此网页中。您是否在代码编辑器中看到<code>&lt;h1&gt;Hello&lt;/h1&gt;</code> ?这是一个HTML <code>element</code> 。大多数HTML元素都有一个<code>opening tag</code>和一个<code>closing tag</code> 。打开标记如下所示: <code>&lt;h1&gt;</code>结束标记如下所示: <code>&lt;/h1&gt;</code>开始标记和结束标记之间的唯一区别是结束标记的左括号后面的正斜杠。每个挑战都有可以随时单击“运行测试”按钮运行的测试。当您通过所有测试时,系统会提示您提交解决方案并转到下一个编码挑战。 </section> <add><section id='description'> <add>欢迎参加 freeCodeCamp 的编程挑战赛,这些挑战将会帮助你逐步掌握 Web 开发。 <add>HTML 是英文 Hyper Text Markup Language(超文本标记语言)的缩写。首先,我们来用 HTML 制作一个简单的网页,你可以直接在网页内置的代码编辑器中编辑代码。 <add>你看到代码编辑器中的<code>&#60;h1&#62;Hello&#60;/h1&#62;</code>了吗? 那就是一个 HTML 元素。 <add>大部分 HTML 元素都有一个<code>开始标记</code>和一个<code>结束标记</code>。 <add>开始标记像这样:<code>&#60;h1&#62;</code> <add>结束标记像这样:<code>&#60;/h1&#62;</code> <add>开始标记和结束标记的唯一区别就是结束标记多了一个<code>/</code>。 <add>每个挑战都有测试,任何时候点击<strong>运行测试</strong>按钮就可以运行测试。如果代码通过测试,将会弹出一个窗口,你就可以进入下一个挑战。反之,测试区会显示你没有通过测试的原因。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">要通过此挑战的测试,请将<code>h1</code>元素的文本更改为“Hello World”。 </section> <add><section id='instructions'> <add>请把<code>h1</code>元素的内容改为:<code>Hello World</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 你的<code>h1</code>元素应该有“Hello World”文本。 <del> testString: 'assert.isTrue((/hello(\s)+world/gi).test($("h1").text()), "Your <code>h1</code> element should have the text "Hello World".");' <add> - text: '<code>h1</code>元素的内容应该为:<code>Hello World</code>。' <add> testString: assert.isTrue((/^hello(\s)+world$/gi).test($('h1').text())); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> ```html <ide> <h1>Hello</h1> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/turn-an-image-into-a-link.chinese.md <ide> id: bad87fee1348bd9aedf08820 <ide> title: Turn an Image into a Link <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 将图像转换为链接 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cRdBnUr' <add>forumTopicId: 18327 <add>localeTitle: 给图片添加链接 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以通过嵌套在他们做出元素融入链接<code>a</code>元素。鸟巢的内部图像<code>a</code>元素。这是一个例子: <code>&lt;a href=&quot;#&quot;&gt;&lt;img src=&quot;https://bit.ly/fcc-running-cats&quot; alt=&quot;Three kittens running towards the camera.&quot;&gt;&lt;/a&gt;</code>记得使用<code>#</code>为你的<code>a</code>元素的<code>href</code>为了把它变成一个死链接属性。 </section> <add><section id='description'> <add>你可以通过把元素嵌套进 <code>a</code> 里使其变成一个链接。 <add>把你的图片嵌套进 <code>a</code>。举例如下: <add><code>&#60;a href="#"&#62;&#60;img src="http://cdn.freecodecamp.cn/running-cats.jpg" alt="三只萌萌的小猫"&#62;&#60;/a&#62;</code> <add>把 <code>a</code> 的<code>href</code>属性设置为<code>#</code>,就可以创建固定链接。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将现有图像元素放在锚元素中。完成此操作后,使用光标将鼠标悬停在图像上。光标的正常指针应该成为链接点击指针。这张照片现在是一个链接。 </section> <add><section id='instructions'> <add>把现存的图片嵌套进 <code>a</code> 中。 <add>当鼠标悬停在图片上时,鼠标的光标如果从箭头指针变成手形指针,那么此时图片就是一个链接了。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 巢现有<code>img</code>一个内元件<code>a</code>元件。 <del> testString: 'assert($("a").children("img").length > 0, "Nest the existing <code>img</code> element within an <code>a</code> element.");' <del> - text: '您<code>a</code>元素应该是<code>href</code>属性设置为<code>#</code>的死链接。' <del> testString: 'assert(new RegExp("#").test($("a").children("img").parent().attr("href")), "Your <code>a</code> element should be a dead link with a <code>href</code> attribute set to <code>#</code>.");' <del> - text: 确保每个的<code>a</code>元素具有一个结束标记。 <del> testString: 'assert(code.match(/<\/a>/g) && code.match(/<a/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length, "Make sure each of your <code>a</code> elements has a closing tag.");' <add> - text: '把现存的图片嵌套进 <code>a</code> 中。' <add> testString: assert($("a").children("img").length > 0); <add> - text: '<code>a</code> 的<code>href</code>属性应为<code>#</code>。' <add> testString: assert(new RegExp("#").test($("a").children("img").parent().attr("href"))); <add> - text: '确保每个 <code>a</code> 都有结束标记。' <add> testString: assert(code.match(/<\/a>/g) && code.match(/<a/g) && code.match(/<\/a>/g).length === code.match(/<a/g).length); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> <del> <del> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <del> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"> <add> <add> <p>在大家心目中,猫是慵懒和可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p> <add> <p>养猫有的时候,就是介于爱与恨之间,当你钦羡别人萌宠这么可爱的时候,你一定没有想过,猫咪会到处掉毛,甚至会屯老鼠,啃鞋子,用爪子爬门,你不理它,它就挠你,你要对它发脾气,它会比你更来劲。所以,猫咪慎入,没有一定的准备,切勿随便去侍养动物。它们一旦认定你了,你就是它们的主人,如果你抛弃它们,它们必定心中重创。</p> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/uncomment-html.chinese.md <ide> id: bad87fee1348bd9aedf08802 <ide> title: Uncomment HTML <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 取消注释HTML <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cBmG9T7' <add>forumTopicId: 18329 <add>localeTitle: 去除 HTML 的注释 <ide> --- <ide> <ide> ## Description <del><section id="description">注释是一种方法,您可以在代码中为其他开发人员留下注释,而不会影响显示给最终用户的结果输出。注释也是使代码处于非活动状态而不必完全删除它的便捷方式。 HTML中的注释以<code>&lt;!--</code>开头,以<code>--&gt;</code>结尾</section> <add><section id='description'> <add>注释的作用是给代码添加一些说明,方便团队合作或日后自己查看,但又不影响代码本身。 <add>注释的另一个用途就是在不删除代码的前提下,让代码不起作用。 <add>在 HTML 中,注释的开始标记是<code>&#60;!--</code>,结束标记是<code>--&#62;</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">取消注释你的<code>h1</code> , <code>h2</code>和<code>p</code>元素。 </section> <add><section id='instructions'> <add>现在我们反其道而行之,去掉<code>h1</code>元素、<code>h2</code>元素、<code>p</code>元素的注释。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 通过取消注释,使您的<code>h1</code>元素在您的页面上可见。 <del> testString: 'assert($("h1").length > 0, "Make your <code>h1</code> element visible on your page by uncommenting it.");' <del> - text: 通过取消注释,使您的<code>h2</code>元素在您的页面上可见。 <del> testString: 'assert($("h2").length > 0, "Make your <code>h2</code> element visible on your page by uncommenting it.");' <del> - text: 通过取消注释,可以在页面上显示您的<code>p</code>元素。 <del> testString: 'assert($("p").length > 0, "Make your <code>p</code> element visible on your page by uncommenting it.");' <del> - text: 请务必删除所有尾随注释标记,即<code>--&gt;</code> 。 <del> testString: 'assert(!/[^fc]-->/gi.test(code.replace(/ *<!--[^fc]*\n/g,"")), "Be sure to delete all trailing comment tags&#44; i.e. <code>--&#62;</code>.");' <add> - text: '确保网页中能看到<code>h1</code>元素。' <add> testString: assert($("h1").length > 0); <add> - text: '确保网页中能看到<code>h2</code>元素。' <add> testString: assert($("h2").length > 0); <add> - text: '确保网页中能看到<code>p</code>元素。' <add> testString: assert($("p").length > 0); <add> - text: '确保删除了注释的结束标记<code>--&#62;</code>。' <add> testString: assert(!/[^fc]-->/gi.test(code.replace(/ *<!--[^fc]*\n/g,''))); <ide> <ide> ``` <ide> <ide> tests: <ide> <ide> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <ide> --> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/use-html5-to-require-a-field.chinese.md <ide> id: bad87fee1348bd9aedc08830 <ide> title: Use HTML5 to Require a Field <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用HTML5需要字段 <add>videoUrl: 'https://scrimba.com/p/pVMPUv/cMd4EcQ' <add>forumTopicId: 18360 <add>localeTitle: 给表单添加一个必填字段 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以订定必填项,限制您的用户在完成必填项之前无法提交表单。如果您要订定必填项段,只需在<code>input</code>元素中添加<code>required</code>的属性,如下所示: <code>&lt;input type=&quot;text&quot; required&gt;</code> </section> <add><section id='description'> <add>当你设计表单时,你可以指定某些字段为必填项(required),只有当用户填写了该字段后,才可以提交表单。 <add>如果你想把文本输入框设置为必填项,在<code>input</code>元素中加上 required 属性就可以了,例如:<code>&#60;input type="text" required&#62;</code> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">利用<code>required</code> 使您的<code>input</code>成为必填项 ,限制您的用户在沒填写必填项的情况下无法提交表单。请尝试在沒有在完成必填项前提交表单,看看HTML5如何通知您少填了必填项。 </section> <add><section id='instructions'> <add>给<code>input</code>元素加上<code>required</code>属性,这样用户就必须先在输入框里填入内容,然后才可以提交表单。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的<code>input</code>元素应具有<code>required</code>属性。 <del> testString: 'assert($("input").prop("required"), "Your text <code>input</code> element should have the <code>required</code> attribute.");' <add> - text: '<code>input</code>元素必须有<code>required</code>属性。' <add> testString: assert($("input").prop("required")); <ide> <ide> ``` <ide> <ide> tests: <ide> ```html <ide> <h2>CatPhotoApp</h2> <ide> <main> <del> <p>Click here to view more <a href="#">cat photos</a>.</p> <del> <del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> <del> <del> <p>Things cats love:</p> <add><p>点击查看更多<a href="#">猫咪图片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <ide> <ul> <del> <li>cat nip</li> <del> <li>laser pointers</li> <del> <li>lasagna</li> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <ide> </ul> <del> <p>Top 3 things cats hate:</p> <add> <p>猫咪最讨厌的三件东西:</p> <ide> <ol> <del> <li>flea treatment</li> <del> <li>thunder</li> <del> <li>other cats</li> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <ide> </ol> <ide> <form action="/submit-cat-photo"> <del> <input type="text" placeholder="cat photo URL"> <del> <button type="submit">Submit</button> <add> <input type="text" placeholder="猫咪图片地址"> <add> <button type="submit">提交</button> <ide> </form> <ide> </main> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> <ide> ## Solution <ide> <section id='solution'> <del> <del>```js <del>// solution required <del>``` <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/use-the-value-attribute-with-radio-buttons-and-checkboxes.chinese.md <add>--- <add>id: 5c6c06847491271903d37cfd <add>title: Use the value attribute with Radio Buttons and Checkboxes <add>challengeType: 0 <add>forumTopicId: 301099 <add>localeTitle: 使用单选框和复选框的 value 属性 <add>--- <add> <add>## Description <add><section id='description'> <add>当表单提交时,包括 options 已选值在内的数据会发送给服务端。<code>radio</code>和<code>checkbox</code>的<code>value</code>值决定了发送到服务端的实际内容。 <add> <add>例如: <add> <add>```html <add><label for="indoor"> <add> <input id="indoor" value="indoor" type="radio" name="indoor-outdoor">Indoor <add></label> <add><label for="outdoor"> <add> <input id="outdoor" value="outdoor" type="radio" name="indoor-outdoor">Outdoor <add></label> <add>``` <add> <add>在这里,有两个 <code>radio</code> 单选框。如果当用户提交表单时 <code>indoor</code> 选项被选中,表单数据会包含:<code>indoor-outdoor=indoor</code>。也就是 "indoor" 单选框的 <code>name</code> 和 <code>value</code> 属性。 <add> <add>如果没写 <code>value</code> 属性,会使用默认值做为表单数据提交,也就是 <code>on</code>。在这种情况下,如果用户点击 "indoor" 选项然后提交表单,表单数据的值为 <code>indoor-outdoor=on</code>,这可能并没有什么意义。因此最好将 <code>value</code> 属性设置一些有意义的内容。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>给每一个<code>radio</code>和<code>checkbox</code>输入框添加<code>value</code>属性。请把每个<code>input</code>对应的<code>label</code>文本转换为小写(如 Outdoor 应转换为 outdoor),设置其为 value 的值(即 <code>value="outdoor"</code>)。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '一个单选按钮应该包含 <code>indoor</code> 的 <code>value</code> 属性。' <add> testString: assert($('label:contains("Indoor") > input[type="radio"]').filter("[value='indoor']").length > 0); <add> - text: '一个单选按钮应该包含 <code>outdoor</code> 的 <code>value</code> 属性。' <add> testString: assert($('label:contains("Outdoor") > input[type="radio"]').filter("[value='outdoor']").length > 0); <add> - text: '一个复选框应该包含 <code>loving</code> 的 <code>value</code> 属性。' <add> testString: assert($('label:contains("Loving") > input[type="checkbox"]').filter("[value='loving']").length > 0); <add> - text: '一个复选框应该包含 <code>lazy</code> 的 <code>value</code> 属性。' <add> testString: assert($('label:contains("Lazy") > input[type="checkbox"]').filter("[value='lazy']").length > 0); <add> - text: '一个复选框应该包含 <code>lazy</code> 的 <code>energetic</code> 属性。' <add> testString: assert($('label:contains("Energetic") > input[type="checkbox"]').filter("[value='energetic']").length > 0); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add><div id='html-seed'> <add> <add>```html <add><h2>CatPhotoApp</h2> <add><main> <add> <p>点击查看更多<a href="#">猫咪照片</a>。</p> <add> <add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一个可爱的橘猫躺在地上"></a> <add> <add> <p>猫咪最喜欢的三件东西:</p> <add> <ul> <add> <li>猫薄荷</li> <add> <li>激光笔</li> <add> <li>千层饼</li> <add> </ul> <add> <p>猫咪最讨厌的三件东西:</p> <add> <ol> <add> <li>跳蚤</li> <add> <li>打雷</li> <add> <li>同类</li> <add> </ol> <add> <form action="/submit-cat-photo"> <add> <label><input type="radio" name="indoor-outdoor"> Indoor</label> <add> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br> <add> <label><input type="checkbox" name="personality"> Loving</label> <add> <label><input type="checkbox" name="personality"> Lazy</label> <add> <label><input type="checkbox" name="personality"> Energetic</label><br> <add> <input type="text" placeholder="cat photo URL" required> <add> <button type="submit">Submit</button> <add> </form> <add></main> <add>``` <add> <add></div> <add> <add> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```html <add>// solution required <add>``` <add> <add></section>
29
Go
Go
remove race condition from ovnmanager
40b55d233688165411365b7ef035ff722257e5c8
<ide><path>libnetwork/drivers/overlay/ovmanager/ovmanager.go <ide> func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, <ide> opts[netlabel.OverlayVxlanIDList] = val <ide> <ide> d.Lock() <add> defer d.Unlock() <add> if _, ok := d.networks[id]; ok { <add> n.releaseVxlanID() <add> return nil, fmt.Errorf("network %s already exists", id) <add> } <ide> d.networks[id] = n <del> d.Unlock() <ide> <ide> return opts, nil <ide> } <ide> func (d *driver) NetworkFree(id string) error { <ide> } <ide> <ide> d.Lock() <add> defer d.Unlock() <ide> n, ok := d.networks[id] <del> d.Unlock() <ide> <ide> if !ok { <ide> return fmt.Errorf("overlay network with id %s not found", id) <ide> func (d *driver) NetworkFree(id string) error { <ide> // Release all vxlan IDs in one shot. <ide> n.releaseVxlanID() <ide> <del> d.Lock() <ide> delete(d.networks, id) <del> d.Unlock() <ide> <ide> return nil <ide> }
1
Ruby
Ruby
prevent stdin trashing
4db0b9963c401296f7099118ac0a36fce8cf3114
<ide><path>Library/Homebrew/test/spec_helper.rb <ide> def find_files <ide> <ide> @__stdout = $stdout.clone <ide> @__stderr = $stderr.clone <add> @__stdin = $stdin.clone <ide> <ide> begin <ide> if (example.metadata.keys & [:focus, :byebug]).empty? && !ENV.key?("HOMEBREW_VERBOSE_TESTS") <ide> $stdout.reopen(File::NULL) <ide> $stderr.reopen(File::NULL) <ide> end <add> $stdin.reopen(File::NULL) <ide> <ide> begin <ide> timeout = example.metadata.fetch(:timeout, 60) <ide> def find_files <ide> <ide> $stdout.reopen(@__stdout) <ide> $stderr.reopen(@__stderr) <add> $stdin.reopen(@__stdin) <ide> @__stdout.close <ide> @__stderr.close <add> @__stdin.close <ide> <ide> Formulary.clear_cache <ide> Tap.clear_cache
1
Python
Python
remove unused code
ee1e677ba3bf150ff5f241579dfc77f71c5d6f0d
<ide><path>utils/exporters/blender/addons/io_three/exporter/geometry.py <ide> def _parse_geometry(self): <ide> mt = api.mesh.blend_shapes(self.node, self.options) or [] <ide> self[constants.MORPH_TARGETS] = mt <ide> if len(mt) > 0 and self._scene: # there's blend shapes, let check for animation <del> #self[constants.CLIPS] = api.mesh.animated_blend_shapes(self.node, self.options) or [] <ide> tracks = api.mesh.animated_blend_shapes(self.node, self[constants.NAME], self.options) or [] <ide> merge = self._scene[constants.ANIMATION][0][constants.KEYFRAMES] <ide> for track in tracks:
1
Javascript
Javascript
hide ishidden challenges
68aef571ee9e6a42db198457febbde49cd8b3bdd
<ide><path>client/gatsby-node.js <ide> exports.createPages = function createPages({ graphql, actions, reporter }) { <ide> node { <ide> block <ide> challengeType <add> isHidden <ide> fields { <ide> slug <ide> } <ide><path>client/src/components/Map/components/SuperBlock.js <ide> export class SuperBlock extends Component { <ide> const blocksForSuperBlock = nodes.filter( <ide> node => node.superBlock === superBlock <ide> ); <add> // since the nodes have been filtered based on isHidden, any blocks whose <add> // nodes have been entirely removed will not appear in this array. <ide> const blockDashedNames = uniq( <ide> blocksForSuperBlock.map(({ block }) => block) <ide> ); <add> // render all non-empty blocks <ide> return ( <ide> <ul> <ide> {blockDashedNames.map(blockDashedName => ( <ide><path>client/src/components/Map/index.js <ide> export class Map extends Component { <ide> <ide> render() { <ide> const { nodes } = this.props; <add> // if a given superBlock's nodes have been filtered (via isHidden, say) that <add> // superBlock will not appear in superBlocks and will not be rendered. <ide> const superBlocks = uniq(nodes.map(({ superBlock }) => superBlock)); <ide> return ( <ide> <Row> <ide><path>client/src/pages/learn.js <ide> export const LearnPage = ({ <ide> isSignedIn={isSignedIn} <ide> nodes={edges <ide> .map(({ node }) => node) <del> .filter(({ isPrivate }) => !isPrivate)} <add> .filter(({ isPrivate, isHidden }) => !isPrivate && !isHidden)} <ide> /> <ide> </Grid> <ide> </LearnLayout> <ide> export const query = graphql` <ide> isRequired <ide> superBlock <ide> dashedName <add> isHidden <ide> } <ide> } <ide> } <ide><path>client/src/redux/propTypes.js <ide> export const ChallengeNode = PropTypes.shape({ <ide> guideUrl: PropTypes.string, <ide> head: PropTypes.arrayOf(PropTypes.string), <ide> instructions: PropTypes.string, <del> isBeta: PropTypes.bool, <add> isHidden: PropTypes.bool, <ide> isComingSoon: PropTypes.bool, <ide> isLocked: PropTypes.bool, <ide> isPrivate: PropTypes.bool, <ide><path>client/utils/gatsby/challengePageCreator.js <ide> exports.createChallengePages = createPage => ({ node }, index, thisArray) => { <ide> required = [], <ide> template, <ide> challengeType, <del> id <add> id, <add> isHidden <ide> } = node; <del> if (challengeType === 7) { <add> // TODO: challengeType === 7 and isPrivate are the same, right? If so, we <add> // should remove one of them. <add> if (challengeType === 7 || isHidden) { <ide> return null; <ide> } <ide> <ide><path>curriculum/getChallenges.js <ide> async function createChallenge(fullPath, maybeMeta) { <ide> challenge.required = required.concat(challenge.required || []); <ide> challenge.template = template; <ide> challenge.time = time; <del> // isBeta should default to true, so if it is missing, set it to be true <del> // eslint-disable-next-line no-undefined <del> challenge.isBeta = challenge.isBeta === undefined ? true : challenge.isBeta; <ide> <ide> return challenge; <ide> } <ide><path>curriculum/schema/challengeSchema.js <ide> function getSchemaForLang(lang) { <ide> helpRoom: Joi.string(), <ide> id: Joi.objectId().required(), <ide> instructions: Joi.string().allow(''), <del> isBeta: Joi.bool(), <add> isHidden: Joi.bool().required(), <ide> isComingSoon: Joi.bool(), <ide> isLocked: Joi.bool(), <ide> isPrivate: Joi.bool(),
8
PHP
PHP
change method order
d9dd691526dcf17eb87390b2dbcf3574388d53ac
<ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php <ide> public function compileTruncate(Builder $query) <ide> return ['truncate table '.$this->wrapTable($query->from) => []]; <ide> } <ide> <add> /** <add> * Compile a "where date" clause. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereDate(Builder $query, $where) <add> { <add> $value = $this->parameter($where['value']); <add> <add> return 'cast('.$this->wrap($where['column']).' as date) '.$where['operator'].' '.$value; <add> } <add> <ide> /** <ide> * Determine if the grammar supports savepoints. <ide> * <ide> protected function wrapValue($value) <ide> <ide> return '['.str_replace(']', ']]', $value).']'; <ide> } <del> <del> /** <del> * Compile a "where date" clause. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function whereDate(Builder $query, $where) <del> { <del> $value = $this->parameter($where['value']); <del> <del> return 'cast('.$this->wrap($where['column']).' as date) '.$where['operator'].' '.$value; <del> } <ide> }
1
Javascript
Javascript
add greek language
1accd5d46b7ca19df043446e851b1223cd4ef286
<ide><path>lang/el.js <add>// moment.js language configuration <add>// language : modern greek (el) <add>// author : Aggelos Karalias : https://github.com/mehiel <add> <add>require('../moment').lang('el', { <add> months : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), <add> monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), <add> weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), <add> weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), <add> weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), <add> meridiem : function (hours, minutes, isLower) { <add> if (hours > 11) { <add> return isLower ? 'μμ' : 'ΜΜ'; <add> } else { <add> return isLower ? 'πμ' : 'ΠΜ'; <add> } <add> }, <add> longDateFormat : { <add> LT : "h:mm A", <add> L : "DD/MM/YYYY", <add> LL : "D MMMM YYYY", <add> LLL : "D MMMM YYYY LT", <add> LLLL : "dddd, D MMMM YYYY LT" <add> }, <add> calendar : function (key, mom) { <add> var _calendar_el = { <add> sameDay : '[Σήμερα {}] LT', <add> nextDay : '[Αύριο {}] LT', <add> nextWeek : 'dddd [{}] LT', <add> lastDay : '[Χθες {}] LT', <add> lastWeek : '[την προηγούμενη] dddd [{}] LT', <add> sameElse : 'L' <add> }, <add> output = _calendar_el[key], <add> hours = mom && mom.hours(); <add> <add> return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); <add> }, <add> relativeTime : { <add> future : "σε %s", <add> past : "%s πριν", <add> s : "δευτερόλεπτα", <add> m : "ένα λεπτό", <add> mm : "%d λεπτά", <add> h : "μία ώρα", <add> hh : "%d ώρες", <add> d : "μία μέρα", <add> dd : "%d μέρες", <add> M : "ένας μήνας", <add> MM : "%d μήνες", <add> y : "ένας χρόνος", <add> yy : "%d χρόνια" <add> }, <add> ordinal : function (number) { <add> return number + 'η'; <add> }, <add> week : { <add> dow : 1, // Monday is the first day of the week. <add> doy : 4 // The week that contains Jan 4st is the first week of the year. <add> } <add>}); <ide><path>test/lang/el.js <add>var moment = require("../../moment"); <add> <add> <add> /************************************************** <add> Modern Greek <add> *************************************************/ <add> <add>exports["lang:el"] = { <add> setUp : function (cb) { <add> moment.lang('el'); <add> cb(); <add> }, <add> <add> tearDown : function (cb) { <add> moment.lang('en'); <add> cb(); <add> }, <add> <add> "parse" : function(test) { <add> test.expect(96); <add> <add> var i, <add> tests = 'Ιανουάριος Ιαν_Φεβρουάριος Φεβ_Μάρτιος Μαρ_Απρίλιος Απρ_Μάιος Μαϊ_Ιούνιος Ιουν_Ιούλιος Ιουλ_Αύγουστος Αυγ_Σεπτέμβριος Σεπ_Οκτώβριος Οκτ_Νοέμβριος Νοε_Δεκέμβριος Δεκ'.split("_"); <add> <add> function equalTest(input, mmm, i) { <add> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <add> } <add> <add> for (i = 0; i < 12; i++) { <add> tests[i] = tests[i].split(' '); <add> equalTest(tests[i][0], 'MMM', i); <add> equalTest(tests[i][1], 'MMM', i); <add> equalTest(tests[i][0], 'MMMM', i); <add> equalTest(tests[i][1], 'MMMM', i); <add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); <add> } <add> <add> test.done(); <add> }, <add> <add> "format" : function(test) { <add> test.expect(22); <add> <add> var a = [ <add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'Κυριακή, Φεβρουάριος 14η 2010, 3:25:50 μμ'], <add> ['ddd, hA', 'Κυρ, 3ΜΜ'], <add> ['M Mo MM MMMM MMM', '2 2η 02 Φεβρουάριος Φεβ'], <add> ['YYYY YY', '2010 10'], <add> ['D Do DD', '14 14η 14'], <add> ['d do dddd ddd dd', '0 0η Κυριακή Κυρ Κυ'], <add> ['DDD DDDo DDDD', '45 45η 045'], <add> ['w wo ww', '6 6η 06'], <add> ['h hh', '3 03'], <add> ['H HH', '15 15'], <add> ['m mm', '25 25'], <add> ['s ss', '50 50'], <add> ['a A', 'μμ ΜΜ'], <add> ['t\\he DDDo \\d\\ay of t\\he ye\\ar', 'the 45η day of the year'], <add> ['L', '14/02/2010'], <add> ['LL', '14 Φεβρουάριος 2010'], <add> ['LLL', '14 Φεβρουάριος 2010 3:25 ΜΜ'], <add> ['LLLL', 'Κυριακή, 14 Φεβρουάριος 2010 3:25 ΜΜ'], <add> ['l', '14/2/2010'], <add> ['ll', '14 Φεβ 2010'], <add> ['lll', '14 Φεβ 2010 3:25 ΜΜ'], <add> ['llll', 'Κυρ, 14 Φεβ 2010 3:25 ΜΜ'] <add> ], <add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <add> i; <add> <add> for (i = 0; i < a.length; i++) { <add> test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); <add> } <add> <add> test.done(); <add> }, <add> <add> "format ordinal" : function(test) { <add> test.expect(31); <add> <add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1η', '1η'); <add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2η', '2η'); <add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3η', '3η'); <add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4η', '4η'); <add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5η', '5η'); <add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6η', '6η'); <add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7η', '7η'); <add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8η', '8η'); <add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9η', '9η'); <add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10η', '10η'); <add> <add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11η', '11η'); <add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12η', '12η'); <add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13η', '13η'); <add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14η', '14η'); <add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15η', '15η'); <add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16η', '16η'); <add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17η', '17η'); <add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18η', '18η'); <add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19η', '19η'); <add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20η', '20η'); <add> <add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21η', '21η'); <add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22η', '22η'); <add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23η', '23η'); <add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24η', '24η'); <add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25η', '25η'); <add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26η', '26η'); <add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27η', '27η'); <add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28η', '28η'); <add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29η', '29η'); <add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30η', '30η'); <add> <add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31η', '31η'); <add> test.done(); <add> }, <add> <add> "format month" : function(test) { <add> test.expect(12); <add> <add> var i, <add> expected = 'Ιανουάριος Ιαν_Φεβρουάριος Φεβ_Μάρτιος Μαρ_Απρίλιος Απρ_Μάιος Μαϊ_Ιούνιος Ιουν_Ιούλιος Ιουλ_Αύγουστος Αυγ_Σεπτέμβριος Σεπ_Οκτώβριος Οκτ_Νοέμβριος Νοε_Δεκέμβριος Δεκ'.split("_"); <add> <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <add> } <add> test.done(); <add> }, <add> <add> "format week" : function(test) { <add> test.expect(7); <add> <add> var i, <add> expected = 'Κυριακή Κυρ Κυ_Δευτέρα Δευ Δε_Τρίτη Τρι Τρ_Τετάρτη Τετ Τε_Πέμπτη Πεμ Πε_Παρασκευή Παρ Πα_Σάββατο Σαβ Σα'.split("_"); <add> <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <add> } <add> <add> test.done(); <add> }, <add> <add> "from" : function(test) { <add> test.expect(30); <add> <add> var start = moment([2007, 1, 28]); <add> <add> test.equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "δευτερόλεπτα", "44 seconds = a few seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "ένα λεπτό", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "ένα λεπτό", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2 λεπτά", "90 seconds = 2 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44 λεπτά", "44 minutes = 44 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "μία ώρα", "45 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "μία ώρα", "89 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2 ώρες", "90 minutes = 2 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5 ώρες", "5 hours = 5 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21 ώρες", "21 hours = 21 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "μία μέρα", "22 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "μία μέρα", "35 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2 μέρες", "36 hours = 2 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "μία μέρα", "1 day = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5 μέρες", "5 days = 5 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25 μέρες", "25 days = 25 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "ένας μήνας", "26 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "ένας μήνας", "30 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "ένας μήνας", "45 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2 μήνες", "46 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2 μήνες", "75 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3 μήνες", "76 days = 3 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "ένας μήνας", "1 month = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5 μήνες", "5 months = 5 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11 μήνες", "344 days = 11 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "ένας χρόνος", "345 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "ένας χρόνος", "547 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2 χρόνια", "548 days = 2 years"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "ένας χρόνος", "1 year = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5 χρόνια", "5 years = 5 years"); <add> <add> test.done(); <add> }, <add> <add> "suffix" : function(test) { <add> test.expect(2); <add> <add> test.equal(moment(30000).from(0), "σε δευτερόλεπτα", "prefix"); <add> test.equal(moment(0).from(30000), "δευτερόλεπτα πριν", "suffix"); <add> <add> test.done(); <add> }, <add> <add> "now from now" : function(test) { <add> test.expect(1); <add> <add> test.equal(moment().fromNow(), "δευτερόλεπτα πριν", "now from now should display as in the past"); <add> <add> test.done(); <add> }, <add> <add> "fromNow" : function(test) { <add> test.expect(2); <add> <add> test.equal(moment().add({s:30}).fromNow(), "σε δευτερόλεπτα", "in a few seconds"); <add> test.equal(moment().add({d:5}).fromNow(), "σε 5 μέρες", "in 5 days"); <add> <add> test.done(); <add> }, <add> <add> "calendar day" : function(test) { <add> test.expect(6); <add> <add> var a = moment().hours(2).minutes(0).seconds(0); <add> <add> test.equal(moment(a).calendar(), "Σήμερα στις 2:00 ΠΜ", "today at the same time"); <add> test.equal(moment(a).add({ m: 25 }).calendar(), "Σήμερα στις 2:25 ΠΜ", "Now plus 25 min"); <add> test.equal(moment(a).add({ h: 1 }).calendar(), "Σήμερα στις 3:00 ΠΜ", "Now plus 1 hour"); <add> test.equal(moment(a).add({ d: 1 }).calendar(), "Αύριο στις 2:00 ΠΜ", "tomorrow at the same time"); <add> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Σήμερα στη 1:00 ΠΜ", "Now minus 1 hour"); <add> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Χθες στις 2:00 ΠΜ", "yesterday at the same time"); <add> <add> test.done(); <add> }, <add> <add> "calendar next week" : function(test) { <add> test.expect(15); <add> <add> var i, m; <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().add({ d: i }); <add> test.equal(m.calendar(), m.format('dddd [' + (m.hours()%12 === 1 ? 'στη' : 'στις') + '] LT'), "Today + " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format('dddd [στις] LT'), "Today + " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format('dddd [στις] LT'), "Today + " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar last week" : function(test) { <add> test.expect(15); <add> <add> var i, m; <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().subtract({ d: i }); <add> test.equal(m.calendar(), m.format('[την προηγούμενη] dddd [' + (m.hours()%12 === 1 ? 'στη' : 'στις') + '] LT'), "Today - " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format('[την προηγούμενη] dddd [στις] LT'), "Today - " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format('[την προηγούμενη] dddd [στις] LT'), "Today - " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar all else" : function(test) { <add> test.expect(4); <add> <add> var weeksAgo = moment().subtract({ w: 1 }), <add> weeksFromNow = moment().add({ w: 1 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); <add> <add> weeksAgo = moment().subtract({ w: 2 }); <add> weeksFromNow = moment().add({ w: 2 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); <add> <add> test.done(); <add> }, <add> <add> // Monday is the first day of the week. <add> // The week that contains Jan 4st is the first week of the year. <add> <add> "weeks year starting sunday" : function(test) { <add> test.expect(5); <add> <add> test.equal(moment([2012, 0, 1]).week(), 52, "Jan 1 2012 should be week 52"); <add> test.equal(moment([2012, 0, 7]).week(), 1, "Jan 7 2012 should be week 1"); <add> test.equal(moment([2012, 0, 8]).week(), 1, "Jan 8 2012 should be week 1"); <add> test.equal(moment([2012, 0, 14]).week(), 2, "Jan 14 2012 should be week 2"); <add> test.equal(moment([2012, 0, 15]).week(), 2, "Jan 15 2012 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting monday" : function(test) { <add> test.expect(6); <add> <add> test.equal(moment([2006, 11, 31]).week(), 52, "Dec 31 2006 should be week 52"); <add> test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); <add> test.equal(moment([2007, 0, 6]).week(), 1, "Jan 6 2007 should be week 1"); <add> test.equal(moment([2007, 0, 7]).week(), 1, "Jan 7 2007 should be week 1"); <add> test.equal(moment([2007, 0, 13]).week(), 2, "Jan 13 2007 should be week 2"); <add> test.equal(moment([2007, 0, 14]).week(), 2, "Jan 14 2007 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting tuesday" : function(test) { <add> test.expect(6); <add> <add> test.equal(moment([2007, 11, 30]).week(), 52, "Dec 30 2007 should be week 52"); <add> test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); <add> test.equal(moment([2008, 0, 5]).week(), 1, "Jan 5 2008 should be week 1"); <add> test.equal(moment([2008, 0, 6]).week(), 1, "Jan 6 2008 should be week 1"); <add> test.equal(moment([2008, 0, 12]).week(), 2, "Jan 12 2008 should be week 2"); <add> test.equal(moment([2008, 0, 13]).week(), 2, "Jan 13 2008 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting wednesday" : function(test) { <add> test.expect(6); <add> <add> test.equal(moment([2002, 11, 29]).week(), 52, "Dec 29 2002 should be week 52"); <add> test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); <add> test.equal(moment([2003, 0, 4]).week(), 1, "Jan 4 2003 should be week 1"); <add> test.equal(moment([2003, 0, 5]).week(), 1, "Jan 5 2003 should be week 1"); <add> test.equal(moment([2003, 0, 11]).week(), 2, "Jan 11 2003 should be week 2"); <add> test.equal(moment([2003, 0, 12]).week(), 2, "Jan 12 2003 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting thursday" : function(test) { <add> test.expect(6); <add> <add> test.equal(moment([2008, 11, 28]).week(), 52, "Dec 28 2008 should be week 52"); <add> test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); <add> test.equal(moment([2009, 0, 3]).week(), 1, "Jan 3 2009 should be week 1"); <add> test.equal(moment([2009, 0, 4]).week(), 1, "Jan 4 2009 should be week 1"); <add> test.equal(moment([2009, 0, 10]).week(), 2, "Jan 10 2009 should be week 2"); <add> test.equal(moment([2009, 0, 11]).week(), 2, "Jan 11 2009 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting friday" : function(test) { <add> test.expect(7); <add> <add> test.equal(moment([2009, 11, 27]).week(), 52, "Dec 27 2009 should be week 52"); <add> test.equal(moment([2010, 0, 1]).week(), 53, "Jan 1 2010 should be week 53"); <add> test.equal(moment([2010, 0, 2]).week(), 53, "Jan 2 2010 should be week 53"); <add> test.equal(moment([2010, 0, 3]).week(), 53, "Jan 3 2010 should be week 1"); <add> test.equal(moment([2010, 0, 9]).week(), 1, "Jan 9 2010 should be week 1"); <add> test.equal(moment([2010, 0, 10]).week(), 1, "Jan 10 2010 should be week 1"); <add> test.equal(moment([2010, 0, 11]).week(), 2, "Jan 11 2010 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting saturday" : function(test) { <add> test.expect(6); <add> <add> test.equal(moment([2010, 11, 26]).week(), 51, "Dec 26 2010 should be week 51"); <add> test.equal(moment([2011, 0, 1]).week(), 52, "Jan 1 2011 should be week 52"); <add> test.equal(moment([2011, 0, 2]).week(), 52, "Jan 2 2011 should be week 52"); <add> test.equal(moment([2011, 0, 8]).week(), 1, "Jan 8 2011 should be week 1"); <add> test.equal(moment([2011, 0, 9]).week(), 1, "Jan 9 2011 should be week 1"); <add> test.equal(moment([2011, 0, 10]).week(), 2, "Jan 10 2011 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting sunday format" : function(test) { <add> test.expect(5); <add> <add> test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52η', "Jan 1 2012 should be week 52"); <add> test.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1η', "Jan 7 2012 should be week 1"); <add> test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1η', "Jan 8 2012 should be week 1"); <add> test.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2η', "Jan 14 2012 should be week 2"); <add> test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2η', "Jan 15 2012 should be week 2"); <add> <add> test.done(); <add> } <add>};
2
Javascript
Javascript
remove the need for extra form scope
5e6ba2520174218d26defbe9488a1073da882072
<ide><path>src/directive/form.js <ide> * of `FormController`. <ide> * <ide> */ <del>FormController.$inject = ['$scope', 'name']; <del>function FormController($scope, name) { <add>FormController.$inject = ['$scope', 'name', '$element']; <add>function FormController($scope, name, element) { <ide> var form = this, <add> parentForm = element.parent().inheritedData('$formController'), <ide> errors = form.error = {}; <ide> <ide> // publish the form into scope <ide> name(this); <ide> <del> $scope.$on('$destroy', function(event, widget) { <del> if (!widget) return; <add> if (parentForm) { <add> parentForm.$addControl(form); <add> } <ide> <del> if (widget.widgetId && form[widget.widgetId] === widget) { <del> delete form[widget.widgetId]; <add> form.$addControl = function(control) { <add> if (control.name && !form.hasOwnProperty(control.name)) { <add> form[control.name] = control; <ide> } <del> forEach(errors, removeWidget, widget); <del> }); <del> <del> $scope.$on('$valid', function(event, error, widget) { <del> removeWidget(errors[error], error, widget); <add> } <ide> <del> if (equals(errors, {})) { <del> form.valid = true; <del> form.invalid = false; <add> form.$removeControl = function(control) { <add> if (control.name && form[control.name] === control) { <add> delete form[control.name]; <ide> } <del> }); <add> forEach(errors, cleanupControlErrors, control); <add> }; <ide> <del> $scope.$on('$invalid', function(event, error, widget) { <del> addWidget(error, widget); <add> form.$setValidity = function(validationToken, isValid, control) { <add> if (isValid) { <add> cleanupControlErrors(errors[validationToken], validationToken, control); <ide> <del> form.valid = false; <del> form.invalid = true; <del> }); <add> if (equals(errors, {})) { <add> form.valid = true; <add> form.invalid = false; <add> } <add> } else { <add> addControlError(validationToken, control); <ide> <del> $scope.$on('$viewTouch', function() { <add> form.valid = false; <add> form.invalid = true; <add> } <add> }; <add> <add> form.$setDirty = function() { <ide> form.dirty = true; <ide> form.pristine = false; <del> }); <del> <del> $scope.$on('$newFormControl', function(event, widget) { <del> if (widget.widgetId && !form.hasOwnProperty(widget.widgetId)) { <del> form[widget.widgetId] = widget; <del> } <del> }); <add> } <ide> <ide> // init state <ide> form.dirty = false; <ide> form.pristine = true; <ide> form.valid = true; <ide> form.invalid = false; <ide> <del> function removeWidget(queue, errorKey, widget) { <add> function cleanupControlErrors(queue, validationToken, control) { <ide> if (queue) { <del> widget = widget || this; // so that we can be used in forEach; <add> control = control || this; // so that we can be used in forEach; <ide> for (var i = 0, length = queue.length; i < length; i++) { <del> if (queue[i] === widget) { <add> if (queue[i] === control) { <ide> queue.splice(i, 1); <ide> if (!queue.length) { <del> delete errors[errorKey]; <add> delete errors[validationToken]; <add> <add> if (parentForm) { <add> parentForm.$setValidity(validationToken, true, form); <add> } <ide> } <ide> } <ide> } <ide> } <ide> } <ide> <del> function addWidget(errorKey, widget) { <del> var queue = errors[errorKey]; <add> function addControlError(validationToken, control) { <add> var queue = errors[validationToken]; <ide> if (queue) { <ide> for (var i = 0, length = queue.length; i < length; i++) { <del> if (queue[i] === widget) { <add> if (queue[i] === control) { <ide> return; <ide> } <ide> } <ide> } else { <del> errors[errorKey] = queue = []; <add> errors[validationToken] = queue = []; <add> <add> if (parentForm) { <add> parentForm.$setValidity(validationToken, false, form); <add> } <ide> } <del> queue.push(widget); <add> queue.push(control); <ide> } <ide> } <ide> <ide> function FormController($scope, name) { <ide> * @name angular.module.ng.$compileProvider.directive.form <ide> * @restrict EA <ide> * <del> * @scope <ide> * @description <ide> * Directive that instantiates <ide> * {@link angular.module.ng.$compileProvider.directive.form.FormController FormController}. <ide> * <del> * If `name` attribute is specified, the controller is published to the scope as well. <add> * If `name` attribute is specified, the form controller is published onto the current scope under <add> * this name. <ide> * <ide> * # Alias: `ng-form` <ide> * <ide> function FormController($scope, name) { <ide> <doc:source> <ide> <script> <ide> function Ctrl($scope) { <del> $scope.text = 'guest'; <add> $scope.userType = 'guest'; <ide> } <ide> </script> <ide> <form name="myForm" ng-controller="Ctrl"> <del> text: <input type="text" name="input" ng-model="text" required> <del> <span class="error" ng-show="myForm.input.error.REQUIRED">Required!</span> <del> <tt>text = {{text}}</tt><br/> <del> <tt>myForm.input.valid = {{myForm.input.valid}}</tt><br/> <del> <tt>myForm.input.error = {{myForm.input.error}}</tt><br/> <del> <tt>myForm.valid = {{myForm.valid}}</tt><br/> <del> <tt>myForm.error.REQUIRED = {{!!myForm.error.REQUIRED}}</tt><br/> <add> userType: <input name="input" ng-model="userType" required> <add> <span class="error" ng-show="myForm.input.error.REQUIRED">Required!</span><br> <add> <tt>userType = {{userType}}</tt><br> <add> <tt>myForm.input.valid = {{myForm.input.valid}}</tt><br> <add> <tt>myForm.input.error = {{myForm.input.error}}</tt><br> <add> <tt>myForm.valid = {{myForm.valid}}</tt><br> <add> <tt>myForm.error.REQUIRED = {{!!myForm.error.REQUIRED}}</tt><br> <ide> </form> <ide> </doc:source> <ide> <doc:scenario> <ide> it('should initialize to model', function() { <del> expect(binding('text')).toEqual('guest'); <add> expect(binding('userType')).toEqual('guest'); <ide> expect(binding('myForm.input.valid')).toEqual('true'); <ide> }); <ide> <ide> it('should be invalid if empty', function() { <del> input('text').enter(''); <del> expect(binding('text')).toEqual(''); <add> input('userType').enter(''); <add> expect(binding('userType')).toEqual(''); <ide> expect(binding('myForm.input.valid')).toEqual('false'); <ide> }); <ide> </doc:scenario> <ide> var formDirective = [function() { <ide> return { <ide> name: 'form', <ide> restrict: 'E', <del> scope: true, <ide> inject: { <ide> name: 'accessor' <ide> }, <ide> controller: FormController, <ide> compile: function() { <ide> return { <ide> pre: function(scope, formElement, attr, controller) { <del> formElement.data('$form', controller); <ide> formElement.bind('submit', function(event) { <ide> if (!attr.action) event.preventDefault(); <ide> }); <ide><path>src/directive/input.js <ide> var inputType = { <ide> <ide> it('should be invalid if over max', function() { <ide> input('value').enter('123'); <del> expect(binding('value')).toEqual('12'); <add> expect(binding('value')).toEqual(''); <ide> expect(binding('myForm.input.valid')).toEqual('false'); <ide> }); <ide> </doc:scenario> <ide> function textInputType(scope, element, attr, ctrl) { <ide> var pattern = attr.ngPattern, <ide> patternValidator; <ide> <del> var emit = function(regexp, value) { <add> var validate = function(regexp, value) { <ide> if (isEmpty(value) || regexp.test(value)) { <ide> ctrl.setValidity('PATTERN', true); <ide> return value; <ide> function textInputType(scope, element, attr, ctrl) { <ide> if (pattern.match(/^\/(.*)\/$/)) { <ide> pattern = new RegExp(pattern.substr(1, pattern.length - 2)); <ide> patternValidator = function(value) { <del> return emit(pattern, value) <add> return validate(pattern, value) <ide> }; <ide> } else { <ide> patternValidator = function(value) { <ide> function textInputType(scope, element, attr, ctrl) { <ide> if (!patternObj || !patternObj.test) { <ide> throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); <ide> } <del> return emit(patternObj, value); <add> return validate(patternObj, value); <ide> }; <ide> } <ide> <ide> function checkboxInputType(scope, element, attr, ctrl) { <ide> <ide> it('should be invalid if empty when required', function() { <ide> input('user.name').enter(''); <del> expect(binding('user')).toEqual('{"last":"visitor","name":null}'); <add> expect(binding('user')).toEqual('{"last":"visitor"}'); <ide> expect(binding('myForm.userName.valid')).toEqual('false'); <ide> expect(binding('myForm.valid')).toEqual('false'); <ide> }); <ide> function checkboxInputType(scope, element, attr, ctrl) { <ide> <ide> it('should be invalid if less than required min length', function() { <ide> input('user.last').enter('xx'); <del> expect(binding('user')).toEqual('{"last":"visitor","name":"guest"}'); <add> expect(binding('user')).toEqual('{"name":"guest"}'); <ide> expect(binding('myForm.lastName.valid')).toEqual('false'); <ide> expect(binding('myForm.lastName.error')).toMatch(/MINLENGTH/); <ide> expect(binding('myForm.valid')).toEqual('false'); <ide> }); <ide> <del> it('should be valid if longer than max length', function() { <add> it('should be invalid if longer than max length', function() { <ide> input('user.last').enter('some ridiculously long name'); <ide> expect(binding('user')) <del> .toEqual('{"last":"visitor","name":"guest"}'); <add> .toEqual('{"name":"guest"}'); <ide> expect(binding('myForm.lastName.valid')).toEqual('false'); <ide> expect(binding('myForm.lastName.error')).toMatch(/MAXLENGTH/); <ide> expect(binding('myForm.valid')).toEqual('false'); <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> this.modelValue = Number.NaN; <ide> this.parsers = []; <ide> this.formatters = []; <add> this.viewChangeListeners = []; <ide> this.error = {}; <ide> this.pristine = true; <ide> this.dirty = false; <ide> this.valid = true; <ide> this.invalid = false; <ide> this.render = noop; <del> this.widgetId = $attr.name; <add> this.name = $attr.name; <ide> <ide> <ide> /** <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> * @methodOf angular.module.ng.$compileProvider.directive.ng-model.NgModelController <ide> * <ide> * @description <del> * Change the validity state, and notifies the form when the widget changes validity. (i.e. does <del> * not emit `$invalid` if given validator is already marked as invalid). <add> * Change the validity state, and notifies the form when the widget changes validity. (i.e. it <add> * does not notify form if given validator is already marked as invalid). <ide> * <del> * This method should be called by validators - ie the parser or formatter method. <add> * This method should be called by validators - i.e. the parser or formatter functions. <ide> * <del> * @param {string} name Name of the validator. <del> * @param {boolean} isValid Whether it should $emit `$valid` (true) or `$invalid` (false) event. <add> * @param {string} validationToken Name of the validator. <add> * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). <ide> */ <del> this.setValidity = function(name, isValid) { <add> this.setValidity = function(validationToken, isValid) { <ide> <del> if (!isValid && this.error[name]) return; <del> if (isValid && !this.error[name]) return; <add> if (!isValid && this.error[validationToken]) return; <add> if (isValid && !this.error[validationToken]) return; <ide> <ide> if (isValid) { <del> delete this.error[name]; <add> delete this.error[validationToken]; <ide> if (equals(this.error, {})) { <ide> this.valid = true; <ide> this.invalid = false; <ide> } <ide> } else { <del> this.error[name] = true; <add> this.error[validationToken] = true; <ide> this.invalid = true; <ide> this.valid = false; <ide> } <ide> <del> return $scope.$emit(isValid ? '$valid' : '$invalid', name, this); <add> if (this.$form) { <add> this.$form.$setValidity(validationToken, isValid, this); <add> } <ide> }; <ide> <ide> <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> * For example {@link angular.module.ng.$compileProvider.directive.input input} or <ide> * {@link angular.module.ng.$compileProvider.directive.select select} directives call it. <ide> * <del> * It internally calls all `formatters` and if resulted value is valid, update the model and emits <del> * `$viewChange` event afterwards. <add> * It internally calls all `formatters` and if resulted value is valid, updates the model and <add> * calls all registered change listeners. <ide> * <del> * @param {string} value Value from the view <add> * @param {string} value Value from the view. <ide> */ <ide> this.setViewValue = function(value) { <ide> this.viewValue = value; <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', <ide> if (this.pristine) { <ide> this.dirty = true; <ide> this.pristine = false; <del> $scope.$emit('$viewTouch', this); <add> if (this.$form) this.$form.$setDirty(); <ide> } <ide> <ide> forEach(this.parsers, function(fn) { <ide> value = fn(value); <ide> }); <ide> <del> if (isDefined(value) && this.model !== value) { <add> if (this.modelValue !== value) { <ide> this.modelValue = value; <ide> ngModel(value); <del> $scope.$emit('$viewChange', value, this); <add> forEach(this.viewChangeListeners, function(listener) { <add> try { <add> listener(); <add> } catch(e) { <add> $exceptionHandler(e); <add> } <add> }) <ide> } <ide> }; <ide> <ide> var ngModelDirective = [function() { <ide> inject: { <ide> ngModel: 'accessor' <ide> }, <del> require: 'ngModel', <add> require: ['ngModel', '^?form'], <ide> controller: NgModelController, <del> link: function(scope, element, attr, ctrl) { <add> link: function(scope, element, attr, ctrls) { <ide> // notify others, especially parent forms <del> scope.$emit('$newFormControl', ctrl); <add> <add> var modelCtrl = ctrls[0], <add> formCtrl = ctrls[1]; <add> <add> modelCtrl.$form = formCtrl; <add> <add> if (formCtrl) formCtrl.$addControl(modelCtrl); <ide> <ide> forEach(['valid', 'invalid', 'pristine', 'dirty'], function(name) { <ide> scope.$watch(function() { <del> return ctrl[name]; <add> return modelCtrl[name]; <ide> }, function(value) { <ide> element[value ? 'addClass' : 'removeClass']('ng-' + name); <ide> }); <ide> }); <ide> <ide> element.bind('$destroy', function() { <del> scope.$emit('$destroy', ctrl); <add> if (formCtrl) formCtrl.$removeControl(modelCtrl); <ide> }); <ide> } <ide> }; <ide> var ngModelDirective = [function() { <ide> var ngChangeDirective = valueFn({ <ide> require: 'ngModel', <ide> link: function(scope, element, attr, ctrl) { <del> scope.$on('$viewChange', function(event, value, widget) { <del> if (ctrl === widget) scope.$eval(attr.ngChange); <add> ctrl.viewChangeListeners.push(function() { <add> scope.$eval(attr.ngChange); <ide> }); <ide> } <ide> }); <ide> var requiredDirective = [function() { <ide> var validator = function(value) { <ide> if (attr.required && (isEmpty(value) || value === false)) { <ide> ctrl.setValidity('REQUIRED', false); <del> return null; <add> return; <ide> } else { <ide> ctrl.setValidity('REQUIRED', true); <ide> return value; <ide><path>test/directive/formSpec.js <ide> describe('form', function() { <ide> <ide> it('should instantiate form and attach it to DOM', function() { <ide> doc = $compile('<form>')(scope); <del> expect(doc.data('$form')).toBeTruthy(); <del> expect(doc.data('$form') instanceof FormController).toBe(true); <add> expect(doc.data('$formController')).toBeTruthy(); <add> expect(doc.data('$formController') instanceof FormController).toBe(true); <ide> }); <ide> <ide> <ide> describe('form', function() { <ide> }); <ide> <ide> <del> it('should publish form to scope', function() { <add> it('should publish form to scope when name attr is defined', function() { <ide> doc = $compile('<form name="myForm"></form>')(scope); <ide> expect(scope.myForm).toBeTruthy(); <del> expect(doc.data('$form')).toBeTruthy(); <del> expect(doc.data('$form')).toEqual(scope.myForm); <add> expect(doc.data('$formController')).toBeTruthy(); <add> expect(doc.data('$formController')).toEqual(scope.myForm); <ide> }); <ide> <ide> <del> it('should allow name to be an expression', function() { <add> it('should allow form name to be an expression', function() { <ide> doc = $compile('<form name="obj.myForm"></form>')(scope); <ide> <ide> expect(scope.obj).toBeDefined(); <ide> describe('form', function() { <ide> var input = child.text; <ide> <ide> input.setValidity('MyError', false); <del> expect(parent.error.MyError).toEqual([input]); <add> expect(parent.error.MyError).toEqual([child]); <ide> expect(child.error.MyError).toEqual([input]); <ide> <ide> input.setValidity('MyError', true); <ide> describe('form', function() { <ide> }); <ide> <ide> <add> it('should support two forms on a single scope', function() { <add> doc = $compile( <add> '<div>' + <add> '<form name="formA">' + <add> '<input name="firstName" ng-model="firstName" required>' + <add> '</form>' + <add> '<form name="formB">' + <add> '<input name="lastName" ng-model="lastName" required>' + <add> '</form>' + <add> '</div>' <add> )(scope); <add> <add> scope.$apply(); <add> <add> expect(scope.formA.error.REQUIRED.length).toBe(1); <add> expect(scope.formA.error.REQUIRED).toEqual([scope.formA.firstName]); <add> expect(scope.formB.error.REQUIRED.length).toBe(1); <add> expect(scope.formB.error.REQUIRED).toEqual([scope.formB.lastName]); <add> <add> var inputA = doc.find('input').eq(0), <add> inputB = doc.find('input').eq(1); <add> <add> inputA.val('val1'); <add> browserTrigger(inputA, 'blur'); <add> inputB.val('val2'); <add> browserTrigger(inputB, 'blur'); <add> <add> expect(scope.firstName).toBe('val1'); <add> expect(scope.lastName).toBe('val2'); <add> <add> expect(scope.formA.error.REQUIRED).toBeUndefined(); <add> expect(scope.formB.error.REQUIRED).toBeUndefined(); <add> }); <add> <add> <ide> it('should chain nested forms in repeater', function() { <ide> doc = jqLite( <ide> '<ng:form name=parent>' + <ide> describe('form', function() { <ide> input.setValidity('myRule', false); <ide> expect(input.error.myRule).toEqual(true); <ide> expect(child.error.myRule).toEqual([input]); <del> expect(parent.error.myRule).toEqual([input]); <add> expect(parent.error.myRule).toEqual([child]); <ide> <ide> input.setValidity('myRule', true); <ide> expect(parent.error.myRule).toBeUndefined(); <ide><path>test/directive/inputSpec.js <ide> describe('NgModelController', function() { <ide> expect(ctrl.formatters).toEqual([]); <ide> expect(ctrl.parsers).toEqual([]); <ide> <del> expect(ctrl.widgetId).toBe('testAlias'); <add> expect(ctrl.name).toBe('testAlias'); <ide> }); <ide> <ide> <ide> describe('setValidity', function() { <ide> <del> it('should emit $invalid only when $valid', function() { <del> var spy = jasmine.createSpy('$invalid'); <del> scope.$on('$invalid', spy); <add> it('should propagate invalid to the parent form only when valid', function() { <add> var spy = jasmine.createSpy('setValidity'); <add> ctrl.$form = {$setValidity: spy}; <ide> <ide> ctrl.setValidity('ERROR', false); <del> expect(spy).toHaveBeenCalledOnce(); <add> expect(spy).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <ide> <ide> spy.reset(); <ide> ctrl.setValidity('ERROR', false); <ide> describe('NgModelController', function() { <ide> <ide> <ide> it('should emit $valid only when $invalid', function() { <del> var spy = jasmine.createSpy('$valid'); <del> scope.$on('$valid', spy); <add> var spy = jasmine.createSpy('setValidity'); <add> ctrl.$form = {$setValidity: spy}; <ide> <ide> ctrl.setValidity('ERROR', true); <ide> expect(spy).not.toHaveBeenCalled(); <ide> <ide> ctrl.setValidity('ERROR', false); <add> expect(spy).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <add> spy.reset(); <ide> ctrl.setValidity('ERROR', true); <del> expect(spy).toHaveBeenCalledOnce(); <add> expect(spy).toHaveBeenCalledOnceWith('ERROR', true, ctrl); <ide> }); <ide> }); <ide> <ide> describe('NgModelController', function() { <ide> }); <ide> <ide> <del> it('should fire $viewChange only if value changed and is valid', function() { <del> var spy = jasmine.createSpy('$viewChange'); <del> scope.$on('$viewChange', spy); <del> <add> it('should fire viewChangeListeners when the value changes in the view (even if invalid)', <add> function() { <add> var spy = jasmine.createSpy('viewChangeListener'); <add> ctrl.viewChangeListeners.push(spy); <ide> ctrl.setViewValue('val'); <ide> expect(spy).toHaveBeenCalledOnce(); <ide> spy.reset(); <ide> <ide> // invalid <ide> ctrl.parsers.push(function() {return undefined;}); <ide> ctrl.setViewValue('val'); <del> expect(spy).not.toHaveBeenCalled(); <add> expect(spy).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> <del> it('should only fire $viewTouch when pristine', function() { <del> var spy = jasmine.createSpy('$viewTouch'); <del> scope.$on('$viewTouch', spy); <add> it('should reset the model when the view is invalid', function() { <add> ctrl.setViewValue('aaaa'); <add> expect(ctrl.modelValue).toBe('aaaa'); <add> <add> // add a validator that will make any input invalid <add> ctrl.parsers.push(function() {return undefined;}); <add> expect(ctrl.modelValue).toBe('aaaa'); <add> ctrl.setViewValue('bbbb'); <add> expect(ctrl.modelValue).toBeUndefined; <add> }); <add> <add> <add> it('should call parentForm.setDirty only when pristine', function() { <add> var spy = jasmine.createSpy('setDirty'); <add> ctrl.$form = {$setDirty: spy}; <ide> <ide> ctrl.setViewValue(''); <ide> expect(ctrl.pristine).toBe(false); <ide> describe('input', function() { <ide> }); <ide> <ide> <del> it('should call $destroy on element remove', function() { <del> compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); <add> it('should cleanup it self from the parent form', function() { <add> compileInput('<input ng-model="name" name="alias" required>'); <ide> <del> var spy = jasmine.createSpy('on destroy'); <del> scope.$on('$destroy', spy); <add> scope.$apply(); <add> expect(scope.form.error.REQUIRED.length).toBe(1); <ide> <ide> inputElm.remove(); <del> expect(spy).toHaveBeenCalled(); <add> expect(scope.form.error.REQUIRED).toBeUndefined(); <ide> }); <ide> <ide> <ide> describe('input', function() { <ide> <ide> describe('number', function() { <ide> <del> it('should not update model if view invalid', function() { <add> it('should reset the model if view is invalid', function() { <ide> compileInput('<input type="number" ng-model="age"/>'); <ide> <ide> scope.$apply(function() { <ide> describe('input', function() { <ide> <ide> changeInputValueTo('123X'); <ide> expect(inputElm.val()).toBe('123X'); <del> expect(scope.age).toBe(123); <add> expect(scope.age).toBeUndefined(); <ide> expect(inputElm).toBeInvalid(); <ide> }); <ide> <ide> describe('input', function() { <ide> expect(widget.error.EMAIL).toBeUndefined(); <ide> <ide> changeInputValueTo('invalid@'); <del> expect(scope.email).toBe('[email protected]'); <add> expect(scope.email).toBeUndefined(); <ide> expect(inputElm).toBeInvalid(); <ide> expect(widget.error.EMAIL).toBeTruthy(); <ide> }); <ide> describe('input', function() { <ide> expect(widget.error.URL).toBeUndefined(); <ide> <ide> changeInputValueTo('invalid.com'); <del> expect(scope.url).toBe('http://www.something.com'); <add> expect(scope.url).toBeUndefined(); <ide> expect(inputElm).toBeInvalid(); <ide> expect(widget.error.URL).toBeTruthy(); <ide> });
4
Javascript
Javascript
fix crash on rc while toggling object status
bab9bfec3aa08e3402427e762d0607e4aa5228d1
<ide><path>Libraries/Components/SwitchIOS/SwitchIOS.ios.js <ide> var SwitchIOS = React.createClass({ <ide> }, <ide> <ide> _onChange: function(event: Event) { <del> this.props.onChange && this.props.onChange(event); <del> this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); <del> <ide> // The underlying switch might have changed, but we're controlled, <ide> // and so want to ensure it represents our value. <ide> this.refs[SWITCH].setNativeProps({value: this.props.value}); <add> <add> if (this.props.value === event.nativeEvent.value || this.props.disabled) { <add> return; <add> } <add> <add> this.props.onChange && this.props.onChange(event); <add> this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); <ide> }, <ide> <ide> render: function() {
1
Go
Go
fix typo that made change detection break
bc1c5ddf2ebbb74dd2e2bc2d4a7a24c75edf6877
<ide><path>changes.go <ide> func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { <ide> // breaks down is if some code intentionally hides a change by setting <ide> // back mtime <ide> oldMtime := syscall.NsecToTimeval(oldStat.Mtim.Nano()) <del> newMtime := syscall.NsecToTimeval(oldStat.Mtim.Nano()) <add> newMtime := syscall.NsecToTimeval(newStat.Mtim.Nano()) <ide> if oldStat.Mode != newStat.Mode || <ide> oldStat.Uid != newStat.Uid || <ide> oldStat.Gid != newStat.Gid ||
1
Javascript
Javascript
add a null check for text node
3e30f83bb10007a240b2a6372273d87d5b1d143d
<ide><path>src/js/control-bar/time-controls/time-display.js <ide> import document from 'global/document'; <ide> import Component from '../../component.js'; <ide> import * as Dom from '../../utils/dom.js'; <ide> import formatTime from '../../utils/format-time.js'; <add>import log from '../../utils/log.js'; <ide> <ide> /** <ide> * Displays time information about the video <ide> class TimeDisplay extends Component { <ide> return; <ide> } <ide> <del> const oldNode = this.textNode_; <add> let oldNode = this.textNode_; <add> <add> if (oldNode && !this.contentEl_.contains(oldNode)) { <add> oldNode = null; <add> <add> log.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.'); <add> } <ide> <ide> this.textNode_ = document.createTextNode(this.formattedTime_); <ide>
1
Python
Python
add message to show if in tree or flat view
5c3a269841981b5b9f8969678c9951c246833975
<ide><path>glances/plugins/glances_processcount.py <ide> # Note: history items list is not compliant with process count <ide> # if a filter is applyed, the graph will show the filtered processes count <ide> <add>PROCESS_TREE = True # TODO remove that and take command line parameter <add> <ide> <ide> class Plugin(GlancesPlugin): <ide> <ide> def msg_curse(self, args=None): <ide> else: <ide> msg = _("sorted by {0}").format(glances_processes.getmanualsortkey()) <ide> ret.append(self.curse_add_line(msg)) <add> ret[-1]["msg"] += ", %s view" % ("tree" if PROCESS_TREE else "flat") <ide> <ide> # Return the message with decoration <ide> return ret
1
Javascript
Javascript
remove leftover `__ember_observesbefore__`
ae867e537eae207b81c4bb2d7c2ada433a63cbc5
<ide><path>packages/ember-utils/lib/super.js <ide> function _wrap(func, superFunc) { <ide> <ide> superWrapper.wrappedFunction = func; <ide> superWrapper.__ember_observes__ = func.__ember_observes__; <del> superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; <ide> superWrapper.__ember_listens__ = func.__ember_listens__; <ide> <ide> return superWrapper;
1
Python
Python
fix unused imports and style
96c4990165f8096da3de30954811b42b731a286d
<ide><path>src/transformers/modeling_tf_distilbert.py <ide> <ide> from .configuration_distilbert import DistilBertConfig <ide> from .file_utils import add_start_docstrings, add_start_docstrings_to_callable <del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, get_initializer, keras_serializable, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, get_initializer, shape_list <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>src/transformers/modeling_tf_openai.py <ide> TFSequenceSummary, <ide> TFSharedEmbeddings, <ide> get_initializer, <del> keras_serializable, <ide> shape_list, <ide> ) <ide> <ide><path>src/transformers/modeling_tf_roberta.py <ide> <ide> import tensorflow as tf <ide> <del>from . import PretrainedConfig <ide> from .configuration_roberta import RobertaConfig <ide> from .file_utils import add_start_docstrings, add_start_docstrings_to_callable <ide> from .modeling_tf_bert import TFBertEmbeddings, TFBertMainLayer, gelu <del>from .modeling_tf_utils import TFPreTrainedModel, get_initializer, keras_serializable, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, get_initializer, shape_list <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>src/transformers/modeling_tf_t5.py <ide> <ide> from .configuration_t5 import T5Config <ide> from .file_utils import DUMMY_INPUTS, DUMMY_MASK, add_start_docstrings <del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, keras_serializable, shape_list <add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, shape_list <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>src/transformers/modeling_tf_xlm.py <ide> <ide> from .configuration_xlm import XLMConfig <ide> from .file_utils import add_start_docstrings, add_start_docstrings_to_callable <del>from .modeling_tf_utils import ( <del> TFPreTrainedModel, <del> TFSequenceSummary, <del> TFSharedEmbeddings, <del> get_initializer, <del> keras_serializable, <del> shape_list, <del>) <add>from .modeling_tf_utils import TFPreTrainedModel, TFSequenceSummary, TFSharedEmbeddings, get_initializer, shape_list <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>tests/test_modeling_tf_common.py <ide> def test_keras_save_load(self): <ide> for module_member_name in dir(module) <ide> if module_member_name.endswith("MainLayer") <ide> for module_member in (getattr(module, module_member_name),) <del> if isinstance(module_member, type) and tf.keras.layers.Layer in module_member.__bases__ <del> and getattr(module_member, '_keras_serializable', False) <add> if isinstance(module_member, type) <add> and tf.keras.layers.Layer in module_member.__bases__ <add> and getattr(module_member, "_keras_serializable", False) <ide> ) <ide> for main_layer_class in tf_main_layer_classes: <ide> main_layer = main_layer_class(config)
6
Ruby
Ruby
fix broken tests
b6923c2b29b4eb6358c46ae086bd0a866f4e43c7
<ide><path>actionmailer/test/mail_service_test.rb <ide> def test_explicitly_multipart_with_invalid_content_type <ide> <ide> def test_implicitly_multipart_messages <ide> mail = TestMailer.create_implicitly_multipart_example(@recipient) <del> assert_equal 3, mail.parts.length <add> assert_equal 6, mail.parts.length <ide> assert_equal "1.0", mail.mime_version <ide> assert_equal "multipart/alternative", mail.content_type <ide> assert_equal "text/yaml", mail.parts[0].content_type <ide> assert_equal "utf-8", mail.parts[0].sub_header("content-type", "charset") <del> assert_equal "text/plain", mail.parts[1].content_type <del> assert_equal "utf-8", mail.parts[1].sub_header("content-type", "charset") <del> assert_equal "text/html", mail.parts[2].content_type <add> assert_equal "text/plain", mail.parts[2].content_type <ide> assert_equal "utf-8", mail.parts[2].sub_header("content-type", "charset") <add> assert_equal "text/html", mail.parts[4].content_type <add> assert_equal "utf-8", mail.parts[4].sub_header("content-type", "charset") <ide> end <ide> <ide> def test_implicitly_multipart_messages_with_custom_order <ide> mail = TestMailer.create_implicitly_multipart_example(@recipient, nil, ["text/yaml", "text/plain"]) <del> assert_equal 3, mail.parts.length <add> assert_equal 6, mail.parts.length <ide> assert_equal "text/html", mail.parts[0].content_type <del> assert_equal "text/plain", mail.parts[1].content_type <del> assert_equal "text/yaml", mail.parts[2].content_type <add> assert_equal "text/plain", mail.parts[2].content_type <add> assert_equal "text/yaml", mail.parts[4].content_type <ide> end <ide> <ide> def test_implicitly_multipart_messages_with_charset
1
Ruby
Ruby
add a method for getting the http auth salt
49ba2710e9fa01c2bedaf306552fae6f3301a119
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> def authentication_request(controller, realm, message = nil) <ide> end <ide> <ide> def secret_token(request) <del> key_generator = request.env["action_dispatch.key_generator"] <del> http_auth_salt = request.env["action_dispatch.http_auth_salt"] <add> key_generator = request.key_generator <add> http_auth_salt = request.http_auth_salt <ide> key_generator.generate_key(http_auth_salt) <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def controller_instance=(controller) # :nodoc: <ide> set_header('action_controller.instance'.freeze, controller) <ide> end <ide> <add> def http_auth_salt <add> get_header "action_dispatch.http_auth_salt" <add> end <add> <ide> def show_exceptions? # :nodoc: <ide> # We're treating `nil` as "unset", and we want the default setting to be <ide> # `true`. This logic should be extracted to `env_config` and calculated
2
Java
Java
remove redundant 'string.substring()' call
4517f40f57df6ee5ef339d21b135ba4b79ffa4e9
<ide><path>spring-web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> private void copyCharactersTillPotentialReference() { <ide> int skipUntilIndex = (this.nextPotentialReferencePosition != -1 ? <ide> this.nextPotentialReferencePosition : this.originalMessage.length()); <ide> if (skipUntilIndex - this.currentPosition > 3) { <del> this.decodedMessage.append(this.originalMessage.substring(this.currentPosition, skipUntilIndex)); <add> this.decodedMessage.append(this.originalMessage, this.currentPosition, skipUntilIndex); <ide> this.currentPosition = skipUntilIndex; <ide> } <ide> else {
1
Javascript
Javascript
use strict comparison
5164a12618cf60150db621aebe1f3d89efb9b9aa
<ide><path>lib/_http_client.js <ide> const errors = require('internal/errors'); <ide> const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; <ide> <ide> function validateHost(host, name) { <del> if (host != null && typeof host !== 'string') { <add> if (host !== null && host !== undefined && typeof host !== 'string') { <ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', `options.${name}`, <ide> ['string', 'undefined', 'null'], host); <ide> } <ide> function ClientRequest(options, cb) { <ide> <ide> var method = options.method; <ide> var methodIsString = (typeof method === 'string'); <del> if (method != null && !methodIsString) { <add> if (method !== null && method !== undefined && !methodIsString) { <ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', <ide> 'string', method); <ide> }
1
Ruby
Ruby
save local_filename to json
26e1d17b4d5bce5f2377b6d7bafc1082f4650b19
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_formula(f) <ide> "tags" => { <ide> tag => { <ide> "filename" => filename.bintray, <add> "local_filename" => filename.to_s, <ide> "sha256" => sha256, <ide> }, <ide> },
1
Text
Text
add model card for hindi-bert
518f291eef9f246e26a3932971cb3970b7d0b11a
<ide><path>model_cards/monsoon-nlp/hindi-bert/README.md <add>--- <add>language: Hindi <add>--- <add> <add># Hindi-BERT (Discriminator) <add> <add>This is a first run of a Hindi language model trained with Google Research's [ELECTRA](https://github.com/google-research/electra). **I don't modify ELECTRA until we get into finetuning** <add> <add>Tokenization and training CoLab: https://colab.research.google.com/drive/1R8TciRSM7BONJRBc9CBZbzOmz39FTLl_ <add> <add>Blog post: https://medium.com/@mapmeld/teaching-hindi-to-electra-b11084baab81 <add> <add>Greatly influenced by: https://huggingface.co/blog/how-to-train <add> <add>## Corpus <add> <add>Download: https://drive.google.com/drive/u/1/folders/1WikYHHMI72hjZoCQkLPr45LDV8zm9P7p <add> <add>The corpus is two files: <add>- Hindi CommonCrawl deduped by OSCAR https://traces1.inria.fr/oscar/ <add>- latest Hindi Wikipedia ( https://dumps.wikimedia.org/hiwiki/20200420/ ) + WikiExtractor to txt <add> <add>Bonus notes: <add>- Adding English wiki text or parallel corpus could help with cross-lingual tasks and training <add> <add>## Vocabulary <add> <add>https://drive.google.com/file/d/1-02Um-8ogD4vjn4t-wD2EwCE-GtBjnzh/view?usp=sharing <add> <add>Bonus notes: <add>- Created with HuggingFace Tokenizers; could be longer or shorter, review ELECTRA vocab_size param <add> <add>## Pretrain TF Records <add> <add>[build_pretraining_dataset.py](https://github.com/google-research/electra/blob/master/build_pretraining_dataset.py) splits the corpus into training documents <add> <add>Set the ELECTRA model size and whether to split the corpus by newlines. This process can take hours on its own. <add> <add>https://drive.google.com/drive/u/1/folders/1--wBjSH59HSFOVkYi4X-z5bigLnD32R5 <add> <add>Bonus notes: <add>- I am not sure of the meaning of the corpus newline split (what is the alternative?) and given this corpus, which creates the better training docs <add> <add>## Training <add> <add>Structure your files, with data-dir named "trainer" here <add> <add>``` <add>trainer <add>- vocab.txt <add>- pretrain_tfrecords <add>-- (all .tfrecord... files) <add>- models <add>-- modelname <add>--- checkpoint <add>--- graph.pbtxt <add>--- model.* <add>``` <add> <add>CoLab notebook gives examples of GPU vs. TPU setup <add> <add>[configure_pretraining.py](https://github.com/google-research/electra/blob/master/configure_pretraining.py) <add> <add>Model https://drive.google.com/drive/folders/1cwQlWryLE4nlke4OixXA7NK8hzlmUR0c?usp=sharing <add> <add>## Using this model with Transformers <add> <add>Sample movie reviews classifier: https://colab.research.google.com/drive/1mSeeSfVSOT7e-dVhPlmSsQRvpn6xC05w
1
Python
Python
add test to check reported training loss
9dc8fb2fc7cd5d595fdcf0cc5dc30c88ee8a6144
<ide><path>tests/test_trainer.py <ide> def test_gradient_accumulation(self): <ide> trainer.train() <ide> self.check_trained_model(trainer.model) <ide> <add> def test_training_loss(self): <add> n_gpus = max(1, get_gpu_count()) <add> <add> # With even logs <add> trainer = get_regression_trainer(logging_steps=64 / (8 * n_gpus)) <add> trainer.train() <add> log_history = trainer.state.log_history <add> <add> losses = [log["loss"] for log in log_history if "loss" in log] <add> train_loss = log_history[-1]["train_loss"] <add> self.assertAlmostEqual(sum(losses) / len(losses), train_loss, places=4) <add> <add> # With uneven logs <add> trainer = get_regression_trainer(logging_steps=5) <add> trainer.train() <add> log_history = trainer.state.log_history <add> <add> # Training loss should be the same as before <add> new_train_loss = log_history[-1]["train_loss"] <add> self.assertAlmostEqual(train_loss, new_train_loss, places=4) <add> <ide> def test_custom_optimizer(self): <ide> train_dataset = RegressionDataset() <ide> args = TrainingArguments("./regression")
1
Ruby
Ruby
use chop! instead of chop! for efficiency
89550ee7e90fa824c99cf4882426d9a5269d0d64
<ide><path>actionpack/lib/action_controller/cgi_ext/raw_post_data_fix.rb <ide> def read_params_from_post <ide> stdinput.binmode if stdinput.respond_to?(:binmode) <ide> content = stdinput.read(Integer(env_table['CONTENT_LENGTH'])) || '' <ide> # fix for Safari Ajax postings that always append \000 <del> content = content.chop if content[-1] == 0 <add> content.chop! if content[-1] == 0 <ide> env_table['RAW_POST_DATA'] = content.freeze <ide> end <ide>
1
PHP
PHP
fix the validation of required file uploads
472e377b02a580f81106b7a96f9e4cee3195a819
<ide><path>laravel/validator.php <ide> protected function validate_required($attribute, $value) <ide> { <ide> return false; <ide> } <add> elseif ( ! is_null(Input::file($attribute)) and $value['tmp_name'] == '') <add> { <add> return false; <add> } <ide> <ide> return true; <ide> } <ide> protected function validate_alpha_dash($attribute, $value) <ide> */ <ide> protected function validate_mimes($attribute, $value, $parameters) <ide> { <del> if (is_array($value) and ! isset($value['tmp_name'])) return true; <add> if ( ! is_array($value) or Arr::get($value, 'tmp_name', '') == '') return true; <ide> <ide> foreach ($parameters as $extension) <ide> {
1
Python
Python
fix imports so that all tests pass
24cd77be0d56b1a98424d4f31aa58b506c4598e0
<ide><path>numpy/linalg/linalg.py <ide> <ide> from numpy.core import * <ide> from numpy.lib import * <add>from old import solve_linear_equations <ide> import lapack_lite <ide> <ide> # Helper routines <ide><path>numpy/linalg/old.py <ide> ] <ide> <ide> from numpy.core import transpose <del>import numpy.linalg as linalg <add>import linalg <ide> <ide> # Error object <ide> class LinAlgError(Exception):
2
Javascript
Javascript
use object-enumeration for pattern type
cca0306789afc294c648f05552e57bb6b4a9868a
<ide><path>src/pattern.js <ide> <ide> 'use strict'; <ide> <del>var AXIAL_PATTERN_TYPE = 2; <del>var RADIAL_PATTERN_TYPE = 3; <add>var PatternType = { <add> AXIAL: 2, <add> RADIAL: 3 <add>}; <ide> <ide> var Pattern = (function patternPattern() { <ide> // Constructor should define this.getPattern <ide> var Pattern = (function patternPattern() { <ide> var type = dict.get('ShadingType'); <ide> <ide> switch (type) { <del> case AXIAL_PATTERN_TYPE: <del> case RADIAL_PATTERN_TYPE: <add> case PatternType.AXIAL: <add> case PatternType.RADIAL: <ide> // Both radial and axial shadings are handled by RadialAxial shading. <ide> return new Shadings.RadialAxial(dict, matrix, xref, res, ctx); <ide> default: <ide> Shadings.RadialAxial = (function radialAxialShading() { <ide> } <ide> <ide> var grad; <del> if (type == AXIAL_PATTERN_TYPE) <add> if (type == PatternType.AXIAL) <ide> grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); <del> else if (type == RADIAL_PATTERN_TYPE) <add> else if (type == PatternType.RADIAL) <ide> grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); <ide> <ide> for (var i = 0, ii = colorStops.length; i < ii; ++i) { <ide> Shadings.RadialAxial = (function radialAxialShading() { <ide> getIR: function radialAxialShadingGetIR() { <ide> var coordsArr = this.coordsArr; <ide> var type = this.shadingType; <del> if (type == AXIAL_PATTERN_TYPE) { <add> if (type == PatternType.AXIAL) { <ide> var p0 = [coordsArr[0], coordsArr[1]]; <ide> var p1 = [coordsArr[2], coordsArr[3]]; <ide> var r0 = null; <ide> var r1 = null; <del> } else if (type == RADIAL_PATTERN_TYPE) { <add> } else if (type == PatternType.RADIAL) { <ide> var p0 = [coordsArr[0], coordsArr[1]]; <ide> var p1 = [coordsArr[3], coordsArr[4]]; <ide> var r0 = coordsArr[2];
1
Python
Python
use related_objects api for django 1.9+
2acc6a756cddf9db2ba5d8007b9e9871541fa63c
<ide><path>rest_framework/compat.py <ide> def template_render(template, context=None, request=None): <ide> # backends template, e.g. django.template.backends.django.Template <ide> else: <ide> return template.render(context, request=request) <add> <add> <add>def get_all_related_objects(opts): <add> """ <add> Django 1.8 changed meta api, see <add> https://docs.djangoproject.com/en/1.8/ref/models/meta/#migrating-old-meta-api <add> https://code.djangoproject.com/ticket/12663 <add> https://github.com/django/django/pull/3848 <add> <add> :param opts: Options instance <add> :return: list of relations except many-to-many ones <add> """ <add> if django.VERSION < (1, 9): <add> return opts.get_all_related_objects() <add> else: <add> return [r for r in opts.related_objects if not r.field.many_to_many] <add> <add> <add>def get_all_related_many_to_many_objects(opts): <add> """ <add> Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() <add> <add> :param opts: Options instance <add> :return: list of many-to-many relations <add> """ <add> if django.VERSION < (1, 9): <add> return opts.get_all_related_many_to_many_objects() <add> else: <add> return [r for r in opts.related_objects if r.field.many_to_many] <ide><path>rest_framework/utils/model_meta.py <ide> from django.db import models <ide> from django.utils import six <ide> <add>from rest_framework.compat import ( <add> get_all_related_many_to_many_objects, get_all_related_objects <add>) <add> <ide> FieldInfo = namedtuple('FieldResult', [ <ide> 'pk', # Model field instance <ide> 'fields', # Dict of field name -> model field instance <ide> def _get_reverse_relationships(opts): <ide> # See: https://code.djangoproject.com/ticket/24208 <ide> <ide> reverse_relations = OrderedDict() <del> for relation in opts.get_all_related_objects(): <add> for relation in get_all_related_objects(opts): <ide> accessor_name = relation.get_accessor_name() <ide> related = getattr(relation, 'related_model', relation.model) <ide> reverse_relations[accessor_name] = RelationInfo( <ide> def _get_reverse_relationships(opts): <ide> ) <ide> <ide> # Deal with reverse many-to-many relationships. <del> for relation in opts.get_all_related_many_to_many_objects(): <add> for relation in get_all_related_many_to_many_objects(opts): <ide> accessor_name = relation.get_accessor_name() <ide> related = getattr(relation, 'related_model', relation.model) <ide> reverse_relations[accessor_name] = RelationInfo(
2
Javascript
Javascript
remove weird spaces from resource mutation test
9985104dc0a2f96b1b318a8b662c0806a96f312b
<ide><path>test/ResourceSpec.js <ide> describe("resource", function() { <ide> expect(callback).wasCalledWith(cc); <ide> }); <ide> <del> it('should not mutate the resource object if response contains no body', function(){ <add> it('should not mutate the resource object if response contains no body', function(){ <ide> var data = {id:{key:123}, number:'9876'}; <ide> xhr.expectGET("/CreditCard/123").respond(data); <ide> var cc = CreditCard.get({id:123});
1
PHP
PHP
add jsonp function to reponse facade
cfbdfa0a0c39e60adeae2041b9c2e48065d4158e
<ide><path>src/Illuminate/Support/Facades/Response.php <ide> public static function json($data = array(), $status = 200, array $headers = arr <ide> return new JsonResponse($data, $status, $headers, $options); <ide> } <ide> <add> /** <add> * Return a new JSONP response from the application. <add> * <add> * @param string $callback <add> * @param string|array $data <add> * @param int $status <add> * @param array $headers <add> * @param int $options <add> * @return \Illuminate\Http\JsonResponse <add> */ <add> public static function jsonp($callback, $data = [], $status = 200, array $headers = [], $options = 0) <add> { <add> return static::json($data, $status, $headers, $options)->setCallback($callback); <add> } <add> <ide> /** <ide> * Return a new streamed response from the application. <ide> *
1
Python
Python
use torch.unique_consecutive to check same element
a2ef9c5446b65c9d20c06ab6940f89fcbee89382
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def forward( <ide> <ide> eos_mask = input_ids.eq(self.config.eos_token_id) <ide> <del> if len(torch.unique(eos_mask.sum(1))) > 1: <add> if len(torch.unique_consecutive(eos_mask.sum(1))) > 1: <ide> raise ValueError("All examples must have the same number of <eos> tokens.") <ide> sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[ <ide> :, -1, : <ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def forward( <ide> <ide> eos_mask = input_ids.eq(self.config.eos_token_id) <ide> <del> if len(torch.unique(eos_mask.sum(1))) > 1: <add> if len(torch.unique_consecutive(eos_mask.sum(1))) > 1: <ide> raise ValueError("All examples must have the same number of <eos> tokens.") <ide> sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[ <ide> :, -1, : <ide><path>src/transformers/models/led/modeling_led.py <ide> def forward( <ide> <ide> eos_mask = input_ids.eq(self.config.eos_token_id) <ide> <del> if len(torch.unique(eos_mask.sum(1))) > 1: <add> if len(torch.unique_consecutive(eos_mask.sum(1))) > 1: <ide> raise ValueError("All examples must have the same number of <eos> tokens.") <ide> sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[ <ide> :, -1, : <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> def forward( <ide> <ide> eos_mask = input_ids.eq(self.config.eos_token_id) <ide> <del> if len(torch.unique(eos_mask.sum(1))) > 1: <add> if len(torch.unique_consecutive(eos_mask.sum(1))) > 1: <ide> raise ValueError("All examples must have the same number of <eos> tokens.") <ide> sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[ <ide> :, -1, : <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py <ide> def forward( <ide> <ide> eos_mask = input_ids.eq(self.config.eos_token_id) <ide> <del> if len(torch.unique(eos_mask.sum(1))) > 1: <add> if len(torch.unique_consecutive(eos_mask.sum(1))) > 1: <ide> raise ValueError("All examples must have the same number of <eos> tokens.") <ide> sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[ <ide> :, -1, :
5
PHP
PHP
remove double spaces in phpdoc
d90a98ea215e5a47eaa49c67deb7fdb71bad8a8b
<ide><path>src/Auth/FormAuthenticate.php <ide> protected function _checkFields(ServerRequest $request, array $fields) <ide> * <ide> * @param \Cake\Http\ServerRequest $request The request that contains login information. <ide> * @param \Cake\Network\Response $response Unused response object. <del> * @return mixed False on login failure. An array of User data on success. <add> * @return mixed False on login failure. An array of User data on success. <ide> */ <ide> public function authenticate(ServerRequest $request, Response $response) <ide> { <ide><path>src/Cache/Cache.php <ide> * There are 5 built-in caching engines: <ide> * <ide> * - `FileEngine` - Uses simple files to store content. Poor performance, but good for <del> * storing large objects, or things that are not IO sensitive. Well suited to development <add> * storing large objects, or things that are not IO sensitive. Well suited to development <ide> * as it is an easy cache to inspect and manually flush. <ide> * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines. <ide> * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage. <ide><path>src/Console/ConsoleOutput.php <ide> public function styles($style = null, $definition = null) <ide> * Get/Set the output type to use. The output type how formatting tags are treated. <ide> * <ide> * @param int|null $type The output type to use. Should be one of the class constants. <del> * @return int|null Either null or the value if getting. <add> * @return int|null Either null or the value if getting. <ide> */ <ide> public function outputAs($type = null) <ide> { <ide><path>src/Console/Exception/ConsoleException.php <ide> use Cake\Core\Exception\Exception; <ide> <ide> /** <del> * Exception class for Console libraries. This exception will be thrown from Console library <add> * Exception class for Console libraries. This exception will be thrown from Console library <ide> * classes when they encounter an error. <ide> */ <ide> class ConsoleException extends Exception <ide><path>src/Controller/Component/SecurityComponent.php <ide> class SecurityComponent extends Component <ide> * and hidden unlocked fields do not have their values checked. <ide> * - `unlockedActions` - Actions to exclude from POST validation checks. <ide> * Other checks like requireAuth(), requireSecure() etc. will still be applied. <del> * - `validatePost` - Whether to validate POST data. Set to false to disable <add> * - `validatePost` - Whether to validate POST data. Set to false to disable <ide> * for data coming from 3rd party services, etc. <ide> * <ide> * @var array <ide><path>src/Database/Dialect/MysqlDialectTrait.php <ide> trait MysqlDialectTrait <ide> use SqlDialectTrait; <ide> <ide> /** <del> * String used to start a database identifier quoting to make it safe <add> * String used to start a database identifier quoting to make it safe <ide> * <ide> * @var string <ide> */ <ide><path>src/Database/Dialect/PostgresDialectTrait.php <ide> trait PostgresDialectTrait <ide> use SqlDialectTrait; <ide> <ide> /** <del> * String used to start a database identifier quoting to make it safe <add> * String used to start a database identifier quoting to make it safe <ide> * <ide> * @var string <ide> */ <ide><path>src/Database/Dialect/SqliteDialectTrait.php <ide> trait SqliteDialectTrait <ide> use TupleComparisonTranslatorTrait; <ide> <ide> /** <del> * String used to start a database identifier quoting to make it safe <add> * String used to start a database identifier quoting to make it safe <ide> * <ide> * @var string <ide> */ <ide><path>src/Database/Expression/FunctionExpression.php <ide> class FunctionExpression extends QueryExpression implements TypedResultInterface <ide> * <ide> * ### Examples: <ide> * <del> * `$f = new FunctionExpression('CONCAT', ['CakePHP', ' rules']);` <add> * `$f = new FunctionExpression('CONCAT', ['CakePHP', ' rules']);` <ide> * <ide> * Previous line will generate `CONCAT('CakePHP', ' rules')` <ide> * <ide><path>src/Datasource/EntityInterface.php <ide> public function errors($field = null, $errors = null, $overwrite = false); <ide> * Stores whether or not a property value can be changed or set in this entity. <ide> * The special property `*` can also be marked as accessible or protected, meaning <ide> * that any other property specified before will take its value. For example <del> * `$entity->accessible('*', true)` means that any property not specified already <add> * `$entity->accessible('*', true)` means that any property not specified already <ide> * will be accessible by default. <ide> * <ide> * @param string|array $property Either a single or list of properties to change its accessibility. <ide><path>src/Datasource/EntityTrait.php <ide> public function invalid($field = null, $value = null, $overwrite = false) <ide> * Stores whether or not a property value can be changed or set in this entity. <ide> * The special property `*` can also be marked as accessible or protected, meaning <ide> * that any other property specified before will take its value. For example <del> * `$entity->accessible('*', true)` means that any property not specified already <add> * `$entity->accessible('*', true)` means that any property not specified already <ide> * will be accessible by default. <ide> * <ide> * You can also call this method with an array of properties, in which case they <ide> public function accessible($property, $set = null) <ide> * Stores whether or not a property value can be changed or set in this entity. <ide> * The special property `*` can also be marked as accessible or protected, meaning <ide> * that any other property specified before will take its value. For example <del> * `$entity->accessible('*', true)` means that any property not specified already <add> * `$entity->accessible('*', true)` means that any property not specified already <ide> * will be accessible by default. <ide> * <ide> * You can also call this method with an array of properties, in which case they <ide><path>src/Error/Debugger.php <ide> public static function log($var, $level = 'debug', $depth = 3) <ide> * - `depth` - The number of stack frames to return. Defaults to 999 <ide> * - `format` - The format you want the return. Defaults to the currently selected format. If <ide> * format is 'array' or 'points' the return will be an array. <del> * - `args` - Should arguments for functions be shown? If true, the arguments for each method call <add> * - `args` - Should arguments for functions be shown? If true, the arguments for each method call <ide> * will be displayed. <ide> * - `start` - The stack frame to start generating a trace from. Defaults to 0 <ide> * <ide> public static function trace(array $options = []) <ide> * - `depth` - The number of stack frames to return. Defaults to 999 <ide> * - `format` - The format you want the return. Defaults to the currently selected format. If <ide> * format is 'array' or 'points' the return will be an array. <del> * - `args` - Should arguments for functions be shown? If true, the arguments for each method call <add> * - `args` - Should arguments for functions be shown? If true, the arguments for each method call <ide> * will be displayed. <ide> * - `start` - The stack frame to start generating a trace from. Defaults to 0 <ide> * <ide><path>src/Error/ErrorHandler.php <ide> * <ide> * Error handler also provides the built in features for handling php errors (trigger_error). <ide> * While in debug mode, errors will be output to the screen using debugger. While in production mode, <del> * errors will be logged to Log. You can control which errors are logged by setting <add> * errors will be logged to Log. You can control which errors are logged by setting <ide> * `errorLevel` option in config/error.php. <ide> * <ide> * #### Logging errors <ide><path>src/Http/Runner.php <ide> public function run($middleware, ServerRequestInterface $request, ResponseInterf <ide> } <ide> <ide> /** <del> * @param \Psr\Http\Message\ServerRequestInterface $request The server request <add> * @param \Psr\Http\Message\ServerRequestInterface $request The server request <ide> * @param \Psr\Http\Message\ResponseInterface $response The response object <ide> * @return \Psr\Http\Message\ResponseInterface An updated response <ide> */ <ide><path>src/Http/ServerRequest.php <ide> public static function createFromGlobals() <ide> /** <ide> * Create a new request object. <ide> * <del> * You can supply the data as either an array or as a string. If you use <del> * a string you can only supply the URL for the request. Using an array will <add> * You can supply the data as either an array or as a string. If you use <add> * a string you can only supply the URL for the request. Using an array will <ide> * let you provide the following keys: <ide> * <ide> * - `post` POST data or non query string data <ide><path>src/I18n/DateFormatTrait.php <ide> public function nice($timezone = null, $locale = null) <ide> * ``` <ide> * <ide> * You can control the default locale to be used by setting the static variable <del> * `Time::$defaultLocale` to a valid locale string. If empty, the default will be <add> * `Time::$defaultLocale` to a valid locale string. If empty, the default will be <ide> * taken from the `intl.default_locale` ini config. <ide> * <ide> * @param string|int|null $format Format string. <ide><path>src/I18n/MessagesFileLoader.php <ide> class MessagesFileLoader <ide> * $package = $loader(); <ide> * ``` <ide> * <del> * Load and parse src/Locale/fr_FR/validation.mo <add> * Load and parse src/Locale/fr_FR/validation.mo <ide> * <ide> * ``` <ide> * $loader = new MessagesFileLoader('validation', 'fr_FR', 'mo'); <ide><path>src/I18n/Middleware/LocaleSelectorMiddleware.php <ide> public function __construct(array $locales = []) <ide> } <ide> <ide> /** <del> * @param ServerRequestInterface $request The request. <add> * @param ServerRequestInterface $request The request. <ide> * @param ResponseInterface $response The response. <ide> * @param callable $next The next middleware to call. <ide> * @return \Psr\Http\Message\ResponseInterface A response. <ide><path>src/Log/Log.php <ide> use InvalidArgumentException; <ide> <ide> /** <del> * Logs messages to configured Log adapters. One or more adapters <del> * can be configured using Cake Logs's methods. If you don't <add> * Logs messages to configured Log adapters. One or more adapters <add> * can be configured using Cake Logs's methods. If you don't <ide> * configure any adapters, and write to Log, the messages will be <ide> * ignored. <ide> * <ide> * <ide> * ### Writing to the log <ide> * <del> * You write to the logs using Log::write(). See its documentation for more information. <add> * You write to the logs using Log::write(). See its documentation for more information. <ide> * <ide> * ### Logging Levels <ide> * <ide> * ### Logging scopes <ide> * <ide> * When logging messages and configuring log adapters, you can specify <del> * 'scopes' that the logger will handle. You can think of scopes as subsystems <del> * in your application that may require different logging setups. For <add> * 'scopes' that the logger will handle. You can think of scopes as subsystems <add> * in your application that may require different logging setups. For <ide> * example in an e-commerce application you may want to handle logged errors <ide> * in the cart and ordering subsystems differently than the rest of the <del> * application. By using scopes you can control logging for each part <add> * application. By using scopes you can control logging for each part <ide> * of your application and also use standard log levels. <ide> */ <ide> class Log <ide> protected static function _loadConfig() <ide> } <ide> <ide> /** <del> * Reset all the connected loggers. This is useful to do when changing the logging <add> * Reset all the connected loggers. This is useful to do when changing the logging <ide> * configuration or during testing when you want to reset the internal state of the <ide> * Log class. <ide> * <ide><path>src/Network/Exception/InvalidCsrfTokenException.php <ide> class InvalidCsrfTokenException extends HttpException <ide> /** <ide> * Constructor <ide> * <del> * @param string|null $message If no message is given 'Invalid CSRF Token' will be the message <add> * @param string|null $message If no message is given 'Invalid CSRF Token' will be the message <ide> * @param int $code Status code, defaults to 403 <ide> */ <ide> public function __construct($message = null, $code = 403) <ide><path>src/ORM/Association/BelongsToMany.php <ide> protected function _appendJunctionJoin($query, $conditions) <ide> * target entity contains the joint property with its primary key and any extra <ide> * information to be stored. <ide> * <del> * On success, the passed `$sourceEntity` will contain `$targetEntities` as value <add> * On success, the passed `$sourceEntity` will contain `$targetEntities` as value <ide> * in the corresponding property for this association. <ide> * <ide> * This method assumes that links between both the source entity and each of the <ide><path>src/ORM/Association/HasMany.php <ide> function ($assoc) use ($targetEntities) { <ide> * <ide> * This method does not check link uniqueness. <ide> * <del> * On success, the passed `$sourceEntity` will contain `$targetEntities` as value <add> * On success, the passed `$sourceEntity` will contain `$targetEntities` as value <ide> * in the corresponding property for this association. <ide> * <ide> * Additional options for new links to be saved can be passed in the third argument, <ide><path>src/ORM/AssociationsNormalizerTrait.php <ide> <ide> /** <ide> * Contains methods for parsing the associated tables array that is typically <del> * passed to a save operation <add> * passed to a save operation <ide> */ <ide> trait AssociationsNormalizerTrait <ide> { <ide><path>src/Routing/Route/Route.php <ide> class Route <ide> public $template = null; <ide> <ide> /** <del> * Is this route a greedy route? Greedy routes have a `/*` in their <add> * Is this route a greedy route? Greedy routes have a `/*` in their <ide> * template <ide> * <ide> * @var bool <ide> class Route <ide> protected $_compiledRoute = null; <ide> <ide> /** <del> * The name for a route. Fetch with Route::getName(); <add> * The name for a route. Fetch with Route::getName(); <ide> * <ide> * @var string|null <ide> */ <ide> protected function _parseExtension($url) <ide> * Return true if a given named $param's $val matches a given $rule depending on $context. <ide> * Currently implemented rule types are controller, action and match that can be combined with each other. <ide> * <del> * @param string $args A string with the passed params. eg. /1/foo <add> * @param string $args A string with the passed params. eg. /1/foo <ide> * @param string $context The current route context, which should contain controller/action keys. <ide> * @return array Array of passed args. <ide> */ <ide><path>src/Routing/RouteCollection.php <ide> public function parseRequest(ServerRequestInterface $request) <ide> } <ide> <ide> /** <del> * Get the set of names from the $url. Accepts both older style array urls, <add> * Get the set of names from the $url. Accepts both older style array urls, <ide> * and newer style urls containing '_name' <ide> * <ide> * @param array $url The url to match. <ide><path>src/Routing/Router.php <ide> public static function setRequestContext($request) <ide> <ide> <ide> /** <del> * Pops a request off of the request stack. Used when doing requestAction <add> * Pops a request off of the request stack. Used when doing requestAction <ide> * <ide> * @return \Cake\Http\ServerRequest The request removed from the stack. <ide> * @see \Cake\Routing\Router::pushRequest() <ide> protected static function _applyUrlFilters($url) <ide> * cake relative URLs are required when using requestAction. <ide> * - `_scheme` - Set to create links on different schemes like `webcal` or `ftp`. Defaults <ide> * to the current scheme. <del> * - `_host` - Set the host to use for the link. Defaults to the current host. <add> * - `_host` - Set the host to use for the link. Defaults to the current host. <ide> * - `_port` - Set the port if you need to create links on non-standard ports. <ide> * - `_full` - If true output of `Router::fullBaseUrl()` will be prepended to generated URLs. <ide> * - `#` - Allows you to set URL hash fragments. <ide> public static function extensions($extensions = null, $merge = true) <ide> * <ide> * ### Options <ide> * <del> * - `separator` The string to use as a separator. Defaults to `:`. <add> * - `separator` The string to use as a separator. Defaults to `:`. <ide> * <ide> * @param \Cake\Http\ServerRequest $request The request object to modify. <ide> * @param array $options The array of options. <ide><path>src/Utility/Exception/XmlException.php <ide> use RuntimeException; <ide> <ide> /** <del> * Exception class for Xml. This exception will be thrown from Xml when it <add> * Exception class for Xml. This exception will be thrown from Xml when it <ide> * encounters an error. <ide> */ <ide> class XmlException extends RuntimeException <ide><path>src/Utility/Hash.php <ide> public static function remove(array $data, $path) <ide> * @param string|null $groupPath A dot-separated string. <ide> * @return array Combined array <ide> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::combine <del> * @throws \RuntimeException When keys and values count is unequal. <add> * @throws \RuntimeException When keys and values count is unequal. <ide> */ <ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null) <ide> { <ide><path>src/Utility/Xml.php <ide> protected static function _loadXml($input, $options) <ide> * ]; <ide> * ``` <ide> * <del> * Calling `Xml::fromArray($value, 'tags');` Will generate: <add> * Calling `Xml::fromArray($value, 'tags');` Will generate: <ide> * <ide> * `<root><tag><id>1</id><value>defect</value>description</tag></root>` <ide> * <ide><path>src/View/Helper/PaginatorHelper.php <ide> class PaginatorHelper extends Helper <ide> * The values that may be specified are: <ide> * <ide> * - `url` Url of the action. See Router::url() <del> * - `url['sort']` the key that the recordset is sorted. <add> * - `url['sort']` the key that the recordset is sorted. <ide> * - `url['direction']` Direction of the sorting (default: 'asc'). <ide> * - `url['page']` Page number to use in links. <ide> * - `model` The name of the model. <ide><path>src/View/Helper/SessionHelper.php <ide> class SessionHelper extends Helper <ide> { <ide> <ide> /** <del> * Constructor <add> * Constructor <ide> * <ide> * @param \Cake\View\View $View The View this helper is being attached to. <ide> * @param array $config Configuration settings for the helper.
31
Text
Text
fix sidebar order of item
f8a48ca8bb5e0d2d9fe08ac72d7b890cbbc59874
<ide><path>docs/components/sidebar.md <ide> - **<i class="fad fa-plane-alt"></i> Flight Manuals (for Staff & Mods)** <ide> - [01 - List Virtual Machines](/flight-manuals/01-getting-list-of-virtual-machines.md) <ide> - [02 - Provision API Instances](/flight-manuals/02-spinning-api-instances.md) <del> - [02 - Using Reply Templates](/flight-manuals/03-using-reply-templates.md) <add> - [03 - Using Reply Templates](/flight-manuals/03-using-reply-templates.md) <ide> ---- <ide> - **<i class="fad fa-user-friends"></i> Our Community** <ide> - [**<i class="fab fa-github"></i> GitHub Repository**](https://github.com/freecodecamp/freecodecamp)
1
Ruby
Ruby
remove unused method
6f44dc41d5316e26a3ac533019199da502f430fc
<ide><path>Library/Homebrew/development_tools.rb <ide> def clear_version_cache <ide> @clang_version = @clang_build_version = nil <ide> @non_apple_gcc_version = {} <ide> end <del> <del> def tar_supports_xz? <del> false <del> end <ide> end <ide> end <ide> <ide><path>Library/Homebrew/extend/os/mac/development_tools.rb <ide> def default_compiler <ide> end <ide> end <ide> end <del> <del> def tar_supports_xz? <del> false <del> end <ide> end <ide> end
2
Python
Python
add couple of tests for filters
21166a3ab62934266ebef5f4a3123a7ead3460ad
<ide><path>tests/test_filters.py <ide> import warnings <ide> from decimal import Decimal <ide> <add>import pytest <ide> from django.conf.urls import url <ide> from django.core.exceptions import ImproperlyConfigured <ide> from django.db import models <ide> def get_queryset(self): <ide> ] <ide> <ide> <add>class BaseFilterTests(TestCase): <add> def setUp(self): <add> self.original_coreapi = filters.coreapi <add> filters.coreapi = True # mock it, because not None value needed <add> self.filter_backend = filters.BaseFilterBackend() <add> <add> def tearDown(self): <add> filters.coreapi = self.original_coreapi <add> <add> def test_filter_queryset_raises_error(self): <add> with pytest.raises(NotImplementedError): <add> self.filter_backend.filter_queryset(None, None, None) <add> <add> def test_get_schema_fields_checks_for_coreapi(self): <add> filters.coreapi = None <add> with pytest.raises(AssertionError): <add> self.filter_backend.get_schema_fields({}) <add> filters.coreapi = True <add> assert self.filter_backend.get_schema_fields({}) == [] <add> <add> <ide> class CommonFilteringTestCase(TestCase): <ide> def _serialize_object(self, obj): <ide> return {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date.isoformat()} <ide> class SearchListView(generics.ListAPIView): <ide> {'id': 2, 'title': 'zz', 'text': 'bcd'} <ide> ] <ide> <add> def test_search_returns_same_queryset_if_no_search_fields_or_terms_provided(self): <add> class SearchListView(generics.ListAPIView): <add> queryset = SearchFilterModel.objects.all() <add> serializer_class = SearchFilterSerializer <add> filter_backends = (filters.SearchFilter,) <add> <add> view = SearchListView.as_view() <add> request = factory.get('/') <add> response = view(request) <add> expected = SearchFilterSerializer(SearchFilterModel.objects.all(), <add> many=True).data <add> assert response.data == expected <add> <ide> def test_exact_search(self): <ide> class SearchListView(generics.ListAPIView): <ide> queryset = SearchFilterModel.objects.all()
1
PHP
PHP
deprecate $confirmmessage argument
53259cb38946c4eefef9abd702ff462a475c8918
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function postButton($title, $url, $options = array()) { <ide> * @param string $title The content to be wrapped by <a> tags. <ide> * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://) <ide> * @param array $options Array of HTML attributes. <del> * @param bool|string $confirmMessage JavaScript confirmation message. <add> * @param bool|string $confirmMessage JavaScript confirmation message. This <add> * argument is deprecated as of 2.6. Use `confirm` key in $options instead. <ide> * @return string An `<a />` element. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink <ide> */ <ide><path>lib/Cake/View/Helper/HtmlHelper.php <ide> public function charset($charset = null) { <ide> * @param string $title The content to be wrapped by <a> tags. <ide> * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://) <ide> * @param array $options Array of options and HTML attributes. <del> * @param string $confirmMessage JavaScript confirmation message. <add> * @param string $confirmMessage JavaScript confirmation message. This <add> * argument is deprecated as of 2.6. Use `confirm` key in $options instead. <ide> * @return string An `<a />` element. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::link <ide> */
2
Javascript
Javascript
update lathegeometry to use points2
d9a108f65099321a80c2d4c84a6a3ff328c408df
<ide><path>editor/js/Sidebar.Geometry.LatheGeometry.js <ide> Sidebar.Geometry.LatheGeometry = function( editor, object ) { <ide> <ide> // points <ide> <del> var lastPointIdx = 0; <del> var pointsUI = []; <del> <ide> var pointsRow = new UI.Row(); <ide> pointsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/lathe_geometry/points' ) ).setWidth( '90px' ) ); <ide> <del> var points = new UI.Span().setDisplay( 'inline-block' ); <del> pointsRow.add( points ); <del> <del> var pointsList = new UI.Div(); <del> points.add( pointsList ); <del> <del> for ( var i = 0; i < parameters.points.length; i ++ ) { <del> <del> var point = parameters.points[ i ]; <del> pointsList.add( createPointRow( point.x, point.y ) ); <del> <del> } <del> <del> var addPointButton = new UI.Button( '+' ).onClick( function() { <del> <del> if( pointsUI.length === 0 ){ <del> <del> pointsList.add( createPointRow( 0, 0 ) ); <del> <del> } else { <del> <del> var point = pointsUI[ pointsUI.length - 1 ]; <del> <del> pointsList.add( createPointRow( point.x.getValue(), point.y.getValue() ) ); <del> <del> } <del> <del> update(); <del> <del> } ); <del> points.add( addPointButton ); <add> var points = new UI.Points2().setValue(parameters.points).onChange(update); <add> pointsRow.add(points); <ide> <ide> container.add( pointsRow ); <ide> <del> // <del> <del> function createPointRow( x, y ) { <del> <del> var pointRow = new UI.Div(); <del> var lbl = new UI.Text( lastPointIdx + 1 ).setWidth( '20px' ); <del> var txtX = new UI.Number( x ).setRange( 0, Infinity ).setWidth( '40px' ).onChange( update ); <del> var txtY = new UI.Number( y ).setWidth( '40px' ).onChange( update ); <del> var idx = lastPointIdx; <del> var btn = new UI.Button( '-' ).onClick( function() { <del> <del> deletePointRow( idx ); <del> <del> } ); <del> <del> pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY } ); <del> lastPointIdx ++; <del> pointRow.add( lbl, txtX, txtY, btn ); <del> <del> return pointRow; <del> <del> } <del> <del> function deletePointRow( idx ) { <del> <del> if ( ! pointsUI[ idx ] ) return; <del> <del> pointsList.remove( pointsUI[ idx ].row ); <del> pointsUI[ idx ] = null; <del> <del> update(); <del> <del> } <del> <ide> function update() { <ide> <del> var points = []; <del> var count = 0; <del> <del> for ( var i = 0; i < pointsUI.length; i ++ ) { <del> <del> var pointUI = pointsUI[ i ]; <del> <del> if ( ! pointUI ) continue; <del> <del> points.push( new THREE.Vector2( pointUI.x.getValue(), pointUI.y.getValue() ) ); <del> count ++; <del> pointUI.lbl.setValue( count ); <del> <del> } <del> <ide> editor.execute( new SetGeometryCommand( object, new THREE[ geometry.type ]( <del> points, <add> points.getValue(), <ide> segments.getValue(), <ide> phiStart.getValue() / 180 * Math.PI, <ide> phiLength.getValue() / 180 * Math.PI
1
Text
Text
remove changelog file
c58113502939650b4e96305f26acee098e54941e
<ide><path>CHANGELOG.md <del>* Improved: Faster and better looking find and replace <del>* Improved: Double-click selection behavior between word/non-word <del>* Added: Solarized theme now bundled by default <del>* Added: Base16 Tomorrow Dark theme now bundled by default <del> <del>* Fixed: Make Atom's version the same as Speakeasy's version <del> <del>* Fixed: Package generator package not opening window to generated package <del> <del>* Fixed: Precompile bootstrap.less for faster startup <del> <del>* Fixed: Save sometimes failing from an editor that was split <del>* Fixed: Search results not appearing when set to exclude ignores <del> <del>* Fixed: Status bar and gutter displaying incorrect Git status information <del>* Fixed: Packages not installing from the Settings view <del>* Fixed: Spec runner now works from a released build <del>* Fixed: Literate CoffeeScript not syntax highlighting correctly <del> <del>* Added: Soft wrap and tab length can now be set in the settings view <del>* Fixed: Python import statements not syntax highlighting correctly <del> <del>* Added: Terminal package now bundled by default, open with ctrl-` <del>* Fixed: Fuzzy finder not showing results for files at a certain depth <del>* Fixed: Atom > Preferences... menu not opening settings in focused window <del> <del>* Fixed: Atom failing to launch if the theme being used was not found <del> <del>* Improved: Theme changes now immediately take effect <del>* Fixed: Wrap in quotes/parens now works in split panes <del>* Improved: Autocomplete now includes CSS property names and values <del>* Improved: Settings GUI is now a pane item <del>* Added: Support package filtering in Settings GUI <del>* Added: Dynamically load all config options in the Settings GUI <del>* Added: Ability to bookmark lines and navigate bookmarks <del>* Fixed: Error when inserting newlines in CSS <del>* Fixed: Folding all will fold comments as well <del>* Added: Ability to fold all code at a given indentation level <del> <del>* Improved: cmd-n now opens a new tab and cmd-shift-n now opens a new window. <del>* Added: Inspect Element context menu <del>* Fixed: Save As dialog now defaults to directory path of current editor <del>* Fixed: Using toggle comment shortcut respects indentation level <del> <del>* Fixed: Search never completing in the command panel <del> <del>* Fixed: cmd-n now works when no windows are open <del> <del>* Fixed: Error selecting a grammar for an untitled editor <del> <del>* Added: j/k now can be used to navigate the tree view and archive editor <del> <del>* Fixed: Atom can now be launched when ~/.atom/config.cson doesn't exist <del>* Added: Initial collaboration sessions <del>* Fixed: Empty lines being deleted via uppercase/downcase command <del>* Fixed: Keybindings not working when using non-English keyboard language <del>* Fixed: cmd-shift-p and cmd-alt-w not doing anything when pressed <del> <del>* Improved: Use grunt (instead of rake) for build system <del>* Fixed: Java files not syntax highlighting correctly. <del>* Fixed: LESS/CSS now indents properly after hitting enter. <del>* Added: Support for browsing .tar.gz and .zip files in the editor <del>* Added: TODO/FIXME/CHANGED are now highlighted in comments. <del>* Fixed: Full screen state of windows is now persisted across restarts. <del>* Added: Makefile syntax highlighting now included. <del>* Added: Open fuzzy finder to specific line using colon suffix (i.e ':25') <del>* Fixed: Issues deleting and moving over certain UTF-8 characters <del>* Fixed: Tree view not properly highlighting or revealing for open images. <del>* Added: Packages can now be installed from the configuration UI. <del>* Fixed: .git folder now ignored by default when searching <del> <del>* Fixed: Not being able to disable packages from configuration UI. <del>* Fixed: Fuzzy finder showing poor results for entered text <del>* Improved: App icon <del> <del>* Fixed: Fuzzy finder being empty sometimes <del> <del>* Improved: App icon <del>* Fixed: End of line invisibles rendering incorrectly with the indent guide <del>* Fixed: Updates not installing automatically on restart <del>* Fixed: Wrap guide not displaying <del>* Fixed: Error when saving with the markdown preview focused <del> <del>* Fixed: Atom always running in dev mode <del>* Fixed: Crash when running in dev mode without a path to the Atom source <del> <del>* Fixed: Freeze when editing a RoR class <del>* Added: meta-N to open a new untitled editor in the current window <del> <del>* Fixed: Styling in command logger <del>* Added: XML and Ruby syntax highlighting in Markdown files <del>* Fixed: Error when editing files in a HEAD-less Git repository <del> <del>* Fixed: Invisible characters not being visible when enabled <del>* Added: Editor gutter now displays Git status for lines <del> <del>* Improved: Startup time <del>* Added: SQL bundle now included <del>* Added: PEG.js bundle now included <del>* Added: Hyperlinks can now be opened with ctrl-O <del>* Fixed: PHP syntax highlighting
1
Go
Go
skip new tests requiring same-host daemon
cfc8372c0a610ab87fed92f6ba6dd4100fef26d8
<ide><path>integration-cli/docker_cli_exec_test.go <ide> func TestExecAfterContainerRestart(t *testing.T) { <ide> } <ide> <ide> func TestExecAfterDaemonRestart(t *testing.T) { <add> testRequires(t, SameHostDaemon) <ide> defer deleteAllContainers() <ide> <ide> d := NewDaemon(t)
1
Python
Python
fix `required_python` in setup.py
ba25869045f203c62a0a9ddf5c54b7f882d8308c
<ide><path>setup.py <ide> from setuptools import find_packages, setup <ide> <ide> CURRENT_PYTHON = sys.version_info[:2] <del>REQUIRED_PYTHON = (3, 5) <add>REQUIRED_PYTHON = (3, 6) <ide> <ide> # This check and everything above must remain compatible with Python 2.7. <ide> if CURRENT_PYTHON < REQUIRED_PYTHON:
1
Text
Text
add a link to second video series about redux
e4d1f86a1db0c05c4825760e68dd9f4a7cca7022
<ide><path>README.md <ide> It is tiny (2kB, including dependencies). <ide> [![Changelog #187](https://img.shields.io/badge/changelog-%23187-lightgrey.svg?style=flat-square)](https://changelog.com/187) <ide> <ide> >**Learn Redux from its creator:** <del>>**[Getting Started with Redux](https://egghead.io/series/getting-started-with-redux) (30 free videos)** <add>>**[Part 1: Getting Started with Redux](https://egghead.io/series/getting-started-with-redux) (30 free videos)**<br> <add>>**[Part 2: Building React Applications with Idiomatic Redux](https://egghead.io/courses/building-react-applications-with-idiomatic-redux) (27 free videos)** <ide> <ide> ### Testimonials <ide>
1
PHP
PHP
apply fixes from styleci
231119b846aa975988d39707b5d404d36be710f2
<ide><path>src/Illuminate/Support/Facades/Storage.php <ide> public static function fake($disk) <ide> public static function persistentFake($disk) <ide> { <ide> static::set($disk, self::createLocalDriver([ <del> 'root' => storage_path('framework/testing/disks/' . $disk) <add> 'root' => storage_path('framework/testing/disks/'.$disk), <ide> ])); <ide> } <ide>
1
Ruby
Ruby
optimize coretap in `.deleted_reason`
2bc54e56e4ab6d3af50fa6ed52c57c99e1a4aab7
<ide><path>Library/Homebrew/missing_formula.rb <ide> def deleted_reason(name, silent: false) <ide> end <ide> end <ide> <del> commit_command = "git log --before='1 month ago' --max-count=1 --format=%H" <del> month_old_commit = Utils.popen_read(commit_command).chomp <del> <del> # Check if the formula has been deleted in the last month <del> # by comparing the diff between now and a month ago. <del> diff_command = "git diff --diff-filter=D --name-only " \ <del> "#{month_old_commit} HEAD -- #{relative_path}" <del> <del> if Utils.popen_read(diff_command).blank? <del> ofail "No previously deleted formula found." unless silent <del> return <add> # The core tap has thousands of monthly commits making the `git log` <add> # command below a performance issue when using `brew search` or <add> # `brew info` to look for a formula that doesn't exist. This first <add> # checks if the formula existed a month ago before continuing. <add> if tap.is_a? CoreTap <add> commit_command = "git log --before='1 month ago' --max-count=1 --format=%H" <add> month_old_commit_hash = Utils.popen_read(commit_command).chomp <add> <add> # Check if the formula has been deleted in the last month <add> # by comparing the diff between now and a month ago. <add> diff_command = "git diff --diff-filter=D --name-only " \ <add> "#{month_old_commit_hash} HEAD -- #{relative_path}" <add> <add> if Utils.popen_read(diff_command).blank? <add> ofail "No previously deleted formula found." unless silent <add> return <add> end <ide> end <ide> <ide> log_command = "git log --since='1 month ago' --diff-filter=D " \ <ide> "--name-only --max-count=1 " \ <del> "--format=%h\\\\n%B -- #{relative_path}" <del> short_hash, *commit_message, relative_path = <add> "--format=%H\\\\n%h\\\\n%B -- #{relative_path}" <add> hash, short_hash, *commit_message, relative_path = <ide> Utils.popen_read(log_command).gsub("\\n", "\n").lines.map(&:chomp) <ide> <add> if hash.blank? || short_hash.blank? || relative_path.blank? <add> ofail "No previously deleted formula found." unless silent <add> return <add> end <add> <ide> commit_message = commit_message.reject(&:empty?).join("\n ") <ide> <ide> commit_message.sub!(/ \(#(\d+)\)$/, " (#{tap.issues_url}/\\1)")
1
Ruby
Ruby
allow assignment right member to reference columns
d1ec33d69d85a3608aef9b064bc2c4799a214000
<ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_Or o, a <ide> end <ide> <ide> def visit_Arel_Nodes_Assignment o, a <del> right = quote(o.right, column_for(o.left)) <del> "#{visit o.left, a} = #{right}" <add> case o.right <add> when Arel::Nodes::UnqualifiedColumn, Arel::Attributes::Attribute <add> "#{visit o.left, a} = #{visit o.right, a}" <add> else <add> right = quote(o.right, column_for(o.left)) <add> "#{visit o.left, a} = #{right}" <add> end <ide> end <ide> <ide> def visit_Arel_Nodes_Equality o, a
1
Java
Java
fix flaky maybeunbsubscribeontest.normal
525bf5820533b245d572db8519b2aee63e29d853
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeUnsubscribeOnTest.java <ide> public void run() throws Exception { <ide> <ide> assertTrue(cdl.await(5, TimeUnit.SECONDS)); <ide> <add> int times = 10; <add> <add> while (times-- > 0 && pp.hasSubscribers()) { <add> Thread.sleep(100); <add> } <add> <ide> assertFalse(pp.hasSubscribers()); <ide> <ide> assertNotEquals(Thread.currentThread().getName(), name[0]);
1
Python
Python
simplify source path names in compilation test
76d12d3fcabad0371b24753ba7d36ca5b1d61bcf
<ide><path>numpy/core/tests/examples/setup.py <ide> from setuptools.extension import Extension <ide> import os <ide> <del>here = os.path.dirname(__file__) <ide> macros = [("NPY_NO_DEPRECATED_API", 0)] <ide> <ide> checks = Extension( <ide> "checks", <del> sources=[os.path.join(here, "checks.pyx")], <add> sources=[os.path.join('.', "checks.pyx")], <ide> include_dirs=[np.get_include()], <ide> define_macros=macros, <ide> ) <ide><path>numpy/core/tests/test_cython.py <ide> def install_temp(request, tmp_path): <ide> here = os.path.dirname(__file__) <ide> ext_dir = os.path.join(here, "examples") <ide> <del> tmp_path = tmp_path._str <del> cytest = os.path.join(tmp_path, "cytest") <add> cytest = str(tmp_path / "cytest") <ide> <ide> shutil.copytree(ext_dir, cytest) <ide> # build the examples and "install" them into a temporary directory <ide> <del> install_log = os.path.join(tmp_path, "tmp_install_log.txt") <add> install_log = str(tmp_path / "tmp_install_log.txt") <ide> subprocess.check_call( <ide> [ <ide> sys.executable, <ide> "setup.py", <ide> "build", <ide> "install", <del> "--prefix", <del> os.path.join(tmp_path, "installdir"), <add> "--prefix", str(tmp_path / "installdir"), <ide> "--single-version-externally-managed", <ide> "--record", <ide> install_log, <ide><path>numpy/random/_examples/cython/setup.py <ide> lib_path = join(np.get_include(), '..', '..', 'random', 'lib') <ide> <ide> extending = Extension("extending", <del> sources=[join(path, 'extending.pyx')], <add> sources=[join('.', 'extending.pyx')], <ide> include_dirs=[ <ide> np.get_include(), <ide> join(path, '..', '..') <ide> ], <ide> define_macros=defs, <ide> ) <ide> distributions = Extension("extending_distributions", <del> sources=[join(path, 'extending_distributions.pyx')], <add> sources=[join('.', 'extending_distributions.pyx')], <ide> include_dirs=[inc_path], <ide> library_dirs=[lib_path], <ide> libraries=['npyrandom'],
3
PHP
PHP
fix boolean casting in sqlite
a6e39df9f63174de55b7415202fd198cd98fb146
<ide><path>Cake/Database/Type.php <ide> public function toStatement($value, Driver $driver) { <ide> * @return boolean <ide> */ <ide> public static function boolval($value) { <del> if (is_string($value)) { <add> if (is_string($value) && !is_numeric($value)) { <ide> return strtolower($value) === 'true' ? true : false; <ide> } <ide> return !empty($value); <ide><path>Cake/Test/TestCase/Database/TypeTest.php <ide> public function testBooleanToDatabase() { <ide> <ide> $driver = $this->getMock('\Cake\Database\Driver'); <ide> $this->assertFalse($type->toDatabase(0, $driver)); <add> <add> $driver = $this->getMock('\Cake\Database\Driver'); <add> $this->assertTrue($type->toDatabase('1', $driver)); <add> <add> $driver = $this->getMock('\Cake\Database\Driver'); <add> $this->assertFalse($type->toDatabase('0', $driver)); <ide> } <ide> <ide> /** <ide> public function testBooleanToPHP() { <ide> <ide> $this->assertTrue($type->toPHP(true, $driver)); <ide> $this->assertTrue($type->toPHP(1, $driver)); <add> $this->assertTrue($type->toPHP('1', $driver)); <ide> $this->assertTrue($type->toPHP('TRUE', $driver)); <ide> $this->assertTrue($type->toPHP('true', $driver)); <ide> <ide> $this->assertFalse($type->toPHP(false, $driver)); <ide> $this->assertFalse($type->toPHP(0, $driver)); <add> $this->assertFalse($type->toPHP('0', $driver)); <ide> $this->assertFalse($type->toPHP('FALSE', $driver)); <ide> $this->assertFalse($type->toPHP('false', $driver)); <ide> }
2
Text
Text
fix changelog.md on master
cded6e7993284c734d2ae9244dfc1e5c4cd4d976
<ide><path>CHANGELOG.md <ide> # Node.js ChangeLog <ide> <add>## 2015-08-18, Version 3.1.0, @Fishrock123 <add> <add>### Notable changes <add> <add>* **buffer**: Fixed a couple large memory leaks (Ben Noordhuis) [#2352](https://github.com/nodejs/node/pull/2352). <add>* **crypto**: <add> - Fixed a couple of minor memory leaks (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375). <add> - Signing now checks for OpenSSL errors (P.S.V.R) [#2342](https://github.com/nodejs/node/pull/2342). **Note that this may expose previously hidden errors in user code.** <add>* **intl**: Intl support using small-icu is now enabled by default in builds (Steven R. Loomis) [#2264](https://github.com/nodejs/node/pull/2264). <add> - [`String#normalize()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) can now be used for unicode normalization. <add> - The [`Intl`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Intl) object and various `String` and `Number` methods are present, but only support the English locale. <add> - For support of all locales, node must be built with [full-icu](https://github.com/nodejs/node#build-with-full-icu-support-all-locales-supported-by-icu). <add>* **tls**: Fixed tls throughput being much lower after an incorrect merge (Fedor Indutny) [#2381](https://github.com/nodejs/node/pull/2381). <add>* **tools**: The v8 tick processor now comes bundled with node (Matt Loring) [#2090](https://github.com/nodejs/node/pull/2090). <add> - This can be used by producing performance profiling output by running node with `--perf`, then running your appropriate platform's script on the output as found in [tools/v8-prof](https://github.com/nodejs/node/tree/master/tools/v8-prof). <add>* **util**: `util.inspect(obj)` now prints the constructor name of the object if there is one (Christopher Monsanto) [#1935](https://github.com/nodejs/io.js/pull/1935). <add> <add>### Known issues <add> <add>See https://github.com/nodejs/io.js/labels/confirmed-bug for complete and current list of known issues. <add> <add>* Some problems with unreferenced timers running during `beforeExit` are still to be resolved. See [#1264](https://github.com/nodejs/io.js/issues/1264). <add>* Surrogate pair in REPL can freeze terminal. [#690](https://github.com/nodejs/io.js/issues/690) <add>* `process.send()` is not synchronous as the docs suggest, a regression introduced in 1.0.2, see [#760](https://github.com/nodejs/io.js/issues/760). <add>* Calling `dns.setServers()` while a DNS query is in progress can cause the process to crash on a failed assertion. [#894](https://github.com/nodejs/io.js/issues/894) <add>* `url.resolve` may transfer the auth portion of the url when resolving between two full hosts, see [#1435](https://github.com/nodejs/io.js/issues/1435). <add> <add>### Commits <add> <add>* [[`3645dc62ed`](https://github.com/nodejs/node/commit/3645dc62ed)] - **build**: work around VS2015 issue in ICU <56 (Steven R. Loomis) [#2283](https://github.com/nodejs/node/pull/2283) <add>* [[`1f12e03266`](https://github.com/nodejs/node/commit/1f12e03266)] - **(SEMVER-MINOR)** **build**: intl: converge from joyent/node (Steven R. Loomis) [#2264](https://github.com/nodejs/node/pull/2264) <add>* [[`071640abdd`](https://github.com/nodejs/node/commit/071640abdd)] - **build**: Intl: bump ICU4C from 54 to 55 (Steven R. Loomis) [#2293](https://github.com/nodejs/node/pull/2293) <add>* [[`07a88b0c8b`](https://github.com/nodejs/node/commit/07a88b0c8b)] - **build**: update manifest to include Windows 10 (Lucien Greathouse) [#2332](https://github.com/nodejs/io.js/pull/2332) <add>* [[`0bb099f444`](https://github.com/nodejs/node/commit/0bb099f444)] - **build**: expand ~ in install prefix early (Ben Noordhuis) [#2307](https://github.com/nodejs/io.js/pull/2307) <add>* [[`7fe6dd8f5d`](https://github.com/nodejs/node/commit/7fe6dd8f5d)] - **crypto**: check for OpenSSL errors when signing (P.S.V.R) [#2342](https://github.com/nodejs/node/pull/2342) <add>* [[`605f6ee904`](https://github.com/nodejs/node/commit/605f6ee904)] - **crypto**: fix memory leak in PBKDF2Request (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`ba6eb8af12`](https://github.com/nodejs/node/commit/ba6eb8af12)] - **crypto**: fix memory leak in ECDH::SetPrivateKey (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`6a16368611`](https://github.com/nodejs/node/commit/6a16368611)] - **crypto**: fix memory leak in PublicKeyCipher::Cipher (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`a760a87803`](https://github.com/nodejs/node/commit/a760a87803)] - **crypto**: fix memory leak in SafeX509ExtPrint (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`f45487cd6e`](https://github.com/nodejs/node/commit/f45487cd6e)] - **crypto**: fix memory leak in SetDHParam (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`2ff183dd86`](https://github.com/nodejs/node/commit/2ff183dd86)] - **doc**: Update FIPS instructions in README.md (Michael Dawson) [#2278](https://github.com/nodejs/node/pull/2278) <add>* [[`6483bc2e8f`](https://github.com/nodejs/node/commit/6483bc2e8f)] - **doc**: clarify options for fs.watchFile() (Rich Trott) [#2425](https://github.com/nodejs/node/pull/2425) <add>* [[`e76822f454`](https://github.com/nodejs/node/commit/e76822f454)] - **doc**: multiple documentation updates cherry picked from v0.12 (James M Snell) [#2302](https://github.com/nodejs/io.js/pull/2302) <add>* [[`1738c9680b`](https://github.com/nodejs/node/commit/1738c9680b)] - **net**: ensure Socket reported address is current (Ryan Graham) [#2095](https://github.com/nodejs/io.js/pull/2095) <add>* [[`844d3f0e3e`](https://github.com/nodejs/node/commit/844d3f0e3e)] - **path**: use '===' instead of '==' for comparison (Sam Stites) [#2388](https://github.com/nodejs/node/pull/2388) <add>* [[`7118b8a882`](https://github.com/nodejs/node/commit/7118b8a882)] - **path**: remove dead code in favor of unit tests (Nathan Woltman) [#2282](https://github.com/nodejs/io.js/pull/2282) <add>* [[`34f2cfa806`](https://github.com/nodejs/node/commit/34f2cfa806)] - **src**: better error message on failed Buffer malloc (Karl Skomski) [#2422](https://github.com/nodejs/node/pull/2422) <add>* [[`b196c1da3c`](https://github.com/nodejs/node/commit/b196c1da3c)] - **src**: fix memory leak in DLOpen (Karl Skomski) [#2375](https://github.com/nodejs/node/pull/2375) <add>* [[`d1307b2995`](https://github.com/nodejs/node/commit/d1307b2995)] - **src**: don't use fopen() in require() fast path (Ben Noordhuis) [#2377](https://github.com/nodejs/node/pull/2377) <add>* [[`455ec570d1`](https://github.com/nodejs/node/commit/455ec570d1)] - **src**: rename Buffer::Use() to Buffer::New() (Ben Noordhuis) [#2352](https://github.com/nodejs/node/pull/2352) <add>* [[`fd63e1ce2b`](https://github.com/nodejs/node/commit/fd63e1ce2b)] - **src**: introduce internal Buffer::Copy() function (Ben Noordhuis) [#2352](https://github.com/nodejs/node/pull/2352) <add>* [[`5586ceca13`](https://github.com/nodejs/node/commit/5586ceca13)] - **src**: move internal functions out of node_buffer.h (Ben Noordhuis) [#2352](https://github.com/nodejs/node/pull/2352) <add>* [[`bff9bcddb6`](https://github.com/nodejs/node/commit/bff9bcddb6)] - **src**: plug memory leaks (Ben Noordhuis) [#2352](https://github.com/nodejs/node/pull/2352) <add>* [[`ccf12df4f3`](https://github.com/nodejs/node/commit/ccf12df4f3)] - **(SEMVER-MINOR)** **src**: add total_available_size to v8 statistics (Roman Klauke) [#2348](https://github.com/nodejs/io.js/pull/2348) <add>* [[`194eeb841b`](https://github.com/nodejs/node/commit/194eeb841b)] - **test**: drop Isolate::GetCurrent() from addon tests (Ben Noordhuis) [#2427](https://github.com/nodejs/node/pull/2427) <add>* [[`46cdb2f6e2`](https://github.com/nodejs/node/commit/46cdb2f6e2)] - **test**: lint addon tests (Ben Noordhuis) [#2427](https://github.com/nodejs/node/pull/2427) <add>* [[`850c794882`](https://github.com/nodejs/node/commit/850c794882)] - **test**: refactor test-fs-watchfile.js (Rich Trott) [#2393](https://github.com/nodejs/node/pull/2393) <add>* [[`a3160c0a33`](https://github.com/nodejs/node/commit/a3160c0a33)] - **test**: correct spelling of 'childProcess' (muddletoes) [#2389](https://github.com/nodejs/node/pull/2389) <add>* [[`e51f90d747`](https://github.com/nodejs/node/commit/e51f90d747)] - **test**: option to run a subset of tests (João Reis) [#2260](https://github.com/nodejs/io.js/pull/2260) <add>* [[`cc46d3bca3`](https://github.com/nodejs/node/commit/cc46d3bca3)] - **test**: clarify dropMembership() call (Rich Trott) [#2062](https://github.com/nodejs/io.js/pull/2062) <add>* [[`0ee4df9c7a`](https://github.com/nodejs/node/commit/0ee4df9c7a)] - **test**: make listen-fd-cluster/server more robust (Sam Roberts) [#1944](https://github.com/nodejs/io.js/pull/1944) <add>* [[`cf9ba81398`](https://github.com/nodejs/node/commit/cf9ba81398)] - **test**: address timing issues in simple http tests (Gireesh Punathil) [#2294](https://github.com/nodejs/io.js/pull/2294) <add>* [[`cbb75c4f86`](https://github.com/nodejs/node/commit/cbb75c4f86)] - **tls**: fix throughput issues after incorrect merge (Fedor Indutny) [#2381](https://github.com/nodejs/node/pull/2381) <add>* [[`94b765f409`](https://github.com/nodejs/node/commit/94b765f409)] - **tls**: fix check for reused session (Fedor Indutny) [#2312](https://github.com/nodejs/io.js/pull/2312) <add>* [[`e83a41ad65`](https://github.com/nodejs/node/commit/e83a41ad65)] - **tls**: introduce internal `onticketkeycallback` (Fedor Indutny) [#2312](https://github.com/nodejs/io.js/pull/2312) <add>* [[`fb0f5d733f`](https://github.com/nodejs/node/commit/fb0f5d733f)] - **(SEMVER-MINOR)** **tools**: run the tick processor without building v8 (Matt Loring) [#2090](https://github.com/nodejs/node/pull/2090) <add>* [[`7606bdb897`](https://github.com/nodejs/node/commit/7606bdb897)] - **(SEMVER-MINOR)** **util**: display constructor when inspecting objects (Christopher Monsanto) [#1935](https://github.com/nodejs/io.js/pull/1935) <add> <ide> ## 2015-08-04, Version 3.0.0, @rvagg <ide> <ide> ### Notable changes
1
Text
Text
change informal voice to formal
19ad212cd66cfed77529be2ed5cd256ea287907c
<ide><path>guide/spanish/accessibility/accessibility-examples/index.md <ide> Para permitir que los usuarios no videntes se salten al contenido principal de u <ide> </main> <ide> ``` <ide> <del>3. Oculta el enlace "omitir navegación" por defecto. Esto garantiza que el enlace solo sea visible para los usuarios videntes cuando el enlace está enfocado. <add>3. Oculte el enlace "omitir navegación" por defecto. Esto garantiza que el enlace solo sea visible para los usuarios videntes cuando el enlace está enfocado. <ide> <del>* Crea una clase para el enlace que se puede diseñar con CSS. En mi ejemplo he añadido la clase de `skip-link` . <add>* Cree una clase para el enlace que se puede diseñar con CSS. En mi ejemplo he añadido la clase de `skip-link` . <ide> <ide> ```css <ide> .skip-link { <ide> Estos estilos CSS ocultan el enlace de manera predeterminada y solo muestran el <ide> <ide> ### Mesas accesibles <ide> <del>### Pestañas accesibles <ide>\ No newline at end of file <add>### Pestañas accesibles
1
Text
Text
fix validation based on object not _id
cfd324b4b68469ba3188e4b7ba8586e59b239693
<ide><path>guides/source/active_record_validations_callbacks.md <ide> class Person < ActiveRecord::Base <ide> end <ide> ``` <ide> <del>If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself. <add>If you want to be sure that an association is present, you'll need to test the associated object itself, and not whether the foreign key used to map the association is present: <ide> <ide> ```ruby <ide> class LineItem < ActiveRecord::Base <ide> belongs_to :order <del> validates :order_id, presence: true <add> validates :order, presence: true <ide> end <ide> ``` <ide>
1
Python
Python
improve history perf
49908fe11ab3711dcab51ff762af99694a9a27ee
<ide><path>glances/__init__.py <ide> # Global name <ide> # Version should start and end with a numerical char <ide> # See https://packaging.python.org/specifications/core-metadata/#version <del>__version__ = '3.1.8b6' <add>__version__ = '3.1.8b7' <ide> __author__ = 'Nicolas Hennion <[email protected]>' <ide> __license__ = 'LGPLv3' <ide>
1
PHP
PHP
remove useless import.
0b3da44c4d176655852c72008795cbe5d94801bf
<ide><path>src/Illuminate/Testing/PendingCommand.php <ide> use PHPUnit\Framework\TestCase as PHPUnitTestCase; <ide> use Symfony\Component\Console\Input\ArrayInput; <ide> use Symfony\Component\Console\Output\BufferedOutput; <del>use Symfony\Component\Console\Output\Output; <ide> <ide> class PendingCommand <ide> {
1
PHP
PHP
rewrite completion shell into a command
a4e221170b19473ec9323558d42b3ecb6a3d6527
<ide><path>src/Command/CompletionCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP Project <add> * @since 2.5.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\CommandCollection; <add>use Cake\Console\CommandCollectionAwareInterface; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add>use Cake\Console\Shell; <add>use Cake\Utility\Inflector; <add>use ReflectionClass; <add>use ReflectionMethod; <add> <add>/** <add> * Provide command completion shells such as bash. <add> */ <add>class CompletionCommand extends Command implements CommandCollectionAwareInterface <add>{ <add> /** <add> * @var \Cake\Command\Cake\Console\CommandCollection <add> */ <add> protected $commands; <add> <add> /** <add> * Set the command collection used to get completion data on. <add> * <add> * @param \Cake\Command\Cake\Console\CommandCollection $commands The command collection <add> * @return void <add> */ <add> public function setCommandCollection(CommandCollection $commands): void <add> { <add> $this->commands = $commands; <add> } <add> <add> /** <add> * Gets the option parser instance and configures it. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The parser to build <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $modes = [ <add> 'commands' => 'Output a list of available commands', <add> 'subcommands' => 'Output a list of available sub-commands for a command', <add> 'options' => 'Output a list of available options for a command and possible subcommand.', <add> 'fuzzy' => 'Does nothing. Only for backwards compatibility', <add> ]; <add> $modeHelp = ''; <add> foreach ($modes as $key => $help) { <add> $modeHelp .= "- <info>{$key}</info> {$help}\n"; <add> } <add> <add> $parser->setDescription( <add> 'Used by shells like bash to autocomplete command name, options and arguments' <add> )->addArgument('mode', [ <add> 'help' => 'The type of thing to get completion on.', <add> 'required' => true, <add> 'choices' => array_keys($modes), <add> ])->addArgument('command', [ <add> 'help' => 'The command name to get information on.', <add> 'required' => false, <add> ])->addArgument('subcommand', [ <add> 'help' => 'The sub-command related to command to get information on.', <add> 'required' => false, <add> ])->setEpilog([ <add> "The various modes allow you to get help information on commands and their arguments.", <add> "The available modes are:", <add> "", <add> $modeHelp, <add> "", <add> 'This command is not intended to be called manually, and should be invoked from a ' . <add> 'terminal completion script.', <add> ]); <add> <add> return $parser; <add> } <add> <add> /** <add> * Main function Prints out the list of commands. <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return int <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> $mode = $args->getArgument('mode'); <add> switch ($mode) { <add> case 'commands': <add> return $this->getCommands($args, $io); <add> case 'subcommands': <add> return $this->getSubcommands($args, $io); <add> case 'options': <add> return $this->getOptions($args, $io); <add> case 'fuzzy': <add> return static::CODE_SUCCESS; <add> default: <add> $io->err('Invalid mode chosen.'); <add> } <add> <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the list of defined commands. <add> * <add> * @param \Cake\Command\Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return int <add> */ <add> protected function getCommands(Arguments $args, ConsoleIo $io): int <add> { <add> $options = []; <add> foreach ($this->commands as $key => $value) { <add> $parts = explode(' ', $key); <add> $options[] = $parts[0]; <add> } <add> $options = array_unique($options); <add> $io->out(implode(' ', $options)); <add> <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the list of defined sub-commands. <add> * <add> * @param \Cake\Command\Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return int <add> */ <add> protected function getSubcommands(Arguments $args, ConsoleIo $io): int <add> { <add> $name = $args->getArgument('command'); <add> if ($name === null || !strlen($name)) { <add> return static::CODE_SUCCESS; <add> } <add> <add> $options = []; <add> foreach ($this->commands as $key => $value) { <add> $parts = explode(' ', $key); <add> if ($parts[0] !== $name) { <add> continue; <add> } <add> <add> // Space separate command name, collect <add> // hits as subcommands <add> if (count($parts) > 1) { <add> $options[] = implode(' ', array_slice($parts, 1)); <add> continue; <add> } <add> <add> // Handle class strings <add> if (is_string($value)) { <add> $reflection = new ReflectionClass($value); <add> $value = $reflection->newInstance(); <add> } <add> if ($value instanceof Shell) { <add> $shellCommands = $this->shellSubcommands($value); <add> $options = array_merge($options, $shellCommands); <add> } <add> } <add> $options = array_unique($options); <add> $io->out(implode(' ', $options)); <add> <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Reflect the subcommands names out of a shell. <add> * <add> * @param \Cake\Console\Shell $shell The shell to get commands for <add> * @return array A list of commands <add> */ <add> protected function shellSubcommands(Shell $shell): array <add> { <add> $shell->initialize(); <add> $shell->loadTasks(); <add> <add> $optionParser = $shell->getOptionParser(); <add> $subcommands = $optionParser->subcommands(); <add> <add> $output = array_keys($subcommands); <add> <add> // If there are no formal subcommands all methods <add> // on a shell are 'subcommands' <add> if (count($subcommands) === 0) { <add> $reflection = new ReflectionClass($shell); <add> foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { <add> if ($shell->hasMethod($method->getName())) { <add> $output[] = $method->getName(); <add> } <add> } <add> } <add> $taskNames = array_map('Cake\Utility\Inflector::underscore', $shell->taskNames); <add> $output = array_merge($output, $taskNames); <add> <add> return array_unique($output); <add> } <add> <add> /** <add> * Get the options for a command or subcommand <add> * <add> * @param \Cake\Command\Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return int <add> */ <add> protected function getOptions(Arguments $args, ConsoleIo $io): ?int <add> { <add> $name = $args->getArgument('command'); <add> $subcommand = $args->getArgument('subcommand'); <add> <add> $options = []; <add> foreach ($this->commands as $key => $value) { <add> $parts = explode(' ', $key); <add> if ($parts[0] !== $name) { <add> continue; <add> } <add> if ($subcommand && isset($parts[1]) && $parts[1] !== $subcommand) { <add> continue; <add> } <add> <add> // Handle class strings <add> if (is_string($value)) { <add> $reflection = new ReflectionClass($value); <add> $value = $reflection->newInstance(); <add> } <add> $parser = null; <add> if ($value instanceof Command) { <add> $parser = $value->getOptionParser(); <add> } <add> if ($value instanceof Shell) { <add> $value->initialize(); <add> $value->loadTasks(); <add> <add> $parser = $value->getOptionParser(); <add> $subcommand = Inflector::camelize((string)$subcommand); <add> if ($subcommand && $value->hasTask($subcommand)) { <add> $parser = $value->{$subcommand}->getOptionParser(); <add> } <add> } <add> <add> if ($parser) { <add> foreach ($parser->options() as $name => $option) { <add> $options[] = "--$name"; <add> $short = $option->short(); <add> if ($short) { <add> $options[] = "-$short"; <add> } <add> } <add> } <add> } <add> $options = array_unique($options); <add> $io->out(implode(' ', $options)); <add> <add> return static::CODE_SUCCESS; <add> } <add>} <ide><path>src/Console/CommandScanner.php <ide> protected function inflectCommandNames(array $commands): array <ide> { <ide> foreach ($commands as $i => $command) { <ide> $command['name'] = str_replace('_', ' ', $command['name']); <add> $command['fullName'] = str_replace('_', ' ', $command['fullName']); <ide> $commands[$i] = $command; <ide> } <ide> <ide><path>src/Shell/CompletionShell.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 Project <del> * @since 2.5.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Shell; <del> <del>use Cake\Console\ConsoleOptionParser; <del>use Cake\Console\Shell; <del> <del>/** <del> * Provide command completion shells such as bash. <del> * <del> * @property \Cake\Shell\Task\CommandTask $Command <del> */ <del>class CompletionShell extends Shell <del>{ <del> /** <del> * Contains tasks to load and instantiate <del> * <del> * @var array <del> */ <del> public $tasks = ['Command']; <del> <del> /** <del> * The command collection for the application <del> * <del> * @var \Cake\Console\CommandCollection <del> */ <del> protected $commandCollection; <del> <del> /** <del> * Echo no header by overriding the startup method <del> * <del> * @return void <del> */ <del> public function startup(): void <del> { <del> } <del> <del> /** <del> * Not called by the autocomplete shell - this is for curious users <del> * <del> * @return int|bool Returns the number of bytes returned from writing to stdout. <del> */ <del> public function main() <del> { <del> return $this->out($this->getOptionParser()->help()); <del> } <del> <del> /** <del> * list commands <del> * <del> * @return int|bool|null Returns the number of bytes returned from writing to stdout. <del> */ <del> public function commands() <del> { <del> $options = $this->Command->commands(); <del> <del> return $this->_output($options); <del> } <del> <del> /** <del> * list options for the named command <del> * <del> * @return int|bool|null Returns the number of bytes returned from writing to stdout. <del> */ <del> public function options() <del> { <del> $commandName = $subCommandName = ''; <del> if (!empty($this->args[0])) { <del> $commandName = $this->args[0]; <del> } <del> if (!empty($this->args[1])) { <del> $subCommandName = $this->args[1]; <del> } <del> $options = $this->Command->options($commandName, $subCommandName); <del> <del> return $this->_output($options); <del> } <del> <del> /** <del> * list subcommands for the named command <del> * <del> * @return int|bool|null Returns the number of bytes returned from writing to stdout. <del> * @throws \ReflectionException <del> */ <del> public function subcommands() <del> { <del> if (!$this->args) { <del> return $this->_output(); <del> } <del> <del> $options = $this->Command->subCommands($this->args[0]); <del> <del> return $this->_output($options); <del> } <del> <del> /** <del> * Guess autocomplete from the whole argument string <del> * <del> * @return int|bool|null Returns the number of bytes returned from writing to stdout. <del> */ <del> public function fuzzy() <del> { <del> return $this->_output(); <del> } <del> <del> /** <del> * Gets the option parser instance and configures it. <del> * <del> * @return \Cake\Console\ConsoleOptionParser <del> */ <del> public function getOptionParser(): ConsoleOptionParser <del> { <del> $parser = parent::getOptionParser(); <del> <del> $parser->setDescription( <del> 'Used by shells like bash to autocomplete command name, options and arguments' <del> )->addSubcommand('commands', [ <del> 'help' => 'Output a list of available commands', <del> 'parser' => [ <del> 'description' => 'List all available', <del> ], <del> ])->addSubcommand('subcommands', [ <del> 'help' => 'Output a list of available subcommands', <del> 'parser' => [ <del> 'description' => 'List subcommands for a command', <del> 'arguments' => [ <del> 'command' => [ <del> 'help' => 'The command name', <del> 'required' => false, <del> ], <del> ], <del> ], <del> ])->addSubcommand('options', [ <del> 'help' => 'Output a list of available options', <del> 'parser' => [ <del> 'description' => 'List options', <del> 'arguments' => [ <del> 'command' => [ <del> 'help' => 'The command name', <del> 'required' => false, <del> ], <del> 'subcommand' => [ <del> 'help' => 'The subcommand name', <del> 'required' => false, <del> ], <del> ], <del> ], <del> ])->addSubcommand('fuzzy', [ <del> 'help' => 'Guess autocomplete', <del> ])->setEpilog([ <del> 'This command is not intended to be called manually', <del> ]); <del> <del> return $parser; <del> } <del> <del> /** <del> * Emit results as a string, space delimited <del> * <del> * @param array $options The options to output <del> * @return int|bool|null Returns the number of bytes returned from writing to stdout. <del> */ <del> protected function _output(array $options = []) <del> { <del> if ($options) { <del> return $this->out(implode($options, ' ')); <del> } <del> } <del>} <ide><path>src/Shell/Task/CommandTask.php <ide> use Cake\Core\App; <ide> use Cake\Core\Plugin; <ide> use Cake\Filesystem\Filesystem; <del>use Cake\Utility\Hash; <ide> use Cake\Utility\Inflector; <del>use ReflectionClass; <del>use ReflectionMethod; <ide> <ide> /** <ide> * Base class for Shell Command reflection. <add> * <add> * @internal <ide> */ <ide> class CommandTask extends Shell <ide> { <ide> protected function _scanDir(string $dir): array <ide> <ide> return $shells; <ide> } <del> <del> /** <del> * Return a list of all commands <del> * <del> * @return array <del> */ <del> public function commands(): array <del> { <del> $shellList = $this->getShellList(); <del> $flatten = Hash::flatten($shellList); <del> $duplicates = array_intersect($flatten, array_unique(array_diff_key($flatten, array_unique($flatten)))); <del> $duplicates = Hash::expand($duplicates); <del> <del> $options = []; <del> foreach ($shellList as $type => $commands) { <del> foreach ($commands as $shell) { <del> $prefix = ''; <del> if (!in_array(strtolower($type), ['app', 'core'], true) && <del> isset($duplicates[$type]) && <del> in_array($shell, $duplicates[$type], true) <del> ) { <del> $prefix = $type . '.'; <del> } <del> <del> $options[] = $prefix . $shell; <del> } <del> } <del> <del> return $options; <del> } <del> <del> /** <del> * Return a list of subcommands for a given command <del> * <del> * @param string $commandName The command you want subcommands from. <del> * @return string[] <del> * @throws \ReflectionException <del> */ <del> public function subCommands(string $commandName): array <del> { <del> $shell = $this->getShell($commandName); <del> <del> if (!$shell) { <del> return []; <del> } <del> <del> $taskMap = $this->Tasks->normalizeArray((array)$shell->tasks); <del> $return = array_keys($taskMap); <del> $return = array_map('Cake\Utility\Inflector::underscore', $return); <del> <del> $shellMethodNames = ['main', 'help', 'getOptionParser', 'initialize', 'runCommand']; <del> <del> $baseClasses = ['Object', 'Shell', 'AppShell']; <del> <del> $Reflection = new ReflectionClass($shell); <del> $methods = $Reflection->getMethods(ReflectionMethod::IS_PUBLIC); <del> $methodNames = []; <del> foreach ($methods as $method) { <del> $declaringClass = $method->getDeclaringClass()->getShortName(); <del> if (!in_array($declaringClass, $baseClasses, true)) { <del> $methodNames[] = $method->getName(); <del> } <del> } <del> <del> $return = array_merge($return, array_diff($methodNames, $shellMethodNames)); <del> sort($return); <del> <del> return $return; <del> } <del> <del> /** <del> * Get Shell instance for the given command <del> * <del> * @param string $commandName The command you want. <del> * @return \Cake\Console\Shell|false Shell instance if the command can be found, false otherwise. <del> */ <del> public function getShell(string $commandName) <del> { <del> [$pluginDot, $name] = pluginSplit($commandName, true); <del> <del> if (in_array(strtolower((string)$pluginDot), ['app.', 'core.'], true)) { <del> $commandName = $name; <del> $pluginDot = ''; <del> } <del> <del> if (!in_array($commandName, $this->commands(), true) <del> && empty($pluginDot) <del> && !in_array($name, $this->commands(), true) <del> ) { <del> return false; <del> } <del> <del> if (empty($pluginDot)) { <del> $shellList = $this->getShellList(); <del> <del> if (!in_array($commandName, $shellList['app']) && !in_array($commandName, $shellList['CORE'], true)) { <del> unset($shellList['CORE'], $shellList['app']); <del> foreach ($shellList as $plugin => $commands) { <del> if (in_array($commandName, $commands, true)) { <del> $pluginDot = $plugin . '.'; <del> break; <del> } <del> } <del> } <del> } <del> <del> $name = Inflector::camelize($name); <del> $pluginDot = Inflector::camelize((string)$pluginDot); <del> $class = App::className($pluginDot . $name, 'Shell', 'Shell'); <del> if (!$class) { <del> return false; <del> } <del> <del> /** @var \Cake\Console\Shell $shell */ <del> $shell = new $class(); <del> $shell->plugin = trim($pluginDot, '.'); <del> $shell->initialize(); <del> <del> return $shell; <del> } <del> <del> /** <del> * Get options list for the given command or subcommand <del> * <del> * @param string $commandName The command to get options for. <del> * @param string $subCommandName The subcommand to get options for. Can be empty to get options for the command. <del> * If this parameter is used, the subcommand must be a valid subcommand of the command passed <del> * @return array Options list for the given command or subcommand <del> */ <del> public function options(string $commandName, string $subCommandName = ''): array <del> { <del> $shell = $this->getShell($commandName); <del> <del> if (!$shell) { <del> return []; <del> } <del> <del> $parser = $shell->getOptionParser(); <del> <del> if (!empty($subCommandName)) { <del> $subCommandName = Inflector::camelize($subCommandName); <del> if ($shell->hasTask($subCommandName)) { <del> $parser = $shell->{$subCommandName}->getOptionParser(); <del> } else { <del> return []; <del> } <del> } <del> <del> $options = []; <del> $array = $parser->options(); <del> /** @var \Cake\Console\ConsoleInputOption $obj */ <del> foreach ($array as $name => $obj) { <del> $options[] = "--$name"; <del> $short = $obj->short(); <del> if ($short) { <del> $options[] = "-$short"; <del> } <del> } <del> <del> return $options; <del> } <ide> } <add><path>tests/TestCase/Command/CompletionCommandTest.php <del><path>tests/TestCase/Shell/CompletionShellTest.php <ide> * @since 2.5.0 <ide> * @license https://opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Shell; <add>namespace Cake\Test\TestCase\Command; <ide> <ide> use Cake\Console\Shell; <add>use Cake\Core\Configure; <add>use Cake\Routing\Router; <ide> use Cake\TestSuite\ConsoleIntegrationTestCase; <ide> <ide> /** <del> * CompletionShellTest <add> * CompletionCommandTest <ide> */ <del>class CompletionShellTest extends ConsoleIntegrationTestCase <add>class CompletionCommandTest extends ConsoleIntegrationTestCase <ide> { <ide> /** <ide> * setUp method <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> static::setAppNamespace(); <del> $this->loadPlugins(['TestPlugin', 'TestPluginTwo']); <add> Configure::write('Plugins.autoload', ['TestPlugin', 'TestPluginTwo']); <add> <add> $this->useCommandRunner(); <ide> } <ide> <ide> /** <ide> public function setUp(): void <ide> public function tearDown(): void <ide> { <ide> parent::tearDown(); <del> static::setAppNamespace('App'); <add> Router::reload(); <ide> $this->clearPlugins(); <ide> } <ide> <ide> public function tearDown(): void <ide> public function testStartup() <ide> { <ide> $this->exec('completion'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Shell::CODE_ERROR); <ide> <ide> $this->assertOutputNotContains('Welcome to CakePHP'); <ide> } <ide> <del> /** <del> * test that main displays a warning <del> * <del> * @return void <del> */ <del> public function testMain() <del> { <del> $this->exec('completion'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <del> <del> $expected = 'This command is not intended to be called manually'; <del> $this->assertOutputContains($expected); <del> } <del> <ide> /** <ide> * test commands method that list all available commands <ide> * <ide> * @return void <ide> */ <ide> public function testCommands() <ide> { <del> $this->markTestIncomplete('pending rebuild'); <ide> $this->exec('completion commands'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> // This currently incorrectly shows `cache clearall` when it should only show `cache` <del> // The subcommands method also needs rework to handle multi-word subcommands <del> $expected = 'TestPlugin.example TestPlugin.sample TestPluginTwo.example unique welcome ' . <del> 'cache help i18n plugin routes schema_cache server upgrade version ' . <del> "abort auto_load_model demo i18m integration merge sample shell_test testing_dispatch"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> 'test_plugin.example', <add> 'test_plugin.sample', <add> 'test_plugin_two.example', <add> 'unique', <add> 'welcome', <add> 'cache', <add> 'help', <add> 'i18n', <add> 'plugin', <add> 'routes', <add> 'schema_cache', <add> 'server', <add> 'upgrade', <add> 'version', <add> 'abort', <add> 'auto_load_model', <add> 'demo', <add> 'i18m', <add> 'integration', <add> 'merge', <add> 'sample', <add> 'shell_test', <add> 'testing_dispatch', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> public function testOptionsNonExistingCommand() <ide> * <ide> * @return void <ide> */ <del> public function testOptions() <add> public function testOptionsShell() <ide> { <ide> $this->exec('completion options schema_cache'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> $expected = "--connection -c --help -h --quiet -q --verbose -v"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> '--connection -c', <add> '--help -h', <add> '--quiet -q', <add> '--verbose -v', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> * test that options with an existing command / subcommand pair returns the proper options <ide> * <ide> * @return void <ide> */ <del> public function testOptionsTask() <add> public function testOptionsShellTask() <ide> { <ide> $this->exec('completion options sample sample'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> $expected = "--help -h --quiet -q --sample -s --verbose -v"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> '--help -h', <add> '--quiet -q', <add> '--sample -s', <add> '--verbose -v', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <add> } <add> <add> /** <add> * test that options with an existing command / subcommand pair returns the proper options <add> * <add> * @return void <add> */ <add> public function testOptionsShellCommand() <add> { <add> $this->exec('completion options cache list'); <add> $this->assertExitCode(Shell::CODE_SUCCESS); <add> <add> $expected = [ <add> '--help -h', <add> '--quiet -q', <add> '--verbose -v', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> public function testOptionsTask() <ide> */ <ide> public function testSubCommandsCorePlugin() <ide> { <del> $this->exec('completion subcommands CORE.schema_cache'); <add> $this->exec('completion subcommands schema_cache'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <ide> $expected = "build clear"; <ide> public function testSubCommandsCorePlugin() <ide> */ <ide> public function testSubCommandsAppPlugin() <ide> { <del> $this->exec('completion subcommands app.sample'); <add> $this->exec('completion subcommands sample'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> $expected = "derp load returnValue sample withAbort"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> 'derp', <add> 'load', <add> 'returnValue', <add> 'sample', <add> 'withAbort', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> public function testSubCommandsAppPlugin() <ide> */ <ide> public function testSubCommandsCoreMultiwordCommand() <ide> { <del> $this->markTestIncomplete(); <del> $this->exec('completion subcommands CORE.cache'); <add> $this->exec('completion subcommands cache'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> $expected = "list clear clearall"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> 'list', 'clear', 'clearall', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> public function testSubCommandsPlugin() <ide> */ <ide> public function testSubCommandsPluginDotNotationBackwardCompatibility() <ide> { <del> $this->exec('completion subcommands TestPluginTwo.welcome'); <add> $this->exec('completion subcommands test_plugin_two.welcome'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <ide> $expected = "say_hello"; <ide> public function testSubCommandsPluginDotNotationBackwardCompatibility() <ide> */ <ide> public function testSubCommandsPluginDotNotation() <ide> { <del> $this->exec('completion subcommands TestPluginTwo.example'); <add> $this->exec('completion subcommands test_plugin_two.example'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <ide> $expected = "say_hello"; <ide> public function testSubCommandsAppDuplicatePluginNoDot() <ide> $this->exec('completion subcommands sample'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <del> $expected = "derp load returnValue sample withAbort"; <del> $this->assertOutputContains($expected); <add> $expected = [ <add> 'derp', <add> 'load', <add> 'returnValue', <add> 'sample', <add> 'withAbort', <add> ]; <add> foreach ($expected as $value) { <add> $this->assertOutputContains($value); <add> } <ide> } <ide> <ide> /** <ide> public function testSubCommandsAppDuplicatePluginNoDot() <ide> */ <ide> public function testSubCommandsPluginDuplicateApp() <ide> { <del> $this->exec('completion subcommands TestPlugin.sample'); <add> $this->exec('completion subcommands test_plugin.sample'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> <ide> $expected = "example"; <ide> public function testFuzzy() <ide> $this->exec('completion fuzzy'); <ide> $this->assertOutputEmpty(); <ide> } <add> <add> /** <add> * test that help returns content <add> * <add> * @return void <add> */ <add> public function testHelp() <add> { <add> $this->exec('completion --help'); <add> $this->assertExitCode(Shell::CODE_SUCCESS); <add> <add> $this->assertOutputContains('Output a list of available commands'); <add> $this->assertOutputContains('Output a list of available sub-commands'); <add> } <ide> } <ide><path>tests/test_app/TestApp/Application.php <ide> namespace TestApp; <ide> <ide> use Cake\Console\CommandCollection; <add>use Cake\Core\Configure; <ide> use Cake\Http\BaseApplication; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Routing\Middleware\RoutingMiddleware; <ide> class Application extends BaseApplication <ide> public function bootstrap(): void <ide> { <ide> parent::bootstrap(); <add> <add> // Load plugins defined in Configure. <add> if (Configure::check('Plugins.autoload')) { <add> foreach (Configure::read('Plugins.autoload') as $value) { <add> $this->addPlugin($value); <add> } <add> } <ide> } <ide> <ide> /**
6
Java
Java
add velocity to onscrollenddrag event
f954f3d9b674b13977f722bc3b8dc6c1b99fe6c7
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java <ide> public class OnScrollDispatchHelper { <ide> <ide> private int mPrevX = Integer.MIN_VALUE; <ide> private int mPrevY = Integer.MIN_VALUE; <add> private float mXFlingVelocity = 0; <add> private float mYFlingVelocity = 0; <add> <ide> private long mLastScrollEventTimeMs = -(MIN_EVENT_SEPARATION_MS + 1); <ide> <add> private static final float THRESHOLD = 0.1f; // Threshold for end fling <add> <ide> /** <ide> * Call from a ScrollView in onScrollChanged, returns true if this onScrollChanged is legit (not a <ide> * duplicate) and should be dispatched. <ide> public boolean onScrollChanged(int x, int y) { <ide> mPrevX != x || <ide> mPrevY != y; <ide> <add> // Skip the first calculation in each scroll <add> if (Math.abs(mXFlingVelocity) < THRESHOLD && Math.abs(mYFlingVelocity) < THRESHOLD) { <add> shouldDispatch = false; <add> } <add> <add> if (eventTime - mLastScrollEventTimeMs != 0) { <add> mXFlingVelocity = (float) (x - mPrevX) / (eventTime - mLastScrollEventTimeMs); <add> mYFlingVelocity = (float) (y - mPrevY) / (eventTime - mLastScrollEventTimeMs); <add> } <add> <ide> mLastScrollEventTimeMs = eventTime; <ide> mPrevX = x; <ide> mPrevY = y; <ide> <ide> return shouldDispatch; <ide> } <add> <add> public float getXFlingVelocity() { <add> return this.mXFlingVelocity; <add> } <add> <add> public float getYFlingVelocity() { <add> return this.mYFlingVelocity; <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java <ide> public class ReactHorizontalScrollView extends HorizontalScrollView implements <ide> ReactClippingViewGroup { <ide> <ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper(); <add> private final VelocityHelper mVelocityHelper = new VelocityHelper(); <ide> <ide> private boolean mActivelyScrolling; <ide> private @Nullable Rect mClippingRect; <ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) { <ide> <ide> mActivelyScrolling = true; <ide> <del> ReactScrollViewHelper.emitScrollEvent(this); <add> ReactScrollViewHelper.emitScrollEvent( <add> this, <add> mOnScrollDispatchHelper.getXFlingVelocity(), <add> mOnScrollDispatchHelper.getYFlingVelocity()); <ide> } <ide> } <ide> <ide> public boolean onTouchEvent(MotionEvent ev) { <ide> return false; <ide> } <ide> <add> mVelocityHelper.calculateVelocity(ev); <ide> int action = ev.getAction() & MotionEvent.ACTION_MASK; <ide> if (action == MotionEvent.ACTION_UP && mDragging) { <del> ReactScrollViewHelper.emitScrollEndDragEvent(this); <add> ReactScrollViewHelper.emitScrollEndDragEvent( <add> this, <add> mVelocityHelper.getXVelocity(), <add> mVelocityHelper.getYVelocity()); <ide> mDragging = false; <ide> // After the touch finishes, we may need to do some scrolling afterwards either as a result <ide> // of a fling or because we need to page align the content <ide> handlePostTouchScrolling(); <ide> } <add> <ide> return super.onTouchEvent(ev); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java <ide> public class ReactScrollView extends ScrollView implements ReactClippingViewGrou <ide> <ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper(); <ide> private final OverScroller mScroller; <add> private final VelocityHelper mVelocityHelper = new VelocityHelper(); <ide> <ide> private @Nullable Rect mClippingRect; <ide> private boolean mDoneFlinging; <ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) { <ide> mDoneFlinging = false; <ide> } <ide> <del> ReactScrollViewHelper.emitScrollEvent(this); <add> ReactScrollViewHelper.emitScrollEvent( <add> this, <add> mOnScrollDispatchHelper.getXFlingVelocity(), <add> mOnScrollDispatchHelper.getYFlingVelocity()); <ide> } <ide> } <ide> <ide> public boolean onTouchEvent(MotionEvent ev) { <ide> return false; <ide> } <ide> <add> mVelocityHelper.calculateVelocity(ev); <ide> int action = ev.getAction() & MotionEvent.ACTION_MASK; <ide> if (action == MotionEvent.ACTION_UP && mDragging) { <del> ReactScrollViewHelper.emitScrollEndDragEvent(this); <add> ReactScrollViewHelper.emitScrollEndDragEvent( <add> this, <add> mVelocityHelper.getXVelocity(), <add> mVelocityHelper.getYVelocity()); <ide> mDragging = false; <ide> disableFpsListener(); <ide> } <add> <ide> return super.onTouchEvent(ev); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java <ide> public class ReactScrollViewHelper { <ide> /** <ide> * Shared by {@link ReactScrollView} and {@link ReactHorizontalScrollView}. <ide> */ <del> public static void emitScrollEvent(ViewGroup scrollView) { <del> emitScrollEvent(scrollView, ScrollEventType.SCROLL); <add> public static void emitScrollEvent(ViewGroup scrollView, float xVelocity, float yVelocity) { <add> emitScrollEvent(scrollView, ScrollEventType.SCROLL, xVelocity, yVelocity); <ide> } <ide> <ide> public static void emitScrollBeginDragEvent(ViewGroup scrollView) { <ide> emitScrollEvent(scrollView, ScrollEventType.BEGIN_DRAG); <ide> } <ide> <del> public static void emitScrollEndDragEvent(ViewGroup scrollView) { <del> emitScrollEvent(scrollView, ScrollEventType.END_DRAG); <add> public static void emitScrollEndDragEvent( <add> ViewGroup scrollView, <add> float xVelocity, <add> float yVelocity) { <add> emitScrollEvent(scrollView, ScrollEventType.END_DRAG, xVelocity, yVelocity); <ide> } <ide> <ide> public static void emitScrollMomentumBeginEvent(ViewGroup scrollView) { <ide> public static void emitScrollMomentumEndEvent(ViewGroup scrollView) { <ide> } <ide> <ide> private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scrollEventType) { <add> emitScrollEvent(scrollView, scrollEventType, 0, 0); <add> } <add> <add> private static void emitScrollEvent( <add> ViewGroup scrollView, <add> ScrollEventType scrollEventType, <add> float xVelocity, <add> float yVelocity) { <ide> View contentView = scrollView.getChildAt(0); <ide> <ide> if (contentView == null) { <ide> private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scroll <ide> scrollEventType, <ide> scrollView.getScrollX(), <ide> scrollView.getScrollY(), <add> xVelocity, <add> yVelocity, <ide> contentView.getWidth(), <ide> contentView.getHeight(), <ide> scrollView.getWidth(), <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java <ide> public class ScrollEvent extends Event<ScrollEvent> { <ide> <ide> private int mScrollX; <ide> private int mScrollY; <add> private double mXVelocity; <add> private double mYVelocity; <ide> private int mContentWidth; <ide> private int mContentHeight; <ide> private int mScrollViewWidth; <ide> public static ScrollEvent obtain( <ide> ScrollEventType scrollEventType, <ide> int scrollX, <ide> int scrollY, <add> float xVelocity, <add> float yVelocity, <ide> int contentWidth, <ide> int contentHeight, <ide> int scrollViewWidth, <ide> public static ScrollEvent obtain( <ide> scrollEventType, <ide> scrollX, <ide> scrollY, <add> xVelocity, <add> yVelocity, <ide> contentWidth, <ide> contentHeight, <ide> scrollViewWidth, <ide> private void init( <ide> ScrollEventType scrollEventType, <ide> int scrollX, <ide> int scrollY, <add> float xVelocity, <add> float yVelocity, <ide> int contentWidth, <ide> int contentHeight, <ide> int scrollViewWidth, <ide> private void init( <ide> mScrollEventType = scrollEventType; <ide> mScrollX = scrollX; <ide> mScrollY = scrollY; <add> mXVelocity = xVelocity; <add> mYVelocity = yVelocity; <ide> mContentWidth = contentWidth; <ide> mContentHeight = contentHeight; <ide> mScrollViewWidth = scrollViewWidth; <ide> private WritableMap serializeEventData() { <ide> layoutMeasurement.putDouble("width", PixelUtil.toDIPFromPixel(mScrollViewWidth)); <ide> layoutMeasurement.putDouble("height", PixelUtil.toDIPFromPixel(mScrollViewHeight)); <ide> <add> WritableMap velocity = Arguments.createMap(); <add> velocity.putDouble("x", mXVelocity); <add> velocity.putDouble("y", mYVelocity); <add> <ide> WritableMap event = Arguments.createMap(); <ide> event.putMap("contentInset", contentInset); <ide> event.putMap("contentOffset", contentOffset); <ide> event.putMap("contentSize", contentSize); <ide> event.putMap("layoutMeasurement", layoutMeasurement); <add> event.putMap("velocity", velocity); <ide> <ide> event.putInt("target", getViewTag()); <ide> event.putBoolean("responderIgnoreScroll", true); <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java <add>/** <add> * Copyright (c) 2017-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.views.scroll; <add> <add>import javax.annotation.Nullable; <add> <add>import android.view.MotionEvent; <add>import android.view.VelocityTracker; <add> <add>/** <add> * This Class helps to calculate the velocity for all ScrollView. The x and y velocity <add> * will later on send to ReactScrollViewHelper for further use. <add> * <add> */ <add>public class VelocityHelper { <add> <add> private @Nullable VelocityTracker mVelocityTracker; <add> private float mXVelocity; <add> private float mYVelocity; <add> <add> /** <add> * Call from a ScrollView in onTouchEvent. <add> * Calculating the velocity for END_DRAG movement and send them back to react ScrollResponder.js <add> * */ <add> public void calculateVelocity(MotionEvent ev) { <add> int action = ev.getAction() & MotionEvent.ACTION_MASK; <add> if (mVelocityTracker == null) { <add> mVelocityTracker = VelocityTracker.obtain(); <add> } <add> mVelocityTracker.addMovement(ev); <add> <add> switch (action) { <add> case MotionEvent.ACTION_UP: <add> case MotionEvent.ACTION_CANCEL: { <add> // Calculate velocity on END_DRAG <add> mVelocityTracker.computeCurrentVelocity(1); // points/millisecond <add> mXVelocity = mVelocityTracker.getXVelocity(); <add> mYVelocity = mVelocityTracker.getYVelocity(); <add> <add> if (mVelocityTracker != null) { <add> mVelocityTracker.recycle(); <add> mVelocityTracker = null; <add> } <add> break; <add> } <add> } <add> } <add> <add> /* Needs to call ACTION_UP/CANCEL to update the mXVelocity */ <add> public float getXVelocity() { <add> return mXVelocity; <add> } <add> <add> /* Needs to call ACTION_UP/CANCEL to update the mYVelocity */ <add> public float getYVelocity() { <add> return mYVelocity; <add> } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java <ide> public void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { <ide> ScrollEventType.SCROLL, <ide> horiz, <ide> vert, <add> 0f, // can't get x velocity <add> 0f, // can't get y velocity <ide> 0, // can't get content width <ide> 0, // can't get content height <ide> mReactEditText.getWidth(), <del> mReactEditText.getHeight() <del> ); <add> mReactEditText.getHeight()); <ide> <ide> mEventDispatcher.dispatchEvent(event); <ide>
7
PHP
PHP
fix gateevaluated event docblocks
75b1e9ea2d9157d65fc3d3d8cb20840aa2887c5b
<ide><path>src/Illuminate/Auth/Access/Events/GateEvaluated.php <ide> class GateEvaluated <ide> /** <ide> * The authenticatable model. <ide> * <del> * @var \Illuminate\Contracts\Auth\Authenticatable <add> * @var \Illuminate\Contracts\Auth\Authenticatable|null <ide> */ <ide> public $user; <ide> <ide> class GateEvaluated <ide> /** <ide> * Create a new event instance. <ide> * <del> * @param \Illuminate\Contracts\Auth\Authenticatable $user <add> * @param \Illuminate\Contracts\Auth\Authenticatable|null $user <ide> * @param string $ability <ide> * @param bool|null $result <ide> * @param array $arguments <ide><path>src/Illuminate/Auth/Access/Gate.php <ide> class Gate implements GateContract <ide> */ <ide> public function __construct(Container $container, callable $userResolver, array $abilities = [], <ide> array $policies = [], array $beforeCallbacks = [], array $afterCallbacks = [], <del> callable $guessPolicyNamesUsingCallback = null) <add> callable $guessPolicyNamesUsingCallback = null) <ide> { <ide> $this->policies = $policies; <ide> $this->container = $container; <ide> protected function callAfterCallbacks($user, $ability, array $arguments, $result <ide> /** <ide> * Dispatch a gate evaluation event. <ide> * <del> * @param \Illuminate\Contracts\Auth\Authenticatable $user <add> * @param \Illuminate\Contracts\Auth\Authenticatable|null $user <ide> * @param string $ability <ide> * @param array $arguments <del> * @param bool $result <add> * @param bool|null $result <ide> * @return void <ide> */ <ide> protected function dispatchGateEvaluatedEvent($user, $ability, array $arguments, $result)
2
Javascript
Javascript
remove timeout handler when data arrives
451ff1540ab536237e8d751d241d7fc3391a4087
<ide><path>lib/http.js <ide> function responseOnEnd() { <ide> assert(!socket.writable); <ide> } else { <ide> debug('AGENT socket keep-alive'); <add> if (req.timeoutCb) { <add> socket.setTimeout(0, req.timeoutCb); <add> req.timeoutCb = null; <add> } <ide> socket.removeListener('close', socketCloseListener); <ide> socket.removeListener('error', socketErrorListener); <ide> socket.emit('free'); <ide> ClientRequest.prototype.setTimeout = function(msecs, callback) { <ide> } <ide> <ide> if (this.socket && this.socket.writable) { <add> if (this.timeoutCb) <add> this.socket.setTimeout(0, this.timeoutCb); <add> this.timeoutCb = emitTimeout; <ide> this.socket.setTimeout(msecs, emitTimeout); <ide> return; <ide> } <ide><path>test/simple/test-http-client-timeout-agent.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>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add> <add>var request_number = 0; <add>var requests_sent = 0; <add>var requests_done = 0; <add>var options = { <add> method: 'GET', <add> port: common.PORT, <add> host: '127.0.0.1', <add>}; <add> <add>//http.globalAgent.maxSockets = 15; <add> <add>var server = http.createServer(function(req, res) { <add> var m = /\/(.*)/.exec(req.url), <add> reqid = parseInt(m[1], 10); <add> if ( reqid % 2 ) { <add> // do not reply the request <add> } else { <add> res.writeHead(200, {'Content-Type': 'text/plain'}); <add> res.write(reqid.toString()); <add> res.end(); <add> } <add> request_number+=1; <add>}); <add> <add>server.listen(options.port, options.host, function() { <add> var req; <add> <add> for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { <add> options.path = '/' + requests_sent; <add> req = http.request(options); <add> req.id = requests_sent; <add> req.on('response', function(res) { <add> res.on('data', function(data) { <add> console.log('res#'+this.req.id+' data:'+data); <add> }); <add> res.on('end', function(data) { <add> console.log('res#'+this.req.id+' end'); <add> requests_done += 1; <add> }); <add> }); <add> req.on('close', function() { <add> console.log('req#'+this.id+' close'); <add> }); <add> req.on('error', function() { <add> console.log('req#'+this.id+' error'); <add> this.destroy(); <add> }); <add> req.setTimeout(50, function () { <add> var req = this; <add> console.log('req#'+this.id + ' timeout'); <add> req.abort(); <add> requests_done += 1; <add> }); <add> req.end(); <add> } <add> setTimeout(function() { <add> server.close(); <add> }, 150); <add>}); <add> <add>process.on('exit', function() { <add> console.error('done=%j sent=%j', requests_done, requests_sent); <add> assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); <add>});
2
Text
Text
fix outdate ninja link
bf46f223e77d49ff5053a0448356c36c3a7e4203
<ide><path>doc/guides/building-node-with-ninja.md <ide> The above alias can be modified slightly to produce a debug build, rather than a <ide> `alias nnodedebug='./configure --ninja && ninja -C out/Debug && ln -fs out/Debug/node node_g'` <ide> <ide> <del>[Ninja]: https://martine.github.io/ninja/ <add>[Ninja]: https://ninja-build.org/
1
Java
Java
prevent empty calls to acac #register and #scan
84a63b6d4bfbfd0d5f1e91786802b68f9cd1411a
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java <ide> import org.springframework.beans.factory.support.BeanNameGenerator; <ide> import org.springframework.context.support.GenericApplicationContext; <ide> import org.springframework.core.env.ConfigurableEnvironment; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * Standalone application context, accepting annotated classes as input - in particular <ide> public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver <ide> * @see #refresh() <ide> */ <ide> public void register(Class<?>... annotatedClasses) { <add> Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); <ide> this.reader.register(annotatedClasses); <ide> } <ide> <ide> public void register(Class<?>... annotatedClasses) { <ide> * @see #refresh() <ide> */ <ide> public void scan(String... basePackages) { <add> Assert.notEmpty(basePackages, "At least one base package must be specified"); <ide> this.scanner.scan(basePackages); <ide> } <ide>
1
Python
Python
fix "`" typo
2051a79da37cd22c3f60ac99f545ae15f28cde55
<ide><path>rest_framework/throttling.py <ide> def get_cache_key(self, request, view): <ide> If `view.throttle_scope` is not set, don't apply this throttle. <ide> <ide> Otherwise generate the unique cache key by concatenating the user id <del> with the '.throttle_scope` property of the view. <add> with the `.throttle_scope` property of the view. <ide> """ <ide> if request.user.is_authenticated: <ide> ident = request.user.pk
1
Python
Python
update runtests.py from scipy
6dfe8641e5086241dda081f82dc8a12610d52fd9
<ide><path>runtests.py <ide> $ python runtests.py -s {SAMPLE_SUBMODULE} <ide> $ python runtests.py -t {SAMPLE_TEST} <ide> $ python runtests.py --ipython <add> $ python runtests.py --python somescript.py <ide> <ide> """ <ide> <ide> SAMPLE_TEST = "numpy/linalg/tests/test_linalg.py:test_byteorder_check" <ide> SAMPLE_SUBMODULE = "linalg" <ide> <add>EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache', <add> '/usr/local/lib/ccache', '/usr/local/lib/f90cache'] <add> <ide> # --------------------------------------------------------------------- <ide> <del>__doc__ = __doc__.format(**globals()) <add> <add>if __doc__ is None: <add> __doc__ = "Run without -OO if you want usage info" <add>else: <add> __doc__ = __doc__.format(**globals()) <add> <ide> <ide> import sys <ide> import os <ide> <ide> import shutil <ide> import subprocess <add>import time <add>import imp <ide> from argparse import ArgumentParser, REMAINDER <ide> <add>ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) <add> <ide> def main(argv): <ide> parser = ArgumentParser(usage=__doc__.lstrip()) <ide> parser.add_argument("--verbose", "-v", action="count", default=1, <ide> def main(argv): <ide> help="Start Unix shell with PYTHONPATH set") <ide> parser.add_argument("--debug", "-g", action="store_true", <ide> help="Debug build") <add> parser.add_argument("--show-build-log", action="store_true", <add> help="Show build output rather than using a log file") <ide> parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, <del> help="Arguments to pass to Nose") <add> help="Arguments to pass to Nose, Python or shell") <ide> args = parser.parse_args(argv) <ide> <ide> if args.pythonpath: <ide> def main(argv): <ide> sys.path.insert(0, site_dir) <ide> os.environ['PYTHONPATH'] = site_dir <ide> <add> extra_argv = args.args[:] <add> if extra_argv and extra_argv[0] == '--': <add> extra_argv = extra_argv[1:] <add> <ide> if args.python: <del> import code <del> code.interact() <del> sys.exit(0) <add> if extra_argv: <add> # Don't use subprocess, since we don't want to include the <add> # current path in PYTHONPATH. <add> sys.argv = extra_argv <add> with open(extra_argv[0], 'r') as f: <add> script = f.read() <add> sys.modules['__main__'] = imp.new_module('__main__') <add> ns = dict(__name__='__main__', <add> __file__=extra_argv[0]) <add> exec_(script, ns) <add> sys.exit(0) <add> else: <add> import code <add> code.interact() <add> sys.exit(0) <ide> <ide> if args.ipython: <ide> import IPython <del> IPython.embed() <add> IPython.embed(user_ns={}) <ide> sys.exit(0) <ide> <ide> if args.shell: <ide> shell = os.environ.get('SHELL', 'sh') <ide> print("Spawning a Unix shell...") <del> os.execv(shell, [shell]) <add> os.execv(shell, [shell] + extra_argv) <ide> sys.exit(1) <ide> <del> extra_argv = args.args <del> <ide> if args.coverage: <del> dst_dir = os.path.join('build', 'coverage') <add> dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage') <ide> fn = os.path.join(dst_dir, 'coverage_html.js') <ide> if os.path.isdir(dst_dir) and os.path.isfile(fn): <ide> shutil.rmtree(dst_dir) <ide> def test(*a, **kw): <ide> __import__(PROJECT_MODULE) <ide> test = sys.modules[PROJECT_MODULE].test <ide> <del> result = test(args.mode, <del> verbose=args.verbose, <del> extra_argv=args.args, <del> doctests=args.doctests, <del> coverage=args.coverage) <add> # Run the tests under build/test <add> test_dir = os.path.join(ROOT_DIR, 'build', 'test') <add> <add> try: <add> shutil.rmtree(test_dir) <add> except OSError: <add> pass <add> try: <add> os.makedirs(test_dir) <add> except OSError: <add> pass <add> <add> cwd = os.getcwd() <add> try: <add> os.chdir(test_dir) <add> result = test(args.mode, <add> verbose=args.verbose, <add> extra_argv=extra_argv, <add> doctests=args.doctests, <add> coverage=args.coverage) <add> finally: <add> os.chdir(cwd) <ide> <ide> if result.wasSuccessful(): <ide> sys.exit(0) <ide> def build_project(args): <ide> <ide> """ <ide> <del> root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__))) <del> root_ok = [os.path.exists(os.path.join(root_dir, fn)) <add> root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn)) <ide> for fn in PROJECT_ROOT_FILES] <ide> if not all(root_ok): <ide> print("To build the project, run runtests.py in " <ide> "git checkout or unpacked source") <ide> sys.exit(1) <ide> <del> dst_dir = os.path.join(root_dir, 'build', 'testenv') <add> dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv') <ide> <ide> env = dict(os.environ) <ide> cmd = [sys.executable, 'setup.py'] <ide> <ide> # Always use ccache, if installed <del> env['PATH'] = os.pathsep.join(['/usr/lib/ccache'] <del> + env.get('PATH', '').split(os.pathsep)) <add> env['PATH'] = os.pathsep.join(EXTRA_PATH + env.get('PATH', '').split(os.pathsep)) <ide> <ide> if args.debug: <ide> # assume everyone uses gcc/gfortran <ide> env['OPT'] = '-O0 -ggdb' <ide> env['FOPT'] = '-O0 -ggdb' <del> cmd += ["build", "--debug"] <add> cmd += ["build"] <ide> <ide> cmd += ['install', '--prefix=' + dst_dir] <ide> <del> print("Building, see build.log...") <del> with open('build.log', 'w') as log: <del> ret = subprocess.call(cmd, env=env, stdout=log, stderr=log, <del> cwd=root_dir) <add> log_filename = os.path.join(ROOT_DIR, 'build.log') <add> <add> if args.show_build_log: <add> ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR) <add> else: <add> log_filename = os.path.join(ROOT_DIR, 'build.log') <add> print("Building, see build.log...") <add> with open(log_filename, 'w') as log: <add> p = subprocess.Popen(cmd, env=env, stdout=log, stderr=log, <add> cwd=ROOT_DIR) <add> <add> # Wait for it to finish, and print something to indicate the <add> # process is alive, but only if the log file has grown (to <add> # allow continuous integration environments kill a hanging <add> # process accurately if it produces no output) <add> last_blip = time.time() <add> last_log_size = os.stat(log_filename).st_size <add> while p.poll() is None: <add> time.sleep(0.5) <add> if time.time() - last_blip > 60: <add> log_size = os.stat(log_filename).st_size <add> if log_size > last_log_size: <add> print(" ... build in progress") <add> last_blip = time.time() <add> last_log_size = log_size <add> <add> ret = p.wait() <ide> <ide> if ret == 0: <ide> print("Build OK") <ide> else: <del> with open('build.log', 'r') as f: <del> print(f.read()) <del> print("Build failed!") <add> if not args.show_build_log: <add> with open(log_filename, 'r') as f: <add> print(f.read()) <add> print("Build failed!") <ide> sys.exit(1) <ide> <ide> from distutils.sysconfig import get_python_lib <ide> site_dir = get_python_lib(prefix=dst_dir, plat_specific=True) <ide> <ide> return site_dir <ide> <add>if sys.version_info[0] >= 3: <add> import builtins <add> exec_ = getattr(builtins, "exec") <add>else: <add> def exec_(code, globs=None, locs=None): <add> """Execute code in a namespace.""" <add> if globs is None: <add> frame = sys._getframe(1) <add> globs = frame.f_globals <add> if locs is None: <add> locs = frame.f_locals <add> del frame <add> elif locs is None: <add> locs = globs <add> exec("""exec code in globs, locs""") <add> <ide> if __name__ == "__main__": <ide> main(argv=sys.argv[1:])
1
Javascript
Javascript
add some test coverage for some error cases
c156ecd483b4adc8e16254b8cab3ee735e893271
<ide><path>packages/react-client/src/ReactFlightClient.js <ide> export function parseModelString( <ide> } else { <ide> const id = parseInt(value.substring(1), 16); <ide> const chunk = getChunk(response, id); <del> if (chunk._status === PENDING) { <del> throw new Error( <del> "We didn't expect to see a forward reference. This is a bug in the React Server.", <del> ); <del> } <ide> return readChunk(chunk); <ide> } <ide> } <ide><path>packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js <ide> global.setImmediate = cb => cb(); <ide> <ide> let act; <ide> let clientExports; <add>let clientModuleError; <ide> let webpackMap; <ide> let Stream; <ide> let React; <ide> let ReactDOMClient; <ide> let ReactServerDOMWriter; <ide> let ReactServerDOMReader; <ide> let Suspense; <add>let ErrorBoundary; <ide> <ide> describe('ReactFlightDOM', () => { <ide> beforeEach(() => { <ide> jest.resetModules(); <ide> act = require('jest-react').act; <ide> const WebpackMock = require('./utils/WebpackMock'); <ide> clientExports = WebpackMock.clientExports; <add> clientModuleError = WebpackMock.clientModuleError; <ide> webpackMap = WebpackMock.webpackMap; <ide> <ide> Stream = require('stream'); <ide> describe('ReactFlightDOM', () => { <ide> ReactDOMClient = require('react-dom/client'); <ide> ReactServerDOMWriter = require('react-server-dom-webpack/writer.node.server'); <ide> ReactServerDOMReader = require('react-server-dom-webpack'); <add> <add> ErrorBoundary = class extends React.Component { <add> state = {hasError: false, error: null}; <add> static getDerivedStateFromError(error) { <add> return { <add> hasError: true, <add> error, <add> }; <add> } <add> render() { <add> if (this.state.hasError) { <add> return this.props.fallback(this.state.error); <add> } <add> return this.props.children; <add> } <add> }; <ide> }); <ide> <ide> function getTestStream() { <ide> describe('ReactFlightDOM', () => { <ide> <ide> // Client Components <ide> <del> class ErrorBoundary extends React.Component { <del> state = {hasError: false, error: null}; <del> static getDerivedStateFromError(error) { <del> return { <del> hasError: true, <del> error, <del> }; <del> } <del> render() { <del> if (this.state.hasError) { <del> return this.props.fallback(this.state.error); <del> } <del> return this.props.children; <del> } <del> } <del> <ide> function MyErrorBoundary({children}) { <ide> return ( <ide> <ErrorBoundary fallback={e => <p>{e.message}</p>}> <ide> describe('ReactFlightDOM', () => { <ide> it('should be able to complete after aborting and throw the reason client-side', async () => { <ide> const reportedErrors = []; <ide> <del> class ErrorBoundary extends React.Component { <del> state = {hasError: false, error: null}; <del> static getDerivedStateFromError(error) { <del> return { <del> hasError: true, <del> error, <del> }; <del> } <del> render() { <del> if (this.state.hasError) { <del> return this.props.fallback(this.state.error); <del> } <del> return this.props.children; <del> } <del> } <del> <ide> const {writable, readable} = getTestStream(); <ide> const {pipe, abort} = ReactServerDOMWriter.renderToPipeableStream( <ide> <div> <ide> describe('ReactFlightDOM', () => { <ide> <ide> expect(reportedErrors).toEqual(['for reasons']); <ide> }); <add> <add> it('should be able to recover from a direct reference erroring client-side', async () => { <add> const reportedErrors = []; <add> <add> const ClientComponent = clientExports(function({prop}) { <add> return 'This should never render'; <add> }); <add> <add> const ClientReference = clientModuleError(new Error('module init error')); <add> <add> const {writable, readable} = getTestStream(); <add> const {pipe} = ReactServerDOMWriter.renderToPipeableStream( <add> <div> <add> <ClientComponent prop={ClientReference} /> <add> </div>, <add> webpackMap, <add> { <add> onError(x) { <add> reportedErrors.push(x); <add> }, <add> }, <add> ); <add> pipe(writable); <add> const response = ReactServerDOMReader.createFromReadableStream(readable); <add> <add> const container = document.createElement('div'); <add> const root = ReactDOMClient.createRoot(container); <add> <add> function App({res}) { <add> return res.readRoot(); <add> } <add> <add> await act(async () => { <add> root.render( <add> <ErrorBoundary fallback={e => <p>{e.message}</p>}> <add> <Suspense fallback={<p>(loading)</p>}> <add> <App res={response} /> <add> </Suspense> <add> </ErrorBoundary>, <add> ); <add> }); <add> expect(container.innerHTML).toBe('<p>module init error</p>'); <add> <add> expect(reportedErrors).toEqual([]); <add> }); <add> <add> it('should be able to recover from a direct reference erroring client-side async', async () => { <add> const reportedErrors = []; <add> <add> const ClientComponent = clientExports(function({prop}) { <add> return 'This should never render'; <add> }); <add> <add> let rejectPromise; <add> const ClientReference = await clientExports( <add> new Promise((resolve, reject) => { <add> rejectPromise = reject; <add> }), <add> ); <add> <add> const {writable, readable} = getTestStream(); <add> const {pipe} = ReactServerDOMWriter.renderToPipeableStream( <add> <div> <add> <ClientComponent prop={ClientReference} /> <add> </div>, <add> webpackMap, <add> { <add> onError(x) { <add> reportedErrors.push(x); <add> }, <add> }, <add> ); <add> pipe(writable); <add> const response = ReactServerDOMReader.createFromReadableStream(readable); <add> <add> const container = document.createElement('div'); <add> const root = ReactDOMClient.createRoot(container); <add> <add> function App({res}) { <add> return res.readRoot(); <add> } <add> <add> await act(async () => { <add> root.render( <add> <ErrorBoundary fallback={e => <p>{e.message}</p>}> <add> <Suspense fallback={<p>(loading)</p>}> <add> <App res={response} /> <add> </Suspense> <add> </ErrorBoundary>, <add> ); <add> }); <add> <add> expect(container.innerHTML).toBe('<p>(loading)</p>'); <add> <add> await act(async () => { <add> rejectPromise(new Error('async module init error')); <add> }); <add> <add> expect(container.innerHTML).toBe('<p>async module init error</p>'); <add> <add> expect(reportedErrors).toEqual([]); <add> }); <add> <add> it('should be able to recover from a direct reference erroring server-side', async () => { <add> const reportedErrors = []; <add> <add> const ClientComponent = clientExports(function({prop}) { <add> return 'This should never render'; <add> }); <add> <add> // We simulate a bug in the Webpack bundler which causes an error on the server. <add> for (const id in webpackMap) { <add> Object.defineProperty(webpackMap, id, { <add> get: () => { <add> throw new Error('bug in the bundler'); <add> }, <add> }); <add> } <add> <add> const {writable, readable} = getTestStream(); <add> const {pipe} = ReactServerDOMWriter.renderToPipeableStream( <add> <div> <add> <ClientComponent /> <add> </div>, <add> webpackMap, <add> { <add> onError(x) { <add> reportedErrors.push(x); <add> }, <add> }, <add> ); <add> pipe(writable); <add> <add> const response = ReactServerDOMReader.createFromReadableStream(readable); <add> <add> const container = document.createElement('div'); <add> const root = ReactDOMClient.createRoot(container); <add> <add> function App({res}) { <add> return res.readRoot(); <add> } <add> <add> await act(async () => { <add> root.render( <add> <ErrorBoundary fallback={e => <p>{e.message}</p>}> <add> <Suspense fallback={<p>(loading)</p>}> <add> <App res={response} /> <add> </Suspense> <add> </ErrorBoundary>, <add> ); <add> }); <add> expect(container.innerHTML).toBe('<p>bug in the bundler</p>'); <add> <add> expect(reportedErrors).toEqual([]); <add> }); <ide> }); <ide><path>packages/react-server-dom-webpack/src/__tests__/utils/WebpackMock.js <ide> const Module = require('module'); <ide> <ide> let webpackModuleIdx = 0; <ide> const webpackModules = {}; <add>const webpackErroredModules = {}; <ide> const webpackMap = {}; <ide> global.__webpack_require__ = function(id) { <add> if (webpackErroredModules[id]) { <add> throw webpackErroredModules[id]; <add> } <ide> return webpackModules[id]; <ide> }; <ide> <ide> Module._extensions['.client.js'] = previousLoader; <ide> exports.webpackMap = webpackMap; <ide> exports.webpackModules = webpackModules; <ide> <add>exports.clientModuleError = function clientModuleError(moduleError) { <add> const idx = '' + webpackModuleIdx++; <add> webpackErroredModules[idx] = moduleError; <add> const path = url.pathToFileURL(idx).href; <add> webpackMap[path] = { <add> '': { <add> id: idx, <add> chunks: [], <add> name: '', <add> }, <add> '*': { <add> id: idx, <add> chunks: [], <add> name: '*', <add> }, <add> }; <add> const mod = {exports: {}}; <add> nodeLoader(mod, idx); <add> return mod.exports; <add>}; <add> <ide> exports.clientExports = function clientExports(moduleExports) { <ide> const idx = '' + webpackModuleIdx++; <ide> webpackModules[idx] = moduleExports; <ide> exports.clientExports = function clientExports(moduleExports) { <ide> }, <ide> }; <ide> if (typeof moduleExports.then === 'function') { <del> moduleExports.then(asyncModuleExports => { <del> for (const name in asyncModuleExports) { <del> webpackMap[path] = { <del> [name]: { <del> id: idx, <del> chunks: [], <del> name: name, <del> }, <del> }; <del> } <del> }); <add> moduleExports.then( <add> asyncModuleExports => { <add> for (const name in asyncModuleExports) { <add> webpackMap[path] = { <add> [name]: { <add> id: idx, <add> chunks: [], <add> name: name, <add> }, <add> }; <add> } <add> }, <add> () => {}, <add> ); <ide> } <ide> for (const name in moduleExports) { <ide> webpackMap[path] = {
3
PHP
PHP
remove backwards compatibility in rijndael
d323ea3680a6bdefcb0b28b2b87c9d5a5596f7d9
<ide><path>lib/Cake/Test/TestCase/Utility/SecurityTest.php <ide> public function testRijndael() { <ide> $this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt')); <ide> } <ide> <del>/** <del> * Test that rijndael() can still decrypt values with a fixed iv. <del> * <del> * @return void <del> */ <del> public function testRijndaelBackwardCompatibility() { <del> $this->skipIf(!function_exists('mcrypt_encrypt')); <del> <del> $txt = 'The quick brown fox jumped over the lazy dog.'; <del> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi'; <del> <del> // Encrypted before random iv <del> $value = base64_decode('1WPjnq96LMzLGwNgmudHF+cAIqVUN5DaUZEpf5tm1EzSgt5iYY9o3d66iRI/fKJLTlTVGsa8HzW0jDNitmVXoQ=='); <del> $this->assertEquals($txt, Security::rijndael($value, $key, 'decrypt')); <del> } <del> <ide> /** <ide> * testRijndaelInvalidOperation method <ide> * <ide><path>lib/Cake/Utility/Security.php <ide> public static function cipher($text, $key) { <ide> /** <ide> * Encrypts/Decrypts a text using the given key using rijndael method. <ide> * <del> * Prior to 2.3.1, a fixed initialization vector was used. This was not <del> * secure. This method now uses a random iv, and will silently upgrade values when <del> * they are re-encrypted. <del> * <ide> * @param string $text Encrypted string to decrypt, normal string to encrypt <ide> * @param string $key Key to use as the encryption key for encrypted data. <ide> * @param string $operation Operation to perform, encrypt or decrypt <ide> public static function rijndael($text, $key, $operation) { <ide> $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND); <ide> return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv); <ide> } <del> // Backwards compatible decrypt with fixed iv <del> if (substr($text, $ivSize, 2) !== '$$') { <del> $iv = substr($key, strlen($key) - 32, 32); <del> return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0"); <del> } <ide> $iv = substr($text, 0, $ivSize); <ide> $text = substr($text, $ivSize + 2); <ide> return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
2
Python
Python
fix wandb/comet problems
4dbca500226e27be21dbb0eb08117dfd0c5264b3
<ide><path>src/transformers/integrations.py <ide> # Comet needs to be imported before any ML frameworks <ide> import comet_ml # noqa: F401 <ide> <add> # XXX: there should be comet_ml.ensure_configured(), like `wandb`, for now emulate it <add> comet_ml.Experiment(project_name="ensure_configured") <ide> _has_comet = True <del>except (ImportError): <add>except (ImportError, ValueError): <ide> _has_comet = False <ide> <ide> try: <ide> def setup(self, args, state, model): <ide> 'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"' <ide> ) <ide> combined_dict = {**args.to_sanitized_dict()} <del> if hasattr(model, "config"): <add> if getattr(model, "config", None) is not None: <ide> combined_dict = {**model.config.to_dict(), **combined_dict} <ide> wandb.init(project=os.getenv("WANDB_PROJECT", "huggingface"), config=combined_dict, name=args.run_name) <ide> # keep track of model topology and gradients, unsupported on TPU
1
Python
Python
add template to livy operator documentation
7dd7400dd4588e063078986026e14ea606a55a76
<ide><path>airflow/providers/apache/livy/operators/livy.py <ide> class LivyOperator(BaseOperator): <ide> This operator wraps the Apache Livy batch REST API, allowing to submit a Spark <ide> application to the underlying cluster. <ide> <del> :param file: path of the file containing the application to execute (required). <del> :param class_name: name of the application Java/Spark main class. <del> :param args: application command line arguments. <del> :param jars: jars to be used in this sessions. <del> :param py_files: python files to be used in this session. <del> :param files: files to be used in this session. <del> :param driver_memory: amount of memory to use for the driver process. <del> :param driver_cores: number of cores to use for the driver process. <del> :param executor_memory: amount of memory to use per executor process. <del> :param executor_cores: number of cores to use for each executor. <del> :param num_executors: number of executors to launch for this session. <del> :param archives: archives to be used in this session. <del> :param queue: name of the YARN queue to which the application is submitted. <del> :param name: name of this session. <del> :param conf: Spark configuration properties. <del> :param proxy_user: user to impersonate when running the job. <add> :param file: path of the file containing the application to execute (required). (templated) <add> :param class_name: name of the application Java/Spark main class. (templated) <add> :param args: application command line arguments. (templated) <add> :param jars: jars to be used in this sessions. (templated) <add> :param py_files: python files to be used in this session. (templated) <add> :param files: files to be used in this session. (templated) <add> :param driver_memory: amount of memory to use for the driver process. (templated) <add> :param driver_cores: number of cores to use for the driver process. (templated) <add> :param executor_memory: amount of memory to use per executor process. (templated) <add> :param executor_cores: number of cores to use for each executor. (templated) <add> :param num_executors: number of executors to launch for this session. (templated) <add> :param archives: archives to be used in this session. (templated) <add> :param queue: name of the YARN queue to which the application is submitted. (templated) <add> :param name: name of this session. (templated) <add> :param conf: Spark configuration properties. (templated) <add> :param proxy_user: user to impersonate when running the job. (templated) <ide> :param livy_conn_id: reference to a pre-defined Livy Connection. <ide> :param livy_conn_auth_type: The auth type for the Livy Connection. <ide> :param polling_interval: time in seconds between polling for job completion. Don't poll for values >=0
1
Ruby
Ruby
fix typo again (thanks phillip oertel)
f5ca190bd33722e6a9b3539968ae9f8ae01fb471
<ide><path>activesupport/lib/active_support/inflector/methods.rb <ide> def const_regexp(camel_cased_word) #:nodoc: <ide> end <ide> end <ide> <del> # Applies inflection rules for +singuralize+ and +pluralize+. <add> # Applies inflection rules for +singularize+ and +pluralize+. <ide> # <ide> # Examples: <ide> # apply_inflections("post", inflections.plurals) # => "posts"
1
Python
Python
show sensors alias in web interface
fa5170d0e0989b060ccb69b7427c07bc0ccbe9b1
<ide><path>glances/plugins/glances_sensors.py <ide> def update(self): <ide> <ide> pass <ide> <add> # Set the alias for each stat <add> for stat in stats: <add> alias = self.has_alias(stat["label"].lower()) <add> if alias: <add> stat["label"] = alias <add> <ide> # Update the stats <ide> self.stats = stats <ide> <ide> def msg_curse(self, args=None, max_width=None): <ide> continue <ide> # New line <ide> ret.append(self.curse_new_line()) <del> # Alias for the lable name ? <del> label = self.has_alias(i['label'].lower()) <del> if label is None: <del> label = i['label'] <del> msg = '{:{width}}'.format(label[:name_max_width], <add> msg = '{:{width}}'.format(i["label"][:name_max_width], <ide> width=name_max_width) <ide> ret.append(self.curse_add_line(msg)) <ide> if i['value'] in (b'ERR', b'SLP', b'UNK', b'NOS'):
1
Python
Python
fix undefined 'v' in python 3
970f4a7e7f8cd87f641637c5054a11d08a720d2d
<ide><path>research/tcn/data_providers.py <ide> def parse_sequence_example(serialized_example, num_views): <ide> views = tf.stack([sequence_parse[v] for v in view_names]) <ide> lens = [sequence_parse[v].get_shape().as_list()[0] for v in view_names] <ide> assert len(set(lens)) == 1 <del> seq_len = tf.shape(sequence_parse[v])[0] <add> seq_len = tf.shape(sequence_parse[view_names[-1]])[0] <ide> return context_parse, views, seq_len <ide> <ide>
1
Mixed
Javascript
support the hints option
ff8539e9e747db61a2adac6d4498ef4ee5826900
<ide><path>doc/api/tls.md <ide> being issued by trusted CA (`options.ca`). <ide> <!-- YAML <ide> added: v0.11.3 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/27816 <add> description: The `hints` option is now supported. <ide> - version: v12.2.0 <ide> pr-url: https://github.com/nodejs/node/pull/27497 <ide> description: The `enableTrace` option is now supported. <ide> changes: <ide> [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one <ide> will be created by passing the entire `options` object to <ide> `tls.createSecureContext()`. <del> * `lookup`: {Function} Custom lookup function. **Default:** <del> [`dns.lookup()`][]. <del> * `timeout`: {number} If set and if a socket is created internally, will call <del> [`socket.setTimeout(timeout)`][] after the socket is created, but before it <del> starts the connection. <ide> * ...: [`tls.createSecureContext()`][] options that are used if the <ide> `secureContext` option is missing, otherwise they are ignored. <add> * ...: Any [`socket.connect()`][] option not already listed. <ide> * `callback` {Function} <ide> * Returns: {tls.TLSSocket} <ide> <ide> where `secureSocket` has the same API as `pair.cleartext`. <ide> [`--tls-cipher-list`]: cli.html#cli_tls_cipher_list_list <ide> [`NODE_OPTIONS`]: cli.html#cli_node_options_options <ide> [`crypto.getCurves()`]: crypto.html#crypto_crypto_getcurves <del>[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback <ide> [`net.createServer()`]: net.html#net_net_createserver_options_connectionlistener <ide> [`net.Server.address()`]: net.html#net_server_address <ide> [`net.Server`]: net.html#net_class_net_server <ide> where `secureSocket` has the same API as `pair.cleartext`. <ide> [`server.getTicketKeys()`]: #tls_server_getticketkeys <ide> [`server.listen()`]: net.html#net_server_listen <ide> [`server.setTicketKeys()`]: #tls_server_setticketkeys_keys <del>[`socket.setTimeout(timeout)`]: #net_socket_settimeout_timeout_callback <add>[`socket.connect()`]: net.html#net_socket_connect_options_connectlistener <ide> [`tls.DEFAULT_ECDH_CURVE`]: #tls_tls_default_ecdh_curve <ide> [`tls.DEFAULT_MAX_VERSION`]: #tls_tls_default_max_version <ide> [`tls.DEFAULT_MIN_VERSION`]: #tls_tls_default_min_version <ide><path>lib/_tls_wrap.js <ide> exports.connect = function connect(...args) { <ide> tlssock.once('secureConnect', cb); <ide> <ide> if (!options.socket) { <del> // If user provided the socket, its their responsibility to manage its <add> // If user provided the socket, it's their responsibility to manage its <ide> // connectivity. If we created one internally, we connect it. <del> const connectOpt = { <del> path: options.path, <del> port: options.port, <del> host: options.host, <del> family: options.family, <del> localAddress: options.localAddress, <del> localPort: options.localPort, <del> lookup: options.lookup <del> }; <del> <ide> if (options.timeout) { <ide> tlssock.setTimeout(options.timeout); <ide> } <ide> <del> tlssock.connect(connectOpt, tlssock._start); <add> tlssock.connect(options, tlssock._start); <ide> } <ide> <ide> tlssock._releaseControl(); <ide><path>test/parallel/test-tls-connect-hints-option.js <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>// This test verifies that `tls.connect()` honors the `hints` option. <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const dns = require('dns'); <add>const tls = require('tls'); <add> <add>const hints = 512; <add> <add>assert.notStrictEqual(hints, dns.ADDRCONFIG); <add>assert.notStrictEqual(hints, dns.V4MAPPED); <add>assert.notStrictEqual(hints, dns.ADDRCONFIG | dns.V4MAPPED); <add> <add>tls.connect({ <add> lookup: common.mustCall((host, options) => { <add> assert.strictEqual(host, 'localhost'); <add> assert.deepStrictEqual(options, { family: undefined, hints }); <add> }), <add> hints <add>});
3
PHP
PHP
fix exception expectations
d68053c4d4816635138e638b662df7519c835857
<ide><path>lib/Cake/Test/Case/Cache/CacheTest.php <ide> public function testInvalidConfig() { <ide> /** <ide> * test that trying to configure classes that don't extend CacheEngine fail. <ide> * <add> * @expectedException CacheException <ide> * @return void <ide> */ <ide> public function testAttemptingToConfigureANonCacheEngineClass() { <ide> $this->getMock('StdClass', array(), array(), 'RubbishEngine'); <del> $this->expectException(); <ide> Cache::config('Garbage', array( <ide> 'engine' => 'Rubbish' <ide> )); <ide><path>lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php <ide> protected function _mockAcl() { <ide> /** <ide> * test authorize() without a mapped action, ensure an error is generated. <ide> * <del> * @expectedException Exception <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testAuthorizeNoMappedAction() { <ide><path>lib/Cake/Test/Case/Controller/Component/DbAclTest.php <ide> public function testCreateWithParent() { <ide> /** <ide> * testDbAclAllow method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testAllow() { <ide> public function testAllow() { <ide> // Samir should still have his tpsReports/view permissions, but does not <ide> $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update')); <ide> <del> $this->expectError(); <ide> $this->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); <ide> } <ide> <ide> /** <ide> * testAllowInvalidNode method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testAllowInvalidNode() { <del> $this->expectError(); <ide> $this->Acl->allow('Homer', 'tpsReports', 'create'); <ide> } <ide> <ide> public function testCheck() { <ide> /** <ide> * testCheckInvalidNode method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testCheckInvalidNode() { <del> $this->expectError(); <ide> $this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read')); <ide> } <ide> <ide> /** <ide> * testCheckInvalidPermission method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Notice <ide> * @return void <ide> */ <ide> public function testCheckInvalidPermission() { <del> $this->expectError(); <del> $this->assertFalse($this->Acl->check('Lumbergh', 'smash', 'foobar')); <add> $this->Acl->check('Lumbergh', 'smash', 'foobar'); <ide> } <ide> <ide> /** <ide> * testCheckMissingPermission method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testCheckMissingPermission() { <del> $this->expectError(); <del> $this->assertFalse($this->Acl->check('users', 'NonExistant', 'read')); <add> $this->Acl->check('users', 'NonExistant', 'read'); <ide> } <ide> <ide> /** <ide> public function testAclCascadingDeny() { <ide> /** <ide> * testDbAclDeny method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testDeny() { <ide> public function testDeny() { <ide> $expected = '-1'; <ide> $this->assertEqual($result[0]['PermissionTwoTest']['_delete'], $expected); <ide> <del> $this->expectError(); <ide> $this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); <ide> } <ide> <ide> public function testInherit() { <ide> /** <ide> * testDbGrant method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testGrant() { <ide> public function testGrant() { <ide> $this->assertTrue($this->Acl->check('Micheal', 'view', 'update')); <ide> $this->assertFalse($this->Acl->check('Micheal', 'view', 'delete')); <ide> <del> $this->expectError(); <ide> $this->assertFalse($this->Acl->allow('Peter', 'ROOT/tpsReports/DoesNotExist', 'create')); <ide> } <ide> <ide> /** <ide> * testDbRevoke method <ide> * <add> * @expectedException PHPUnit_Framework_Error_Warning <ide> * @return void <ide> */ <ide> public function testRevoke() { <ide> public function testRevoke() { <ide> $this->assertFalse($this->Acl->check('Samir', 'printers', 'read')); <ide> $this->assertFalse($this->Acl->check('Peter', 'printers', 'read')); <ide> <del> $this->expectError(); <del> $this->assertFalse($this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create')); <add> $this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create'); <ide> } <ide> /** <ide> * debug function - to help editing/creating test cases for the ACL component <ide><path>lib/Cake/Test/Case/Model/DbAclTest.php <ide> class AclNodeTest extends CakeTestCase { <ide> * @return void <ide> */ <ide> public function setUp() { <add> parent::setUp(); <ide> Configure::write('Acl.classname', 'TestDbAcl'); <ide> Configure::write('Acl.database', 'test'); <ide> } <ide><path>lib/Cake/Test/Case/Utility/XmlTest.php <ide> public static function invalidDataProvider() { <ide> array(null), <ide> array(false), <ide> array(''), <del> array('<tag>') <ide> ); <ide> } <ide> <ide> /** <ide> * testBuildInvalidData <ide> * <ide> * @dataProvider invalidDataProvider <del> * @expectedException Exception <add> * @expectedException XmlException <ide> * return void <ide> */ <ide> public function testBuildInvalidData($value) { <ide> Xml::build($value); <ide> } <ide> <add>/** <add> * test build with a single empty tag <add> * <add> * return void <add> */ <add> public function testBuildEmptyTag() { <add> try { <add> Xml::build('<tag>'); <add> $this->fail('No exception'); <add> } catch (Exception $e) { <add> $this->assertTrue(true, 'An exception was raised'); <add> } <add> } <add> <ide> /** <ide> * testFromArray method <ide> * <ide> public static function invalidArrayDataProvider() { <ide> * testFromArrayFail method <ide> * <ide> * @dataProvider invalidArrayDataProvider <del> * @expectedException Exception <ide> */ <ide> public function testFromArrayFail($value) { <del> Xml::fromArray($value); <add> try { <add> Xml::fromArray($value); <add> $this->fail('No exception.'); <add> } catch (Exception $e) { <add> $this->assertTrue(true, 'Caught exception.'); <add> } <ide> } <ide> <ide> /** <ide> public static function invalidToArrayDataProvider() { <ide> * testToArrayFail method <ide> * <ide> * @dataProvider invalidToArrayDataProvider <del> * @expectedException Exception <add> * @expectedException XmlException <ide> */ <ide> public function testToArrayFail($value) { <ide> Xml::toArray($value);
5