text
stringlengths
2
1.04M
meta
dict
module Mutant class Mutator class Node # OrAsgn mutator class OrAsgn < self handle(:or_asgn) children :left, :right private # Emit mutations # # @return [undefined] def dispatch emit_singletons emit_right_mutations return if n_ivasgn?(left) emit_left_mutations do |node| AST::Types::ASSIGNABLE_VARIABLES.include?(node.type) end end end # OrAsgn end # Node end # Mutator end # Mutant
{ "content_hash": "43e8ff83635643e3b7d73dff32eafc94", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 64, "avg_line_length": 18.724137931034484, "alnum_prop": 0.5395948434622467, "repo_name": "kbrock/mutant", "id": "2a1088887b17c590ebf9bd2d0f80112911458ac7", "size": "543", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/mutant/mutator/node/or_asgn.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Groff", "bytes": "466" }, { "name": "Ruby", "bytes": "482806" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Upload上传</title> <!-- Fine Uploader New/Modern CSS file ====================================================================== --> <link href="fine-uploader/fine-uploader-new.css" rel="stylesheet"> <!-- Fine Uploader JS file ====================================================================== --> <script src="fine-uploader/fine-uploader.js"></script> <!-- dialog-polyfill ====================================================================== --> <script src="/node_modules/dialog-polyfill/dialog-polyfill.js"></script> <link href="/node_modules/dialog-polyfill/dialog-polyfill.css" rel="stylesheet" type="text/css"/> <!-- 公共组件的样式 ====================================================================== --> <link rel="stylesheet" href="/dist/css/fly.css"/> <!-- 自定义上传组件的样式 ====================================================================== --> <link rel="stylesheet" href="/style/upload.css"> </head> <body> <dialog class="large-preview"> <button title="close" class="close-preview-dialog">X</button> <img class="largePreviewImg" /> </dialog> <section class="main-content"> <header> <h1>Upload上传</h1> <p>通过点击或者拖拽上传文件</p> </header> <fieldset> <legend>点击上传多个文件</legend> <div id="1-multiple-upload"> </div> <p class="comments">只能上传jpg/png文件,且不超过500kb</p> <div class="code-example"></div> </fieldset> <fieldset> <legend>图片列表样式</legend> <div id="2-pic-list-upload"> </div> <p class="comments">只能上传jpg/png文件,且不超过500kb</p> <p class="comments">点击缩略图可以预览图片</p> <div class="code-example"></div> </fieldset> <fieldset> <legend>单个图片</legend> <div id="3-pic-single-upload"> </div> <p class="comments">只能上传jpg/png文件,且不超过500kb</p> <div class="code-example"></div> </fieldset> <fieldset> <legend>拖拽上传</legend> <div id="4-drag-upload"> </div> <div class="code-example"></div> </fieldset> <fieldset> <legend>照片墙</legend> <div id="5-pic-wall"> </div> <p class="comments">只能上传jpg/png文件,且不超过500kb</p> <div class="code-example"></div> </fieldset> </section> <!-- 多个文件上传 ====================================================================== --> <script type="text/template" id="1-multiple-upload-template"> <div class="qq-uploader-selector"> <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div> </div> <ul class="qq-upload-list-selector file-list"> <li> <div class="qq-progress-bar-container-selector"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div> </div> <a href="#"> <span class="qq-upload-spinner-selector jm-icon-loading jm-icon jm-margin-r-10px"></span> <span class="jm-icon-file jm-icon jm-margin-r-10px"></span> <span class="qq-upload-file-selector"></span> </a> <span class="qq-upload-delete-selector jm-upload-btn-delete">删除</span> </li> </ul> <div class="qq-upload-button-selector jm-btn"> <div>上传</div> </div> </div> </script> <!-- 图片列表上传 ====================================================================== --> <script type="text/template" id="2-pic-list-upload-template"> <div class="qq-uploader-selector"> <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div> </div> <ul class="qq-upload-list-selector file-list"> <li> <div class="qq-progress-bar-container-selector"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div> </div> <a href="#"> <span class="qq-upload-spinner-selector jm-icon-loading jm-icon jm-margin-r-10px"></span> <img class="qq-thumbnail-selector thumbnail50-50 jm-margin-r-10px thumbnail-button" qq-max-size="100" qq-server-scale> <span class="qq-upload-file-selector"></span> </a> <span class="qq-upload-delete-selector jm-upload-btn-delete">删除</span> </li> </ul> <div class="qq-upload-button-selector jm-btn"> <div>上传</div> </div> </div> </script> <!-- 单个图片上传 ====================================================================== --> <script type="text/template" id="3-pic-single-upload-template"> <div class="qq-uploader-selector"> <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div> </div> <div class="qq-upload-button-selector jm-single-upload-placeholder"> <div class="jm-single-upload-content"> <span class="jm-icon-add jm-icon jm-upload-plus"></span> <div class="jm-single-upload-btn-text">上传</div> </div> <ul class="qq-upload-list-selector file-list jm-upload"> <li> <a href="#"> <img class="qq-thumbnail-selector thumbnail150-150" qq-max-size="100" qq-server-scale> </a> </li> </ul> </div> </div> </script> <!-- 拖拽上传 ====================================================================== --> <script type="text/template" id="4-drag-upload-template"> <div class="qq-uploader-selector"> <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div> </div> <span class="qq-drop-processing-selector qq-drop-processing"> <span>Processing dropped files...</span> <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span> </span> <div class="jm-drag-zone qq-upload-button-selector"> <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone> <span class="qq-upload-drop-area-text-selector"></span> </div> <i class="jm-icon-upload"></i> <div class="jm-dragger-text">将文件拖到此处,或<em>点击上传</em></div> </div> <p class="comments margin-bottom-10px">只能上传jpg/png文件,且不超过500kb</p> <ul class="qq-upload-list-selector file-list"> <li> <div class="qq-progress-bar-container-selector"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div> </div> <a href="#"> <span class="qq-upload-spinner-selector jm-icon-loading jm-icon jm-margin-r-10px"></span> <span class="jm-icon-file jm-icon jm-margin-r-10px"></span> <span class="qq-upload-file-selector"></span> </a> <span class="qq-upload-delete-selector jm-upload-btn-delete">删除</span> </li> </ul> </div> </script> <!-- 照片墙 ====================================================================== --> <script type="text/template" id="5-pic-wall-template"> <div class="qq-uploader-selector" > <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div> </div> <ul class="qq-upload-list-selector pic-wall-list"> <li> <div class="qq-progress-bar-container-selector"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div> </div> <a href="#"> <img class="qq-thumbnail-selector thumbnail100-100" qq-max-size="100" qq-server-scale> </a> <span class="qq-upload-delete-selector jm-upload-btn-delete">删除</span> </li> </ul> <div class="qq-upload-button-selector jm-pic-wall-placeholder"> <div class="jm-pic-wall-upload-content"> <span class="jm-icon-add jm-icon jm-upload-plus"></span> <div class="jm-single-upload-btn-text">上传</div> </div> </div> </div> </script> <script> // <!-- 多个文件上传 //====================================================================== --> new qq.FineUploader({ element: document.getElementById("1-multiple-upload"), template: '1-multiple-upload-template', request: { endpoint: "/uploads" }, deleteFile: { endpoint: "/uploads", forceConfirm: true, enabled: true }, // validation: { // allowedExtensions: ['jpeg', 'jpg', 'png'], // itemLimit: 10, // sizeLimit: 512000 // 500 kB = 500 * 1024 bytes // } }) // <!-- 图片列表上传 //====================================================================== --> var previewDialog = document.querySelector('.large-preview'); var largePreviewImg = document.querySelector('.largePreviewImg'); var largePreviewSize = 500; var picListUploader = new qq.FineUploader({ element: document.getElementById("2-pic-list-upload"), template: '2-pic-list-upload-template', request: { endpoint: "/uploads" }, deleteFile: { endpoint: "/uploads", forceConfirm: true, enabled: true }, validation: { allowedExtensions: ['jpeg', 'jpg', 'png'], itemLimit: 10, sizeLimit: 512000 // 500 kB = 500 * 1024 bytes }, callbacks: { onSubmitted: function(id, name) { var fileEl = this.getItemByFileId(id), thumbnailEl = fileEl.querySelector('.thumbnail-button'); thumbnailEl.addEventListener('click', function() { openLargerPreview(picListUploader, previewDialog, largePreviewSize, id); }); var closeButton = document.querySelector('.close-preview-dialog'); closeButton.addEventListener('click', function() { closePreview(previewDialog); }); } } }) function openLargerPreview(uploader, modal, size, fileId) { uploader.drawThumbnail(fileId, new Image(), size).then(function(image) { largePreviewImg.src = image.src; modal.showModal(); }); } function closePreview(modal) { modal.close(); } // <!-- 单个图片上传 //====================================================================== --> new qq.FineUploader({ element: document.getElementById("3-pic-single-upload"), template: '3-pic-single-upload-template', request: { endpoint: "/uploads" }, deleteFile: { endpoint: "/uploads", // forceConfirm: true, enabled: true }, validation: { allowedExtensions: ['jpeg', 'jpg', 'png'], // itemLimit: 1, sizeLimit: 512000 // 500 kB = 500 * 1024 bytes }, callbacks: { onComplete: function(id, name, response) { console.log(id); if (id > 0) { this.deleteFile(id-1); } var btnUpload= document.getElementsByClassName('jm-single-upload-content'); if (btnUpload && btnUpload.length > 0) { btnUpload[0].style.display = 'none'; } } } }) // <!-- 拖拽上传 //====================================================================== --> new qq.FineUploader({ element: document.getElementById("4-drag-upload"), template: '4-drag-upload-template', request: { endpoint: "/uploads" }, deleteFile: { endpoint: "/uploads", forceConfirm: true, enabled: true }, // validation: { // allowedExtensions: ['jpeg', 'jpg', 'png'], // itemLimit: 10, // sizeLimit: 512000 // 500 kB = 500 * 1024 bytes // } }) // <!-- 照片墙 //====================================================================== --> new qq.FineUploader({ element: document.getElementById("5-pic-wall"), template: '5-pic-wall-template', request: { endpoint: "/uploads" }, deleteFile: { endpoint: "/uploads", forceConfirm: true, enabled: true }, // validation: { // allowedExtensions: ['jpeg', 'jpg', 'png'], // itemLimit: 10, // sizeLimit: 512000 // 500 kB = 500 * 1024 bytes // } }) </script> </body> </html>
{ "content_hash": "eefc1c317a211f72a7ec066ddc7bd1e2", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 179, "avg_line_length": 36.172494172494176, "alnum_prop": 0.46236628431498905, "repo_name": "jm-team/fly", "id": "e4b8e326534e6591f84acc9fc165d40d51f6f80c", "size": "15924", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/upload/demo/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "339418" }, { "name": "HTML", "bytes": "1384951" }, { "name": "JavaScript", "bytes": "3153935" }, { "name": "PHP", "bytes": "2830" }, { "name": "Vue", "bytes": "7717" } ], "symlink_target": "" }
package net.sf.mmm.util.transferobject.base.example.common.to; import net.sf.mmm.util.transferobject.api.EntityTo; import net.sf.mmm.util.transferobject.base.example.common.Person; /** * This is the {@link EntityTo ETO} implementing {@link Person}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 5.0.0 */ public class PersonEto extends EntityTo<Long> implements Person { private static final long serialVersionUID = 1L; private Long addressId; private String lastName; private String firstName; /** * The constructor. */ public PersonEto() { super(); } @Override public String getFirstName() { return this.firstName; } @Override public void setFirstName(String firstName) { this.firstName = firstName; } @Override public String getLastName() { return this.lastName; } @Override public void setLastName(String lastName) { this.lastName = lastName; } @Override public Long getAddressId() { return this.addressId; } @Override public void setAddressId(Long addressId) { this.addressId = addressId; } }
{ "content_hash": "86c7131c94bfab33142a323b16bf642f", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 65, "avg_line_length": 16.940298507462686, "alnum_prop": 0.6951541850220264, "repo_name": "m-m-m/util", "id": "1aa7425444b2d6d13cd7695a8e4a4ed7887a4504", "size": "1263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "entity/src/test/java/net/sf/mmm/util/transferobject/base/example/common/to/PersonEto.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "116" }, { "name": "HTML", "bytes": "57" }, { "name": "Java", "bytes": "4988376" } ], "symlink_target": "" }
package org.apache.druid.segment.realtime.appenderator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.AbstractFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import org.apache.druid.data.input.Committer; import org.apache.druid.data.input.InputRow; import org.apache.druid.data.input.MapBasedInputRow; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.query.Query; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.SegmentDescriptor; import org.apache.druid.segment.loading.DataSegmentKiller; import org.apache.druid.segment.realtime.FireDepartmentMetrics; import org.apache.druid.segment.realtime.appenderator.StreamAppenderatorDriverTest.TestCommitterSupplier; import org.apache.druid.segment.realtime.appenderator.StreamAppenderatorDriverTest.TestSegmentAllocator; import org.apache.druid.segment.realtime.appenderator.StreamAppenderatorDriverTest.TestSegmentHandoffNotifierFactory; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.partition.NumberedShardSpec; import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.hamcrest.CoreMatchers; import org.joda.time.Interval; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; public class StreamAppenderatorDriverFailTest extends EasyMockSupport { private static final String DATA_SOURCE = "foo"; private static final ObjectMapper OBJECT_MAPPER = new DefaultObjectMapper(); private static final long PUBLISH_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(5); private static final List<InputRow> ROWS = ImmutableList.of( new MapBasedInputRow( DateTimes.of("2000"), ImmutableList.of("dim1"), ImmutableMap.of("dim1", "foo", "met1", "1") ), new MapBasedInputRow( DateTimes.of("2000T01"), ImmutableList.of("dim1"), ImmutableMap.of("dim1", "foo", "met1", 2.0) ), new MapBasedInputRow( DateTimes.of("2000T01"), ImmutableList.of("dim2"), ImmutableMap.of("dim2", "bar", "met1", 2.0) ) ); SegmentAllocator allocator; TestSegmentHandoffNotifierFactory segmentHandoffNotifierFactory; StreamAppenderatorDriver driver; DataSegmentKiller dataSegmentKiller; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { allocator = new TestSegmentAllocator(DATA_SOURCE, Granularities.HOUR); segmentHandoffNotifierFactory = new TestSegmentHandoffNotifierFactory(); dataSegmentKiller = createStrictMock(DataSegmentKiller.class); } @After public void tearDown() throws Exception { if (driver != null) { driver.clear(); driver.close(); } } @Test public void testFailDuringPersist() throws IOException, InterruptedException, TimeoutException, ExecutionException { expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.instanceOf(ISE.class)); expectedException.expectMessage("Fail test while persisting segments" + "[[foo_2000-01-01T00:00:00.000Z_2000-01-01T01:00:00.000Z_abc123, " + "foo_2000-01-01T01:00:00.000Z_2000-01-01T02:00:00.000Z_abc123]]"); driver = new StreamAppenderatorDriver( createPersistFailAppenderator(), allocator, segmentHandoffNotifierFactory, new NoopUsedSegmentChecker(), dataSegmentKiller, OBJECT_MAPPER, new FireDepartmentMetrics() ); driver.startJob(); final TestCommitterSupplier<Integer> committerSupplier = new TestCommitterSupplier<>(); segmentHandoffNotifierFactory.setHandoffDelay(100); Assert.assertNull(driver.startJob()); for (int i = 0; i < ROWS.size(); i++) { committerSupplier.setMetadata(i + 1); Assert.assertTrue(driver.add(ROWS.get(i), "dummy", committerSupplier, false, true).isOk()); } driver.publish( StreamAppenderatorDriverTest.makeOkPublisher(), committerSupplier.get(), ImmutableList.of("dummy") ).get(PUBLISH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } @Test public void testFailDuringPush() throws IOException, InterruptedException, TimeoutException, ExecutionException { expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.instanceOf(ISE.class)); expectedException.expectMessage("Fail test while pushing segments" + "[[foo_2000-01-01T00:00:00.000Z_2000-01-01T01:00:00.000Z_abc123, " + "foo_2000-01-01T01:00:00.000Z_2000-01-01T02:00:00.000Z_abc123]]"); driver = new StreamAppenderatorDriver( createPushFailAppenderator(), allocator, segmentHandoffNotifierFactory, new NoopUsedSegmentChecker(), dataSegmentKiller, OBJECT_MAPPER, new FireDepartmentMetrics() ); driver.startJob(); final TestCommitterSupplier<Integer> committerSupplier = new TestCommitterSupplier<>(); segmentHandoffNotifierFactory.setHandoffDelay(100); Assert.assertNull(driver.startJob()); for (int i = 0; i < ROWS.size(); i++) { committerSupplier.setMetadata(i + 1); Assert.assertTrue(driver.add(ROWS.get(i), "dummy", committerSupplier, false, true).isOk()); } driver.publish( StreamAppenderatorDriverTest.makeOkPublisher(), committerSupplier.get(), ImmutableList.of("dummy") ).get(PUBLISH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } @Test public void testFailDuringDrop() throws IOException, InterruptedException, TimeoutException, ExecutionException { expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.instanceOf(ISE.class)); expectedException.expectMessage( "Fail test while dropping segment[foo_2000-01-01T00:00:00.000Z_2000-01-01T01:00:00.000Z_abc123]" ); driver = new StreamAppenderatorDriver( createDropFailAppenderator(), allocator, segmentHandoffNotifierFactory, new NoopUsedSegmentChecker(), dataSegmentKiller, OBJECT_MAPPER, new FireDepartmentMetrics() ); driver.startJob(); final TestCommitterSupplier<Integer> committerSupplier = new TestCommitterSupplier<>(); segmentHandoffNotifierFactory.setHandoffDelay(100); Assert.assertNull(driver.startJob()); for (int i = 0; i < ROWS.size(); i++) { committerSupplier.setMetadata(i + 1); Assert.assertTrue(driver.add(ROWS.get(i), "dummy", committerSupplier, false, true).isOk()); } final SegmentsAndMetadata published = driver.publish( StreamAppenderatorDriverTest.makeOkPublisher(), committerSupplier.get(), ImmutableList.of("dummy") ).get(PUBLISH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); driver.registerHandoff(published).get(); } @Test public void testFailDuringPublish() throws Exception { expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.instanceOf(ISE.class)); expectedException.expectMessage("Failed to publish segments."); testFailDuringPublishInternal(false); } @Test public void testFailWithExceptionDuringPublish() throws Exception { expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.instanceOf(RuntimeException.class)); expectedException.expectMessage("test"); testFailDuringPublishInternal(true); } private void testFailDuringPublishInternal(boolean failWithException) throws Exception { driver = new StreamAppenderatorDriver( new FailableAppenderator(), allocator, segmentHandoffNotifierFactory, new NoopUsedSegmentChecker(), dataSegmentKiller, OBJECT_MAPPER, new FireDepartmentMetrics() ); driver.startJob(); final TestCommitterSupplier<Integer> committerSupplier = new TestCommitterSupplier<>(); segmentHandoffNotifierFactory.setHandoffDelay(100); Assert.assertNull(driver.startJob()); for (int i = 0; i < ROWS.size(); i++) { committerSupplier.setMetadata(i + 1); Assert.assertTrue(driver.add(ROWS.get(i), "dummy", committerSupplier, false, true).isOk()); } if (!failWithException) { // Should only kill segments if there was _no_ exception. dataSegmentKiller.killQuietly(new DataSegment( "foo", Intervals.of("2000-01-01T00:00:00.000Z/2000-01-01T01:00:00.000Z"), "abc123", ImmutableMap.of(), ImmutableList.of(), ImmutableList.of(), new NumberedShardSpec(0, 0), 0, 0 )); EasyMock.expectLastCall().once(); dataSegmentKiller.killQuietly(new DataSegment( "foo", Intervals.of("2000-01-01T01:00:00.000Z/2000-01-01T02:00:00.000Z"), "abc123", ImmutableMap.of(), ImmutableList.of(), ImmutableList.of(), new NumberedShardSpec(0, 0), 0, 0 )); EasyMock.expectLastCall().once(); } EasyMock.replay(dataSegmentKiller); try { driver.publish( StreamAppenderatorDriverTest.makeFailingPublisher(failWithException), committerSupplier.get(), ImmutableList.of("dummy") ).get(PUBLISH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (Exception e) { throw e; } finally { EasyMock.verify(dataSegmentKiller); } } private static class NoopUsedSegmentChecker implements UsedSegmentChecker { @Override public Set<DataSegment> findUsedSegments(Set<SegmentIdWithShardSpec> identifiers) { return ImmutableSet.of(); } } static Appenderator createPushFailAppenderator() { return new FailableAppenderator().disablePush(); } static Appenderator createPushInterruptAppenderator() { return new FailableAppenderator().interruptPush(); } static Appenderator createPersistFailAppenderator() { return new FailableAppenderator().disablePersist(); } static Appenderator createDropFailAppenderator() { return new FailableAppenderator().disableDrop(); } private static class FailableAppenderator implements Appenderator { private final Map<SegmentIdWithShardSpec, List<InputRow>> rows = new HashMap<>(); private boolean dropEnabled = true; private boolean persistEnabled = true; private boolean pushEnabled = true; private boolean interruptPush = false; private int numRows; public FailableAppenderator disableDrop() { dropEnabled = false; return this; } public FailableAppenderator disablePersist() { persistEnabled = false; return this; } public FailableAppenderator disablePush() { pushEnabled = false; interruptPush = false; return this; } public FailableAppenderator interruptPush() { pushEnabled = false; interruptPush = true; return this; } @Override public String getDataSource() { return null; } @Override public Object startJob() { return null; } @Override public AppenderatorAddResult add( SegmentIdWithShardSpec identifier, InputRow row, Supplier<Committer> committerSupplier, boolean allowIncrementalPersists ) { rows.computeIfAbsent(identifier, k -> new ArrayList<>()).add(row); numRows++; return new AppenderatorAddResult(identifier, numRows, false, null); } @Override public List<SegmentIdWithShardSpec> getSegments() { return ImmutableList.copyOf(rows.keySet()); } @Override public int getRowCount(SegmentIdWithShardSpec identifier) { final List<InputRow> rows = this.rows.get(identifier); if (rows != null) { return rows.size(); } else { return 0; } } @Override public int getTotalRowCount() { return numRows; } @Override public void clear() { rows.clear(); } @Override public ListenableFuture<?> drop(SegmentIdWithShardSpec identifier) { if (dropEnabled) { rows.remove(identifier); return Futures.immediateFuture(null); } else { return Futures.immediateFailedFuture(new ISE("Fail test while dropping segment[%s]", identifier)); } } @Override public ListenableFuture<Object> persistAll(Committer committer) { if (persistEnabled) { // do nothing return Futures.immediateFuture(committer.getMetadata()); } else { return Futures.immediateFailedFuture(new ISE("Fail test while persisting segments[%s]", rows.keySet())); } } @Override public ListenableFuture<SegmentsAndMetadata> push( Collection<SegmentIdWithShardSpec> identifiers, Committer committer, boolean useUniquePath ) { if (pushEnabled) { final List<DataSegment> segments = identifiers.stream() .map( id -> new DataSegment( id.getDataSource(), id.getInterval(), id.getVersion(), ImmutableMap.of(), ImmutableList.of(), ImmutableList.of(), id.getShardSpec(), 0, 0 ) ) .collect(Collectors.toList()); return Futures.transform( persistAll(committer), (Function<Object, SegmentsAndMetadata>) commitMetadata -> new SegmentsAndMetadata(segments, commitMetadata) ); } else { if (interruptPush) { return new AbstractFuture<SegmentsAndMetadata>() { @Override public SegmentsAndMetadata get(long timeout, TimeUnit unit) throws InterruptedException { throw new InterruptedException("Interrupt test while pushing segments"); } @Override public SegmentsAndMetadata get() throws InterruptedException { throw new InterruptedException("Interrupt test while pushing segments"); } }; } else { return Futures.immediateFailedFuture(new ISE("Fail test while pushing segments[%s]", identifiers)); } } } @Override public void close() { } @Override public void closeNow() { } @Override public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals) { throw new UnsupportedOperationException(); } @Override public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs) { throw new UnsupportedOperationException(); } } }
{ "content_hash": "a1a9cec76d7679452eab45192135eee5", "timestamp": "", "source": "github", "line_count": 526, "max_line_length": 119, "avg_line_length": 31.59315589353612, "alnum_prop": 0.6539896497773499, "repo_name": "liquidm/druid", "id": "79b575434bc9215dbb665accef411512460a64fc", "size": "17425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/test/java/org/apache/druid/segment/realtime/appenderator/StreamAppenderatorDriverFailTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "4141" }, { "name": "CSS", "bytes": "41839" }, { "name": "Dockerfile", "bytes": "6007" }, { "name": "HTML", "bytes": "20699" }, { "name": "Java", "bytes": "23022993" }, { "name": "JavaScript", "bytes": "308250" }, { "name": "Makefile", "bytes": "1572" }, { "name": "PostScript", "bytes": "5" }, { "name": "R", "bytes": "17002" }, { "name": "Roff", "bytes": "3617" }, { "name": "Shell", "bytes": "43333" }, { "name": "TSQL", "bytes": "6493" }, { "name": "TeX", "bytes": "399508" }, { "name": "Thrift", "bytes": "1003" }, { "name": "TypeScript", "bytes": "158576" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: tomes * Date: 4/23/2016 * Time: 4:53 PM. */ namespace Command; use Broadway\CommandHandling\CommandHandler; /** * Class CreatePostCommandHandler. */ class CreatePostCommandHandler extends CommandHandler { /** * @param CreatePostCommand $createPostCommand */ public function handleCreatePostCommand(CreatePostCommand $createPostCommand) { echo $createPostCommand->getTitle(); echo $createPostCommand->getContent(); } }
{ "content_hash": "6d2e1540829335e7830dab2f71c1b5b9", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 81, "avg_line_length": 20.4, "alnum_prop": 0.6941176470588235, "repo_name": "tstuttard/ddd-blog", "id": "35811f49829e5023c669da2ab3243954f416071f", "size": "510", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Command/CreatePostCommandHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "CSS", "bytes": "72" }, { "name": "Cucumber", "bytes": "874" }, { "name": "JavaScript", "bytes": "503" }, { "name": "PHP", "bytes": "74070" } ], "symlink_target": "" }
package com.example.chhavi.swiftintern; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.animation.Animation; import android.widget.ImageView; import com.chhavi.swiftintern.R; import com.example.chhavi.swiftintern.Utility.AppPreferences; /** * Created by chhavi on 11/7/15. */ public class SplashScreen extends Activity implements Animation.AnimationListener{ private ImageView mainImage; private Animation animFadeIn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen_layout); /* mainImage = (ImageView)findViewById(R.id.main_image); animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in_anim); animFadeIn.setAnimationListener(this); mainImage.setAnimation(animFadeIn);*/ Thread splashThread = new Thread(){ @Override public void run() { try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }finally { Intent i; if(AppPreferences.isLoggedIn(SplashScreen.this)) { i = new Intent(SplashScreen.this, CompaniesList.class); }else{ i = new Intent(SplashScreen.this, LogInActivity.class); } startActivity(i); finish(); } } }; splashThread.start(); } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
{ "content_hash": "76c0e67d637a717ea17c60c3868af65e", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 82, "avg_line_length": 28.242424242424242, "alnum_prop": 0.6030042918454935, "repo_name": "Swiftintern/PlacementPapers", "id": "9ebf7d05722e8e4a7984d5fa839d6ee39e428107", "size": "1864", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SwiftIntern/app/src/main/java/com/example/chhavi/swiftintern/SplashScreen.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "82685" } ], "symlink_target": "" }
require 'em-resolv-replace'
{ "content_hash": "ad55ad57daf81f9095b57ba5e7b983ff", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 27, "avg_line_length": 27, "alnum_prop": 0.8148148148148148, "repo_name": "mtvillwock/hummingbird", "id": "4e6eeaccf1db17b7a61dc6518187973b0a8c66db", "size": "27", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "config/initializers/dns.rb", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "4588" }, { "name": "Ruby", "bytes": "25418" } ], "symlink_target": "" }
<?php namespace DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp; use DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlHandler; use DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlMultiHandler; use DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\Proxy; use DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\StreamHandler; /** * Expands a URI template * * @param string $template URI template * @param array $variables Template variables * * @return string */ function uri_template($template, array $variables) { if (extension_loaded('uri_template')) { // @codeCoverageIgnoreStart return \uri_template($template, $variables); // @codeCoverageIgnoreEnd } static $uriTemplate; if (!$uriTemplate) { $uriTemplate = new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\UriTemplate(); } return $uriTemplate->expand($template, $variables); } /** * Debug function used to describe the provided value type and class. * * @param mixed $input * * @return string Returns a string containing the type of the variable and * if a class is provided, the class name. */ function describe_type($input) { switch (gettype($input)) { case 'object': return 'object(' . get_class($input) . ')'; case 'array': return 'array(' . count($input) . ')'; default: ob_start(); var_dump($input); // normalize float vs double return str_replace('double(', 'float(', rtrim(ob_get_clean())); } } /** * Parses an array of header lines into an associative array of headers. * * @param array $lines Header lines array of strings in the following * format: "Name: Value" * @return array */ function headers_from_lines($lines) { $headers = []; foreach ($lines as $line) { $parts = explode(':', $line, 2); $headers[trim($parts[0])][] = isset($parts[1]) ? trim($parts[1]) : null; } return $headers; } /** * Returns a debug stream based on the provided variable. * * @param mixed $value Optional value * * @return resource */ function debug_resource($value = null) { if (is_resource($value)) { return $value; } elseif (defined('STDOUT')) { return STDOUT; } return fopen('php://output', 'w'); } /** * Chooses and creates a default handler to use based on the environment. * * The returned handler is not wrapped by any default middlewares. * * @throws \RuntimeException if no viable Handler is available. * @return callable Returns the best handler for the given system. */ function choose_handler() { $handler = null; if (function_exists('curl_multi_exec') && function_exists('curl_exec')) { $handler = \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\Proxy::wrapSync(new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlMultiHandler(), new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlHandler()); } elseif (function_exists('curl_exec')) { $handler = new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlHandler(); } elseif (function_exists('curl_multi_exec')) { $handler = new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\CurlMultiHandler(); } if (ini_get('allow_url_fopen')) { $handler = $handler ? \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\Proxy::wrapStreaming($handler, new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\StreamHandler()) : new \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Handler\StreamHandler(); } elseif (!$handler) { throw new \RuntimeException('GuzzleHttp requires cURL, the ' . 'allow_url_fopen ini setting, or a custom HTTP handler.'); } return $handler; } /** * Get the default User-Agent string to use with Guzzle * * @return string */ function default_user_agent() { static $defaultAgent = ''; if (!$defaultAgent) { $defaultAgent = 'GuzzleHttp/' . \DeliciousBrains\WP_Offload_SES\Aws3\GuzzleHttp\Client::VERSION; if (extension_loaded('curl') && function_exists('curl_version')) { $defaultAgent .= ' curl/' . \curl_version()['version']; } $defaultAgent .= ' PHP/' . PHP_VERSION; } return $defaultAgent; } /** * Returns the default cacert bundle for the current system. * * First, the openssl.cafile and curl.cainfo php.ini settings are checked. * If those settings are not configured, then the common locations for * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X * and Windows are checked. If any of these file locations are found on * disk, they will be utilized. * * Note: the result of this function is cached for subsequent calls. * * @return string * @throws \RuntimeException if no bundle can be found. */ function default_ca_bundle() { static $cached = null; static $cafiles = [ // Red Hat, CentOS, Fedora (provided by the ca-certificates package) '/etc/pki/tls/certs/ca-bundle.crt', // Ubuntu, Debian (provided by the ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // FreeBSD (provided by the ca_root_nss package) '/usr/local/share/certs/ca-root-nss.crt', // SLES 12 (provided by the ca-certificates package) '/var/lib/ca-certificates/ca-bundle.pem', // OS X provided by homebrew (using the default path) '/usr/local/etc/openssl/cert.pem', // Google app engine '/etc/ca-certificates.crt', // Windows? 'C:\\windows\\system32\\curl-ca-bundle.crt', 'C:\\windows\\curl-ca-bundle.crt', ]; if ($cached) { return $cached; } if ($ca = ini_get('openssl.cafile')) { return $cached = $ca; } if ($ca = ini_get('curl.cainfo')) { return $cached = $ca; } foreach ($cafiles as $filename) { if (file_exists($filename)) { return $cached = $filename; } } throw new \RuntimeException(<<<EOT No system CA bundle could be found in any of the the common system locations. PHP versions earlier than 5.6 are not properly configured to use the system's CA bundle by default. In order to verify peer certificates, you will need to supply the path on disk to a certificate bundle to the 'verify' request option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not need a specific certificate bundle, then Mozilla provides a commonly used CA bundle which can be downloaded here (provided by the maintainer of cURL): https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt. Once you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP ini setting to point to the path to the file, allowing you to omit the 'verify' request option. See http://curl.haxx.se/docs/sslcerts.html for more information. EOT ); } /** * Creates an associative array of lowercase header names to the actual * header casing. * * @param array $headers * * @return array */ function normalize_header_keys(array $headers) { $result = []; foreach (array_keys($headers) as $key) { $result[strtolower($key)] = $key; } return $result; } /** * Returns true if the provided host matches any of the no proxy areas. * * This method will strip a port from the host if it is present. Each pattern * can be matched with an exact match (e.g., "foo.com" == "foo.com") or a * partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" == * "baz.foo.com", but ".foo.com" != "foo.com"). * * Areas are matched in the following cases: * 1. "*" (without quotes) always matches any hosts. * 2. An exact match. * 3. The area starts with "." and the area is the last part of the host. e.g. * '.mit.edu' will match any host that ends with '.mit.edu'. * * @param string $host Host to check against the patterns. * @param array $noProxyArray An array of host patterns. * * @return bool */ function is_host_in_noproxy($host, array $noProxyArray) { if (strlen($host) === 0) { throw new \InvalidArgumentException('Empty host provided'); } // Strip port if present. if (strpos($host, ':')) { $host = explode($host, ':', 2)[0]; } foreach ($noProxyArray as $area) { // Always match on wildcards. if ($area === '*') { return true; } elseif (empty($area)) { // Don't match on empty values. continue; } elseif ($area === $host) { // Exact matches. return true; } else { // Special match if the area when prefixed with ".". Remove any // existing leading "." and add a new leading ".". $area = '.' . ltrim($area, '.'); if (substr($host, -strlen($area)) === $area) { return true; } } } return false; } /** * Wrapper for json_decode that throws when an error occurs. * * @param string $json JSON data to parse * @param bool $assoc When true, returned objects will be converted * into associative arrays. * @param int $depth User specified recursion depth. * @param int $options Bitmask of JSON decode options. * * @return mixed * @throws \InvalidArgumentException if the JSON cannot be decoded. * @link http://www.php.net/manual/en/function.json-decode.php */ function json_decode($json, $assoc = false, $depth = 512, $options = 0) { $data = \json_decode($json, $assoc, $depth, $options); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException('json_decode error: ' . json_last_error_msg()); } return $data; } /** * Wrapper for JSON encoding that throws when an error occurs. * * @param mixed $value The value being encoded * @param int $options JSON encode option bitmask * @param int $depth Set the maximum depth. Must be greater than zero. * * @return string * @throws \InvalidArgumentException if the JSON cannot be encoded. * @link http://www.php.net/manual/en/function.json-encode.php */ function json_encode($value, $options = 0, $depth = 512) { $json = \json_encode($value, $options, $depth); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException('json_encode error: ' . json_last_error_msg()); } return $json; }
{ "content_hash": "bad9bf74409b061f486912e5f776ab99", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 272, "avg_line_length": 36.58843537414966, "alnum_prop": 0.6264757832109324, "repo_name": "mandino/nu", "id": "7f82bc496b31d97c383016357d3fea59e8effd25", "size": "10757", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "wp-content/plugins/wp-ses/vendor/Aws3/GuzzleHttp/functions.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2534865" }, { "name": "HTML", "bytes": "131438" }, { "name": "JavaScript", "bytes": "3766596" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "19289064" }, { "name": "Perl", "bytes": "2554" }, { "name": "Shell", "bytes": "1145" } ], "symlink_target": "" }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Newtonsoft.Json; using osu.Framework.Bindables; namespace osu.Framework.IO.Serialization { /// <summary> /// An interface which allows <see cref="Bindable{T}"/> to be json serialized/deserialized. /// </summary> [JsonConverter(typeof(BindableJsonConverter))] internal interface ISerializableBindable { void SerializeTo(JsonWriter writer, JsonSerializer serializer); void DeserializeFrom(JsonReader reader, JsonSerializer serializer); } }
{ "content_hash": "202145a35bce9e63ef69d0d1e4fbbc3e", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 95, "avg_line_length": 35.55555555555556, "alnum_prop": 0.728125, "repo_name": "DrabWeb/osu-framework", "id": "7805823c88084d56bc5b4ec3b68d8697c167a589", "size": "642", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "osu.Framework/IO/Serialization/ISerializableBindable.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3192069" }, { "name": "C++", "bytes": "948" }, { "name": "GLSL", "bytes": "8174" }, { "name": "PowerShell", "bytes": "2538" }, { "name": "Shell", "bytes": "1018" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="eu.freme.eservices.tilde.terminology" /> </beans>
{ "content_hash": "186e0f2300b3a0e9ffaa7f4baf735ef2", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 116, "avg_line_length": 49.81818181818182, "alnum_prop": 0.7737226277372263, "repo_name": "freme-project/e-services", "id": "1e11e968c89ebb9a452ba3cd29dee0ab76389ca9", "size": "548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tilde-services/src/main/resources/spring-configurations/tilde-terminology.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "128549" } ], "symlink_target": "" }
package org.elasticsearch.action.support; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.tasks.Task; import org.elasticsearch.transport.TransportRequest; import java.io.IOException; /** * Base class for requests that can have associated child tasks */ public class ChildTaskRequest extends TransportRequest { private String parentTaskNode; private long parentTaskId; protected ChildTaskRequest() { } public void setParentTask(String parentTaskNode, long parentTaskId) { this.parentTaskNode = parentTaskNode; this.parentTaskId = parentTaskId; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); parentTaskNode = in.readOptionalString(); parentTaskId = in.readLong(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(parentTaskNode); out.writeLong(parentTaskId); } @Override public Task createTask(long id, String type, String action) { return new Task(id, type, action, this::getDescription, parentTaskNode, parentTaskId); } }
{ "content_hash": "371190f32f380d120c770328b8d4c578", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 94, "avg_line_length": 26.914893617021278, "alnum_prop": 0.7201581027667984, "repo_name": "tebriel/elasticsearch", "id": "59ebb476703e8ccfb845bd57b7311c6da4eeed5a", "size": "2053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/elasticsearch/action/support/ChildTaskRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "8172" }, { "name": "Batchfile", "bytes": "11622" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "208368" }, { "name": "HTML", "bytes": "3409" }, { "name": "Java", "bytes": "32566355" }, { "name": "Perl", "bytes": "6923" }, { "name": "Python", "bytes": "95396" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "90887" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XamarinClient.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XamarinClient.Android")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
{ "content_hash": "e518fe2b990689d577e19b451aa439de", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 84, "avg_line_length": 37.911764705882355, "alnum_prop": 0.7579519006982157, "repo_name": "ProfessionalCSharp/ProfessionalCSharp7", "id": "bf7056f63ed382aeb54dd8946b47ffe8501e53de", "size": "1292", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "DependencyInjection/PISample/XamarinClient/XamarinClient.Android/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "210" }, { "name": "Batchfile", "bytes": "21458" }, { "name": "C#", "bytes": "1710305" }, { "name": "CSS", "bytes": "8195" }, { "name": "Dockerfile", "bytes": "439" }, { "name": "HTML", "bytes": "199109" }, { "name": "JavaScript", "bytes": "214593" }, { "name": "TypeScript", "bytes": "9812" } ], "symlink_target": "" }
package org.apache.flink.client.cli; import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.configuration.ConfigOption; import org.apache.flink.configuration.ConfigOptions; import java.time.Duration; /** Describes a client configuration parameter. */ @PublicEvolving public class ClientOptions { public static final ConfigOption<Duration> CLIENT_TIMEOUT = ConfigOptions.key("client.timeout") .durationType() .defaultValue(Duration.ofSeconds(60)) .withDeprecatedKeys( "akka.client.timeout") // the deprecated AkkaOptions.CLIENT_TIMEOUT .withDescription("Timeout on the client side."); public static final ConfigOption<Duration> CLIENT_RETRY_PERIOD = ConfigOptions.key("client.retry-period") .durationType() .defaultValue(Duration.ofMillis(2000)) .withDescription( "The interval (in ms) between consecutive retries of failed attempts to execute " + "commands through the CLI or Flink's clients, wherever retry is supported (default 2sec)."); }
{ "content_hash": "5b07ab4fa070a712a4c42054aabc29ba", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 130, "avg_line_length": 41.1, "alnum_prop": 0.6293592862935928, "repo_name": "gyfora/flink", "id": "33cda70d91da9e3f92564d1fb948283b406bd051", "size": "2033", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "flink-clients/src/main/java/org/apache/flink/client/cli/ClientOptions.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "20596" }, { "name": "Batchfile", "bytes": "1863" }, { "name": "C", "bytes": "847" }, { "name": "Cython", "bytes": "130661" }, { "name": "Dockerfile", "bytes": "5563" }, { "name": "FreeMarker", "bytes": "92068" }, { "name": "GAP", "bytes": "139514" }, { "name": "HTML", "bytes": "154937" }, { "name": "HiveQL", "bytes": "119516" }, { "name": "Java", "bytes": "92548821" }, { "name": "JavaScript", "bytes": "7038" }, { "name": "Less", "bytes": "68979" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "2574816" }, { "name": "Scala", "bytes": "10552608" }, { "name": "Shell", "bytes": "521488" }, { "name": "TypeScript", "bytes": "311274" }, { "name": "q", "bytes": "9630" } ], "symlink_target": "" }
var proj4 = require("proj4"); module.exports = function(Geozone) { Geozone.generateGeoAlarms = function(geozones, messages, cb) { // alarms collection var events = {}; var persistenceEvents = []; var emailEvents = []; var smsEvents = []; geozones.forEach(function(geozone) { messages.forEach(function (message) { // project geopoint to openlayers projection var projection = proj4('EPSG:4326', 'EPSG:3857', [message.longitude, message.latitude]); var x = projection[0]; var y = projection[1]; var inside = false; for (var i = 0, j = geozone.geometry.length - 1; i < geozone.geometry.length; j = i++) { var xi = geozone.geometry[i][0], yi = geozone.geometry[i][1]; var xj = geozone.geometry[j][0], yj = geozone.geometry[j][1]; var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); if (intersect) { if (geozone.events.persist == true) { persistenceEvents.push({ message: geozone.message, date: new Date(), group: 'alarm', type: geozone.type, projectId: message.projectId, hubById: message.hubId, confirm: false }); } if (geozone.events.emails.length > 0) { emailEvents.push({ message: geozone.message, date: new Date(), group: 'alarm', type: geozone.type, hubDescription: message.hubDescription, deviceDescription: message.deviceDescription, emails: geozone.events.emails }); } if (geozone.events.telephones.length > 0) { smsEvents.push({ message: geozone.message, date: new Date(), group: 'alarm', type: geozone.type, hubDescription: message.hubDescription, deviceDescription: message.deviceDescription, telephones: geozone.events.telephones }); } } } }); }); // exist when all alarm designe are treated events.persistenceEvents = persistenceEvents; events.emailEvents = emailEvents; events.smsEvents = smsEvents; // if created all events for all messages alarmed exit cb(null, events); }; Geozone.remoteMethod ( 'generateGeoAlarms', { description : "Find events in a date interval from a organization", accepts: [{arg: 'geozones', description: 'Geozones', type: 'array', required: true, http: {source: 'body'}}, {arg: 'points', description: 'geopoints', type: 'array', required: true, http: {source: 'body'}}], returns: {arg: 'result', type: 'boolean', root: true}, http: {verb: 'post', path: '/geozones/generateGeoAlarms'} } ); };
{ "content_hash": "fccd4bc487f15da25281122a68eb7500", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 121, "avg_line_length": 42.666666666666664, "alnum_prop": 0.43345905172413796, "repo_name": "thingtrack/node-sensor-api", "id": "5c030fb759e78c8423a2c446ec118c44f34877cd", "size": "3712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/models/geozone.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "12944" } ], "symlink_target": "" }
import { deepEqual, equal } from 'assert'; import { WindowsExternalTerminalService, LinuxExternalTerminalService, MacExternalTerminalService, DEFAULT_TERMINAL_OSX } from 'vs/workbench/contrib/externalTerminal/node/externalTerminalService'; suite('ExternalTerminalService', () => { let mockOnExit: Function; let mockOnError: Function; let mockConfig: any; setup(() => { mockConfig = { terminal: { explorerKind: 'external', external: { windowsExec: 'testWindowsShell', osxExec: 'testOSXShell', linuxExec: 'testLinuxShell' } } }; mockOnExit = (s: any) => s; mockOnError = (e: any) => e; }); test(`WinTerminalService - uses terminal from configuration`, done => { let testShell = 'cmd'; let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(command, testShell, 'shell should equal expected'); equal(args[args.length - 1], mockConfig.terminal.external.windowsExec, 'terminal should equal expected'); equal(opts.cwd, testCwd, 'opts.cwd should equal expected'); done(); return { on: (evt: any) => evt }; } }; let testService = new WindowsExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testShell, testCwd, mockOnExit, mockOnError ); }); test(`WinTerminalService - uses default terminal when configuration.terminal.external.windowsExec is undefined`, done => { let testShell = 'cmd'; let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(args[args.length - 1], WindowsExternalTerminalService.getDefaultTerminalWindows(), 'terminal should equal expected'); done(); return { on: (evt: any) => evt }; } }; mockConfig.terminal.external.windowsExec = undefined; let testService = new WindowsExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testShell, testCwd, mockOnExit, mockOnError ); }); test(`WinTerminalService - uses default terminal when configuration.terminal.external.windowsExec is undefined`, done => { let testShell = 'cmd'; let testCwd = 'c:/foo'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(opts.cwd, 'C:/foo', 'cwd should be uppercase regardless of the case that\'s passed in'); done(); return { on: (evt: any) => evt }; } }; let testService = new WindowsExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testShell, testCwd, mockOnExit, mockOnError ); }); test(`WinTerminalService - cmder should be spawned differently`, done => { let testShell = 'cmd'; mockConfig.terminal.external.windowsExec = 'cmder'; let testCwd = 'c:/foo'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert deepEqual(args, ['C:/foo']); equal(opts, undefined); done(); return { on: (evt: any) => evt }; } }; let testService = new WindowsExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testShell, testCwd, mockOnExit, mockOnError ); }); test(`MacTerminalService - uses terminal from configuration`, done => { let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(args[1], mockConfig.terminal.external.osxExec, 'terminal should equal expected'); done(); return { on: (evt: any) => evt }; } }; let testService = new MacExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testCwd, mockOnExit, mockOnError ); }); test(`MacTerminalService - uses default terminal when configuration.terminal.external.osxExec is undefined`, done => { let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(args[1], DEFAULT_TERMINAL_OSX, 'terminal should equal expected'); done(); return { on: (evt: any) => evt }; } }; mockConfig.terminal.external.osxExec = undefined; let testService = new MacExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testCwd, mockOnExit, mockOnError ); }); test(`LinuxTerminalService - uses terminal from configuration`, done => { let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(command, mockConfig.terminal.external.linuxExec, 'terminal should equal expected'); equal(opts.cwd, testCwd, 'opts.cwd should equal expected'); done(); return { on: (evt: any) => evt }; } }; let testService = new LinuxExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testCwd, mockOnExit, mockOnError ); }); test(`LinuxTerminalService - uses default terminal when configuration.terminal.external.linuxExec is undefined`, done => { LinuxExternalTerminalService.getDefaultTerminalLinuxReady().then(defaultTerminalLinux => { let testCwd = 'path/to/workspace'; let mockSpawner = { spawn: (command: any, args: any, opts: any) => { // assert equal(command, defaultTerminalLinux, 'terminal should equal expected'); done(); return { on: (evt: any) => evt }; } }; mockConfig.terminal.external.linuxExec = undefined; let testService = new LinuxExternalTerminalService(mockConfig); (<any>testService).spawnTerminal( mockSpawner, mockConfig, testCwd, mockOnExit, mockOnError ); }); }); });
{ "content_hash": "859ad7f1acadc177dc49d36cbce8eccc", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 196, "avg_line_length": 27.00921658986175, "alnum_prop": 0.6625149291929705, "repo_name": "joaomoreno/vscode", "id": "821460d6eb7e07320eacf49eba4879d9b0a86b78", "size": "6212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/vs/workbench/contrib/externalTerminal/node/externalTerminalService.test.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5218" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "1640" }, { "name": "C++", "bytes": "1072" }, { "name": "CSS", "bytes": "444529" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "652" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "32402" }, { "name": "Inno Setup", "bytes": "131467" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "869244" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "941" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl 6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "8943" }, { "name": "Python", "bytes": "2119" }, { "name": "R", "bytes": "362" }, { "name": "Roff", "bytes": "351" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "38696" }, { "name": "Swift", "bytes": "220" }, { "name": "TypeScript", "bytes": "17091332" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
@implementation UMERedView - (id)initWithFrame:(NSRect)frame { if (self = [super initWithFrame:frame]) { } return self; } - (BOOL)isOpaque { return YES; } - (void)drawRect:(NSRect)r { NSDrawWindowBackground(r); [super drawRect:r]; // [[NSColor redColor] set]; // NSRectFill(r); } @end
{ "content_hash": "2c3fad1c52414bfd78a724dc8bbc73f8", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 45, "avg_line_length": 14, "alnum_prop": 0.6149068322981367, "repo_name": "nagyistoce/umekit", "id": "205f22dd9370fb93ecea595c18eb6f94d1862bf3", "size": "946", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/UMERedView.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4042" }, { "name": "Objective-C", "bytes": "164076" } ], "symlink_target": "" }
package com.ohmdb.impl; import com.ohmdb.abstracts.Any; import com.ohmdb.api.Table; public class AnySearch<E> implements Any<E> { private final Table<E> table; public AnySearch(Table<E> table) { this.table = table; } @Override public long[] ids() { return null; } @Override public long[] all() { return table.ids(); } public int size() { return table.size(); } @Override public String toString() { return "ANY " + table; } }
{ "content_hash": "6ab0965c3c1faa137c7e16c5931f62c9", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 45, "avg_line_length": 13.142857142857142, "alnum_prop": 0.6543478260869565, "repo_name": "gitblit/ohmdb", "id": "50ca0183f67d68788ff3fd241c0fe6e240de524a", "size": "1114", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "ohmdb-core/src/main/java/com/ohmdb/impl/AnySearch.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "640976" }, { "name": "Shell", "bytes": "63" } ], "symlink_target": "" }
namespace installer { class Product; } class BrowserDistribution { public: enum Type { CHROME_BROWSER, CHROME_FRAME, CHROME_BINARIES, CHROME_APP_HOST, NUM_TYPES }; // Flags to control what to show in the UserExperiment dialog. enum ToastUIflags { kUninstall = 1, // Uninstall radio button. kDontBugMeAsButton = 2, // Don't bug me is a button, not a radio button. kWhyLink = 4, // Has the 'why I am seeing this' link. kMakeDefault = 8 // Has the 'make it default' checkbox. }; // A struct for communicating what a UserExperiment contains. In these // experiments we show toasts to the user if they are inactive for a certain // amount of time. struct UserExperiment { string16 prefix; // The experiment code prefix for this experiment, // also known as the 'TV' part in 'TV80'. int flavor; // The flavor index for this experiment. int heading; // The heading resource ID to use for this experiment. int flags; // See ToastUIFlags above. int control_group; // Size of the control group (in percentages). Control // group is the group that qualifies for the // experiment but does not participate. }; virtual ~BrowserDistribution() {} static BrowserDistribution* GetDistribution(); static BrowserDistribution* GetSpecificDistribution(Type type); Type GetType() const { return type_; } virtual void DoPostUninstallOperations(const Version& version, const FilePath& local_data_path, const string16& distribution_data); virtual string16 GetAppGuid(); // Returns the unsuffixed application name of this program. // This is the base of the name registered with Default Programs on Windows. // IMPORTANT: This should only be called by the installer which needs to make // decisions on the suffixing of the upcoming install, not by external callers // at run-time. virtual string16 GetBaseAppName(); // Returns the localized name of the program. virtual string16 GetAppShortCutName(); virtual string16 GetAlternateApplicationName(); // Returns the unsuffixed appid of this program. // The AppUserModelId is a property of Windows programs. // IMPORTANT: This should only be called by ShellUtil::GetAppId as the appid // should be suffixed in all scenarios. virtual string16 GetBaseAppId(); virtual string16 GetInstallSubDir(); virtual string16 GetPublisherName(); virtual string16 GetAppDescription(); virtual string16 GetLongAppDescription(); virtual std::string GetSafeBrowsingName(); virtual string16 GetStateKey(); virtual string16 GetStateMediumKey(); virtual string16 GetStatsServerURL(); virtual std::string GetNetworkStatsServer() const; virtual std::string GetHttpPipeliningTestServer() const; #if defined(OS_WIN) virtual string16 GetDistributionData(HKEY root_key); #endif virtual string16 GetUninstallLinkName(); virtual string16 GetUninstallRegPath(); virtual string16 GetVersionKey(); virtual bool CanSetAsDefault(); virtual bool CanCreateDesktopShortcuts(); virtual int GetIconIndex(); virtual bool GetChromeChannel(string16* channel); // Returns true if the distribution includes a DelegateExecute verb handler, // and provides the COM registration data if so: // |handler_class_uuid| is the CommandExecuteImpl class UUID. // |type_lib_uuid| and |type_lib_version| identify its type library. // |interface_uuid| is the ICommandExecuteImpl interface UUID. // Only non-null parameters will be set, others will be ignored. virtual bool GetDelegateExecuteHandlerData(string16* handler_class_uuid, string16* type_lib_uuid, string16* type_lib_version, string16* interface_uuid); virtual void UpdateInstallStatus(bool system_install, installer::ArchiveType archive_type, installer::InstallStatus install_status); // Gets the experiment details for a given language-brand combo. If |flavor| // is -1, then a flavor will be selected at random. |experiment| is the struct // you want to write the experiment information to. Returns false if no // experiment details could be gathered. virtual bool GetExperimentDetails(UserExperiment* experiment, int flavor); // After an install or upgrade the user might qualify to participate in an // experiment. This function determines if the user qualifies and if so it // sets the wheels in motion or in simple cases does the experiment itself. virtual void LaunchUserExperiment(const FilePath& setup_path, installer::InstallStatus status, const Version& version, const installer::Product& product, bool system_level); // The user has qualified for the inactive user toast experiment and this // function just performs it. virtual void InactiveUserToastExperiment(int flavor, const string16& experiment_group, const installer::Product& installation, const FilePath& application_path); protected: explicit BrowserDistribution(Type type); template<class DistributionClass> static BrowserDistribution* GetOrCreateBrowserDistribution( BrowserDistribution** dist); const Type type_; private: BrowserDistribution(); DISALLOW_COPY_AND_ASSIGN(BrowserDistribution); }; #endif // CHROME_INSTALLER_UTIL_BROWSER_DISTRIBUTION_H_
{ "content_hash": "4e978d3872814d50e4677a1333ea29a9", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 80, "avg_line_length": 36.19496855345912, "alnum_prop": 0.6830582102519548, "repo_name": "Crystalnix/BitPop", "id": "96360a9e0d1bcfef8519744397885f1c0752b585", "size": "6357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/installer/util/browser_distribution.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1871" }, { "name": "C", "bytes": "1472539" }, { "name": "C++", "bytes": "68615409" }, { "name": "Java", "bytes": "465810" }, { "name": "JavaScript", "bytes": "17052804" }, { "name": "Objective-C", "bytes": "5073580" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "64450" }, { "name": "Python", "bytes": "2794547" }, { "name": "Ruby", "bytes": "650" }, { "name": "Shell", "bytes": "262004" }, { "name": "XSLT", "bytes": "418" } ], "symlink_target": "" }
cMooshroom::cMooshroom(void) : super("Mooshroom", mtMooshroom, "mob.cow.hurt", "mob.cow.hurt", 0.9, 1.3) { } void cMooshroom::GetDrops(cItems & a_Drops, cEntity * a_Killer) { unsigned int LootingLevel = 0; if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_LEATHER); AddRandomDropItem(a_Drops, 1, 3 + LootingLevel, IsOnFire() ? E_ITEM_STEAK : E_ITEM_RAW_BEEF); } void cMooshroom::OnRightClicked(cPlayer & a_Player) { switch (a_Player.GetEquippedItem().m_ItemType) { case E_ITEM_BUCKET: { if (!a_Player.IsGameModeCreative()) { a_Player.GetInventory().RemoveOneEquippedItem(); a_Player.GetInventory().AddItem(E_ITEM_MILK); } } break; case E_ITEM_BOWL: { if (!a_Player.IsGameModeCreative()) { a_Player.GetInventory().RemoveOneEquippedItem(); a_Player.GetInventory().AddItem(E_ITEM_MUSHROOM_SOUP); } } break; case E_ITEM_SHEARS: { if (!a_Player.IsGameModeCreative()) { a_Player.UseEquippedItem(); } cItems Drops; Drops.push_back(cItem(E_BLOCK_RED_MUSHROOM, 5, 0)); m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY(), GetPosZ(), 10); m_World->SpawnMob(GetPosX(), GetPosY(), GetPosZ(), mtCow); Destroy(); } break; } }
{ "content_hash": "187854c8f7dcbcb1c716376c80337e94", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 99, "avg_line_length": 22.5, "alnum_prop": 0.6674074074074074, "repo_name": "Tri125/MCServer", "id": "3b2fbad57972072521bfa7228248ebb3179cedbe", "size": "1512", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Mobs/Mooshroom.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8149" }, { "name": "C", "bytes": "6524886" }, { "name": "C++", "bytes": "6484522" }, { "name": "CMake", "bytes": "84529" }, { "name": "CSS", "bytes": "12444" }, { "name": "Groff", "bytes": "1612" }, { "name": "HTML", "bytes": "65997" }, { "name": "Java", "bytes": "22153" }, { "name": "Lua", "bytes": "753509" }, { "name": "Makefile", "bytes": "17573" }, { "name": "Objective-C", "bytes": "30562" }, { "name": "Python", "bytes": "4892" }, { "name": "QMake", "bytes": "2927" }, { "name": "Shell", "bytes": "8009" } ], "symlink_target": "" }
package com.demonwav.ectotokens.action; import com.demonwav.ectotokens.EctoTokens; import com.demonwav.ectotokens.TokensManager; import com.demonwav.ectotokens.config.shop.actions.RepairItemsActionConfig; import com.demonwav.ectotokens.gui.Window; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class RepairItemsAction extends Action { private final RepairItemsActionConfig config; public RepairItemsAction(RepairItemsActionConfig config) { this.config = config; } @Override @SuppressWarnings("deprecation") public void run(Window window, Player player, EctoTokens plugin) { int start = 0; if (config.getOnlyEquippedItems()) start = 36; for (int i = start; i < 40; i++) { ItemStack stack = player.getInventory().getItem(i); if (stack != null) { if (config.getItemTypes().isEmpty() || config.getItemTypes().contains(stack.getTypeId())) { double damage = stack.getDurability(); Material material = stack.getType(); double percentage = damage / (double)material.getMaxDurability(); long cost = Math.round(percentage * config.getCost()); TokensManager.getInstance().modifyBalance(player, -1 * cost, "REPAIR_COST"); stack.setDurability((short) 0); } } } window.updateInformation(); } @Override @SuppressWarnings("deprecation") public boolean checkAction(Window window, Player player, EctoTokens plugin) { int start = 0; if (config.getOnlyEquippedItems()) start = 36; long runningCost = 0; for (int i = start; i < 40; i++) { ItemStack stack = player.getInventory().getItem(i); if (stack != null) { if (config.getItemTypes().isEmpty() || config.getItemTypes().contains(stack.getTypeId())) { double damage = stack.getDurability(); Material material = stack.getType(); double percentage = damage / (double) material.getMaxDurability(); runningCost += Math.round(percentage * config.getCost()); } } } return TokensManager.getInstance().getBalance(player) >= runningCost; } }
{ "content_hash": "a2b338b2f7aa05cc97de51659ed2aeb1", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 108, "avg_line_length": 39.24193548387097, "alnum_prop": 0.604603370324702, "repo_name": "DemonWav/EctoTokens", "id": "84c5c249bed7f4f4fffa1859db103990045c2901", "size": "2433", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/demonwav/ectotokens/action/RepairItemsAction.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "203427" } ], "symlink_target": "" }
permalink: /speaker/profile/30/ title: Barbara Shaurette | DjangoCon in Austin, TX --- <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"/> <title>Barbara Shaurette | DjangoCon in Austin, TX</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta content="DjangoCon US 2015 in Austin, TX" property="og:title"> <meta content="website" property="og:type"> <meta content="https://2015.djangocon.us/" property="og:url"/> <meta content="DjangoCon US 2015" property="og:site_name"/> <meta content="A six-day not-for-profit by-the-community and for-the-community international conference for the Django web framework. " property="og:description"/> <meta content="https://2015.djangocon.us/site_media/static/images/djangocon-logo-thumb.png" property="og:image"/> <link href="/site_media/static/main.css" media="screen,projection" rel="stylesheet" type="text/css"/> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="//oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <link href="/site_media/static/images/favicon.ico" rel="shortcut icon"/> <script src="https://cdn.jsdelivr.net/jquery/1.11.2/jquery.min.js"></script> </meta></meta></head> <body class="full" id=""> <div class="poster-bg"> <div class="poster-shadow"> <div class="django-sticker"></div> <!-- Fixed navbar --> <div class="navbar-wrapper"> <div class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse" type="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/proposals/submit/"> <img alt="logo" class="img-responsive" src="/site_media/static/images/logo.png" width="180"/> </a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> About <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/about/" role="menuitem">What is Djangocon?</a> </li> <li role="presentation"> <a href="/organizers/" role="menuitem">DjangoCon Organizers</a> </li> <li role="presentation"> <a href="/code_of_conduct/" role="menuitem">Code of Conduct</a> </li> <li role="presentation"> <a href="/diversity/" role="menuitem">Diversity</a> </li> <li role="presentation"> <a href="/accessibility/" role="menuitem">Accessibility</a> </li> <li role="presentation"> <a href="/financial_aid/" role="menuitem">Financial Aid</a> </li> <li role="presentation"> <a href="/childcare/" role="menuitem">Childcare</a> </li> <li role="presentation"> <a href="/volunteers/" role="menuitem">Volunteers</a> </li> <li role="presentation"> <a href="/contact/" role="menuitem">Contact Us</a> </li> </ul> </li> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> Schedule <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/schedule/tutorials/list/" role="menuitem">Tutorial Schedule</a> </li> <li role="presentation"> <a href="/schedule/general-sessions/" role="menuitem">Talk Schedule</a> </li> <li role="presentation"> <a href="/sprints/" role="menuitem">Sprints</a> </li> <li role="presentation"> <a href="https://djangogirls.org/philadelphia/" role="menuitem">DjangoGirls Austin Workshop</a> </li> <li role="presentation"> <a href="/beginners/" role="menuitem">Beginner's Guide</a> </li> </ul> </li> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> Registration <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/registration/" role="menuitem">Register for DjangoCon US</a> </li> <li role="presentation"> <a href="https://djangogirls.org/philadelphia/apply/" role="menuitem">Register for DjangoGirls Austin Workshop</a> </li> <li role="presentation"> <a href="https://resweb.passkey.com/go/DJANGO0915" role="menuitem">Register for Hotel Accommodations</a> </li> </ul> </li> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> Venue <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/hotels/" role="menuitem">Hotel Accommodations</a> </li> <li role="presentation"> <a href="/travel/" role="menuitem">Travel</a> </li> <li role="presentation"> <a href="/austin/" role="menuitem">City Guide to Austin</a> </li> </ul> </li> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> Speaking <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/speaking/cfp/" role="menuitem">Call For Proposals</a> </li> <li role="presentation"> <a href="/speaking/mentors/" role="menuitem">Speaker Mentors</a> </li> <li role="presentation"> <a href="/lightning_talks/" role="menuitem">Lightning Talks</a> </li> </ul> </li> <li class="dropdown "> <a class="dropdown-toggle" data-toggle="dropdown" href="/#"> Sponsors <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"> <a href="/become-sponsor/" role="menuitem">Become a Sponsor</a> </li> <li role="presentation"> <a href="/sponsors/" role="menuitem">DjangoCon Sponsors</a> </li> </ul> </li> <li class=" "> <a href="/blog/"> News </a> </li> </ul> <div class="" id="capsules"> <ul class="nav navbar-nav navbar-right"> <li><a href="/account/login/">Log in</a></li> <li><a href="/account/signup/">Sign up</a></li> </ul> </div> <form action="https://2015.djangocon.us/account/logout/" id="accountLogOutForm" method="POST" style="display: none;"> <input name="csrfmiddlewaretoken" type="hidden" value="vKDUxSvBXQum2uTW0DN1QlXrjKdu8pjA"/> </form> </div> <!--/.nav-collapse --> </div> </div> </div> <div class="row small-header"> <div class="container"> <h1 class="brdp"></h1> </div> </div> <div class="row base-row"> <div class="container"> </div> </div> <div class="row base-row"> <div class="container"> <div class="span2"> <img alt="Barbara Shaurette" src="/site_media/media/speaker_photos/532638_10151141246707466_38194087_n.jpg.128x128_q85.jpg"/> </div> <div class="span6"> <h1>Barbara Shaurette</h1> <div class="bio"><p>Barbara is an open source veteran, with fifteen years of experience as a professional developer, much of that as an active participant in the Python and Django communities. She is an organizer for PyLadies Austin, and teaches and mentors through organizations such as PyLadies, Girl Develop It and Django Girls. Currently, she works as a Python developer for Cox Media Group.</p></div> <h2>Presentations</h2> <h3><a href="/schedule/presentation/40/">Things that are tired: Uggs, Segways and YOU! Coming back from burnout</a></h3> <p> Monday 10:30 a.m.–10:55 a.m. in Amphitheater 204 </p> </div> </div> </div> <div class="row" id="footer"> <div class="mainback"> <div class="turm"> <div class="outer"> <div class="inner"> <div class="container"> <div class="nail nail-bl"></div> <div class="nail nail-br"></div> <div class="col-md-6 col-centered footer-note"> <div class="contact-us">Questions? Comments?</div><a href="/contact/">Contact Us</a><br/> Design + Build by <a href="https://www.lincolnloop.com">Lincoln Loop</a> <br> Hosted on <a href="https://gondor.io">Gondor</a> <br/> Presented by <a href="https://www.defna.org">DEFNA</a> <p>©2016 DjangoCon</p> </br></div> </div> </div> </div> </div> </div> </div> </div> </div> <script charset="utf-8" src="/site_media/static/main.js" type="text/javascript"></script> {% include analytics.html %} </body> </html>
{ "content_hash": "b1f3c4fbfb2002d2b76550f32f227544", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 405, "avg_line_length": 33.53629032258065, "alnum_prop": 0.654082000721414, "repo_name": "djangocon/2015.djangocon.us", "id": "2bb7b0ec102366ddf0acb2ffe3ece702c1e2c8ba", "size": "8324", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_pages/speaker-profile-30.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "816042" }, { "name": "HTML", "bytes": "4058071" }, { "name": "JavaScript", "bytes": "830075" }, { "name": "Ruby", "bytes": "1137" } ], "symlink_target": "" }
classdef graphViz4Matlab < handle % Visualize a graph in a Matlab figure window by specifying an % adjacency matrix and optionally node labels, descriptions, colors and the % the layout algorithm. The best layout algorithms require that graphViz be % installed, available free at <http://www.graphviz.org>. % % Matthew Dunham % University of British Columbia % Last Updated: April 24, 2010 % Requires Matlab version 2008a or newer. % % Syntax (see more examples below): % graphViz4Matlab('-adjMat',adj,'-nodeLabels',labels,'-nodeColors',colors); % % Self loops are removed and not represented on the graph. % % Once the graph is displayed, there are several operations you can perform % with the mouse. % (1) Move a single node around. % (2) Draw a mouse box around several nodes and move them all together. % (3) Enter a description for a node by double clicking it. % (4) Shade the node by right clicking it % (5) Display a node's properties on the console by shift clicking it. % (6) Increase or decrease the font size % (7) Increase or decrease the node size % (8) Tighten the axes and relax the square aspect ratio. % (9) Ask the current layout algorithm to layout the nodes as though the % arrows were pointing the other way. This only affects some of the % layouts. % (10) Change the layout algorithm and refresh the graph % % Additionally, any operation you could do with a regular Matlab figure can % be done here, e.g. annotating or saving as a pdf. % % Options are specified via name value pairs in any order. % [] denote defaults. % % '-adjMat' [example matrix] The adjacency matrix % % '-layout' [Gvizlayout if graphViz installed, else Gridlayout] % A layout object, i.e. Gvizlayout | Gridlayout | Circlelayout % (See knownLayouts Property) % % '-nodeLabels' ['1':'n'] A cell array of labels for the nodes % % '-nodeDescriptions' [{}] Longer descriptions for the nodes, displayed when % double clicking on a node. % % '-nodeColors' ['c'] A cell array or n-by-3 matrix specifying colors % for the nodes. If fewer colors than nodes are specified, % the specified colors are reused and cycled through. % % '-undirected' [false] If true, no arrows are displayed. % % '-edgeColors' [] An n-by-3 cell array listing % {fromName,toName,color} for each row. You can % list only the n < numel(edges) edges you want to % color. If you do not label the nodes, graphViz4Matlab % uses '1','2','3', etc, in which case use these. % You can specify the text 'all' in place of toName, % to mean all nodes, i.e. {fromName,'all',color} % % % '-splitLabels' [true] If true, long node labels are split into % several rows % % '-doubleClickFn' (by default, double clicking a node brings up % an edit box for the node's description, but you % can pass in a custom function handle. The function % gets passed the node's label. % Examples: % % adj = rand(5,5) > 0.8; % labels = {'First','Second','Third','Fourth','Fifth'}; % colors = {'g','b'}; % will cycle through % s = graphViz4Matlab('-adjMat',adj,'-nodeLabels',labels,'-nodeColors',colors); % freeze(s); % convert to an image % % If you are only specifying an adjacency matrix, you can omit the % '-adjMat' name as in graphViz4Matlab(adj). % % Calling graphViz4Matlab without any parameters displays an example graph. % properties(GetAccess = 'public', SetAccess = 'private') % read only path = addpath(genpath(fileparts(which(mfilename)))); % automatically adds subdirectories to path graphVizPath = setupPath(); nnodes = 0; % The number of nodes nedges = 0; % The number of edges currentLayout= []; % The current layout object layouts = []; % List currently added layout objects adjMatrix = []; % The adjacency matrix isvisible = false; % True iff the graph is being displayed nodeArray = []; % The nodes edgeArray = []; % The edges fig = []; % The main window ax = []; % The main axes doubleClickFn = []; % function to execute when a user double clicks on a node, (must be a function handle that takes in the node name selectedNode = []; % The selected node, if any minNodeSize = []; % A minimum size for the nodes maxNodeSize = []; % A maximum size for the nodes undirected = false; % If undirected, arrows are not displayed flipped = false; % If true, layout is done as though edge directions were reversed. % (does not affect the logical layout). knownLayouts = {Gvizlayout ,... % add your own layout here or use Treelayout ,... % the addLayout() method Radiallayout,... Circularlayout,... Springlayout,... Circlelayout,... Gridlayout ,... Randlayout }; defaultEdgeColor = [0,0,0];%[20,43,140]/255; edgeColors; square = true; % amounts to a the call "axis square" splitLabels = true; end properties(GetAccess = 'private', SetAccess = 'private') % These values store the initial values not the current ones. nodeLabels = {}; nodeDescriptions = {}; nodeColors = {}; end properties(GetAccess = 'protected',SetAccess = 'protected') toolbar; % The button toolbar layoutButtons; % The layout buttons fontSize; % last calculated optimal font size selectedFontSize; % previousMouseLocation; % last mouse location relative to the axes groupSelectionMode = 0; % current stage in a group selection task groupSelectedNodes; % selected nodes in a group selection groupSelectedDims; % size of enclosing rectangle of selected nodes groupSelectedRect; % a bounding rectangle for the selected nodes end methods function obj = graphViz4Matlab(varargin) % graphViz4Matlab constructor if(~exist('processArgs','file')), error('Requires processArgs() function'); end obj.addKnownLayouts(); obj.processInputs(varargin{:}) obj.addNodes(); obj.addEdges(); obj.draw(); end function draw(obj) % Draw the graph if(obj.isvisible) obj.erase() end obj.createWindow(); obj.calculateMinMaxNodeSize(); obj.layoutNodes(); obj.displayGraph(); obj.isvisible = true; obj.paperCrop(); end function fig = freeze(obj) % Freeze the current image into a regular Matlab figure figure(obj.fig); print tmp.png -dpng -r300 fig = figure; image(imread('tmp.png')); axis off; delete tmp.png; close(obj.fig); end function redraw(obj) % Redraw the graph. (You could also call draw() again but then the % window is recreated as well and it doesn't look as nice). if(~obj.isvisible) obj.draw(); return; end cla(obj.ax); obj.clearGroupSelection(); obj.calculateMinMaxNodeSize(); obj.layoutNodes(); obj.displayGraph(); end function flip(obj,varargin) % Have the layout algorithms layout the graph as though the arrows % were pointing in the opposite direction. The node connectivity % remains the same and if node one pointed to node 2 before, it % still does after. This is useful for tree layout, for example to % turn the tree on its head. Calling it twice flips it back. obj.flipped = ~obj.flipped; if(obj.isvisible) obj.redraw(); end end function erase(obj) % Erase the graph but maintain the state so that it can be redrawn. if(obj.isvisible) obj.clearGroupSelection(); delete(obj.fig); obj.isvisible = false; end end function nodeSelected(obj,node) % This function is called by nodes when they are selected by the % mouse. It should not be called manually. if(obj.groupSelectionMode == 1) obj.groupSelectionStage1(); return; end if(~isempty(obj.selectedNode)) node.deselect(); obj.selectedNode = []; return; end switch get(obj.fig,'SelectionType') case 'normal' obj.singleClick(node); case 'open' obj.doubleClick(node); case 'alt' obj.rightClick(node); otherwise obj.shiftClick(node); end end function addLayout(obj,layout) % Let the graph know about a new layout you have created so that it % will be available via a toolbar button. The layout object must be % a descendant of the Abstractlayout class. This method does not have % to be called for existing layouts, nor does it need to be called % if you passed the new layout to the constructor or to the % setLayout() method. It will not add two layouts with the same % name property. if(~ismember(layout.name,fieldnames(obj.layouts))) if(layout.isavailable()) obj.layouts.(layout.name) = layout; if(obj.isvisible) obj.addButtons(); end else warning('graphViz4Matlab:layout','This layout is not available'); end end end function setLayout(obj,layout) % Set a new layout algorithm and refresh the graph. if(layout.isavailable()) obj.addLayout(layout); obj.currentLayout = obj.layouts.(layout.name); obj.redraw(); else warning('graphViz4Matlab:layout','Sorry, this layout is not available'); end end function squareAxes(obj,varargin) % Toggle the axes from square to normal and vice versa. obj.clearGroupSelection(); if(obj.square) axis(obj.ax,'normal'); obj.square = false; else axis(obj.ax,'square'); obj.square = true; end end function tightenAxes(obj,varargin) % Tighten the axes as much as possible. obj.clearGroupSelection(); xpos = vertcat(obj.nodeArray.xpos); ypos = vertcat(obj.nodeArray.ypos); r = obj.nodeArray(1).width/2; axis(obj.ax,[min(xpos)-r,max(xpos)+r,min(ypos)-r,max(ypos)+r]); axis normal; end end % end of public methods methods(Access = 'protected') function addKnownLayouts(obj) % Add all of the known layouts obj.layouts = struct; for i=1:numel(obj.knownLayouts) layout = obj.knownLayouts{i}; if(layout.isavailable()) obj.layouts.(layout.name) = layout; end end end function processInputs(obj,varargin) % Process the inputs and perform error checking labels = {'adj', 'adjMatrix', 'adjMat', 'layout', 'nodeLabels', 'nodeDescriptions', 'nodeColors', 'undirected', 'edgeColors', 'splitLabels', 'doubleClickFn'}; for i=1:numel(varargin) arg = varargin{i}; if ~ischar(arg), continue; end for j = 1:numel(labels) if strcmpi(arg, labels{i}); varargin{i} = ['-', arg]; end if strcmpi(arg, '-adj') || strcmpi(arg, '-adjMatrix') varargin{i} = '-adjMat'; end end end [adjMatrix, currentLayout, nodeLabels, nodeDescriptions, nodeColors,obj.undirected,obj.edgeColors,obj.splitLabels,obj.doubleClickFn] = processArgs(varargin,... '-adjMat' , [] ,... '-layout' , [] ,... '-nodeLabels' , {} ,... '-nodeDescriptions' , {} ,... '-nodeColors' , {} ,... '-undirected' , false ,... '-edgeColors' , [] ,... '-splitLabels' , true ,... '-doubleClickFn' , [] ); if(~isempty(currentLayout) && ~isavailable(currentLayout)) currentLayout = []; end if(isempty(adjMatrix)) adjMatrix = [0 0 0 0; 1 0 0 0; 1 1 0 0; 1 1 1 0]; % example graph end if(isempty(currentLayout)) fields = fieldnames(obj.layouts); currentLayout = obj.layouts.(fields{1}); else obj.addLayout(currentLayout); end obj.nnodes = size(adjMatrix,1); obj.adjMatrix = adjMatrix; if(isempty(nodeDescriptions)) nodeDescriptions = repmat({'Enter a description here...'},size(adjMatrix,1),1); end obj.nodeDescriptions = nodeDescriptions; obj.nodeColors = nodeColors; if(isempty(nodeLabels)) nodeLabels = cellfun(@(x)num2str(x),mat2cell(1:obj.nnodes,1,ones(1,obj.nnodes)),'UniformOutput',false); end obj.nodeLabels = nodeLabels; if(~isequal(numel(obj.nodeLabels),size(adjMatrix,1),size(adjMatrix,2))) error('graphViz4Matlab:dimMismatch','The number of labels must match the dimensions of adjmatrix.'); end obj.currentLayout = currentLayout; end function createWindow(obj) % Create the main window obj.fig = figure(floor(1000*rand) + 1000); set(obj.fig,'Name','graphViz4Matlab',... 'NumberTitle' ,'off',... 'Color','w' ,'Toolbar','none'); obj.createAxes(); ssize = get(0,'ScreenSize'); pos = [ssize(3)/2,50,-20+ssize(3)/2,ssize(4)-200]; set(obj.fig,'Position',pos); obj.setCallbacks(); obj.addButtons(); end function createAxes(obj) % Create the axes upon which the graph will be displayed. obj.ax = axes('Parent',obj.fig,'box','on','UserData','main'); outerpos = get(obj.ax,'OuterPosition'); axpos = outerpos; axpos(4) = 0.90; axpos(2) = 0.03; axis manual if(obj.square) axis square end set(obj.ax,'Position',axpos,'XTick',[],'YTick',[],'LineWidth',0.5); set(obj.ax,'ButtonDownFcn',@obj.axPressed); end function setCallbacks(obj) % Set the callback functions for the figure, i.e. functions that % will be called when the user performs various actions. set(obj.fig,'ResizeFcn' ,@obj.windowResized); set(obj.fig,'WindowButtonMotionFcn' ,@obj.mouseMoved); set(obj.fig,'WindowButtonUpFcn' ,@obj.buttonUp); set(obj.fig,'DeleteFcn' ,@obj.deleted); end function addNodes(obj) % Add all of the nodes to the graph structure, but don't display % them yet. obj.nodeArray = []; for i=1:obj.nnodes newnode = graphViz4MatlabNode(obj.nodeLabels{i}); newnode.containingGraph = obj; newnode.showFullLabel = ~obj.splitLabels; obj.nodeArray = [obj.nodeArray newnode]; end obj.addNodeDescriptions(obj.nodeDescriptions); obj.addNodeColors(obj.nodeColors); end function addNodeDescriptions(obj,nodeDescriptions) % Add any descriptions to the newly created nodes. if(~isempty(nodeDescriptions)) if(numel(nodeDescriptions) == 1) nodeDescriptions = repmat(nodeDescriptions,obj.nnodes,1); end for i=1:obj.nnodes obj.nodeArray(i).description = nodeDescriptions{i}; end end end function addNodeColors(obj,nodeColors) % Shade the nodes according to the specified colors. If too few % colors are specified, they are cycled through. if(~isempty(nodeColors)) if(~iscell(nodeColors)) nodeColors = mat2cell(nodeColors,ones(1,size(nodeColors,1)),size(nodeColors,2)); end if(size(nodeColors,2) > size(nodeColors,1)) nodeColors = nodeColors'; end if(numel(nodeColors) < obj.nnodes) nodeColors = repmat(nodeColors,ceil(obj.nnodes/numel(nodeColors)),1); nodeColors = nodeColors(1:obj.nnodes); end for i=1:obj.nnodes obj.nodeArray(i).shade(nodeColors{i}); end obj.nodeColors = nodeColors; end end function addEdges(obj) % Add all of the edges to the graph structure, but don't display % them yet. if(any(diag(obj.adjMatrix))) fprintf('\nRemoving Self Loops\n'); obj.adjMatrix = obj.adjMatrix - diag(diag(obj.adjMatrix)); end obj.edgeArray = struct('from',[],'to',[],'arrow',[]); counter = 1; for i=1:obj.nnodes for j=1:obj.nnodes if(obj.adjMatrix(i,j)) obj.edgeArray(counter) = struct('from',obj.nodeArray(i),'to',obj.nodeArray(j),'arrow',-1); obj.nodeArray(i).outedges = [obj.nodeArray(i).outedges,counter]; obj.nodeArray(j).inedges = [obj.nodeArray(j).inedges,counter]; counter = counter + 1; end end end obj.nedges = counter -1; end function calculateMinMaxNodeSize(obj) % calculates the maximum and minimum node sizes in data units SCREEN_PROPORTION_MAX = 1/10; SCREEN_PROPORTION_MIN = 1/35; units = get(0,'Units'); set(0,'Units','pixels'); screensize = get(0,'ScreenSize'); set(0,'Units',units); axunits = get(obj.ax,'Units'); set(obj.ax,'Units','pixels'); axsize = get(obj.ax,'Position'); set(obj.ax,'Units',axunits); if(screensize(3) < screensize(4)) dataUnitsPerPixel = abs(diff(xlim))/axsize(3); obj.minNodeSize = (SCREEN_PROPORTION_MIN*screensize(3))*dataUnitsPerPixel; obj.maxNodeSize = (SCREEN_PROPORTION_MAX*screensize(3))*dataUnitsPerPixel; else dataUnitsPerPixel = abs(diff(ylim))/axsize(4); obj.minNodeSize = (SCREEN_PROPORTION_MIN*screensize(4))*dataUnitsPerPixel; obj.maxNodeSize = (SCREEN_PROPORTION_MAX*screensize(4))*dataUnitsPerPixel; end end function layoutNodes(obj) % Layout the nodes and edges according to the current layout % algorithm. if(obj.flipped) adj = obj.adjMatrix'; else adj = obj.adjMatrix; end obj.currentLayout.dolayout(adj,obj.ax,obj.maxNodeSize); nodesize = obj.currentLayout.nodeSize(); locs = obj.currentLayout.centers(); for i=1:obj.nnodes node = obj.nodeArray(i); node.resize(nodesize); node.move(locs(i,1),locs(i,2)); end end function displayGraph(obj) % Display all of the nodes and edges. cla(obj.ax); obj.setFontSize(); for i=1:obj.nnodes node = obj.nodeArray(i); node.fontSize = obj.fontSize; node.draw(obj.ax); end displayEdges(obj); end function displayEdges(obj,indices) % Display or refresh the specified edges. If none specified, all % are refreshed. Currently only works with round nodes. figure(obj.fig); if(nargin < 2) indices = 1:obj.nedges; else indices = unique(indices); end for i=1:numel(indices) edge = obj.edgeArray(indices(i)); [X,Y,Xarrow,Yarrow] = obj.calcPositions(edge); if(ishandle(edge.arrow)) delete(edge.arrow) end hold on; edgeColor = obj.defaultEdgeColor; if ~isempty(obj.edgeColors) candidates = obj.edgeColors(findString(edge.from.label,obj.edgeColors(:,1)),:); if size(candidates,1)==1 && strcmpi(candidates(1,2),'all') edgeColor = candidates{1,3}; else edgeCol = candidates(findString(edge.to.label,candidates(:,2)),3); if ~isempty(edgeCol); edgeColor = edgeCol{1}; end end end edge.arrow = plot(X,Y,'LineWidth',2,'HitTest','off','Color',edgeColor); if(~obj.undirected) arrowHead = obj.displayArrowHead(X,Y,Xarrow,Yarrow,edgeColor); edge.arrow = [edge.arrow arrowHead]; end hold off; obj.edgeArray(indices(i)) = edge; end end function arrowHead = displayArrowHead(obj,X,Y,Xarrow,Yarrow,arrowColor) %#ok % Displays the arrow head given the appropriate coordinates % calculated via the calcPositions() function. arrowHead = patch('Faces' ,[1,2,3] ,... 'Vertices' ,[Xarrow(1) Yarrow(1); Xarrow(2) Yarrow(2) ;X(2) Y(2)],... 'FaceColor' ,arrowColor); end function [X,Y,Xarrow,Yarrow] = calcPositions(obj,edge) % Helper function for displayEdges() - calculates edge and arrow % start and end positions in data units. X = [edge.from.xpos edge.to.xpos]; Y = [edge.from.ypos edge.to.ypos]; ratio = (Y(2) - Y(1))/(X(2)-X(1)); if(isinf(ratio)) ratio = realmax; end % dx: x-distance from node1 center to perimeter in direction of node2 % dy: y-distance from node1 center to perimeter in direction of node2 % ddx: x-distance from node1 perimeter to base of arrow head % ddy: y-distance from node1 perimeter to base of arrow head % dpx: x-offset away from edge in perpendicular direction, for arrow head % dpy: y-offset away from edge in perpendicular direction, for arrow head arrowSize = obj.maxNodeSize/10; [dx,dy] = pol2cart(atan(ratio),edge.from.width/2); [ddx,ddy] = pol2cart(atan(ratio),arrowSize); ratio = 1/ratio; % now work out perpendicular directions. if(isinf(ratio)) ratio = realmax; end [dpx dpy] = pol2cart(atan(ratio),arrowSize/2); ddx = abs(ddx); ddy = abs(ddy); dpx = abs(dpx); dpy = abs(dpy); dx = abs(dx); dy = abs(dy); if(X(1) < X(2)) X(1) = X(1) + dx; X(2) = X(2) - dx; else X(1) = X(1) - dx; X(2) = X(2) + dx; end if(Y(1) < Y(2)) Y(1) = Y(1) + dy; Y(2) = Y(2) - dy; else Y(1) = Y(1) - dy; Y(2) = Y(2) + dy; end if(X(1) <= X(2) && Y(1) <= Y(2)) Xarrow(1) = X(2) - ddx - dpx; Xarrow(2) = X(2) - ddx + dpx; Yarrow(1) = Y(2) - ddy + dpy; Yarrow(2) = Y(2) - ddy - dpy; elseif(X(1) <= X(2) && Y(1) >= Y(2)) Xarrow(1) = X(2) - ddx - dpx; Xarrow(2) = X(2) - ddx + dpx; Yarrow(1) = Y(2) + ddy - dpy; Yarrow(2) = Y(2) + ddy + dpy; elseif(X(1) >= X(2) && Y(1) <= Y(2)) Xarrow(1) = X(2) + ddx - dpx; Xarrow(2) = X(2) + ddx + dpx; Yarrow(1) = Y(2) - ddy - dpy; Yarrow(2) = Y(2) - ddy + dpy; else % (X(1) >= (X(2) && Y(1) >= Y(2)) Xarrow(1) = X(2) + ddx - dpx; Xarrow(2) = X(2) + ddx + dpx; Yarrow(1) = Y(2) + ddy + dpy; Yarrow(2) = Y(2) + ddy - dpy; end end function addButtons(obj) % Add user interface buttons. if(~isempty(obj.toolbar)) if(ishandle(obj.toolbar)) delete(obj.toolbar); obj.toolbar = []; end end obj.toolbar = uitoolbar(obj.fig); % button icons load glicons; uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.decreaseFontSize,... 'TooltipString' ,'Decrease Font Size',... 'CData' ,icons.downblue); uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.increaseFontSize,... 'TooltipString' ,'Increase Font Size',... 'CData' ,icons.upblue); uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.tightenAxes,... 'TooltipString' ,'Tighten Axes',... 'CData' ,icons.expand); uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.flip,... 'TooltipString' ,'Flip/Reset Layout',... 'CData' , icons.flip); uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.shrinkNodes,... 'TooltipString' ,'Decrease Node Size',... 'CData' , icons.downdarkblue); uipushtool(obj.toolbar,... 'ClickedCallback' ,@obj.growNodes,... 'TooltipString' ,'Increase Node Size',... 'CData' , icons.updarkblue); if(~isempty(obj.layoutButtons)) for i=1:numel(obj.layoutButtons) if(ishandle(obj.layoutButtons(i))) delete(obj.layoutButtons(i)); end end obj.layoutButtons = []; end layoutNames = fieldnames(obj.layouts); for i=1:numel(layoutNames) layout = obj.layouts.(layoutNames{i}); layoutButton = uipushtool(obj.toolbar,... 'ClickedCallback', @obj.layoutButtonPushed,... 'TooltipString', layout.shortDescription,... 'UserData' , layoutNames{i},... 'Separator' , 'on',... 'CData' , layout.image); obj.layoutButtons = [obj.layoutButtons,layoutButton]; end end function setFontSize(obj) % fontsize = obj.maxFontSize; fontSize = 20; maxchars = size(char(obj.nodeLabels),2); width = obj.nodeArray(1).width; height = obj.nodeArray(1).height; xpos = -10; ypos = -10; t = text(xpos,ypos,repmat('g',1,maxchars),... 'FontUnits' , 'points' ,... 'Units' , 'data' ,... 'HorizontalAlignment' , 'center' ,... 'VerticalAlignment' , 'middle' ,... 'FontWeight' , 'demi' ,... 'LineStyle' , 'none' ,... 'Margin' , 0.01 ,... 'FontSize' , fontSize ,... 'Color' , 'w' ); extent = get(t,'Extent'); while(extent(3) > width || extent(4) > height) fontSize = fontSize - 1; if(fontSize < 2), break,end set(t,'FontSize',fontSize); extent = get(t,'Extent'); end obj.fontSize = fontSize; end function asp = aspectRatio(obj) % Return the current aspect ratio of the figure, width/height units = get(obj.ax,'Units'); set(obj.ax,'Units','pixels'); pos = get(obj.ax,'Position'); set(obj.ax,'Units',units); asp = (pos(3)/pos(4)); end function paperCrop(obj) % Make the papersize the same as the the figure size. This is % useful when saving as pdf. units = get(obj.fig,'Units'); set(obj.fig,'Units','inches'); pos = get(obj.fig,'Position'); set(obj.fig,'Units',units); set(obj.fig,'PaperPositionMode','auto','PaperSize',pos(3:4)); end %% % Callbacks function layoutButtonPushed(obj,buttonPushed,varargin) % Called when a layout button is pushed. name = get(buttonPushed,'UserData'); obj.currentLayout = obj.layouts.(name); axis square; obj.redraw; end function windowResized(obj,varargin) % This function is called whenever the window is resized. It % redraws the whole graph. if(obj.isvisible) obj.redraw; obj.paperCrop(); end end function mouseMoved(obj,varargin) % This function is called whenever the mouse moves within the % figure. if(obj.groupSelectionMode == 2) % Move all of the nodes & rectangle currentPoint = get(obj.ax,'CurrentPoint'); xlimits = get(obj.ax,'XLim'); ylimits = get(obj.ax,'YLim'); sdims = obj.groupSelectedDims; xdiff = currentPoint(1,1) - obj.previousMouseLocation(1,1); ydiff = currentPoint(1,2) - obj.previousMouseLocation(1,2); if(xdiff <=0) xdiff = max(xdiff,(xlimits(1)-sdims(1))); else xdiff = min(xdiff,xlimits(2)-sdims(2)); end if(ydiff <=0) ydiff = max(ydiff,(ylimits(1)-sdims(3))); else ydiff = min(ydiff,ylimits(2)-sdims(4)); end xnodepos = vertcat(obj.groupSelectedNodes.xpos) + xdiff; ynodepos = vertcat(obj.groupSelectedNodes.ypos) + ydiff; for i=1:numel(obj.groupSelectedNodes) obj.groupSelectedNodes(i).move(xnodepos(i),ynodepos(i)); end recpos = get(obj.groupSelectedRect,'Position'); recpos(1) = recpos(1) + xdiff; recpos(2) = recpos(2) + ydiff; obj.groupSelectedDims = [recpos(1),recpos(1)+recpos(3),recpos(2),recpos(2)+recpos(4)]; set(obj.groupSelectedRect,'Position',recpos); edges = [obj.groupSelectedNodes.inedges,obj.groupSelectedNodes.outedges]; obj.displayEdges(edges); obj.previousMouseLocation = currentPoint; else if(isempty(obj.selectedNode)), return,end currentPoint = get(obj.ax,'CurrentPoint'); x = currentPoint(1,1); y = currentPoint(1,2); xl = xlim + [obj.selectedNode.width,-obj.selectedNode.width]/2; yl = ylim + [obj.selectedNode.height,-obj.selectedNode.height]/2; x = min(max(xl(1),x),xl(2)); y = min(max(yl(1),y),yl(2)); obj.selectedNode.move(x,y); obj.displayEdges([obj.selectedNode.inedges,obj.selectedNode.outedges]); end end function buttonUp(obj,varargin) % This function executes when the mouse button is released. if(obj.groupSelectionMode == 2) obj.clearGroupSelection(); return; end if(isempty(obj.selectedNode)),return,end obj.selectedNode.deselect(); obj.selectedNode.useFullLabel = false; obj.selectedNode.fontSize = obj.selectedFontSize; obj.selectedNode.redraw(); obj.selectedNode = []; set(gcf,'Pointer','arrow'); end function axPressed(obj,varargin) % Called when the user selects the axes but not a node switch obj.groupSelectionMode case 0 % hasn't been selected yet xpos = vertcat(obj.nodeArray.xpos); ypos = vertcat(obj.nodeArray.ypos); p1 = get(obj.ax,'CurrentPoint'); rbbox; % returns after box drawn p2 = get(obj.ax,'CurrentPoint'); xleft = min(p1(1,1),p2(1,1)); xright = max(p1(1,1),p2(1,1)); ylower = min(p1(1,2),p2(1,2)); yupper = max(p1(1,2),p2(1,2)); selectedX = (xpos <= xright) & (xpos >= xleft); selectedY = (ypos <= yupper) & (ypos >= ylower); selected = selectedX & selectedY; if(~any(selected)),return,end obj.groupSelectionMode = 1; obj.groupSelectedNodes = obj.nodeArray(selected); for i=1:numel(obj.groupSelectedNodes) node = obj.groupSelectedNodes(i); node.select(); node.redraw(); end w = obj.groupSelectedNodes(1).width/2; h = obj.groupSelectedNodes(1).height/2; x = vertcat(obj.groupSelectedNodes.xpos); y = vertcat(obj.groupSelectedNodes.ypos); minx = min(x)-w; maxx = max(x)+w; miny = min(y)-h; maxy = max(y)+h; obj.groupSelectedDims = [minx,maxx,miny,maxy]; obj.groupSelectedRect = rectangle('Position',[minx,miny,maxx-minx,maxy-miny],'LineStyle','--','EdgeColor','r'); case 1 % nodes selected obj.groupSelectionStage1(); case 2 %not ever reached in this function obj.clearGroupSelection(); end end function groupSelectionStage1(obj) % Called after a group of nodes has been selected and the mouse % button has been pressed somewhere on the axes, (or on a node). p = get(obj.ax,'CurrentPoint'); obj.previousMouseLocation = p; dims = obj.groupSelectedDims; if(p(1,1) >= dims(1) && p(1,1) <= dims(2) && p(1,2) >= dims(3) && p(1,2) <=dims(4)) set(gcf,'Pointer','hand'); obj.groupSelectionMode = 2; else obj.clearGroupSelection(); end end function clearGroupSelection(obj) % Clear a group selection if(ishandle(obj.groupSelectedRect)) delete(obj.groupSelectedRect); end obj.groupSelectedRect = []; for i=1:numel(obj.groupSelectedNodes) obj.groupSelectedNodes(i).deselect(); end obj.groupSelectedNodes = []; obj.groupSelectedDims = []; obj.groupSelectionMode = 0; set(gcf,'Pointer','arrow'); end function deleted(obj,varargin) % Called when the figure is deleted by the user. obj.isvisible = false; obj.clearGroupSelection(); end function singleClick(obj,node) % Called when a user single clicks on a node. obj.selectedNode = node; node.select(); set(gcf,'Pointer','hand'); obj.selectedFontSize = node.fontSize; node.useFullLabel = true; node.fontSize = max(15,node.fontSize*1.5); node.redraw(); end function doubleClick(obj,node) % Called when a user double clicks on a node if isempty(obj.doubleClickFn) description = node.description; if(~iscell(description)) description = {description}; end answer = inputdlg('',node.label,4,description); if(~isempty(answer)) node.description = answer; end else obj.doubleClickFn(node.label); end end function rightClick(obj,node) %#ok % Called when a user right clicks on a node if(node.isshaded) node.unshade(); else node.shade(); end end function shiftClick(obj,node) %#ok % Called when a user shift clicks on a node display(node); end end methods % Callbacks that can be called by the user programmatically. function shrinkNodes(obj,varargin) % Shrink the nodes to 95% of their original size, (but not smaller % than a calculated minimum. obj.clearGroupSelection(); s = max(0.8*obj.nodeArray(1).width,obj.minNodeSize); obj.nodeArray(1).resize(s); obj.setFontSize(); for i=1:obj.nnodes node = obj.nodeArray(i); node.fontSize = obj.fontSize; node.resize(s); end obj.displayEdges(); end function growNodes(obj,varargin) % Grow the nodes to 1/0.95 times their original size, (but not % larger than a calculated maximum. obj.clearGroupSelection(); s = min(obj.nodeArray(1).width/0.8,1.5*obj.maxNodeSize); obj.nodeArray(1).resize(s); obj.setFontSize(); for i=1:obj.nnodes node = obj.nodeArray(i); node.fontSize = obj.fontSize; node.resize(s); end obj.displayEdges(); end function increaseFontSize(obj,varargin) % Increase the fontsize of all the nodes by 0.5 points. current = get(obj.nodeArray(1).labelhandle,'FontSize'); newsize = current + 1; for i=1:numel(obj.nodeArray) node = obj.nodeArray(i); node.fontSize = newsize; node.redraw(); end end function decreaseFontSize(obj,varargin) % Decrease the fontsize of all the nodes by 0.5 points. current = get(obj.nodeArray(1).labelhandle,'FontSize'); newsize = max(current - 1,1); for i=1:numel(obj.nodeArray) node = obj.nodeArray(i); node.fontSize = newsize; node.redraw(); end end function XY = getNodePositions(obj) % Return the current positions of the nodes. The bottom left % corner is [0 0] and the top right is [1 1]. Node positions % refer to the centre of a node. XY = zeros(obj.nnodes, 2); for i=1:obj.nnodes XY(i, 1) = obj.nodeArray(i).xpos; XY(i, 2) = obj.nodeArray(i).ypos; end end function setNodePositions(obj, XY) % Programmatically set the node positions % XY(i, 1) is the xposition of node i, XY(i, 2) is the yposition. for i=1:obj.nnodes obj.nodeArray(i).move(XY(i, 1), XY(i, 2)); end obj.displayGraph(); end function moveNode(obj, nodeIndex, xpos, ypos) % Programmatically set a node position. obj.nodeArray(nodeIndex).move(xpos, ypos); obj.displayGraph(); end end end
{ "content_hash": "d423851836ef35cb4a6831ca2db6c5dd", "timestamp": "", "source": "github", "line_count": 1028, "max_line_length": 171, "avg_line_length": 42.63813229571984, "alnum_prop": 0.48389304617630957, "repo_name": "echanthe/hydiag", "id": "e3e8c54c34bd93e283c3428797e566d842a6b600", "size": "43832", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "graphViz4Matlab/graphViz4Matlab.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "52737" }, { "name": "Limbo", "bytes": "42" }, { "name": "M", "bytes": "22456" }, { "name": "Matlab", "bytes": "363391" }, { "name": "Objective-C", "bytes": "296" } ], "symlink_target": "" }
import pandas as pd from sklearn import model_selection from sklearn.ensemble import GradientBoostingClassifier url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] df = pd.read_csv(url, names=names) array = df.values X = array[:,0:8] y = array[:,8] seed = 21 num_trees = 100 kfold = model_selection.KFold(n_splits=10, random_state=seed) model = GradientBoostingClassifier(n_estimators=num_trees, random_state=seed) results = model_selection.cross_val_score(model, X, y, cv=kfold) print('results: ') print(results) print() print('mean: ' + str(results.mean()))
{ "content_hash": "e6a0d60036931babef05f81abd8e5b0a", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 114, "avg_line_length": 32.13636363636363, "alnum_prop": 0.7256011315417256, "repo_name": "sindresf/The-Playground", "id": "77888f51e949298f0f8a1a69a71b3a090a45ff95", "size": "707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/Machine Learning/ScikitClassifiers/Classifiers/Stochastic Gradient Boosting.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1117180" }, { "name": "Python", "bytes": "98856" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace ApiPlatform\Core\DataPersister; /** * Manages data persistence. * * @author Baptiste Meyer <baptiste.meyer@gmail.com> */ interface DataPersisterInterface { /** * Is the data supported by the persister? */ public function supports($data): bool; /** * Persists the data. * * @return object|void Void will not be supported in API Platform 3, an object should always be returned */ public function persist($data); /** * Removes the data. */ public function remove($data); }
{ "content_hash": "dcc5ee642d9e4d43ca84212c743268e3", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 108, "avg_line_length": 18.3125, "alnum_prop": 0.6382252559726962, "repo_name": "teohhanhui/DunglasApiBundle", "id": "a8ab88c04c8fc3ad8ea936e9103ffb86c7fcc45c", "size": "817", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/DataPersister/DataPersisterInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "Cucumber", "bytes": "91968" }, { "name": "PHP", "bytes": "490263" } ], "symlink_target": "" }
'use strict'; //eslint-disable-line strict //------------------------------------------------------------------------------- // Requires //------------------------------------------------------------------------------- const gulp = require('gulp'); const babel = require('gulp-babel'); const eslint = require('gulp-eslint'); const jest = require('gulp-jest-iojs'); const recipe = require('gulp-recipe'); const sourcemaps = require('gulp-sourcemaps'); const util = require('gulp-util'); //------------------------------------------------------------------------------- // Gulp Properties //------------------------------------------------------------------------------- const sources = { babel: [ 'src/**', '!**/tests/**' ] }; //------------------------------------------------------------------------------- // Gulp Tasks //------------------------------------------------------------------------------- gulp.task('default', ['prod']); gulp.task('prod', ['babel']); gulp.task('dev', ['babel', 'lint', 'babel-watch', 'lint-watch']); gulp.task('babel', function() { return gulp.src(sources.babel) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(babel({ presets: ['es2015', 'stage-2'] })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist')) .on('error', function(error) { util.log(error); }); }); gulp.task('lint', recipe.get('eslint', [ 'src/**/*.js', '!node_modules/**' ])); gulp.task('test', ['lint']); //------------------------------------------------------------------------------- // Gulp Watchers //------------------------------------------------------------------------------- gulp.task('babel-watch', function() { gulp.watch(sources.babel, ['babel']); }); gulp.task('lint-watch', function() { const lintAndPrint = eslint(); lintAndPrint.pipe(eslint.formatEach()); return gulp.watch('src/**/*.js', function(event) { if (event.type !== 'deleted') { gulp.src(event.path) .pipe(lintAndPrint, {end: false}) .on('error', function(error) { util.log(error); }); } }); });
{ "content_hash": "3123cbe80be01338875b89678aa50748", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 81, "avg_line_length": 28.048780487804876, "alnum_prop": 0.3695652173913043, "repo_name": "brianneisler/gulp-recipe", "id": "76c013ccd9d34dffe681f10353cff02675c5cf0e", "size": "2300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.babel.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "58098" } ], "symlink_target": "" }
package io.opentracing.tag; import io.opentracing.Span; public interface Tag<T> { String getKey(); void set(Span span, T value); }
{ "content_hash": "6923f67f53adbff5b697cbdad48816b7", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 33, "avg_line_length": 15.777777777777779, "alnum_prop": 0.6901408450704225, "repo_name": "opentracing/opentracing-java", "id": "755dc0d3ce0e24e81e4145ff04ee0d30f50200a4", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "opentracing-api/src/main/java/io/opentracing/tag/Tag.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "246183" }, { "name": "Shell", "bytes": "5236" } ], "symlink_target": "" }
<!-- <activity-photo activity-id="{{how to get this? I have it in the route}}"></activity-photo> --> <activity-photo></activity-photo>
{ "content_hash": "bf265b785e9ea1615d64f8dd4e191e4f", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 100, "avg_line_length": 45, "alnum_prop": 0.674074074074074, "repo_name": "sethladd/dart-snap-booth-chat", "id": "bc08d63c95c665126e06db5e29926dc84971f5cf", "size": "135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/views/activity.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1237" }, { "name": "Dart", "bytes": "44099" } ], "symlink_target": "" }
import {expect} from "chai"; import {Metadata} from "../../../../src/core"; function logger(target: any, method?: any, descriptor?: any) { return descriptor; } @logger class Test { @logger attribut: string = ""; constructor(private type?: string) { } @logger method(type: string): boolean { return true; } static methodStatic() { } } class Test2 { attribut: any; constructor() { } method() { } static methodStatic() { } } describe("Metadata", () => { describe("has", () => { it("should return false (String)", () => { expect(Metadata.has("testunknow", String)).to.equal(false); }); it("should return false (bad target)", () => { expect(Metadata.has("testunknow", undefined)).to.equal(false); }); }); describe("set", () => { it("should set meta on a class", () => { expect(Metadata.set("metadatakey1", "test1", Test)).to.equal(undefined); expect(Metadata.has("metadatakey1", Test)).to.be.true; }); it("should set meta on instance", () => { expect(Metadata.set("metadatakey2", "test2", new Test)).to.equal(undefined); expect(Metadata.has("metadatakey2", Test)).to.be.true; }); it("should set meta on a method", () => { expect(Metadata.set("metadatakey3", "test1", Test, "method")).to.equal(undefined); expect(Metadata.has("metadatakey3", Test, "method")).to.be.true; }); }); describe("get", () => { it("should get meta on a class", () => { expect(Metadata.get("metadatakey1", Test)).to.equal("test1"); }); it("should get meta on a method", () => { expect(Metadata.get("metadatakey3", Test, "method")).to.equal("test1"); }); }); describe("getOwn", () => { it("should get meta on a class", () => { expect(Metadata.getOwn("metadatakey1", Test)).to.equal("test1"); }); it("should get meta on a method", () => { expect(Metadata.getOwn("metadatakey3", Test, "method")).to.equal("test1"); }); }); describe("delete", () => { it("should remove meta on a class", () => { expect(Metadata.delete("metadatakey1", Test)).to.equal(true); }); }); describe("getType", () => { it("should return attribut type", () => { expect(Metadata.getType(Test.prototype, "attribut")).to.equal(String); }); }); describe("getOwnType", () => { it("should return attribut type", () => { expect(Metadata.getOwnType(Test.prototype, "attribut")).to.equal(String); }); }); describe("getParamTypes", () => { it("should return types on constructor", () => { expect(Metadata.getParamTypes(Test)).to.be.an("array"); expect(Metadata.getParamTypes(Test)[0]).to.equal(String); }); it("should return types on method", () => { expect(Metadata.getParamTypes(Test.prototype, "method")).to.be.an("array"); expect(Metadata.getParamTypes(Test.prototype, "method")[0]).to.equal(String); }); }); describe("getOwnParamTypes", () => { it("should return types on constructor", () => { expect(Metadata.getOwnParamTypes(Test)).to.be.an("array"); expect(Metadata.getOwnParamTypes(Test)[0]).to.equal(String); }); it("should return types on method", () => { expect(Metadata.getOwnParamTypes(Test.prototype, "method")).to.be.an("array"); expect(Metadata.getOwnParamTypes(Test.prototype, "method")[0]).to.equal(String); }); }); describe("getReturnType", () => { it("should return types on method", () => { expect(Metadata.getReturnType(Test.prototype, "method")).to.equal(Boolean); }); }); describe("getOwnReturnType", () => { it("should return types on method", () => { expect(Metadata.getOwnReturnType(Test.prototype, "method")).to.equal(Boolean); }); }); describe("list", () => { it("should return unique provide from property key", () => { Metadata.set("controller", "test", Test); Metadata.set("controller", "test2", Test2); Metadata.set("controller", "test", Test); const result = Metadata.getTargetsFromPropertyKey("controller"); expect(result).to.be.an("array"); // expect(result.length).to.equal(2); expect(result.indexOf(Test) > -1).to.be.true; expect(result.indexOf(Test2) > -1).to.be.true; const result2 = Metadata.getTargetsFromPropertyKey("controller2"); expect(result2).to.be.an("array"); expect(result2.length).to.equal(0); }); }); });
{ "content_hash": "ca1cca000da8af175374ea5d241b0066", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 94, "avg_line_length": 29.36904761904762, "alnum_prop": 0.5397243615727605, "repo_name": "lwallent/ts-express-decorators", "id": "4cf89cd6372f7f21dd2b7518fbb00c3a0b91af58", "size": "4934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/units/core/class/Metadata.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "66" }, { "name": "HTML", "bytes": "7206" }, { "name": "JavaScript", "bytes": "9253" }, { "name": "Shell", "bytes": "3001" }, { "name": "TypeScript", "bytes": "1035802" } ], "symlink_target": "" }
/* r1620 Remove unused options */ DELETE FROM `cot_config` WHERE `config_owner` = 'core' AND `config_cat` = 'performance' AND `config_name` = 'theme_consolidate';
{ "content_hash": "bdf1570d8ff7dea2983be97dabce0b3e", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 128, "avg_line_length": 81, "alnum_prop": 0.7098765432098766, "repo_name": "Velm14/dribascorp", "id": "71f2bc8f316608f4d13718eb9dfcbfceb58ea593", "size": "162", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "setup/siena/patch_0.9.0-r1620.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "125" }, { "name": "CSS", "bytes": "104664" }, { "name": "HTML", "bytes": "7932" }, { "name": "JavaScript", "bytes": "93545" }, { "name": "PHP", "bytes": "3379214" }, { "name": "Smarty", "bytes": "544125" } ], "symlink_target": "" }
<?php if (!defined('APPLICATION')) exit(); ?> <div class="Profile"> <?php if ($this->Data['Balance']) { ?> <ul class="DataList KarmaBank Karma"> <li class="Item KarmaTitles"> <div class="ItemContent"> <div class="Item"><?php echo T('KarmaBank.Transaction','Transaction') ?></div> <div class="Description"><?php echo T('KarmaBank.Date','Date') ?></div> <div class="Amount"> <span class="Karma"><?php echo T('KarmaBank.Karma','Karma') ?></span></div> <div class="Clear"></div> </div> </li> <?php foreach ($this->Data['Transactions'] As $Transaction) { $TransParts = explode(' ', $Transaction->Type); $Trans=array(); foreach($TransParts As $TransPart) $Trans[]=T(urldecode($TransPart)); $TransOrder=T($Trans[0].'.Order',trim(join(' ',array_fill(0,count($Trans),'%s')))); $Trans = vsprintf($TransOrder,$Trans); ?> <li class="Item KarmaTrans"> <div class="ItemContent"> <div class="Item"><?php echo $Trans ?></div> <div class="Description"> <?php echo Gdn_Format::Date(strtotime($Transaction->Date),T('KarmaBank.DateDefaultFormat',T('Date.DefaultFormat')).' '. T('KarmaBank.DateDefaultTimeFormat',T('Date.DefaultTimeFormat'))); ?> </div> <div class="Amount"><?php echo sprintf(T('KarmaBank.NumberFormat',"%01.2f"),$Transaction->Amount) ?><span class="Karma"></span></div> <div class="Clear"></div> </div> </li> <?php } ?> <li class="Item KarmaBal"> <div class="ItemContent"> <div class="Item"><?php echo T('KarmaBank.Balance','Balance') ?></div> <div class="Description"></div> <div class="Amount"><?php echo sprintf(T('KarmaBank.NumberFormat',"%01.2f"),$this->Data['Balance']) ?><span class="Karma"><?php echo T('KarmaBank.Karma','Karma') ?></span></div> <div class="Clear"></div> </div> </li> </ul> <?php echo $this->Pager->Render(); } else { echo '<div class="Empty">'.T('KarmaBank.NoKarmaYet','You do not have any Karma yet.').'</div>'; } if(Gdn::Session()->CheckPermission('Plugins.KarmaBank.RewardTax') || Gdn::Session()->User->Admin){ echo $this->Form->Open(); echo $this->Form->Errors(); ?> <div class="Configuration"> <div class="ConfigurationForm"> <ul> <li> <?php echo $this->Form->Label(T('KarmaBank.RewardTaxReason','Reason '),'RewardTaxReason'); echo $this->Form->TextBox('RewardTaxReason',array('class'=>'SmallInput','maxlength'=>C('Plugins.KarmaBank.ReasonMaxLength',25))); echo $this->Form->Label(T('KarmaBank.Amount','Amount'),'RewardTax'); echo $this->Form->TextBox('RewardTax',array('class'=>'SmallInput')); echo $this->Form->Button(T('KarmaBank.RewardTax','Reward / Tax')); ?> </li> </ul> </div> </div> <?php echo $this->Form->Close(); } ?> </div>
{ "content_hash": "9a5879f08b414f37355c83fda5b5efa3", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 177, "avg_line_length": 37.513888888888886, "alnum_prop": 0.6319881525360977, "repo_name": "x00/KarmaBank-Vanilla-Plugin", "id": "c83280f379f8775ea2c6587b1f77875be6d1c9d2", "size": "2701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/karmabank.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "890" }, { "name": "JavaScript", "bytes": "1115" }, { "name": "PHP", "bytes": "42677" } ], "symlink_target": "" }
<?php /* *--------------------------------------------------------------- * APPLICATION ENVIRONMENT *--------------------------------------------------------------- * * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production * * NOTE: If you change these, also change the error_reporting() code below */ define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); /* *--------------------------------------------------------------- * ERROR REPORTING *--------------------------------------------------------------- * * Different environments will require different levels of error reporting. * By default development will show errors but testing and live will hide them. */ switch (ENVIRONMENT) { case 'development': error_reporting(-1); ini_set('display_errors', 1); break; case 'testing': case 'production': ini_set('display_errors', 0); if (version_compare(PHP_VERSION, '5.3', '>=')) { error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); } else { error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); } break; default: header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'The application environment is not set correctly.'; exit(1); // EXIT_ERROR } /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. */ $system_path = '/home/pi/www/sixsided.com/system'; /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder than the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * https://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! */ $application_folder = '/home/pi/www/sixsided.com/application'; /* *--------------------------------------------------------------- * VIEW FOLDER NAME *--------------------------------------------------------------- * * If you want to move the view folder out of the application * folder set the path to the folder here. The folder can be renamed * and relocated anywhere on your server. If blank, it will default * to the standard location inside your application folder. If you * do move this, use the full server path to this folder. * * NO TRAILING SLASH! */ $view_folder = ''; /* * -------------------------------------------------------------------- * DEFAULT CONTROLLER * -------------------------------------------------------------------- * * Normally you will set your default controller in the routes.php file. * You can, however, force a custom routing by hard-coding a * specific controller class/function here. For most applications, you * WILL NOT set your routing here, but it's an option for those * special instances where you might want to override the standard * routing in a specific front controller that shares a common CI installation. * * IMPORTANT: If you set the routing here, NO OTHER controller will be * callable. In essence, this preference limits your application to ONE * specific controller. Leave the function name blank if you need * to call functions dynamically via the URI. * * Un-comment the $routing array below to use this feature */ // The directory name, relative to the "controllers" folder. Leave blank // if your controller is not in a sub-folder within the "controllers" folder // $routing['directory'] = ''; // The controller class file name. Example: mycontroller // $routing['controller'] = ''; // The controller function you wish to be called. // $routing['function'] = ''; /* * ------------------------------------------------------------------- * CUSTOM CONFIG VALUES * ------------------------------------------------------------------- * * The $assign_to_config array below will be passed dynamically to the * config class when initialized. This allows you to set custom config * items or override any default config values found in the config.php file. * This can be handy as it permits you to share one application between * multiple front controller files, with each file containing different * config values. * * Un-comment the $assign_to_config array below to use this feature */ // $assign_to_config['name_of_config_item'] = 'value of config item'; // -------------------------------------------------------------------- // END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE // -------------------------------------------------------------------- /* * --------------------------------------------------------------- * Resolve the system path for increased reliability * --------------------------------------------------------------- */ // Set the current directory correctly for CLI requests if (defined('STDIN')) { chdir(dirname(__FILE__)); } if (($_temp = realpath($system_path)) !== FALSE) { $system_path = $_temp.'/'; } else { // Ensure there's a trailing slash $system_path = rtrim($system_path, '/').'/'; } // Is the system path correct? if ( ! is_dir($system_path)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME); exit(3); // EXIT_CONFIG } /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); // Path to the system folder define('BASEPATH', str_replace('\\', '/', $system_path)); // Path to the front controller (this file) define('FCPATH', dirname(__FILE__).'/'); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); // The path to the "application" folder if (is_dir($application_folder)) { if (($_temp = realpath($application_folder)) !== FALSE) { $application_folder = $_temp; } define('APPPATH', $application_folder.DIRECTORY_SEPARATOR); } else { if ( ! is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; exit(3); // EXIT_CONFIG } define('APPPATH', BASEPATH.$application_folder.DIRECTORY_SEPARATOR); } // The path to the "views" folder if ( ! is_dir($view_folder)) { if ( ! empty($view_folder) && is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR)) { $view_folder = APPPATH.$view_folder; } elseif ( ! is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; exit(3); // EXIT_CONFIG } else { $view_folder = APPPATH.'views'; } } if (($_temp = realpath($view_folder)) !== FALSE) { $view_folder = $_temp.DIRECTORY_SEPARATOR; } else { $view_folder = rtrim($view_folder, '/\\').DIRECTORY_SEPARATOR; } define('VIEWPATH', $view_folder); /* * -------------------------------------------------------------------- * LOAD THE BOOTSTRAP FILE * -------------------------------------------------------------------- * * And away we go... */ require_once BASEPATH.'core/CodeIgniter.php';
{ "content_hash": "b46041b8b712dc1f0ae803a8ef96e185", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 158, "avg_line_length": 31.90661478599222, "alnum_prop": 0.5604878048780488, "repo_name": "kbrohkahn/sixsided.com", "id": "d811622e76a2cdb2ef0d40063a0dc116ce0fcfe5", "size": "9860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "90794" }, { "name": "HTML", "bytes": "13397" }, { "name": "JavaScript", "bytes": "55258" }, { "name": "PHP", "bytes": "3418501" }, { "name": "Ruby", "bytes": "1950" }, { "name": "Shell", "bytes": "263" } ], "symlink_target": "" }
package za.org.grassroot.core.domain.notification; import za.org.grassroot.core.domain.User; import za.org.grassroot.core.domain.task.TodoLog; import za.org.grassroot.core.enums.AlertPreference; import za.org.grassroot.core.enums.NotificationDetailedType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("TODO_CANCELLED") public class TodoCancelledNotification extends TodoNotification { private TodoCancelledNotification() { // for JPA } @Override public User getSender() { return getTodoLog().getUser(); } @Override public NotificationDetailedType getNotificationDetailedType() { return NotificationDetailedType.TODO_CANCELLED; } public TodoCancelledNotification(User target, String message, TodoLog todoLog) { super(target, message, todoLog); this.priority = AlertPreference.NOTIFY_ONLY_NEW.getPriority(); } }
{ "content_hash": "1878ec5eb1ee9e43aeca18afc546adb9", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 81, "avg_line_length": 28.03125, "alnum_prop": 0.8015607580824972, "repo_name": "grassrootza/grassroot-platform", "id": "b6ee45f89d85d1d3aacf8d04709d19679a8bd4ec", "size": "897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "grassroot-core/src/main/java/za/org/grassroot/core/domain/notification/TodoCancelledNotification.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "15432" }, { "name": "CSS", "bytes": "876" }, { "name": "Dockerfile", "bytes": "827" }, { "name": "HTML", "bytes": "29802" }, { "name": "Java", "bytes": "3488612" }, { "name": "PLSQL", "bytes": "3059" }, { "name": "PLpgSQL", "bytes": "5246" }, { "name": "SQLPL", "bytes": "2733" }, { "name": "Shell", "bytes": "6615" }, { "name": "TSQL", "bytes": "45559" } ], "symlink_target": "" }
<div class="u-mdlayout " id="dicttype-mdlayout"> <div class="u-mdlayout-btn u-row"> <div id="dicttype_list_button_2" class="u-col-4 user-actions"> <div class=" u-button-group margin-0 padding-0"> <!--兼容ie9以下enter问题--> <!--[if lt IE 10]><button style="display:block;width:1px;height:1px;border:none;">1</button><![endif]--> <button class="u-button u-button-primary u-button-sm" id="user-action-add" data-bind="click: event.addClick">增加 </button> <button class="u-button u-button-primary u-button-sm" id="user-action-edit" data-bind="click: event.saveClick">保存 </button> <button class="u-button u-button-primary u-button-sm" id="user-action-del" data-bind="click: event.delRow">删除 </button> </div> </div> <div class="u-col-4 center-title"> <span>档案管理</span> </div> </div> <div class=" form-search " style="z-index:0;"> <div class="u-panel-heading u-collapse-updown" u-data-toggle="collapse" href="#condition-row-dic"> <span class="u-panel-title padding-5 padding-left-15">快速查询 <span class="u-link u-right u-input-label sm"> <span>展开</span> <a> <i class="uf uf-arrow-down"></i> </a> </span> </span> </div> <div class="u-row u-panel-body collapse" id="condition-row-dic"> <div class="u-col-8 u-col-sm-12"> <div class="u-col-2 u-col-sm-4" style="text-align: right; height: 100%;padding: 5px;"> <label>字典编码</label> </div> <div class="u-col-4 u-col-sm-8 m-b-sm"> <input class="u-form-control sm input_search search-enter" id="search_dicttypecode" name="search_dicttypecode"/> </div> <div class="u-col-2 u-col-sm-4" style="text-align: right; height: 100%;padding: 5px;"> <label>字典名称</label> </div> <div class="u-col-4 u-col-sm-8 m-b-sm"> <input class="u-form-control sm input_search search-enter" id="search_dicttypename" name="search_dicttypename"/> </div> </div> <div class="u-col-4 u-col-sm-12"> <div class=" padding-top-2"> <button class="u-button u-button-primary raised gray-btn u-button-pa margin-right-20" id="user-action-search" data-bind="click: event.search">搜索 </button> <button class="u-button u-button-primary raised gray-btn u-button-pa" id="user-action-cleanSearch" data-bind="click: event.cleanSearch">清空 </button> </div> </div> </div> </div> <div class="u-mdlayout-detail width-full"> <!-- list --> <div class="u-mdlayout-page u-navlayout-fixed-header current" id="list"> <div class="u-mdlayout-page-section"> <div class="user-page-content"> <div class="user-datagrid "> <div class="table-container"> <div type="text" id="dicttype" u-meta='{"id":"grid_dicttype","data":"dictTypeDa","type":"grid","editable":true,"multiSelect":true,"editType":"default","columnWidth":"150px"}'> <div options='{"field":"dicttypecode","dataType":"String","title":"编码","editType":"string","editOptions":{"validType":"string","required":true}}'></div> <div options='{"field":"dicttypename","dataType":"String","title":"名称","editType":"string","editOptions":{"validType":"string","required":true}}'></div> <div options='{"field":"isfixed","dataType":"String","title":"系统预置","editType":"combo","editOptions":{"datasource":"yesOrNo","type":"combo","onlySelect":true},"renderType":"event.showValue"}'></div> <div options='{"field":"creator","dataType":"String","title":"创建人","editType":"string"}'></div> <div options='{"field":"createtime","dataType":"date","title":"创建时间","editType":"date","renderType":"dateRender","format":"YYYY-MM-DD"}'></div> <div options='{"field":"remark","dataType":"String","title":"备注","editType":"string"}'></div> </div> <div id='pagination' class='pagination u-pagination pagination-sm ' u-meta='{"type":"pagination","data":"dictTypeDa","pageChange":"event.pageChange","sizeChange":"event.sizeChange"}'></div> </div> </div> </div> </div> </div> <!-- end list --> </div> </div>
{ "content_hash": "94cb7756815cd48cd9f53e4676244f79", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 230, "avg_line_length": 60.06976744186046, "alnum_prop": 0.4899341850561363, "repo_name": "uba-templates/uba-boilerplate-webapp", "id": "0cc07a4ed15d7c1b900199c94cd7d9475f20236f", "size": "5268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/dict/dicttype.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "60088" }, { "name": "HTML", "bytes": "70469" }, { "name": "JavaScript", "bytes": "115036" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace ZendTest\Expressive\Tooling\MigrateInteropMiddleware; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use Zend\Expressive\Tooling\MigrateInteropMiddleware\ConvertInteropMiddleware; class ConvertInteropMiddlewareTest extends TestCase { use ProjectSetupTrait; public function testConvertsFilesAndEmitsInfoMessagesAsExpected() { $dir = vfsStream::setup('migrate'); $this->setupSrcDir($dir); $path = vfsStream::url('migrate'); $console = $this->setupConsoleHelper(); $converter = new ConvertInteropMiddleware($console->reveal()); $converter->process($path); $this->assertExpected($path); } }
{ "content_hash": "3d3d62fcf5977dea018e6a7cc33f7b8b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 78, "avg_line_length": 24.96551724137931, "alnum_prop": 0.7140883977900553, "repo_name": "zendframework/zend-expressive-tooling", "id": "5ec913a7a318cf768d89ab9010ae95fb41922618", "size": "1031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/MigrateInteropMiddleware/ConvertInteropMiddlewareTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "268276" } ], "symlink_target": "" }
namespace Google.Cloud.OsLogin.V1Beta.Snippets { // [START oslogin_v1beta_generated_OsLoginService_ImportSshPublicKey_sync_flattened2_resourceNames] using Google.Cloud.OsLogin.Common; using Google.Cloud.OsLogin.V1Beta; public sealed partial class GeneratedOsLoginServiceClientSnippets { /// <summary>Snippet for ImportSshPublicKey</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public void ImportSshPublicKey2ResourceNames() { // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName parent = UserName.FromUser("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey, projectId); } } // [END oslogin_v1beta_generated_OsLoginService_ImportSshPublicKey_sync_flattened2_resourceNames] }
{ "content_hash": "1e46db72f677210b89aea1a6074a351c", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 123, "avg_line_length": 50.36666666666667, "alnum_prop": 0.6909331568497684, "repo_name": "googleapis/google-cloud-dotnet", "id": "6259ed28c4c299857579c7070db8164094306e92", "size": "2133", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.OsLogin.V1Beta/Google.Cloud.OsLogin.V1Beta.GeneratedSnippets/OsLoginServiceClient.ImportSshPublicKey2ResourceNamesSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
namespace Framework.Reflection.Impl { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using Framework.Ioc; using Framework.Reflection.Mappers; internal class ReflectionProperty : IReflectionProperty { private readonly PropertyInfo property; private readonly Func<object, object> getAccessor; private readonly Action<object, object> setAccesor; private readonly Lazy<IReadOnlyList<Attribute>> attributes; public ReflectionProperty(PropertyInfo property) { this.property = property; this.attributes = new Lazy<IReadOnlyList<Attribute>>(() => this.property.GetCustomAttributes(false).Cast<Attribute>().ToList()); ParameterExpression instance = Expression.Parameter(typeof(object), "instance"); UnaryExpression instanceCast = (!this.property.DeclaringType.IsValueType) ? Expression.TypeAs(instance, this.property.DeclaringType) : Expression.Convert(instance, this.property.DeclaringType); if (this.property.GetMethod != null && this.property.GetMethod.IsPublic) { if (this.property.CanRead) { this.CanRead = true; this.getAccessor = this.property.GetGetMethod().IsStatic ? Expression.Lambda<Func<object, object>>( Expression.TypeAs(Expression.Call(null, this.property.GetGetMethod()), typeof(object)), instance).Compile() : Expression.Lambda<Func<object, object>>( Expression.TypeAs(Expression.Call(instanceCast, this.property.GetGetMethod()), typeof(object)), instance).Compile(); } } if (this.property.SetMethod != null && this.property.SetMethod.IsPublic) { ParameterExpression value = Expression.Parameter(typeof(object), "value"); UnaryExpression valueCast = (!this.property.PropertyType.IsValueType) ? Expression.TypeAs(value, this.property.PropertyType) : Expression.Convert(value, this.property.PropertyType); if (this.property.CanWrite) { this.CanWrite = true; this.setAccesor = this.property.GetSetMethod().IsStatic ? Expression.Lambda<Action<object, object>>(Expression.Call(null, this.property.GetSetMethod(), valueCast), new[] { instance, value }) .Compile() : Expression.Lambda<Action<object, object>>( Expression.Call(instanceCast, this.property.GetSetMethod(), valueCast), new[] { instance, value }).Compile(); } } this.SetPropertyInfo(this.property.PropertyType); } public bool IsPrimitive { get; private set; } public bool IsEnumerable { get; private set; } public bool IsDictionary { get; private set; } public Type EnumerableType { get; private set; } public Type KeyType { get; private set; } public bool IsNullable { get; private set; } public bool IsClass { get; private set; } public bool CanRead { get; private set; } public bool CanWrite { get; private set; } public string Name { get { return this.property.Name; } } public IReadOnlyList<Attribute> Attributes { get { return this.attributes.Value; } } public Type Type { get { if (this.IsNullable) { return Nullable.GetUnderlyingType(this.property.PropertyType); } return this.property.PropertyType; } } public T Get<T>(object instance = null) { var accessor = this.getAccessor; if (accessor != null) { return (T)accessor(instance); } return default(T); } public object Get(object instance = null) { var accessor = this.getAccessor; if (accessor != null) { return accessor(instance); } return null; } public void Set(object instance, object value) { var accesor = this.setAccesor; if (accesor != null) { accesor(instance, this.Map(value)); } } public void Set(object value) { var accesor = this.setAccesor; if (accesor != null) { accesor(null, this.Map(value)); } } private void SetPropertyInfo(Type type) { this.IsNullable = type.IsNullableType(); this.IsPrimitive = type.IsPrimitiveType(); if (!this.IsPrimitive) { if (type.IsEnumerable()) { this.IsEnumerable = true; if (type.IsArray || type == typeof(ArrayList)) { if (type.HasElementType) { this.EnumerableType = type.GetElementType(); } } else if (type.IsDictionary()) { this.IsDictionary = true; Type[] genericArguments = type.GetGenericArguments(); this.KeyType = genericArguments[0]; this.EnumerableType = genericArguments[1]; } else { Type[] genericArguments = type.GetGenericArguments(); this.EnumerableType = genericArguments[0]; } } else if (type.IsClass) { this.IsClass = true; } } } private object Map(object value) { var mappers = Container.GetAll<IObjectMapper>(); foreach (var mapper in mappers) { if (mapper.CanMap(this.Type)) { return mapper.Map(this.Type, value); } } return value; } } }
{ "content_hash": "2ee60f7b48803c0dd2932994dc454e3e", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 176, "avg_line_length": 33.72727272727273, "alnum_prop": 0.48602638672152076, "repo_name": "anwarjaved/Innosparx", "id": "7e13b3fc1703989dfece40855b14857002d77711", "size": "7051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Framework.Reflection/Impl/ReflectionProperty.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "2824025" } ], "symlink_target": "" }
namespace Rosalia.Core.Api { using Rosalia.Core.Tasks; public static partial class Extensions { public static ITask<T> ToTask<T>(this ITaskRegistry<T> registry) where T : class { return new SubflowTask<T>(registry, Identities.Empty); } public static ITask<TResult> AsTask<TResult>(this ITask<TResult> task) where TResult : class { return task; } public static ITaskRegistry<TResult> AsSubflow<TResult>(this ITaskRegistry<TResult> task) where TResult : class { return task; } } }
{ "content_hash": "609e4ef70bbcedf733c3370059b499bd", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 119, "avg_line_length": 27.545454545454547, "alnum_prop": 0.6122112211221122, "repo_name": "rosaliafx/Rosalia", "id": "51a4c283669344cde6c5881f3ae4cf5abd519a99", "size": "608", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/Rosalia.Core/Api/Extensions_Task.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "291" }, { "name": "C#", "bytes": "309169" }, { "name": "Pascal", "bytes": "501" }, { "name": "PowerShell", "bytes": "849" } ], "symlink_target": "" }
using System; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; using STEP; namespace IFC { /// <summary> /// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcpredefinedpropertyset.htm"/> /// </summary> public abstract partial class IfcPreDefinedPropertySet : IfcPropertySetDefinition { /// <summary> /// Construct a IfcPreDefinedPropertySet with all required attributes. /// </summary> public IfcPreDefinedPropertySet(IfcGloballyUniqueId globalId):base(globalId) { } /// <summary> /// Construct a IfcPreDefinedPropertySet with required and optional attributes. /// </summary> [JsonConstructor] public IfcPreDefinedPropertySet(IfcGloballyUniqueId globalId,IfcOwnerHistory ownerHistory,IfcLabel name,IfcText description):base(globalId,ownerHistory,name,description) { } public static new IfcPreDefinedPropertySet FromJSON(string json){ return JsonConvert.DeserializeObject<IfcPreDefinedPropertySet>(json); } } }
{ "content_hash": "ec61deaa96877f0ca4b0cc0cb4737aba", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 171, "avg_line_length": 27.91891891891892, "alnum_prop": 0.7734753146176185, "repo_name": "ikeough/IFC-gen", "id": "58bf84e7c99baf81480d7f179098e6b6b90821a3", "size": "1035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/csharp/src/IFC/IfcPreDefinedPropertySet.g.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "16049" }, { "name": "Batchfile", "bytes": "593" }, { "name": "C#", "bytes": "2679991" }, { "name": "JavaScript", "bytes": "319" }, { "name": "Makefile", "bytes": "1222" }, { "name": "TypeScript", "bytes": "1605804" } ], "symlink_target": "" }
<?php namespace ExpressiveLogger; class LoggerSystemErrorHandler implements ILoggerErrorHandler { public function __invoke(\Throwable $e) { error_log((string)$e, 0); } }
{ "content_hash": "89bdf7fd6b9c322b7aaa4906fed4c066", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 61, "avg_line_length": 17.454545454545453, "alnum_prop": 0.6875, "repo_name": "davidburger/expressive-logger", "id": "10af333409238e060196b17e453e2efec5829364", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/LoggerSystemErrorHandler.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "12974" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>faustcompile</title> <link rel="stylesheet" type="text/css" href="csound.css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" /> <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" /> <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" /> <link rel="prev" href="faustaudio.html" title="faustaudio" /> <link rel="next" href="faustctl.html" title="faustctl" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">faustcompile</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="faustaudio.html">Précédent</a> </td> <th width="60%" align="center">Opcodes et opérateurs de l'orchestre</th> <td width="20%" align="right"> <a accesskey="n" href="faustctl.html">Suivant</a></td> </tr> </table> <hr /> </div> <div class="refentry"> <a id="faustcompile"></a> <div class="titlepage"></div> <a id="Indexfaustcompile" class="indexterm"></a> <div class="refnamediv"> <h2> <span class="refentrytitle">faustcompile</span> </h2> <p>faustcompile — Invoque le compilateur à la volée pour produire un processus DSP instanciable depuis un programme Faust. </p> </div> <div class="refsect1"> <a id="idm47887682829136"></a> <h2>Description</h2> <p> <span class="emphasis"><em>faustcompile</em></span> compile un programme Faust contenu dans une chaîne de caractères, contrôlé par divers arguments. On peut utiliser des chaînes sur plusieurs lignes, délimitées par {{ }}. </p> </div> <div class="refsect1"> <a id="idm47887682760960"></a> <h2>Syntaxe</h2> <pre class="synopsis"><span class="command"><strong>ihandle faustcompile</strong></span> Scode, Sargs </pre> </div> <div class="refsect1"> <a id="idm47887682759184"></a> <h2>Initialisation</h2> <p> <span class="emphasis"><em><span class="quote">« <span class="quote">Scode</span> »</span></em></span> -- une chaîne de caractères (entre guillemets ou délimitée par {{ }}) contenant un programme Faust. </p> <p> <span class="emphasis"><em><span class="quote">« <span class="quote">Sargs</span> »</span></em></span> -- une chaîne de caractères (entre guillemets ou délimitée par {{ }}) contenant les arguments du compilateur Faust. </p> </div> <div class="refsect1"> <a id="idm47887682756096"></a> <h2>Exemples</h2> <p> Voici un exemple de l'opcode faustcompile. Il utilise le fichier <a class="ulink" href="examples/faustcompile.csd" target="_top"><em class="citetitle">faustcompile.csd</em></a>. </p> <div class="example"> <a id="idm47887682754288"></a> <p class="title"> <strong>Exemple 257. Exemple de l'opcode faustcompile.</strong> </p> <div class="example-contents"> <p>Voir les sections <a class="link" href="UsingRealTime.html" title="Audio en temps réel"><em class="citetitle">Audio en temps réel</em></a> et <a class="link" href="CommandFlags.html" title="Ligne de commande de Csound"><em class="citetitle">Options de la ligne de commande</em></a> pour plus d'information sur l'utilisation des options de la ligne de commande.</p> <div class="refsect1"> <a id="idm47887527361952"></a> <pre class="programlisting"> <span class="csdtag">&lt;CsoundSynthesizer&gt;</span> <span class="csdtag">&lt;CsOptions&gt;</span> -odac <span class="csdtag">&lt;/CsOptions&gt;</span> <span class="csdtag">&lt;CsInstruments&gt;</span> <span class="oblock">instr</span> 1 a1 <span class="opc">rand</span> <span class="ohdr">0dbfs</span><span class="op">/</span>4 a2 <span class="opc">oscili</span> <span class="ohdr">0dbfs</span><span class="op">/</span>4, 440 ihandle faustcompile "process<span class="op">=</span><span class="op">+</span><span class="comment">;", "-vec -lv 1"</span> idsp,asig faustaudio ihandle,a1,a2 <span class="opc">out</span> asig <span class="oblock">endin</span> <span class="csdtag">&lt;/CsInstruments&gt;</span> <span class="csdtag">&lt;CsScore&gt;</span> <span class="stamnt">i</span>1 0 10 <span class="csdtag">&lt;/CsScore&gt;</span> <span class="csdtag">&lt;/CsoundSynthesizer&gt;</span> </pre> </div> </div> </div> <p><br class="example-break" /> </p> </div> <div class="refsect1"> <a id="idm47887682749920"></a> <h2>Crédits</h2> <p>Auteur : Victor Lazzarini, 2013 </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="faustaudio.html">Précédent</a> </td> <td width="20%" align="center"> <a accesskey="u" href="OpcodesTop.html">Niveau supérieur</a> </td> <td width="40%" align="right"> <a accesskey="n" href="faustctl.html">Suivant</a></td> </tr> <tr> <td width="40%" align="left" valign="top">faustaudio </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Sommaire</a> </td> <td width="40%" align="right" valign="top"> faustctl</td> </tr> </table> </div> </body> </html>
{ "content_hash": "d61ddee0a20886b3b1d5e8267938e6e8", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 160, "avg_line_length": 43.481751824817515, "alnum_prop": 0.5949303340607689, "repo_name": "ketchupok/csound.github.io", "id": "a0c14116fb3823cb7726a6dc77c59655870e9748", "size": "6004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/manual-fr/faustcompile.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "288915" }, { "name": "Csound", "bytes": "78793" }, { "name": "Csound Document", "bytes": "6928941" }, { "name": "HTML", "bytes": "221855" }, { "name": "JavaScript", "bytes": "155989" }, { "name": "Processing", "bytes": "8668" }, { "name": "Ruby", "bytes": "3609" } ], "symlink_target": "" }
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @ClassName: ListFileServlet * @Description: 列出Web系统中所有下载文件 * @author: 孤傲苍狼 * @date: 2015-1-4 下午9:54:40 * */ public class ListFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取上传文件的目录 String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload"); //存储要下载的文件名 Map<String,String> fileNameMap = new HashMap<String,String>(); //递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中 listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一个文件也可以代表一个目录 //将Map集合发送到listfile.jsp页面进行显示 request.setAttribute("fileNameMap", fileNameMap); request.getRequestDispatcher("/listfile.jsp").forward(request, response); } /** * @Method: listfile * @Description: 递归遍历指定目录下的所有文件 * @Anthor:孤傲苍狼 * @param file 即代表一个文件,也代表一个文件目录 * @param map 存储文件名的Map集合 */ public void listfile(File file,Map<String,String> map){ //如果file代表的不是一个文件,而是一个目录 if(!file.isFile()){ //列出该目录下的所有文件和目录 File files[] = file.listFiles(); //遍历files[]数组 for(File f : files){ //递归 listfile(f,map); } }else{ /** * 处理文件名,上传后的文件是以uuid_文件名的形式去重新命名的,去除文件名的uuid_部分 file.getName().indexOf("_")检索字符串中第一次出现"_"字符的位置,如果文件名类似于:9349249849-88343-8344_阿_凡_达.avi 那么file.getName().substring(file.getName().indexOf("_")+1)处理之后就可以得到阿_凡_达.avi部分 */ String realName = file.getName().substring(file.getName().indexOf("_")+1); //file.getName()得到的是文件的原始名称,这个名称是唯一的,因此可以作为key,realName是处理过后的名称,有可能会重复 map.put(file.getName(), realName); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
{ "content_hash": "db20e07b998e8753ecdf71b8773684fb", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 103, "avg_line_length": 34.63636363636363, "alnum_prop": 0.6452318460192475, "repo_name": "yuSniper/FileUpLoad-android-web", "id": "675523795077d3e9a70b06c1dbeb7e593f5e8cda", "size": "2882", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/ZuBaProject/src/ListFileServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "132937" } ], "symlink_target": "" }
/* Css Framework ============= - see http://www.contentwithstyle.co.uk/Articles/17/a-css-framework for more info. */ @import url("tools.css"); @import url("typo.css"); @import url("forms.css"); /* Swap layout stylesheet: layout-navtop-localleft.css layout-navtop-subright.css layout-navtop-3col.css layout-navtop-1col.css layout-navleft-1col.css layout-navleft-2col.css */ @import url("layout-navtop-localleft.css"); @import url("layout.css");
{ "content_hash": "69113af56db3ea00e5d95ae9f8922e53", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 23.857142857142858, "alnum_prop": 0.6427145708582834, "repo_name": "mrdon/gae-sandbox", "id": "f142b702880afc660847e79512726a8881ebae4b", "size": "501", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "html/styles/main.css", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : /bonfire/modules/migrations/</title> <link rel="stylesheet" href="../../../sample.css" type="text/css"> <link rel="stylesheet" href="../../../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../../../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../../../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../../../'; subdir='bonfire/modules/migrations'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../../../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../../../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../../../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../../../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../../../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../../../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <div class="filelist"> <h2 class="filelist-title">/bonfire/modules/migrations/</h2> <table width="100%"><tr><td class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="../index.html">Up one level</a> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="config/index.html">config/</a><br> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="controllers/index.html">controllers/</a><br> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="docs/index.html">docs/</a><br> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="language/index.html">language/</a><br> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="libraries/index.html">libraries/</a><br> <td>&nbsp;</td></tr> <tr><td valign="top" class="filelist-filename" nowrap="nowrap" width="25"><img src="../../../_icons/folder.gif" alt="Folder"></td><td valign="top" class="filelist-filename" nowrap="nowrap"><a class="filelist-filename" href="views/index.html">views/</a><br> <td>&nbsp;</td></tr> </table></div> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Thu Oct 23 18:57:41 2014</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
{ "content_hash": "513e7b582eb068b46df3b2345cc74bbf", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 268, "avg_line_length": 61.14563106796116, "alnum_prop": 0.6617973959987298, "repo_name": "inputx/code-ref-doc", "id": "4aa8333bbcbe02ffa77dd58a42a7c6ad09470405", "size": "6298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bonfire/bonfire/modules/migrations/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17952" }, { "name": "JavaScript", "bytes": "255489" } ], "symlink_target": "" }
package com.alipay.api.request; import com.alipay.api.domain.KoubeiQualityTestCloudacptCheckresultSubmitModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.KoubeiQualityTestCloudacptCheckresultSubmitResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: koubei.quality.test.cloudacpt.checkresult.submit request * * @author auto create * @since 1.0, 2016-06-15 15:06:55 */ public class KoubeiQualityTestCloudacptCheckresultSubmitRequest implements AlipayRequest<KoubeiQualityTestCloudacptCheckresultSubmitResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 云验收检测结果提交 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "koubei.quality.test.cloudacpt.checkresult.submit"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<KoubeiQualityTestCloudacptCheckresultSubmitResponse> getResponseClass() { return KoubeiQualityTestCloudacptCheckresultSubmitResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
{ "content_hash": "125f05ac897874d5bb3ba116f2d6a79b", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 143, "avg_line_length": 22.605839416058394, "alnum_prop": 0.7420083952211818, "repo_name": "wendal/alipay-sdk", "id": "271b63879e06944fb61871b55493fae87a651556", "size": "3115", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/alipay/api/request/KoubeiQualityTestCloudacptCheckresultSubmitRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5737833" }, { "name": "Python", "bytes": "368" } ], "symlink_target": "" }
<?php /** * Configuration options for the link on an place */ return array( /** * Determines whether the link fields are shown in the administrator screens and whether they are seeded in the * fake seeder */ 'show' => true, );
{ "content_hash": "bca4699233e520129f495c4ccedaca59", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 112, "avg_line_length": 17.071428571428573, "alnum_prop": 0.6778242677824268, "repo_name": "FbF/Laravel-Places", "id": "0e8983efd77274ac8442144422e16c7480c38f5e", "size": "239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/config/link.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "39154" } ], "symlink_target": "" }
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; DROP SCHEMA IF EXISTS `espehel_ubilearn` ; CREATE SCHEMA IF NOT EXISTS `espehel_ubilearn` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; USE `espehel_ubilearn` ; -- ----------------------------------------------------- -- Table `espehel_ubilearn`.`User` -- ----------------------------------------------------- DROP TABLE IF EXISTS `espehel_ubilearn`.`User` ; CREATE TABLE IF NOT EXISTS `espehel_ubilearn`.`User` ( `id` INT NOT NULL AUTO_INCREMENT , `email` VARCHAR(45) NOT NULL , `password` VARCHAR(45) NOT NULL , `timeCreated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id`) ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `espehel_ubilearn`.`TrainingStats` -- ----------------------------------------------------- DROP TABLE IF EXISTS `espehel_ubilearn`.`TrainingStats` ; CREATE TABLE IF NOT EXISTS `espehel_ubilearn`.`TrainingStats` ( `id` INT NOT NULL , `userId` INT NOT NULL , `progress` INT NOT NULL , `score` INT NOT NULL , `gold` INT NOT NULL , `silver` INT NOT NULL , `bronze` INT NOT NULL , PRIMARY KEY (`id`) , FOREIGN KEY (`userId`) REFERENCES User(id) ) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
{ "content_hash": "c73d1cf11b299d149ce46cbba7d82358", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 99, "avg_line_length": 36.53658536585366, "alnum_prop": 0.6068090787716955, "repo_name": "espehel/UbiLearn", "id": "b0cfd9fa10900045ed3f07050d02d9580741eace", "size": "1498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ubilearn-server/src/main/java/no/ntnu/stud/ubilearn/server/db/ubilearn.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3753" }, { "name": "Java", "bytes": "265454" }, { "name": "SQL", "bytes": "2996" } ], "symlink_target": "" }
import sys, re import math import fileinput from subprocess import * from nlputil import * import itertools import time import os.path import traceback ############################################################################ # Quick Start # ############################################################################ # This program reads in data from the specified bzipped files, concatenates # them, splits them at newlines after a certain amount of data has been # read, and bzips the results. The files are assumed to contains tweets in # JSON format, and the resulting split files after named after the date # in the first tweet of the split. We take some care to ensure that we # start the file with a valid tweet, in case something invalid is in the # file. ############################################################################ # Notes # ############################################################################ # When this script was run, an example run was # # run-nohup ~tgp/split_bzip.py -s 1450000000 -o split.global. ../global.tweets.2011-*.bz2 & # # The value given to -s is the uncompressed size of each split and has been # empirically determined to give compressed sizes slightly under 192 MB -- # useful for Hadoop as it means that each split will take slightly under 3 # HDFS blocks at the default 64MB block size. # # NOTE: On the Longhorn work machines with 48GB of memory, it takes about 12 # hours to process 20-21 days of global tweets and 24-25 days of spritzer # tweets. Given that you only have a maximum of 24 hours of time, you # should probably not process more than about a month's worth of tweets in # a single run. (As an alternative, if your process gets terminated due to # running out of time or for any other reason, try removing the last, # partially written split file and then rerunning the command with the # additional option --skip-existing. This will cause it to redo the same split # but not overwrite the files that already exist. Since bzip compression takes # up most of the time, this should fairly rapidly scan through all of the # already-written files and then do the rest of them. As an example, a split # run on spritzer output that took 24 hours to process 49 days took only # 3.5 hours to skip through them when --skip-existing was used.) ####################################################################### # Process files # ####################################################################### def split_tweet_bzip_files(opts, args): status = StatusMessage("tweet") totalsize = 0 outproc = None skip_tweets = False def finish_outproc(outproc): errprint("Total uncompressed size this split: %s" % totalsize) errprint("Total number of tweets so far: %s" % status.num_processed()) outproc.stdin.close() errprint("Waiting for termination of output process ...") outproc.wait() errprint("Waiting for termination of output process ... done.") for infile in args: errprint("Opening input %s..." % infile) errprint("Total uncompressed size this split so far: %s" % totalsize) errprint("Total number of tweets so far: %s" % status.num_processed()) # NOTE: close_fds=True turns out to be necessary to avoid a deadlock in # the following circumstance: # # 1) Open input from bzcat. # 2) Open output to bzip2. # 3) bzcat ends partway through a split (possibly after multiple splits, # and hence multiple invocations of bzip2). # 4) Wait for bzcat to finish, then start another bzcat for the next file. # 5) End the split, close bzip2's stdin (our output pipe), and wait for # bzip2 to finish. # 6) Blammo! Deadlock while waiting for bzip2 to finish. # # When we opened the second bzcat, if we don't call close_fds, it # inherits the file descriptor of the pipe to bzip2, and that screws # things up. Presumably, the file descriptor inheritance means that # there's still a file descriptor to the pipe to bzip2, so closing the # output doesn't actually cause the pipe to get closed -- hence bzip2 # waits indefinitely for more input. inproc = Popen("bzcat", stdin=open(infile, "rb"), stdout=PIPE, close_fds=True) for full_line in inproc.stdout: line = full_line[:-1] status.item_processed() if not line.startswith('{"'): errprint("Unparsable line, not JSON?, #%s: %s" % (status.num_processed(), line)) else: if totalsize >= opts.split_size or (not outproc and not skip_tweets): # We need to open a new file. But keep writing the old file # (if any) until we see a tweet with a time in it. json = None try: json = split_json(line) except Exception, exc: errprint("Exception parsing JSON in line #%s: %s" % (status.num_processed(), line)) errprint("Exception is %s" % exc) traceback.print_exc() if json: json = json[0] #errprint("Processing JSON %s:" % json) #errprint("Length: %s" % len(json)) for i in xrange(len(json)): #errprint("Saw %s=%s" % (i, json[i])) if json[i] == '"created_at"': #errprint("Saw created") if i + 2 >= len(json) or json[i+1] != ':' or json[i+2][0] != '"' or json[i+2][-1] != '"': errprint("Something weird with JSON in line #%s, around here: %s" % (status.num_processed(), json[i-1:i+4])) else: json_time = json[i+2][1:-1].replace(" +0000 ", " UTC ") tweet_time = time.strptime(json_time, "%a %b %d %H:%M:%S %Z %Y") if not tweet_time: errprint("Can't parse time in line #%s: %s" % (status.num_processed(), json_time)) else: # Now we're ready to create a new split. skip_tweets = False timesuff = time.strftime("%Y-%m-%d.%H%M-UTC", tweet_time) def make_filename(suff): return opts.output_prefix + suff + ".bz2" outfile = make_filename(timesuff) if os.path.exists(outfile): if opts.skip_existing: errprint("Skipping writing tweets to existing %s" % outfile) skip_tweets = True else: errprint("Warning, path %s exists, not overwriting" % outfile) for ind in itertools.count(1): # Use _ not - because - sorts before the . of .bz2 but # _ sorts after (as well as after all letters and numbers). outfile = make_filename(timesuff + ("_%03d" % ind)) if not os.path.exists(outfile): break if outproc: finish_outproc(outproc) outproc = None totalsize = 0 if not skip_tweets: errprint("About to write to %s..." % outfile) outfd = open(outfile, "wb") outproc = Popen("bzip2", stdin=PIPE, stdout=outfd, close_fds=True) outfd.close() break totalsize += len(full_line) if skip_tweets: pass elif outproc: outproc.stdin.write(full_line) else: errprint("Warning: Nowhere to write bad line #%s, skipping: %s" % (status.num_processed(), line)) errprint("Waiting for termination of input process ...") inproc.stdout.close() # This sleep probably isn't necessary. I put it in while attempting to # solve the deadlock when closing the pipe to bzip2 (see comments above # about close_fds). sleep_time = 5 errprint("Sleeping %s seconds ..." % sleep_time) time.sleep(sleep_time) inproc.wait() errprint("Waiting for termination of input process ... done.") if outproc: finish_outproc(outproc) outproc = None # A very simple JSON splitter. Doesn't take the next step of assembling # into dictionaries, but easily could. # # FIXME: This is totally unnecessary, as Python has a built-in JSON parser. # (I didn't realize this when I wrote the function.) def split_json(line): split = re.split(r'("(?:\\.|[^"])*?"|[][:{},])', line) split = (x for x in split if x) # Filter out empty strings curind = 0 def get_nested(endnest): nest = [] try: while True: item = next(split) if item == endnest: return nest elif item == '{': nest += [get_nested('}')] elif item == '[': nest += [get_nested(']')] else: nest += [item] except StopIteration: if not endnest: return nest else: raise return get_nested(None) ####################################################################### # Main code # ####################################################################### def main(): op = OptionParser(usage="%prog [options] input_dir") op.add_option("-s", "--split-size", metavar="SIZE", type="int", default=1000000000, help="""Size (uncompressed) of each split. Note that JSON tweets compress in bzip about 8 to 1, hence 1 GB is a good uncompressed size for Hadoop. Default %default.""") op.add_option("-o", "--output-prefix", metavar="PREFIX", help="""Prefix to use for all splits.""") op.add_option("--skip-existing", action="store_true", help="""If we would try and open an existing file, skip writing any of the corresponding tweets.""") opts, args = op.parse_args() if not opts.output_prefix: op.error("Must specify output prefix using -o or --output-prefix") if not args: op.error("No input files specified") split_tweet_bzip_files(opts, args) main()
{ "content_hash": "24e8b80c73dbe2c504eb48e46f391445", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 126, "avg_line_length": 44.96491228070175, "alnum_prop": 0.5562817011314866, "repo_name": "utcompling/fieldspring", "id": "3d20a77051781493a4e3569a2d271821aa41f4c3", "size": "10359", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/python/split_bzip.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "423772" }, { "name": "Python", "bytes": "464375" }, { "name": "Scala", "bytes": "1232469" }, { "name": "Shell", "bytes": "26594" } ], "symlink_target": "" }
layout: page title: AhkIni() tagline: Fast Ini lib with standard comment-linked support ghlink: https://github.com/aviaryan/autohotkey-scripts/blob/master/Functions/AhkIni.ahk --- <a href="http://www.autohotkey.com/board/topic/95162-">Ahk Board Topic</a> <br /><br /> Class to perform Ini reading and writing operations<br /> Created as a complete replacement of the default Ini commands<br /><br /> <ul><li>Much much faster than the default Ini operations. <li>Support for reading/writing linked comments to keys and sections. <li>Same syntax as the default Ini commands.</ul><br /> <h4>Example of an Ini created through the lib</h4> {% highlight ini %} [section1] ;section1 comment key1 = hithere_key1 ;keycomment ;line2 ;line3 key2 = hithere_key2 ;keycomment2 key3 = hithere_key3 [section2] ;section2 comment key1 = hithere2 ;keycomment2 {% endhighlight %} <h4>The code</h4> {% highlight autohotkey %} SetWorkingDir,% A_scriptdir Ini := new AhkIni("black2.ini") ;will create new ini if nothing exists ini.write("section1", "key1", "hithere_key1", "keycomment`nline2`nline3") ini.write("section1", "key2", "hithere_key2", "keycomment2", "section1 comment") ini.write("section1", "key3", "hithere_key3") ;no comment for this key ini.write("section2", "key1", "hithere2", "keycomment2", "section2 comment") msgbox,% ini.read("section1", "key1", key, sec) "`n`n" key "`n`n" sec msgbox,% "Section1 keys are `n`n" ini.read("section1") ;read the keys in section 1 msgbox,% "Sections in the ini are`n`n" ini.read() ;ini.delete("section1", "key1") ;delete the above read key ini.Save() #include, AhkIni.ahk {% endhighlight %} <br /> <hr><br /> <a name=methods> <h3>Methods</h3> </a> <ul> <li>New(Inifile) <p class="tab">Sets a pointer to an Ini settings file.<br /> The Ini file is created if it doesn't exists.</p> <li>.Read(Section="", Key="", Byref Key_com="", ByRef Sec_com="") <p class="tab">Reads value of the Key contained in a Section to the outputvar.<br /> If the <b>Byref</b> parameters are specified, the <b>linked</b> Key comments (Key_com) and Section comments (Sec_com) are also read.<br /> If Section="" i.e. the first param is unspecified, the list of sections in the ini will be returned in a fashion similar to the AHK_l IniRead command.<br /> If Key="" , the list of Keys in the specified Section is returned.</p> <li>.Write(Section, Key, Value, Key_com="", Sec_com="") <p class=tab>Write values to a key, creating the key and section if necessary.<br /> The params <code class="Syntax">Key_com</code> and <code class="Syntax">Sec_com</code> are for key and section comments.<br /> If these params are omitted, then the original corresponding comment is left unchanged but if<br /> these params are called as a Space <code class="Syntax">(" " or A_space)</code>, then the linked comment for the section/key is deleted and changed to null.</p> <li>.Delete(Section="", Key="") <p class="tab">Delete keys or sections from the ini.<br /> If Key is omitted , the whole section is deleted.<br /> If Section is omitted , the whole Ini is deleted.</p> <li>.Save() <p class="tab">Saves the changes made to the Ini made in memory to the file.<br /> Remember to call <code class="Syntax">.Save</code> after making the changes.</p> </ul> <br /><br />
{ "content_hash": "c8f434d1b67a83d98ea79141a9cb3620", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 138, "avg_line_length": 38.0989010989011, "alnum_prop": 0.6700317277184886, "repo_name": "aviaryan/aviaryan.github.com", "id": "5868088ba0a738a9a87a89d1f0af9f48fa7a8078", "size": "3472", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ahk/functions/ahkini.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7170" }, { "name": "HTML", "bytes": "52816" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mém. Soc. Émul. Montbéliard, Sér. 2 5: 246 (1872) #### Original name Agaricus algidus Fr., 1821 ### Remarks null
{ "content_hash": "915e8ee2380119fc9d94e458413291ac", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 49, "avg_line_length": 15.384615384615385, "alnum_prop": 0.69, "repo_name": "mdoering/backbone", "id": "ce119a0ee2447b97fc48a969816f71b78f011c9d", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Pleurotaceae/Hohenbuehelia/Hohenbuehelia atrocoerulea/ Syn. Pleurotus algidus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; namespace NuGetPackages { class Program { static void Main() { Console.Clear(); Console.WriteLine(@" ============================================================================ This application exists for the main purpose of referencing Nuget and other external packages and copying them to a local folder so that we don't need to change referencing the various packages in every dependent project; we need only reference these from the copied location and which saves a lot of build/compilation time besides TeamCity total build time. ============================================================================ All referenced libraries are copied to a relative folder (..\bin\) above this project's folder. Forany new added reference to the solution we need to add it first here (and don't forget to limit the allowed versions in packages.config file) then reference the DLL from that project next. This requires to set the NuGetPackages project as the first one in the solution's build order. ============================================================================ "); if (Debugger.IsAttached) { Console.WriteLine(); Console.WriteLine(@"Press any key to continue ... "); Console.ReadKey(); } } } }
{ "content_hash": "9781a9a87241ceffe3dd34790057a37a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 116, "avg_line_length": 42.08064516129032, "alnum_prop": 0.6588731314679954, "repo_name": "dnnsoftware/Dnn.AdminExperience.Extensions", "id": "f4eb239592d60bf101602a51deca486bd6470f81", "size": "2616", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/NuGetPackages/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "362" }, { "name": "C#", "bytes": "1752728" }, { "name": "CSS", "bytes": "495897" }, { "name": "HTML", "bytes": "38779" }, { "name": "JavaScript", "bytes": "3436901" } ], "symlink_target": "" }
Small executable for invoking .NET methods in an assembly. Useful in build steps. NuGet package: https://www.nuget.org/packages/AssemblyInvoker/ ## Usage ``` AssemblyInvoker.exe [assembly] [class] [method] [args...] ``` ## Example ``` AssemblyInvoker.exe MyAssembly.dll SomeNamespace.MyClass RunThatCode "42" ```
{ "content_hash": "0eec2378ed1845cc305b0a9086b445d3", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 73, "avg_line_length": 18.764705882352942, "alnum_prop": 0.7335423197492164, "repo_name": "rasmuskl/AssemblyInvoker", "id": "4c8ff68ae7026967fe47c3bd0d5fcd0d44afa448", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "75" }, { "name": "C#", "bytes": "3316" } ], "symlink_target": "" }
<?xml version="1.0"?> <response><id>1200</id><name>Poss&#xE9;der un pouvoir magique lanc&#xE9; &#xE0; un NLS sup&#xE9;rieur</name><link></link><feat><id>519</id><nameId>pouvoir-magique-rapide</nameId><name>Pouvoir magique rapide</name><description>La cr&#xE9;ature peut utiliser un de ses pouvoirs magiques quasiment sans effort.</description><benefit><![CDATA[<div> Ce don s’applique à un des pouvoirs magiques de la créature, qui doit vérifier les conditions décrites ci-dessous. Trois fois par jour (ou moins souvent si la créature est normalement limitée à une ou deux utilisations quotidiennes du pouvoir), le pouvoir choisi peut être utilisé de manière rapide. Une action rapide suffit pour activer le pouvoir, et celle-ci ne provoque pas d’<a class="pagelink" href="Pathfinder-RPG.attaque%20dopportunit%c3%a9.ashx" title="attaque d'opportunité">attaque d’opportunité</a>. La créature peut entreprendre d’autres actions au cours du même round (utiliser un autre pouvoir magique par exemple, mais pas une autre <a class="pagelink" href="Pathfinder-RPG.action%20rapide.ashx" title="Action rapide">action rapide</a>). Elle ne peut utiliser qu’un seul pouvoir magique rapide par round. Le pouvoir magique choisi doit imiter un sort dont le niveau est inférieur ou égal à la moitié du NLS de la créature (arrondi vers le bas) moins 4. Le tableau ci-dessous présente les restrictions imposées par cette condition.<br><br><b>Spécial.</b> La créature peut gagner ce don plusieurs fois, mais ses effets ne se cumulent pas : il s’applique chaque fois à un pouvoir magique différent.<br><br><center> <table class="tablo" width="50%"> <caption>Pouvoirs magiques à effets rapides</caption> <tr class="titre"> <td>Niveau du sort</td> <td>NLS minimal pour utilisation rapide</td> </tr> <tr class="premier"> <td>0</td> <td>8</td> </tr> <tr class="alt"> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>12</td> </tr> <tr class="alt"> <td>3</td> <td>14</td> </tr> <tr> <td>4</td> <td>16</td> </tr> <tr class="alt"> <td>5</td> <td>18</td> </tr> <tr> <td>6</td> <td>20</td> </tr> <tr class="alt"> <td>7</td> <td>—</td> </tr> <tr> <td>8</td> <td>—</td> </tr> <tr class="alt"> <td>9</td> <td>—</td> </tr> </table> </center> </div>]]></benefit><slug>pouvoir-magique-rapide</slug></feat><slug>posseder-un-pouvoir-magique-lance-a-un-nls-superieur-1</slug></response>
{ "content_hash": "d148c97641aca33d3d2fa2f9490cfa9f", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 644, "avg_line_length": 43.51851851851852, "alnum_prop": 0.7165957446808511, "repo_name": "KmeCnin/icosahedron", "id": "358a39fffac86490a93b9b34c68ce85cdaa532e4", "size": "2394", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "web/Database/RulesBundle/FeatPrerequisite/posseder-un-pouvoir-magique-lance-a-un-nls-superieur-1.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3757" }, { "name": "CSS", "bytes": "143040" }, { "name": "HTML", "bytes": "141362" }, { "name": "JavaScript", "bytes": "32937" }, { "name": "PHP", "bytes": "672323" } ], "symlink_target": "" }
class AddReceiverEmailToMessage < ActiveRecord::Migration def up add_column :messages, :receiver_email, :string execute(<<-SQL) UPDATE messages SET receiver_email = users.email FROM users WHERE messages.receiver_id = users.id SQL change_column :messages, :receiver_email, :string, null: false end def down remove_column :messages, :receiver_email end end
{ "content_hash": "b962f1a767129a4b8cdd4f4927f8a541", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 66, "avg_line_length": 22.5, "alnum_prop": 0.6938271604938272, "repo_name": "orchardpie/nochat", "id": "de1b2afe2e59a10ea0f465713eb1703224c2378e", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20140506195738_add_receiver_email_to_message.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "568" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "71641" } ], "symlink_target": "" }
import sys import os import urllib.parse import requests from deconstrst.builder import DeconstJSONBuilder from sphinx.application import Sphinx from sphinx.builders import BUILTIN_BUILDERS def build(srcdir, destdir): """ Invoke Sphinx with locked arguments to generate JSON content. """ # I am a terrible person BUILTIN_BUILDERS['deconst'] = DeconstJSONBuilder doctreedir = os.path.join(destdir, '.doctrees') app = Sphinx(srcdir=srcdir, confdir=srcdir, outdir=destdir, doctreedir=doctreedir, buildername="deconst", confoverrides={}, status=sys.stdout, warning=sys.stderr, freshenv=True, warningiserror=False, tags=[], verbosity=0, parallel=1) app.build(True, []) return app.statuscode def submit(destdir, content_store_url, content_store_apikey, content_id_base): """ Submit the generated json files to the content store API. """ headers = { "Content-Type": "application/json", "Authorization": 'deconst apikey="{}"'.format(content_store_apikey) } for dirpath, dirnames, filenames in os.walk(destdir): for name in filenames: fullpath = os.path.join(dirpath, name) base, ext = os.path.splitext(name) if os.path.isfile(fullpath) and ext == ".json": relpath = os.path.relpath(fullpath, destdir) if base == "index": full_suffix = dirpath else: full_suffix = os.path.join(dirpath, base) content_suffix = os.path.relpath(full_suffix, destdir) content_id = content_id_base + content_suffix content_id = content_id.rstrip("/.") print( "submitting [{}] as [{}] ... ".format(relpath, content_id), end='' ) url = content_store_url + "content/" + \ urllib.parse.quote(content_id, safe='') with open(fullpath, "rb") as inf: response = requests.put(url, data=inf, headers=headers) response.raise_for_status() print("success") print("All generated content submitted to the content store.") return 0
{ "content_hash": "9c6e241ad243d1403e70b4cb5ff102af", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 79, "avg_line_length": 30.906666666666666, "alnum_prop": 0.5763589301121657, "repo_name": "ktbartholomew/preparer-sphinx", "id": "8f5c5e37946dea3e89a3d599681295ad2175cf48", "size": "2343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deconstrst/deconstrst.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1708" }, { "name": "Python", "bytes": "9969" }, { "name": "Shell", "bytes": "785" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <title>Digital Land Charges</title> <head> <link rel="stylesheet" href="/public/stylesheets/styles.css"> <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,700' rel='stylesheet' type='text/css'> </head> <body> {{>includes/header}} <div id="content"> <div class="spacer_10"></div> <h1 class="title_36">Bankruptcy registration</h1> <div class="spacer_10"></div> <div class="text_16_gray"> <a href="lrrabo_step1" class="link_16 no_link_style">1. Retrieve original</a> &nbsp;&nbsp; <a href="lrrabo_step2" class="link_16 no_link_style">2. View and amend</a> &nbsp;&nbsp; <a href="lrrabo_step3" class="link_16 no_link_style">3. Check details</a> &nbsp;&nbsp; <span class="text_16_bold">4. Key number</span> </div> <div class="spacer_30"></div> <div class="grid-row"> <div class="column-form"> <p class="text_24_bold">Court</p> <div class="spacer_10"></div> <div class="form"> <label class="form_label">Key number</label> <input class="form_textfield" type="text" autofocus> </div> <div class="spacer_30"></div> <div> <table> <tr> <td width="50%" class="no-line"> <a href="b_am_list_success"><input type="submit" value="Complete" class="form_button"></a> </td> </tr> </table> </div> </div> <!-- ///////////////////////////////// Script for page 1 in two columns ///////////////////////////////// --> <div id="page1"> <div id="zoomIn"> <div class="column-scan"> <div> <table> <tr> <td class="magnify_glass"> <a href="javascript:show('zoomOut')"><img src="../../../../../public/images/MGlass_1.png" alt="Zoom in"></a> </td> <td class="pagination_scanned_pages custom_2"> <span>Page 1 of 2 &nbsp; <a class="link_14" href="javascript:show('page2')">Next</a></span> </td> </tr> </table> </div> <a href="javascript:show('zoomOut')"> <img class="img_resize_big" src="../../../../../public/images/amend.jpg" alt="LRRABO document"> </a> </div> <div class="column-scan-small"> <div class="spacer_30"></div> <div class="spacer_5"></div> <img class="img_resize_small_selected" src="../../../../../public/images/amend.jpg" alt="LRRABO document"> <div class="spacer_10"></div> <div> <img onclick="show('page2');" class="img_resize_small" src="../../../../../public/images/additional_address.jpg" alt="LRRABO document"> </div> </div> </div> <div id="zoomOut"> <div class="column-scan"> <div> <table> <tr> <td class="magnify_glass"> <a href="javascript:show('zoomIn')"><img src="../../../../../public/images/MGlass_2.png" alt="Zoom 0ut"></a> </td> <td class="pagination_scanned_pages custom_2"> <span>Page 1 of 2 &nbsp; <a class="link_14" href="javascript:show('page2')">Next</a></span> </td> </tr> </table> </div> <a href="javascript:show('zoomIn')"> <img class="img_resize_big_magnified" src="../../../../../public/images/amendzoom2.jpg" alt="LRRABO document"> </a> </div> <div class="column-scan-small"> <div class="spacer_30"></div> <div class="spacer_5"></div> <div style="position:relative"> <img class="img_resize_small_selected" src="../../../../../public/images/amend.jpg" alt="LRRABO document"> <div class="selected_area_1"></div> </div> <div class="spacer_10"></div> <div > <img onclick="show('page2');" class="img_resize_small" src="../../../../../public/images/additional_address.jpg" alt="LRRABO document"> </div> </div> </div> </div> <!-- ///////////////////////////////// End of script for page 1 in two columns ///////////////////////////////// --> <!-- ///////////////////////////////// Script for page 2 in two columns ///////////////////////////////// --> <div id="page2"> <div id="zoomInp2"> <div class="column-scan"> <div> <table> <tr> <td class="magnify_glass"> <a href="javascript:show('zoomOut')"><img src="../../../../../public/images/MGlass_1.png" alt="Zoom in"></a> </td> <td class="pagination_scanned_pages custom_2"> <span>Page 2 of 2 &nbsp; <a class="link_14" href="javascript:show('page1')">Previous</a></span> </td> </tr> </table> </div> <a href="javascript:show('zoomOut')"> <img class="img_resize_big" src="../../../../../public/images/additional_address.jpg" alt="LRRABO document"> </a> </div> <div class="column-scan-small"> <div class="spacer_30"></div> <div class="spacer_5"></div> <img onclick="show('page1');" class="img_resize_small" src="../../../../../public/images/amend.jpg" alt="LRRABO document"> <div class="spacer_10"></div> <div > <img class="img_resize_small_selected" src="../../../../../public/images/additional_address.jpg" alt="LRRABO document"> </div> </div> </div> <div id="zoomOutp2"> <div class="column-scan"> <div> <table> <tr> <td class="magnify_glass"> <a href="javascript:show('zoomIn')"><img src="../../../../../public/images/MGlass_2.png" alt="Zoom 0ut"></a> </td> <td class="pagination_scanned_pages custom_2"> <span>Page 2 of 2 &nbsp; <a class="link_14" href="javascript:show('page1')">Previous</a></span> </td> </tr> </table> </div> <a href="javascript:show('zoomIn')"> <img class="img_resize_big_magnified" src="../../../../../public/images/additional_address_2.jpg" alt="LRRABO document"> </a> </div> <div class="column-scan-small"> <div class="spacer_30"></div> <div class="spacer_5"></div> <img onclick="show('page1');" class="img_resize_small" src="../../../../../public/images/amend.jpg" alt="LRRABO document"> <div class="spacer_10"></div> <div style="position:relative"> <img class="img_resize_small_selected" src="../../../../../public/images/additional_address.jpg" alt="LRRABO document"> <div class="selected_area_10"></div> </div> </div> </div> </div> <!-- ///////////////////////////////// End of script for page 2 in two columns ///////////////////////////////// --> </div> </div> {{>includes/footer}} </body> <script> function page() { if (document.getElementById("page1").checked) { document.getElementById("page_a").style.display = 'none'; document.getElementById("page_b").style.display = 'block'; } else if (document.getElementById("page2").checked) { document.getElementById("page_a").style.display = 'block'; document.getElementById("page_b").style.display = 'none'; } } document.getElementById("page_a").style.display = 'none'; document.getElementById("page_b").style.display = 'none'; </script> <script> function add_additional_county() { if (document.getElementById("add").style.display == 'block'){ document.getElementById("county1").style.display = 'none'; } } document.getElementById("county1").style.display = 'none'; </script> <script> function show(column) { if (column == 'zoomIn'){ document.getElementById("zoomIn").style.display = 'block'; document.getElementById("zoomOut").style.display = 'none'; document.getElementById("zoomInp2").style.display = 'block'; document.getElementById("zoomOutp2").style.display = 'none'; } else if (column == 'zoomOut'){ document.getElementById("zoomOut").style.display = 'block'; document.getElementById("zoomIn").style.display = 'none'; document.getElementById("zoomOutp2").style.display = 'block'; document.getElementById("zoomInp2").style.display = 'none'; } else if (column == 'page1'){ document.getElementById("page1").style.display = 'block'; document.getElementById("page2").style.display = 'none'; show('zoomIn'); } else if (column == 'page2'){ document.getElementById("page2").style.display = 'block'; document.getElementById("page1").style.display = 'none'; show('zoomIn'); } } document.getElementById("zoomOut").style.display = 'none'; document.getElementById("page2").style.display = 'none'; </script> </html>
{ "content_hash": "859cdc762bc3ca3aedfd470cfb9c9f3f", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 159, "avg_line_length": 37.09375, "alnum_prop": 0.4443508377796499, "repo_name": "LandRegistry/lc-prototype", "id": "4d30fde4e38767ec8bd965dee3b63544ed1eab82", "size": "10683", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/views/projects/digital_land_charges/beta/sprint5v1/lrrabo_step4.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "178796" }, { "name": "HTML", "bytes": "13266475" }, { "name": "JavaScript", "bytes": "83794" }, { "name": "Ruby", "bytes": "299" } ], "symlink_target": "" }
license: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- device.model =========== Get the device's model name. var string = device.model; Description ----------- The `device.model` returns the name of the device's model or product. The value is set by the device manufacturer and may be different across versions of the same product. Supported Platforms ------------------- - Android - BlackBerry WebWorks (OS 5.0 and higher) - iOS - Tizen - Windows Phone 7 and 8 - Windows 8 Quick Example ------------- // Android: Nexus One returns "Passion" (Nexus One code name) // Motorola Droid returns "voles" // BlackBerry: Torch 9800 returns "9800" // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models // var model = device.model; Full Example ------------ <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device Cordova: ' + device.cordova + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Model: ' + device.model + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html> Android Quirks -------------- - Gets the [product name](http://developer.android.com/reference/android/os/Build.html#PRODUCT) instead of the [model name](http://developer.android.com/reference/android/os/Build.html#MODEL), which is often the production code name. For example, the Nexus One returns `Passion`, and Motorola Droid returns `voles`. Tizen Quirks ----------- - Returns the device model assigned by the vendor, for example, `TIZEN` Windows Phone 7 and 8 Quirks ------------- - Returns the device model specified by the manufacturer. For example, the Samsung Focus returns `SGH-i917`.
{ "content_hash": "92eeba3f8f383b4e81ef1458f305a746", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 315, "avg_line_length": 35.26262626262626, "alnum_prop": 0.6092810083070753, "repo_name": "kant2002/cordova-docs", "id": "5831039c7fb1ed081f4ee081db3a7ec4ed55dca9", "size": "3495", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "docs/en/2.9.0/cordova/device/device.model.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5116" }, { "name": "CSS", "bytes": "10901" }, { "name": "HTML", "bytes": "110669" }, { "name": "JavaScript", "bytes": "62601" } ], "symlink_target": "" }
<!-- %APPDATA%\Notepad++\userDefineLang.xml --> <!-- <NotepadPlus> --> <UserLang name="protobuf" ext="proto" udlVersion="2.1"> <Settings> <Global caseIgnored="no" allowFoldOfComments="no" foldCompact="no" forcePureLC="0" decimalSeparator="0" /> <Prefix Keywords1="no" Keywords2="no" Keywords3="no" Keywords4="no" Keywords5="yes" Keywords6="no" Keywords7="no" Keywords8="no" /> </Settings> <KeywordLists> <Keywords name="Comments">00// 01 02 03 04</Keywords> <Keywords name="Numbers, prefix1"></Keywords> <Keywords name="Numbers, prefix2"></Keywords> <Keywords name="Numbers, extras1"></Keywords> <Keywords name="Numbers, extras2"></Keywords> <Keywords name="Numbers, suffix1"></Keywords> <Keywords name="Numbers, suffix2"></Keywords> <Keywords name="Numbers, range"></Keywords> <Keywords name="Operators1">= ( ) [ ] { } . , ; &gt; &lt;</Keywords> <Keywords name="Operators2"></Keywords> <Keywords name="Folders in code1, open"></Keywords> <Keywords name="Folders in code1, middle"></Keywords> <Keywords name="Folders in code1, close"></Keywords> <Keywords name="Folders in code2, open"></Keywords> <Keywords name="Folders in code2, middle"></Keywords> <Keywords name="Folders in code2, close"></Keywords> <Keywords name="Folders in comment, open"></Keywords> <Keywords name="Folders in comment, middle"></Keywords> <Keywords name="Folders in comment, close"></Keywords> <Keywords name="Keywords1">syntax option package import</Keywords> <Keywords name="Keywords2">message enum extend service</Keywords> <Keywords name="Keywords3">repeated optional required oneof extensions rpc returns stream</Keywords> <Keywords name="Keywords4">bool float double int uint string bytes map</Keywords> <Keywords name="Keywords5">int32 int64 sint32 sint64 uint32 uint64 fixed32 fixed64 sfixed32 sfixed64</Keywords> <Keywords name="Keywords6">default packed deprecated</Keywords> <Keywords name="Keywords7">true false</Keywords> <Keywords name="Keywords8"></Keywords> <Keywords name="Delimiters">00&quot; 01\ 02&quot; 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23</Keywords> </KeywordLists> <Styles> <WordsStyle name="DEFAULT" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="COMMENTS" fgColor="008000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="LINE COMMENTS" fgColor="008000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="NUMBERS" fgColor="A52A2A" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="KEYWORDS1" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="1" nesting="0" /> <WordsStyle name="KEYWORDS2" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="1" nesting="0" /> <WordsStyle name="KEYWORDS3" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="1" nesting="0" /> <WordsStyle name="KEYWORDS4" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="KEYWORDS5" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="KEYWORDS6" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="KEYWORDS7" fgColor="AA0000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="KEYWORDS8" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="OPERATORS" fgColor="000080" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="1" nesting="0" /> <WordsStyle name="FOLDER IN CODE1" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="FOLDER IN CODE2" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="FOLDER IN COMMENT" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS1" fgColor="0000FF" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS2" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS3" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS4" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS5" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS6" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS7" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> <WordsStyle name="DELIMITERS8" fgColor="000000" bgColor="FFFFFF" colorStyle="1" fontName="" fontStyle="0" nesting="0" /> </Styles> </UserLang> <!-- </NotepadPlus> -->
{ "content_hash": "608d8c7269bd33d4c95ec30dec184af8", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 143, "avg_line_length": 88.3076923076923, "alnum_prop": 0.6395470383275261, "repo_name": "ichenq/gist", "id": "afcb972d61df67ac2b10185d4c94f1c8e1d65c37", "size": "5740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "npp/protobuf/userDefineLang.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294412" }, { "name": "C++", "bytes": "279668" }, { "name": "Erlang", "bytes": "2251" }, { "name": "Go", "bytes": "108838" }, { "name": "Java", "bytes": "1877967" }, { "name": "JavaScript", "bytes": "1961" }, { "name": "Lua", "bytes": "51107" }, { "name": "PHP", "bytes": "6428" }, { "name": "Python", "bytes": "27199" }, { "name": "Shell", "bytes": "15057" }, { "name": "Vim script", "bytes": "443" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .button { background-color: #FA58F4; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button1 {background-color: #D315BC ;} .button2 {background-color: #EA4ED7 ;} .button3 {background-color: #D315BC ; color: black;} .button4 {background-color: #EA4ED7 ;} .button5{background-color: #D315BC ; color: black;} .button6{background-color: #EA4ED7 ;} .button7{background-color: #D315BC ;} .button8{background-color: #EA4ED7 ;} .button9{background-color: #D315BC ;} </style> <title>Класификација</title> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/mk_MK/sdk.js#xfbml=1&version=v2.9"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fenster"> <a href="./klasifikacija.html"><img src="klasss Kopie.jpg" height="500" width="100%" style="float:left"></a> </div> <button class="button button1"><a href="./pochetna.html"><font color="black">Почетна</font></a></button> <button class="button button2"><a href="./zakancerot.html"><font color="black">За канцерот</font></a></button> <button class="button button3"><a href="./stadiumi.html"><font color="black">Хемотерапија</font></a></button> <button class="button button4"><a href="./recepti.html"><font color="black">Рецепти</font></a></button> <button class="button button5"><a href="./dieti.html"><font color="black">Исхрана</font></a></button> <button class="button button6"><a href="./soveti.html"><font color="black">Совети</font></a></button> <button class="button button7"><a href="./bolnici.html"><font color="black"</font>Болници</a></button> <button class="button button8"><a href="./Donacii.html"><font color="black">Донации</font></a></button> <button class="button button9"><a href="./lekovi.html"><font color="black">Лекови</font></a></button> <p><i><font size="4" color="black"><b>Видовите на рак се класифицираат според видот на клетки кои наликуваат на тумор, и според тоа, на ткивото за кое се претпоставува дека е зачеток на туморот. Подолу е хистологијата и местоположбата на видовите рак. Примери за неколку општи категории се: Карцином: Малигни тумори кои потекнуваат од епителни клетки. Во оваа група припаѓаат најчестите видови на рак, вклучувајќи ги ракот на дојката, простатата, белите дробови и дебелото црево. Сарком: Малигни тумори кои потекнуваат од сврзните ткива, или мезенхималните клетки. Лимфом и леукемија: Малигноми кои потекнуваат од хематопоетските (крвотворните) клетки Бактериски рак: Тумори кои потекнуваат од тотипотентните клетки. Кај возрасните најчесто може да се најде во тестисите и јајчниците, додека кај фетусите, бебињата и малите деца најчесто се наоѓаат во средишниот дел на телото, на врвот на опашната коска, а кај коњите во основата на черепот. Бластен тумор или бластом: Тумор (обично малигнен) кој наликува на незрело или ембрионско ткиво. Овие тумори се најчести кај децата. тумори (видови рак) обично се именуваат користејќи –карцином, -сарком или –бластом како суфикс, и латинскиот или грчкиот збор за органот од кој потекнуваат како корен на името. На пример, ракот на црниот дроб се нарекува хепатокарцином, ракот на масните клетки- липосарком итн. Бенигните тумори (кои не се рак) се именуваат користејќи –ом како суфикс, и името на органот како корен. На пример, бенигнен тумор на мазната мускулатура на матката се нарекува леиомиом (почест израз за овој вид тумор е фиброид). За жал, и некои видови рак го користат суфиксот –ом, како што е случајот со меланом и семином </font></i></p></b> <iframe width="70%" height="500" src="https://www.youtube.com/embed/72-2Bumwyh0" frameborder="0" allowfullscreen></iframe> <div class="fb-comments" data-href="http://127.0.0.1:8020/borbaprotivkancerot/klasifikacija.html" data-numposts="5"></div> </body> </html>
{ "content_hash": "5fe8f5d153cd27a362025ba442a3f87d", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 140, "avg_line_length": 45.84782608695652, "alnum_prop": 0.7159791370317686, "repo_name": "majaradichevich/majaradichevich.github.io", "id": "7ed025a1c9e8db3faad7a92693291f6f197a9621", "size": "5642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "klasifikacija.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6042" }, { "name": "HTML", "bytes": "185244" }, { "name": "JavaScript", "bytes": "11231" } ], "symlink_target": "" }
[![npm version](https://badge.fury.io/js/xgallerify.svg)](https://badge.fury.io/js/xgallerify) [![Bower version](https://badge.fury.io/bo/xGallerify.svg)](https://badge.fury.io/bo/xGallerify) [![](https://data.jsdelivr.com/v1/package/npm/xgallerify/badge)](https://www.jsdelivr.com/package/npm/xgallerify) [![Status Deprecated](https://img.shields.io/badge/Status-Deprecated-dd741f.svg)](https://github.com/xremix/ng-xGallerify) **!!!!There is a new version of this project, based on angular!!!!** **Please check [xremix/ng-xGallerify](https://github.com/xremix/ng-xGallerify) for the latest version of this project. This project will still be maintained with bug fixes.** A lightweight, responsive, smart gallery based on jQuery. - Responsive - Simple to use - Customizable and custom styling - Only 3kb file size - [AngularJS directive available](https://github.com/JohnnyTheTank/angular-xGallerify) ## Demo Check out the [Demo](https://rawgit.com/xremix/xGallerify/master/Demo.html) or try it yourself with [CodePen](http://codepen.io/xremix/pen/QyqJzQ) To see a real-live sample see the [Flickr Demo](https://rawgit.com/xremix/xGallerify/master/Demo-Flickr.html) or try it yourself with the [CodePen Sample](http://codepen.io/xremix/pen/OMxarm) ## Usage ```JS $('.photos').gallerify({ margin:10, mode:'default' }); ``` In this sample `.photos` is a `<div>` containing the images. xGallerify will resize the images in a pleasant way for you. #### Custom Styling Images can be put inside of div's and styled on your own. Check out the full [CodePen Demo](http://codepen.io/xremix/pen/QyqJzQ) including all settings, for a sample with a custom styled div. ### CDN [jsDelivr](https://www.jsdelivr.com/package/npm/xgallerify) The official CDN for xGallerify is hosted on [jsDelivr](https://www.jsdelivr.com/package/npm/xgallerify) and will support the latest version (served from NPM). ```HTML <!-- Latest Version --> <script src="https://cdn.jsdelivr.net/npm/xgallerify@latest/dist/jquery.xgallerify.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/xgallerify@latest/dist/jquery.xgallerify.js"></script> <!-- Specific Version --> <script src="https://cdn.jsdelivr.net/npm/xgallerify@0.1.5/dist/jquery.xgallerify.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/xgallerify@0.1.5/dist/jquery.xgallerify.js"></script> ``` #### Alternate CDN (rawgit) Specific branch versions directly from github.com are hosted at the [rawgit CDN](https://rawgit.com). ```HTML <!-- Master Branch --> <script src="https://rawgit.com/xremix/xGallerify/master/dist/jquery.xgallerify.js"></script> <!-- Develop Branch --> <script src="https://rawgit.com/xremix/xGallerify/develop/dist/jquery.xgallerify.js"></script> ``` ## Parameters | Name | Default / Options | Type | Description | |---|---|---|---| | `margin` | e.g. `10` | `int` | Value in pixels of the margin of each image on each side | | `galleryMargin` | e.g. `17` | `int` | Value in pixels of the margin outside of the gallery. **This is set to 17px default because of some rendering issue on macOS Safari** | | `mode` | `default`, `bootstrap`, `bootstrapv4`, `flickr`, `small` or custom object | `string` or `object` | The style mode wich defines how the gallery should be displayed and how many images fit in a row. See description in the mode section. | | `lastRow` | `adjust`, `fullwidth` or `hidden` | `string` | Set the last row to the full width, hide it or find a good adjustment. *NOTE:* I personally prefer `adjust`, wich is also the default. | | `jsSetup` | `true` or `false` | `bool` | Sets some default CSS values to the elements like `dislay:inline-block` and for each image inside of a container `width:100%`. This can be disabled if you want to have your own floating or style this in plain CSS. | | `debounceTime` | `0` | `int` | This functionality waits `x ms` before rendering a new loaded image to boost the performance on older machines. | | `width` | `800` | `int` | Width of the gallery in `px` - **Work in Progress!** It is recommended to use an outer div with a specific width to controll the width of the Gallery. | ### Modes The modes property defines **how many** images do show at what **container width** *NOTE* If you want to have another mode you are welcome to contribute or open an [issue](https://github.com/xremix/xGallerify/issues). The maximal image height helps to show multiple images in a row, if the images do have a very high ratio like 3:9. #### Predefined Modes | Mode| Breakpoint | Images per row | | ---------------- | ---------------- | ---------------- | | **default mode** | Container width > 1800 | 4 | | | Container width > 1200 | 3 | | | Container width > 768 | 2 | | | Container width < 768 | 1 | | | Maximal image height | Screen Height * 0.5 | | **bootstrap mode** | Container width > 1170 | 4 | | | Container width > 970 | 3 | | | Container width > 750 | 2 | | | Container width < 750 | 1 | | | Maximal image height | Screen Height * 0.5 | | **bootstrapv4 mode** | Container width > 1200 | 4 | | | Container width > 992 | 3 | | | Container width > 768 | 2 | | | Container width < 768 | 1 | | | Maximal image height | Screen Height * 0.5 | | **flickr mode** | Container width > 1800 | 4 | | | Container width > 1300 | 3 | | | Container width > 610 | 2 | | | Container width < 610 | 1 | | | Maximal image height | Screen Height * 0.4 | | **small mode** | Container width > 1800 | 14 | | | Container width > 1300 | 10 | | | Container width > 610 | 6 | | | Container width < 610 | 4 | | | Maximal image height | Screen Height * 0.4 | #### Custom Modes The mode parameter can also be an object that defnies the breakpoints and max height of an image. Check out the [Codepen](http://codepen.io/xremix/pen/QyqJzQ) demo or the following sample object: ```JS var gallery = $('.photos').gallerify({ margin:5, mode:{ maxHeight: screen.height * 0.5, breakPoints:[ { minWidth: 1170, columns: 10, },{ minWidth: 970, columns: 6, },{ minWidth: 750, columns: 3, },{ maxWidth: 750, columns: 2, } ] }, lastRow:'adjust' }); ``` ## Functions ### Render If new images are added or loaded you can call `render` to reinitialize the gallery. This will only resize the images to fit again. ```JS $('.photos').gallerify(); //... $(window).on('load', function() { // Eventlistener that fires when all images are loaded $('.photos').gallerify.render(); }); ``` ### Render Async Images Automatically renders every time an image has been loaded. This needs to get called everytime you add a new image to `.photos` after calling `gallerify()`, if you don't have your own *image loaded* event listener like described in the Render function documentation. ```JS $('.photos').gallerify(); $('.photos').append('<img src="sample-image.jpg">'); $('.photos').append('<img src="sample-image2.jpg">'); $('.photos').append('<img src="sample-image3.jpg">'); $('.photos').gallerify.renderAsyncImages(); ``` ## Community xGallerify AngularJS directive: [JohnnyTheTank/angular-xGallerify](https://github.com/JohnnyTheTank/angular-xGallerify) xGallerify Angular component: [xremix/ng-xGallerify](https://github.com/xremix/ng-xGallerify) Thanks everyone for contributing. Suggestions are always welcome. Also I'm happy to hear in which projects you've used the library. [![Analytics](https://ga-beacon.appspot.com/UA-40522413-9/xGallerify/readme)](https://github.com/xremix/xGallerify)
{ "content_hash": "3d961c428d44fde1fda3cb01e29c75c5", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 265, "avg_line_length": 40.50810810810811, "alnum_prop": 0.692020282892981, "repo_name": "xremix/xGallerify", "id": "8a979d831078082ef4d52c24d3a1563a5b66c3d6", "size": "7507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6514" }, { "name": "JavaScript", "bytes": "9911" } ], "symlink_target": "" }
import Data.List -------------------------------------------------------------------------------- type RomanDigit = Char type RomanNumber = [RomanDigit] -------------------------------------------------------------------------------- digitValue :: RomanDigit -> Int digitValue 'I' = 1 digitValue 'V' = 5 digitValue 'X' = 10 digitValue 'L' = 50 digitValue 'C' = 100 digitValue 'D' = 500 digitValue 'M' = 1000 -------------------------------------------------------------------------------- fromRoman :: RomanNumber -> Int fromRoman roman = fst $ foldr update (0, 0) $ map digitValue roman where update :: Int -> (Int, Int) -> (Int, Int) update val (acc, prev) = if prev <= val then (acc+val, val) else (acc-val, prev) -------------------------------------------------------------------------------- toRoman :: Int -> RomanNumber toRoman n = convert "" n [(1000, "M"), (900, "MC"), (500, "D"), (400, "DC"), ( 100, "C"), ( 90, "CX"), ( 50, "L"), ( 40, "LX"), ( 10, "X"), ( 9, "XI"), ( 5, "V"), ( 4, "VI"), ( 1, "I")] where convert :: RomanNumber -> Int -> [(Int, [RomanDigit])] -> RomanNumber convert acc n factors@((v, digits):factors') | n == 0 = reverse acc | v <= n = convert (digits ++ acc) (n-v) factors | otherwise = convert acc n factors' -------------------------------------------------------------------------------- main = do fileLines <- readFile "euler_0089.txt" let originalNumbers = lines fileLines let reworkedNumbers = map (toRoman . fromRoman) originalNumbers let originalVal = length $ concat originalNumbers let finalVal = length $ concat reworkedNumbers putStrLn ("Number of characters: ") putStrLn (" Initial: " ++ show originalVal) putStrLn (" Final : " ++ show finalVal) putStrLn (" Gain : " ++ show (originalVal - finalVal)) --------------------------------------------------------------------------------
{ "content_hash": "87ff66dacc2244e59a41949d19c9fe81", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 80, "avg_line_length": 36.64912280701754, "alnum_prop": 0.4155098133078028, "repo_name": "dpieroux/euler", "id": "226cc0415adca030d0f0e1e2ede4bb2c7d58486f", "size": "2089", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "0/0089.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "140" }, { "name": "Haskell", "bytes": "292108" }, { "name": "Julia", "bytes": "31751" } ], "symlink_target": "" }
package com.planet_ink.coffee_mud.Commands; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.ListingLibrary; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; public class Equipment extends StdCommand { public Equipment() { } private final String[] access = I(new String[] { "EQUIPMENT", "EQ", "EQUIP" }); @Override public String[] getAccessWords() { return access; } private final static Class<?>[][] internalParameters=new Class<?>[][]{{MOB.class},{Boolean.class},{}}; public StringBuilder getEquipment(final MOB seer, final MOB mob, final boolean allPlaces) { final StringBuilder msg=new StringBuilder(""); if(CMLib.flags().isSleeping(seer)) return new StringBuilder("(nothing you can see right now)"); final int wrap=CMLib.lister().fixColWidth(74,seer.session()); final int shortWrap=CMLib.lister().fixColWidth(50,seer.session()); final int headWrap=26; long wornCode=0; String header=null; String wornName=null; Item thisItem=null; String tat=null; final boolean paragraphView=(CMProps.getIntVar(CMProps.Int.EQVIEW)>CMProps.Int.EQVIEW_MIXED) ||((seer!=mob)&&(CMProps.getIntVar(CMProps.Int.EQVIEW)>CMProps.Int.EQVIEW_DEFAULT)) ||seer.isAttributeSet(MOB.Attrib.COMPRESS); final HashSet<Item> alreadyDone=new HashSet<Item>(); final Wearable.CODES codes = Wearable.CODES.instance(); for(int l=0;l<codes.all_ordered().length;l++) { wornCode=codes.all_ordered()[l]; wornName=codes.name(wornCode); if(paragraphView) header=" ^!"; else { header="^N(^H"+wornName+"^?)"; header+=CMStrings.SPACES.substring(0,headWrap-header.length())+": ^!"; } final List<Item> wornHere=mob.fetchWornItems(wornCode,(short)(Short.MIN_VALUE+1),(short)0); int shownThisLoc=0; int numLocations=mob.getWearPositions(wornCode); if(numLocations==0) numLocations=1; int emptySlots=numLocations; if(wornHere.size()>0) { if(!allPlaces) { final List<List<Item>> sets=new Vector<List<Item>>(numLocations); for(int i=0;i<numLocations;i++) sets.add(new Vector<Item>()); Item I=null; Item I2=null; short layer=Short.MAX_VALUE; short layerAtt=0; short layer2=Short.MAX_VALUE; short layerAtt2=0; List<Item> set=null; for(int i=0;i<wornHere.size();i++) { I=wornHere.get(i); if(I.container()!=null) continue; if(I instanceof Armor) { layer=((Armor)I).getClothingLayer(); layerAtt=((Armor)I).getLayerAttributes(); } else { layer=0; layerAtt=0; } for(int s=0;s<sets.size();s++) { set=sets.get(s); if(set.size()==0) { set.add(I); break; } for(int s2=0;s2<set.size();s2++) { I2=set.get(s2); if(I2 instanceof Armor) { layer2=((Armor)I2).getClothingLayer(); layerAtt2=((Armor)I2).getLayerAttributes(); } else { layer2=0; layerAtt2=0; } if(layer2==layer) { if(((layerAtt&Armor.LAYERMASK_MULTIWEAR)>0) &&((layerAtt2&Armor.LAYERMASK_MULTIWEAR)>0)) set.add(s2,I); break; } if(layer2>layer) { set.add(s2,I); break; } } if(set.contains(I)) break; if(layer2<layer) { set.add(I); break; } } } wornHere.clear(); for(int s=0;s<sets.size();s++) { set=sets.get(s); int s2=set.size()-1; for(;s2>=0;s2--) { I2=set.get(s2); wornHere.add(I2); if((!(I2 instanceof Armor)) ||(!CMath.bset(((Armor)I2).getLayerAttributes(),Armor.LAYERMASK_SEETHROUGH))) { emptySlots--; break; } } } } for(int i=0;i<wornHere.size();i++) { thisItem=wornHere.get(i); if((thisItem.container()==null)&&(thisItem.amWearingAt(wornCode))) { if(paragraphView) { if(alreadyDone.contains(thisItem)) continue; alreadyDone.add(thisItem); } if(CMLib.flags().canBeSeenBy(thisItem,seer)) { if(paragraphView) { String name=thisItem.name(); if(!allPlaces) name=CMStrings.ellipseColored(name,wrap); if(wornCode==Wearable.WORN_HELD) { if(msg.length()==0) msg.append(L("nothing.")); if(mob==seer) msg.append(L("\n\rHolding ^<EItem^>@x1^</EItem^>@x2^N",name,CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim())); else msg.append(L("\n\r@x1 is holding @x2@x3^N.",mob.charStats().HeShe(),name.trim(),CMLib.flags().getDispositionBlurbs(thisItem, seer).toString().trim())); } else if(wornCode==Wearable.WORN_WIELD) { if(msg.length()==0) msg.append(L("nothing.")); if(mob==seer) msg.append(L("\n\rWielding ^<EItem^>@x1^</EItem^>@x2^N.",name,CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim())); else msg.append(L("\n\r@x1 is wielding @x2@x3^N.",mob.charStats().HeShe(),name.trim(),CMLib.flags().getDispositionBlurbs(thisItem, seer).toString().trim())); } else { if(mob==seer) msg.append(header+"^<EItem^>"+name+"^</EItem^>"+CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim()+"^N,"); else msg.append(header+name.trim()+CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim()+"^N,"); } } else { String name=thisItem.name(); if((name.length()>shortWrap)&&(!allPlaces)) name=CMStrings.ellipseColored(name,shortWrap); if(mob==seer) msg.append(header+"^<EItem^>"+name+"^</EItem^>"+CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim()+"^?\n\r"); else msg.append(header+name.trim()+CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim()+"^?\n\r"); } shownThisLoc++; } else if(seer==mob) { msg.append(L("@x1(something you can`t see)@x2^?\n\r",header,CMLib.flags().getDispositionBlurbs(thisItem,seer).toString().trim())); shownThisLoc++; } } } } if(emptySlots>0) { double numTattoosTotal=0; wornName=wornName.toUpperCase(); for(final Enumeration<Tattoo> e=mob.tattoos();e.hasMoreElements();) { final Tattoo T = e.nextElement(); if(T.getTattooName().startsWith(wornName+":")) numTattoosTotal+=1.0; } int numTattoosToShow=(int)Math.round(Math.ceil(CMath.mul(numTattoosTotal,CMath.div(emptySlots,numLocations)))); for(final Enumeration<Tattoo> e=mob.tattoos();e.hasMoreElements();) { final Tattoo T = e.nextElement(); if((T.getTattooName().startsWith(wornName+":")) &&((--numTattoosToShow)>=0)) { tat=T.getTattooName(); if(paragraphView) { tat=tat.substring(wornName.length()+1).toLowerCase(); if(tat.length()>wrap) tat=tat.substring(0,wrap)+"..."; msg.append(header+tat+"^?,"); } else { tat=CMStrings.capitalizeAndLower(tat.substring(wornName.length()+1).toLowerCase()); if(tat.length()>shortWrap) tat=tat.substring(0,shortWrap)+"..."; msg.append(header+tat+"^?\n\r"); } shownThisLoc++; } } } if((allPlaces)&&(shownThisLoc==0)) { if(((!paragraphView)&&(wornCode!=Wearable.WORN_FLOATING_NEARBY)) ||((paragraphView)&&(wornCode!=Wearable.WORN_WIELD))) for(int i=mob.getWearPositions(wornCode)-1;i>=0;i--) msg.append(header+"^?\n\r"); } } if(msg.length()==0) { msg.append(L("^!(nothing)^?\n\r")); } else { int commaDex=(paragraphView)?msg.lastIndexOf(","):-1; if((paragraphView)&&(commaDex > -1)) { msg.insert(commaDex + 1, "."); msg.deleteCharAt(commaDex); commaDex=msg.lastIndexOf(","); if(commaDex > -1) msg.insert(commaDex + 1, " and"); } } return msg; } private void viewEquipment(final MOB mob, final boolean longView) { final Session session=mob.session(); if(session!=null) { final boolean paragraphView=(CMProps.getIntVar(CMProps.Int.EQVIEW)==CMProps.Int.EQVIEW_PARAGRAPH); if(paragraphView) { if(longView) session.wraplessPrintln(L("You are wearing @x1",getEquipment(mob,mob,true).toString())); else session.wraplessPrintln(L("You are wearing @x1",getEquipment(mob,mob,false).toString())); } else if(longView) session.wraplessPrintln(L("You are wearing:\n\r@x1",getEquipment(mob,mob,true).toString())); else session.wraplessPrintln(L("You are wearing:\n\r@x1",getEquipment(mob,mob,false).toString())); } } @Override public boolean execute(final MOB mob, final List<String> commands, final int metaFlags) throws java.io.IOException { viewEquipment(mob,(commands.size()>1)&&(CMParms.combine(commands,1).equalsIgnoreCase("long"))); return false; } @Override public boolean canBeOrdered() { return true; } @Override public Object executeInternal(final MOB mob, final int metaFlags, final Object... args) throws java.io.IOException { if(!super.checkArguments(internalParameters, args)) return null; if((args.length>0)&&(args[0] instanceof MOB)) return getEquipment((MOB)args[0],mob,false); else if((args.length>0)&&(args[0] instanceof Boolean)) viewEquipment(mob,((Boolean)args[0]).booleanValue()); else viewEquipment(mob,false); return null; } }
{ "content_hash": "d3f1d06a0e3fbed84b651b6e9715fa4b", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 162, "avg_line_length": 31.052325581395348, "alnum_prop": 0.5942707358172626, "repo_name": "bozimmerman/CoffeeMud", "id": "9ec7df7cdb545358f3f1cb45bc862e134ee18db1", "size": "11286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com/planet_ink/coffee_mud/Commands/Equipment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5847" }, { "name": "CSS", "bytes": "1619" }, { "name": "HTML", "bytes": "12319179" }, { "name": "Java", "bytes": "38979811" }, { "name": "JavaScript", "bytes": "45220" }, { "name": "Makefile", "bytes": "23191" }, { "name": "Shell", "bytes": "8783" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Prob2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Prob2")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c26890e1-441e-4cf5-a326-409f6181bdad")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "bf72770ae67f3dc5fa02973b3b3c313a", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.416666666666664, "alnum_prop": 0.7425885755603759, "repo_name": "LazarDL/TelerikHomeworks", "id": "a4f669cd41e0a2301823e75601c1f992297b1cf2", "size": "1386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#2/TestPreparation/Prob2/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "307819" }, { "name": "C#", "bytes": "3112321" }, { "name": "CSS", "bytes": "282650" }, { "name": "CoffeeScript", "bytes": "491" }, { "name": "JavaScript", "bytes": "12003372" }, { "name": "XSLT", "bytes": "2333" } ], "symlink_target": "" }
/* * ESO Archive * * $Id: FITSCodec.java 4414 2004-02-03 16:21:36Z brighton $ * * who when what * -------------- ---------- ---------------------------------------- * Allan Brighton 1999/05/03 Created */ package jsky.image.fits.codec; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import com.sun.media.jai.codec.ForwardSeekableStream; import com.sun.media.jai.codec.ImageCodec; import com.sun.media.jai.codec.ImageDecoder; import com.sun.media.jai.codec.ImageDecodeParam; import com.sun.media.jai.codec.ImageEncoder; import com.sun.media.jai.codec.ImageEncodeParam; import com.sun.media.jai.codec.SeekableStream; import java.awt.image.*; /** * A subclass of <code>ImageCodec</code> that handles * the FITS image format. * * @version $Revision: 4414 $ * @author Allan Brighton */ public final class FITSCodec extends ImageCodec { /** Constructs an instance of <code>FITSCodec</code>. */ public FITSCodec() { } /** Returns the name of the format handled by this codec. */ public String getFormatName() { return "fits"; } /** * Returns <code>Object.class</code> since no DecodeParam * object is required for decoding. */ public Class getDecodeParamClass() { return Object.class; } /** Returns <code>null</code> since no encoder exists. */ public Class getEncodeParamClass() { return null; } /** Returns true if the image is encodable by this codec. */ public boolean canEncodeImage(RenderedImage im, ImageEncodeParam param) { SampleModel sampleModel = im.getSampleModel(); int dataType = sampleModel.getTransferType(); int numBands = sampleModel.getNumBands(); if (numBands != 1 /* && numBands != 3 XXX not impl */) { return false; } return true; } /** * Instantiates a <code>FITSEncoder</code> to write to the * given <code>OutputStream</code>. * * @param dst the <code>OutputStream</code> to write to. * @param param an instance of <code>FITSEncodeParam</code> used to * control the encoding process, or <code>null</code>. A * <code>ClassCastException</code> will be thrown if * <code>param</code> is non-null but not an instance of * <code>FITSEncodeParam</code>. */ protected ImageEncoder createImageEncoder(OutputStream dst, ImageEncodeParam param) { FITSEncodeParam p = null; if (param != null) { p = (FITSEncodeParam) param; // May throw a ClassCast exception } return new FITSEncoder(dst, p); } /** * Instantiates a <code>FITSDecoder</code> to read from the * given <code>InputStream</code>. * * <p> By overriding this method, <code>FITSCodec</code> is able to * ensure that a <code>ForwardSeekableStream</code> is used to * wrap the source <code>InputStream</code> instead of the a * general (and more expensive) subclass of * <code>SeekableStream</code>. Since the FITS decoder does not * require the ability to seek backwards in its input, this allows * for greater efficiency. * * @param src the <code>InputStream</code> to read from. * @param param an instance of <code>ImageDecodeParam</code> used to * control the decoding process, or <code>null</code>. */ protected ImageDecoder createImageDecoder(InputStream src, ImageDecodeParam param) { // Add buffering for efficiency (XXX no: done in FITS I/O classes) //if (!(src instanceof BufferedInputStream)) { // src = new BufferedInputStream(src); //} try { return new FITSDecoder(new ForwardSeekableStream(src), param); } catch (Exception e) { throw new RuntimeException(e); } } /** * Instantiates a <code>FITSDecoder</code> to read from the * given <code>SeekableStream</code>. * * @param src the <code>SeekableStream</code> to read from. * @param param an instance of <code>ImageDecodeParam</code> used to * control the decoding process, or <code>null</code>. */ protected ImageDecoder createImageDecoder(SeekableStream src, ImageDecodeParam param) { try { return new FITSDecoder(src, param); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Returns the number of bytes from the beginning of the data required * to recognize it as being in FITS format. */ public int getNumHeaderBytes() { return 6; } /** * Returns <code>true</code> if the header bytes indicate FITS format. * * @param header an array of bytes containing the initial bytes of the * input data. */ public boolean isFormatRecognized(byte[] header) { return ((header[0] == 'S') && (header[1] == 'I') && (header[2] == 'M') && (header[3] == 'P') && (header[4] == 'L') && (header[5] == 'E')); } }
{ "content_hash": "53ecfb579e43e3a30f6f5d0972e51442", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 91, "avg_line_length": 32.9625, "alnum_prop": 0.6069397042093287, "repo_name": "arturog8m/ocs", "id": "a02c7100d802ff0f0c2970efc4c39ad3c16cd8c6", "size": "5274", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "bundle/jsky.app.ot/src/main/java/jsky/image/fits/codec/FITSCodec.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "490242" }, { "name": "Java", "bytes": "14504312" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "4967047" }, { "name": "Shell", "bytes": "4989" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
package main import ( "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "strconv" "syscall" "github.com/gorilla/mux" "github.com/lxc/lxd/shared" ) func containerFileHandler(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLXDLoad(d, name) if err != nil { return SmartError(err) } targetPath := r.FormValue("path") if targetPath == "" { return BadRequest(fmt.Errorf("missing path argument")) } if !c.IsRunning() { return BadRequest(fmt.Errorf("container is not running")) } initPid, err := c.InitPidGet() if err != nil { return InternalError(err) } switch r.Method { case "GET": return containerFileGet(initPid, r, targetPath) case "POST": idmapset, err := c.IdmapSetGet() if err != nil { return InternalError(err) } return containerFilePut(initPid, r, targetPath, idmapset) default: return NotFound } } func containerFileGet(pid int, r *http.Request, path string) Response { /* * Copy out of the ns to a temporary file, and then use that to serve * the request from. This prevents us from having to worry about stuff * like people breaking out of the container root by symlinks or * ../../../s etc. in the path, since we can just rely on the kernel * for correctness. */ temp, err := ioutil.TempFile("", "lxd_forkgetfile_") if err != nil { return InternalError(err) } defer temp.Close() cmd := exec.Command( os.Args[0], "forkgetfile", temp.Name(), fmt.Sprintf("%d", pid), path, ) if out, err := cmd.CombinedOutput(); err != nil { return InternalError(fmt.Errorf("%s: %s", err.Error(), string(out))) } fi, err := temp.Stat() if err != nil { return SmartError(err) } /* * Unfortunately, there's no portable way to do this: * https://groups.google.com/forum/#!topic/golang-nuts/tGYjYyrwsGM * https://groups.google.com/forum/#!topic/golang-nuts/ywS7xQYJkHY */ sb := fi.Sys().(*syscall.Stat_t) headers := map[string]string{ "X-LXD-uid": strconv.FormatUint(uint64(sb.Uid), 10), "X-LXD-gid": strconv.FormatUint(uint64(sb.Gid), 10), "X-LXD-mode": fmt.Sprintf("%04o", fi.Mode()&os.ModePerm), } files := make([]fileResponseEntry, 1) files[0].identifier = filepath.Base(path) files[0].path = temp.Name() files[0].filename = filepath.Base(path) return FileResponse(r, files, headers, true) } func containerFilePut(pid int, r *http.Request, p string, idmapset *shared.IdmapSet) Response { uid, gid, mode := shared.ParseLXDFileHeaders(r.Header) uid, gid = idmapset.ShiftIntoNs(uid, gid) if uid == -1 || gid == -1 { return BadRequest(fmt.Errorf("unmapped uid or gid specified")) } temp, err := ioutil.TempFile("", "lxd_forkputfile_") if err != nil { return InternalError(err) } defer func() { temp.Close() os.Remove(temp.Name()) }() _, err = io.Copy(temp, r.Body) if err != nil { return InternalError(err) } cmd := exec.Command( os.Args[0], "forkputfile", temp.Name(), fmt.Sprintf("%d", pid), p, fmt.Sprintf("%d", uid), fmt.Sprintf("%d", gid), fmt.Sprintf("%d", mode&os.ModePerm), ) out, err := cmd.CombinedOutput() if err != nil { return InternalError(fmt.Errorf("%s: %s", err.Error(), string(out))) } return EmptySyncResponse }
{ "content_hash": "1af3d28433390a4e8c14aaef86c5ff35", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 95, "avg_line_length": 22.880281690140844, "alnum_prop": 0.6565096952908587, "repo_name": "rcj4747/lxd", "id": "5001dadd8882ad2c7e5faa07c200db8c088bc151", "size": "3249", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lxd/container_file.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "548841" }, { "name": "Makefile", "bytes": "1981" }, { "name": "Protocol Buffer", "bytes": "649" }, { "name": "Python", "bytes": "24296" }, { "name": "Shell", "bytes": "59768" } ], "symlink_target": "" }
/** * Boot up the Vue instance and wire up the router. */ var hn = {} var Vue = require('vue') var Router = require('director').Router hn.app = new Vue(require('./app.vue')) hn.router = new Router() console.log('Initializing HAcker News Web Application....'); Vue.config.debug = false hn.router.on('/', function () { window.scrollTo(0, 0) hn.app.view = 'news-view' hn.app.params.page = 1 }) hn.router.on('/news', function () { window.scrollTo(0, 0) hn.app.view = 'news-view' hn.app.params.page = 1 }) hn.router.on('/news/:page', function (page) { window.scrollTo(0, 0) hn.app.view = 'news-view' hn.app.params.page = +page }) hn.router.on('/user/:id', function (id) { window.scrollTo(0, 0) hn.app.view = 'user-view' hn.app.params.userId = id }) hn.router.on('/item/:id', function (id) { window.scrollTo(0, 0) hn.app.view = 'item-view' hn.app.params.itemId = id }) hn.router.configure({ html5history: true, notfound: function () { hn.router.setRoute('/news/1') } }) hn.router.init() window.hn = hn
{ "content_hash": "0191fbc6d9531fbaf2f146eba9cf939f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 60, "avg_line_length": 19.754716981132077, "alnum_prop": 0.6332378223495702, "repo_name": "denismars/hackernews", "id": "2a9b368176ed24862e2559236c602b2ed2044ddd", "size": "1047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clients/web/main.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "903" }, { "name": "JavaScript", "bytes": "556858" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WCFHost")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WCFHost")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("65184859-0189-4969-8280-0383cddb82fe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "f22071d838640eb2611b2fd89a2f87e5", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.52777777777778, "alnum_prop": 0.7433309300648883, "repo_name": "rohansen/Code-Examples", "id": "8b18a70c0cd9801c752b63c3d437471b63cac4f5", "size": "1390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Public Web Services/MultipleServicesOnSamePort/WCFHost/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "1230" }, { "name": "C#", "bytes": "1452823" }, { "name": "CSS", "bytes": "11785" }, { "name": "HTML", "bytes": "62571" }, { "name": "JavaScript", "bytes": "108868" } ], "symlink_target": "" }
from django.core.exceptions import ImproperlyConfigured from django.db import models from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from feincms_simplegallery.util.mixins import OrderableMixin try: from feincms.admin.item_editor import FeinCMSInline except ImportError: # pragma: no cover, FeinCMS not available. # Does not do anything sane, but does not hurt either from django.contrib.admin import StackedInline as FeinCMSInline class BaseContainer(OrderableMixin): """ Container of Elements to be rendered. Do not instance this! Instance subclasses instead! """ title = models.CharField(_('Title'), max_length=300) def __str__(self): return self.title class Meta: abstract = True ordering = ['_order', 'title'] verbose_name = _('Base Container') verbose_name_plural = _('Base Containers') def render(self, **kwargs): # return return render_to_string( # 'content/containers/%s/container.html' % self.type, 'content/simplegallery/gallery/default/container.html', { 'elements': self.container_elements.all(), 'container_title': self.title, 'container_id': id(self) }, context_instance=kwargs.get('context')) class BaseElement(OrderableMixin, models.Model): """ Base Element to be rendered. Do not instance this! Instance subclasses instead! """ title = models.CharField( _('Title'), max_length=100, blank=True, null=True ) subtitle = models.CharField( _('Subtitle'), max_length=200, blank=True, null=True ) description = models.TextField( _('Description'), blank=True, null=True ) url = models.CharField( _('URL'), max_length=2048, blank=True, null=True ) class Meta: abstract = True ordering = ['_order', 'title'] verbose_name = _('Base Element') verbose_name_plural = _('Base Elements') def __str__(self): return self.title def render(self, **kwargs): return render_to_string( 'content/containers/%s/elem.html' % self.__class__.__name__.lower(), { 'elem': self, 'elem_id': id(self) }, context_instance=kwargs.get('context')) class BaseContentInline(FeinCMSInline): raw_id_fields = ('container',) class BaseContent(models.Model): feincms_item_editor_inline = BaseContentInline container_type = 'base' class Meta: abstract = True verbose_name = _('Base Content') verbose_name_plural = _('Base Content') def __str__(self): return _('Base Content') + "#{}".format(self.pk) @classmethod def initialize_type(cls, TYPE_CHOICES=None, cleanse=None): if cls == BaseContent: raise ImproperlyConfigured( 'You cannot instance BaseContent class.' 'Instance its subclasses instead' ) if TYPE_CHOICES is None: raise ImproperlyConfigured( 'You need to set TYPE_CHOICES when creating a' ' %s' % cls.__name__ ) cls.add_to_class( 'type', models.CharField( _('type'), max_length=20, choices=TYPE_CHOICES, default=TYPE_CHOICES[0][0] ) ) if cleanse: cls.cleanse = cleanse def render(self, **kwargs): # return template_dir = 'content/simplegallery/%s/%s/' % ( self.container_type, self.type, ) template_container = template_dir + 'container.html' template_element = template_dir + 'element.html' return render_to_string( template_container, { 'elements': self.container.container_elements.all(), 'container': self, 'container_title': self.container.title, 'container_id': id(self), 'template_dir': template_dir, 'template_element': template_element, }, context_instance=kwargs.get('context'))
{ "content_hash": "68ea60a9c51772158e661525ccedbed1", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 69, "avg_line_length": 28.305732484076433, "alnum_prop": 0.5562556255625563, "repo_name": "paramono/feincms_simplegallery", "id": "247820a60c88b56208515dbbc8c5f965b9f3962a", "size": "4444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "feincms_simplegallery/util/base.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "5512" }, { "name": "Python", "bytes": "17821" } ], "symlink_target": "" }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Monitoring.Performance.Windows { using System; using Util; public class MessagePerformanceCounter<TMessage> : IDisposable, IMessagePerformanceCounter { readonly IPerformanceCounter _consumedPerSecond; readonly IPerformanceCounter _consumeDuration; readonly IPerformanceCounter _consumeDurationBase; readonly IPerformanceCounter _faulted; readonly IPerformanceCounter _faultPercentage; readonly IPerformanceCounter _faultPercentageBase; readonly IPerformanceCounter _totalConsumed; readonly IPerformanceCounter _publishedPerSecond; readonly IPerformanceCounter _publishFaulted; readonly IPerformanceCounter _publishFaultPercentage; readonly IPerformanceCounter _publishFaultPercentageBase; readonly IPerformanceCounter _sendFaulted; readonly IPerformanceCounter _sendFaultPercentage; readonly IPerformanceCounter _sendFaultPercentageBase; readonly IPerformanceCounter _sentPerSecond; readonly IPerformanceCounter _totalPublished; readonly IPerformanceCounter _totalSent; public MessagePerformanceCounter(ICounterFactory factory) { string messageType = TypeMetadataCache<TMessage>.ShortName; if (messageType.Length > 127) messageType = messageType.Substring(messageType.Length - 127); _totalConsumed = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.TotalReceived.CounterName, messageType); _consumedPerSecond = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumedPerSecond.CounterName, messageType); _consumeDuration = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumeDuration.CounterName, messageType); _consumeDurationBase = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumeDurationBase.CounterName, messageType); _faulted = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumeFaulted.CounterName, messageType); _faultPercentage = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumeFaultPercentage.CounterName, messageType); _faultPercentageBase = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.ConsumeFaultPercentageBase.CounterName, messageType); _totalSent = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.TotalSent.CounterName, messageType); _sentPerSecond = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.SentPerSecond.CounterName, messageType); _sendFaulted = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.SendFaulted.CounterName, messageType); _sendFaultPercentage = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.SendFaultPercentage.CounterName, messageType); _sendFaultPercentageBase = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.SendFaultPercentageBase.CounterName, messageType); _totalPublished = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.TotalPublished.CounterName, messageType); _publishedPerSecond = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.PublishedPerSecond.CounterName, messageType); _publishFaulted = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.PublishFaulted.CounterName, messageType); _publishFaultPercentage = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.PublishFaultPercentage.CounterName, messageType); _publishFaultPercentageBase = factory.Create(BuiltInCounters.Messages.Category, MessagePerformanceCounters.PublishFaultPercentageBase.CounterName, messageType); } public void Dispose() { _consumeDuration.Dispose(); _consumeDurationBase.Dispose(); _consumedPerSecond.Dispose(); _faultPercentage.Dispose(); _faultPercentageBase.Dispose(); _faulted.Dispose(); _totalConsumed.Dispose(); _totalSent.Dispose(); _sentPerSecond.Dispose(); _sendFaulted.Dispose(); _sendFaultPercentage.Dispose(); _sendFaultPercentageBase.Dispose(); _totalPublished.Dispose(); _publishedPerSecond.Dispose(); _publishFaulted.Dispose(); _publishFaultPercentage.Dispose(); _publishFaultPercentageBase.Dispose(); } public void Consumed(TimeSpan duration) { _totalConsumed.Increment(); _consumedPerSecond.Increment(); _consumeDuration.IncrementBy((long)duration.TotalMilliseconds); _consumeDurationBase.Increment(); _faultPercentageBase.Increment(); } public void ConsumeFaulted(TimeSpan duration) { _totalConsumed.Increment(); _consumedPerSecond.Increment(); _faulted.Increment(); _faultPercentage.Increment(); _faultPercentageBase.Increment(); } public void Sent() { _totalSent.Increment(); _sentPerSecond.Increment(); _sendFaultPercentageBase.Increment(); } public void Published() { _totalPublished.Increment(); _publishedPerSecond.Increment(); _publishFaultPercentageBase.Increment(); } public void PublishFaulted() { _totalPublished.Increment(); _publishedPerSecond.Increment(); _publishFaulted.Increment(); _publishFaultPercentage.Increment(); _publishFaultPercentageBase.Increment(); } public void SendFaulted() { _totalSent.Increment(); _sentPerSecond.Increment(); _sendFaulted.Increment(); _sendFaultPercentage.Increment(); _sendFaultPercentageBase.Increment(); } } }
{ "content_hash": "245064c5480ec6d797eac4aaed877f36", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 96, "avg_line_length": 45.3109756097561, "alnum_prop": 0.6616875252321357, "repo_name": "SanSYS/MassTransit", "id": "3649e2f63ae0b3c00ccb76e60251a36f04cd2e44", "size": "7433", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/MassTransit/Monitoring/Performance/Windows/MessagePerformanceCounter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2121" }, { "name": "C#", "bytes": "3494751" }, { "name": "PowerShell", "bytes": "1631" }, { "name": "Ruby", "bytes": "43324" } ], "symlink_target": "" }
from __future__ import unicode_literals import re from collections import namedtuple from six import string_types from prompt_toolkit.document import Document from prompt_toolkit.filters import to_filter from .base import Completer, Completion from .word_completer import WordCompleter __all__ = [ 'FuzzyCompleter', 'FuzzyWordCompleter', ] class FuzzyCompleter(Completer): """ Fuzzy completion. This wraps any other completer and turns it into a fuzzy completer. If the list of words is: ["leopard" , "gorilla", "dinosaur", "cat", "bee"] Then trying to complete "oar" would yield "leopard" and "dinosaur", but not the others, because they match the regular expression 'o.*a.*r'. Similar, in another application "djm" could expand to "django_migrations". The results are sorted by relevance, which is defined as the start position and the length of the match. Notice that this is not really a tool to work around spelling mistakes, like what would be possible with difflib. The purpose is rather to have a quicker or more intuitive way to filter the given completions, especially when many completions have a common prefix. Fuzzy algorithm is based on this post: https://blog.amjith.com/fuzzyfinder-in-10-lines-of-python :param completer: A :class:`~.Completer` instance. :param WORD: When True, use WORD characters. :param pattern: Regex pattern which selects the characters before the cursor that are considered for the fuzzy matching. :param enable_fuzzy: (bool or `Filter`) Enabled the fuzzy behavior. For easily turning fuzzyness on or off according to a certain condition. """ def __init__(self, completer, WORD=False, pattern=None, enable_fuzzy=True): assert isinstance(completer, Completer) assert pattern is None or pattern.startswith('^') self.completer = completer self.pattern = pattern self.WORD = WORD self.pattern = pattern self.enable_fuzzy = to_filter(enable_fuzzy) def get_completions(self, document, complete_event): if self.enable_fuzzy(): return self._get_fuzzy_completions(document, complete_event) else: return self.completer.get_completions(document, complete_event) def _get_pattern(self): if self.pattern: return self.pattern if self.WORD: return r'[^\s]+' return '^[a-zA-Z0-9_]*' def _get_fuzzy_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor( pattern=re.compile(self._get_pattern())) # Get completions document2 = Document( text=document.text[:document.cursor_position - len(word_before_cursor)], cursor_position=document.cursor_position - len(word_before_cursor)) completions = list(self.completer.get_completions(document2, complete_event)) fuzzy_matches = [] pat = '.*?'.join(map(re.escape, word_before_cursor)) pat = '(?=({0}))'.format(pat) # lookahead regex to manage overlapping matches regex = re.compile(pat, re.IGNORECASE) for compl in completions: matches = list(regex.finditer(compl.text)) if matches: # Prefer the match, closest to the left, then shortest. best = min(matches, key=lambda m: (m.start(), len(m.group(1)))) fuzzy_matches.append(_FuzzyMatch(len(best.group(1)), best.start(), compl)) def sort_key(fuzzy_match): " Sort by start position, then by the length of the match. " return fuzzy_match.start_pos, fuzzy_match.match_length fuzzy_matches = sorted(fuzzy_matches, key=sort_key) for match in fuzzy_matches: # Include these completions, but set the correct `display` # attribute and `start_position`. yield Completion( match.completion.text, start_position=match.completion.start_position - len(word_before_cursor), display_meta=match.completion.display_meta, display=self._get_display(match, word_before_cursor), style=match.completion.style) def _get_display(self, fuzzy_match, word_before_cursor): """ Generate formatted text for the display label. """ m = fuzzy_match word = m.completion.text if m.match_length == 0: # No highlighting when we have zero length matches (no input text). return word result = [] # Text before match. result.append(('class:fuzzymatch.outside', word[:m.start_pos])) # The match itself. characters = list(word_before_cursor) for c in word[m.start_pos:m.start_pos + m.match_length]: classname = 'class:fuzzymatch.inside' if characters and c.lower() == characters[0].lower(): classname += '.character' del characters[0] result.append((classname, c)) # Text after match. result.append( ('class:fuzzymatch.outside', word[m.start_pos + m.match_length:])) return result class FuzzyWordCompleter(Completer): """ Fuzzy completion on a list of words. (This is basically a `WordCompleter` wrapped in a `FuzzyCompleter`.) :param words: List of words or callable that returns a list of words. :param meta_dict: Optional dict mapping words to their meta-information. :param WORD: When True, use WORD characters. """ def __init__(self, words, meta_dict=None, WORD=False): assert callable(words) or all(isinstance(w, string_types) for w in words) self.words = words self.meta_dict = meta_dict or {} self.WORD = WORD self.word_completer = WordCompleter( words=lambda: self.words, WORD=self.WORD) self.fuzzy_completer = FuzzyCompleter( self.word_completer, WORD=self.WORD) def get_completions(self, document, complete_event): return self.fuzzy_completer.get_completions(document, complete_event) _FuzzyMatch = namedtuple('_FuzzyMatch', 'match_length start_pos completion')
{ "content_hash": "e679741a6612d58467c73e6d1fc51ba5", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 90, "avg_line_length": 36.87134502923977, "alnum_prop": 0.6413957176843775, "repo_name": "lmregus/Portfolio", "id": "83e602495a3ca41e62808b1b04390d59bdc5aa99", "size": "6305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/design_patterns/env/lib/python3.7/site-packages/prompt_toolkit/completion/fuzzy_completer.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "27682" }, { "name": "C++", "bytes": "25458" }, { "name": "CSS", "bytes": "12842" }, { "name": "HTML", "bytes": "49171" }, { "name": "Java", "bytes": "99711" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Python", "bytes": "42857" }, { "name": "Shell", "bytes": "5710" } ], "symlink_target": "" }
/* Use to fix hidden section headers behind the navbar when using links with targets See: http://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header */ $jqTheme(document).ready(function() { $jqTheme('a[href*=#]:not([href=#])').on('click', function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $jqTheme(this.hash); target = target.length ? target : $('a.headerlink[href="#' + this.hash.slice(1) +'""]'); if (target.length) { $jqTheme('html,body').animate({ scrollTop: target.offset().top - 60 //offsets for fixed header }, 1000); return false; } } }); //Executed on page load with URL containing an anchor tag. if($jqTheme(location.href.split("#")[1])) { var target = $('#'+location.href.split("#")[1]); if (target.length) { $jqTheme('html,body').animate({ scrollTop: target.offset().top - 60 //offset height of header here too. }, 1000); return false; } } });
{ "content_hash": "9884e5d7f40cc6974bf18d4ea4124b20", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 109, "avg_line_length": 38.96551724137931, "alnum_prop": 0.588495575221239, "repo_name": "ekoi/DANS-DVN-4.6.1", "id": "fac5d6056f2aa4bb50ebb7a2b11c815968286905", "size": "1130", "binary": false, "copies": "9", "ref": "refs/heads/v4.6.1-merge", "path": "doc/sphinx-guides/source/_static/navbarscroll.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54459" }, { "name": "HTML", "bytes": "1082716" }, { "name": "Java", "bytes": "6003734" }, { "name": "JavaScript", "bytes": "395698" }, { "name": "Makefile", "bytes": "3660" }, { "name": "Perl", "bytes": "65916" }, { "name": "Python", "bytes": "61153" }, { "name": "R", "bytes": "38228" }, { "name": "Ruby", "bytes": "1670" }, { "name": "Shell", "bytes": "108312" }, { "name": "XSLT", "bytes": "455" } ], "symlink_target": "" }
QUnit.module('Db'); QUnit.test("DB.collection() :: Create Collection", function() { base.dbUp(); user = db.collection('user'); organisation = db.collection('organisation'); ok(user !== undefined, "Complete"); base.dbDown(); }); QUnit.test("DB.collection() :: Check that passing a collection to get a collection returns the same collection", function() { base.dbUp(); var coll = db.collection('moo'); var coll2 = db.collection(coll); strictEqual(coll, coll2, "Collections are the same"); base.dbDown(); }); QUnit.test("Drop DB", function() { base.dbUp(); var coll = db.collection('test'); coll.insert({moo: true}); strictEqual(coll.find().length, 1, 'Check collection has been set up correctly'); db.drop(); var coll = db.collection('test'); strictEqual(coll.find().length, 0, 'Check db had dropped collections'); base.dbDown(); }); QUnit.test("DB.peek() :: Search all database collections for string", function() { base.dbUp(); base.dataUp(); var result = db.peek('an'); strictEqual(result.length, 16, "Got correct number of results"); strictEqual(result[0]._id, '2', "Got expected result id"); strictEqual(result[1]._id, '4', "Got expected result id"); strictEqual(result[2]._id, '5', "Got expected result id"); base.dbDown(); }); QUnit.test("DB.peekCat() :: Search all database collections for string", function() { base.dbUp(); base.dataUp(); var result = db.peekCat('an'); strictEqual(result.organisation && result.organisation.length, 13, "Got correct number of organisation results"); strictEqual(result.user && result.user.length, 3, "Got correct number of user results"); base.dbDown(); });
{ "content_hash": "30471b5a25a84624440543baf924d89b", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 125, "avg_line_length": 26.19047619047619, "alnum_prop": 0.683030303030303, "repo_name": "anywhichway/frx-example", "id": "17901fa37d89f6819096ff8907e8ca2439a7c5f7", "size": "1650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/forerunnerdb/js/unitTests/tests/testsDb.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "163247" }, { "name": "HTML", "bytes": "5780" }, { "name": "JavaScript", "bytes": "48563" } ], "symlink_target": "" }
const authenticate = require('./functions/authenticate.js'); const getMetadata = require('./functions/getMetadata.js'); const remoteRenameProject = require('./functions/remoteRenameProject.js'); const error = require('./functions/error.js'); const checkbox = require('./functions/checkbox.js'); const readline = require('readline'); const checkNewVersion = require('./functions/checkNewVersion.js'); /** * Rename a remote Google Apps Script project * * @param {String} identifier - Id of the remote project to rename. * @param {String} newProjectName - new name of the project. * @returns {void} */ module.exports = async (identifier, newProjectName) => { let auth; try { const checkedVersion = await checkNewVersion(); process.stdout.write(`Renaming remote '${identifier}' to '${newProjectName}' ...`); auth = await authenticate([]); const metadata = await getMetadata(auth, identifier); readline.clearLine(process.stdout); readline.cursorTo(process.stdout, 0); process.stdout.write(`Renaming remote '${metadata.name}' to '${newProjectName}' ...`); const renamed = await remoteRenameProject(auth, metadata.projectId, metadata.name, newProjectName); if (renamed) { checkbox.display('green'); } else { checkbox.display('yellow'); process.stdout.write('Skipped renaming because old and new name appear to be the same\n'); } process.exit(0); } catch (err) { checkbox.display('red'); await error.log(err, auth); process.exit(1); } };
{ "content_hash": "6f49ba6b683bd66621238910cc075675", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 107, "avg_line_length": 39.292682926829265, "alnum_prop": 0.6561142147734327, "repo_name": "MaartenDesnouck/google-apps-script", "id": "f00d2f4110d284d32053dff0c683738338de54c4", "size": "1611", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rename-project.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "134670" }, { "name": "Shell", "bytes": "23266" } ], "symlink_target": "" }
#ifndef __DISJOINTSETS_H__ #define __DISJOINTSETS_H__ class Roadmap; class RoadmapNode; struct DisjointSetsNode { friend class DisjointSets; friend class RoadmapNode; private: DisjointSetsNode(): disjointSetsParent(this), disjointSetsRank(0) { } DisjointSetsNode* disjointSetsParent; int disjointSetsRank; }; class DisjointSets { friend class Roadmap; private: DisjointSets(): m_setCount(0) { } int getSetCount() const { return m_setCount; } void makeSet(DisjointSetsNode& element) { element.disjointSetsParent = &element; element.disjointSetsRank = 0; ++m_setCount; } void uniteSets(DisjointSetsNode& element1, DisjointSetsNode& element2) { DisjointSetsNode* set1 = findSet(&element1); DisjointSetsNode* set2 = findSet(&element2); if (set1 != set2) { if (set1->disjointSetsRank > set2->disjointSetsRank) { set2->disjointSetsParent = set1; } else { set1->disjointSetsParent = set2; if (set1->disjointSetsRank == set2->disjointSetsRank) { ++set2->disjointSetsRank; } } --m_setCount; } } bool sameComponent(DisjointSetsNode& element1, DisjointSetsNode& element2) { return findSet(&element1) == findSet(&element2); } DisjointSetsNode* findSet(DisjointSetsNode* element) { if (element != element->disjointSetsParent) { element->disjointSetsParent = findSet(element->disjointSetsParent); } return element->disjointSetsParent; } int m_setCount; }; #endif
{ "content_hash": "6c2a4515aa95353a274c4bb2895f4ba5", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 79, "avg_line_length": 19.903225806451612, "alnum_prop": 0.5623987034035657, "repo_name": "qroph/motion-solver", "id": "398c8ad3d11260bb1b611d7c0d2bfb920cbe6a85", "size": "2913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DisjointSets.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "49770" }, { "name": "C++", "bytes": "149906" }, { "name": "CSS", "bytes": "885" }, { "name": "IDL", "bytes": "616" } ], "symlink_target": "" }
<?php require("crud.php"); delete(array('username'=>$_POST['username']));
{ "content_hash": "28a78ccc8ca1e7fb46c0eadaa4d48199", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 46, "avg_line_length": 18.5, "alnum_prop": 0.6486486486486487, "repo_name": "dnaextrim/ajax-crud-bootstrap", "id": "289584c2896a1f2b2988a515e0a6328380a0d1e0", "size": "74", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "delete.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90790" }, { "name": "JavaScript", "bytes": "192564" }, { "name": "PHP", "bytes": "98266" } ], "symlink_target": "" }
CU_ErrorCode add_test_cut_rod(); #endif
{ "content_hash": "9b7430db96dc7c49eb7524cf8289a2b7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 32, "avg_line_length": 13.666666666666666, "alnum_prop": 0.7073170731707317, "repo_name": "jungor/algorithms", "id": "3a6d3af1e4840b18959333c4c6a49968a2325b8a", "size": "110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chap15/test_cut_rod.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "41275" }, { "name": "C++", "bytes": "265" }, { "name": "CMake", "bytes": "827" } ], "symlink_target": "" }
AFSpritz ======================= A complete Spritz SDK for iOS ![alt text](https://raw.github.com/AlvaroFranco/AFSpritz/master/example.gif "Example") ##CocoaPods AFSpritz is on [CocoaPods](http://cocoapods.org), so you can get the pod by adding this line to your Podfile pod 'AFSpritz', '~> 1.3' If not, just import these files to your project: AFSpritzManager.h AFSpritzManager.m AFSpritzWords.h AFSpritzWords.m AFSpritzLabel.h AFSpritzLabel.m NSTimer+Blocks.h NSTimer+Blocks.m NSTimer+Control.h NSTimer+Control.m ##Usage First of all, import AFSpritzManager.h to your class #import "AFSpritzManager.h" Initialise ```AFSpritzManager``` assigning a text and a number of words per minute, that will determine the speed of the reading. Theorically, there's no limit, but the more confortable speed is 200-250 words per minute. However, Spritz is made for let you read more than 500 words per minute. AFSpritzManager *manager = [[AFSpritzManager alloc]initWithText:@"Welcome to AFSpritz! Spritz is a brand new revolutionary reading method that will help you to improve your number of words per minute. Take a look at AFSpritz!" andWordsPerMinute:250]; Then, call the block that will update the Spritz label [manager updateLabelWithNewWordAndCompletion:^(AFSpritzWords *word, BOOL finished) { if (!finished) { //Update the AFSpritzLabel } else { NSLog(@"Finished!"); } }]; ###Checking the status typedef NS_ENUM(int, AFSpritzStatus) { AFSpritzStatusStopped, AFSpritzStatusReading, AFSpritzStatusNotStarted, AFSpritzStatusFinished }; AFSpritz has the feature of checking in each moment the status of the reading using ```-status:```. Example: if ([manager status:AFSpritzStatusReading]) { // The current status is reading } else if ([manager status:AFSpritzStatusNotStarted]) { // The current status is not started yet } else if ([manager AFSpritzStatusStopped]) { // The current status is stopped, so it can be resumed } else if ([manager AFSpritzStatusFinished]) { // The current status is finished } ###Pausing and resuming Now you can pause and resume your reading just calling these two methods: [manager pauseReading]; [manager resumeReading]; ##AFSpritzLabel API AFSpritzLabel is an incredible, well crafted and 100% AFSpritzWords-compatible UIView subclass that will let you show your Spritz reading. You can customize many properties from AFSpritzLabel, such as: | Property | Class | Required | Default | Description | |----------|-------|----------|---------|-------------| | word | AFSpritzWords | Yes | nil | Determines the AFSpritzWords-subclassed word to show. | | markerColor | UIColor | No | Red | Determines the color of the letter you're supposed to be focused on. | | markeringLinesColor | UIColor | No | Black | Determines the color of the lines around the word. | | textColor | UIColor | No | Black | Determines the color of the text. | | textFont | UIFont | No | System font with size 20 | Determines the font of the text. | | backgroundColor | UIColor | No | White | Determines the color of the background. | ##Wishlist 1. ~~Customize speed throught the number of words per minute.~~ 2. ~~Stop and resume the reading~~. 3. ~~Add a little stop when there's a stop on the text (. … : , ! ?).~~ 4. Restart the reading. ##Author Made by Alvaro Franco. If you have any question, feel free to drop me a line at [alvarofrancoayala@gmail.com](mailto:alvarofrancoayala@gmail.com)
{ "content_hash": "e4f53c3d36acabd1d1ebf5d72d4c4484", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 293, "avg_line_length": 32.71559633027523, "alnum_prop": 0.7120022434099832, "repo_name": "sumitmundra/AFSpritz", "id": "f1626dd8262eacbe3ba2835619098c500075ecec", "size": "3568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
"""generated automatically by auto_dao.py""" class DBChangeParameter(object): vtType = 'changeParameter' def __init__(self, moduleId=None, alias=None, functionId=None, function=None, parameterId=None, parameter=None, type=None, value=None): self.__db_moduleId = moduleId self.__db_alias = alias self.__db_functionId = functionId self.__db_function = function self.__db_parameterId = parameterId self.__db_parameter = parameter self.__db_type = type self.__db_value = value def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_alias(self): return self.__db_alias def __set_db_alias(self, alias): self.__db_alias = alias db_alias = property(__get_db_alias, __set_db_alias) def db_add_alias(self, alias): self.__db_alias = alias def db_change_alias(self, alias): self.__db_alias = alias def db_delete_alias(self, alias): self.__db_alias = None def __get_db_functionId(self): return self.__db_functionId def __set_db_functionId(self, functionId): self.__db_functionId = functionId db_functionId = property(__get_db_functionId, __set_db_functionId) def db_add_functionId(self, functionId): self.__db_functionId = functionId def db_change_functionId(self, functionId): self.__db_functionId = functionId def db_delete_functionId(self, functionId): self.__db_functionId = None def __get_db_function(self): return self.__db_function def __set_db_function(self, function): self.__db_function = function db_function = property(__get_db_function, __set_db_function) def db_add_function(self, function): self.__db_function = function def db_change_function(self, function): self.__db_function = function def db_delete_function(self, function): self.__db_function = None def __get_db_parameterId(self): return self.__db_parameterId def __set_db_parameterId(self, parameterId): self.__db_parameterId = parameterId db_parameterId = property(__get_db_parameterId, __set_db_parameterId) def db_add_parameterId(self, parameterId): self.__db_parameterId = parameterId def db_change_parameterId(self, parameterId): self.__db_parameterId = parameterId def db_delete_parameterId(self, parameterId): self.__db_parameterId = None def __get_db_parameter(self): return self.__db_parameter def __set_db_parameter(self, parameter): self.__db_parameter = parameter db_parameter = property(__get_db_parameter, __set_db_parameter) def db_add_parameter(self, parameter): self.__db_parameter = parameter def db_change_parameter(self, parameter): self.__db_parameter = parameter def db_delete_parameter(self, parameter): self.__db_parameter = None def __get_db_type(self): return self.__db_type def __set_db_type(self, type): self.__db_type = type db_type = property(__get_db_type, __set_db_type) def db_add_type(self, type): self.__db_type = type def db_change_type(self, type): self.__db_type = type def db_delete_type(self, type): self.__db_type = None def __get_db_value(self): return self.__db_value def __set_db_value(self, value): self.__db_value = value db_value = property(__get_db_value, __set_db_value) def db_add_value(self, value): self.__db_value = value def db_change_value(self, value): self.__db_value = value def db_delete_value(self, value): self.__db_value = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBDeleteFunction(object): vtType = 'deleteFunction' def __init__(self, moduleId=None, functionId=None): self.__db_moduleId = moduleId self.__db_functionId = functionId def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_functionId(self): return self.__db_functionId def __set_db_functionId(self, functionId): self.__db_functionId = functionId db_functionId = property(__get_db_functionId, __set_db_functionId) def db_add_functionId(self, functionId): self.__db_functionId = functionId def db_change_functionId(self, functionId): self.__db_functionId = functionId def db_delete_functionId(self, functionId): self.__db_functionId = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBDeleteConnection(object): vtType = 'deleteConnection' def __init__(self, connectionId=None): self.__db_connectionId = connectionId def __get_db_connectionId(self): return self.__db_connectionId def __set_db_connectionId(self, connectionId): self.__db_connectionId = connectionId db_connectionId = property(__get_db_connectionId, __set_db_connectionId) def db_add_connectionId(self, connectionId): self.__db_connectionId = connectionId def db_change_connectionId(self, connectionId): self.__db_connectionId = connectionId def db_delete_connectionId(self, connectionId): self.__db_connectionId = None def getPrimaryKey(self): return self.__db_connectionId """generated automatically by auto_dao.py""" class DBAddModule(object): vtType = 'addModule' def __init__(self, id=None, cache=None, name=None, x=None, y=None): self.__db_id = id self.__db_cache = cache self.__db_name = name self.__db_x = x self.__db_y = y def __get_db_id(self): return self.__db_id def __set_db_id(self, id): self.__db_id = id db_id = property(__get_db_id, __set_db_id) def db_add_id(self, id): self.__db_id = id def db_change_id(self, id): self.__db_id = id def db_delete_id(self, id): self.__db_id = None def __get_db_cache(self): return self.__db_cache def __set_db_cache(self, cache): self.__db_cache = cache db_cache = property(__get_db_cache, __set_db_cache) def db_add_cache(self, cache): self.__db_cache = cache def db_change_cache(self, cache): self.__db_cache = cache def db_delete_cache(self, cache): self.__db_cache = None def __get_db_name(self): return self.__db_name def __set_db_name(self, name): self.__db_name = name db_name = property(__get_db_name, __set_db_name) def db_add_name(self, name): self.__db_name = name def db_change_name(self, name): self.__db_name = name def db_delete_name(self, name): self.__db_name = None def __get_db_x(self): return self.__db_x def __set_db_x(self, x): self.__db_x = x db_x = property(__get_db_x, __set_db_x) def db_add_x(self, x): self.__db_x = x def db_change_x(self, x): self.__db_x = x def db_delete_x(self, x): self.__db_x = None def __get_db_y(self): return self.__db_y def __set_db_y(self, y): self.__db_y = y db_y = property(__get_db_y, __set_db_y) def db_add_y(self, y): self.__db_y = y def db_change_y(self, y): self.__db_y = y def db_delete_y(self, y): self.__db_y = None def getPrimaryKey(self): return self.__db_id """generated automatically by auto_dao.py""" class DBDeleteAnnotation(object): vtType = 'deleteAnnotation' def __init__(self, moduleId=None, key=None): self.__db_moduleId = moduleId self.__db_key = key def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_key(self): return self.__db_key def __set_db_key(self, key): self.__db_key = key db_key = property(__get_db_key, __set_db_key) def db_add_key(self, key): self.__db_key = key def db_change_key(self, key): self.__db_key = key def db_delete_key(self, key): self.__db_key = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBDeleteModulePort(object): vtType = 'deleteModulePort' def __init__(self, moduleId=None, portType=None, portName=None): self.__db_moduleId = moduleId self.__db_portType = portType self.__db_portName = portName def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_portType(self): return self.__db_portType def __set_db_portType(self, portType): self.__db_portType = portType db_portType = property(__get_db_portType, __set_db_portType) def db_add_portType(self, portType): self.__db_portType = portType def db_change_portType(self, portType): self.__db_portType = portType def db_delete_portType(self, portType): self.__db_portType = None def __get_db_portName(self): return self.__db_portName def __set_db_portName(self, portName): self.__db_portName = portName db_portName = property(__get_db_portName, __set_db_portName) def db_add_portName(self, portName): self.__db_portName = portName def db_change_portName(self, portName): self.__db_portName = portName def db_delete_portName(self, portName): self.__db_portName = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBDeleteModule(object): vtType = 'deleteModule' def __init__(self, moduleId=None): self.__db_moduleId = moduleId def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBTag(object): vtType = 'tag' def __init__(self, time=None, name=None): self.__db_time = time self.__db_name = name def __get_db_time(self): return self.__db_time def __set_db_time(self, time): self.__db_time = time db_time = property(__get_db_time, __set_db_time) def db_add_time(self, time): self.__db_time = time def db_change_time(self, time): self.__db_time = time def db_delete_time(self, time): self.__db_time = None def __get_db_name(self): return self.__db_name def __set_db_name(self, name): self.__db_name = name db_name = property(__get_db_name, __set_db_name) def db_add_name(self, name): self.__db_name = name def db_change_name(self, name): self.__db_name = name def db_delete_name(self, name): self.__db_name = None def getPrimaryKey(self): return self.__db_time """generated automatically by auto_dao.py""" class DBAddModulePort(object): vtType = 'addModulePort' def __init__(self, moduleId=None, portType=None, portName=None, portSpec=None): self.__db_moduleId = moduleId self.__db_portType = portType self.__db_portName = portName self.__db_portSpec = portSpec def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_portType(self): return self.__db_portType def __set_db_portType(self, portType): self.__db_portType = portType db_portType = property(__get_db_portType, __set_db_portType) def db_add_portType(self, portType): self.__db_portType = portType def db_change_portType(self, portType): self.__db_portType = portType def db_delete_portType(self, portType): self.__db_portType = None def __get_db_portName(self): return self.__db_portName def __set_db_portName(self, portName): self.__db_portName = portName db_portName = property(__get_db_portName, __set_db_portName) def db_add_portName(self, portName): self.__db_portName = portName def db_change_portName(self, portName): self.__db_portName = portName def db_delete_portName(self, portName): self.__db_portName = None def __get_db_portSpec(self): return self.__db_portSpec def __set_db_portSpec(self, portSpec): self.__db_portSpec = portSpec db_portSpec = property(__get_db_portSpec, __set_db_portSpec) def db_add_portSpec(self, portSpec): self.__db_portSpec = portSpec def db_change_portSpec(self, portSpec): self.__db_portSpec = portSpec def db_delete_portSpec(self, portSpec): self.__db_portSpec = None def getPrimaryKey(self): return self.__db_moduleId """generated automatically by auto_dao.py""" class DBAction(object): vtType = 'action' def __init__(self, time=None, parent=None, user=None, what=None, date=None, notes=None, datas=None): self.__db_time = time self.__db_parent = parent self.__db_user = user self.__db_what = what self.__db_date = date self.__db_notes = notes if datas is None: self.__db_datas = [] else: self.__db_datas = datas def __get_db_time(self): return self.__db_time def __set_db_time(self, time): self.__db_time = time db_time = property(__get_db_time, __set_db_time) def db_add_time(self, time): self.__db_time = time def db_change_time(self, time): self.__db_time = time def db_delete_time(self, time): self.__db_time = None def __get_db_parent(self): return self.__db_parent def __set_db_parent(self, parent): self.__db_parent = parent db_parent = property(__get_db_parent, __set_db_parent) def db_add_parent(self, parent): self.__db_parent = parent def db_change_parent(self, parent): self.__db_parent = parent def db_delete_parent(self, parent): self.__db_parent = None def __get_db_user(self): return self.__db_user def __set_db_user(self, user): self.__db_user = user db_user = property(__get_db_user, __set_db_user) def db_add_user(self, user): self.__db_user = user def db_change_user(self, user): self.__db_user = user def db_delete_user(self, user): self.__db_user = None def __get_db_what(self): return self.__db_what def __set_db_what(self, what): self.__db_what = what db_what = property(__get_db_what, __set_db_what) def db_add_what(self, what): self.__db_what = what def db_change_what(self, what): self.__db_what = what def db_delete_what(self, what): self.__db_what = None def __get_db_date(self): return self.__db_date def __set_db_date(self, date): self.__db_date = date db_date = property(__get_db_date, __set_db_date) def db_add_date(self, date): self.__db_date = date def db_change_date(self, date): self.__db_date = date def db_delete_date(self, date): self.__db_date = None def __get_db_notes(self): return self.__db_notes def __set_db_notes(self, notes): self.__db_notes = notes db_notes = property(__get_db_notes, __set_db_notes) def db_add_notes(self, notes): self.__db_notes = notes def db_change_notes(self, notes): self.__db_notes = notes def db_delete_notes(self, notes): self.__db_notes = None def __get_db_datas(self): return self.__db_datas def __set_db_datas(self, datas): self.__db_datas = datas db_datas = property(__get_db_datas, __set_db_datas) def db_get_datas(self): return self.__db_datas def db_add_data(self, data): self.__db_datas.append(data) def db_change_data(self, data): found = False for i in xrange(len(self.__db_datas)): if self.__db_datas[i].db_id == data.db_id: self.__db_datas[i] = data found = True break if not found: self.__db_datas.append(data) def db_delete_data(self, data): for i in xrange(len(self.__db_datas)): if self.__db_datas[i].db_id == data.db_id: del self.__db_datas[i] break def db_get_data(self, key): for i in xrange(len(self.__db_datas)): if self.__db_datas[i].db_id == data.db_id: return self.__db_datas[i] return None def getPrimaryKey(self): return self.__db_time """generated automatically by auto_dao.py""" class DBAddConnection(object): vtType = 'addConnection' def __init__(self, id=None, destinationId=None, destinationModule=None, destinationPort=None, sourceId=None, sourceModule=None, sourcePort=None): self.__db_id = id self.__db_destinationId = destinationId self.__db_destinationModule = destinationModule self.__db_destinationPort = destinationPort self.__db_sourceId = sourceId self.__db_sourceModule = sourceModule self.__db_sourcePort = sourcePort def __get_db_id(self): return self.__db_id def __set_db_id(self, id): self.__db_id = id db_id = property(__get_db_id, __set_db_id) def db_add_id(self, id): self.__db_id = id def db_change_id(self, id): self.__db_id = id def db_delete_id(self, id): self.__db_id = None def __get_db_destinationId(self): return self.__db_destinationId def __set_db_destinationId(self, destinationId): self.__db_destinationId = destinationId db_destinationId = property(__get_db_destinationId, __set_db_destinationId) def db_add_destinationId(self, destinationId): self.__db_destinationId = destinationId def db_change_destinationId(self, destinationId): self.__db_destinationId = destinationId def db_delete_destinationId(self, destinationId): self.__db_destinationId = None def __get_db_destinationModule(self): return self.__db_destinationModule def __set_db_destinationModule(self, destinationModule): self.__db_destinationModule = destinationModule db_destinationModule = property(__get_db_destinationModule, __set_db_destinationModule) def db_add_destinationModule(self, destinationModule): self.__db_destinationModule = destinationModule def db_change_destinationModule(self, destinationModule): self.__db_destinationModule = destinationModule def db_delete_destinationModule(self, destinationModule): self.__db_destinationModule = None def __get_db_destinationPort(self): return self.__db_destinationPort def __set_db_destinationPort(self, destinationPort): self.__db_destinationPort = destinationPort db_destinationPort = property(__get_db_destinationPort, __set_db_destinationPort) def db_add_destinationPort(self, destinationPort): self.__db_destinationPort = destinationPort def db_change_destinationPort(self, destinationPort): self.__db_destinationPort = destinationPort def db_delete_destinationPort(self, destinationPort): self.__db_destinationPort = None def __get_db_sourceId(self): return self.__db_sourceId def __set_db_sourceId(self, sourceId): self.__db_sourceId = sourceId db_sourceId = property(__get_db_sourceId, __set_db_sourceId) def db_add_sourceId(self, sourceId): self.__db_sourceId = sourceId def db_change_sourceId(self, sourceId): self.__db_sourceId = sourceId def db_delete_sourceId(self, sourceId): self.__db_sourceId = None def __get_db_sourceModule(self): return self.__db_sourceModule def __set_db_sourceModule(self, sourceModule): self.__db_sourceModule = sourceModule db_sourceModule = property(__get_db_sourceModule, __set_db_sourceModule) def db_add_sourceModule(self, sourceModule): self.__db_sourceModule = sourceModule def db_change_sourceModule(self, sourceModule): self.__db_sourceModule = sourceModule def db_delete_sourceModule(self, sourceModule): self.__db_sourceModule = None def __get_db_sourcePort(self): return self.__db_sourcePort def __set_db_sourcePort(self, sourcePort): self.__db_sourcePort = sourcePort db_sourcePort = property(__get_db_sourcePort, __set_db_sourcePort) def db_add_sourcePort(self, sourcePort): self.__db_sourcePort = sourcePort def db_change_sourcePort(self, sourcePort): self.__db_sourcePort = sourcePort def db_delete_sourcePort(self, sourcePort): self.__db_sourcePort = None def getPrimaryKey(self): return self.__db_id """generated automatically by auto_dao.py""" class DBMoveModule(object): vtType = 'moveModule' def __init__(self, id=None, dx=None, dy=None): self.__db_id = id self.__db_dx = dx self.__db_dy = dy def __get_db_id(self): return self.__db_id def __set_db_id(self, id): self.__db_id = id db_id = property(__get_db_id, __set_db_id) def db_add_id(self, id): self.__db_id = id def db_change_id(self, id): self.__db_id = id def db_delete_id(self, id): self.__db_id = None def __get_db_dx(self): return self.__db_dx def __set_db_dx(self, dx): self.__db_dx = dx db_dx = property(__get_db_dx, __set_db_dx) def db_add_dx(self, dx): self.__db_dx = dx def db_change_dx(self, dx): self.__db_dx = dx def db_delete_dx(self, dx): self.__db_dx = None def __get_db_dy(self): return self.__db_dy def __set_db_dy(self, dy): self.__db_dy = dy db_dy = property(__get_db_dy, __set_db_dy) def db_add_dy(self, dy): self.__db_dy = dy def db_change_dy(self, dy): self.__db_dy = dy def db_delete_dy(self, dy): self.__db_dy = None def getPrimaryKey(self): return self.__db_id """generated automatically by auto_dao.py""" class DBVistrail(object): vtType = 'vistrail' def __init__(self, version=None, actions=None, tags=None): self.__db_version = version if actions is None: self.__db_actions = {} else: self.__db_actions = actions if tags is None: self.__db_tags = {} else: self.__db_tags = tags def __get_db_version(self): return self.__db_version def __set_db_version(self, version): self.__db_version = version db_version = property(__get_db_version, __set_db_version) def db_add_version(self, version): self.__db_version = version def db_change_version(self, version): self.__db_version = version def db_delete_version(self, version): self.__db_version = None def __get_db_actions(self): return self.__db_actions def __set_db_actions(self, actions): self.__db_actions = actions db_actions = property(__get_db_actions, __set_db_actions) def db_get_actions(self): return self.__db_actions.values() def db_add_action(self, action): self.__db_actions[action.db_time] = action def db_change_action(self, action): self.__db_actions[action.db_time] = action def db_delete_action(self, action): del self.__db_actions[action.db_time] def db_get_action(self, key): if self.__db_actions.has_key(key): return self.__db_actions[key] return None def __get_db_tags(self): return self.__db_tags def __set_db_tags(self, tags): self.__db_tags = tags db_tags = property(__get_db_tags, __set_db_tags) def db_get_tags(self): return self.__db_tags.values() def db_add_tag(self, tag): self.__db_tags[tag.db_time] = tag def db_change_tag(self, tag): self.__db_tags[tag.db_time] = tag def db_delete_tag(self, tag): del self.__db_tags[tag.db_time] def db_get_tag(self, key): if self.__db_tags.has_key(key): return self.__db_tags[key] return None def getPrimaryKey(self): return self.__db_version """generated automatically by auto_dao.py""" class DBChangeAnnotation(object): vtType = 'changeAnnotation' def __init__(self, moduleId=None, key=None, value=None): self.__db_moduleId = moduleId self.__db_key = key self.__db_value = value def __get_db_moduleId(self): return self.__db_moduleId def __set_db_moduleId(self, moduleId): self.__db_moduleId = moduleId db_moduleId = property(__get_db_moduleId, __set_db_moduleId) def db_add_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_change_moduleId(self, moduleId): self.__db_moduleId = moduleId def db_delete_moduleId(self, moduleId): self.__db_moduleId = None def __get_db_key(self): return self.__db_key def __set_db_key(self, key): self.__db_key = key db_key = property(__get_db_key, __set_db_key) def db_add_key(self, key): self.__db_key = key def db_change_key(self, key): self.__db_key = key def db_delete_key(self, key): self.__db_key = None def __get_db_value(self): return self.__db_value def __set_db_value(self, value): self.__db_value = value db_value = property(__get_db_value, __set_db_value) def db_add_value(self, value): self.__db_value = value def db_change_value(self, value): self.__db_value = value def db_delete_value(self, value): self.__db_value = None def getPrimaryKey(self): return self.__db_moduleId
{ "content_hash": "0cde2962949e864950b0475889e6869f", "timestamp": "", "source": "github", "line_count": 841, "max_line_length": 149, "avg_line_length": 33.72294887039239, "alnum_prop": 0.6011071541906139, "repo_name": "CMUSV-VisTrails/WorkflowRecommendation", "id": "ccc0198c70be9785335dd0c00a4860486a3e3b1a", "size": "30204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vistrails/db/versions/v0_3_0/domain/auto_gen.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "57" }, { "name": "PHP", "bytes": "48730" }, { "name": "Python", "bytes": "12760768" }, { "name": "Shell", "bytes": "33785" }, { "name": "XSLT", "bytes": "1090" } ], "symlink_target": "" }
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef _FX_FONT_H_ #define _FX_FONT_H_ #ifndef _FXCRT_EXTENSION_ #include "../../include/fxcrt/fx_ext.h" #endif #ifndef _FX_DIB_H_ #include "fx_dib.h" #endif typedef struct FT_FaceRec_* FXFT_Face; typedef void* FXFT_Library; class IFX_FontEncoding; class CFX_PathData; class CFX_SubstFont; class CFX_FaceCache; class IFX_FontMapper; class CFX_FontMapper; class IFX_SystemFontInfo; class CFontFileFaceInfo; #define FXFONT_FIXED_PITCH 0x01 #define FXFONT_SERIF 0x02 #define FXFONT_SYMBOLIC 0x04 #define FXFONT_SCRIPT 0x08 #define FXFONT_ITALIC 0x40 #define FXFONT_BOLD 0x40000 #define FXFONT_USEEXTERNATTR 0x80000 #define FXFONT_CIDFONT 0x100000 #define FXFONT_ANSI_CHARSET 0 #define FXFONT_DEFAULT_CHARSET 1 #define FXFONT_SYMBOL_CHARSET 2 #define FXFONT_SHIFTJIS_CHARSET 128 #define FXFONT_HANGEUL_CHARSET 129 #define FXFONT_GB2312_CHARSET 134 #define FXFONT_CHINESEBIG5_CHARSET 136 #define FXFONT_THAI_CHARSET 222 #define FXFONT_EASTEUROPE_CHARSET 238 #define FXFONT_RUSSIAN_CHARSET 204 #define FXFONT_GREEK_CHARSET 161 #define FXFONT_TURKISH_CHARSET 162 #define FXFONT_HEBREW_CHARSET 177 #define FXFONT_ARABIC_CHARSET 178 #define FXFONT_BALTIC_CHARSET 186 #define FXFONT_FF_FIXEDPITCH 1 #define FXFONT_FF_ROMAN (1<<4) #define FXFONT_FF_SCRIPT (4<<4) #define FXFONT_FW_NORMAL 400 #define FXFONT_FW_BOLD 700 class CFX_Font : public CFX_Object { public: CFX_Font(); ~CFX_Font(); FX_BOOL LoadSubst(const CFX_ByteString& face_name, FX_BOOL bTrueType, FX_DWORD flags, int weight, int italic_angle, int CharsetCP, FX_BOOL bVertical = FALSE); FX_BOOL LoadEmbedded(FX_LPCBYTE data, FX_DWORD size); FX_BOOL LoadFile(IFX_FileRead* pFile); FXFT_Face GetFace() const { return m_Face; } const CFX_SubstFont* GetSubstFont() const { return m_pSubstFont; } CFX_PathData* LoadGlyphPath(FX_DWORD glyph_index, int dest_width = 0); int GetGlyphWidth(FX_DWORD glyph_index); int GetAscent() const; int GetDescent() const; FX_BOOL GetGlyphBBox(FX_DWORD glyph_index, FX_RECT &bbox); FX_BOOL IsItalic(); FX_BOOL IsBold(); FX_BOOL IsFixedWidth(); FX_BOOL IsVertical() const { return m_bVertical; } CFX_WideString GetPsName() const; CFX_ByteString GetFamilyName() const; CFX_ByteString GetFaceName() const; FX_BOOL IsTTFont(); FX_BOOL GetBBox(FX_RECT &bbox); int GetHeight(); int GetULPos(); int GetULthickness(); int GetMaxAdvanceWidth(); FXFT_Face m_Face; CFX_SubstFont* m_pSubstFont; FX_BOOL IsEmbedded() { return m_bEmbedded; } void AdjustMMParams(int glyph_index, int width, int weight); FX_LPBYTE m_pFontDataAllocation; FX_LPBYTE m_pFontData; FX_LPBYTE m_pGsubData; FX_DWORD m_dwSize; CFX_BinaryBuf m_OtfFontData; void* m_hHandle; void* m_pPlatformFont; void* m_pPlatformFontCollection; void* m_pDwFont; FX_BOOL m_bDwLoaded; void ReleasePlatformResource(); void DeleteFace(); protected: FX_BOOL m_bEmbedded; FX_BOOL m_bVertical; void* m_pOwnedStream; }; #define ENCODING_INTERNAL 0 #define ENCODING_UNICODE 1 class IFX_FontEncoding : public CFX_Object { public: virtual ~IFX_FontEncoding() {} virtual FX_DWORD GlyphFromCharCode(FX_DWORD charcode) = 0; virtual CFX_WideString UnicodeFromCharCode(FX_DWORD charcode) const = 0; virtual FX_DWORD CharCodeFromUnicode(FX_WCHAR Unicode) const = 0; }; IFX_FontEncoding* FXGE_CreateUnicodeEncoding(CFX_Font* pFont); #define FXFONT_SUBST_MM 0x01 #define FXFONT_SUBST_GLYPHPATH 0x04 #define FXFONT_SUBST_CLEARTYPE 0x08 #define FXFONT_SUBST_TRANSFORM 0x10 #define FXFONT_SUBST_NONSYMBOL 0x20 #define FXFONT_SUBST_EXACT 0x40 #define FXFONT_SUBST_STANDARD 0x80 class CFX_SubstFont : public CFX_Object { public: CFX_SubstFont(); FX_LPVOID m_ExtHandle; CFX_ByteString m_Family; int m_Charset; FX_DWORD m_SubstFlags; int m_Weight; int m_ItalicAngle; FX_BOOL m_bSubstOfCJK; int m_WeightCJK; FX_BOOL m_bItlicCJK; }; #define FX_FONT_FLAG_SERIF 0x01 #define FX_FONT_FLAG_FIXEDPITCH 0x02 #define FX_FONT_FLAG_ITALIC 0x04 #define FX_FONT_FLAG_BOLD 0x08 #define FX_FONT_FLAG_SYMBOLIC_SYMBOL 0x10 #define FX_FONT_FLAG_SYMBOLIC_DINGBATS 0x20 #define FX_FONT_FLAG_MULTIPLEMASTER 0x40 typedef struct { FX_LPCBYTE m_pFontData; FX_DWORD m_dwSize; } FoxitFonts; class CFX_FontMgr : public CFX_Object { public: CFX_FontMgr(); ~CFX_FontMgr(); void InitFTLibrary(); FXFT_Face GetCachedFace(const CFX_ByteString& face_name, int weight, FX_BOOL bItalic, FX_LPBYTE& pFontData); FXFT_Face AddCachedFace(const CFX_ByteString& face_name, int weight, FX_BOOL bItalic, FX_LPBYTE pData, FX_DWORD size, int face_index); FXFT_Face GetCachedTTCFace(int ttc_size, FX_DWORD checksum, int font_offset, FX_LPBYTE& pFontData); FXFT_Face AddCachedTTCFace(int ttc_size, FX_DWORD checksum, FX_LPBYTE pData, FX_DWORD size, int font_offset); FXFT_Face GetFileFace(FX_LPCSTR filename, int face_index); FXFT_Face GetFixedFace(FX_LPCBYTE pData, FX_DWORD size, int face_index); void ReleaseFace(FXFT_Face face); void SetSystemFontInfo(IFX_SystemFontInfo* pFontInfo); FXFT_Face FindSubstFont(const CFX_ByteString& face_name, FX_BOOL bTrueType, FX_DWORD flags, int weight, int italic_angle, int CharsetCP, CFX_SubstFont* pSubstFont); void FreeCache(); FX_BOOL GetStandardFont(FX_LPCBYTE& pFontData, FX_DWORD& size, int index); CFX_FontMapper* m_pBuiltinMapper; IFX_FontMapper* m_pExtMapper; CFX_MapByteStringToPtr m_FaceMap; FXFT_Library m_FTLibrary; FoxitFonts m_ExternalFonts[16]; }; class IFX_FontMapper : public CFX_Object { public: virtual ~IFX_FontMapper() {} virtual FXFT_Face FindSubstFont(const CFX_ByteString& face_name, FX_BOOL bTrueType, FX_DWORD flags, int weight, int italic_angle, int CharsetCP, CFX_SubstFont* pSubstFont) = 0; CFX_FontMgr* m_pFontMgr; }; class IFX_FontEnumerator { public: virtual ~IFX_FontEnumerator() { } virtual void HitFont() = 0; virtual void Finish() = 0; }; class IFX_AdditionalFontEnum { public: virtual ~IFX_AdditionalFontEnum() { } virtual int CountFiles() = 0; virtual IFX_FileStream* GetFontFile(int index) = 0; }; class CFX_FontMapper : public IFX_FontMapper { public: CFX_FontMapper(); virtual ~CFX_FontMapper(); void SetSystemFontInfo(IFX_SystemFontInfo* pFontInfo); IFX_SystemFontInfo* GetSystemFontInfo() { return m_pFontInfo; } void AddInstalledFont(const CFX_ByteString& name, int charset); void LoadInstalledFonts(); CFX_ByteStringArray m_InstalledTTFonts; void SetFontEnumerator(IFX_FontEnumerator* pFontEnumerator) { m_pFontEnumerator = pFontEnumerator; } IFX_FontEnumerator* GetFontEnumerator() const { return m_pFontEnumerator; } virtual FXFT_Face FindSubstFont(const CFX_ByteString& face_name, FX_BOOL bTrueType, FX_DWORD flags, int weight, int italic_angle, int CharsetCP, CFX_SubstFont* pSubstFont); private: CFX_ByteString GetPSNameFromTT(void* hFont); CFX_ByteString MatchInstalledFonts(const CFX_ByteString& norm_name); FXFT_Face UseInternalSubst(CFX_SubstFont* pSubstFont, int iBaseFont, int italic_angle, int weight, int picthfamily); FX_BOOL m_bListLoaded; FXFT_Face m_MMFaces[2]; CFX_ByteString m_LastFamily; CFX_DWordArray m_CharsetArray; CFX_ByteStringArray m_FaceArray; IFX_SystemFontInfo* m_pFontInfo; FXFT_Face m_FoxitFaces[14]; IFX_FontEnumerator* m_pFontEnumerator; }; class IFX_SystemFontInfo : public CFX_Object { public: static IFX_SystemFontInfo* CreateDefault(); virtual void Release() = 0; virtual FX_BOOL EnumFontList(CFX_FontMapper* pMapper) = 0; virtual void* MapFont(int weight, FX_BOOL bItalic, int charset, int pitch_family, FX_LPCSTR face, FX_BOOL& bExact) = 0; virtual void* GetFont(FX_LPCSTR face) = 0; virtual FX_DWORD GetFontData(void* hFont, FX_DWORD table, FX_LPBYTE buffer, FX_DWORD size) = 0; virtual FX_BOOL GetFaceName(void* hFont, CFX_ByteString& name) = 0; virtual FX_BOOL GetFontCharset(void* hFont, int& charset) = 0; virtual int GetFaceIndex(void* hFont) { return 0; } virtual void DeleteFont(void* hFont) = 0; virtual void* RetainFont(void* hFont) { return NULL; } protected: ~IFX_SystemFontInfo() { } }; class CFX_FolderFontInfo : public IFX_SystemFontInfo { public: CFX_FolderFontInfo(); virtual ~CFX_FolderFontInfo(); void AddPath(FX_BSTR path); virtual void Release(); virtual FX_BOOL EnumFontList(CFX_FontMapper* pMapper); virtual void* MapFont(int weight, FX_BOOL bItalic, int charset, int pitch_family, FX_LPCSTR face, FX_BOOL& bExact); virtual void* GetFont(FX_LPCSTR face); virtual FX_DWORD GetFontData(void* hFont, FX_DWORD table, FX_LPBYTE buffer, FX_DWORD size); virtual void DeleteFont(void* hFont); virtual FX_BOOL GetFaceName(void* hFont, CFX_ByteString& name); virtual FX_BOOL GetFontCharset(void* hFont, int& charset); protected: CFX_MapByteStringToPtr m_FontList; CFX_ByteStringArray m_PathList; CFX_FontMapper* m_pMapper; void ScanPath(CFX_ByteString& path); void ScanFile(CFX_ByteString& path); void ReportFace(CFX_ByteString& path, FXSYS_FILE* pFile, FX_DWORD filesize, FX_DWORD offset); }; class CFX_CountedFaceCache : public CFX_Object { public: CFX_FaceCache* m_Obj; FX_DWORD m_nCount; }; typedef CFX_MapPtrTemplate<FXFT_Face, CFX_CountedFaceCache*> CFX_FTCacheMap; class CFX_FontCache : public CFX_Object { public: ~CFX_FontCache(); CFX_FaceCache* GetCachedFace(CFX_Font* pFont); void ReleaseCachedFace(CFX_Font* pFont); void FreeCache(FX_BOOL bRelease = FALSE); private: CFX_FTCacheMap m_FTFaceMap; CFX_FTCacheMap m_ExtFaceMap; }; class CFX_AutoFontCache { public: CFX_AutoFontCache(CFX_FontCache* pFontCache, CFX_Font* pFont) : m_pFontCache(pFontCache) , m_pFont(pFont) { } ~CFX_AutoFontCache() { m_pFontCache->ReleaseCachedFace(m_pFont); } CFX_FontCache* m_pFontCache; CFX_Font* m_pFont; }; #define FX_FONTCACHE_DEFINE(pFontCache, pFont) CFX_AutoFontCache autoFontCache((pFontCache), (pFont)) class CFX_GlyphBitmap : public CFX_Object { public: int m_Top; int m_Left; CFX_DIBitmap m_Bitmap; }; class CFX_FaceCache : public CFX_Object { public: ~CFX_FaceCache(); const CFX_GlyphBitmap* LoadGlyphBitmap(CFX_Font* pFont, FX_DWORD glyph_index, FX_BOOL bFontStyle, const CFX_AffineMatrix* pMatrix, int dest_width, int anti_alias, int& text_flags); const CFX_PathData* LoadGlyphPath(CFX_Font* pFont, FX_DWORD glyph_index, int dest_width); CFX_FaceCache(FXFT_Face face); private: FXFT_Face m_Face; CFX_GlyphBitmap* RenderGlyph(CFX_Font* pFont, FX_DWORD glyph_index, FX_BOOL bFontStyle, const CFX_AffineMatrix* pMatrix, int dest_width, int anti_alias); CFX_GlyphBitmap* RenderGlyph_Nativetext(CFX_Font* pFont, FX_DWORD glyph_index, const CFX_AffineMatrix* pMatrix, int dest_width, int anti_alias); CFX_GlyphBitmap* LookUpGlyphBitmap(CFX_Font* pFont, const CFX_AffineMatrix* pMatrix, CFX_ByteStringC& FaceGlyphsKey, FX_DWORD glyph_index, FX_BOOL bFontStyle, int dest_width, int anti_alias); CFX_MapByteStringToPtr m_SizeMap; CFX_MapPtrToPtr m_PathMap; CFX_DIBitmap* m_pBitmap; void* m_pPlatformGraphics; void* m_pPlatformBitmap; void* m_hDC; void* m_hBitmap; void* m_hOldBitmap; void* m_hGdiFont; void* m_hOldGdiFont; void InitPlatform(); void DestroyPlatform(); }; typedef struct { const CFX_GlyphBitmap* m_pGlyph; int m_OriginX, m_OriginY; FX_FLOAT m_fOriginX, m_fOriginY; } FXTEXT_GLYPHPOS; FX_RECT FXGE_GetGlyphsBBox(FXTEXT_GLYPHPOS* pGlyphAndPos, int nChars, int anti_alias, FX_FLOAT retinaScaleX = 1.0f, FX_FLOAT retinaScaleY = 1.0f); FX_BOOL OutputGlyph(void* dib, int x, int y, CFX_Font* pFont, double font_size, CFX_AffineMatrix* pMatrix, unsigned long glyph_index, unsigned long argb); FX_BOOL OutputText(void* dib, int x, int y, CFX_Font* pFont, double font_size, CFX_AffineMatrix* pText_matrix, unsigned short const* text, unsigned long argb); class IFX_GSUBTable { public: virtual void Release() = 0; virtual FX_BOOL GetVerticalGlyph(FX_DWORD glyphnum, FX_DWORD* vglyphnum) = 0; protected: ~IFX_GSUBTable() { } }; IFX_GSUBTable* FXGE_CreateGSUBTable(CFX_Font* pFont); #endif
{ "content_hash": "72c5d6303273f18b1211616364ec6348", "timestamp": "", "source": "github", "line_count": 433, "max_line_length": 146, "avg_line_length": 31.993071593533486, "alnum_prop": 0.6539377752111456, "repo_name": "CTSRD-SOAAP/chromium-42.0.2311.135", "id": "bf9bb40500a60aa1d9fc1f59dec35715a169b39d", "size": "14012", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "third_party/pdfium/core/include/fxge/fx_font.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "8402" }, { "name": "Assembly", "bytes": "241154" }, { "name": "C", "bytes": "12370053" }, { "name": "C++", "bytes": "266788423" }, { "name": "CMake", "bytes": "27829" }, { "name": "CSS", "bytes": "813488" }, { "name": "Emacs Lisp", "bytes": "2360" }, { "name": "Go", "bytes": "13628" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "20131029" }, { "name": "Java", "bytes": "8495790" }, { "name": "JavaScript", "bytes": "12980966" }, { "name": "LLVM", "bytes": "1169" }, { "name": "Logos", "bytes": "6893" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "208709" }, { "name": "Objective-C", "bytes": "1509363" }, { "name": "Objective-C++", "bytes": "7960581" }, { "name": "PLpgSQL", "bytes": "215882" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "432373" }, { "name": "Python", "bytes": "11147426" }, { "name": "Ragel in Ruby Host", "bytes": "104923" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "1207731" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "VimL", "bytes": "4075" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
package freemarker.core; import freemarker.template.TemplateModel; import freemarker.template.TemplateSequenceModel; /** * Indicates that a {@link TemplateSequenceModel} value was expected, but the value had a different type. * * @since 2.3.21 */ public class NonSequenceException extends UnexpectedTypeException { private static final Class[] EXPECTED_TYPES = new Class[] { TemplateSequenceModel.class }; public NonSequenceException(Environment env) { super(env, "Expecting sequence value here"); } public NonSequenceException(String description, Environment env) { super(env, description); } NonSequenceException(Environment env, _ErrorDescriptionBuilder description) { super(env, description); } NonSequenceException( Expression blamed, TemplateModel model, Environment env) throws InvalidReferenceException { super(blamed, model, "sequence", EXPECTED_TYPES, env); } NonSequenceException( Expression blamed, TemplateModel model, String tip, Environment env) throws InvalidReferenceException { super(blamed, model, "sequence", EXPECTED_TYPES, tip, env); } NonSequenceException( Expression blamed, TemplateModel model, String[] tips, Environment env) throws InvalidReferenceException { super(blamed, model, "sequence", EXPECTED_TYPES, tips, env); } }
{ "content_hash": "bafdac181d1840c0e727a1f1109723ed", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 118, "avg_line_length": 30.829787234042552, "alnum_prop": 0.694271911663216, "repo_name": "ekollof/DarkUniverse", "id": "1fd9b797ca2f949ba78c4b5e53fc79fcf145fa83", "size": "2078", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "lib/Freemarker/source/src/main/java/freemarker/core/NonSequenceException.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "47" }, { "name": "HTML", "bytes": "14328" }, { "name": "Java", "bytes": "3661165" }, { "name": "Shell", "bytes": "47" } ], "symlink_target": "" }
class RailsExceptionHandler class InstallGenerator < Rails::Generators::Base desc "Copy initialization file" source_root File.expand_path('../templates', __FILE__) class_option :template_engine def copy_initializer copy_file 'rails_exception_handler.rb', 'config/initializers/rails_exception_handler.rb' end end end
{ "content_hash": "d4f8d1a6955363d96bc916f7ab59abcc", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 94, "avg_line_length": 31.545454545454547, "alnum_prop": 0.729106628242075, "repo_name": "Sharagoz/rails_exception_handler", "id": "88cff4e733cb6ac7257191757957312048fd8ed4", "size": "347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/rails_exception_handler/install_generator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2486" }, { "name": "HTML", "bytes": "5241" }, { "name": "JavaScript", "bytes": "2933" }, { "name": "Ruby", "bytes": "145575" } ], "symlink_target": "" }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; using Correspondence.Mementos; namespace Correspondence.UnitTest { [TestClass] public class ThreadSafeHashCodeTest { private const int KnownHashCode = 1611906182; private const int HashCount = 2000000; private CountdownEvent _threadsRunning; private int _computedHashCode = KnownHashCode; [TestInitialize] public void Initialize() { _threadsRunning = new CountdownEvent(2); } [TestMethod] public void HashCodeOfKnownType() { int hashCode = KnownType.GetHashCode(); Assert.AreEqual(KnownHashCode, hashCode); } [TestMethod] public void TypeHashCodeIsThreadSafe() { Thread noise = new Thread(NoiseThreadProc); Thread test = new Thread(TestThreadProc); noise.Start(); test.Start(); _threadsRunning.Wait(); Assert.AreEqual(KnownHashCode, _computedHashCode); } private void NoiseThreadProc() { for (int i = 0; i < HashCount; i++) { int hashCode = new CorrespondenceFactType(Guid.NewGuid().ToString(), 1).GetHashCode(); } _threadsRunning.Signal(); } private void TestThreadProc() { for (int i = 0; i < HashCount; i++) { int hashCode = KnownType.GetHashCode(); if (hashCode != KnownHashCode) { _computedHashCode = hashCode; break; } } _threadsRunning.Signal(); } private static CorrespondenceFactType KnownType { get { return new CorrespondenceFactType("FacetedWorlds.Model.IdentityListShare", 1); } } } }
{ "content_hash": "c8715a9cfb93475f9cd77d751a3ff8da", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 102, "avg_line_length": 27.698630136986303, "alnum_prop": 0.5613254203758655, "repo_name": "michaellperry/Correspondence", "id": "96b7aa5ff8be3a7d863d5e3d7c133e93a56495f0", "size": "2024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Portable/Correspondence.UnitTest/ThreadSafeHashCodeTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "677" }, { "name": "C#", "bytes": "1190528" }, { "name": "Pascal", "bytes": "36218" }, { "name": "Puppet", "bytes": "130" } ], "symlink_target": "" }
package org.shaolin.bmdp.designtime.orm; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.shaolin.bmdp.datamodel.bediagram.BEListType; import org.shaolin.bmdp.datamodel.bediagram.BEObjRefType; import org.shaolin.bmdp.datamodel.bediagram.BusinessEntityType; import org.shaolin.bmdp.datamodel.bediagram.CEObjRefType; import org.shaolin.bmdp.datamodel.bediagram.DateTimeType; import org.shaolin.bmdp.datamodel.bediagram.JavaObjRefType; import org.shaolin.bmdp.datamodel.bediagram.MemberType; import org.shaolin.bmdp.datamodel.bediagram.TimeType; import org.shaolin.bmdp.datamodel.common.DiagramType; import org.shaolin.bmdp.datamodel.rdbdiagram.ClassMappingType; import org.shaolin.bmdp.datamodel.rdbdiagram.FieldMappingType; import org.shaolin.bmdp.datamodel.rdbdiagram.JoinTableType; import org.shaolin.bmdp.datamodel.rdbdiagram.ListFieldMappingType; import org.shaolin.bmdp.datamodel.rdbdiagram.PKType; import org.shaolin.bmdp.datamodel.rdbdiagram.RDBDiagram; import org.shaolin.bmdp.datamodel.rdbdiagram.RDBType; import org.shaolin.bmdp.datamodel.rdbdiagram.TableType; import org.shaolin.bmdp.datamodel.rdbdiagram.ViewType; import org.shaolin.bmdp.designtime.bediagram.BESourceGenerator; import org.shaolin.bmdp.designtime.tools.GeneratorOptions; import org.shaolin.bmdp.designtime.tools.PumpWriter; import org.shaolin.bmdp.runtime.Registry; import org.shaolin.bmdp.runtime.be.BEUtil; import org.shaolin.bmdp.runtime.entity.EntityAddedEvent; import org.shaolin.bmdp.runtime.entity.EntityManager; import org.shaolin.bmdp.runtime.entity.EntityNotFoundException; import org.shaolin.bmdp.runtime.entity.EntityUpdatedEvent; import org.shaolin.bmdp.runtime.entity.IEntityEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HibernateMappingGenerator implements IEntityEventListener<TableType, RDBDiagram> { private static final Logger logger = LoggerFactory.getLogger(BESourceGenerator.class.getName()); private final PumpWriter out = new PumpWriter(); private Map<String, RDBType> compMap = new HashMap<String, RDBType>(); private List<TableType> tables = new ArrayList<TableType>(); private EntityManager entityManager; private GeneratorOptions options; public HibernateMappingGenerator(GeneratorOptions options) { this.options = options; out.setOutputDir(options.getHBMDirectory()); out.setEncoding(Registry.getInstance().getEncoding()); } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public void notify(EntityAddedEvent<TableType, RDBDiagram> event) { if (event.getDiagram().getDaoPackage().indexOf(options.getBundleName()) == -1) { return; } RDBDiagram diagram = event.getDiagram(); TableType table = event.getEntity(); ClassMappingType mapping = event.getEntity().getMapping(); if (mapping == null) { return; } if (mapping.getBusinessEntity() == null) { return; } String beName = mapping.getBusinessEntity().getEntityName(); BusinessEntityType be = entityManager.getEntity(beName, BusinessEntityType.class); if (!be.isNeedPersist()) { return; } try { File path = new File(options.getHBMDirectory(), table.getEntityName()+ ".hbm.xml"); out.write("\n!!!!file "); out.print(path.getAbsolutePath()); out.write("\n"); if (logger.isInfoEnabled()) { logger.info("Table's hbm is {}, whose generated file is {}", table.getEntityName(), path.getAbsolutePath()); } out.write("<?xml version=\"1.0\"?>\n"); out.write("<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \n"); out.write("\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">\n"); out.write("<hibernate-mapping>\n"); out.write(" <class name=\""); out.print(mapping.getBusinessEntity().getEntityName() + "Impl"); out.write("\" table=\""); String tableName = table.getEntityName(); tableName = tableName.substring(tableName.lastIndexOf('.') + 1); out.print(tableName); out.write("\" dynamic-update=\"true\">\n"); List<FieldMappingType> fieldMappings = mapping.getFieldMappings(); if (table.getPrimaryKeies() != null) { List<PKType> pks = table.getPrimaryKeies(); for (PKType pk: pks) { out.write(" <id name=\""); out.print(getBEField(pk.getColumnName(), mapping)); out.write("\" column=\""); out.print(pk.getColumnName()); out.write("\">\n"); out.write(" <generator class=\"native\" />\n"); // out.write("<param name=\"sequence\">"); // out.print(table.getSequence().getName()); // out.write("</param>\n"); // out.write(" </generator>\n"); out.write(" </id>\n"); // remove PK mapping. FieldMappingType matched = null; for (FieldMappingType fm: fieldMappings) { if (pk.getColumnName().equals(fm.getColumnName())) { matched = fm; } } if (matched != null) { fieldMappings.remove(matched); } } } for (FieldMappingType fm: fieldMappings) { if (fm instanceof ListFieldMappingType) { ListFieldMappingType listMapping = (ListFieldMappingType)fm; /** * &lt;enumeration value="One-to-One"/> * &lt;enumeration value="One-to-Many"/> * &lt;enumeration value="Many-to-Many"/> */ if ("One-to-One".equals(listMapping.getMappingType())) { // A bidirectional one-to-one association on a foreign key is common: out.write(" <many-to-one name=\""); out.print(listMapping.getBeFieldName()); out.write("\" column=\""); out.print(listMapping.getColumnName()); out.write("\" unique=\"true\" not-null=\"true\" lazy=\"false\" insert=\"false\" update=\"false\"/>\n"); } else if ("One-to-Many".equals(listMapping.getMappingType())) { String targetBEClass = BEUtil.getBEImplementClassName(listMapping.getCollectionElement()); JoinTableType joinTable = getJoinTable(diagram, listMapping.getAssociationName()); out.write(" <set name=\""); out.print(joinTable.getSrcCollection()); out.write("\" table=\""); out.print(joinTable.getName()); //cascade="all|none|save-update|delete|all-delete-orphan|(6)delete-orphan" //sort="unsorted|natural|comparatorClass" //TODO: cascading decision is difficult here. out.write("\" cascade=\"all-delete-orphan\" lazy=\"true\" fetch=\"select\">\n"); out.write(" <key column=\""); out.print(joinTable.getTarPKColumn()); out.write("\"/>\n"); out.write(" <one-to-many class=\""); out.print(targetBEClass); out.write("\"/>\n"); out.write(" </set>\n"); } else if ("Many-to-Many".equals(listMapping.getMappingType())) { // A unidirectional one-to-many association on a foreign key is an // unusual case, and is not recommended. // You should instead use a join table for this kind of association. // A unidirectional one-to-many association on a join table is the preferred option. // Specifying unique="true", changes the multiplicity from many-to-many to one-to-many. String targetBEClass = BEUtil.getBEImplementClassName(listMapping.getCollectionElement()); JoinTableType joinTable = getJoinTable(diagram, listMapping.getAssociationName()); out.write(" <list name=\""); out.print(listMapping.getBeFieldName()); out.write("\" table=\""); out.print(joinTable.getName()); out.write("\" cascade=\"all-delete-orphan\" lazy=\"true\" fetch=\"select\">\n"); out.write(" <key column=\""); out.print(joinTable.getTarPKColumn()); out.write("\"/>\n"); out.write(" <index column=\"_index\"/>\n"); out.write(" <many-to-many class=\""); out.print(targetBEClass); out.write("\"/>\n"); out.write(" </list>\n"); } } else { // 8.1.1. Basic types hibernate-release-4.2.3.Final/ // documentation/devguide/en-US/html_single/index.html#d5e2292 out.write(" <property name=\""); if (isCEType(be, fm.getBeFieldName())) { out.print(fm.getBeFieldName()); out.write("Int"); } else if (isCEListType(be, fm.getBeFieldName())) { out.print(fm.getBeFieldName()); out.write("IntValues"); } else { out.print(fm.getBeFieldName()); } getPropertyType(be, fm.getBeFieldName()); out.write("\" column=\""); out.print(fm.getColumnName()); out.write("\"/>\n"); } } out.write(" <property name=\"_cas\" type=\"long\" column=\"_cas\"/>\n"); out.write(" </class>\n"); out.write("</hibernate-mapping>\n"); out.finish(); } finally { tables.remove(event.getEntity()); } } public void notify(EntityUpdatedEvent<TableType, RDBDiagram> event) { } public Class<TableType> getEventType() { return TableType.class; } @Override public void notifyLoadFinish(DiagramType diagram) { } public void notifyAllLoadFinish() { } public boolean isCEType(BusinessEntityType be, String beField) { for (MemberType m: be.getMembers()) { if (beField.equals(m.getName())) { return m.getType() instanceof CEObjRefType; } } if (be.getParentObject() != null) { if (be.getParentObject() instanceof BEObjRefType) { String entityName = ((BEObjRefType)be.getParentObject()).getTargetEntity().getEntityName(); if (entityName.indexOf('.') == -1) { entityName = be.getEntityName().substring(0, be.getEntityName().lastIndexOf('.') + 1) + entityName; } BusinessEntityType parent = entityManager.getEntity(entityName, BusinessEntityType.class); return isCEType(parent, beField); } } return false; } public boolean isCEListType(BusinessEntityType be, String beField) { for (MemberType m: be.getMembers()) { if (beField.equals(m.getName())) { if (m.getType().getClass() == BEListType.class && ((BEListType)m.getType()).getElementType().getClass() == CEObjRefType.class) { return true; } } } if (be.getParentObject() != null) { if (be.getParentObject() instanceof BEObjRefType) { String entityName = ((BEObjRefType)be.getParentObject()).getTargetEntity().getEntityName(); if (entityName.indexOf('.') == -1) { entityName = be.getEntityName().substring(0, be.getEntityName().lastIndexOf('.') + 1) + entityName; } BusinessEntityType parent = entityManager.getEntity(entityName, BusinessEntityType.class); return isCEListType(parent, beField); } } return false; } /** * The name of a Hibernate basic type: * integer, string, character, date, * timestamp, float, binary, serializable, * object, blob * * @param beName * @param beField * @return */ public void getPropertyType(BusinessEntityType be, String beField) { List<MemberType> fields = be.getMembers(); for (MemberType field: fields) { if (field.getName().equals(beField)) { if (field.getType() instanceof DateTimeType) { out.write("\" type=\"timestamp");; } else if (field.getType() instanceof TimeType) { out.write("\" type=\"timestamp"); } else if (field.getType() instanceof CEObjRefType) { out.write("\" type=\"integer"); } else if (field.getType() instanceof JavaObjRefType) { JavaObjRefType objRef = (JavaObjRefType)field.getType(); if ("byte[]".equals(objRef.getTargetJava().getName())) { //http://redleaf.iteye.com/blog/100718 //hibernate with blob solution. out.write("\" type=\"binary"); } } return; } } // history attributes if ("_version".equals(beField)) { out.write("\" type=\"int"); return; } else if ("_taskId".equals(beField)) { out.write("\" type=\"long"); return; } else if ("_sessionId".equals(beField)) { return; } else if ("orgId".equals(beField)) { out.write("\" type=\"long"); return; } else if ("createDate".equals(beField)) { out.write("\" type=\"timestamp"); return; } else if ("_starttime".equals(beField)) { out.write("\" type=\"timestamp"); return; } else if ("_endtime".equals(beField)) { out.write("\" type=\"timestamp"); return; } else if ("_optuserid".equals(beField)) { out.write("\" type=\"long"); return; } else if ("_enable".equals(beField)) { out.write("\" type=\"boolean"); return; } else if ("_cas".equals(beField)) { out.write("\" type=\"long"); return; } else if ("x".equals(beField)) { out.write("\" type=\"int"); return; } else if ("y".equals(beField)) { out.write("\" type=\"int"); return; } if (be.getParentObject() != null) { if (be.getParentObject() instanceof BEObjRefType) { String entityName = ((BEObjRefType)be.getParentObject()).getTargetEntity().getEntityName(); if (entityName.indexOf('.') == -1) { entityName = be.getEntityName().substring(0, be.getEntityName().lastIndexOf('.') + 1) + entityName; } BusinessEntityType parent = entityManager.getEntity(entityName, BusinessEntityType.class); getPropertyType(parent, beField); return; } } throw new IllegalArgumentException("The field '" + beField + "' can't be found in BE entity " + be.getEntityName()); } private String getBEField(String columnName, ClassMappingType mapping) { List<FieldMappingType> mappings = mapping.getFieldMappings(); for (FieldMappingType m : mappings) { if (columnName.equals(m.getColumnName())) { return m.getBeFieldName(); } } throw new IllegalArgumentException("The be field[" + columnName + "] can't be found in ClassMapping of BE " + mapping.getBusinessEntity().getEntityName() + "."); } private JoinTableType getJoinTable(RDBDiagram diagram, String associateName) { for (JoinTableType table: diagram.getJoinTables()) { if (associateName.equals(table.getName())) { return table; } } return null; } private TableType getTableByName(String entityName) { return (TableType) getRDBByName(entityName); } private RDBType getRDBByName(String entityName) { RDBType rdb = (RDBType) compMap.get(entityName); if (rdb != null) { return rdb; } return getRDBByComponent(entityName); } private RDBType getRDBByComponent(String entityName) { try { TableType table = entityManager.getEntity(entityName, TableType.class); compMap.put(table.getEntityName(), table); return table; } catch (EntityNotFoundException e) { ViewType view = entityManager.getEntity(entityName, ViewType.class); compMap.put(view.getEntityName(), view); return view; } } }
{ "content_hash": "65d67eead625a7e4fcb6df0d83fa8684", "timestamp": "", "source": "github", "line_count": 410, "max_line_length": 109, "avg_line_length": 35.646341463414636, "alnum_prop": 0.6704071159767362, "repo_name": "shaolinwu/uimaster", "id": "77bdc4da56533ef28ea08df42001b170342ef1fb", "size": "14615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/designtime/src/main/java/org/shaolin/bmdp/designtime/orm/HibernateMappingGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "562" }, { "name": "Batchfile", "bytes": "3807" }, { "name": "CSS", "bytes": "200928" }, { "name": "Java", "bytes": "5815822" }, { "name": "JavaScript", "bytes": "1226516" } ], "symlink_target": "" }
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php55Kafka < AbstractPhp55Extension init desc "PHP extension for Apache Kafka" homepage "https://github.com/EVODelavega/phpkafka/" url "https://github.com/EVODelavega/phpkafka/archive/6a0908803ab6e9d862097e99f84aeb0fff9ecf03.tar.gz" version "rev-6a09088" sha256 "f76933b8dea53f822028368380f83e3d4c13ef93811e2014e023408ce4920357" head "https://github.com/EVODelavega/phpkafka.git" depends_on "librdkafka" => :build def install ENV.universal_binary if build.universal? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig, "--enable-kafka" system "make" prefix.install "modules/kafka.so" write_config_file if build.with? "config-file" end end
{ "content_hash": "a4e3a7c8d1748c171f12ccb025d89801", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 103, "avg_line_length": 33.44, "alnum_prop": 0.6985645933014354, "repo_name": "dguyon/homebrew-php", "id": "b9944bd30ef1cd6604e11ce04f362cde6524291e", "size": "836", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Formula/php55-kafka.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "831753" } ], "symlink_target": "" }
// Copyright 2014 Frank A. Krueger // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.Ast.Transforms; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; using Mono.Cecil; using ICSharpCode.NRefactory; namespace Netjs { public class CsToTs : IAstTransform { public static bool ES3Compatible = false; public const string ES3GetterPrefix = "Get"; public const string ES3SetterPrefix = "Set"; public CsToTs (bool es3Compatible = false) { ES3Compatible = es3Compatible; } public void Run (AstNode compilationUnit) { foreach (var t in GetTransforms ()) { t.Run (compilationUnit); } } IEnumerable<IAstTransform> GetTransforms () { yield return new FixBadNames (); yield return new LiftNestedClasses (); yield return new RemoveConstraints (); yield return new FlattenNamespaces (); yield return new StructToClass (); yield return new FixGenericsThatUseObject (); yield return new FixEvents (); yield return new FixTypeOf (); yield return new RemoveNonGenericEnumerable (); yield return new RemovePrivateInterfaceOverloads (); yield return new AvoidTrickyJsKeywords (); yield return new AddAbstractMethodBodies (); yield return new MergeCtors (); yield return new EnsureAtLeastOneCtor (); yield return new StaticCtorsToMethods (); yield return new PropertiesToMethods (); yield return new InitializeFields (); yield return new MakeSuperCtorFirst (); yield return new MergeOverloads (); yield return new FixCatches (); yield return new FixEmptyThrow (); yield return new AnonymousInitializersNeedNames (); yield return new ReplaceObjectEquals (); yield return new InlineDelegates (); yield return new OperatorDeclsToMethods (); yield return new ExpandOperators (); yield return new ExpandIndexers (); yield return new InlineEnumMethods (); yield return new NewArraysNeedDefaultValues (); yield return new PassArraysAsEnumerables (); yield return new WrapRefArgs (); yield return new ReplaceDefault (); yield return new IndexersToMethods (); yield return new ReplaceInstanceMembers (); yield return new CharsToNumbers (); yield return new StringConstructorsToMethods (); yield return new MakePrimitiveTypesJsTypes (); yield return new FixIsOp (); yield return new Renames (); yield return new SuperPropertiesToThis (); yield return new BitwiseOrToConditionalForBooleans (); yield return new RemoveDelegateConstructors (); yield return new MakeNullableExplicit (); yield return new RemoveEnumBaseType (); yield return new RemoveGenericArgsInIsExpr (); yield return new RemoveAttributes (); yield return new RemoveModifiers (); yield return new RemoveEmptySwitch (); yield return new MakeWhileLoop (); yield return new GotoRemoval (); yield return new OrderClasses (); yield return new CallStaticCtors (); yield return new AddReferences (); yield return new NullableChecks (); yield return new AccessorsToInvocations (); } class CallStaticCtors : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); var ts = compilationUnit.Descendants.OfType<TypeDeclaration> ().Where (x => x.Members.Any (y => y.Name.EndsWith ("_cctor", StringComparison.Ordinal))).ToList (); if (ts.Count == 0) return; var p = ts [0].Parent; var b = new BlockStatement (); foreach (var t in ts) { var cctor = t.Members.First (y => y.Name.EndsWith ("_cctor", StringComparison.Ordinal)); b.AddChild (new ExpressionStatement (new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType (t.Name)), cctor.Name) )), BlockStatement.StatementRole); } p.AddChild (b, SyntaxTree.MemberRole); } } class NewArraysNeedDefaultValues : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitArrayCreateExpression (ArrayCreateExpression arrayCreateExpression) { base.VisitArrayCreateExpression (arrayCreateExpression); if (arrayCreateExpression.Arguments.Count != 1 || !arrayCreateExpression.Initializer.IsNull) return; var count = arrayCreateExpression.Arguments.First (); if (count is PrimitiveExpression && Convert.ToInt32 (((PrimitiveExpression)count).Value) == 0) return; var s = arrayCreateExpression.GetParent<Statement> (); if (s == null) return; var find = new FindFirstUseOfArray (); var variableDeclarationStatement = s as VariableDeclarationStatement; if (variableDeclarationStatement != null) { var v = arrayCreateExpression.GetParent <VariableInitializer> (); find.Variable = new IdentifierExpression (v.Name); } else { var es = s as ExpressionStatement; if (es != null && es.Expression is AssignmentExpression) { find.Variable = ((AssignmentExpression)es.Expression).Left; } else { return; // Don't know what's going on } } if (find.Variable == null) return; arrayCreateExpression.GetParent<EntityDeclaration> ().AcceptVisitor (find); if ((find.First is AssignmentExpression)) return; var i = new IdentifierExpression ("_ai"); var def = GetDefaultValue (arrayCreateExpression.Type); var init = new ForStatement { Condition = new BinaryOperatorExpression ( i, BinaryOperatorType.LessThan, new MemberReferenceExpression ((Expression)find.Variable.Clone (), "length")), EmbeddedStatement = new ExpressionStatement ( new AssignmentExpression ( new IndexerExpression ((Expression)find.Variable.Clone (), i.Clone ()), def.Clone ())), }; init.Initializers.Add (new VariableDeclarationStatement (new PrimitiveType ("number"), i.Identifier, new PrimitiveExpression (0))); init.Iterators.Add (new ExpressionStatement (new UnaryOperatorExpression (UnaryOperatorType.Increment, (Expression)i.Clone ()))); s.Parent.InsertChildAfter (s, init, (Role<Statement>)s.Role); } class FindFirstUseOfArray : DepthFirstAstVisitor { public AstNode Variable; public AstNode First; bool Match (AstNode p) { return NodesEqual (Variable, p); } public override void VisitIndexerExpression (IndexerExpression indexerExpression) { base.VisitIndexerExpression (indexerExpression); if (Match (indexerExpression.Target) && First == null) { First = indexerExpression; } } public override void VisitAssignmentExpression (AssignmentExpression assignmentExpression) { var indexerExpression = assignmentExpression.Left as IndexerExpression; if (indexerExpression != null) { if (Match (indexerExpression.Target) && First == null) { First = assignmentExpression; } } base.VisitAssignmentExpression (assignmentExpression); } } } static bool NodeCollectionsEqual<T>(AstNodeCollection<T> anodes, AstNodeCollection<T> bnodes) where T : AstNode { if (anodes.Count != bnodes.Count) return false; return anodes.Zip (bnodes, NodesEqual).All (x => x); } static bool NodesEqual(AstNode Variable, AstNode p) { if (Variable is IdentifierExpression) { var pi = p as IdentifierExpression; if (pi == null) return false; return ((IdentifierExpression)Variable).Identifier == pi.Identifier; } var mr = Variable as MemberReferenceExpression; if (mr != null) { var pmr = p as MemberReferenceExpression; if (pmr == null) return false; if (mr.MemberName != pmr.MemberName) return false; return NodesEqual (mr.Target, pmr.Target); } var tr = Variable as TypeReferenceExpression; if (tr != null) { var ptr = p as TypeReferenceExpression; if (ptr == null) return false; return tr.Type.Equals (ptr.Type); } var th = Variable as ThisReferenceExpression; if (th != null) { var pth = p as ThisReferenceExpression; return pth != null; } var ind = Variable as IndexerExpression; if (ind != null) { var pind = p as IndexerExpression; return pind != null && NodeCollectionsEqual (ind.Arguments, pind.Arguments); } throw new NotImplementedException (Variable + " (" + Variable.GetType () + ") == " + p); } class ReplaceObjectEquals : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitInvocationExpression (InvocationExpression invocationExpression) { base.VisitInvocationExpression (invocationExpression); var mr = invocationExpression.Target as MemberReferenceExpression; if (mr == null) return; if (mr.MemberName != "Equals") return; var m = invocationExpression.Annotation<MemberReference> (); if (m.DeclaringType.FullName != "System.Object") return; var i = new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType ("NObject")), "GenericEquals"), mr.Target.Clone (), invocationExpression.Arguments.First ().Clone ()); invocationExpression.ReplaceWith (i); } } class NullableChecks : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) { base.VisitMemberReferenceExpression (memberReferenceExpression); if (memberReferenceExpression.MemberName == "HasValue") { var t = GetTypeRef (memberReferenceExpression.Target); if (t != null && t.FullName.StartsWith ("System.Nullable`1", StringComparison.Ordinal)) { var ta = memberReferenceExpression.Target; ta.Remove (); var n = new BinaryOperatorExpression (ta, BinaryOperatorType.InEquality, new NullReferenceExpression ()); memberReferenceExpression.ReplaceWith (n); } } } } class FixTypeOf : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeOfExpression (TypeOfExpression typeOfExpression) { base.VisitTypeOfExpression (typeOfExpression); var nt = new ObjectCreateExpression ( new SimpleType ("Type"), new PrimitiveExpression (GetJsConstructor (typeOfExpression.Type))); typeOfExpression.ReplaceWith (nt); } } class InitializeFields : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); if (typeDeclaration.ClassType != ClassType.Class) return; foreach (var fieldDeclaration in typeDeclaration.Members.OfType<FieldDeclaration> ()) { foreach (var v in fieldDeclaration.Variables) { if (v.Initializer.IsNull) { v.Initializer = GetDefaultValue (fieldDeclaration.ReturnType); } } } } } static Expression GetDefaultValue (AstType returnType) { var js = GetJsConstructor (returnType); if (js == "Number") return new PrimitiveExpression (0); if (js == "Boolean") return new PrimitiveExpression (false); return new PrimitiveExpression (null); } class OrderClasses : IAstTransform { public void Run (AstNode compilationUnit) { var types = compilationUnit.Descendants.OfType<TypeDeclaration> ().ToList (); if (types.Count == 0) return; var needsMore = true; while (needsMore) { needsMore = false; for (int i = 0; i < types.Count; i++) { var t = types [i]; if (t.BaseTypes.Count == 0) continue; for (int j = i+1; j < types.Count; j++) { var u = types [j]; if (UsesType (t, u)) { // // Need to move it to before t // types.RemoveAt (j); types.Insert (i, u); needsMore = true; break; } } if (needsMore) break; } } var role = types [0].Role; var parent = types [0].Parent; foreach (var t in types) { t.Remove (); parent.AddChild ((AstNode)t, (Role<AstNode>)role); } } bool UsesType (TypeDeclaration t, TypeDeclaration u) { TI refTypes = null; if (!refs.TryGetValue (t.Name, out refTypes)) { refTypes = new TI (t); refs [t.Name] = refTypes; } return refTypes.UsesType (u); } Dictionary<string, TI> refs = new Dictionary<string, TI> (); class TI { readonly HashSet<string> ReferencedTypes = new HashSet<string> (); readonly AstNode parent; public TI (TypeDeclaration type) { parent = type.Parent; foreach (var bt in type.BaseTypes) { AddType (bt); } foreach (var i in type.Members.OfType<FieldDeclaration> () .Where (x => x.HasModifier (Modifiers.Static)) .SelectMany (x => x.Variables, (x,y) => y.Initializer) .Where (x => !x.IsNull)) { AddExpression (i); } } void AddExpression (AstNode expr) { // // Looks for static methods // foreach (var t in from x in expr.DescendantsAndSelf.OfType<InvocationExpression> () let mr = x.Target as MemberReferenceExpression where mr != null select mr) { var th = t.Target as ThisReferenceExpression; if (th != null) { var ty = th.GetParent<TypeDeclaration> (); var memName = t.MemberName; foreach (var m in ty.Members.Where (x => x.Name == memName)) { AddExpression (m); } } char.IsWhiteSpace ('d'); var tr = t.Target as TypeReferenceExpression; if (tr != null) { var tname = t.MemberName; AddType (tr.Type); var rname = GetTypeName (tr.Type); if (!string.IsNullOrEmpty (rname)) { var r = parent.Descendants.OfType<TypeDeclaration> ().FirstOrDefault (x => x.Name == rname); if (r != null) { foreach (var m in r.Members.OfType<MethodDeclaration> ().Where (x => x.Name == tname)) { AddExpression (m); } } } } } // // Look for constructors called // foreach (var t in expr.DescendantsAndSelf.OfType<ObjectCreateExpression> ()) { if (AddType (t.Type)) { var rname = GetTypeName (t.Type); if (!string.IsNullOrEmpty (rname)) { var r = parent.Descendants.OfType<TypeDeclaration> ().FirstOrDefault (x => x.Name == rname); if (r != null) { // // Add the ctor // foreach (var m in r.Members.Where (x => x.Name.StartsWith ("constructor", StringComparison.Ordinal))) { AddExpression (m); } // // Add the initialized fields // foreach (var i in r.Members.OfType<FieldDeclaration> () .Where (x => !x.HasModifier (Modifiers.Static)) .SelectMany (x => x.Variables, (x,y) => y.Initializer) .Where (x => !x.IsNull)) { AddExpression (i); } } } } } // // Grab loose ends // // foreach (var t in expr.DescendantsAndSelf.OfType<TypeReferenceExpression> ()) // AddType (t.Type); } bool AddType (AstType type) { var st = type as SimpleType; if (st != null) { if (!ReferencedTypes.Contains (st.Identifier)) { ReferencedTypes.Add (st.Identifier); return true; } } return false; } string GetTypeName (AstType type) { var st = type as SimpleType; if (st != null) { return st.Identifier; } return null; } public bool UsesType (TypeDeclaration type) { return ReferencedTypes.Contains (type.Name); } } static bool SameType (TypeDeclaration otherType, AstType type) { var st = type as SimpleType; return st != null && st.Identifier == otherType.Name; } } class AvoidTrickyJsKeywords : DepthFirstAstVisitor, IAstTransform { readonly HashSet<string> keywords = new HashSet<string> { "arguments", }; public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var badPs = methodDeclaration.Parameters.Where (x => keywords.Contains (x.Name)).ToList (); if (badPs.Count == 0) return; foreach (var bp in badPs) { var oldName = bp.Name; var newName = "_" + oldName; bp.Name = newName; foreach (var i in methodDeclaration.Body.Descendants.OfType<IdentifierExpression> ()) { if (i.Identifier == oldName) { i.Identifier = newName; } } } } public override void VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration) { base.VisitConstructorDeclaration (constructorDeclaration); var badPs = constructorDeclaration.Parameters.Where (x => keywords.Contains (x.Name)).ToList (); if (badPs.Count == 0) return; foreach (var bp in badPs) { var oldName = bp.Name; var newName = "_" + oldName; bp.Name = newName; foreach (var i in constructorDeclaration.Body.Descendants.OfType<IdentifierExpression> ()) { if (i.Identifier == oldName) { i.Identifier = newName; } } foreach (var i in constructorDeclaration.Initializer.Descendants.OfType<IdentifierExpression> ()) { if (i.Identifier == oldName) { i.Identifier = newName; } } } } } class MakeWhileLoop : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitLabelStatement (LabelStatement labelStatement) { base.VisitLabelStatement (labelStatement); var ifs = labelStatement.NextSibling as IfElseStatement; if (ifs == null || !ifs.FalseStatement.IsNull) return; var b = ifs.TrueStatement as BlockStatement; if (b == null || b.Statements.Count == 0) return; var gt = b.Statements.Last () as GotoStatement; if (gt == null || gt.Label != labelStatement.Label) return; if (labelStatement.GetParent<MethodDeclaration> ().Descendants.OfType<GotoStatement> ().Count () != 1) return; gt.Remove (); b.Remove (); var wh = new WhileStatement { Condition = ifs.Condition.Clone (), EmbeddedStatement = b, }; ifs.ReplaceWith (wh); labelStatement.Remove (); } } class RemoveEmptySwitch : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitSwitchStatement (SwitchStatement switchStatement) { base.VisitSwitchStatement (switchStatement); if (switchStatement.SwitchSections.Count > 0) return; if (!(switchStatement.Expression is IdentifierExpression)) return; switchStatement.Remove (); } } class GotoRemoval : DepthFirstAstVisitor, IAstTransform { static int nextId = 1; public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (new MoveLabelsOutOfTry ()); compilationUnit.AcceptVisitor (this); } // OMG OMG HACK: Goto removal is a deep dark problem that I continually fail // at solving. So here is the trick: we transform the method until it's in a // simple form whose gotos can be replicated with a JS labelled loop. // Problem is, those transforms are very finicky. Some work well on some methods // while causing problems on others. So we try a variety of transforms hoping that // at least one set will work. readonly IAstVisitor[][] transforms = { new IAstVisitor[] { }, new IAstVisitor[] { new LiftLabeledSwitchSections () }, new IAstVisitor[] { new LiftLabeledSwitchSections (), new SmallInlineGoto () }, new IAstVisitor[] { new LiftLabeledSwitchSections (), new SmallInlineGoto (), new BigInlineGoto () }, new IAstVisitor[] { new LiftLabeledSwitchSections (), new AddImplicitGoto (), new BigInlineGoto () }, }; public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); // // Try to force the method into a form we can handle // var m = methodDeclaration; var gotos = m.Body.Descendants.OfType<GotoStatement> ().ToList (); if (gotos.Count == 0) return; if (HasBadLabels (m)) { foreach (var ts in transforms) { m = (MethodDeclaration)methodDeclaration.Clone (); m.AcceptVisitor (new LabelLoops ()); m.AcceptVisitor (new SwitchSectionBlocksToStatements ()); foreach (var t in ts) { m.AcceptVisitor (t); m.AcceptVisitor (new RemoveRedundantGotos ()); m.AcceptVisitor (new RemoveUnreachableStatements ()); } m.AcceptVisitor (new RemoveLabelsWithoutGotos ()); if (!HasBadLabels (m)) { break; } } if (HasBadLabels (m)) { App.Warning ("! GOTO labels at different levels in {0}.{1}(). This is not supported.", methodDeclaration.GetParent<TypeDeclaration> ().Name, methodDeclaration.Name); return; } else { methodDeclaration.ReplaceWith (m); } } // // Handle it // m.AcceptVisitor (new CreateGotoLoop ()); m.AcceptVisitor (new RewriteGotos ()); } class MoveLabelsOutOfTry : DepthFirstAstVisitor { public override void VisitLabelStatement (LabelStatement labelStatement) { base.VisitLabelStatement (labelStatement); var t = labelStatement.GetParent <TryCatchStatement> (); if (t == null) return; if (t.TryBlock.Statements.First () == labelStatement) { labelStatement.Remove (); t.Parent.InsertChildBefore (t, labelStatement, (Role<Statement>)t.Role); } } } class RewriteGotos : DepthFirstAstVisitor { public override void VisitGotoStatement (GotoStatement gotoStatement) { base.VisitGotoStatement (gotoStatement); var a = new ExpressionStatement ( new AssignmentExpression ( new IdentifierExpression ("_goto"), new IdentifierExpression (gotoStatement.Label))); var c = new ContinueStatement (); c.AddAnnotation (new LabelStatement { Label = "_GOTO_LOOP" }); gotoStatement.ReplaceWith (c); c.Parent.InsertChildBefore (c, a, (Role<Statement>)c.Role); } } class CreateGotoLoop : DepthFirstAstVisitor { public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var gotos = methodDeclaration.Body.Descendants.OfType<GotoStatement> ().ToList (); if (gotos.Count == 0) return; var loop = new WhileStatement { Condition = new PrimitiveExpression (true), }; var loopBlock = new BlockStatement (); var loopSwitch = new SwitchStatement { Expression = new IdentifierExpression ("_goto"), }; var loopLabel = new LabelStatement { Label = "_GOTO_LOOP", }; loopBlock.Statements.Add (loopSwitch); loop.EmbeddedStatement = loopBlock; var firstLabel = methodDeclaration.Body.Descendants.First (x => /*(x is GotoStatement) ||*/ (x is LabelStatement && HasGoto ((LabelStatement)x))); var stmtRole = (Role<Statement>)firstLabel.Role; var block = firstLabel.Parent; var labels = new List<Tuple<LabelStatement, List<AstNode>>> (); labels.Add (new Tuple<LabelStatement, List<AstNode>> (null, new List<AstNode> ())); var n = firstLabel.Parent.FirstChild; while (n != null && !n.IsNull) { var l = n as LabelStatement; if (l != null && gotos.Any (x => x.Label == l.Label)) { labels.Add (new Tuple<LabelStatement, List<AstNode>> (l, new List<AstNode> ())); } else { labels.Last ().Item2.Add (n); } var s = n.NextSibling; n.Remove (); n = s; } for (int i = 0; i < labels.Count; i++) { var ls = labels [i]; var sec = new SwitchSection (); sec.CaseLabels.Add (ls.Item1 != null ? new CaseLabel (new PrimitiveExpression (i)) : new CaseLabel ()); if (ls.Item2.Count == 0 || !StatementIsBranch (ls.Item2.Last ())) { if (i + 1 < labels.Count) { ls.Item2.Add (new GotoStatement (labels [i + 1].Item1.Label)); } else { var br = new BreakStatement (); br.AddAnnotation (new LabelStatement { Label = "_GOTO_LOOP" }); ls.Item2.Add (br); } } sec.Statements.AddRange (ls.Item2.OfType<Statement> ()); loopSwitch.SwitchSections.Add (sec); if (ls.Item1 != null) { block.AddChild ( new VariableDeclarationStatement (new PrimitiveType ("number"), ls.Item1.Label, new PrimitiveExpression (i)), stmtRole); } } block.AddChild ( new VariableDeclarationStatement (new PrimitiveType ("number"), "_goto", new PrimitiveExpression (0)), stmtRole); block.AddChild (loopLabel, stmtRole); block.AddChild (loop, stmtRole); } } static bool HasBadLabels (MethodDeclaration methodDeclaration) { var labels = methodDeclaration.Body.Descendants.OfType<LabelStatement> ().Where (HasGoto).ToList (); if (labels.Count == 0) return false; var labelsParent = labels [0].Parent; return labels.Any (x => x.Parent != labelsParent); } class AddImplicitGoto : DepthFirstAstVisitor { public override void VisitLabelStatement (LabelStatement labelStatement) { base.VisitLabelStatement (labelStatement); var safes = GetSafesToEnd (labelStatement); if (safes.Count < 1) return; if (StatementIsBranch (safes.Last ())) return; var n = StatementGetNextStatement ((Statement)safes.Last ()) as LabelStatement; if (n == null) return; labelStatement.Parent.InsertChildAfter (safes.Last (), new GotoStatement (n.Label), (Role<Statement>)labelStatement.Role); } } static Statement StatementGetNextStatement (Statement start) { return start.GetNextNode() as Statement; } static IfElseStatement GetParentIf (AstNode node) { var p = node.Parent; while (p != null && !p.IsNull) { var pif = p as IfElseStatement; if (pif != null) return pif; p = p.Parent; } return null; } class SwitchSectionBlocksToStatements : DepthFirstAstVisitor { public override void VisitSwitchSection (SwitchSection switchSection) { base.VisitSwitchSection (switchSection); if (switchSection.Statements.Count != 1) return; var block = switchSection.Statements.First () as BlockStatement; if (block == null) return; foreach (var s in block.Statements.ToList ()) { s.Remove (); switchSection.Statements.Add (s); } block.Remove (); } } class RemoveLabelsWithoutGotos : DepthFirstAstVisitor { public override void VisitLabelStatement (LabelStatement labelStatement) { base.VisitLabelStatement (labelStatement); if (HasGoto (labelStatement) || HasBreakto (labelStatement)) { return; } labelStatement.Remove (); } } class RemoveRedundantGotos : DepthFirstAstVisitor { public override void VisitGotoStatement (GotoStatement gotoStatement) { base.VisitGotoStatement (gotoStatement); var label = gotoStatement.NextSibling as LabelStatement; if (label != null && label.Label == gotoStatement.Label) gotoStatement.Remove (); } public override void VisitSwitchStatement (SwitchStatement switchStatement) { base.VisitSwitchStatement (switchStatement); if (switchStatement.SwitchSections.Count == 0) return; var trailingLabel = switchStatement.NextSibling as LabelStatement; if (trailingLabel == null) return; foreach (var s in switchStatement.SwitchSections) { if (s.Statements.Count == 1 && s.Statements.First () is GotoStatement && ((GotoStatement)s.Statements.First ()).Label == trailingLabel.Label) { s.Statements.First ().ReplaceWith (new BreakStatement ()); } } } } class RemoveUnreachableStatements : DepthFirstAstVisitor { public override void VisitGotoStatement (GotoStatement gotoStatement) { base.VisitGotoStatement (gotoStatement); while (gotoStatement.NextSibling != null && !gotoStatement.NextSibling.IsNull && !(gotoStatement.NextSibling.DescendantsAndSelf.OfType<LabelStatement> ().Any ())) { gotoStatement.NextSibling.Remove (); } } public override void VisitReturnStatement (ReturnStatement returnStatement) { base.VisitReturnStatement (returnStatement); while (returnStatement.NextSibling != null && !returnStatement.NextSibling.IsNull && !(returnStatement.NextSibling.DescendantsAndSelf.OfType<LabelStatement> ().Any ())) { returnStatement.NextSibling.Remove (); } } } static bool HasGoto (LabelStatement label) { var m = label.GetParent<MethodDeclaration> (); if (m == null) return false; return m.Descendants.OfType<GotoStatement> ().Any (x => x.Label == label.Label); } static bool HasBreakto (LabelStatement label) { var m = label.GetParent<MethodDeclaration> (); if (m == null) return false; return m.Descendants.OfType<BreakStatement> ().Any (x => { var l = x.Annotation<LabelStatement> (); if (l == null) return false; return l.Label == label.Label; }); } class LabelLoops : DepthFirstAstVisitor { public override void VisitBreakStatement (BreakStatement breakStatement) { base.VisitBreakStatement (breakStatement); var loop = GetOuterLoop (breakStatement); if (loop == null || loop is SwitchStatement) return; var label = GetOrAddStatementLabel (loop, "loop"); breakStatement.AddAnnotation (label); } } static Statement GetOuterLoop (Statement s) { AstNode l = s; while (l != null && !l.IsNull && !(l is ForStatement || l is WhileStatement || l is DoWhileStatement || l is SwitchStatement)) { l = l.Parent; } return l as Statement; } static LabelStatement GetOrAddStatementLabel (Statement s, string name) { var label = GetStatementLabel (s); if (label == null) { label = AddStatementLabel (s, name); } return label; } static LabelStatement GetStatementLabel (Statement s) { return s.PrevSibling as LabelStatement; } static LabelStatement AddStatementLabel (Statement s, string name) { var l = new LabelStatement { Label = "_" + name + (nextId++), }; s.Parent.InsertChildBefore (s, l, (ICSharpCode.NRefactory.Role<Statement>)s.Role); return l; } class BigInlineGoto : DepthFirstAstVisitor { public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var i = new Inline (); while (i.KeepGoing) { i.KeepGoing = false; methodDeclaration.AcceptVisitor (i); } } class Inline : DepthFirstAstVisitor { public bool KeepGoing = true; public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var inlabels = methodDeclaration.Body.Descendants.OfType<LabelStatement> ().Select (LabelIsBigInlineable).Where (x => x.Item2.Count > 0) .OrderBy (x => x.Item2.Count).ToList (); if (inlabels.Count == 0) return; KeepGoing = true; var l = inlabels[0]; var labelName = l.Item1.Label; foreach (var g in methodDeclaration.Body.Descendants.OfType<GotoStatement> ().Where (x => x.Label == labelName)) { foreach (var n in l.Item2) { g.Parent.InsertChildBefore (g, (Statement)n.Clone (), (Role<Statement>)g.Role); } g.Remove (); } l.Item1.Remove (); } } } class SmallInlineGoto : DepthFirstAstVisitor { public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var inlabels = methodDeclaration.Body.Descendants.OfType<LabelStatement> ().Select (LabelIsSmallInlineable).Where (x => x.Item2.Count > 0).ToList (); if (inlabels.Count == 0) return; foreach (var l in inlabels) { var labelName = l.Item1.Label; foreach (var g in methodDeclaration.Body.Descendants.OfType<GotoStatement> ().Where (x => x.Label == labelName)) { foreach (var n in l.Item2) { g.Parent.InsertChildBefore (g, (Statement)n.Clone (), (Role<Statement>)g.Role); } g.Remove (); } l.Item1.Remove (); } } } static List<AstNode> GetSafesToEnd (LabelStatement label) { var safes = new List<AstNode> (); var s = label.NextSibling; do { if (StatementIsBranch (s)) { safes.Add (s); return safes; } else if (StatementIsSafe (s)) { safes.Add (s); s = s.NextSibling; } else { safes.Clear (); return safes; } } while (s != null && !s.IsNull); return safes; } static Tuple<LabelStatement, List<AstNode>> LabelIsBigInlineable (LabelStatement label) { var safes = new List<AstNode> (); var s = label.NextSibling; do { if (StatementIsBranch (s)) { safes.Add (s); return Tuple.Create (label, safes); } else if (StatementIsSafe (s)) { safes.Add (s); s = s.NextSibling; } else { safes.Clear (); return Tuple.Create (label, safes); } } while (s != null && !s.IsNull); safes.Clear (); return Tuple.Create (label, safes); } static Tuple<LabelStatement, List<AstNode>> LabelIsSmallInlineable (LabelStatement label) { var safes = new List<AstNode> (); var s = label.NextSibling; if (StatementIsBranch (s)) { safes.Add (s); } else { safes.Clear (); } return Tuple.Create (label, safes); } static bool StatementIsSafe (AstNode n) { return !n.DescendantsAndSelf.Any (x => x is LabelStatement || x is SwitchStatement); } static bool StatementIsBranch (AstNode n) { if (n is ThrowStatement || n is GotoStatement || n is ReturnStatement) return true; var b = n as BreakStatement; if (b != null) { var blabel = b.Annotation<LabelStatement> (); if (blabel != null) return true; } return false; } class AddGotoLabeledSwitchSections : DepthFirstAstVisitor { public override void VisitSwitchStatement (SwitchStatement switchStatement) { base.VisitSwitchStatement (switchStatement); var labelledSections = switchStatement.SwitchSections.Where (x => x.Statements.Count > 0 && x.Statements.First () is LabelStatement).ToList (); if (labelledSections.Count == 0) return; // // Make sure the statement after the switch is labelled // so that we can branch to it // var endLabel = switchStatement.NextSibling as LabelStatement; if (endLabel == null) { endLabel = new LabelStatement { Label = "_SwitchEnd" + nextId++ }; switchStatement.Parent.InsertChildAfter ( switchStatement, endLabel, (ICSharpCode.NRefactory.Role<Statement>)switchStatement.Role); } foreach (var ls in labelledSections) { var last = ls.Statements.Last (); if (last is BreakStatement) { last.ReplaceWith (new GotoStatement (endLabel.Label)); } } } } class LiftLabeledSwitchSections : DepthFirstAstVisitor { public override void VisitSwitchStatement (SwitchStatement switchStatement) { base.VisitSwitchStatement (switchStatement); var labelledSections = switchStatement.SwitchSections.Where (x => x.Statements.Count > 0 && x.Statements.First () is LabelStatement).ToList (); if (labelledSections.Count == 0) return; // // Make sure the statement after the switch is labelled // so that we can branch to it // var endLabel = switchStatement.NextSibling as LabelStatement; if (endLabel == null) { endLabel = new LabelStatement { Label = "_SwitchEnd" + nextId++ }; switchStatement.Parent.InsertChildAfter ( switchStatement, endLabel, (ICSharpCode.NRefactory.Role<Statement>)switchStatement.Role); } foreach (var ls in labelledSections) { // // Move labeled sections out of the switch // var label = (LabelStatement)ls.Statements.First (); AstNode p = switchStatement; foreach (var s in ls.Statements) { var br = s as BreakStatement; var ns = br != null ? new GotoStatement (endLabel.Label) : s.Clone (); switchStatement.Parent.InsertChildAfter ( p, ns, (Role<Statement>)p.Role); p = ns; } // // Have the switch goto that label // ls.Statements.Clear (); ls.Statements.Add (new GotoStatement (label.Label)); } // // Remind the switch to run its next statement // if (endLabel != switchStatement.NextSibling) { switchStatement.Parent.InsertChildAfter ( switchStatement, new GotoStatement (endLabel.Label), (Role<Statement>)switchStatement.Role); } } } } class PassArraysAsEnumerables : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitInvocationExpression (InvocationExpression invocationExpression) { base.VisitInvocationExpression (invocationExpression); var md = GetMethodDef (invocationExpression); if (md == null) { return; } var i = 0; foreach (var a in invocationExpression.Arguments) { var p = md.Parameters[i]; i++; var tra = GetTypeRef (a); if (tra == null || !tra.IsArray) { continue; } var trp = p.ParameterType; if (!trp.Name.StartsWith ("IEnumerable", StringComparison.Ordinal)) { continue; } var wrap = new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType ("NArray")), "ToEnumerable"), a.Clone ()); a.ReplaceWith (wrap); } } public override void VisitVariableInitializer (VariableInitializer variableInitializer) { base.VisitVariableInitializer (variableInitializer); var tra = GetTypeRef (variableInitializer.Initializer); if (tra == null || !tra.IsArray) return; var f = variableInitializer.Parent as VariableDeclarationStatement; if (f == null) return; var st = f.Type as SimpleType; if (st == null || !st.Identifier.StartsWith ("IEnumerable", StringComparison.Ordinal)) return; var wrap = new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType ("NArray")), "ToEnumerable"), variableInitializer.Initializer.Clone ()); variableInitializer.Initializer = wrap; } } class InlineEnumMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitInvocationExpression (InvocationExpression invocationExpression) { base.VisitInvocationExpression (invocationExpression); var mr = invocationExpression.Target as MemberReferenceExpression; if (mr == null) return; var target = mr.Target; var td = GetTypeDef (target); if (td == null || !td.IsEnum) return; if (mr.MemberName == "GetHashCode") { target.Remove (); invocationExpression.ReplaceWith (target); } else if (mr.MemberName == "ToString") { target.Remove (); var idx = new IndexerExpression ( new TypeReferenceExpression (new SimpleType (td.Name)), target); invocationExpression.ReplaceWith (idx); } } } class StringConstructorsToMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression) { base.VisitObjectCreateExpression (objectCreateExpression); if (!IsString (objectCreateExpression.Type)) return; var m = new InvocationExpression ( new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType ("NString")), "FromChars"), objectCreateExpression.Arguments.Select (x => x.Clone ())); objectCreateExpression.ReplaceWith (m); } } static bool IsString (AstType type) { var pt = type as PrimitiveType; if (pt != null && pt.KnownTypeCode == KnownTypeCode.String) return true; var tr = GetTypeRef (type); return (tr != null && tr.FullName == "System.String"); } class EnsureAtLeastOneCtor : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); if (typeDeclaration.ClassType != ClassType.Class) return; if (typeDeclaration.Members.OfType<ConstructorDeclaration> ().Any ()) return; var ctor = new ConstructorDeclaration (); ctor.Name = "constructor"; ctor.Body = new BlockStatement (); ctor.Body.Add (new InvocationExpression (new BaseReferenceExpression ())); typeDeclaration.Members.Add (ctor); } } class CharsToNumbers : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitPrimitiveExpression (PrimitiveExpression primitiveExpression) { base.VisitPrimitiveExpression (primitiveExpression); if (primitiveExpression.Value is char) { var ch = (char)primitiveExpression.Value; var sch = ch.ToString (); if (ch == '\n') sch = "\\n"; if (ch == '\r') sch = "\\r"; if (ch == '\t') sch = "\\t"; primitiveExpression.Value = (int)ch; primitiveExpression.Parent.InsertChildAfter (primitiveExpression, new Comment ("'"+sch+"'", CommentType.MultiLine), Roles.Comment); } } public override void VisitIndexerExpression (IndexerExpression indexerExpression) { base.VisitIndexerExpression (indexerExpression); var t = GetTypeRef (indexerExpression.Target); if (t != null && t.FullName == "System.String") { var targ = indexerExpression.Target; targ.Remove (); var index = indexerExpression.Arguments.FirstOrNullObject (); index.Remove (); var i = new InvocationExpression ( new MemberReferenceExpression (targ, "charCodeAt"), index); indexerExpression.ReplaceWith (i); } } } class MakeSuperCtorFirst : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration) { base.VisitConstructorDeclaration (constructorDeclaration); if (constructorDeclaration.Body.IsNull) return; var hasInits = constructorDeclaration.GetParent<TypeDeclaration> ().Members.OfType<FieldDeclaration> ().Any (x => x.Variables.Any (y => !y.Initializer.IsNull)); if (!hasInits) return; var supers = constructorDeclaration.Body.Descendants.OfType<InvocationExpression> ().Where ( x => x.Target is BaseReferenceExpression).Select (x => x.GetParent<Statement> ()).ToList (); foreach (var s in supers) { s.Remove (); } if (supers.Count > 0) { constructorDeclaration.Body.Statements.InsertBefore ( constructorDeclaration.Body.Statements.FirstOrNullObject (), supers [0]); } } } class FixGenericsThatUseObject : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); if (methodDeclaration.TypeParameters.Count == 0) return; var q = from mr in methodDeclaration.Body.Descendants.OfType<MemberReferenceExpression> () where mr.MemberName == "Equals" || mr.MemberName == "ToString" || mr.MemberName == "GetHashCode" let tr = GetTypeRef (mr.Target) where tr != null && tr.IsGenericParameter select tr; var ms = q.ToList (); if (ms.Count == 0) return; foreach (var m in ms) { var c = new Constraint { TypeParameter = new SimpleType (m.Name) }; c.BaseTypes.Add (new SimpleType ("NObject")); methodDeclaration.Constraints.Add (c); } } } class RemoveNonGenericEnumerable : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); foreach (var n in typeDeclaration.BaseTypes.Where (x => IsType (x, "IEnumerable") || IsType (x, "IEnumerator"))) { n.Remove (); } foreach (var n in typeDeclaration.Members.OfType<MethodDeclaration> ().Where (x => IsType (x.PrivateImplementationType, "IEnumerable") || IsType (x.PrivateImplementationType, "IEnumerator"))) { n.Remove (); } foreach (var n in typeDeclaration.Members.OfType<PropertyDeclaration> ().Where (x => IsType (x.PrivateImplementationType, "IEnumerable") || IsType (x.PrivateImplementationType, "IEnumerator"))) { n.Remove (); } } static bool IsType (AstType type, string typeName) { var st = type as SimpleType; return st != null && st.Identifier == typeName && st.TypeArguments.Count == 0; } } class RemovePrivateInterfaceOverloads : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); var mgs = typeDeclaration.Members.OfType<MethodDeclaration> ().GroupBy (x => x.Name); foreach (var mse in mgs) { var ms = mse.ToList (); var hasNorms = ms.Any (x => x.PrivateImplementationType.IsNull); var hasPrivs = ms.Any (x => !x.PrivateImplementationType.IsNull); if (hasPrivs) { if (hasNorms) { // // If we already have a public def, kill these private ones // foreach (var m in ms.Where (x => !x.PrivateImplementationType.IsNull)) { m.Remove (); } } else { foreach (var m in ms.Where (x => !x.PrivateImplementationType.IsNull)) { m.PrivateImplementationType.Remove (); } } } } } } class RemoveGenericArgsInIsExpr : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitIsExpression (IsExpression isExpression) { base.VisitIsExpression (isExpression); var st = isExpression.Type as SimpleType; if (st != null && st.TypeArguments.Count > 0) { var nt = (SimpleType)st.Clone (); nt.TypeArguments.Clear (); } } } class RemoveDelegateConstructors : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression) { base.VisitObjectCreateExpression (objectCreateExpression); var td = GetTypeDef (objectCreateExpression.Type); if (td == null || !IsDelegate (td) || objectCreateExpression.Arguments.Count != 1) return; var a = objectCreateExpression.Arguments.First (); a.Remove (); objectCreateExpression.ReplaceWith (a); } public override void VisitAssignmentExpression (AssignmentExpression assignmentExpression) { base.VisitAssignmentExpression (assignmentExpression); if (assignmentExpression.Operator != AssignmentOperatorType.Add && assignmentExpression.Operator != AssignmentOperatorType.Subtract) return; var t = assignmentExpression.Left.Annotation<EventDefinition> (); if (t == null) return; var left = assignmentExpression.Left; var right = assignmentExpression.Right; left.Remove (); right.Remove (); var isAdd = assignmentExpression.Operator == AssignmentOperatorType.Add; var m = new InvocationExpression ( new MemberReferenceExpression (left, isAdd ? "Add" : "Remove"), right); assignmentExpression.ReplaceWith (m); } } class BitwiseOrToConditionalForBooleans : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression) { base.VisitBinaryOperatorExpression (binaryOperatorExpression); if (binaryOperatorExpression.Operator != BinaryOperatorType.BitwiseOr) return; var leftT = GetTypeRef (binaryOperatorExpression.Left); if (leftT != null && leftT.FullName == "System.Boolean") { binaryOperatorExpression.Operator = BinaryOperatorType.ConditionalOr; } } } class ReplaceInstanceMembers : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) { base.VisitMemberReferenceExpression (memberReferenceExpression); var tre = memberReferenceExpression.Target as TypeReferenceExpression; if (tre != null) { var p = tre.Type as PrimitiveType; if (p != null) { if (p.KnownTypeCode == KnownTypeCode.String) { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NString")); } else if (p.KnownTypeCode == KnownTypeCode.Boolean) { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NBoolean")); } else if (p.KnownTypeCode == KnownTypeCode.Char) { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NChar")); } else if (p.KnownTypeCode == KnownTypeCode.Object) { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NObject")); } else if (GetJsConstructor (p) == "Number") { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NNumber")); } } else { var tr = tre != null ? GetTypeRef (tre.Type) : null; var name = tr != null ? tr.FullName : ""; if (name == "System.Math") { switch (memberReferenceExpression.MemberName) { case "Abs": memberReferenceExpression.MemberName = "abs"; break; case "Sqrt": memberReferenceExpression.MemberName = "sqrt"; break; case "Exp": memberReferenceExpression.MemberName = "exp"; break; case "Pow": memberReferenceExpression.MemberName = "pow"; break; case "Floor": memberReferenceExpression.MemberName = "floor"; break; case "Ceiling": memberReferenceExpression.MemberName = "ceil"; break; case "Cos": memberReferenceExpression.MemberName = "cos"; break; case "Acos": memberReferenceExpression.MemberName = "acos"; break; case "Sin": memberReferenceExpression.MemberName = "sin"; break; case "Asin": memberReferenceExpression.MemberName = "asin"; break; case "Atan": memberReferenceExpression.MemberName = "atan"; break; case "Atan2": memberReferenceExpression.MemberName = "atan2"; break; case "Tan": memberReferenceExpression.MemberName = "tan"; break; case "Min": memberReferenceExpression.MemberName = "min"; break; case "Max": memberReferenceExpression.MemberName = "max"; break; default: memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NMath")); break; } } else if (name == "System.Array") { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NArray")); } else if (name == "System.Console") { memberReferenceExpression.Target = new TypeReferenceExpression (new SimpleType ("NConsole")); } } } else { } } public override void VisitInvocationExpression (InvocationExpression invocationExpression) { base.VisitInvocationExpression (invocationExpression); var memberReferenceExpression = invocationExpression.Target as MemberReferenceExpression; if (memberReferenceExpression == null) return; var t = GetTypeRef (memberReferenceExpression.Target); if (t == null) return; HashSet<string> repls = null; string newTypeName = null; if (t.FullName == "System.Object") { repls = objectRepls; newTypeName = "NObject"; } else if (t.FullName == "System.String") { repls = stringRepls; newTypeName = "NString"; } else if (t.FullName == "System.Boolean") { repls = boolRepls; newTypeName = "NBoolean"; } else if (t != null && t.IsPrimitive) { repls = numberRepls; newTypeName = "NNumber"; } if (repls != null && repls.Contains (memberReferenceExpression.MemberName)) { if (memberReferenceExpression.MemberName == "Equals") { var left = memberReferenceExpression.Target; var right = invocationExpression.Arguments.First (); left.Remove (); right.Remove (); invocationExpression.ReplaceWith (new BinaryOperatorExpression (left, BinaryOperatorType.Equality, right)); } else { var newName = memberReferenceExpression.MemberName; if (newTypeName == "NObject") { newName = "Generic" + newName; } var n = new InvocationExpression ( new MemberReferenceExpression ( new TypeReferenceExpression (new SimpleType (newTypeName)), newName), new Expression[] { memberReferenceExpression.Target.Clone () } .Concat (invocationExpression.Arguments.Select (x => x.Clone ()))); var td = t.Resolve (); var meth = td.Methods.First (x => x.Name == memberReferenceExpression.MemberName); n.AddAnnotation (meth.ReturnType); invocationExpression.ReplaceWith (n); } } } } static HashSet<string> objectRepls = new HashSet<string> { "GetHashCode", "ToString", }; static HashSet<string> numberRepls = new HashSet<string> { "GetHashCode", "ToString", }; static HashSet<string> boolRepls = new HashSet<string> { "GetHashCode", "ToString", }; static HashSet<string> stringRepls = new HashSet<string> { "ToLowerInvariant", "ToUpperInvariant", "GetHashCode", "Replace", "IndexOf", "IndexOfAny", "StartsWith", "EndsWith", "Substring", "Trim", "TrimStart", "TrimEnd", "Equals", "Remove", "Contains", "Split", }; class SuperPropertiesToThis : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) { base.VisitMemberReferenceExpression (memberReferenceExpression); var s = memberReferenceExpression.Target as BaseReferenceExpression; if (s != null) { if (memberReferenceExpression.Annotation<PropertyDefinition>() != null || memberReferenceExpression.Annotation<PropertyReference>() != null) { memberReferenceExpression.Target = new ThisReferenceExpression (); } } } } class FixIsOp : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitIsExpression (IsExpression isExpression) { base.VisitIsExpression (isExpression); var p = isExpression.Type as PrimitiveType; if (p != null) { var e = isExpression.Expression; e.Remove (); var n = new BinaryOperatorExpression ( new MemberReferenceExpression (e, "constructor"), BinaryOperatorType.Equality, new TypeReferenceExpression (GetJsConstructorType (isExpression.Type))); isExpression.ReplaceWith (n); } } } class ExpandIndexers : IAstTransform { public void Run (AstNode compilationUnit) { var ei = new EI (); ei.Changed = true; while (ei.Changed) { ei.Changed = false; compilationUnit.AcceptVisitor (ei); } } class EI : DepthFirstAstVisitor { public bool Changed = false; public override void VisitIndexerExpression (IndexerExpression indexerExpression) { base.VisitIndexerExpression (indexerExpression); var tr = GetTypeRef (indexerExpression.Target); if (tr != null && (tr.IsArray || tr.FullName == "System.String")) return; var t = indexerExpression.Target; var pa = indexerExpression.Parent as AssignmentExpression; if (pa != null && pa.Left == indexerExpression) { var s = new InvocationExpression ( new MemberReferenceExpression (t.Clone(), "set_Item"), indexerExpression.Arguments.Concat (new[]{pa.Right.Clone()}).Select (x => x.Clone ())); pa.ReplaceWith (s); } else { var s = new InvocationExpression ( new MemberReferenceExpression (t.Clone(), "get_Item"), indexerExpression.Arguments.Select (x => x.Clone ())); indexerExpression.ReplaceWith (s); } Changed = true; } } } class ExpandOperators : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression) { base.VisitBinaryOperatorExpression (binaryOperatorExpression); var leftT = GetTypeDef (binaryOperatorExpression.Left); if (leftT != null && !(leftT.IsPrimitive || leftT.FullName=="System.String")) { var name = ""; switch (binaryOperatorExpression.Operator) { case BinaryOperatorType.Add: name = "op_Addition"; break; case BinaryOperatorType.Subtract: name = "op_Subtraction"; break; case BinaryOperatorType.Multiply: name = "op_Multiply"; break; case BinaryOperatorType.Divide: name = "op_Division"; break; case BinaryOperatorType.Equality: name = "op_Equality"; break; case BinaryOperatorType.InEquality: name = "op_Inequality"; break; case BinaryOperatorType.LessThan: name = "op_LessThan"; break; case BinaryOperatorType.LessThanOrEqual: name = "op_LessThanOrEqual"; break; case BinaryOperatorType.GreaterThan: name = "op_GreaterThan"; break; case BinaryOperatorType.GreaterThanOrEqual: name = "op_GreaterThanOrEqual"; break; } var m = FindMethod (leftT, name); if (m != null && m.DeclaringType.FullName != "System.MulticastDelegate") { var left = binaryOperatorExpression.Left; var right = binaryOperatorExpression.Right; left.Remove (); right.Remove (); var n = new InvocationExpression ( new MemberReferenceExpression (new IdentifierExpression (leftT.Name), name), left, right); n.AddAnnotation (m.ReturnType); binaryOperatorExpression.ReplaceWith (n); } } } } static MethodDefinition FindMethod (TypeDefinition type, string name) { if (string.IsNullOrEmpty (name)) return null; var t = type; var m = t.Methods.FirstOrDefault (x => x.Name == name); while (m == null && t != null) { t = t.BaseType as TypeDefinition; if (t != null) { m = t.Methods.FirstOrDefault (x => x.Name == name); } } return m; } static TypeDefinition GetTypeDef (AstNode expr) { var tr = GetTypeRef (expr); var td = tr as TypeDefinition; if (td == null && tr != null) td = tr.Resolve (); return td; } static TypeReference GetTypeRef (AstNode expr) { var anno = GetAnnotationType (expr); if (expr is InvocationExpression invoke && invoke.Target is MemberReferenceExpression member && member.MemberName.StartsWith ("op_")) { var argTypes = invoke.Arguments.Select (x => GetTypeRef (x)).ToList (); var declType = GetTypeDef (member.Target) ?? anno?.Resolve (); var methodDefs = declType?.Methods .Where (x => x.Name == member.MemberName && x.Parameters.Count == argTypes.Count) .OrderByDescending (x => x.Parameters.Zip(argTypes, (p,a)=>(p.ParameterType,a)).Count (z => z.a?.FullName == z.ParameterType?.FullName)); var methodDef = methodDefs?.FirstOrDefault (); if (methodDef != null) return methodDef.ReturnType; } if (anno != null) return anno; if (expr is IndexerExpression ie) { var it = GetTypeRef (ie.Target); if (it != null && it.IsArray) { return it.GetElementType (); } } return null; } static TypeReference GetAnnotationType (AstNode expr) { var td = expr.Annotation<TypeDefinition> (); if (td != null) { return td; } var tr = expr.Annotation<TypeReference> (); if (tr != null) { return tr; } var ti = expr.Annotation<ICSharpCode.Decompiler.Ast.TypeInformation> (); if (ti != null) { return ti.InferredType; } var ilv = expr.Annotation<ICSharpCode.Decompiler.ILAst.ILVariable> (); if (ilv != null) { return ilv.Type; } var fr = expr.Annotation<FieldDefinition> (); if (fr != null) { return fr.FieldType; } var pr = expr.Annotation<PropertyDefinition> (); if (pr != null) { return pr.PropertyType; } return null; } class AccessorsToInvocations : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { if (ES3Compatible) // otherwise usual accessors are used { compilationUnit.AcceptVisitor (this); } } public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) { base.VisitMemberReferenceExpression (memberReferenceExpression); var methodDef = GetMethodDef (memberReferenceExpression); // condition for blocking transformation of `String.length` to `String.Getlength()` in ES3Compatible mode var pd = memberReferenceExpression.Annotation<PropertyDefinition>(); if (pd != null) { var tt = pd.DeclaringType; if (tt.FullName == "System.String") { return; } } if (methodDef != null && methodDef.IsGetter) { var getterInvocation = new InvocationExpression ( new MemberReferenceExpression ( memberReferenceExpression.Target.Clone (), ES3GetterPrefix + memberReferenceExpression.MemberName)); memberReferenceExpression.ReplaceWith (getterInvocation); } } public override void VisitAssignmentExpression (AssignmentExpression assignmentExpression) { base.VisitAssignmentExpression (assignmentExpression); var leftExpression = assignmentExpression.Left as MemberReferenceExpression; if (leftExpression != null) { var methodDef = GetMethodDef (leftExpression); if (methodDef != null && methodDef.IsSetter) { var setterInvocation = new InvocationExpression ( new MemberReferenceExpression ( leftExpression.Target.Clone (), ES3SetterPrefix + leftExpression.MemberName), assignmentExpression.Right.Clone ()); assignmentExpression.ReplaceWith (setterInvocation); } } } } class Renames : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) { base.VisitMemberReferenceExpression (memberReferenceExpression); if (memberReferenceExpression.MemberName == "Length") { var tt = GetTargetTypeRef (memberReferenceExpression); if (tt != null) { if (tt.IsArray || tt.FullName == "System.String") { memberReferenceExpression.MemberName = "length"; } } } } TypeReference GetTargetTypeRef (MemberReferenceExpression memberReferenceExpression) { var pd = memberReferenceExpression.Annotation<PropertyDefinition> (); if (pd != null) { return pd.DeclaringType; } var fd = memberReferenceExpression.Annotation<FieldDefinition> (); if (fd == null) fd = memberReferenceExpression.Annotation<FieldReference> () as FieldDefinition; if (fd != null) { return fd.DeclaringType; } return GetTypeRef (memberReferenceExpression.Target); } } class RemoveEnumBaseType : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); if (typeDeclaration.ClassType == ClassType.Enum) { typeDeclaration.BaseTypes.Clear (); } } } class RemoveConstraints : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); methodDeclaration.Constraints.Clear (); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); typeDeclaration.Constraints.Clear (); } } class FixBadNames : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitIdentifier (Identifier identifier) { base.VisitIdentifier (identifier); var o = identifier.Name; var n = o.Replace ('<', '_').Replace ('>', '_'); if (n != o) { identifier.Name = n; } else { if (o == "arguments") { identifier.Name = "$arguments"; } } } } class FlattenNamespaces : IAstTransform { public void Run (AstNode compilationUnit) { var ns = compilationUnit.Children.OfType<NamespaceDeclaration> (); foreach (var d in ns.SelectMany (x => x.Members)) { d.Remove (); compilationUnit.AddChild (d, SyntaxTree.MemberRole); } foreach (var n in ns) { n.Remove (); } } } class MakePrimitiveTypesJsTypes : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public static PrimitiveType GetPrimitiveTypeReplacement (PrimitiveType primitiveType) { switch (primitiveType.KnownTypeCode) { case KnownTypeCode.Object: return new PrimitiveType ("any"); case KnownTypeCode.Boolean: return new PrimitiveType ("boolean"); case KnownTypeCode.String: return new PrimitiveType ("string"); case KnownTypeCode.Char: return new PrimitiveType ("number"); case KnownTypeCode.Void: return new PrimitiveType ("void"); case KnownTypeCode.Byte: case KnownTypeCode.SByte: case KnownTypeCode.Int16: case KnownTypeCode.Int32: case KnownTypeCode.Int64: case KnownTypeCode.IntPtr: case KnownTypeCode.UInt16: case KnownTypeCode.UInt32: case KnownTypeCode.UInt64: case KnownTypeCode.Decimal: case KnownTypeCode.Single: case KnownTypeCode.Double: return new PrimitiveType ("number"); } switch (primitiveType.Keyword) { case "String": return new PrimitiveType ("string"); case "Boolean": case "boolean": return new PrimitiveType ("boolean"); case "Number": case "number": return new PrimitiveType ("number"); case "any": case "Object": return new PrimitiveType ("any"); default: throw new NotSupportedException (primitiveType.Keyword); } } public override void VisitPrimitiveType (PrimitiveType primitiveType) { base.VisitPrimitiveType (primitiveType); primitiveType.ReplaceWith (GetPrimitiveTypeReplacement (primitiveType)); } public override void VisitSimpleType (SimpleType simpleType) { base.VisitSimpleType (simpleType); if (simpleType.Identifier == "IntPtr") { simpleType.ReplaceWith (new PrimitiveType ("number")); } } } class AddReferences : IAstTransform { public void Run (AstNode compilationUnit) { var filename = ES3Compatible ? "mscorlib.es3.ts" : "mscorlib.ts"; var c = new Comment (string.Format("/<reference path='{0}'/>", filename)); compilationUnit.InsertChildBefore (compilationUnit.FirstChild, c, Roles.Comment); } } class StructToClass : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); if (typeDeclaration.ClassType == ClassType.Struct) { typeDeclaration.ClassType = ClassType.Class; } } // TODO: Introduce Clone } class IndexersToMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration) { base.VisitIndexerDeclaration (indexerDeclaration); if (!indexerDeclaration.Getter.IsNull) { var g = indexerDeclaration.Getter; var m = new MethodDeclaration { Name = "get_Item", ReturnType = indexerDeclaration.ReturnType.Clone (), }; m.Parameters.AddRange (indexerDeclaration.Parameters.Select (x => (ParameterDeclaration)x.Clone ())); var b = g.Body; b.Remove (); m.Body = b; indexerDeclaration.GetParent <TypeDeclaration> ().Members.InsertBefore (indexerDeclaration, m); } if (!indexerDeclaration.Setter.IsNull) { var g = indexerDeclaration.Setter; var m = new MethodDeclaration { Name = "set_Item", ReturnType = new PrimitiveType ("void"), }; m.Parameters.AddRange (indexerDeclaration.Parameters.Select (x => (ParameterDeclaration)x.Clone ())); m.Parameters.Add (new ParameterDeclaration { Name = "value", Type = indexerDeclaration.ReturnType.Clone (), }); var b = g.Body; b.Remove (); m.Body = b; indexerDeclaration.GetParent <TypeDeclaration> ().Members.InsertBefore (indexerDeclaration, m); } indexerDeclaration.Remove (); } } class ReplaceDefault : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitDefaultValueExpression (DefaultValueExpression defaultValueExpression) { base.VisitDefaultValueExpression (defaultValueExpression); var ctor = GetJsConstructor (defaultValueExpression.Type); object val = null; switch (ctor) { case "Number": val = 0; break; case "Boolean": val = false; break; } defaultValueExpression.ReplaceWith (new PrimitiveExpression (val)); } } class MakeNullableExplicit : IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (new FixAssignments ()); compilationUnit.AcceptVisitor (new ComposedToNullable ()); } class FixAssignments : DepthFirstAstVisitor { public override void VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement) { base.VisitVariableDeclarationStatement (variableDeclarationStatement); var composedType = variableDeclarationStatement.Type as ComposedType; if (composedType == null) return; if (!composedType.HasNullableSpecifier) return; foreach (var v in variableDeclarationStatement.Variables) { if (!v.Initializer.IsNull && v.Initializer is NullReferenceExpression) { var st = new SimpleType ("Nullable", composedType.BaseType.Clone ()); v.Initializer = new ObjectCreateExpression (st); } } } } class ComposedToNullable : DepthFirstAstVisitor { public override void VisitComposedType (ComposedType composedType) { base.VisitComposedType (composedType); if (!composedType.HasNullableSpecifier) return; composedType.BaseType = new SimpleType ("Nullable", composedType.BaseType.Clone ()); if (composedType.ArraySpecifiers.Count == 0) composedType.ReplaceWith (composedType.BaseType); } } } class AnonymousInitializersNeedNames : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitAnonymousTypeCreateExpression (AnonymousTypeCreateExpression anonymousTypeCreateExpression) { base.VisitAnonymousTypeCreateExpression (anonymousTypeCreateExpression); foreach (var init in anonymousTypeCreateExpression.Initializers.ToList ()) { var ident = init as IdentifierExpression; if (ident != null) { init.ReplaceWith (new NamedExpression (ident.Identifier, ident.Clone ())); } } } } class FixCatches : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTryCatchStatement (TryCatchStatement tryCatchStatement) { base.VisitTryCatchStatement (tryCatchStatement); var catches = tryCatchStatement.CatchClauses.ToList (); if (catches.Count == 0) return; var varName = catches.Where (x => !string.IsNullOrEmpty (x.VariableName)).Select (x => x.VariableName).FirstOrDefault (); if (varName == null) { varName = "_ex"; } // // Fix first // foreach (var c in catches) { if (string.IsNullOrEmpty (c.VariableName)) { c.VariableName = varName; } } // // Merge them // if (catches.Count > 0) { var body = new BlockStatement (); var newCatch = new CatchClause { VariableName = varName, Body = body, }; IfElseStatement lastIf = null; foreach (var c in catches) { var cbody = c.Body; cbody.Remove (); var iff = new IfElseStatement (GetNotNullTypeCheck (varName, c.Type), cbody); if (lastIf == null) body.Add (iff); else lastIf.FalseStatement = iff; lastIf = iff; c.Remove (); } var rethrow = new ThrowStatement (new IdentifierExpression (varName)); if (lastIf == null) body.Add (rethrow); else lastIf.FalseStatement = rethrow; tryCatchStatement.CatchClauses.Add (newCatch); } } } class FixEmptyThrow : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitThrowStatement (ThrowStatement throwStatement) { base.VisitThrowStatement (throwStatement); if (throwStatement.Expression.IsNull) { var cc = throwStatement.GetParent<CatchClause> (); if (cc != null) { throwStatement.Expression = new IdentifierExpression (cc.VariableName); } } } } static Expression GetNotNullTypeCheck (string id, AstType type) { return new IsExpression { Expression = new IdentifierExpression (id), Type = type.Clone (), }; } class OperatorDeclsToMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration) { base.VisitOperatorDeclaration (operatorDeclaration); var newm = new MethodDeclaration { Name = GetOpName (operatorDeclaration.OperatorType), Modifiers = operatorDeclaration.Modifiers, ReturnType = operatorDeclaration.ReturnType.Clone (), }; newm.Parameters.AddRange (operatorDeclaration.Parameters.Select (x => (ParameterDeclaration)x.Clone ())); var body = operatorDeclaration.Body; body.Remove (); newm.Body = body; operatorDeclaration.ReplaceWith (newm); } static string GetOpName(OperatorType op) { return "op_" + op; } } class InlineDelegates : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitDelegateDeclaration (DelegateDeclaration delegateDeclaration) { base.VisitDelegateDeclaration (delegateDeclaration); delegateDeclaration.Remove (); } public override void VisitSimpleType (SimpleType simpleType) { base.VisitSimpleType (simpleType); var td = GetTypeDef (simpleType); if (td == null || !IsDelegate (td)) { return; } var subs = new Dictionary<string, AstType> (); var invoke = td.Methods.First (x => x.Name == "Invoke"); if (simpleType.TypeArguments.Count > 0) { var ps = td.GenericParameters; var i = 0; foreach (var a in simpleType.TypeArguments) { subs [ps [i].Name] = a; i++; } } var nt = new FunctionType (); foreach (var p in invoke.Parameters) { var pt = p.ParameterType.IsGenericParameter ? subs [p.ParameterType.Name] : GetTsType (p.ParameterType); nt.Parameters.Add (new ParameterDeclaration (pt.Clone (), p.Name)); } nt.ReturnType = invoke.ReturnType.IsGenericParameter ? subs [invoke.ReturnType.Name] : GetTsType (invoke.ReturnType); if (nt.ReturnType is PrimitiveType) { nt.ReturnType = MakePrimitiveTypesJsTypes.GetPrimitiveTypeReplacement ((PrimitiveType)nt.ReturnType); } foreach (var p in nt.Parameters) { if (p.Type is PrimitiveType) { p.Type = MakePrimitiveTypesJsTypes.GetPrimitiveTypeReplacement ((PrimitiveType)p.Type); } } nt.AddAnnotation (td); simpleType.ReplaceWith (nt); } } static AstType GetTsType (TypeReference tr) { AstType r; switch (tr.FullName) { case "System.Object": r = new PrimitiveType ("any"); break; case "System.String": r = new PrimitiveType ("string"); break; case "System.Void": r = new PrimitiveType ("void"); break; case "System.Boolean": r = new PrimitiveType ("boolean"); break; case "System.Decimal": case "System.Single": case "System.Double": case "System.Byte": case "System.SByte": case "System.Int16": case "System.Int32": case "System.Int64": case "System.UInt16": case "System.UInt32": case "System.UInt64": case "System.IntPtr": r = new PrimitiveType ("number"); break; default: if (tr.IsGenericInstance) { var git = (GenericInstanceType)tr; var st = new SimpleType (git.Name.Substring (0, git.Name.IndexOf ('`'))); st.TypeArguments.AddRange (git.GenericArguments.Select (x => GetTsType (x))); r = st; } else { r = new SimpleType (tr.Name); } break; } r.AddAnnotation (tr); return r; } static TypeDefinition GetTypeDef (AstType type) { var td = type.Annotation<TypeDefinition> (); if (td == null) { var tr = type.Annotation<TypeReference> (); if (tr != null) { td = tr.Resolve (); } } return td; } static TypeReference GetTypeRef (AstType type) { return type.Annotation<TypeDefinition> () as TypeReference ?? type.Annotation<TypeReference> (); } public static bool IsDelegate(TypeDefinition typeDefinition) { if (typeDefinition == null || typeDefinition.BaseType == null) { return false; } return typeDefinition.BaseType.FullName == "System.MulticastDelegate"; } class FixEvents : IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (new FixEvents1 ()); compilationUnit.AcceptVisitor (new FixEvents2 ()); } class FixEvents1 : DepthFirstAstVisitor { public override void VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement) { base.VisitVariableDeclarationStatement (variableDeclarationStatement); foreach (var v in variableDeclarationStatement.Variables) { if (v.Initializer.IsNull || !IsEventRef (v.Initializer)) continue; var wrap = new InvocationExpression (new MemberReferenceExpression ( v.Initializer.Clone (), "ToMulticastFunction")); v.Initializer = wrap; } } } class FixEvents2 : DepthFirstAstVisitor { public override void VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration) { base.VisitCustomEventDeclaration (eventDeclaration); var fd = new FieldDeclaration { Name = eventDeclaration.Name, ReturnType = new SimpleType ("NEvent", eventDeclaration.ReturnType.Clone ()), }; fd.Variables.Add (new VariableInitializer ( eventDeclaration.Name, IsInterface (eventDeclaration.GetParent<TypeDeclaration> ()) ? null : new ObjectCreateExpression (new SimpleType ("NEvent", eventDeclaration.ReturnType.Clone ())))); eventDeclaration.ReplaceWith (fd); } public override void VisitEventDeclaration (EventDeclaration eventDeclaration) { base.VisitEventDeclaration (eventDeclaration); var fd = new FieldDeclaration { Name = eventDeclaration.Name, ReturnType = new SimpleType ("NEvent", eventDeclaration.ReturnType.Clone ()), }; foreach (var v in eventDeclaration.Variables) { fd.Variables.Add (new VariableInitializer ( v.Name, IsInterface (eventDeclaration.GetParent<TypeDeclaration> ()) ? null : new ObjectCreateExpression (new SimpleType ("NEvent", eventDeclaration.ReturnType.Clone ())))); } eventDeclaration.ReplaceWith (fd); } } static bool IsEventRef (Expression expr) { var fd = expr.Annotation<FieldDefinition> (); if (fd == null) return false; var t = expr.GetParent<TypeDeclaration> (); if (t == null) return false; var f = t.Members.FirstOrDefault (x => x.Name == fd.Name); if (f == null) return false; return f is CustomEventDeclaration || f is EventDeclaration; } } class AddAbstractMethodBodies : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); if (methodDeclaration.Body.IsNull && methodDeclaration.GetParent<TypeDeclaration> ().ClassType != ClassType.Interface ) { var block = new BlockStatement (); block.Add (new ThrowStatement (new ObjectCreateExpression (new SimpleType ("NotSupportedException")))); methodDeclaration.Body = block; } } } class RemoveAttributes : IAstTransform { public void Run (AstNode compilationUnit) { foreach (var a in compilationUnit.Children.OfType<AttributeSection> ()) { a.Remove (); } } } class LiftNestedClasses : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); var children = typeDeclaration.Children.OfType<TypeDeclaration> ().ToList (); if (children.Count == 0) return; foreach (var n in children) { n.Remove (); if (typeDeclaration.TypeParameters.Count > 0) { if (n.TypeParameters.Count > 0) { App.Warning ("WARNING Nested class is generic and so is its parent. This is not supported."); n.TypeParameters.AddRange (typeDeclaration.TypeParameters.Select (x => (TypeParameterDeclaration)x.Clone ())); } } n.Name = typeDeclaration.Name + "_" + n.Name; typeDeclaration.Parent.InsertChildAfter (typeDeclaration, n, NamespaceDeclaration.MemberRole); } // // Need to make all the privates public // foreach (var m in typeDeclaration.Members) { m.Modifiers &= ~(Modifiers.Private); } } public override void VisitMemberType (MemberType memberType) { base.VisitMemberType (memberType); AstNodeCollection<AstType> args = memberType.TypeArguments; var mems = new Stack<MemberType> (); var t = (AstType)memberType; var mem = memberType; while (mem != null) { mems.Push (mem); if (args.Count == 0) args = mem.TypeArguments; t = mem.Target; mem = t as MemberType; } var newName = ""; var simp = t as SimpleType; if (simp != null) { if (args.Count == 0) args = simp.TypeArguments; newName += (simp.Identifier); } else { t.AcceptVisitor (this); } while (mems.Count > 0) { var mm = mems.Pop (); newName += ("_" + mm.MemberName); } var newType = new SimpleType (newName, args.Select (x => x.Clone ())); var td = memberType.Annotation<TypeDefinition> (); if (td != null) { newType.AddAnnotation (td); } memberType.ReplaceWith (newType); } } static bool IsRefParam (ParameterDeclaration x) { return (x.ParameterModifier == ParameterModifier.Ref || x.ParameterModifier == ParameterModifier.Out); } class WrapRefArgs : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var hasRefs = methodDeclaration.Parameters.Any (IsRefParam); if (!hasRefs) return; var sub = new Substitute (); foreach (var p in methodDeclaration.Parameters.Where (IsRefParam).ToList ()) { var pcompty = p.Type as ComposedType; if (pcompty == null) continue; var pty = pcompty.BaseType; var access = new IndexerExpression (new IdentifierExpression (p.Name), new PrimitiveExpression (0)); var ptd = GetTypeDef (pty); if (ptd != null) access.AddAnnotation (ptd); sub.Subs [p.Name] = access; p.ParameterModifier = ParameterModifier.None; var c = new ComposedType { BaseType = p.Type.Clone (), }; c.ArraySpecifiers.Add (new ArraySpecifier (1)); p.Type = c; } methodDeclaration.Body.AcceptVisitor (sub); } public override void VisitInvocationExpression (InvocationExpression invocationExpression) { base.VisitInvocationExpression (invocationExpression); var hasRefs = invocationExpression.Arguments.OfType<DirectionExpression> ().Any (); if (hasRefs) { var args = invocationExpression.Arguments.OfType<DirectionExpression> ().ToList (); var target = invocationExpression.Target; var lblock = new BlockStatement { }; for (int i = 0; i < args.Count; i++) { var a = args [i]; var vname = "_p" + i; var va = new VariableDeclarationStatement (AstType.Null, vname, new ArrayCreateExpression { Initializer = new ArrayInitializerExpression (a.Expression.Clone ()) }); a.ReplaceWith (new IdentifierExpression (vname)); lblock.Add (va); } var rname = "_r"; var ra = new VariableDeclarationStatement (AstType.Null, rname, invocationExpression.Clone ()); lblock.Add (ra); for (int i = 0; i < args.Count; i++) { var a = args [i]; var vname = "_p" + i; var va = new AssignmentExpression (a.Expression.Clone (), new IndexerExpression ( new IdentifierExpression (vname), new PrimitiveExpression (0))); lblock.Add (va); } lblock.Add (new ReturnStatement (new IdentifierExpression (rname))); var lambda = new LambdaExpression { Body = lblock, }; var ilambda = new InvocationExpression (lambda); invocationExpression.ReplaceWith (ilambda); } } } class StaticCtorsToMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); var ctor = typeDeclaration.Members.OfType<ConstructorDeclaration> ().FirstOrDefault (x => (x.Modifiers & Modifiers.Static) != 0); if (ctor != null) { var b = ctor.Body; b.Remove (); var mctor = new MethodDeclaration { Name = typeDeclaration.Name + "_cctor", Modifiers = Modifiers.Static, ReturnType = new PrimitiveType ("void"), Body = b, }; ctor.ReplaceWith (mctor); } } } class MergeOverloads : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); var mgs = typeDeclaration.Members.OfType<MethodDeclaration> ().GroupBy ( x => x.Name + ((x.Modifiers & Modifiers.Static) != 0 ? "Static" : "")); var isInterface = typeDeclaration.ClassType == ClassType.Interface; foreach (var mg in mgs) { var ms = mg.ToList (); if (ms.Count == 1) continue; var name = ms[0].Name; for (int i = 0; i < ms.Count; i++) { var m = ms [i]; m.Name = m.Name + "_" + i; } var newCtor = new MethodDeclaration { Body = new BlockStatement (), Name = name, ReturnType = ms[0].ReturnType.Clone (), Modifiers = ms[0].Modifiers, }; var diffs = GetDiffs (ms.Select (x => x.Parameters.ToList ()).ToList ()); newCtor.Parameters.AddRange (diffs.Item1); typeDeclaration.InsertChildBefore (ms [0], newCtor, Roles.TypeMemberRole); var isVoid = (ms [0].ReturnType is PrimitiveType) && ((PrimitiveType)ms [0].ReturnType).KnownTypeCode == KnownTypeCode.Void; var isStatic = ms [0].HasModifier (Modifiers.Static); for (int i = 0; i < diffs.Item2.Count; i++) { var diff = diffs.Item2 [i]; var c = ms [i]; var ss = ((BlockStatement)diff.TrueStatement); var call = new InvocationExpression ( new MemberReferenceExpression ( isStatic ? (Expression)new TypeReferenceExpression (new SimpleType (typeDeclaration.Name)) : new ThisReferenceExpression (), c.Name), diffs.Item1.Take (c.Parameters.Count).Select (x => new IdentifierExpression (x.Name))); if (isVoid) { ss.Add (call); } else { ss.Add (new ReturnStatement (call)); } if (i + 1 < diffs.Item2.Count) { if (isVoid) { ss.Add (new ReturnStatement ()); } newCtor.Body.Add (diff); } else { foreach (var x in ss.Statements) { x.Remove (); newCtor.Body.Add (x); } } var mo = new MethodDeclaration { Name = name, ReturnType = ms[0].ReturnType.Clone (), Modifiers = ms[0].Modifiers, }; mo.Parameters.AddRange (ms [i].Parameters.Select (x => (ParameterDeclaration)x.Clone ())); foreach (var p in mo.Parameters) { if (!p.DefaultExpression.IsNull) p.DefaultExpression.Remove (); } typeDeclaration.InsertChildBefore (newCtor, mo, Roles.TypeMemberRole); } foreach (var m in ms) { m.Modifiers |= Modifiers.Private; foreach (var p in m.Parameters) { if (!p.DefaultExpression.IsNull) p.DefaultExpression.Remove (); } } // // If it's an interface, remove the bodies we created and the overloads // if (isInterface) { newCtor.Body.Remove (); foreach (var m in ms) { m.Remove (); } } } } } class MergeCtors : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); var ctors = typeDeclaration.Members.OfType<ConstructorDeclaration> ().Where (x => (x.Modifiers & Modifiers.Static)==0).ToList (); if (ctors.Count == 0) return; if (ctors.Count > 1) { for (int i = 0; i < ctors.Count; i++) { var c = ctors [i]; c.Name = "constructor_" + i; } } // // Make sure everyone has a super call // foreach (var c in ctors) { if (c.Initializer.IsNull) { c.Initializer = new ConstructorInitializer { ConstructorInitializerType = ConstructorInitializerType.Base }; } } // // Move this to a call // foreach (var c in ctors) { if (c.Initializer.ConstructorInitializerType == ConstructorInitializerType.This) { var thisInit = c.Initializer; var md = GetMethodDef (thisInit); var thisCtor = ctors.FirstOrDefault (x => GetMethodDef (x) == (md)); // // Inline this // var sup = new InvocationExpression (new MemberReferenceExpression (new ThisReferenceExpression (), thisCtor.Name), thisInit.Arguments.Select (x => x.Clone ())); c.Body.InsertChildBefore (c.Body.FirstChild, new ExpressionStatement (sup), BlockStatement.StatementRole); // // Find the new super() // var subs = new Substitute (); ConstructorInitializer baseInit = null; if (baseInit == null) { subs.Subs = thisCtor.Parameters.Zip (thisInit.Arguments, (x, y) => Tuple.Create (x, y)).ToDictionary (x => x.Item1.Name, x => x.Item2); var i = thisCtor.Initializer; if (i.ConstructorInitializerType == ConstructorInitializerType.Base) { baseInit = (ConstructorInitializer)i.Clone (); } } if (baseInit == null) { throw new NotSupportedException ("This initializer for ctor `"+typeDeclaration.Name+"/"+c.Parameters.Count+"` not supported"); } foreach (var a in baseInit.Arguments) { a.AcceptVisitor (subs); } c.Initializer = baseInit; } } // // // if (ctors.Count == 1) { var c = ctors [0]; var sup = GetBaseInitCall (c, new Substitute ()); c.Body.InsertChildBefore (c.Body.FirstChild, new ExpressionStatement (sup), BlockStatement.StatementRole); ctors [0].Initializer.Remove (); } else { // // Synthesize the 1 constructor // var newCtor = new ConstructorDeclaration { Body = new BlockStatement (), Name = "constructor", }; var diffs = GetDiffs (ctors.Select (x => x.Parameters.ToList ()).ToList ()); newCtor.Parameters.AddRange (diffs.Item1); for (int i = 0; i < diffs.Item2.Count; i++) { var diff = diffs.Item2 [i]; var c = ctors [i]; var ss = ((BlockStatement)diff.TrueStatement); var subs = new Substitute (); var args = c.Parameters.ToList (); for (int j = 0; j < args.Count; j++) { var p = diffs.Item1 [j]; subs.Subs [args [j].Name] = new IdentifierExpression (p.Name); } ss.Add (GetBaseInitCall (c, subs)); ss.Add (new InvocationExpression ( new MemberReferenceExpression (new ThisReferenceExpression (), c.Name), diffs.Item1.Take (c.Parameters.Count).Select (x => new IdentifierExpression (x.Name)))); if (i + 1 < diffs.Item2.Count) { ss.Add (new ReturnStatement ()); newCtor.Body.Add (diff); } else { foreach (var x in ss.Statements) { x.Remove (); newCtor.Body.Add (x); } } } typeDeclaration.InsertChildBefore (ctors [0], newCtor, Roles.TypeMemberRole); foreach (var c in ctors) { var body = c.Body; body.Remove (); // // Create the implementation method // var m = new MethodDeclaration { Name = c.Name, Body = body, ReturnType = new PrimitiveType ("void"), Modifiers = Modifiers.Private, }; m.Parameters.AddRange (c.Parameters.Select (x => (ParameterDeclaration)x.Clone ())); foreach (var p in m.Parameters) { if (!p.DefaultExpression.IsNull) p.DefaultExpression.Remove (); } c.ReplaceWith (m); // // Insert overload prototype // var mo = new ConstructorDeclaration { }; mo.Parameters.AddRange (c.Parameters.Select (x => (ParameterDeclaration)x.Clone ())); foreach (var p in mo.Parameters) { if (!p.DefaultExpression.IsNull) p.DefaultExpression.Remove (); } typeDeclaration.InsertChildBefore (newCtor, mo, Roles.TypeMemberRole); } } } Expression GetBaseInitCall (ConstructorDeclaration c, Substitute subs) { var thisInit = c.Initializer; var i = new InvocationExpression ( new BaseReferenceExpression (), thisInit.Arguments.Select (x => x.Clone ())); i.AcceptVisitor (subs); return i; } } static MethodDefinition GetMethodDef (AstNode node) { var mr = GetMethodRef (node); var md = mr as MethodDefinition; if (md != null) return md; if (mr != null) return mr.Resolve (); return null; } static MethodReference GetMethodRef (AstNode node) { var mr = node.Annotation<MethodReference> (); if (mr != null) return mr; mr = node.Annotation<MethodDefinition> (); if (mr != null) return mr; return null; } class Substitute : DepthFirstAstVisitor { public Dictionary<string, Expression> Subs = new Dictionary<string, Expression> (); public override void VisitIdentifierExpression (IdentifierExpression identifierExpression) { base.VisitIdentifierExpression (identifierExpression); Expression change; if (Subs.TryGetValue (identifierExpression.Identifier, out change)) { identifierExpression.ReplaceWith (change.Clone ()); } } } class PropertiesToMethods : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitPropertyDeclaration (PropertyDeclaration p) { if (p.Getter != null && p.Getter.Body.IsNull && p.Setter != null && p.Setter.Body.IsNull) { if (ES3Compatible) { if (p.GetParent<TypeDeclaration> ().ClassType == ClassType.Interface) { MakeCommonAccessors (p); } else { MakeES3CompatibleField (p); } } else { MakeCommonField (p); } } else { MakeCommonAccessors (p); } } private void MakeES3CompatibleField (PropertyDeclaration p) { var fieldDeclaration = new FieldDeclaration { Modifiers = p.Modifiers | Modifiers.Private, ReturnType = p.ReturnType.Clone () }; var fieldName = Char.ToLowerInvariant (p.Name[0]) + p.Name.Substring (1); fieldDeclaration.Variables.Add (new VariableInitializer (fieldName)); p.Parent.InsertChildBefore (p, fieldDeclaration, Roles.TypeMemberRole); foreach (var a in p.Children.OfType<Accessor> ()) { MethodDeclaration fun; if (a.Role == PropertyDeclaration.GetterRole) { var body = new BlockStatement (); body.AddChild ( new ReturnStatement ( new MemberReferenceExpression ( new ThisReferenceExpression (), fieldName)), BlockStatement.StatementRole); fun = new MethodDeclaration { Body = body, Name = ES3GetterPrefix + p.Name, Modifiers = a.Modifiers == Modifiers.None ? p.Modifiers : a.Modifiers, ReturnType = p.ReturnType.Clone () }; } else { var body = new BlockStatement (); var valueParam = new ParameterDeclaration { Name = "value", Type = p.ReturnType.Clone (), }; body.AddChild ( new ExpressionStatement ( new AssignmentExpression ( new MemberReferenceExpression ( new ThisReferenceExpression (), fieldName), new IdentifierExpression(valueParam.Name))), BlockStatement.StatementRole); fun = new MethodDeclaration { Body = body, Name = ES3SetterPrefix + p.Name, Modifiers = a.Modifiers == Modifiers.None ? p.Modifiers : a.Modifiers, ReturnType = new PrimitiveType ("void") }; fun.Parameters.Add (valueParam); } fun.AddAnnotation (a); p.Parent.InsertChildAfter (p, fun, Roles.TypeMemberRole); } p.Remove (); } private void MakeCommonField (PropertyDeclaration p) { var f = new FieldDeclaration { Modifiers = p.Modifiers, ReturnType = p.ReturnType.Clone (), }; f.Variables.Add (new VariableInitializer (p.Name)); p.ReplaceWith (f); } private void MakeCommonAccessors (PropertyDeclaration p) { foreach (var a in p.Children.OfType<Accessor> ()) { var getter = a.Role == PropertyDeclaration.GetterRole; var methodNamePrefix = (getter ? "get " : "set "); if (ES3Compatible) methodNamePrefix = (getter ? ES3GetterPrefix : ES3SetterPrefix); var fun = new MethodDeclaration { Body = (BlockStatement) a.Body.Clone (), Name = methodNamePrefix + p.Name, Modifiers = p.Modifiers, }; fun.AddAnnotation (a); if (getter) { fun.ReturnType = p.ReturnType.Clone (); } else { fun.ReturnType = new PrimitiveType ("void"); fun.Parameters.Add (new ParameterDeclaration { Name = "value", Type = p.ReturnType.Clone (), }); } p.Parent.InsertChildAfter (p, fun, Roles.TypeMemberRole); } p.Remove (); } } class RemoveModifiers : DepthFirstAstVisitor, IAstTransform { public void Run (AstNode compilationUnit) { compilationUnit.AcceptVisitor (this); } public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); methodDeclaration.Modifiers = Rem (methodDeclaration.Modifiers); methodDeclaration.Attributes.Clear (); } public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration) { base.VisitParameterDeclaration (parameterDeclaration); parameterDeclaration.Attributes.Clear (); } public override void VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration) { base.VisitConstructorDeclaration (constructorDeclaration); constructorDeclaration.Modifiers = Rem (constructorDeclaration.Modifiers) & ~(Modifiers.Private); constructorDeclaration.Attributes.Clear (); constructorDeclaration.Name = "constructor"; } public override void VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration) { base.VisitPropertyDeclaration (propertyDeclaration); propertyDeclaration.Modifiers = Rem (propertyDeclaration.Modifiers); propertyDeclaration.Attributes.Clear (); } public override void VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration) { base.VisitOperatorDeclaration (operatorDeclaration); operatorDeclaration.Modifiers = Rem (operatorDeclaration.Modifiers); operatorDeclaration.Attributes.Clear (); } public override void VisitFieldDeclaration (FieldDeclaration fieldDeclaration) { base.VisitFieldDeclaration (fieldDeclaration); fieldDeclaration.Modifiers = Rem (fieldDeclaration.Modifiers); fieldDeclaration.Attributes.Clear (); } public override void VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement) { base.VisitVariableDeclarationStatement (variableDeclarationStatement); variableDeclarationStatement.Modifiers = Rem (variableDeclarationStatement.Modifiers); } public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration) { base.VisitTypeDeclaration (typeDeclaration); typeDeclaration.Modifiers = Rem (typeDeclaration.Modifiers) & ~(Modifiers.Static | Modifiers.Private); typeDeclaration.Attributes.Clear (); if ((typeDeclaration.ClassType == ClassType.Class || typeDeclaration.ClassType == ClassType.Struct) && typeDeclaration.BaseTypes.All (IsInterface)) { typeDeclaration.BaseTypes.Add (new SimpleType ("NObject")); } } static Modifiers Rem (Modifiers m) { if ((m & Modifiers.Const) != 0) { m |= Modifiers.Static; } m &= ~(Modifiers.Public | Modifiers.Abstract | Modifiers.Async | Modifiers.Const | Modifiers.Protected | Modifiers.Readonly | Modifiers.Override | Modifiers.Virtual | Modifiers.Sealed | Modifiers.Internal); return m; } } public static bool IsDelegate (AstNode type) { return IsDelegate (GetTypeDef (type)); } public static bool IsInterface (AstType type) { return IsInterface (GetTypeDef (type)); } public static bool IsInterface (TypeDeclaration type) { return type.ClassType == ClassType.Interface; } public static bool IsInterface (TypeDefinition td) { if (td == null) return false; return td.IsInterface; } class Diff { public ParameterDeclaration[] Item1; public List<IfElseStatement> Item2; } static Diff GetDiffs (List<List<ParameterDeclaration>> methods) { // // Devise a new parameter list // var maxArgs = methods.Max (x => x.Count); var minArgs = methods.Min (x => x.Count); var ps = new ParameterDeclaration[maxArgs]; foreach (var m in methods) { for (int i = 0; i < m.Count; i++) { var p = m [i]; if (ps [i] == null) { ps [i] = (ParameterDeclaration)p.Clone (); if (i >= minArgs && ps[i].DefaultExpression.IsNull) { ps [i].AddAnnotation (new OptionalParameterNote ()); } } else { var exName = ps [i].Name; if (exName != p.Name) { var orName = "Or" + Capitalize (p.Name); if (!exName.StartsWith (p.Name + "Or", StringComparison.Ordinal) && !exName.Contains (orName)) { ps [i].Name += orName; } } ps [i].Type = MergeTypes (ps [i].Type, p.Type); } } } // // Generate the conditions // var order = methods.ToList (); var ifs = order.Select (x => new IfElseStatement { Condition = MakeCondition (x, ps), TrueStatement = new BlockStatement (), }).ToList (); return new Diff { Item1 = ps, Item2 = ifs }; } static bool TypesEqual (AstType x, AstType y) { var px = x as PrimitiveType; var py = y as PrimitiveType; if (px != null && py != null && px.KnownTypeCode == py.KnownTypeCode) { return true; } var sx = x as SimpleType; var sy = y as SimpleType; if (sx != null && sy != null && sx.Identifier == sy.Identifier && sx.TypeArguments.Count == sy.TypeArguments.Count && sx.TypeArguments.Zip (sy.TypeArguments, (a,b) => TypesEqual(a,b)).All (a => a)) { return true; } return false; } static AstType MergeTypes (AstType x, AstType y) { if (TypesEqual (x, y)) { return x.Clone (); } return new PrimitiveType ("object"); } static string Capitalize (string name) { if (string.IsNullOrEmpty (name)) return ""; if (char.IsUpper (name [0])) return name; return char.ToUpperInvariant (name [0]) + name.Substring (1); } static Expression MakeCondition (List<ParameterDeclaration> ps, ParameterDeclaration[] newPs) { Expression e = new BinaryOperatorExpression ( new MemberReferenceExpression (new IdentifierExpression ("arguments"), "length"), BinaryOperatorType.Equality, new PrimitiveExpression (ps.Count)); for (int i = 0; i < ps.Count; i++) { var p = ps [i]; if (IsInterface (p.Type)) continue; // Now way to check interfaces? if (IsDelegate (p.Type)) continue; var nullc = new BinaryOperatorExpression (new IdentifierExpression (newPs [i].Name), BinaryOperatorType.Equality, new PrimitiveExpression (null)); var ctor = new IsExpression { Expression = new IdentifierExpression (newPs [i].Name), Type = GetJsConstructorType (p.Type) }; var norc = new BinaryOperatorExpression (nullc, BinaryOperatorType.ConditionalOr, ctor); e = new BinaryOperatorExpression (e, BinaryOperatorType.ConditionalAnd, norc); } return e; } static AstType GetJsConstructorType (AstType type) { var tr = GetTypeDef (type); if (tr != null && tr.IsEnum) { return new PrimitiveType ("Number"); } var ct = type as ComposedType; if (ct != null) { return new SimpleType ("Array"); } var st = type as SimpleType; if (st != null) { var r = (SimpleType)st.Clone (); r.TypeArguments.Clear (); return r; } var pt = type as PrimitiveType; if (pt != null) { switch (pt.KnownTypeCode) { case KnownTypeCode.Object: return new PrimitiveType ("Object"); case KnownTypeCode.String: return new PrimitiveType ("String"); case KnownTypeCode.Char: return new PrimitiveType ("Number"); case KnownTypeCode.Boolean: return new PrimitiveType ("Boolean"); case KnownTypeCode.Byte: case KnownTypeCode.SByte: case KnownTypeCode.Int16: case KnownTypeCode.Int32: case KnownTypeCode.Int64: case KnownTypeCode.IntPtr: case KnownTypeCode.UInt16: case KnownTypeCode.UInt32: case KnownTypeCode.UInt64: case KnownTypeCode.Decimal: case KnownTypeCode.Single: case KnownTypeCode.Double: return new PrimitiveType ("Number"); } switch (pt.Keyword) { case "any": return new PrimitiveType ("Object"); case "boolean": return new PrimitiveType ("Boolean"); case "number": return new PrimitiveType ("Number"); } } var mt = type as MemberType; if (mt != null) { return new SimpleType (mt.MemberName); } throw new NotSupportedException ("Unknown JS constructor"); } static string GetJsConstructor (AstType type) { var tr = GetTypeDef (type); if (tr != null && tr.IsEnum) { return "Number"; } var ct = type as ComposedType; if (ct != null) { return "Array"; } var st = type as SimpleType; if (st != null) { return st.Identifier; } var pt = type as PrimitiveType; if (pt != null) { switch (pt.KnownTypeCode) { case KnownTypeCode.Object: return "Object"; case KnownTypeCode.String: return "String"; case KnownTypeCode.Char: return "Number"; case KnownTypeCode.Boolean: return "Boolean"; case KnownTypeCode.Byte: case KnownTypeCode.SByte: case KnownTypeCode.Int16: case KnownTypeCode.Int32: case KnownTypeCode.Int64: case KnownTypeCode.IntPtr: case KnownTypeCode.UInt16: case KnownTypeCode.UInt32: case KnownTypeCode.UInt64: case KnownTypeCode.Decimal: case KnownTypeCode.Single: case KnownTypeCode.Double: return "Number"; } switch (pt.Keyword) { case "any": return "Object"; case "boolean": return "Boolean"; case "number": return "Number"; } } var mt = type as MemberType; if (mt != null) { return mt.MemberName; } throw new NotSupportedException ("Unknown JS constructor"); } static int Specificity (List<ParameterDeclaration> ps) { return ps.Select (x => GetJsConstructor (x.Type)).Distinct ().Count (); } } class OptionalParameterNote {} }
{ "content_hash": "3a1e0070319a6d3cff8e65ff4051602e", "timestamp": "", "source": "github", "line_count": 4119, "max_line_length": 210, "avg_line_length": 28.615440640932267, "alnum_prop": 0.6365479735634232, "repo_name": "praeclarum/Netjs", "id": "9e45ebaf479636cb170aeb12497440fdfabc2fd4", "size": "117869", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Netjs/CsToTs.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "7684162" }, { "name": "HTML", "bytes": "395" }, { "name": "TypeScript", "bytes": "70981" } ], "symlink_target": "" }
<?php namespace Ongoing; class ArticleClass { /** * @var int $SystemId */ protected $SystemId = null; /** * @var string $Name */ protected $Name = null; /** * @var string $ArticleNumber */ protected $ArticleNumber = null; /** * @var string $ProductCode */ protected $ProductCode = null; /** * @var string $BarCode */ protected $BarCode = null; /** * @var string $Description */ protected $Description = null; /** * @var string $SupplierArticleNumber */ protected $SupplierArticleNumber = null; /** * @var string $StatisticsNumber */ protected $StatisticsNumber = null; /** * @var string $ArticleGroupName */ protected $ArticleGroupName = null; /** * @var string $ArticleGroupCode */ protected $ArticleGroupCode = null; /** * @var string $MainSupplierName */ protected $MainSupplierName = null; /** * @var string $MainSupplierNumber */ protected $MainSupplierNumber = null; /** * @var string $ArticleCategoryName */ protected $ArticleCategoryName = null; /** * @var string $ArticleCategoryCode */ protected $ArticleCategoryCode = null; /** * @var string $CountryOfOriginCode */ protected $CountryOfOriginCode = null; /** * @var boolean $IsStockArticle */ protected $IsStockArticle = null; /** * @var string $ArticleUnitCode */ protected $ArticleUnitCode = null; /** * @var string $VatCode */ protected $VatCode = null; /** * @var float $VatPercent */ protected $VatPercent = null; /** * @var float $Length */ protected $Length = null; /** * @var float $Width */ protected $Width = null; /** * @var float $Height */ protected $Height = null; /** * @var float $Price */ protected $Price = null; /** * @var float $CustomerPrice */ protected $CustomerPrice = null; /** * @var float $PurchasePrice */ protected $PurchasePrice = null; /** * @var float $Weight */ protected $Weight = null; /** * @var float $NetWeight */ protected $NetWeight = null; /** * @var float $Volume */ protected $Volume = null; /** * @var float $QuantityPerPallet */ protected $QuantityPerPallet = null; /** * @var float $QuantityPerPackage */ protected $QuantityPerPackage = null; /** * @var DangerousGoods[] $DangerousGoods */ protected $DangerousGoods = null; /** * @var string $PurchaseCurrencyCode */ protected $PurchaseCurrencyCode = null; /** * @var string $PurchaseCurrencyName */ protected $PurchaseCurrencyName = null; /** * @param boolean $IsStockArticle */ public function __construct($IsStockArticle) { $this->IsStockArticle = $IsStockArticle; } /** * @return int */ public function getSystemId() { return $this->SystemId; } /** * @param int $SystemId * @return \Ongoing\ArticleClass */ public function setSystemId($SystemId) { $this->SystemId = $SystemId; return $this; } /** * @return string */ public function getName() { return $this->Name; } /** * @param string $Name * @return \Ongoing\ArticleClass */ public function setName($Name) { $this->Name = $Name; return $this; } /** * @return string */ public function getArticleNumber() { return $this->ArticleNumber; } /** * @param string $ArticleNumber * @return \Ongoing\ArticleClass */ public function setArticleNumber($ArticleNumber) { $this->ArticleNumber = $ArticleNumber; return $this; } /** * @return string */ public function getProductCode() { return $this->ProductCode; } /** * @param string $ProductCode * @return \Ongoing\ArticleClass */ public function setProductCode($ProductCode) { $this->ProductCode = $ProductCode; return $this; } /** * @return string */ public function getBarCode() { return $this->BarCode; } /** * @param string $BarCode * @return \Ongoing\ArticleClass */ public function setBarCode($BarCode) { $this->BarCode = $BarCode; return $this; } /** * @return string */ public function getDescription() { return $this->Description; } /** * @param string $Description * @return \Ongoing\ArticleClass */ public function setDescription($Description) { $this->Description = $Description; return $this; } /** * @return string */ public function getSupplierArticleNumber() { return $this->SupplierArticleNumber; } /** * @param string $SupplierArticleNumber * @return \Ongoing\ArticleClass */ public function setSupplierArticleNumber($SupplierArticleNumber) { $this->SupplierArticleNumber = $SupplierArticleNumber; return $this; } /** * @return string */ public function getStatisticsNumber() { return $this->StatisticsNumber; } /** * @param string $StatisticsNumber * @return \Ongoing\ArticleClass */ public function setStatisticsNumber($StatisticsNumber) { $this->StatisticsNumber = $StatisticsNumber; return $this; } /** * @return string */ public function getArticleGroupName() { return $this->ArticleGroupName; } /** * @param string $ArticleGroupName * @return \Ongoing\ArticleClass */ public function setArticleGroupName($ArticleGroupName) { $this->ArticleGroupName = $ArticleGroupName; return $this; } /** * @return string */ public function getArticleGroupCode() { return $this->ArticleGroupCode; } /** * @param string $ArticleGroupCode * @return \Ongoing\ArticleClass */ public function setArticleGroupCode($ArticleGroupCode) { $this->ArticleGroupCode = $ArticleGroupCode; return $this; } /** * @return string */ public function getMainSupplierName() { return $this->MainSupplierName; } /** * @param string $MainSupplierName * @return \Ongoing\ArticleClass */ public function setMainSupplierName($MainSupplierName) { $this->MainSupplierName = $MainSupplierName; return $this; } /** * @return string */ public function getMainSupplierNumber() { return $this->MainSupplierNumber; } /** * @param string $MainSupplierNumber * @return \Ongoing\ArticleClass */ public function setMainSupplierNumber($MainSupplierNumber) { $this->MainSupplierNumber = $MainSupplierNumber; return $this; } /** * @return string */ public function getArticleCategoryName() { return $this->ArticleCategoryName; } /** * @param string $ArticleCategoryName * @return \Ongoing\ArticleClass */ public function setArticleCategoryName($ArticleCategoryName) { $this->ArticleCategoryName = $ArticleCategoryName; return $this; } /** * @return string */ public function getArticleCategoryCode() { return $this->ArticleCategoryCode; } /** * @param string $ArticleCategoryCode * @return \Ongoing\ArticleClass */ public function setArticleCategoryCode($ArticleCategoryCode) { $this->ArticleCategoryCode = $ArticleCategoryCode; return $this; } /** * @return string */ public function getCountryOfOriginCode() { return $this->CountryOfOriginCode; } /** * @param string $CountryOfOriginCode * @return \Ongoing\ArticleClass */ public function setCountryOfOriginCode($CountryOfOriginCode) { $this->CountryOfOriginCode = $CountryOfOriginCode; return $this; } /** * @return boolean */ public function getIsStockArticle() { return $this->IsStockArticle; } /** * @param boolean $IsStockArticle * @return \Ongoing\ArticleClass */ public function setIsStockArticle($IsStockArticle) { $this->IsStockArticle = $IsStockArticle; return $this; } /** * @return string */ public function getArticleUnitCode() { return $this->ArticleUnitCode; } /** * @param string $ArticleUnitCode * @return \Ongoing\ArticleClass */ public function setArticleUnitCode($ArticleUnitCode) { $this->ArticleUnitCode = $ArticleUnitCode; return $this; } /** * @return string */ public function getVatCode() { return $this->VatCode; } /** * @param string $VatCode * @return \Ongoing\ArticleClass */ public function setVatCode($VatCode) { $this->VatCode = $VatCode; return $this; } /** * @return float */ public function getVatPercent() { return $this->VatPercent; } /** * @param float $VatPercent * @return \Ongoing\ArticleClass */ public function setVatPercent($VatPercent) { $this->VatPercent = $VatPercent; return $this; } /** * @return float */ public function getLength() { return $this->Length; } /** * @param float $Length * @return \Ongoing\ArticleClass */ public function setLength($Length) { $this->Length = $Length; return $this; } /** * @return float */ public function getWidth() { return $this->Width; } /** * @param float $Width * @return \Ongoing\ArticleClass */ public function setWidth($Width) { $this->Width = $Width; return $this; } /** * @return float */ public function getHeight() { return $this->Height; } /** * @param float $Height * @return \Ongoing\ArticleClass */ public function setHeight($Height) { $this->Height = $Height; return $this; } /** * @return float */ public function getPrice() { return $this->Price; } /** * @param float $Price * @return \Ongoing\ArticleClass */ public function setPrice($Price) { $this->Price = $Price; return $this; } /** * @return float */ public function getCustomerPrice() { return $this->CustomerPrice; } /** * @param float $CustomerPrice * @return \Ongoing\ArticleClass */ public function setCustomerPrice($CustomerPrice) { $this->CustomerPrice = $CustomerPrice; return $this; } /** * @return float */ public function getPurchasePrice() { return $this->PurchasePrice; } /** * @param float $PurchasePrice * @return \Ongoing\ArticleClass */ public function setPurchasePrice($PurchasePrice) { $this->PurchasePrice = $PurchasePrice; return $this; } /** * @return float */ public function getWeight() { return $this->Weight; } /** * @param float $Weight * @return \Ongoing\ArticleClass */ public function setWeight($Weight) { $this->Weight = $Weight; return $this; } /** * @return float */ public function getNetWeight() { return $this->NetWeight; } /** * @param float $NetWeight * @return \Ongoing\ArticleClass */ public function setNetWeight($NetWeight) { $this->NetWeight = $NetWeight; return $this; } /** * @return float */ public function getVolume() { return $this->Volume; } /** * @param float $Volume * @return \Ongoing\ArticleClass */ public function setVolume($Volume) { $this->Volume = $Volume; return $this; } /** * @return float */ public function getQuantityPerPallet() { return $this->QuantityPerPallet; } /** * @param float $QuantityPerPallet * @return \Ongoing\ArticleClass */ public function setQuantityPerPallet($QuantityPerPallet) { $this->QuantityPerPallet = $QuantityPerPallet; return $this; } /** * @return float */ public function getQuantityPerPackage() { return $this->QuantityPerPackage; } /** * @param float $QuantityPerPackage * @return \Ongoing\ArticleClass */ public function setQuantityPerPackage($QuantityPerPackage) { $this->QuantityPerPackage = $QuantityPerPackage; return $this; } /** * @return DangerousGoods[] */ public function getDangerousGoods() { return $this->DangerousGoods; } /** * @param DangerousGoods[] $DangerousGoods * @return \Ongoing\ArticleClass */ public function setDangerousGoods(array $DangerousGoods = null) { $this->DangerousGoods = $DangerousGoods; return $this; } /** * @return string */ public function getPurchaseCurrencyCode() { return $this->PurchaseCurrencyCode; } /** * @param string $PurchaseCurrencyCode * @return \Ongoing\ArticleClass */ public function setPurchaseCurrencyCode($PurchaseCurrencyCode) { $this->PurchaseCurrencyCode = $PurchaseCurrencyCode; return $this; } /** * @return string */ public function getPurchaseCurrencyName() { return $this->PurchaseCurrencyName; } /** * @param string $PurchaseCurrencyName * @return \Ongoing\ArticleClass */ public function setPurchaseCurrencyName($PurchaseCurrencyName) { $this->PurchaseCurrencyName = $PurchaseCurrencyName; return $this; } }
{ "content_hash": "bb2d75d9f78ad1c06f6b5d18f78194b6", "timestamp": "", "source": "github", "line_count": 775, "max_line_length": 68, "avg_line_length": 18.587096774193547, "alnum_prop": 0.5628601180145782, "repo_name": "starweb/ongoing", "id": "f2a7e409538cd86154c45019c409a9804dc175d5", "size": "14405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Ongoing/ArticleClass.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "994263" } ], "symlink_target": "" }
package io.github.ibuildthecloud.gdapi.id; import io.github.ibuildthecloud.gdapi.factory.SchemaFactory; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javax.inject.Inject; public class TypeIdFormatter implements IdFormatter { private Map<String, String> typeCache = Collections.synchronizedMap(new WeakHashMap<String, String>()); String globalPrefix = "1"; SchemaFactory schemaFactory; Set<String> plainTypes = new HashSet<String>(); @Override public String formatId(String type, Object id) { if (id == null) { return null; } String idString = id.toString(); if (idString.length() == 0) { return null; } if (plainTypes.contains(type)) { return id.toString(); } String shortType = typeCache.get(type); if (shortType == null) { shortType = getShortType(type); } if (!Character.isDigit(idString.charAt(0))) { return shortType + "!" + id; } else { return shortType + id; } } @Override public String parseId(String id) { if (id == null || id.length() == 0) return null; if (Character.isLetter(id.charAt(0)) && !id.startsWith(globalPrefix)) { return id; } if (!id.startsWith(globalPrefix)) { return null; } id = id.substring(globalPrefix.length()); if (id.length() == 0 || !Character.isLetter(id.charAt(0))) { return null; } String parsedId = id.replaceAll("^[a-z]*", ""); try { if (parsedId.startsWith("!")) { return parsedId.substring(1); } else { return parsedId; } } catch (NumberFormatException e) { return null; } } protected String getShortType(String type) { String base = schemaFactory.getBaseType(type); if (base != null) { type = base; } StringBuilder buffer = new StringBuilder(globalPrefix); buffer.append(type.charAt(0)); buffer.append(type.replaceAll("[a-z]+", "")); String result = buffer.toString().toLowerCase(); typeCache.put(type, result); return result; } public SchemaFactory getSchemaFactory() { return schemaFactory; } @Inject public void setSchemaFactory(SchemaFactory schemaFactory) { this.schemaFactory = schemaFactory; } public Set<String> getPlainTypes() { return plainTypes; } public void setPlainTypes(Set<String> plainTypes) { this.plainTypes = plainTypes; } }
{ "content_hash": "f43fcd6da2b494d1fcb76996be0caff3", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 107, "avg_line_length": 25.243243243243242, "alnum_prop": 0.5724482512491078, "repo_name": "gpndata/cattle", "id": "ad8bce82f00ce54fe055558c93cfa806f222fadb", "size": "2802", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "code/framework/java-server/src/main/java/io/github/ibuildthecloud/gdapi/id/TypeIdFormatter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "824" }, { "name": "Java", "bytes": "5234939" }, { "name": "Python", "bytes": "546504" }, { "name": "Shell", "bytes": "39843" } ], "symlink_target": "" }
package dagger.hilt.android.processor.internal.customtestapplication; import static net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.ISOLATING; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableSet; import dagger.hilt.processor.internal.BaseProcessor; import dagger.hilt.processor.internal.ClassNames; import javax.annotation.processing.Processor; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import net.ltgt.gradle.incap.IncrementalAnnotationProcessor; /** Processes usages of {@link dagger.hilt.android.testing.CustomTestApplication}. */ @IncrementalAnnotationProcessor(ISOLATING) @AutoService(Processor.class) public final class CustomTestApplicationProcessor extends BaseProcessor { @Override public ImmutableSet<String> getSupportedAnnotationTypes() { return ImmutableSet.of(ClassNames.CUSTOM_TEST_APPLICATION.toString()); } @Override public void processEach(TypeElement annotation, Element element) throws Exception { CustomTestApplicationMetadata metadata = CustomTestApplicationMetadata.of(element, getElementUtils()); new CustomTestApplicationGenerator(getProcessingEnv(), metadata).generate(); } }
{ "content_hash": "9dd88798f24882ef751ddbcb60d1082e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 85, "avg_line_length": 38.5, "alnum_prop": 0.8238636363636364, "repo_name": "google/dagger", "id": "fd1a6c87dc6018232fe056c8d2bb155f332acc43", "size": "1834", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "java/dagger/hilt/android/processor/internal/customtestapplication/CustomTestApplicationProcessor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5751023" }, { "name": "Kotlin", "bytes": "370467" }, { "name": "Python", "bytes": "2010" }, { "name": "Shell", "bytes": "23050" }, { "name": "Starlark", "bytes": "411015" } ], "symlink_target": "" }
using System; using System.Xml; using System.IO; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Diagnostics; using System.Reflection; using MS.Utility; #if !PBTCOMPILER using System.Windows; using System.Windows.Navigation; using System.Windows.Threading; #endif #if PBTCOMPILER namespace MS.Internal.Markup #else namespace System.Windows.Markup #endif { /// <summary> /// A class to encapsulate XML-specific attributes of a DependencyObject /// </summary> #if PBTCOMPILER internal sealed class XmlAttributeProperties #else public sealed class XmlAttributeProperties #endif { #if !PBTCOMPILER #region Public Methods // This is a dummy contructor to prevent people // from being able to instantiate this class private XmlAttributeProperties() { } static XmlAttributeProperties() { XmlSpaceProperty = DependencyProperty.RegisterAttached("XmlSpace", typeof(string), typeof(XmlAttributeProperties), new FrameworkPropertyMetadata("default")); XmlnsDictionaryProperty = DependencyProperty.RegisterAttached("XmlnsDictionary", typeof(XmlnsDictionary), typeof(XmlAttributeProperties), new FrameworkPropertyMetadata((object)null, FrameworkPropertyMetadataOptions.Inherits)); XmlnsDefinitionProperty = DependencyProperty.RegisterAttached("XmlnsDefinition", typeof(string), typeof(XmlAttributeProperties), new FrameworkPropertyMetadata(XamlReaderHelper.DefinitionNamespaceURI, FrameworkPropertyMetadataOptions.Inherits)); XmlNamespaceMapsProperty = DependencyProperty.RegisterAttached("XmlNamespaceMaps", typeof(Hashtable), typeof(XmlAttributeProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits)); } #if Lookups /// <summary> /// Looks up the namespace corresponding to an XML namespace prefix /// </summary> /// <param name="elem">The DependencyObject containing the namespace mappings to be /// used in the lookup</param> /// <param name="prefix">The XML namespace prefix to look up</param> /// <returns>The namespace corresponding to the given prefix if it exists, /// null otherwise</returns> public static string LookupNamespace(DependencyObject elem, string prefix) { if (elem == null) { throw new ArgumentNullException( "elem" ); } if (prefix == null) { throw new ArgumentNullException( "prefix" ); } // Walk up the parent chain until one of the parents has the passed prefix in // its xmlns dictionary, or until a null parent is reached. XmlnsDictionary d = GetXmlnsDictionary(elem); while ((null == d || null == d[prefix]) && null != elem) { elem = LogicalTreeHelper.GetParent(elem); if (elem != null) { d = GetXmlnsDictionary(elem); } } if (null != d) { return d[prefix]; } else { return null; } } /// <summary> /// Looks up the XML prefix corresponding to a namespaceUri /// </summary> /// <param name="elem">The DependencyObject containing the namespace mappings to /// be used in the lookup</param> /// <param name="uri">The namespaceUri to look up</param> /// <returns> /// string.Empty if the given namespace corresponds to the default namespace; otherwise, /// the XML prefix corresponding to the given namespace, or null if none exists /// </returns> public static string LookupPrefix(DependencyObject elem, string uri) { DependencyObject oldElem = elem; if (elem == null) { throw new ArgumentNullException( "elem" ); } if (uri == null) { throw new ArgumentNullException( "uri" ); } // Following the letter of the specification, the default namespace should take // precedence in the case of redundancy, so we check that first. if (DefaultNamespace(elem) == uri) return string.Empty; while (null != elem) { XmlnsDictionary d = GetXmlnsDictionary(elem); if (null != d) { // Search through all key/value pairs in the dictionary foreach (DictionaryEntry e in d) { if ((string)e.Value == uri && LookupNamespace(oldElem, (string)e.Key) == uri) { return (string)e.Key; } } } elem = LogicalTreeHelper.GetParent(elem); } return null; } // Get the Default Namespace same as LookupNamespace(e,String.Empty); /// <summary> /// Returns the default namespaceUri for the given DependencyObject /// </summary> /// <param name="e">The element containing the namespace mappings to use in the lookup</param> /// <returns>The default namespaceUri for the given Element</returns> public static string DefaultNamespace(DependencyObject e) { return LookupNamespace(e, string.Empty); } #endif #endregion Public Methods #region AttachedProperties /// <summary> /// xml:space Element property /// </summary> [Browsable(false)] [Localizability(LocalizationCategory.NeverLocalize)] public static readonly DependencyProperty XmlSpaceProperty ; /// <summary> /// Return value of xml:space on the passed DependencyObject /// </summary> [DesignerSerializationOptions(DesignerSerializationOptions.SerializeAsAttribute)] [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static string GetXmlSpace(DependencyObject dependencyObject) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } return (string)dependencyObject.GetValue(XmlSpaceProperty); } /// <summary> /// Set value of xml:space on the passed DependencyObject /// </summary> public static void SetXmlSpace(DependencyObject dependencyObject, string value) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } dependencyObject.SetValue(XmlSpaceProperty, value); } /// <summary> /// XmlnsDictionary Element property /// </summary> [Browsable(false)] public static readonly DependencyProperty XmlnsDictionaryProperty ; /// <summary> /// Return value of XmlnsDictionary on the passed DependencyObject /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static XmlnsDictionary GetXmlnsDictionary(DependencyObject dependencyObject) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } return (XmlnsDictionary)dependencyObject.GetValue(XmlnsDictionaryProperty); } /// <summary> /// Set value of XmlnsDictionary on the passed DependencyObject /// </summary> public static void SetXmlnsDictionary(DependencyObject dependencyObject, XmlnsDictionary value) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } if (dependencyObject.IsSealed == false) { dependencyObject.SetValue(XmlnsDictionaryProperty, value); } } /// <summary> /// XmlnsDefinition Directory property /// </summary> [Browsable(false)] public static readonly DependencyProperty XmlnsDefinitionProperty ; /// <summary> /// Return value of xmlns definition directory on the passed DependencyObject /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DesignerSerializationOptions(DesignerSerializationOptions.SerializeAsAttribute)] [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static string GetXmlnsDefinition(DependencyObject dependencyObject) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } return (string)dependencyObject.GetValue(XmlnsDefinitionProperty); } /// <summary> /// Set value of xmlns definition directory on the passed DependencyObject /// </summary> public static void SetXmlnsDefinition(DependencyObject dependencyObject, string value) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } dependencyObject.SetValue(XmlnsDefinitionProperty, value); } /// <summary> /// XmlNamespaceMaps that map xml namespace uri to assembly/clr namespaces /// </summary> [Browsable(false)] public static readonly DependencyProperty XmlNamespaceMapsProperty ; /// <summary> /// Return value of XmlNamespaceMaps on the passed DependencyObject /// </summary> /// <remarks> /// XmlNamespaceMaps map xml namespace uri to Assembly/CLR namespaces /// </remarks> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static string GetXmlNamespaceMaps(DependencyObject dependencyObject) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } return (string)dependencyObject.GetValue(XmlNamespaceMapsProperty); } /// <summary> /// Set value of XmlNamespaceMaps on the passed DependencyObject /// </summary> /// <remarks> /// XmlNamespaceMaps map xml namespace uri to Assembly/CLR namespaces /// </remarks> public static void SetXmlNamespaceMaps(DependencyObject dependencyObject, string value) { if (dependencyObject == null) { throw new ArgumentNullException( "dependencyObject" ); } dependencyObject.SetValue(XmlNamespaceMapsProperty, value); } #endregion AttachedProperties #else private XmlAttributeProperties() { } #endif // temporal PBT #region Internal // Return the setter method info for XmlSpace internal static MethodInfo XmlSpaceSetter { get { if (_xmlSpaceSetter == null) { _xmlSpaceSetter = typeof(XmlAttributeProperties).GetMethod("SetXmlSpace", BindingFlags.Public | BindingFlags.Static); } return _xmlSpaceSetter; } } // These are special attributes that aren't mapped like other properties internal static readonly string XmlSpaceString = "xml:space"; internal static readonly string XmlLangString = "xml:lang"; internal static readonly string XmlnsDefinitionString = "xmlns"; private static MethodInfo _xmlSpaceSetter = null; #endregion Internal } }
{ "content_hash": "ecaf372102fde4b58aa12024ad23978b", "timestamp": "", "source": "github", "line_count": 348, "max_line_length": 132, "avg_line_length": 36.07471264367816, "alnum_prop": 0.5879400987732993, "repo_name": "lindexi/lindexi_gd", "id": "6980a358e3824e57f1f033f529b93204f3a790cc", "size": "12823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PresentationBuildTasksTest/WPF/WpfSourceDir/PresentationFramework/System/Windows/Markup/XmlAttributeProperties.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "29822" }, { "name": "Batchfile", "bytes": "57394" }, { "name": "C", "bytes": "983450" }, { "name": "C#", "bytes": "36237467" }, { "name": "C++", "bytes": "316762" }, { "name": "CSS", "bytes": "121116" }, { "name": "Dockerfile", "bytes": "882" }, { "name": "HTML", "bytes": "113044" }, { "name": "JavaScript", "bytes": "3323" }, { "name": "Q#", "bytes": "556" }, { "name": "Roff", "bytes": "450615" }, { "name": "ShaderLab", "bytes": "3270" }, { "name": "Smalltalk", "bytes": "18" }, { "name": "TSQL", "bytes": "23558" } ], "symlink_target": "" }
package scenes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import org.jbox2d.collision.AABB; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.World; import org.mt4j.MTApplication; import org.mt4j.components.MTComponent; import org.mt4j.components.TransformSpace; import org.mt4j.components.visibleComponents.widgets.MTTextField; import org.mt4j.components.visibleComponents.font.FontManager; import org.mt4j.components.visibleComponents.font.IFont; import org.mt4j.components.visibleComponents.shapes.MTEllipse; import org.mt4j.components.visibleComponents.shapes.MTLine; import org.mt4j.components.visibleComponents.shapes.MTRectangle; import org.mt4j.components.visibleComponents.shapes.MTRoundRectangle; import org.mt4j.components.visibleComponents.widgets.MTBackgroundImage; import org.mt4j.components.visibleComponents.widgets.MTImage; import org.mt4j.components.visibleComponents.widgets.MTSlider; import org.mt4j.components.visibleComponents.widgets.MTTextArea; import org.mt4j.components.visibleComponents.widgets.MTTextField; import org.mt4j.components.visibleComponents.widgets.buttons.MTImageButton; import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent; import org.mt4j.sceneManagement.AbstractScene; import org.mt4j.sceneManagement.Iscene; import org.mt4j.util.MT4jSettings; import org.mt4j.util.MTColor; import org.mt4j.util.math.Vector3D; import org.mt4j.util.math.Vertex; import advanced.physics.util.PhysicsHelper; import advanced.physics.util.UpdatePhysicsAction; import processing.core.PImage; import supportClasses.MoviePhysics; public class NinjaSettings extends AbstractScene { //Applicatie variabelen private MTApplication mtApp; private Iscene menuOpen; private String category; private World world; private float timeStep = 1.0f/30.0f; private int constraintIterations = 10; private float scale = 20; private MTTextArea volume; private MTTextArea brightness; private MTTextArea title; private MTSlider brightnessslid; private MTSlider volumeslid; public NinjaSettings(MTApplication mtApplication, String name) { //Setup van het scherm. super(mtApplication, name); this.mtApp = mtApplication; this.category = "Hot"; this.setClearColor(new MTColor(0, 0, 0, 255)); PImage bg_img = mtApplication.loadImage("../data/ninja_bg.jpg"); MTBackgroundImage bg = new MTBackgroundImage(mtApp, bg_img, false); //Aanmaken van het logo dat dienst doet als menu opener //Tevens functionaliteit meegeven om te reageren op click-events PImage logo = mtApplication.loadImage("../data/menu/ninjaLogo.png"); MTImageButton logoMenu = new MTImageButton(logo, mtApp); logoMenu.setNoStroke(true); if (MT4jSettings.getInstance().isOpenGlMode()) { bg.setUseDirectGL(true); logoMenu.setUseDirectGL(true); } logoMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch(e.getID()) { case TapEvent.BUTTON_CLICKED: //Save scene mtApp.pushScene(); if(menuOpen == null) { menuOpen = new NinjaMainMenu(mtApp, "Ninjanieuws", category); mtApp.addScene(menuOpen); } mtApp.changeScene(menuOpen); break; default: break; } } }); //Alle elementen toevoegen op het canvas. this.getCanvas().addChild(bg); this.getCanvas().addChild(logoMenu); logoMenu.setPositionGlobal(new Vector3D(mtApp.width - logoMenu.getWidthXY(TransformSpace.GLOBAL) / 2, logoMenu.getHeightXY(TransformSpace.GLOBAL) / 2)); // Overlay MTRectangle overlaykader = new MTRectangle (0, 0, 1920, 1080, mtApplication); overlaykader.setFillColor(MTColor.GRAY); getCanvas().addChild(overlaykader); MTColor transparentColour = new MTColor(0, 0, 0, 130); overlaykader.setFillColor(transparentColour); overlaykader.setNoStroke(true); overlaykader.setPickable(false); // Settingskader MTRoundRectangle settingskader = new MTRoundRectangle (mtApplication.width/2 - 306, mtApplication.height/2-380, 64, 612, 760, 30, 30, mtApplication); settingskader.setFillColor(MTColor.RED); getCanvas().addChild(settingskader); MTColor settingskleur = new MTColor(0, 109, 104); settingskader.setFillColor(settingskleur); settingskader.setNoStroke(true); settingskader.setPickable(false); // Settings woord MTTextArea instellingen = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 30, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font instellingen.setPositionGlobal(new Vector3D(mtApplication.width/2 - 63, mtApplication.height -780)); instellingen.setText("Instellingen"); instellingen.setPickable(false); instellingen.setNoFill(true); instellingen.setNoStroke(true); this.getCanvas().addChild(instellingen); MTLine line = new MTLine(mtApplication, new Vertex(650, 145), new Vertex(800, 145)); line.setPickable(false); getCanvas().addChild(line); // helderheid woord MTTextArea helderheid = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font helderheid.setPositionGlobal(new Vector3D(mtApplication.width/2 - 252, mtApplication.height -680)); helderheid.setText("Helderheid:"); helderheid.setPickable(false); helderheid.setNoFill(true); helderheid.setNoStroke(true); this.getCanvas().addChild(helderheid); // helderheid slider MTSlider helderheidwaarde = new MTSlider (mtApplication.width/2 -50, mtApplication.height/2-240, 300, 25, 0, 100, mtApplication); this.getCanvas().addChild(helderheidwaarde); // volume woord MTTextArea volume = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font volume.setPositionGlobal(new Vector3D(mtApplication.width/2 - 252, mtApplication.height -580)); volume.setText("Volume:"); volume.setPickable(false); volume.setNoFill(true); volume.setNoStroke(true); this.getCanvas().addChild(volume); // volume slider MTSlider volumewaarde = new MTSlider (mtApplication.width/2 -50, mtApplication.height/2 - 140, 300, 25, 0, 100, mtApplication); this.getCanvas().addChild(volumewaarde); // slaapstand woord MTTextArea slaapstand = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font slaapstand.setPositionGlobal(new Vector3D(mtApplication.width/2 - 252, mtApplication.height -480)); slaapstand.setText("Slaapstand:"); slaapstand.setPickable(false); slaapstand.setNoFill(true); slaapstand.setNoStroke(true); this.getCanvas().addChild(slaapstand); // slaapstand waarden MTTextArea waarden = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font waarden.setPositionGlobal(new Vector3D(mtApplication.width/2 + 150, mtApplication.height -480)); waarden.setText("5 minuten"); waarden.setPickable(false); waarden.setNoFill(true); waarden.setNoStroke(true); this.getCanvas().addChild(waarden); // opslaan MTTextArea textFieldVijf = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font textFieldVijf.setPositionGlobal(new Vector3D(mtApplication.width/2 - 122, mtApplication.height -380)); textFieldVijf.setText("Opslaan"); textFieldVijf.setPickable(false); textFieldVijf.setNoFill(true); textFieldVijf.setNoStroke(true); this.getCanvas().addChild(textFieldVijf); // annuleren MTTextArea annuleren = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font annuleren.setPositionGlobal(new Vector3D(mtApplication.width/2 + 30, mtApplication.height -380)); annuleren.setText("Annuleren"); annuleren.setPickable(false); annuleren.setNoFill(true); annuleren.setNoStroke(true); this.getCanvas().addChild(annuleren); // meer over deze app MTTextArea meerinfo = new MTTextArea(mtApplication, FontManager.getInstance().createFont(mtApplication, "FuturaStd-Light.otf", 24, //Font size new MTColor(255, 255, 255, 255), //Font fill color new MTColor(255, 255, 255, 255))); // Font meerinfo.setPositionGlobal(new Vector3D(mtApplication.width/2 + 60, mtApplication.height -120)); meerinfo.setText("Meer over deze app"); meerinfo.setPickable(false); meerinfo.setNoFill(true); meerinfo.setNoStroke(true); this.getCanvas().addChild(meerinfo); } public NinjaSettings(MTApplication mtApplication, String name, String _category) { //Setup van het scherm. super(mtApplication, name); this.mtApp = mtApplication; if(_category == null) { this.category = "Hot"; } else { this.category = _category; } this.setClearColor(new MTColor(0, 0, 0, 255)); PImage bg_img = mtApplication.loadImage("../data/ninja_bg.jpg"); MTBackgroundImage bg = new MTBackgroundImage(mtApp, bg_img, false); //Aanmaken van het logo dat dienst doet als menu opener //Tevens functionaliteit meegeven om te reageren op click-events PImage logo = mtApplication.loadImage("../data/menu/ninjaLogo.png"); MTImageButton logoMenu = new MTImageButton(logo, mtApp); logoMenu.setNoStroke(true); if (MT4jSettings.getInstance().isOpenGlMode()) { logoMenu.setUseDirectGL(true); } logoMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch(e.getID()) { case TapEvent.BUTTON_CLICKED: //Save scene mtApp.pushScene(); if(menuOpen == null) { menuOpen = new NinjaMainMenu(mtApp, "Ninjanieuws", category); mtApp.addScene(menuOpen); } mtApp.changeScene(menuOpen); break; default: break; } } }); //Alle elementen toevoegen op het canvas. this.getCanvas().addChild(bg); this.getCanvas().addChild(logoMenu); logoMenu.setPositionGlobal(new Vector3D(mtApp.width - logoMenu.getWidthXY(TransformSpace.GLOBAL) / 2, logoMenu.getHeightXY(TransformSpace.GLOBAL) / 2)); } @Override public void init() { // TODO Auto-generated method stub } @Override public void shutDown() { // TODO Auto-generated method stub } }
{ "content_hash": "32f9cbb3598470ce8f642b7415a3ff84", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 154, "avg_line_length": 37.33003300330033, "alnum_prop": 0.7231014057112546, "repo_name": "Multec/Multec_IM_13_1", "id": "a260e35e44109973900c8640384505d2a23c062a", "size": "11311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scenes/NinjaSettings.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "90038" } ], "symlink_target": "" }
package com.datastax.driver.core; import com.datastax.driver.core.utils.Bytes; import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class RPTokenFactoryTest { Token.Factory factory = Token.RPToken.FACTORY; @Test(groups = "unit") public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA) .isEqualTo(factory.fromString("59959303159920881837560881824507314222")) .isEqualTo(tokenB); } @Test(groups = "unit") public void should_split_range() { List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("127605887595351923798765477786913079296"), 3); assertThat(splits).containsExactly( factory.fromString("42535295865117307932921825928971026432"), factory.fromString("85070591730234615865843651857942052864") ); } @Test(groups = "unit") public void should_split_range_that_wraps_around_the_ring() { List<Token> splits = factory.split( factory.fromString("127605887595351923798765477786913079296"), factory.fromString("85070591730234615865843651857942052864"), 3); assertThat(splits).containsExactly( factory.fromString("0"), factory.fromString("42535295865117307932921825928971026432") ); } @Test(groups = "unit") public void should_split_range_producing_empty_splits_near_ring_end() { Token minToken = factory.fromString("-1"); Token maxToken = factory.fromString("170141183460469231731687303715884105728"); // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring) List<Token> splits = factory.split(maxToken, minToken, 3); assertThat(splits).containsExactly( maxToken, maxToken ); splits = factory.split(minToken, factory.fromString("0"), 3); assertThat(splits).containsExactly( factory.fromString("0"), factory.fromString("0") ); } @Test(groups = "unit") public void should_split_whole_ring() { List<Token> splits = factory.split(factory.fromString("-1"), factory.fromString("-1"), 3); assertThat(splits).containsExactly( factory.fromString("56713727820156410577229101238628035242"), factory.fromString("113427455640312821154458202477256070485") ); } }
{ "content_hash": "8ede0592c051028be18b5e93d4dec801", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 135, "avg_line_length": 37.554054054054056, "alnum_prop": 0.6527527887729399, "repo_name": "tolbertam/java-driver", "id": "42c3b78f00ee440731560c47510be5d58cb432ce", "size": "3380", "binary": false, "copies": "1", "ref": "refs/heads/3.x", "path": "driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1221" }, { "name": "Java", "bytes": "5266737" }, { "name": "PowerShell", "bytes": "5766" }, { "name": "Python", "bytes": "6866" }, { "name": "Shell", "bytes": "1593" } ], "symlink_target": "" }
author: "Adam Presley" date: 2009-12-17T16:41:00Z tags: ["development", "coldfusion", "openbd"] title: "SES URLs with OpenBD and Google App Engine" slug: "ses-urls-with-openbd-and-google-app-engine" --- A little tidbit that I though I'd share. While playing with the Google App Engine (GAE) version of the OpenBD CFML engine I noticed that SES friendly URL's weren't working for me. After a small search I came across a bug entry on the OpenBD site that suggested that the SES filter is not setup in the GAE version by default, and that the following XML needed to be added to the WEB-INF/web.xml configuration file. {{< highlight xml >}} <filter> <filter-name>SearchEngineFriendlyURLFilter</filter-name> <display-name>SearchEngineFriendlyURLFilter</display-name> <description>SearchEngineFriendlyURLFilter</description> <filter-class>com.newatlanta.filters.SearchEngineFriendlyURLFilter</filter-class> <init-param> <param-name>extensions</param-name> <param-value>cfm,cfml</param-value> </init-param> </filter> <filter-mapping> <filter-name>SearchEngineFriendlyURLFilter</filter-name> <url-pattern>/index.cfm/*</url-pattern> </filter-mapping> {{< / highlight >}} This is to be inserted just before the closing tag. After a quick restart of the OpenBD context, I was good to go. Happy coding!
{ "content_hash": "ac76a6ca02d54d874e214b79155058cf", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 82, "avg_line_length": 37.4, "alnum_prop": 0.7677616501145913, "repo_name": "adampresley/adampresley.github.io", "id": "df11a88f9b8e67a968b7e30ca8c1220abbda66bf", "size": "1313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/post/2009-12-17-ses-urls-with-openbd-and-google-app-engine.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "25" }, { "name": "CSS", "bytes": "20927" }, { "name": "JavaScript", "bytes": "5213" }, { "name": "Shell", "bytes": "101" } ], "symlink_target": "" }
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-2-d-7.js * @description Object.freeze - 'O' is a RegExp object */ function testcase() { var regObj = new RegExp(); Object.freeze(regObj); return Object.isFrozen(regObj); } runTestCase(testcase);
{ "content_hash": "8c4bcf4bac0c06d9f088c5716bac9a7e", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 83, "avg_line_length": 35.31578947368421, "alnum_prop": 0.6676602086438153, "repo_name": "mbrowne/typescript-dci", "id": "a5ae89491af00620a4f6c228f0c4fa482059e418", "size": "671", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tests/Fidelity/test262/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-2-d-7.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Elixir", "bytes": "3294" }, { "name": "HTML", "bytes": "7930" }, { "name": "JavaScript", "bytes": "23053088" }, { "name": "Shell", "bytes": "386" }, { "name": "TypeScript", "bytes": "16490923" } ], "symlink_target": "" }
function ClusterConfig(params) { var self = this; self.clusterConfig = undefined; self.loading = true; var refreshConfig = function () { ApiHelper.getInstance().getClusterConfig(params).done(function (data) { if (data.status === 0) { self.loading = false; self.clusterConfig = data; huePubSub.publish('cluster.config.set.config', self.clusterConfig); } else { $(document).trigger("error", data.message); huePubSub.publish('cluster.config.set.config'); } }).fail(function () { huePubSub.publish('clustser.config.set.config'); }).always(function () { self.loading = false; }); }; huePubSub.subscribe('cluster.config.refresh.config', refreshConfig); if (window.location.pathname.indexOf('/accounts/login') === -1) { refreshConfig(); } huePubSub.subscribe('cluster.config.get.config', function () { if (!self.loading) { huePubSub.publish('cluster.config.set.config', self.clusterConfig); } }); } new ClusterConfig();
{ "content_hash": "13a83d4a97fe0c711ae6314b8af1d8e5", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 75, "avg_line_length": 28.18918918918919, "alnum_prop": 0.6395014381591563, "repo_name": "xq262144/hue", "id": "c35f880fbf1d995cf4591b131993e293f1839a1b", "size": "1829", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "desktop/core/src/desktop/static/desktop/js/clusterConfig.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3096" }, { "name": "Batchfile", "bytes": "41710" }, { "name": "C", "bytes": "2692409" }, { "name": "C++", "bytes": "199897" }, { "name": "CSS", "bytes": "521820" }, { "name": "Emacs Lisp", "bytes": "11704" }, { "name": "Genshi", "bytes": "946" }, { "name": "Go", "bytes": "6671" }, { "name": "Groff", "bytes": "16669" }, { "name": "HTML", "bytes": "24188238" }, { "name": "Java", "bytes": "575404" }, { "name": "JavaScript", "bytes": "4987047" }, { "name": "M4", "bytes": "1377" }, { "name": "Makefile", "bytes": "144341" }, { "name": "Mako", "bytes": "3052598" }, { "name": "Myghty", "bytes": "936" }, { "name": "PLSQL", "bytes": "13774" }, { "name": "PLpgSQL", "bytes": "3646" }, { "name": "Perl", "bytes": "3499" }, { "name": "PigLatin", "bytes": "328" }, { "name": "Python", "bytes": "44291483" }, { "name": "Shell", "bytes": "44147" }, { "name": "Smarty", "bytes": "130" }, { "name": "Thrift", "bytes": "278712" }, { "name": "Visual Basic", "bytes": "2884" }, { "name": "XSLT", "bytes": "518588" } ], "symlink_target": "" }
<?php defined('BX_DOL') or die('hack attempt'); bx_import('BxBaseModTextGridAdministration'); class BxPostsGridAdministration extends BxBaseModTextGridAdministration { public function __construct ($aOptions, $oTemplate = false) { $this->MODULE = 'bx_posts'; parent::__construct ($aOptions, $oTemplate); } } /** @} */
{ "content_hash": "b3eebe65f03d7cb2f145a0aff84fb161", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 71, "avg_line_length": 23.066666666666666, "alnum_prop": 0.6705202312138728, "repo_name": "boonex/trident", "id": "dbad54436081838bf115a1d07e4589de5d88ee33", "size": "549", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "modules/boonex/posts/updates/8.0.4_8.0.5/source/classes/BxPostsGridAdministration.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1763" }, { "name": "CSS", "bytes": "1481231" }, { "name": "HTML", "bytes": "690596" }, { "name": "JavaScript", "bytes": "4916309" }, { "name": "PHP", "bytes": "28451148" }, { "name": "Shell", "bytes": "1265" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0f49116b5f551c23649efa5d82ab2e54", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "c3dade443f1155c7f0d711f00d5bdff969219f2e", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia guarujana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
""" This file contains the class definition for the sampler MCMCSample classes. """ __author__ = 'Brandon C. Kelly' import numpy as np from matplotlib import pyplot as plt import scipy.stats import acor class MCMCSample(object): """ Class for parameter samples generated by a yamcmc++ sampler. This class contains a dictionary of samples generated by an MCMC sampler for a set of parameters, as well as methods for plotting and summarizing the results. In general, the MCMCSample object is empty upon instantiation. One adds parameters to the dictionary through the AddStep method of a Sampler object. Running a Sampler object then fills the dictionary up with the parameter values. After running a Sampler object, the MCMCSample object will contain the parameter values, which can then be analyzed further. Alternatively, one can load the parameters and their values from a file. This is done through the method generate_from_file. This is helpful if one has a set of MCMC samples generated by a different program. """ def __init__(self, filename=None, logpost=None, trace=None): """ Constructor for an MCMCSample object. If no arguments are supplied, then this just creates an empty dictionary that will contain the MCMC samples. In this case parameters are added to the dictionary through the addstep method of a Sampler object, and the values are generated by running the Sampler object. Otherwise, if a filename is supplied then the parameter names and MCMC samples are read in from that file. :param filename: A string giving the name of an asciifile containing the MCMC samples. """ self._samples = dict() # Empty dictionary. We will place the samples for each tracked parameter here. if logpost is not None: self.set_logpost(logpost) if trace is not None: self.generate_from_trace(trace) elif filename is not None: # Construct MCMCSample object by reading in MCMC samples from one or more asciifiles. self.generate_from_file([filename]) def get_samples(self, name): """ Returns a copy of the numpy array containing the samples for a parameter. This is safer then directly accessing the dictionary object containing the samples to prevent one from inadvertently changes the values of the samples output from an MCMC sampler. :param name: The name of the parameter for which the samples are desired. """ return self._samples[name].copy() def generate_from_file(self, filename): """ Build the dictionary of parameter samples from an ascii file of MCMC samples. The first line of this file should contain the parameter names. :param filename: The name of the file containing the MCMC samples. """ # TODO: put in exceptions to make sure files are ready correctly for fname in filename: file = open(fname, 'r') name = file.readline() # Grab the MCMC output trace = np.genfromtxt(fname, skip_header=1) if name not in self._samples: # Parameter is not already in the dictionary, so add it. Otherwise do nothing. self._samples[name] = trace def autocorr_timescale(self, trace): """ Compute the autocorrelation time scale as estimated by the `acor` module. :param trace: The parameter trace, a numpy array. """ acors = [] for i in range(trace.shape[1]): tau, mean, sigma = acor.acor(trace[:, i].real) # Warning, does not work with numpy.complex acors.append(tau) return np.array(acors) def effective_samples(self, name): """ Return the effective number of independent samples of the MCMC sampler. :param name: The name of the parameter to compute the effective number of independent samples for. """ if name not in self._samples: print("WARNING: sampler does not have", name) return else: print("Calculating effective number of samples") traces = self._samples[name] # Get the sampled parameter values npts = traces.shape[0] timescale = self.autocorr_timescale(traces) return npts / timescale def plot_trace(self, name, doShow=False): """ Plot the trace of the values, a time series showing the evolution of the parameter values for the MCMC sampler. Only a single parameter element trace is shown per plot, and all plots are shown on the same plotting window. In particular, if a parameter is array-valued, then the traces for each element of its array are plotted on a separate subplot. :param name: The parameter name. :param doShow: If true, then show the plot. """ if name not in self._samples: print("WARNING: sampler does not have", name) return else: print("Plotting Trace") fig = plt.figure() traces = self._samples[name] # Get the sampled parameter values ntrace = traces.shape[1] spN = plt.subplot(ntrace, 1, ntrace) spN.plot(traces[:,-1], ".", markersize=2) spN.set_xlabel("Step") spN.set_ylabel("par %d" % (ntrace-1)) for i in range(ntrace-1): sp = plt.subplot(ntrace, 1, i+1, sharex=spN) sp.plot(traces[:,i], ".", markersize=2) sp.set_ylabel("par %d" % (i)) plt.setp(sp.get_xticklabels(), visible=False) plt.suptitle(name) if doShow: plt.show() def plot_1dpdf(self, name, doShow=False): """ Plot histograms of the parameter values generated by the MCMC sampler. If the parameter is array valued then histograms of all of the parameter's elements will be plotted. :param name: The parameter name. :param doShow: If true, then show the plot. """ if name not in self._samples: print("WARNING: sampler does not have", name) return else: print("Plotting 1d PDF") fig = plt.figure() traces = self._samples[name] # Get the sampled parameter values ntrace = traces.shape[1] for i in range(ntrace): sp = plt.subplot(ntrace, 1, i+1) sp.hist(traces[:,i], bins=50, normed=True) sp.set_ylabel("par %d" % (i)) if i == ntrace-1: sp.set_xlabel("val") plt.suptitle(name) if doShow: plt.show() def plot_2dpdf(self, name1, name2, pindex1=0, pindex2=0, doShow=False): """ Plot joint distribution of the parameter values generated by the MCMC sampler. :param name1: The parameter name along x-axis :param name2: The parameter name along y-axis :param pindex1: Which element of the array to plot :param pindex2: Which element of the array to plot :param doShow: Call plt.show() """ if ((name1 not in self._samples) or (name2 not in self._samples)): print("WARNING: sampler does not have", name1, name2) return if pindex1 >= self._samples[name1].shape[1]: print("WARNING: not enough data in", name1) return if pindex2 >= self._samples[name2].shape[1]: print("WARNING: not enough data in", name2) return print("Plotting 2d PDF") fig = plt.figure() trace1 = self._samples[name1][:,pindex1] trace2 = self._samples[name2][:,pindex2] # joint distribution axJ = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # [left, bottom, width, height] # y histogram axY = fig.add_axes([0.8, 0.1, 0.125, 0.7], sharey=axJ) # x histogram axX = fig.add_axes([0.1, 0.8, 0.7, 0.125], sharex=axJ) axJ.plot(trace1, trace2, 'ro', ms=1, alpha=0.5) axX.hist(trace1, bins=100) axY.hist(trace2, orientation='horizontal', bins=100) axJ.set_xlabel("%s %d" % (name1, pindex1)) axJ.set_ylabel("%s %d" % (name2, pindex2)) plt.setp(axX.get_xticklabels()+axX.get_yticklabels(), visible=False) plt.setp(axY.get_xticklabels()+axY.get_yticklabels(), visible=False) if doShow: plt.show() def plot_2dkde(self, name1, name2, pindex1=0, pindex2=0, nbins=100, doPlotStragglers=True, doShow=False): """ Plot joint distribution of the parameter values generated by the MCMC sampler using a kernel density estimate. :param name1: The parameter name along x-axis :param name2: The parameter name along y-axis :param pindex1: Which element of the array to plot :param pindex2: Which element of the array to plot :param doShow: Call plt.show() :param nbins: Number of bins along each axis for KDE :param doPlotStragglers: Plot individual data points outside KDE contours. Works poorly for small samples. """ if ((name1 not in self._samples) or (name2 not in self._samples)): print("WARNING: sampler does not have", name1, name2) return if pindex1 >= self._samples[name1].shape[1]: print("WARNING: not enough data in", name1) return if pindex2 >= self._samples[name2].shape[1]: print("WARNING: not enough data in", name2) return print("Plotting 2d PDF w KDE") fig = plt.figure() trace1 = self._samples[name1][:,pindex1].real # JIC we get something imaginary? trace2 = self._samples[name2][:,pindex2].real npts = trace1.shape[0] kde = scipy.stats.gaussian_kde((trace1, trace2)) bins1 = np.linspace(trace1.min(), trace1.max(), nbins) bins2 = np.linspace(trace2.min(), trace2.max(), nbins) mesh1, mesh2 = np.meshgrid(bins1, bins2) hist = kde([mesh1.ravel(), mesh2.ravel()]).reshape(mesh1.shape) clevels = [] for frac in [0.9973, 0.9545, 0.6827]: hfrac = lambda level, hist=hist, frac=frac: hist[hist>=level].sum()/hist.sum() - frac level = scipy.optimize.bisect(hfrac, hist.min(), hist.max()) clevels.append(level) # joint distribution axJ = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # [left, bottom, width, height] # y histogram axY = fig.add_axes([0.8, 0.1, 0.125, 0.7], sharey=axJ) # x histogram axX = fig.add_axes([0.1, 0.8, 0.7, 0.125], sharex=axJ) cont = axJ.contour(mesh1, mesh2, hist, clevels, linestyles="solid", cmap=plt.cm.jet) axX.hist(trace1, bins=100) axY.hist(trace2, orientation='horizontal', bins=100) axJ.set_xlabel(name1 + '[' + str(pindex1) + ']') axJ.set_ylabel(name2 + '[' + str(pindex2) + ']') plt.setp(axX.get_xticklabels()+axX.get_yticklabels(), visible=False) plt.setp(axY.get_xticklabels()+axY.get_yticklabels(), visible=False) # Note to self: you need to set up the contours above to have # the outer one first, for collections[0] to work below. # # Also a note: this does not work if the outer contour is not # fully connected. if doPlotStragglers: outer = cont.collections[0]._paths sx = [] sy = [] for i in range(npts): found = [o.contains_point((trace1[i], trace2[i])) for o in outer] if not (True in found): sx.append(trace1[i]) sy.append(trace2[i]) axJ.plot(sx, sy, 'k.', ms = 1, alpha = 0.1) if doShow: plt.show() def plot_autocorr(self, name, acorrFac = 10.0, doShow=False): """ Plot the autocorrelation functions of the traces for a parameter. If the parameter is array-value then autocorrelation plots for each of the parameter's elements will be plotted. :param name: The parameter name. :param acorrFac: The maximum number of lags to plot, in terms of the autocorrelation time scale of the MCMC samples. The default is 10 autocorrelation time scales. :param doShow: """ if name not in self._samples: print("WARNING: sampler does not have", name) return else: print("Plotting autocorrelation function (this make take a while)") fig = plt.figure() traces = self._samples[name] # Get the sampled parameter values mtrace = np.mean(traces, axis=0) ntrace = traces.shape[1] acorr = self.autocorr_timescale(traces) for i in range(ntrace): sp = plt.subplot(ntrace, 1, i+1) lags, acf, not_needed1, not_needed2 = plt.acorr(traces[:, i] - mtrace[i], maxlags=traces.shape[0]-1, lw=2) #sp.set_xlim(-0.5, acorrFac * acorr[i]) sp.set_ylim(-0.01, 1.01) sp.axhline(y=0.5, c='k', linestyle='--') sp.axvline(x=acorr[i], c='r', linestyle='--') sp.set_ylabel("par %d autocorr" % (i)) if i == ntrace-1: sp.set_xlabel("lag") plt.suptitle(name) if doShow: plt.show() def plot_parameter(self, name, pindex=0, doShow=False): """ Simultaneously plots the trace, histogram, and autocorrelation of this parameter's values. If the parameter is array-valued, then the user must specify the index of the array to plot, as these are all 1-d plots on a single plotting window. :param name: The name of the parameter that the plots are made for. :param pindex: If the parameter is array-valued, then this is the index of the array that the plots are made for. :param doShow: Call plt.show(). """ if name not in self._samples: print("WARNING: sampler does not have", name) return else: print("Plotting parameter summary") fig = plt.figure() traces = self._samples[name] plot_title = name if traces.ndim > 1: # Parameter is array valued, grab the column corresponding to pindex if traces.ndim > 2: # Parameter values are at least matrix-valued, reshape to a vector traces = traces.reshape(traces.shape[0], np.prod(traces.shape[1:])) traces = traces[:, pindex] plot_title = name + "[" + str(pindex) + "]" # First plot the trace plt.subplot(211) plt.plot(traces, '.', markersize=2, alpha=0.5, rasterized=(len(traces) > 1e4)) plt.xlim(0, traces.size) plt.xlabel("Iteration") plt.ylabel("Value") plt.title(plot_title) # Now add the histogram of values to the trace plot axes pdf, bin_edges = np.histogram(traces, bins=25) bin_edges = bin_edges[0:pdf.size] # Stretch the PDF so that it is readable on the trace plot when plotted horizontally pdf = pdf / float(pdf.max()) * 0.34 * traces.size # Add the histogram to the plot plt.barh(bin_edges, pdf, height=bin_edges[1] - bin_edges[0], alpha=0.5, color='DarkOrange') # Finally, plot the autocorrelation function of the trace plt.subplot(212) centered_trace = traces - traces.mean() lags, acf, not_needed1, not_needed2 = plt.acorr(centered_trace, maxlags=traces.size - 1, lw=2) plt.ylabel("ACF") plt.xlabel("Lag") # Compute the autocorrelation timescale, and then reset the x-axis limits accordingly acf_timescale = self.autocorr_timescale(traces[:, np.newaxis]) plt.xlim(0, np.min([5 * acf_timescale[0], len(traces)])) if doShow: plt.show() def posterior_summaries(self, name): """ Print out the posterior medians, standard deviations, and 68th, 95th, and 99th credibility intervals. :param name: The name of the parameter for which the summaries are desired. """ traces = self._samples[name] # Get the sampled parameter values effective_nsamples = self.effective_samples(name) # Get the effective number of independent samples if traces.ndim == 1: # Parameter is scalar valued, so this is easy print("Posterior summary for parameter", name) print("----------------------------------------------") print("Effective number of independent samples:", effective_nsamples) print("Median:", np.median(traces)) print("Standard deviation:", np.std(traces)) print("68% credibility interval:", np.percentile(traces, (16.0, 84.0))) print("95% credibility interval:", np.percentile(traces, (2.5, 97.5))) print("99% credibility interval:", np.percentile(traces, (0.5, 99.5))) else: if traces.ndim > 2: # Parameter values are at least matrix-valued, reshape to a vector. traces = traces.reshape(traces.shape[0], np.prod(traces.shape[1:])) for i in range(traces.shape[1]): # give summary for each element of this parameter separately # Parameter is scalar valued, so this is easy print("Posterior summary for parameter", name, " element", i) print("----------------------------------------------") print("Effective number of independent samples:", effective_nsamples[i]) print("Median:", np.median(traces[:, i])) print("Standard deviation:", np.std(traces[:, i])) print("68% credibility interval:", np.percentile(traces[:, i], (16.0, 84.0))) print("95% credibility interval:", np.percentile(traces[:, i], (2.5, 97.5))) print("99% credibility interval:", np.percentile(traces[:, i], (0.5, 99.5))) def newaxis(self): for key in self._samples.keys(): if len(self._samples[key].shape) == 1: self._samples[key] = self._samples[key][:,np.newaxis]
{ "content_hash": "980848820bd3a467977f2cca42438c73", "timestamp": "", "source": "github", "line_count": 408, "max_line_length": 120, "avg_line_length": 44.97794117647059, "alnum_prop": 0.597896572393875, "repo_name": "brandonckelly/carma_pack", "id": "057afae722b9581e6d0186bfd2cd44395214b0dc", "size": "18351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/carmcmc/samplers.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "207171" }, { "name": "Python", "bytes": "140314" }, { "name": "Roff", "bytes": "3126" } ], "symlink_target": "" }
package com.connectsdk.service.netcast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class NetcastApplicationsParser extends DefaultHandler { public JSONArray applicationList; public JSONObject application; public String value; public final String DATA = "data"; public final String AUID = "auid"; public final String NAME = "name"; public final String TYPE = "type"; public final String CPID = "cpid"; public final String ADULT = "adult"; public final String ICON_NAME = "icon_name"; public NetcastApplicationsParser() { applicationList = new JSONArray(); value = null; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(DATA)) { application = new JSONObject(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { try { if (qName.equalsIgnoreCase(DATA)) { applicationList.put(application); } else if (qName.equalsIgnoreCase(AUID)) { application.put("id", value); } else if (qName.equalsIgnoreCase(NAME)) { application.put("title", value); } else if (qName.equalsIgnoreCase(TYPE)) { application.put(TYPE, value); } else if (qName.equalsIgnoreCase(CPID)) { application.put(CPID, value); } else if (qName.equalsIgnoreCase(ADULT)) { application.put(ADULT, value); } else if (qName.equalsIgnoreCase(ICON_NAME)) { application.put(ICON_NAME, value); } value = null; } catch (JSONException e) { e.printStackTrace(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { value = new String(ch, start, length); } public JSONArray getApplications() { return applicationList; } }
{ "content_hash": "68ce7f17417ccb330caaaf63560ba0ec", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 117, "avg_line_length": 30.355263157894736, "alnum_prop": 0.6042479410489814, "repo_name": "david-fenton/Connect-SDK-Cordova-Plugin-Android", "id": "6b04090e5209e686226c29945d582aa7f06418ed", "size": "3003", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "Connect-SDK-Android/core/src/com/connectsdk/service/netcast/NetcastApplicationsParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1181430" }, { "name": "JavaScript", "bytes": "68020" } ], "symlink_target": "" }
using System; using System.Globalization; namespace Cauldron { /// <summary> /// Provides useful methods regarding <see cref="DateTime"/> /// </summary> public static class Utilities { /// <summary> /// Returns the <see cref="DateTime"/> representation of the year and week of year /// </summary> /// <param name="year">The year to convert</param> /// <param name="weekOfYear">The week of year to convert</param> /// <exception cref="ArgumentOutOfRangeException">Argument <paramref name="weekOfYear"/> is more than the given year has weeks</exception> /// <exception cref="ArgumentOutOfRangeException">Argument <paramref name="weekOfYear"/> is lower than 0</exception> /// <returns></returns> public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear) { // http://stackoverflow.com/questions/662379/calculate-date-from-week-number var jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; var firstThursday = jan1.AddDays(daysOffset); var calendar = CultureInfo.CurrentCulture.Calendar; int firstWeek = calendar.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); if (weekOfYear > GetWeeksInYear(year)) throw new ArgumentOutOfRangeException("Argument weekOfYear is more than the given year has weeks"); if (weekOfYear <= 0) throw new ArgumentOutOfRangeException("Argument weekOfYear is lower than 0"); var weekNum = weekOfYear; if (firstWeek <= 1) weekNum -= 1; var result = firstThursday.AddDays(weekNum * 7); return result.AddDays(-3); } /// <summary> /// Returns the maximum of the week of the given year /// </summary> /// <param name="year">The year to get the maximum weeks</param> /// <returns>The maximum week of the given year</returns> public static int GetWeeksInYear(int year) { var dateTimeInfo = DateTimeFormatInfo.CurrentInfo; var date1 = new DateTime(year, 12, 31); var calendar = dateTimeInfo.Calendar; return calendar.GetWeekOfYear(date1, dateTimeInfo.CalendarWeekRule, dateTimeInfo.FirstDayOfWeek); } } }
{ "content_hash": "9ff49df65b4eabed00b9a1bde6b5a49c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 146, "avg_line_length": 41.13559322033898, "alnum_prop": 0.6279357231149567, "repo_name": "Capgemini/Cauldron", "id": "c972de0f6e1fa14108c047b80166288804a9a452", "size": "2429", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Shared/Cauldron/Utilities.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "603" }, { "name": "C#", "bytes": "6246714" }, { "name": "PowerShell", "bytes": "8223" } ], "symlink_target": "" }
using TermWin tshow( Main, title="Main" )
{ "content_hash": "815febf15f1b81936c73ead77808eaab", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 27, "avg_line_length": 11, "alnum_prop": 0.6818181818181818, "repo_name": "JuliaPackageMirrors/TermWin.jl", "id": "6b605cd987ac19e48f8a9ba8d979a43ec6a86ab8", "size": "44", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/twMain.jl", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "297856" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator; use ProxyManager\Generator\MagicMethodGenerator; use Zend\Code\Generator\ParameterGenerator; use ProxyManager\ProxyGenerator\LazyLoadingGhost\PropertyGenerator\PrivatePropertiesMap; use ProxyManager\ProxyGenerator\LazyLoadingGhost\PropertyGenerator\ProtectedPropertiesMap; use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap; use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator; use ReflectionClass; use Zend\Code\Generator\MethodGenerator; use Zend\Code\Generator\PropertyGenerator; /** * Magic `__unset` method for lazy loading ghost objects * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class MagicUnset extends MagicMethodGenerator { /** * @var string */ private $callParentTemplate = <<<'PHP' %s if (isset(self::$%s[$name])) { unset($this->$name); return; } if (isset(self::$%s[$name])) { // check protected property access via compatible class $callers = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); $caller = isset($callers[1]) ? $callers[1] : []; $object = isset($caller['object']) ? $caller['object'] : ''; $expectedType = self::$%s[$name]; if ($object instanceof $expectedType) { unset($this->$name); return; } $class = isset($caller['class']) ? $caller['class'] : ''; if ($class === $expectedType || is_subclass_of($class, $expectedType) || $class === 'ReflectionProperty') { unset($this->$name); return; } } elseif (isset(self::$%s[$name])) { // check private property access via same class $callers = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); $caller = isset($callers[1]) ? $callers[1] : []; $class = isset($caller['class']) ? $caller['class'] : ''; static $accessorCache = []; if (isset(self::$%s[$name][$class])) { $cacheKey = $class . '#' . $name; $accessor = isset($accessorCache[$cacheKey]) ? $accessorCache[$cacheKey] : $accessorCache[$cacheKey] = \Closure::bind(function ($instance) use ($name) { unset($instance->$name); }, null, $class); return $accessor($this); } if ('ReflectionProperty' === $class) { $tmpClass = key(self::$%s[$name]); $cacheKey = $tmpClass . '#' . $name; $accessor = isset($accessorCache[$cacheKey]) ? $accessorCache[$cacheKey] : $accessorCache[$cacheKey] = \Closure::bind(function ($instance) use ($name) { unset($instance->$name); }, null, $tmpClass); return $accessor($this); } } %s PHP; /** * @param ReflectionClass $originalClass * @param PropertyGenerator $initializerProperty * @param MethodGenerator $callInitializer * @param PublicPropertiesMap $publicProperties * @param ProtectedPropertiesMap $protectedProperties * @param PrivatePropertiesMap $privateProperties * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException * @throws \InvalidArgumentException */ public function __construct( ReflectionClass $originalClass, PropertyGenerator $initializerProperty, MethodGenerator $callInitializer, PublicPropertiesMap $publicProperties, ProtectedPropertiesMap $protectedProperties, PrivatePropertiesMap $privateProperties ) { parent::__construct($originalClass, '__unset', [new ParameterGenerator('name')]); $override = $originalClass->hasMethod('__unset'); $this->setDocBlock(($override ? "{@inheritDoc}\n" : '') . '@param string $name'); $parentAccess = 'return parent::__unset($name);'; if (! $override) { $parentAccess = PublicScopeSimulator::getPublicAccessSimulationCode( PublicScopeSimulator::OPERATION_UNSET, 'name' ); } $this->setBody(sprintf( $this->callParentTemplate, '$this->' . $initializerProperty->getName() . ' && $this->' . $callInitializer->getName() . '(\'__unset\', array(\'name\' => $name));', $publicProperties->getName(), $protectedProperties->getName(), $protectedProperties->getName(), $privateProperties->getName(), $privateProperties->getName(), $privateProperties->getName(), $parentAccess )); } }
{ "content_hash": "60561ca2269013dfa7d14ec23300fa0f", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 111, "avg_line_length": 32.67857142857143, "alnum_prop": 0.6170491803278688, "repo_name": "rainlike/justshop", "id": "20e352f3406e94a67e33bb68403367837a17b5f3", "size": "5492", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/ocramius/proxy-manager/src/ProxyManager/ProxyGenerator/LazyLoadingGhost/MethodGenerator/MagicUnset.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1153" }, { "name": "CSS", "bytes": "821" }, { "name": "HTML", "bytes": "17134" }, { "name": "JavaScript", "bytes": "1135" }, { "name": "PHP", "bytes": "110346" }, { "name": "Shell", "bytes": "400" } ], "symlink_target": "" }