commit
stringlengths
40
40
old_file
stringlengths
4
184
new_file
stringlengths
4
184
old_contents
stringlengths
1
3.6k
new_contents
stringlengths
5
3.38k
subject
stringlengths
15
778
message
stringlengths
16
6.74k
lang
stringclasses
201 values
license
stringclasses
13 values
repos
stringlengths
6
116k
config
stringclasses
201 values
content
stringlengths
137
7.24k
diff
stringlengths
26
5.55k
diff_length
int64
1
123
relative_diff_length
float64
0.01
89
n_lines_added
int64
0
108
n_lines_deleted
int64
0
106
ac6dd3cb921c2d19f39ce5cea8cdc529897a7590
.codecov.yml
.codecov.yml
ignore: - "/Tests/*" comment: layout: "header, diff" behavior: default require_changes: no
ignore: - "/Tests/*" comment: layout: "header, diff" behavior: default require_changes: no coverage: status: project: default: target: auto threshold: null base: auto paths: "Sources/*"
Configure commit statuses (ignore coverage of Tests files).
Configure commit statuses (ignore coverage of Tests files).
YAML
mit
lorentey/GlueKit,lorentey/GlueKit,lorentey/GlueKit
yaml
## Code Before: ignore: - "/Tests/*" comment: layout: "header, diff" behavior: default require_changes: no ## Instruction: Configure commit statuses (ignore coverage of Tests files). ## Code After: ignore: - "/Tests/*" comment: layout: "header, diff" behavior: default require_changes: no coverage: status: project: default: target: auto threshold: null base: auto paths: "Sources/*"
ignore: - "/Tests/*" comment: layout: "header, diff" behavior: default require_changes: no + coverage: + status: + project: + default: + target: auto + threshold: null + base: auto + paths: "Sources/*"
8
1.333333
8
0
11f4130222b2620d75f363df590eaabf9b62781e
utils/vim/mlir.vim
utils/vim/mlir.vim
" Vim syntax file " Language: MLIR " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif syn keyword mlirType index i1 i2 i4 i8 i13 i16 i32 i64 \ f16 f32 tf_control syn keyword mlirType memref tensor vector syntax keyword mlirKeywords extfunc cfgfunc mlfunc for to step return syntax keyword mlirConditional if else syn match mlirInt "-\=\<\d\+\>" syn match mlirFloat "-\=\<\d\+\.\d\+\>" syn match mlirMapOutline "#.*$" syn match mlirOperator "[+\-*=]" syn region mlirComment start="//" skip="\\$" end="$" syn region mlirString matchgroup=mlirString start=+"+ end=+"+ hi def link mlirComment Comment hi def link mlirKeywords Statement hi def link mlirInt Constant hi def link mlirType Type hi def link mlirMapOutline PreProc hi def link mlirConditional Conditional hi def link mlirString String hi def link mlirOperator Operator hi def link mlirInstruction Operator hi def link mlirAffineOp Operator let b:current_syntax = "mlir"
" Vim syntax file " Language: MLIR " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif syn keyword mlirType index i1 i2 i4 i8 i13 i16 i32 i64 \ f16 f32 tf_control syn keyword mlirType memref tensor vector syntax keyword mlirKeywords extfunc cfgfunc mlfunc for to step return syntax keyword mlirConditional if else syntax keyword mlirCoreOps dim addf addi subf subi mulf muli cmpi select constant affine_apply call call_indirect extract_element getTensor memref_cast tensor_cast load store alloc dealloc dma_start dma_wait syn match mlirInt "-\=\<\d\+\>" syn match mlirFloat "-\=\<\d\+\.\d\+\>" syn match mlirMapOutline "#.*$" syn match mlirOperator "[+\-*=]" syn region mlirComment start="//" skip="\\$" end="$" syn region mlirString matchgroup=mlirString start=+"+ end=+"+ hi def link mlirComment Comment hi def link mlirKeywords Statement hi def link mlirCoreOps Statement hi def link mlirInt Constant hi def link mlirType Type hi def link mlirMapOutline PreProc hi def link mlirConditional Conditional hi def link mlirString String hi def link mlirOperator Operator hi def link mlirInstruction Operator hi def link mlirAffineOp Operator let b:current_syntax = "mlir"
Update vim syntax file to highlight core ops
Update vim syntax file to highlight core ops PiperOrigin-RevId: 227082502
VimL
apache-2.0
DavidNorman/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,DavidNorman/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,renyi533/tensorflow,aam-at/tensorflow,adit-chandra/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,renyi533/tensorflow,gunan/tensorflow,arborh/tensorflow,renyi533/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,xzturn/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,jhseu/tensorflow,arborh/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,DavidNorman/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,jhseu/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,Intel-tensorflow/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,karllessard/tensorflow,karllessard/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,yongtang/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,adit-chandra/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,sarvex/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,xzturn/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,DavidNorman/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,renyi533/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,arborh/tensorflow,tensorflow/tensorflow,annarev/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jhseu/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,DavidNorman/tensorflow,jhseu/tensorflow,aldian/tensorflow,aam-at/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,annarev/tensorflow,karllessard/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,gunan/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,aldian/tensorflow,aldian/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,cxxgtxy/tensorflow,jhseu/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,gunan/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,annarev/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,xzturn/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,karllessard/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,DavidNorman/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aldian/tensorflow,karllessard/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,gunan/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,karllessard/tensorflow,arborh/tensorflow,arborh/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,yongtang/tensorflow,arborh/tensorflow,xzturn/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,petewarden/tensorflow,arborh/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,gunan/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,aldian/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,arborh/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,annarev/tensorflow,jhseu/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,aldian/tensorflow,petewarden/tensorflow,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred
viml
## Code Before: " Vim syntax file " Language: MLIR " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif syn keyword mlirType index i1 i2 i4 i8 i13 i16 i32 i64 \ f16 f32 tf_control syn keyword mlirType memref tensor vector syntax keyword mlirKeywords extfunc cfgfunc mlfunc for to step return syntax keyword mlirConditional if else syn match mlirInt "-\=\<\d\+\>" syn match mlirFloat "-\=\<\d\+\.\d\+\>" syn match mlirMapOutline "#.*$" syn match mlirOperator "[+\-*=]" syn region mlirComment start="//" skip="\\$" end="$" syn region mlirString matchgroup=mlirString start=+"+ end=+"+ hi def link mlirComment Comment hi def link mlirKeywords Statement hi def link mlirInt Constant hi def link mlirType Type hi def link mlirMapOutline PreProc hi def link mlirConditional Conditional hi def link mlirString String hi def link mlirOperator Operator hi def link mlirInstruction Operator hi def link mlirAffineOp Operator let b:current_syntax = "mlir" ## Instruction: Update vim syntax file to highlight core ops PiperOrigin-RevId: 227082502 ## Code After: " Vim syntax file " Language: MLIR " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif syn keyword mlirType index i1 i2 i4 i8 i13 i16 i32 i64 \ f16 f32 tf_control syn keyword mlirType memref tensor vector syntax keyword mlirKeywords extfunc cfgfunc mlfunc for to step return syntax keyword mlirConditional if else syntax keyword mlirCoreOps dim addf addi subf subi mulf muli cmpi select constant affine_apply call call_indirect extract_element getTensor memref_cast tensor_cast load store alloc dealloc dma_start dma_wait syn match mlirInt "-\=\<\d\+\>" syn match mlirFloat "-\=\<\d\+\.\d\+\>" syn match mlirMapOutline "#.*$" syn match mlirOperator "[+\-*=]" syn region mlirComment start="//" skip="\\$" end="$" syn region mlirString matchgroup=mlirString start=+"+ end=+"+ hi def link mlirComment Comment hi def link mlirKeywords Statement hi def link mlirCoreOps Statement hi def link mlirInt Constant hi def link mlirType Type hi def link mlirMapOutline PreProc hi def link mlirConditional Conditional hi def link mlirString String hi def link mlirOperator Operator hi def link mlirInstruction Operator hi def link mlirAffineOp Operator let b:current_syntax = "mlir"
" Vim syntax file " Language: MLIR " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif syn keyword mlirType index i1 i2 i4 i8 i13 i16 i32 i64 \ f16 f32 tf_control syn keyword mlirType memref tensor vector syntax keyword mlirKeywords extfunc cfgfunc mlfunc for to step return syntax keyword mlirConditional if else + syntax keyword mlirCoreOps dim addf addi subf subi mulf muli cmpi select constant affine_apply call call_indirect extract_element getTensor memref_cast tensor_cast load store alloc dealloc dma_start dma_wait syn match mlirInt "-\=\<\d\+\>" syn match mlirFloat "-\=\<\d\+\.\d\+\>" syn match mlirMapOutline "#.*$" syn match mlirOperator "[+\-*=]" syn region mlirComment start="//" skip="\\$" end="$" syn region mlirString matchgroup=mlirString start=+"+ end=+"+ hi def link mlirComment Comment hi def link mlirKeywords Statement + hi def link mlirCoreOps Statement hi def link mlirInt Constant hi def link mlirType Type hi def link mlirMapOutline PreProc hi def link mlirConditional Conditional hi def link mlirString String hi def link mlirOperator Operator hi def link mlirInstruction Operator hi def link mlirAffineOp Operator let b:current_syntax = "mlir"
2
0.057143
2
0
807a3bd06265a0afde54ef78abeb18a3579411ea
README.md
README.md
Square Open Source Portal ========================= A simple, static portal which outlines our open source offerings. Intentionally themed to look like a merchant page on the directory. Development ----------- Due to the use of absolute URLs in CSS files that are (essentially) out of our control, the easiest way to develop is by running with Jekyll. jekyll serve Repositories are listed in the `repos.json` file as a map of repository names to a list of their categories. Invoking the `generate.py` script will update the `index.html` page with the latest repos by using the `index.mustache` file as a template. Run `pip install pystache requests pygithub3` if needed to install python dependencies. Repository data is pulled via the GitHub API (e.g., website). By default the script performs unauthenticated requests, so it's easy to run up against GitHub's limit of [60 unauthenticated requests per hour](http://developer.github.com/v3/#rate-limiting). To make authenticated requests and work around the rate-limiting, add an entry for api.github.com to your ~/.netrc file, preferably with a Personal Access Token from https://github.com/settings/applications. machine api.github.com login YourUsername password PersonalAccessToken Images are loaded by convention from the `repo_images/` directory. Ensure the name is the same as the repo name in the `repos.json` file and has a `.jpg` extension. Currently all images are rotated 10 degrees counter-clockwise to break up the overwhelming horizontal and vertical visual lines on the page.
kinshuk4.github.io - My Portfolio site ====================================== A simple, static portal which outlines my portfolio. Help Taken ---------- I have taken the help from http://square.github.io/.
Update the readme to be more cleaner
docs: Update the readme to be more cleaner
Markdown
mit
kinshuk4/kinshuk4.github.io,kinshuk4/kinshuk4.github.io
markdown
## Code Before: Square Open Source Portal ========================= A simple, static portal which outlines our open source offerings. Intentionally themed to look like a merchant page on the directory. Development ----------- Due to the use of absolute URLs in CSS files that are (essentially) out of our control, the easiest way to develop is by running with Jekyll. jekyll serve Repositories are listed in the `repos.json` file as a map of repository names to a list of their categories. Invoking the `generate.py` script will update the `index.html` page with the latest repos by using the `index.mustache` file as a template. Run `pip install pystache requests pygithub3` if needed to install python dependencies. Repository data is pulled via the GitHub API (e.g., website). By default the script performs unauthenticated requests, so it's easy to run up against GitHub's limit of [60 unauthenticated requests per hour](http://developer.github.com/v3/#rate-limiting). To make authenticated requests and work around the rate-limiting, add an entry for api.github.com to your ~/.netrc file, preferably with a Personal Access Token from https://github.com/settings/applications. machine api.github.com login YourUsername password PersonalAccessToken Images are loaded by convention from the `repo_images/` directory. Ensure the name is the same as the repo name in the `repos.json` file and has a `.jpg` extension. Currently all images are rotated 10 degrees counter-clockwise to break up the overwhelming horizontal and vertical visual lines on the page. ## Instruction: docs: Update the readme to be more cleaner ## Code After: kinshuk4.github.io - My Portfolio site ====================================== A simple, static portal which outlines my portfolio. Help Taken ---------- I have taken the help from http://square.github.io/.
- Square Open Source Portal + kinshuk4.github.io - My Portfolio site - ========================= + ====================================== ? +++++++++++++ + A simple, static portal which outlines my portfolio. - A simple, static portal which outlines our open source offerings. Intentionally - themed to look like a merchant page on the directory. - Development + Help Taken - ----------- ? - + ---------- + I have taken the help from http://square.github.io/. - - Due to the use of absolute URLs in CSS files that are (essentially) out of our - control, the easiest way to develop is by running with Jekyll. - - jekyll serve - - Repositories are listed in the `repos.json` file as a map of repository names - to a list of their categories. Invoking the `generate.py` script will update - the `index.html` page with the latest repos by using the `index.mustache` file - as a template. Run `pip install pystache requests pygithub3` if needed to - install python dependencies. - - Repository data is pulled via the GitHub API (e.g., website). By default the - script performs unauthenticated requests, so it's easy to run up against - GitHub's limit of [60 unauthenticated requests per - hour](http://developer.github.com/v3/#rate-limiting). To make authenticated - requests and work around the rate-limiting, add an entry for api.github.com to - your ~/.netrc file, preferably with a Personal Access Token from - https://github.com/settings/applications. - - machine api.github.com - login YourUsername - password PersonalAccessToken - - Images are loaded by convention from the `repo_images/` directory. Ensure the - name is the same as the repo name in the `repos.json` file and has a `.jpg` - extension. Currently all images are rotated 10 degrees counter-clockwise to - break up the overwhelming horizontal and vertical visual lines on the page.
40
1.081081
6
34
39a8878b9eb2785829e5ddb3c6201622561ef4c5
NavigationReactNative/src/android/src/main/java/com/navigation/reactnative/BottomSheetView.java
NavigationReactNative/src/android/src/main/java/com/navigation/reactnative/BottomSheetView.java
package com.navigation.reactnative; import android.content.Context; import android.view.ViewGroup; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.facebook.react.uimanager.PixelUtil; import com.google.android.material.bottomsheet.BottomSheetBehavior; public class BottomSheetView extends ViewGroup { public BottomSheetView(Context context) { super(context); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setBehavior(new BottomSheetBehavior()); setLayoutParams(params); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); BottomSheetBehavior.from(this).setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { } }
package com.navigation.reactnative; import android.content.Context; import android.view.ViewGroup; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.facebook.react.uimanager.PixelUtil; import com.google.android.material.bottomsheet.BottomSheetBehavior; public class BottomSheetView extends ViewGroup { public BottomSheetView(Context context) { super(context); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); BottomSheetBehavior bottomSheetBehavior = new BottomSheetBehavior(); bottomSheetBehavior.setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); params.setBehavior(bottomSheetBehavior); setLayoutParams(params); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { } }
Set behavior prop before added to window
Set behavior prop before added to window Otherwise there's a noticeable flicker before bottom sheet appears
Java
apache-2.0
grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation
java
## Code Before: package com.navigation.reactnative; import android.content.Context; import android.view.ViewGroup; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.facebook.react.uimanager.PixelUtil; import com.google.android.material.bottomsheet.BottomSheetBehavior; public class BottomSheetView extends ViewGroup { public BottomSheetView(Context context) { super(context); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setBehavior(new BottomSheetBehavior()); setLayoutParams(params); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); BottomSheetBehavior.from(this).setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { } } ## Instruction: Set behavior prop before added to window Otherwise there's a noticeable flicker before bottom sheet appears ## Code After: package com.navigation.reactnative; import android.content.Context; import android.view.ViewGroup; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.facebook.react.uimanager.PixelUtil; import com.google.android.material.bottomsheet.BottomSheetBehavior; public class BottomSheetView extends ViewGroup { public BottomSheetView(Context context) { super(context); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); BottomSheetBehavior bottomSheetBehavior = new BottomSheetBehavior(); bottomSheetBehavior.setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); params.setBehavior(bottomSheetBehavior); setLayoutParams(params); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { } }
package com.navigation.reactnative; import android.content.Context; import android.view.ViewGroup; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.facebook.react.uimanager.PixelUtil; import com.google.android.material.bottomsheet.BottomSheetBehavior; public class BottomSheetView extends ViewGroup { public BottomSheetView(Context context) { super(context); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + BottomSheetBehavior bottomSheetBehavior = new BottomSheetBehavior(); + bottomSheetBehavior.setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); - params.setBehavior(new BottomSheetBehavior()); ? ^^^^^ -- + params.setBehavior(bottomSheetBehavior); ? ^ setLayoutParams(params); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - BottomSheetBehavior.from(this).setPeekHeight((int) PixelUtil.toPixelFromDIP(200)); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { } }
10
0.357143
3
7
2a18497c9cc7579ad45d2c2ad80845b14b1b1afb
package.json
package.json
{ "name": "panama-network", "version": "0.1.0", "description": "Visualization of influence networks for candidates in Panama", "main": "Gruntfile.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "www.github.io/masegalab/panama-network" }, "keywords": [ "candidates", "elections", "panama" ], "author": "Masega", "license": "ISC", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-copy": "~0.5.0", "grunt-contrib-less": "~0.9.0" } }
{ "name": "panama-network", "version": "0.1.0", "description": "Visualization of influence networks for candidates in Panama", "main": "Gruntfile.js", "repository": { "type": "git", "url": "www.github.io/masegalab/panama-network" }, "keywords": [ "candidates", "elections", "panama" ], "author": "Masega", "license": "ISC", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-copy": "~0.5.0", "grunt-contrib-less": "~0.9.0" } }
Increase version number to 0.1.0
Increase version number to 0.1.0
JSON
mit
poderomedia/nodemapper,poderopedia/panama-network
json
## Code Before: { "name": "panama-network", "version": "0.1.0", "description": "Visualization of influence networks for candidates in Panama", "main": "Gruntfile.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "www.github.io/masegalab/panama-network" }, "keywords": [ "candidates", "elections", "panama" ], "author": "Masega", "license": "ISC", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-copy": "~0.5.0", "grunt-contrib-less": "~0.9.0" } } ## Instruction: Increase version number to 0.1.0 ## Code After: { "name": "panama-network", "version": "0.1.0", "description": "Visualization of influence networks for candidates in Panama", "main": "Gruntfile.js", "repository": { "type": "git", "url": "www.github.io/masegalab/panama-network" }, "keywords": [ "candidates", "elections", "panama" ], "author": "Masega", "license": "ISC", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-copy": "~0.5.0", "grunt-contrib-less": "~0.9.0" } }
{ "name": "panama-network", "version": "0.1.0", "description": "Visualization of influence networks for candidates in Panama", "main": "Gruntfile.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, "repository": { "type": "git", "url": "www.github.io/masegalab/panama-network" }, "keywords": [ "candidates", "elections", "panama" ], "author": "Masega", "license": "ISC", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-copy": "~0.5.0", "grunt-contrib-less": "~0.9.0" } }
3
0.12
0
3
5682c2a311dbaf94f0b7876b10cabbc90eb88628
hooks/post_gen_project.py
hooks/post_gen_project.py
from __future__ import print_function import os from subprocess import call # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) def remove_version_file(): """Removes the _version file if versionner is going to be used.""" file_name = os.path.join(PROJECT_DIRECTORY, '{{ cookiecutter.project_name }}/_version.py') remove_file(file_name) def install_versioneer(): """Start versioneer in the repository, this will create versioneer.py and _version.py.""" call(['versioneer', 'install']) # 1. Removes _version file and run versionner install if use_versionner == y if '{{ cookiecutter.use_versioneer }}'.lower() == 'y': remove_version_file() try: install_versioneer() except Exception: print( "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
from __future__ import print_function import os from subprocess import call # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) def remove_version_file(): """Removes the _version file if versionner is going to be used.""" file_name = os.path.join(PROJECT_DIRECTORY, '{{ cookiecutter.project_name }}/_version.py') remove_file(file_name) def install_versioneer(): """Start versioneer in the repository, this will create versioneer.py and _version.py.""" try: call(['versioneer', 'install']) except Exception: print( "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install") def init_git(): """Start git repository""" try: call(['git', 'init']) except Exception: print("git isn't avalaible, please install git and run:\n $ git init") # 1. Removes _version file and run versionner install if use_versionner == y if '{{ cookiecutter.use_versioneer }}'.lower() == 'y': remove_version_file() init_git() install_versioneer()
Add git init to post hooks, and move error handling to functions
Add git init to post hooks, and move error handling to functions
Python
mit
rlaverde/spyder-plugin-cookiecutter
python
## Code Before: from __future__ import print_function import os from subprocess import call # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) def remove_version_file(): """Removes the _version file if versionner is going to be used.""" file_name = os.path.join(PROJECT_DIRECTORY, '{{ cookiecutter.project_name }}/_version.py') remove_file(file_name) def install_versioneer(): """Start versioneer in the repository, this will create versioneer.py and _version.py.""" call(['versioneer', 'install']) # 1. Removes _version file and run versionner install if use_versionner == y if '{{ cookiecutter.use_versioneer }}'.lower() == 'y': remove_version_file() try: install_versioneer() except Exception: print( "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install") ## Instruction: Add git init to post hooks, and move error handling to functions ## Code After: from __future__ import print_function import os from subprocess import call # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) def remove_version_file(): """Removes the _version file if versionner is going to be used.""" file_name = os.path.join(PROJECT_DIRECTORY, '{{ cookiecutter.project_name }}/_version.py') remove_file(file_name) def install_versioneer(): """Start versioneer in the repository, this will create versioneer.py and _version.py.""" try: call(['versioneer', 'install']) except Exception: print( "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install") def init_git(): """Start git repository""" try: call(['git', 'init']) except Exception: print("git isn't avalaible, please install git and run:\n $ git init") # 1. Removes _version file and run versionner install if use_versionner == y if '{{ cookiecutter.use_versioneer }}'.lower() == 'y': remove_version_file() init_git() install_versioneer()
from __future__ import print_function import os from subprocess import call # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) def remove_version_file(): """Removes the _version file if versionner is going to be used.""" file_name = os.path.join(PROJECT_DIRECTORY, '{{ cookiecutter.project_name }}/_version.py') remove_file(file_name) def install_versioneer(): """Start versioneer in the repository, this will create versioneer.py and _version.py.""" + try: - call(['versioneer', 'install']) + call(['versioneer', 'install']) ? ++++ + except Exception: + print( + "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install") + + def init_git(): + """Start git repository""" + try: + call(['git', 'init']) + except Exception: + print("git isn't avalaible, please install git and run:\n $ git init") + # 1. Removes _version file and run versionner install if use_versionner == y if '{{ cookiecutter.use_versioneer }}'.lower() == 'y': remove_version_file() - try: + + init_git() - install_versioneer() ? ---- + install_versioneer() - except Exception: - print( - "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
22
0.628571
16
6
e3eb1b90c50d56d9958724cde3d9c1410fd22a8b
test/test_grammars.rb
test/test_grammars.rb
require_relative "./helper" class TestGrammars < Test::Unit::TestCase def setup @grammars = YAML.load(File.read(File.expand_path("../../grammars.yml", __FILE__))) end def test_no_duplicate_scopes scopes = @grammars.values.flatten duplicates = scopes.group_by { |s| s }.select { |k, v| v.length > 1 }.map(&:first) assert duplicates.empty?, "The following scopes appear in grammars.yml more than once:\n#{duplicates.sort.join("\n")}" end end
require_relative "./helper" class TestGrammars < Test::Unit::TestCase ROOT = File.expand_path("../..", __FILE__) def setup @grammars = YAML.load(File.read(File.join(ROOT, "grammars.yml"))) end def test_no_duplicate_scopes scopes = @grammars.values.flatten duplicates = scopes.group_by { |s| s }.select { |k, v| v.length > 1 }.map(&:first) assert duplicates.empty?, "The following scopes appear in grammars.yml more than once:\n#{duplicates.sort.join("\n")}" end def test_submodules_are_in_sync submodules = `git config --list --file "#{File.join(ROOT, ".gitmodules")}"`.lines.grep(/\.path=/).map { |line| line.chomp.split("=", 2).last } # Strip off paths inside the submodule so that just the submodule path remains. listed_submodules = @grammars.keys.grep(/grammar_sources/).map { |source| source[%r{grammar_sources/[^/]+}] } nonexistent_submodules = listed_submodules - submodules unlisted_submodules = submodules - listed_submodules message = "" unless nonexistent_submodules.empty? message << "The following submodules are listed in grammars.yml but don't seem to exist in the repository. Maybe you should remove them from grammars.yml?\n" message << nonexistent_submodules.sort.join("\n") end unless unlisted_submodules.empty? message << "\n" unless message.empty? message << "The following submodules exist in the repository but aren't listed in grammars.yml. Maybe you should add them to grammars.yml?\n" message << unlisted_submodules.sort.join("\n") end assert nonexistent_submodules.empty? && unlisted_submodules.empty?, message end end
Test that grammars.yml agrees with the list of submodules
Test that grammars.yml agrees with the list of submodules If any submodules are missing from grammars.yml, or are listed in grammars.yml but missing from the repo, the test will fail. Eventually it would be good to test that the scopes for each submodule are accurate, but that will take some more work.
Ruby
mit
pchaigno/linguist,marcojonker/test,georgesuperman/linguist,pchaigno/linguist,Mx7f/linguist,kyoungrok0517/linguist,sebgod/linguist,erkyrath/linguist,SRI-CSL/linguist,BerkeleyTrue/linguist,sagar290/linguist,matt40k/linguist,alitalia/linguist,stanhu/linguist,wcandillon/linguist,manveru/linguist,MahmoudFayed/linguist,wcandillon/linguist,phpsgi/linguist,scttnlsn/linguist,nburkley/linguist,erkyrath/linguist,nburkley/linguist,meunierfrederic/octocatlinguist,JJ/linguist,hcatlin/linguist,adamkaplan/linguist,R4PaSs/linguist,mattn/linguist,stanhu/linguist,manveru/linguist,ya7lelkom/linguist,stanhu/linguist,yyx990803/linguist,Rockyspade/linguist,github/linguist,jrnold/linguist,ppaulweber/github-linguist,SRI-CSL/linguist,sagar290/linguist,martynbm/linguist,JJ/linguist,yyx990803/linguist,cybernet14/linguist,marcojonker/test,ammaraskar/linguist,pchaigno/linguist,yyx990803/linguist,ammaraskar/linguist,yscho/linguist,stanhu/linguist,phpsgi/linguist,douglas-larocca/linguist,0a-/linguist,iblech/linguist,jjatria/linguist,chiranjeevjain/linguist,mwpastore/linguist,anhongyue/test222,alvarotrigo/linguist,sideci-sample/sideci-sample-linguist,MadcapJake/linguist,FStarLang/linguist,JJ/linguist,yscho/linguist,MostAwesomeDude/linguist,erkyrath/linguist,kr/linguist,adamkaplan/linguist,tschf/linguist,jtbandes/linguist,alvarotrigo/linguist,cybernet14/linguist,PsichiX/linguist,CegepVictoriaville/linguist,assimovt/ling-ist,jrnold/linguist,pcantrell/linguist,bluebear94/linguist,sebgod/linguist,a0viedo/linguist,meunierfrederic/octocatlinguist,a0viedo/linguist,douglas-larocca/linguist,Rockyspade/linguist,bluebear94/linguist,matt40k/linguist,whitj00/linguist,thejameskyle/linguist,scttnlsn/linguist,github/linguist,pchaigno/linguist,hcutler/linguist,steventhanna/linguist,c-lipka/linguist,BerkeleyTrue/linguist,mcandre/linguist,c-lipka/linguist,tschf/linguist,cokeboL/linguist,hcutler/linguist,anhongyue/test222,CoderXpert/linguist,MahmoudFayed/linguist,chiranjeevjain/linguist,github/linguist,ppaulweber/github-linguist,meunierfrederic/octocatlinguist,JJ/linguist,MostAwesomeDude/linguist,georgesuperman/linguist,mcandre/linguist,MadcapJake/linguist,osorgin/linguist,ilyes14/linguist,ilyes14/linguist,osorgin/linguist,R4PaSs/linguist,jjatria/linguist,seanders/linguist,iblech/linguist,PsichiX/linguist,yyx990803/linguist,whitj00/linguist,davidzchen/linguist,FStarLang/linguist,assimovt/ling-ist,steventhanna/linguist,kyoungrok0517/linguist,mattn/linguist,thejameskyle/linguist,CegepVictoriaville/linguist,mwpastore/linguist,alitalia/linguist,kr/linguist,jtbandes/linguist,sebgod/linguist,martynbm/linguist,hcatlin/linguist,Mx7f/linguist,cokeboL/linguist,pcantrell/linguist,CoderXpert/linguist,christop/linguist,sideci-sample/sideci-sample-linguist,0a-/linguist,sebgod/linguist,davidzchen/linguist,ya7lelkom/linguist,github/linguist,seanders/linguist,erkyrath/linguist,christop/linguist
ruby
## Code Before: require_relative "./helper" class TestGrammars < Test::Unit::TestCase def setup @grammars = YAML.load(File.read(File.expand_path("../../grammars.yml", __FILE__))) end def test_no_duplicate_scopes scopes = @grammars.values.flatten duplicates = scopes.group_by { |s| s }.select { |k, v| v.length > 1 }.map(&:first) assert duplicates.empty?, "The following scopes appear in grammars.yml more than once:\n#{duplicates.sort.join("\n")}" end end ## Instruction: Test that grammars.yml agrees with the list of submodules If any submodules are missing from grammars.yml, or are listed in grammars.yml but missing from the repo, the test will fail. Eventually it would be good to test that the scopes for each submodule are accurate, but that will take some more work. ## Code After: require_relative "./helper" class TestGrammars < Test::Unit::TestCase ROOT = File.expand_path("../..", __FILE__) def setup @grammars = YAML.load(File.read(File.join(ROOT, "grammars.yml"))) end def test_no_duplicate_scopes scopes = @grammars.values.flatten duplicates = scopes.group_by { |s| s }.select { |k, v| v.length > 1 }.map(&:first) assert duplicates.empty?, "The following scopes appear in grammars.yml more than once:\n#{duplicates.sort.join("\n")}" end def test_submodules_are_in_sync submodules = `git config --list --file "#{File.join(ROOT, ".gitmodules")}"`.lines.grep(/\.path=/).map { |line| line.chomp.split("=", 2).last } # Strip off paths inside the submodule so that just the submodule path remains. listed_submodules = @grammars.keys.grep(/grammar_sources/).map { |source| source[%r{grammar_sources/[^/]+}] } nonexistent_submodules = listed_submodules - submodules unlisted_submodules = submodules - listed_submodules message = "" unless nonexistent_submodules.empty? message << "The following submodules are listed in grammars.yml but don't seem to exist in the repository. Maybe you should remove them from grammars.yml?\n" message << nonexistent_submodules.sort.join("\n") end unless unlisted_submodules.empty? message << "\n" unless message.empty? message << "The following submodules exist in the repository but aren't listed in grammars.yml. Maybe you should add them to grammars.yml?\n" message << unlisted_submodules.sort.join("\n") end assert nonexistent_submodules.empty? && unlisted_submodules.empty?, message end end
require_relative "./helper" class TestGrammars < Test::Unit::TestCase + ROOT = File.expand_path("../..", __FILE__) + def setup - @grammars = YAML.load(File.read(File.expand_path("../../grammars.yml", __FILE__))) ? ^^^^ ------ ------ ---------- + @grammars = YAML.load(File.read(File.join(ROOT, "grammars.yml"))) ? ^^^ ++++++ end def test_no_duplicate_scopes scopes = @grammars.values.flatten duplicates = scopes.group_by { |s| s }.select { |k, v| v.length > 1 }.map(&:first) assert duplicates.empty?, "The following scopes appear in grammars.yml more than once:\n#{duplicates.sort.join("\n")}" end + + def test_submodules_are_in_sync + submodules = `git config --list --file "#{File.join(ROOT, ".gitmodules")}"`.lines.grep(/\.path=/).map { |line| line.chomp.split("=", 2).last } + # Strip off paths inside the submodule so that just the submodule path remains. + listed_submodules = @grammars.keys.grep(/grammar_sources/).map { |source| source[%r{grammar_sources/[^/]+}] } + + nonexistent_submodules = listed_submodules - submodules + unlisted_submodules = submodules - listed_submodules + + message = "" + unless nonexistent_submodules.empty? + message << "The following submodules are listed in grammars.yml but don't seem to exist in the repository. Maybe you should remove them from grammars.yml?\n" + message << nonexistent_submodules.sort.join("\n") + end + unless unlisted_submodules.empty? + message << "\n" unless message.empty? + message << "The following submodules exist in the repository but aren't listed in grammars.yml. Maybe you should add them to grammars.yml?\n" + message << unlisted_submodules.sort.join("\n") + end + + assert nonexistent_submodules.empty? && unlisted_submodules.empty?, message + end end
26
2
25
1
9d54e5312484b270b245adcb992e84a462976d3c
src/main/stores/reactions.ts
src/main/stores/reactions.ts
import { observe } from "mobx" import { isNotNull } from "../../common/helpers/array" import { resetSelection } from "../actions" import MIDIOutput from "../services/MIDIOutput" import RootStore from "./RootStore" export const registerReactions = (rootStore: RootStore) => { // reset selection when tool changed observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore)) // sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled const updateOutputDevices = () => { const { midiDeviceStore } = rootStore rootStore.services.player.allSoundsOff() const getMIDIDeviceEntries = () => Array.from(midiDeviceStore.enabledOutputIds.values()) .map((deviceId) => { const device = midiDeviceStore.outputs.find((d) => d.id === deviceId) if (device === undefined) { console.error(`device not found: ${deviceId}`) return null } return { synth: new MIDIOutput(device), isEnabled: true } }) .filter(isNotNull) rootStore.services.synthGroup.outputs = [ { synth: rootStore.services.synth, isEnabled: midiDeviceStore.isFactorySoundEnabled, }, ...getMIDIDeviceEntries(), ] } observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices) observe( rootStore.midiDeviceStore, "isFactorySoundEnabled", updateOutputDevices ) }
import { autorun, observe } from "mobx" import { isNotNull } from "../../common/helpers/array" import { emptySelection } from "../../common/selection/Selection" import { resetSelection } from "../actions" import MIDIOutput from "../services/MIDIOutput" import RootStore from "./RootStore" export const registerReactions = (rootStore: RootStore) => { // reset selection when tool changed observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore)) // sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled const updateOutputDevices = () => { const { midiDeviceStore } = rootStore rootStore.services.player.allSoundsOff() const getMIDIDeviceEntries = () => Array.from(midiDeviceStore.enabledOutputIds.values()) .map((deviceId) => { const device = midiDeviceStore.outputs.find((d) => d.id === deviceId) if (device === undefined) { console.error(`device not found: ${deviceId}`) return null } return { synth: new MIDIOutput(device), isEnabled: true } }) .filter(isNotNull) rootStore.services.synthGroup.outputs = [ { synth: rootStore.services.synth, isEnabled: midiDeviceStore.isFactorySoundEnabled, }, ...getMIDIDeviceEntries(), ] } observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices) observe( rootStore.midiDeviceStore, "isFactorySoundEnabled", updateOutputDevices ) // reset selection when change track autorun(() => { // deep observe const _ = rootStore.song.selectedTrackId rootStore.pianoRollStore.selection = emptySelection }) }
Remove selection when track changed
Remove selection when track changed
TypeScript
mit
ryohey/signal,ryohey/signal,ryohey/signal
typescript
## Code Before: import { observe } from "mobx" import { isNotNull } from "../../common/helpers/array" import { resetSelection } from "../actions" import MIDIOutput from "../services/MIDIOutput" import RootStore from "./RootStore" export const registerReactions = (rootStore: RootStore) => { // reset selection when tool changed observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore)) // sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled const updateOutputDevices = () => { const { midiDeviceStore } = rootStore rootStore.services.player.allSoundsOff() const getMIDIDeviceEntries = () => Array.from(midiDeviceStore.enabledOutputIds.values()) .map((deviceId) => { const device = midiDeviceStore.outputs.find((d) => d.id === deviceId) if (device === undefined) { console.error(`device not found: ${deviceId}`) return null } return { synth: new MIDIOutput(device), isEnabled: true } }) .filter(isNotNull) rootStore.services.synthGroup.outputs = [ { synth: rootStore.services.synth, isEnabled: midiDeviceStore.isFactorySoundEnabled, }, ...getMIDIDeviceEntries(), ] } observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices) observe( rootStore.midiDeviceStore, "isFactorySoundEnabled", updateOutputDevices ) } ## Instruction: Remove selection when track changed ## Code After: import { autorun, observe } from "mobx" import { isNotNull } from "../../common/helpers/array" import { emptySelection } from "../../common/selection/Selection" import { resetSelection } from "../actions" import MIDIOutput from "../services/MIDIOutput" import RootStore from "./RootStore" export const registerReactions = (rootStore: RootStore) => { // reset selection when tool changed observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore)) // sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled const updateOutputDevices = () => { const { midiDeviceStore } = rootStore rootStore.services.player.allSoundsOff() const getMIDIDeviceEntries = () => Array.from(midiDeviceStore.enabledOutputIds.values()) .map((deviceId) => { const device = midiDeviceStore.outputs.find((d) => d.id === deviceId) if (device === undefined) { console.error(`device not found: ${deviceId}`) return null } return { synth: new MIDIOutput(device), isEnabled: true } }) .filter(isNotNull) rootStore.services.synthGroup.outputs = [ { synth: rootStore.services.synth, isEnabled: midiDeviceStore.isFactorySoundEnabled, }, ...getMIDIDeviceEntries(), ] } observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices) observe( rootStore.midiDeviceStore, "isFactorySoundEnabled", updateOutputDevices ) // reset selection when change track autorun(() => { // deep observe const _ = rootStore.song.selectedTrackId rootStore.pianoRollStore.selection = emptySelection }) }
- import { observe } from "mobx" + import { autorun, observe } from "mobx" ? +++++++++ import { isNotNull } from "../../common/helpers/array" + import { emptySelection } from "../../common/selection/Selection" import { resetSelection } from "../actions" import MIDIOutput from "../services/MIDIOutput" import RootStore from "./RootStore" export const registerReactions = (rootStore: RootStore) => { // reset selection when tool changed observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore)) // sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled const updateOutputDevices = () => { const { midiDeviceStore } = rootStore rootStore.services.player.allSoundsOff() const getMIDIDeviceEntries = () => Array.from(midiDeviceStore.enabledOutputIds.values()) .map((deviceId) => { const device = midiDeviceStore.outputs.find((d) => d.id === deviceId) if (device === undefined) { console.error(`device not found: ${deviceId}`) return null } return { synth: new MIDIOutput(device), isEnabled: true } }) .filter(isNotNull) rootStore.services.synthGroup.outputs = [ { synth: rootStore.services.synth, isEnabled: midiDeviceStore.isFactorySoundEnabled, }, ...getMIDIDeviceEntries(), ] } observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices) observe( rootStore.midiDeviceStore, "isFactorySoundEnabled", updateOutputDevices ) + + // reset selection when change track + autorun(() => { + // deep observe + const _ = rootStore.song.selectedTrackId + rootStore.pianoRollStore.selection = emptySelection + }) }
10
0.227273
9
1
6aad731cd3808e784530e8632cf778c2b9e19543
gcsa/util/date_time_util.py
gcsa/util/date_time_util.py
from datetime import datetime, timedelta, date import pytz from tzlocal import get_localzone def get_utc_datetime(dt, *args, **kwargs): if isinstance(dt, datetime): return dt.isoformat() else: return datetime(dt, *args, **kwargs).isoformat() def date_range(start_date, day_count): for n in range(day_count): yield start_date + timedelta(n) def insure_localisation(dt, timezone=str(get_localzone())): """Insures localisation with provided timezone on "datetime" object. Does nothing to object of type "date".""" if isinstance(dt, datetime): tz = pytz.timezone(timezone) if dt.tzinfo is None: dt = tz.localize(dt) return dt elif isinstance(dt, date): return dt else: raise TypeError('"date" or "datetime" object expected, not {!r}.'.format(dt.__class__.__name__))
from datetime import datetime, date import pytz from tzlocal import get_localzone def insure_localisation(dt, timezone=str(get_localzone())): """Insures localisation with provided timezone on "datetime" object. Does nothing to object of type "date".""" if isinstance(dt, datetime): tz = pytz.timezone(timezone) if dt.tzinfo is None: dt = tz.localize(dt) return dt elif isinstance(dt, date): return dt else: raise TypeError('"date" or "datetime" object expected, not {!r}.'.format(dt.__class__.__name__))
Remove unused functions from util
Remove unused functions from util
Python
mit
kuzmoyev/Google-Calendar-Simple-API
python
## Code Before: from datetime import datetime, timedelta, date import pytz from tzlocal import get_localzone def get_utc_datetime(dt, *args, **kwargs): if isinstance(dt, datetime): return dt.isoformat() else: return datetime(dt, *args, **kwargs).isoformat() def date_range(start_date, day_count): for n in range(day_count): yield start_date + timedelta(n) def insure_localisation(dt, timezone=str(get_localzone())): """Insures localisation with provided timezone on "datetime" object. Does nothing to object of type "date".""" if isinstance(dt, datetime): tz = pytz.timezone(timezone) if dt.tzinfo is None: dt = tz.localize(dt) return dt elif isinstance(dt, date): return dt else: raise TypeError('"date" or "datetime" object expected, not {!r}.'.format(dt.__class__.__name__)) ## Instruction: Remove unused functions from util ## Code After: from datetime import datetime, date import pytz from tzlocal import get_localzone def insure_localisation(dt, timezone=str(get_localzone())): """Insures localisation with provided timezone on "datetime" object. Does nothing to object of type "date".""" if isinstance(dt, datetime): tz = pytz.timezone(timezone) if dt.tzinfo is None: dt = tz.localize(dt) return dt elif isinstance(dt, date): return dt else: raise TypeError('"date" or "datetime" object expected, not {!r}.'.format(dt.__class__.__name__))
- from datetime import datetime, timedelta, date ? ----------- + from datetime import datetime, date import pytz from tzlocal import get_localzone - - - def get_utc_datetime(dt, *args, **kwargs): - if isinstance(dt, datetime): - return dt.isoformat() - else: - return datetime(dt, *args, **kwargs).isoformat() - - - def date_range(start_date, day_count): - for n in range(day_count): - yield start_date + timedelta(n) def insure_localisation(dt, timezone=str(get_localzone())): """Insures localisation with provided timezone on "datetime" object. Does nothing to object of type "date".""" if isinstance(dt, datetime): tz = pytz.timezone(timezone) if dt.tzinfo is None: dt = tz.localize(dt) return dt elif isinstance(dt, date): return dt else: raise TypeError('"date" or "datetime" object expected, not {!r}.'.format(dt.__class__.__name__))
14
0.4375
1
13
5741bf52684a02268e13856146ec64b634fb2c6c
stylesheets/design-patterns/_alpha-beta.scss
stylesheets/design-patterns/_alpha-beta.scss
@import "../colours"; @import "../typography"; @import "../shims"; @import "../grid_layout"; // Phase banner usage: // // .phase-banner { // @include phase-banner($state: beta); // } @mixin phase-banner($state: alpha) { padding: 10px 0 8px; @include media(tablet) { padding-bottom: 10px; } border-bottom: 1px solid $border-colour; p { margin: 0; color: $banner-text-colour; @include core-16; } .phase-tag { @include phase-tag($state); } span { vertical-align: baseline; } } // Phase tag usage: // // Alpha // .phase-tag { // @include phase-tag; // } // // Beta // .phase-tag { // @include phase-tag(beta); // } @mixin phase-tag($state: alpha) { @include inline-block; margin: 0 8px 0 0; padding: 2px 5px 0; @include bold-16($line-height: 20 / 16); text-transform: uppercase; letter-spacing: 1px; text-decoration: none; color: $white; @if $state == alpha { background-color: $alpha-colour; } @else if $state == beta { background-color: $beta-colour; } }
@import "../colours"; @import "../typography"; @import "../shims"; @import "../grid_layout"; // Phase banner usage: // // .phase-banner { // @include phase-banner($state: beta); // } @mixin phase-banner($state: alpha) { padding: 10px 0 8px; @include media(tablet) { padding-bottom: 10px; } border-bottom: 1px solid $border-colour; p { display: table; margin: 0; color: $banner-text-colour; @include core-16; } .phase-tag { @include phase-tag($state); } span { display: table-cell; vertical-align: baseline; } } // Phase tag usage: // // Alpha // .phase-tag { // @include phase-tag; // } // // Beta // .phase-tag { // @include phase-tag(beta); // } @mixin phase-tag($state: alpha) { @include inline-block; margin: 0 8px 0 0; padding: 2px 5px 0; @include bold-16($line-height: 20 / 16); text-transform: uppercase; letter-spacing: 1px; text-decoration: none; color: $white; @if $state == alpha { background-color: $alpha-colour; } @else if $state == beta { background-color: $beta-colour; } }
Use display:table and table-cell for alignment
Use display:table and table-cell for alignment This ensures that the line of text to the right of the phase tag lines up with the phase tag. For smaller screens, this text no longer wraps underneath the phase tag.
SCSS
mit
alphagov/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit
scss
## Code Before: @import "../colours"; @import "../typography"; @import "../shims"; @import "../grid_layout"; // Phase banner usage: // // .phase-banner { // @include phase-banner($state: beta); // } @mixin phase-banner($state: alpha) { padding: 10px 0 8px; @include media(tablet) { padding-bottom: 10px; } border-bottom: 1px solid $border-colour; p { margin: 0; color: $banner-text-colour; @include core-16; } .phase-tag { @include phase-tag($state); } span { vertical-align: baseline; } } // Phase tag usage: // // Alpha // .phase-tag { // @include phase-tag; // } // // Beta // .phase-tag { // @include phase-tag(beta); // } @mixin phase-tag($state: alpha) { @include inline-block; margin: 0 8px 0 0; padding: 2px 5px 0; @include bold-16($line-height: 20 / 16); text-transform: uppercase; letter-spacing: 1px; text-decoration: none; color: $white; @if $state == alpha { background-color: $alpha-colour; } @else if $state == beta { background-color: $beta-colour; } } ## Instruction: Use display:table and table-cell for alignment This ensures that the line of text to the right of the phase tag lines up with the phase tag. For smaller screens, this text no longer wraps underneath the phase tag. ## Code After: @import "../colours"; @import "../typography"; @import "../shims"; @import "../grid_layout"; // Phase banner usage: // // .phase-banner { // @include phase-banner($state: beta); // } @mixin phase-banner($state: alpha) { padding: 10px 0 8px; @include media(tablet) { padding-bottom: 10px; } border-bottom: 1px solid $border-colour; p { display: table; margin: 0; color: $banner-text-colour; @include core-16; } .phase-tag { @include phase-tag($state); } span { display: table-cell; vertical-align: baseline; } } // Phase tag usage: // // Alpha // .phase-tag { // @include phase-tag; // } // // Beta // .phase-tag { // @include phase-tag(beta); // } @mixin phase-tag($state: alpha) { @include inline-block; margin: 0 8px 0 0; padding: 2px 5px 0; @include bold-16($line-height: 20 / 16); text-transform: uppercase; letter-spacing: 1px; text-decoration: none; color: $white; @if $state == alpha { background-color: $alpha-colour; } @else if $state == beta { background-color: $beta-colour; } }
@import "../colours"; @import "../typography"; @import "../shims"; @import "../grid_layout"; // Phase banner usage: // // .phase-banner { // @include phase-banner($state: beta); // } @mixin phase-banner($state: alpha) { padding: 10px 0 8px; @include media(tablet) { padding-bottom: 10px; } border-bottom: 1px solid $border-colour; p { + display: table; margin: 0; color: $banner-text-colour; @include core-16; } .phase-tag { @include phase-tag($state); } span { + display: table-cell; vertical-align: baseline; } } // Phase tag usage: // // Alpha // .phase-tag { // @include phase-tag; // } // // Beta // .phase-tag { // @include phase-tag(beta); // } @mixin phase-tag($state: alpha) { @include inline-block; margin: 0 8px 0 0; padding: 2px 5px 0; @include bold-16($line-height: 20 / 16); text-transform: uppercase; letter-spacing: 1px; text-decoration: none; color: $white; @if $state == alpha { background-color: $alpha-colour; } @else if $state == beta { background-color: $beta-colour; } }
2
0.03125
2
0
3a50f11618963554555a1b3fe6d90418d0744e16
shell_tips.sh
shell_tips.sh
echo "$1 $2" | awk '{print ($1+$2-1)/$2}' # floor division @ awk echo "$1 $2" | awk '{print int($1/$2)}'
echo "$1 $2" | awk '{print ($1+$2-1)/$2}' # floor division @ awk echo "$1 $2" | awk '{print int($1/$2)}' # edit a string with sed sed 's/_/ /g' <<< "el_stringo" # >> O/P: "el stringo"
Edit a string with sed
Edit a string with sed
Shell
cc0-1.0
yunque/thinkingaboutthinking,yunque/thinkingaboutthinking
shell
## Code Before: echo "$1 $2" | awk '{print ($1+$2-1)/$2}' # floor division @ awk echo "$1 $2" | awk '{print int($1/$2)}' ## Instruction: Edit a string with sed ## Code After: echo "$1 $2" | awk '{print ($1+$2-1)/$2}' # floor division @ awk echo "$1 $2" | awk '{print int($1/$2)}' # edit a string with sed sed 's/_/ /g' <<< "el_stringo" # >> O/P: "el stringo"
echo "$1 $2" | awk '{print ($1+$2-1)/$2}' # floor division @ awk echo "$1 $2" | awk '{print int($1/$2)}' + + # edit a string with sed + sed 's/_/ /g' <<< "el_stringo" + # >> O/P: "el stringo"
4
1
4
0
a87ff2a898507de906ab4a68dd6fa5b9f214b303
aliases_freebsd.bash
aliases_freebsd.bash
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " export PAGER=less export EDITOR=vim source "${DOTFILES_DIR}aliases_shared.bash" #built ins alias grepc="grep -nrP --color=always" source "${DOTFILES_DIR}aliases_shared_footer.bash"
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " export PAGER=less export EDITOR=vim source "${DOTFILES_DIR}aliases_shared.bash" #built ins alias grepc="grep -nrP --color=always" alias pkg="sudo pkg" source "${DOTFILES_DIR}aliases_shared_footer.bash"
Add freebsd alias for pkg
Add freebsd alias for pkg
Shell
mit
allen-garvey/bash-dotfiles
shell
## Code Before: export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " export PAGER=less export EDITOR=vim source "${DOTFILES_DIR}aliases_shared.bash" #built ins alias grepc="grep -nrP --color=always" source "${DOTFILES_DIR}aliases_shared_footer.bash" ## Instruction: Add freebsd alias for pkg ## Code After: export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " export PAGER=less export EDITOR=vim source "${DOTFILES_DIR}aliases_shared.bash" #built ins alias grepc="grep -nrP --color=always" alias pkg="sudo pkg" source "${DOTFILES_DIR}aliases_shared_footer.bash"
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ " export PAGER=less export EDITOR=vim source "${DOTFILES_DIR}aliases_shared.bash" #built ins alias grepc="grep -nrP --color=always" + alias pkg="sudo pkg" + source "${DOTFILES_DIR}aliases_shared_footer.bash"
2
0.142857
2
0
1305afacf5d8032a476d6eed5f9e5e498be47a4d
app/views/person_sessions/show.html.erb
app/views/person_sessions/show.html.erb
<% @page_title = "Logged-in as #{current_person.email}" %> <div class="tabs"> <%= link_to('Public Homepage', "/") %> | <%= link_to('Admin Pages', admin_events_path) %> | <%= link_to "Logout", person_session_path, :method => :delete %> </div>
<% @page_title = "Logged-in as #{current_person.login}" %> <h2>You are logged in as <%= current_person.login %></h2> <div class="tabs top_margin"> <%= link_to("#{ASSOCIATION.short_name} Homepage", root_url(:protocol => "http")) %> | <% if administrator? -%> <%= link_to('Admin Pages', admin_events_path) %> | <% end -%> <%= link_to "Logout", person_session_path, :method => :delete %> </div>
Make person current session page prettier
Make person current session page prettier
HTML+ERB
mit
scottwillson/racing_on_rails,scottwillson/racing_on_rails,scottwillson/racing_on_rails,scottwillson/racing_on_rails
html+erb
## Code Before: <% @page_title = "Logged-in as #{current_person.email}" %> <div class="tabs"> <%= link_to('Public Homepage', "/") %> | <%= link_to('Admin Pages', admin_events_path) %> | <%= link_to "Logout", person_session_path, :method => :delete %> </div> ## Instruction: Make person current session page prettier ## Code After: <% @page_title = "Logged-in as #{current_person.login}" %> <h2>You are logged in as <%= current_person.login %></h2> <div class="tabs top_margin"> <%= link_to("#{ASSOCIATION.short_name} Homepage", root_url(:protocol => "http")) %> | <% if administrator? -%> <%= link_to('Admin Pages', admin_events_path) %> | <% end -%> <%= link_to "Logout", person_session_path, :method => :delete %> </div>
- <% @page_title = "Logged-in as #{current_person.email}" %> ? ^^^ ^ + <% @page_title = "Logged-in as #{current_person.login}" %> ? ^^^ ^ + <h2>You are logged in as <%= current_person.login %></h2> + - <div class="tabs"> + <div class="tabs top_margin"> ? +++++++++++ - <%= link_to('Public Homepage', "/") %> | + <%= link_to("#{ASSOCIATION.short_name} Homepage", root_url(:protocol => "http")) %> | + <% if administrator? -%> <%= link_to('Admin Pages', admin_events_path) %> | + <% end -%> <%= link_to "Logout", person_session_path, :method => :delete %> </div>
10
1.428571
7
3
73260ef3f58f706c2b645becd0fd5d6d19d0c579
src/Validator/Exceptions/FormValidationFailedException.php
src/Validator/Exceptions/FormValidationFailedException.php
<?php namespace SRLabs\Validator\Exceptions; use Exception; class FormValidationFailedException extends Exception { protected $errors; /** * @param string $message * @param int $errors */ public function __construct($message, $errors) { $this->message = $message; $this->errors = $errors; } /** * @return int */ public function getErrors() { return $this->errors; } }
<?php namespace SRLabs\Validator\Exceptions; use Exception; class FormValidationFailedException extends Exception { protected $errors; /** * @param string $message * @param int $errors */ public function __construct($message, $errors) { $this->message = $message . '. '; $this->errors = $errors; foreach ($this->errors->all() as $message) { $this->message .= ' ' . $message; } } /** * @return int */ public function getErrors() { return $this->errors; } }
Add validation error details to exception message
Add validation error details to exception message
PHP
mit
SRLabs/Laravel-Form-Validator
php
## Code Before: <?php namespace SRLabs\Validator\Exceptions; use Exception; class FormValidationFailedException extends Exception { protected $errors; /** * @param string $message * @param int $errors */ public function __construct($message, $errors) { $this->message = $message; $this->errors = $errors; } /** * @return int */ public function getErrors() { return $this->errors; } } ## Instruction: Add validation error details to exception message ## Code After: <?php namespace SRLabs\Validator\Exceptions; use Exception; class FormValidationFailedException extends Exception { protected $errors; /** * @param string $message * @param int $errors */ public function __construct($message, $errors) { $this->message = $message . '. '; $this->errors = $errors; foreach ($this->errors->all() as $message) { $this->message .= ' ' . $message; } } /** * @return int */ public function getErrors() { return $this->errors; } }
+ <?php + - <?php namespace SRLabs\Validator\Exceptions; ? ------ + namespace SRLabs\Validator\Exceptions; use Exception; - class FormValidationFailedException extends Exception { ? -- + class FormValidationFailedException extends Exception + { protected $errors; /** * @param string $message * @param int $errors */ public function __construct($message, $errors) { - $this->message = $message; + $this->message = $message . '. '; ? +++++++ $this->errors = $errors; + + foreach ($this->errors->all() as $message) { + $this->message .= ' ' . $message; + } } /** * @return int */ public function getErrors() { return $this->errors; } - } + }
15
0.576923
11
4
abba08a6a535c202af9c8e2a5e79680b8789b34e
CECProject/src/tests/AllTests.java
CECProject/src/tests/AllTests.java
package tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ EmailBuilderTests.class, EmailTests.class }) public class AllTests { }
package tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ EmailBuilderTests.class, EmailTests.class, EmailSortingTests.class }) public class AllTests { }
Add the sorting test class to the test suite.
Add the sorting test class to the test suite.
Java
mit
amishwins/project-cec-2013,amishwins/project-cec-2013
java
## Code Before: package tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ EmailBuilderTests.class, EmailTests.class }) public class AllTests { } ## Instruction: Add the sorting test class to the test suite. ## Code After: package tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ EmailBuilderTests.class, EmailTests.class, EmailSortingTests.class }) public class AllTests { }
package tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ EmailBuilderTests.class, - EmailTests.class }) ? ^^^ + EmailTests.class, ? ^ + EmailSortingTests.class }) public class AllTests { }
3
0.230769
2
1
dc3d982ea995425fcbba30b80cc4d4de649c503a
library/EventListener/AccessToken.php
library/EventListener/AccessToken.php
<?php namespace Imbo\MetadataSearch\EventListener; use Imbo\EventListener\AccessToken as ImboAccessToken; /** * Access token event listener used for authenticating metadata endpoints * * @author Kristoffer Brabrand <kristoffer@brabrand.net> */ class AccessToken extends ImboAccessToken { public static function getSubscribedEvents() { return [ 'metadata.search' => ['checkAccessToken' => 100] ]; } }
<?php namespace Imbo\MetadataSearch\EventListener; use Imbo\EventListener\AccessToken as ImboAccessToken; /** * Access token event listener adding event hook until introduced in * Imbo core. The event makes it possible for custom resources to hook * onto the core auth flow. * * @author Kristoffer Brabrand <kristoffer@brabrand.net> */ class AccessToken extends ImboAccessToken { public static function getSubscribedEvents() { return [ 'auth.accesstoken' => ['checkAccessToken' => 100], ]; } }
Change event bind on in access token event listener
Change event bind on in access token event listener
PHP
mit
tv2/imbo-metadata-search,tv2/imbo-metadata-search,kbrabrand/imbo-metadata-search,kbrabrand/imbo-metadata-search,imbo/imbo-metadata-search
php
## Code Before: <?php namespace Imbo\MetadataSearch\EventListener; use Imbo\EventListener\AccessToken as ImboAccessToken; /** * Access token event listener used for authenticating metadata endpoints * * @author Kristoffer Brabrand <kristoffer@brabrand.net> */ class AccessToken extends ImboAccessToken { public static function getSubscribedEvents() { return [ 'metadata.search' => ['checkAccessToken' => 100] ]; } } ## Instruction: Change event bind on in access token event listener ## Code After: <?php namespace Imbo\MetadataSearch\EventListener; use Imbo\EventListener\AccessToken as ImboAccessToken; /** * Access token event listener adding event hook until introduced in * Imbo core. The event makes it possible for custom resources to hook * onto the core auth flow. * * @author Kristoffer Brabrand <kristoffer@brabrand.net> */ class AccessToken extends ImboAccessToken { public static function getSubscribedEvents() { return [ 'auth.accesstoken' => ['checkAccessToken' => 100], ]; } }
<?php namespace Imbo\MetadataSearch\EventListener; use Imbo\EventListener\AccessToken as ImboAccessToken; /** - * Access token event listener used for authenticating metadata endpoints + * Access token event listener adding event hook until introduced in + * Imbo core. The event makes it possible for custom resources to hook + * onto the core auth flow. * * @author Kristoffer Brabrand <kristoffer@brabrand.net> */ class AccessToken extends ImboAccessToken { public static function getSubscribedEvents() { return [ - 'metadata.search' => ['checkAccessToken' => 100] ? ^ ^^^^^^^ ^^^^ + 'auth.accesstoken' => ['checkAccessToken' => 100], ? ^^^^^^^^ ++ ^^ ^ + ]; } }
6
0.333333
4
2
fea34788c7ba37f72838cebd97184132fe16339f
src/app/app.module.ts
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule, MdIconRegistry } from '@angular/material'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { HeaderComponent } from './layout/header/header.component'; import { FooterComponent } from './layout/footer/footer.component'; @NgModule({ declarations: [ AppComponent, AboutComponent, HeaderComponent, FooterComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, MaterialModule ], providers: [ MdIconRegistry ], bootstrap: [ AppComponent ] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule, MdIconRegistry } from '@angular/material'; import * as firebase from 'firebase'; // See https://github.com/angular/angularfire2/issues/529 import { AngularFireModule } from 'angularfire2'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { HeaderComponent } from './layout/header/header.component'; import { FooterComponent } from './layout/footer/footer.component'; import { config } from './config/config'; @NgModule({ declarations: [ AppComponent, AboutComponent, HeaderComponent, FooterComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, MaterialModule.forRoot(), AngularFireModule.initializeApp(config.FIREBASE_CONFIG, config.FIREBASE_AUTH_CONFIG), ], providers: [ MdIconRegistry, ], bootstrap: [ AppComponent, ] }) export class AppModule { }
Initialize of Firebase with custom configuration.
Initialize of Firebase with custom configuration.
TypeScript
mit
tarlepp/angular2-firebase-material-demo,tarlepp/Angular-Firebase-Material-Demo,tarlepp/Angular-Firebase-Material-Demo,tarlepp/angular2-firebase-material-demo,tarlepp/angular2-firebase-material-demo
typescript
## Code Before: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule, MdIconRegistry } from '@angular/material'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { HeaderComponent } from './layout/header/header.component'; import { FooterComponent } from './layout/footer/footer.component'; @NgModule({ declarations: [ AppComponent, AboutComponent, HeaderComponent, FooterComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, MaterialModule ], providers: [ MdIconRegistry ], bootstrap: [ AppComponent ] }) export class AppModule { } ## Instruction: Initialize of Firebase with custom configuration. ## Code After: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule, MdIconRegistry } from '@angular/material'; import * as firebase from 'firebase'; // See https://github.com/angular/angularfire2/issues/529 import { AngularFireModule } from 'angularfire2'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { HeaderComponent } from './layout/header/header.component'; import { FooterComponent } from './layout/footer/footer.component'; import { config } from './config/config'; @NgModule({ declarations: [ AppComponent, AboutComponent, HeaderComponent, FooterComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, MaterialModule.forRoot(), AngularFireModule.initializeApp(config.FIREBASE_CONFIG, config.FIREBASE_AUTH_CONFIG), ], providers: [ MdIconRegistry, ], bootstrap: [ AppComponent, ] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule, MdIconRegistry } from '@angular/material'; + import * as firebase from 'firebase'; // See https://github.com/angular/angularfire2/issues/529 + import { AngularFireModule } from 'angularfire2'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { HeaderComponent } from './layout/header/header.component'; import { FooterComponent } from './layout/footer/footer.component'; + import { config } from './config/config'; @NgModule({ declarations: [ AppComponent, AboutComponent, HeaderComponent, FooterComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, - MaterialModule + MaterialModule.forRoot(), ? +++++++++++ + AngularFireModule.initializeApp(config.FIREBASE_CONFIG, config.FIREBASE_AUTH_CONFIG), ], providers: [ - MdIconRegistry + MdIconRegistry, ? + ], bootstrap: [ - AppComponent + AppComponent, ? + ] }) export class AppModule { }
10
0.285714
7
3
1506295380223f5858146e072cd11483fa953164
docs/source/docs/what-is-tailwind.blade.md
docs/source/docs/what-is-tailwind.blade.md
--- extends: _layouts.documentation title: "What is Tailwind?" --- # What is Tailwind? Tailwind is a utility-first CSS framework designed for rapid UI development. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ## Key benefits - Rapidly build beautiful front-end interfaces using ready-to-go utilty classes. - Developing in the browser has never been easier. Stop waiting for your build process. - Drastically reduce the amount of CSS you have to write. - Implement any design without it feeling like you've used a CSS framework. - Dynamically generate your own utilities. Tailwind has been designed for customization. - Generate comparible (if not smaller) CSS files. ## Quick example <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> <img class="max-w-xs" src="/img/adam.jpg"> <div class="text-slate-darker mt-2">Adam Wathan</div> <div class="text-slate text-sm">Web Developer</div> </div> ```html <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> <img class="max-w-xs" src="/img/adam.jpg"> <div class="text-slate-darker mt-2">Adam Wathan</div> <div class="text-slate text-sm">Web Developer</div> </div> ```
--- extends: _layouts.documentation title: "What is Tailwind?" --- # What is Tailwind? - Utility-first (explain what this means) + Talk about problems with premature abstraction in CSS - Powered by PostCSS, use any preprocessor - Responsive as h*ck - For building custom UIs + Doesn't have a "look" + Doesn't come with opinions you have to fight to undo
Add notes we want to cover to 'what is...' page
Add notes we want to cover to 'what is...' page
Markdown
mit
tailwindcss/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss
markdown
## Code Before: --- extends: _layouts.documentation title: "What is Tailwind?" --- # What is Tailwind? Tailwind is a utility-first CSS framework designed for rapid UI development. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ## Key benefits - Rapidly build beautiful front-end interfaces using ready-to-go utilty classes. - Developing in the browser has never been easier. Stop waiting for your build process. - Drastically reduce the amount of CSS you have to write. - Implement any design without it feeling like you've used a CSS framework. - Dynamically generate your own utilities. Tailwind has been designed for customization. - Generate comparible (if not smaller) CSS files. ## Quick example <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> <img class="max-w-xs" src="/img/adam.jpg"> <div class="text-slate-darker mt-2">Adam Wathan</div> <div class="text-slate text-sm">Web Developer</div> </div> ```html <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> <img class="max-w-xs" src="/img/adam.jpg"> <div class="text-slate-darker mt-2">Adam Wathan</div> <div class="text-slate text-sm">Web Developer</div> </div> ``` ## Instruction: Add notes we want to cover to 'what is...' page ## Code After: --- extends: _layouts.documentation title: "What is Tailwind?" --- # What is Tailwind? - Utility-first (explain what this means) + Talk about problems with premature abstraction in CSS - Powered by PostCSS, use any preprocessor - Responsive as h*ck - For building custom UIs + Doesn't have a "look" + Doesn't come with opinions you have to fight to undo
--- extends: _layouts.documentation title: "What is Tailwind?" --- # What is Tailwind? + - Utility-first (explain what this means) + + Talk about problems with premature abstraction in CSS + - Powered by PostCSS, use any preprocessor + - Responsive as h*ck + - For building custom UIs + + Doesn't have a "look" + + Doesn't come with opinions you have to fight to undo - Tailwind is a utility-first CSS framework designed for rapid UI development. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. - - ## Key benefits - - - Rapidly build beautiful front-end interfaces using ready-to-go utilty classes. - - Developing in the browser has never been easier. Stop waiting for your build process. - - Drastically reduce the amount of CSS you have to write. - - Implement any design without it feeling like you've used a CSS framework. - - Dynamically generate your own utilities. Tailwind has been designed for customization. - - Generate comparible (if not smaller) CSS files. - - ## Quick example - - <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> - <img class="max-w-xs" src="/img/adam.jpg"> - <div class="text-slate-darker mt-2">Adam Wathan</div> - <div class="text-slate text-sm">Web Developer</div> - </div> - - ```html - <div class="inline-block p-2 pb-4 bg-white border rounded box-shadow text-center"> - <img class="max-w-xs" src="/img/adam.jpg"> - <div class="text-slate-darker mt-2">Adam Wathan</div> - <div class="text-slate text-sm">Web Developer</div> - </div> - ```
33
1
7
26
e1080d7bd75ce27edac64bebbc55b27caa1c6f8b
src/misc/generate_tools_yml.sh
src/misc/generate_tools_yml.sh
generate_tools_yml(){ if [ -f $1 ]; then rm $1 fi touch $1 echo "- hosts: localhost" >> $1 echo " connection: local" >> $1 echo " vars:" >> $1 echo " roles:" >> $1 echo " - role: ansible-galaxy-tools" >> $1 echo " galaxy_tools_galaxy_instance_url: http://$host:$port/" >> $1 echo " galaxy_tools_api_key: $master_api_key" >> $1 echo " galaxy_tools_tool_list_files: [ \"files/tool_list.yaml\" ]" >> $1 }
generate_tools_yml(){ if [ -f $1 ]; then rm $1 fi touch $1 echo "- hosts: localhost" >> $1 echo " connection: local" >> $1 echo " roles:" >> $1 echo " - role: ansible-galaxy-tools" >> $1 echo " galaxy_tools_galaxy_instance_url: http://$host:$port/" >> $1 echo " galaxy_tools_api_key: $master_api_key" >> $1 echo " galaxy_tools_tool_list_files: [ \"files/common_tool_list.yaml\", \"files/pretreatments_tool_list.yaml\", \"files/functional_assignation_tool_list.yaml\", \"files/taxonomic_assignation_tool_list.yaml\" ]" >> $1 echo " galaxy_server_dir: $PWD/$galaxy_dir/" >> $1 }
Correct script to generation tools.yml for ansible playbook
Correct script to generation tools.yml for ansible playbook
Shell
apache-2.0
ASaiM/framework,ASaiM/framework
shell
## Code Before: generate_tools_yml(){ if [ -f $1 ]; then rm $1 fi touch $1 echo "- hosts: localhost" >> $1 echo " connection: local" >> $1 echo " vars:" >> $1 echo " roles:" >> $1 echo " - role: ansible-galaxy-tools" >> $1 echo " galaxy_tools_galaxy_instance_url: http://$host:$port/" >> $1 echo " galaxy_tools_api_key: $master_api_key" >> $1 echo " galaxy_tools_tool_list_files: [ \"files/tool_list.yaml\" ]" >> $1 } ## Instruction: Correct script to generation tools.yml for ansible playbook ## Code After: generate_tools_yml(){ if [ -f $1 ]; then rm $1 fi touch $1 echo "- hosts: localhost" >> $1 echo " connection: local" >> $1 echo " roles:" >> $1 echo " - role: ansible-galaxy-tools" >> $1 echo " galaxy_tools_galaxy_instance_url: http://$host:$port/" >> $1 echo " galaxy_tools_api_key: $master_api_key" >> $1 echo " galaxy_tools_tool_list_files: [ \"files/common_tool_list.yaml\", \"files/pretreatments_tool_list.yaml\", \"files/functional_assignation_tool_list.yaml\", \"files/taxonomic_assignation_tool_list.yaml\" ]" >> $1 echo " galaxy_server_dir: $PWD/$galaxy_dir/" >> $1 }
generate_tools_yml(){ if [ -f $1 ]; then rm $1 fi touch $1 echo "- hosts: localhost" >> $1 echo " connection: local" >> $1 - echo " vars:" >> $1 echo " roles:" >> $1 echo " - role: ansible-galaxy-tools" >> $1 echo " galaxy_tools_galaxy_instance_url: http://$host:$port/" >> $1 echo " galaxy_tools_api_key: $master_api_key" >> $1 - echo " galaxy_tools_tool_list_files: [ \"files/tool_list.yaml\" ]" >> $1 + echo " galaxy_tools_tool_list_files: [ \"files/common_tool_list.yaml\", \"files/pretreatments_tool_list.yaml\", \"files/functional_assignation_tool_list.yaml\", \"files/taxonomic_assignation_tool_list.yaml\" ]" >> $1 + echo " galaxy_server_dir: $PWD/$galaxy_dir/" >> $1 }
4
0.266667
2
2
99ad6544dd216402326ffc53bbf4b78aff7cab40
script/download-latest-rcedit.js
script/download-latest-rcedit.js
const fs = require('fs') const got = require('got') const path = require('path') const downloadURL = 'https://ci.appveyor.com/api/projects/electron-bot/rcedit/artifacts/Default/rcedit.exe?job=Image:%20Visual%20Studio%202015&branch=master' const filePath = path.join(__dirname, '..', 'bin', 'rcedit.exe') process.on('uncaughtException', (error) => { console.log('Dowload failed:', error.message) }) got.stream(downloadURL).pipe(fs.createWriteStream(filePath))
const fs = require('fs') const got = require('got') const path = require('path') const downloadURL = 'https://ci.appveyor.com/api/projects/electron-bot/rcedit/artifacts/Default/rcedit.exe?job=Image:%20Visual%20Studio%202015&branch=master' const filePath = path.join(__dirname, '..', 'bin', 'rcedit.exe') process.on('uncaughtException', (error) => { console.log('Downloading rcedit.exe failed:', error.message) }) got.stream(downloadURL).pipe(fs.createWriteStream(filePath))
Fix typo in error message
Fix typo in error message
JavaScript
mit
dmascord/node-rcedit,dmascord/node-rcedit
javascript
## Code Before: const fs = require('fs') const got = require('got') const path = require('path') const downloadURL = 'https://ci.appveyor.com/api/projects/electron-bot/rcedit/artifacts/Default/rcedit.exe?job=Image:%20Visual%20Studio%202015&branch=master' const filePath = path.join(__dirname, '..', 'bin', 'rcedit.exe') process.on('uncaughtException', (error) => { console.log('Dowload failed:', error.message) }) got.stream(downloadURL).pipe(fs.createWriteStream(filePath)) ## Instruction: Fix typo in error message ## Code After: const fs = require('fs') const got = require('got') const path = require('path') const downloadURL = 'https://ci.appveyor.com/api/projects/electron-bot/rcedit/artifacts/Default/rcedit.exe?job=Image:%20Visual%20Studio%202015&branch=master' const filePath = path.join(__dirname, '..', 'bin', 'rcedit.exe') process.on('uncaughtException', (error) => { console.log('Downloading rcedit.exe failed:', error.message) }) got.stream(downloadURL).pipe(fs.createWriteStream(filePath))
const fs = require('fs') const got = require('got') const path = require('path') const downloadURL = 'https://ci.appveyor.com/api/projects/electron-bot/rcedit/artifacts/Default/rcedit.exe?job=Image:%20Visual%20Studio%202015&branch=master' const filePath = path.join(__dirname, '..', 'bin', 'rcedit.exe') process.on('uncaughtException', (error) => { - console.log('Dowload failed:', error.message) + console.log('Downloading rcedit.exe failed:', error.message) ? + ++++++++++++++ }) got.stream(downloadURL).pipe(fs.createWriteStream(filePath))
2
0.153846
1
1
cb48856f8d206bbac2f24f9dc40d529bcd30a459
server/app/controllers/products_controller.rb
server/app/controllers/products_controller.rb
class ProductsController < ApplicationController before_action :product_find def index @users = Product.all end def show render json: {product: @product} end def new @product = Product.new end def create @product = Product.new(id: params[:id], shopstyle_id: params[:shopstyle_id]) if @product.save render json: { product: @product }, status: :created else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product.destroy end private def product_find @product = Product.find(params[:id]) end end
class ProductsController < ApplicationController before_action :product_find, only: [:show, :edit, :destroy] def index @products = Product.all render json: @products end def show render json: {product: @product} end def new @product = Product.new end def create @product = Product.new(id: params[:id], shopstyle_id: params[:shopstyle_id]) if @product.save render json: { product: @product }, status: :created else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product.destroy end private def product_find @product = Product.find(params[:id]) end end
Add only to before_action in the product controller
Add only to before_action in the product controller
Ruby
mit
kpedersen00/price-tracker,jacobmoyle/price-tracker,kpedersen00/price-tracker,jacobmoyle/price-tracker
ruby
## Code Before: class ProductsController < ApplicationController before_action :product_find def index @users = Product.all end def show render json: {product: @product} end def new @product = Product.new end def create @product = Product.new(id: params[:id], shopstyle_id: params[:shopstyle_id]) if @product.save render json: { product: @product }, status: :created else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product.destroy end private def product_find @product = Product.find(params[:id]) end end ## Instruction: Add only to before_action in the product controller ## Code After: class ProductsController < ApplicationController before_action :product_find, only: [:show, :edit, :destroy] def index @products = Product.all render json: @products end def show render json: {product: @product} end def new @product = Product.new end def create @product = Product.new(id: params[:id], shopstyle_id: params[:shopstyle_id]) if @product.save render json: { product: @product }, status: :created else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product.destroy end private def product_find @product = Product.find(params[:id]) end end
class ProductsController < ApplicationController - before_action :product_find + before_action :product_find, only: [:show, :edit, :destroy] def index - @users = Product.all ? ^^^ + @products = Product.all ? ++++ ^^ + render json: @products end def show render json: {product: @product} end def new @product = Product.new end def create @product = Product.new(id: params[:id], shopstyle_id: params[:shopstyle_id]) if @product.save render json: { product: @product }, status: :created else render json: @product.errors.full_messages, status: :unprocessable_entity end end def destroy @product.destroy end private def product_find @product = Product.find(params[:id]) end end
5
0.131579
3
2
c8e5d70761101242e4d2643e6ab08621279d72c9
Gui/opensim/view/src/org/opensim/threejs/ModernPathColorMap.java
Gui/opensim/view/src/org/opensim/threejs/ModernPathColorMap.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import org.opensim.modeling.GeometryPath; import org.opensim.modeling.State; import org.opensim.modeling.Vec3; /** * * @author Ayman-NMBL * * Default ColorMap for earlier versions of OpenSim red-to-blue 0-1 * RGB components scales linearly */ public class ModernPathColorMap implements PathColorMap { @Override public Vec3 getColor(GeometryPath path, State state) { Vec3 activationBasedColor = path.getColor(state); double redness = activationBasedColor.get(0); Vec3 mappedColor = new Vec3(0.6435 + 0.07588*redness, 0.7009 - 0.6396*redness, 0.8554 - 0.6891*redness); return mappedColor; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import java.util.prefs.Preferences; import org.opensim.modeling.GeometryPath; import org.opensim.modeling.State; import org.opensim.modeling.Vec3; import org.opensim.utils.TheApp; /** * * @author Ayman-NMBL * * Default ColorMap for earlier versions of OpenSim red-to-blue 0-1 * RGB components scales linearly */ public class ModernPathColorMap implements PathColorMap { double weight = 0.0; void updateWeight (){ String weightString="0."; String saved=Preferences.userNodeForPackage(TheApp.class).get("ColorMap Weight", weightString); Preferences.userNodeForPackage(TheApp.class).put("ColorMap Weight", saved); weight = Double.parseDouble(saved); } @Override public Vec3 getColor(GeometryPath path, State state) { updateWeight (); Vec3 activationBasedColor = path.getColor(state); double redness = activationBasedColor.get(0); Vec3 mappedColor = new Vec3(0.6435 + 0.07588*redness, 0.7009 - 0.6396*redness, 0.8554 - 0.6891*redness); Vec3 rawColor = new Vec3(redness, 0, 1-redness); Vec3 weightedColor = new Vec3(); for (int i=0; i<3; i++) weightedColor.set(i, weight*rawColor.get(i)+(1 - weight)*mappedColor.get(i)); return weightedColor; } }
Introduce blending weight to tune muscle colors
Introduce blending weight to tune muscle colors
Java
apache-2.0
opensim-org/opensim-gui,opensim-org/opensim-gui,opensim-org/opensim-gui,opensim-org/opensim-gui
java
## Code Before: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import org.opensim.modeling.GeometryPath; import org.opensim.modeling.State; import org.opensim.modeling.Vec3; /** * * @author Ayman-NMBL * * Default ColorMap for earlier versions of OpenSim red-to-blue 0-1 * RGB components scales linearly */ public class ModernPathColorMap implements PathColorMap { @Override public Vec3 getColor(GeometryPath path, State state) { Vec3 activationBasedColor = path.getColor(state); double redness = activationBasedColor.get(0); Vec3 mappedColor = new Vec3(0.6435 + 0.07588*redness, 0.7009 - 0.6396*redness, 0.8554 - 0.6891*redness); return mappedColor; } } ## Instruction: Introduce blending weight to tune muscle colors ## Code After: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; import java.util.prefs.Preferences; import org.opensim.modeling.GeometryPath; import org.opensim.modeling.State; import org.opensim.modeling.Vec3; import org.opensim.utils.TheApp; /** * * @author Ayman-NMBL * * Default ColorMap for earlier versions of OpenSim red-to-blue 0-1 * RGB components scales linearly */ public class ModernPathColorMap implements PathColorMap { double weight = 0.0; void updateWeight (){ String weightString="0."; String saved=Preferences.userNodeForPackage(TheApp.class).get("ColorMap Weight", weightString); Preferences.userNodeForPackage(TheApp.class).put("ColorMap Weight", saved); weight = Double.parseDouble(saved); } @Override public Vec3 getColor(GeometryPath path, State state) { updateWeight (); Vec3 activationBasedColor = path.getColor(state); double redness = activationBasedColor.get(0); Vec3 mappedColor = new Vec3(0.6435 + 0.07588*redness, 0.7009 - 0.6396*redness, 0.8554 - 0.6891*redness); Vec3 rawColor = new Vec3(redness, 0, 1-redness); Vec3 weightedColor = new Vec3(); for (int i=0; i<3; i++) weightedColor.set(i, weight*rawColor.get(i)+(1 - weight)*mappedColor.get(i)); return weightedColor; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensim.threejs; + import java.util.prefs.Preferences; import org.opensim.modeling.GeometryPath; import org.opensim.modeling.State; import org.opensim.modeling.Vec3; + import org.opensim.utils.TheApp; /** * * @author Ayman-NMBL * * Default ColorMap for earlier versions of OpenSim red-to-blue 0-1 * RGB components scales linearly */ public class ModernPathColorMap implements PathColorMap { + double weight = 0.0; + + void updateWeight (){ + String weightString="0."; + String saved=Preferences.userNodeForPackage(TheApp.class).get("ColorMap Weight", weightString); + Preferences.userNodeForPackage(TheApp.class).put("ColorMap Weight", saved); + weight = Double.parseDouble(saved); + } @Override public Vec3 getColor(GeometryPath path, State state) { + updateWeight (); Vec3 activationBasedColor = path.getColor(state); double redness = activationBasedColor.get(0); Vec3 mappedColor = new Vec3(0.6435 + 0.07588*redness, 0.7009 - 0.6396*redness, 0.8554 - 0.6891*redness); + Vec3 rawColor = new Vec3(redness, 0, 1-redness); + Vec3 weightedColor = new Vec3(); + for (int i=0; i<3; i++) + weightedColor.set(i, weight*rawColor.get(i)+(1 - weight)*mappedColor.get(i)); - return mappedColor; ? ^^^^ + return weightedColor; ? ^^^^^^ } }
17
0.548387
16
1
1bd51f3f49f637075ecbac76de952bf5e87b2c7f
requirements.txt
requirements.txt
futures;python_version<="2.7" python-dateutil requests>=2.9.2 vcrpy azure-common cryptography>=1.3.0;python_version!="3.3" cryptography<=1.9.0;python_version=="3.3" adal
futures;python_version<="2.7" python-dateutil requests>=2.9.2 vcrpy<2.0.0 #2.0 breaks python 3.4 azure-common cryptography>=1.3.0;python_version!="3.3" cryptography<=1.9.0;python_version=="3.3" adal
Fix vcrpy's version to avoid breaking python 3.4 build
Fix vcrpy's version to avoid breaking python 3.4 build
Text
mit
Azure/azure-storage-python,Azure/azure-storage-python
text
## Code Before: futures;python_version<="2.7" python-dateutil requests>=2.9.2 vcrpy azure-common cryptography>=1.3.0;python_version!="3.3" cryptography<=1.9.0;python_version=="3.3" adal ## Instruction: Fix vcrpy's version to avoid breaking python 3.4 build ## Code After: futures;python_version<="2.7" python-dateutil requests>=2.9.2 vcrpy<2.0.0 #2.0 breaks python 3.4 azure-common cryptography>=1.3.0;python_version!="3.3" cryptography<=1.9.0;python_version=="3.3" adal
futures;python_version<="2.7" python-dateutil requests>=2.9.2 - vcrpy + vcrpy<2.0.0 #2.0 breaks python 3.4 azure-common cryptography>=1.3.0;python_version!="3.3" cryptography<=1.9.0;python_version=="3.3" adal
2
0.25
1
1
2b1e60a9910561de5a71e83d042b845f6be0bc73
__init__.py
__init__.py
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(): main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run()
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run()
Allow run argument to avoid @every template
Allow run argument to avoid @every template
Python
bsd-2-clause
furbrain/tingbot-python
python
## Code Before: from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(): main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run() ## Instruction: Allow run argument to avoid @every template ## Code After: from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run()
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() - def run(): + def run(loop=None): + if loop is not None: + every(seconds=1.0/30)(loop) + main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run()
5
0.384615
4
1
b4039d9645e7c9479ab84427030da6e01acb7ed1
main.go
main.go
package main import ( "fmt" "net/http" "os" ) func hello(resp http.ResponseWriter, req *http.Request) { fmt.Fprintln(resp, "<html><head><title>How about them apples?!</title></head><body><h1>") fmt.Fprintln(resp, "Hello world!") fmt.Fprintln(resp, "</h1></body></html>") } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { panic(err) } }
package main import ( "html/template" "net/http" "os" ) func hello(resp http.ResponseWriter, req *http.Request) { content, err := template.New("").Parse("<html><head><title>{{.title}}</title></head><body><ul>{{range .envs}}<li>{{.}}</li>{{end}}</ul></body></html>") if err != nil { panic(err) } ctx := map[string]interface{} { "title": "How about them apples?!", "envs": os.Environ(), } content.Execute(resp, ctx) } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { panic(err) } }
Use templates to print env.
Use templates to print env.
Go
mit
jgastal/mural,jgastal/mural,jgastal/mural,jgastal/mural
go
## Code Before: package main import ( "fmt" "net/http" "os" ) func hello(resp http.ResponseWriter, req *http.Request) { fmt.Fprintln(resp, "<html><head><title>How about them apples?!</title></head><body><h1>") fmt.Fprintln(resp, "Hello world!") fmt.Fprintln(resp, "</h1></body></html>") } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { panic(err) } } ## Instruction: Use templates to print env. ## Code After: package main import ( "html/template" "net/http" "os" ) func hello(resp http.ResponseWriter, req *http.Request) { content, err := template.New("").Parse("<html><head><title>{{.title}}</title></head><body><ul>{{range .envs}}<li>{{.}}</li>{{end}}</ul></body></html>") if err != nil { panic(err) } ctx := map[string]interface{} { "title": "How about them apples?!", "envs": os.Environ(), } content.Execute(resp, ctx) } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { panic(err) } }
package main import ( - "fmt" + "html/template" "net/http" "os" ) func hello(resp http.ResponseWriter, req *http.Request) { - fmt.Fprintln(resp, "<html><head><title>How about them apples?!</title></head><body><h1>") - fmt.Fprintln(resp, "Hello world!") - fmt.Fprintln(resp, "</h1></body></html>") + content, err := template.New("").Parse("<html><head><title>{{.title}}</title></head><body><ul>{{range .envs}}<li>{{.}}</li>{{end}}</ul></body></html>") + if err != nil { + panic(err) + } + + ctx := map[string]interface{} { + "title": "How about them apples?!", + "envs": os.Environ(), + } + + content.Execute(resp, ctx) } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { panic(err) } }
16
0.761905
12
4
15de7ac7e0da78c73e06bf8f4abbdbc10045f38d
README.md
README.md
This short program adds the functionality of pngs as workspaces to yabar. To make it work properly, the images have to be in the right dimensions depending to the bar's dimensions. You can assign keys to the workspaces in this program, but it will not bind these keys to the actual switching. This you have to manage on your own using xbindkeys or the window manager itself. It is just used to display the key next to the name of the workspace. I do not ship any icons, you have to find icons on your own. You can find the icons I use on [Icons 8](https://www.icons8.com). ![screenshot](screenshot.png?raw=true "Screenshot")
This short program adds the functionality of pngs as workspaces to yabar. To make it work properly, the images have to be in the right dimensions depending to the bar's dimensions. You can assign keys to the workspaces in this program, but it will not bind these keys to the actual switching. This you have to manage on your own using xbindkeys or the window manager itself. It is just used to display the key next to the name of the workspace. I do not ship any icons, you have to find icons on your own. You can find the icons I use on [Icons 8](https://www.icons8.com). ![screenshot](screenshot.png?raw=true "Screenshot") ### Yabar configuration You have to add a block in yabar for each workspace (even if it is not displayed when inactive) ''' bar: { ... block-list: ["ws1", "ws2"]; ws1: { # where k # is the number the workspace this block is responsible for exec:"python /location/of/workspace.py -k 1"; type: "persist"; image: "/location/of/ws1_current.png"; # you can also use image-shift/scale to center image, see yabar documentation background-color-argb:0x0; variable-size: true; pango-markup: true; } ws2: { # where k # is the number the workspace this block is responsible for exec:"python /location/of/workspace.py -k 2"; type: "persist"; image: "/location/of/ws2_current.png"; # you can also use image-shift/scale to center image, see yabar documentation background-color-argb:0x0; variable-size: true; pango-markup: true; } } '''
Add yabar configuration example to description
Add yabar configuration example to description
Markdown
apache-2.0
wtho/yabar-png-workspaces
markdown
## Code Before: This short program adds the functionality of pngs as workspaces to yabar. To make it work properly, the images have to be in the right dimensions depending to the bar's dimensions. You can assign keys to the workspaces in this program, but it will not bind these keys to the actual switching. This you have to manage on your own using xbindkeys or the window manager itself. It is just used to display the key next to the name of the workspace. I do not ship any icons, you have to find icons on your own. You can find the icons I use on [Icons 8](https://www.icons8.com). ![screenshot](screenshot.png?raw=true "Screenshot") ## Instruction: Add yabar configuration example to description ## Code After: This short program adds the functionality of pngs as workspaces to yabar. To make it work properly, the images have to be in the right dimensions depending to the bar's dimensions. You can assign keys to the workspaces in this program, but it will not bind these keys to the actual switching. This you have to manage on your own using xbindkeys or the window manager itself. It is just used to display the key next to the name of the workspace. I do not ship any icons, you have to find icons on your own. You can find the icons I use on [Icons 8](https://www.icons8.com). ![screenshot](screenshot.png?raw=true "Screenshot") ### Yabar configuration You have to add a block in yabar for each workspace (even if it is not displayed when inactive) ''' bar: { ... block-list: ["ws1", "ws2"]; ws1: { # where k # is the number the workspace this block is responsible for exec:"python /location/of/workspace.py -k 1"; type: "persist"; image: "/location/of/ws1_current.png"; # you can also use image-shift/scale to center image, see yabar documentation background-color-argb:0x0; variable-size: true; pango-markup: true; } ws2: { # where k # is the number the workspace this block is responsible for exec:"python /location/of/workspace.py -k 2"; type: "persist"; image: "/location/of/ws2_current.png"; # you can also use image-shift/scale to center image, see yabar documentation background-color-argb:0x0; variable-size: true; pango-markup: true; } } '''
This short program adds the functionality of pngs as workspaces to yabar. To make it work properly, the images have to be in the right dimensions depending to the bar's dimensions. You can assign keys to the workspaces in this program, but it will not bind these keys to the actual switching. This you have to manage on your own using xbindkeys or the window manager itself. It is just used to display the key next to the name of the workspace. I do not ship any icons, you have to find icons on your own. You can find the icons I use on [Icons 8](https://www.icons8.com). ![screenshot](screenshot.png?raw=true "Screenshot") + + ### Yabar configuration + + You have to add a block in yabar for each workspace (even if it is not displayed when inactive) + + ''' + bar: { + ... + block-list: ["ws1", "ws2"]; + + ws1: { + # where k # is the number the workspace this block is responsible for + exec:"python /location/of/workspace.py -k 1"; + type: "persist"; + image: "/location/of/ws1_current.png"; + # you can also use image-shift/scale to center image, see yabar documentation + background-color-argb:0x0; + variable-size: true; + pango-markup: true; + } + + ws2: { + # where k # is the number the workspace this block is responsible for + exec:"python /location/of/workspace.py -k 2"; + type: "persist"; + image: "/location/of/ws2_current.png"; + # you can also use image-shift/scale to center image, see yabar documentation + background-color-argb:0x0; + variable-size: true; + pango-markup: true; + } + } + + '''
34
3.090909
34
0
806c65e5aae0f900c75a42a010c248f4eb8d77b6
.travis.yml
.travis.yml
language: ruby script : script/cibuild sudo: false notifications: email: false branches: only: - master rvm: - 2.2 - 2.1 - 2.0 env: - "" - BUNTO_VERSION=2.0.0.beta8 - BUNTO_VERSION=1.0 matrix: include: - # GitHub Pages rvm: 2.1.1 env: GH_PAGES=true - # Ruby 1.9 rvm: 1.9 env: BUNTO_VERSION=1.0
language: ruby before_script: - chmod a+x script/bootstrap - chmod a+x script/cibuild - gem install bundler script : script/cibuild sudo: false notifications: email: false branches: only: - master rvm: - 2.3.1 - 2.3.0 env: - "" - BUNTO_VERSION=3.2.1 - BUNTO_VERSION=3.0.0 matrix: allow_failures: - # GitHub Pages rvm: 2.1.1 env: GH_PAGES=true include: - # Ruby 2.2.5 rvm: 2.2.5 env: BUNTO_VERSION=3.0.0
Correct RVM & Bunto versions
Correct RVM & Bunto versions
YAML
mit
bunto/bunto-gist,bunto/bunto-gist
yaml
## Code Before: language: ruby script : script/cibuild sudo: false notifications: email: false branches: only: - master rvm: - 2.2 - 2.1 - 2.0 env: - "" - BUNTO_VERSION=2.0.0.beta8 - BUNTO_VERSION=1.0 matrix: include: - # GitHub Pages rvm: 2.1.1 env: GH_PAGES=true - # Ruby 1.9 rvm: 1.9 env: BUNTO_VERSION=1.0 ## Instruction: Correct RVM & Bunto versions ## Code After: language: ruby before_script: - chmod a+x script/bootstrap - chmod a+x script/cibuild - gem install bundler script : script/cibuild sudo: false notifications: email: false branches: only: - master rvm: - 2.3.1 - 2.3.0 env: - "" - BUNTO_VERSION=3.2.1 - BUNTO_VERSION=3.0.0 matrix: allow_failures: - # GitHub Pages rvm: 2.1.1 env: GH_PAGES=true include: - # Ruby 2.2.5 rvm: 2.2.5 env: BUNTO_VERSION=3.0.0
language: ruby + before_script: + - chmod a+x script/bootstrap + - chmod a+x script/cibuild + - gem install bundler script : script/cibuild sudo: false notifications: email: false branches: only: - master rvm: + - 2.3.1 + - 2.3.0 - - 2.2 - - 2.1 - - 2.0 env: - "" - - BUNTO_VERSION=2.0.0.beta8 ? ^^^^^^^^^ + - BUNTO_VERSION=3.2.1 ? ++ ^ - - BUNTO_VERSION=1.0 ? ^ + - BUNTO_VERSION=3.0.0 ? ^ ++ matrix: - include: + allow_failures: - # GitHub Pages rvm: 2.1.1 env: GH_PAGES=true + include: - - # Ruby 1.9 ? ^ ^ + - # Ruby 2.2.5 ? ^ ^^^ - rvm: 1.9 ? ^ ^ + rvm: 2.2.5 ? ^ ^^^ - env: BUNTO_VERSION=1.0 ? ^ + env: BUNTO_VERSION=3.0.0 ? ^ ++
22
0.88
13
9
4e6dbe6d1aec29351b3ae0a7a998cbc976dedf16
lib/pharrell.rb
lib/pharrell.rb
require 'pharrell/config' require 'pharrell/injectable' require 'pharrell/constructor' require 'pharrell/errors' module Pharrell @@configs = {} @@config = nil def self.config(name, opts = {}, &blk) check_options([:extends], opts) if opts[:extends] @@configs[name] = fetch_config(opts[:extends]).extend(blk) else @@configs[name] = Config.new(blk) end end def self.use_config(name) @@config = name rebuild! end def self.instance_for(klass) current_config.instance_for(klass) end def self.rebuild! current_config.rebuild! end def self.reset! @@configs = {} @@config = nil end private def self.current_config fetch_config(@@config) end def self.fetch_config(name) config = @@configs[name] if config config else raise ConfigNotDefinedError end end def self.check_options(opts, opt_hash) extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } if extra_keys.empty? true else raise InvalidOptionsError.new(extra_keys) end end end
require 'pharrell/config' require 'pharrell/injectable' require 'pharrell/constructor' require 'pharrell/errors' module Pharrell @@environment = nil def self.config(name, opts = {}, &blk) environment.config(name, opts, &blk) end def self.use_config(name) environment.use_config(name) end def self.instance_for(klass) environment.instance_for(klass) end def self.rebuild! environment.rebuild! end def self.reset! environment.reset! end private def self.environment @@enironment ||= Environment.new end class Environment @configs = {} @config = nil def config(name, opts = {}, &blk) check_options([:extends], opts) if opts[:extends] @configs[name] = fetch_config(opts[:extends]).extend(blk) else @configs[name] = Config.new(blk) end end def use_config(name) @config = name rebuild! end def instance_for(klass) current_config.instance_for(klass) end def rebuild! current_config.rebuild! end def reset! @configs = {} @config = nil end private def current_config fetch_config(@config) end def fetch_config(name) config = @configs[name] if config config else raise ConfigNotDefinedError end end def check_options(opts, opt_hash) extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } if extra_keys.empty? true else raise InvalidOptionsError.new(extra_keys) end end end end
Refactor Pharrell global object to use Environment instance :neckbeard:
Refactor Pharrell global object to use Environment instance :neckbeard: This means that the configuration state is all held within an instance that is held in one static reference rather than having multiple static variables hanging around. Might allow for a cleaner internal interface and a more modular setup.
Ruby
mit
seadowg/pharrell
ruby
## Code Before: require 'pharrell/config' require 'pharrell/injectable' require 'pharrell/constructor' require 'pharrell/errors' module Pharrell @@configs = {} @@config = nil def self.config(name, opts = {}, &blk) check_options([:extends], opts) if opts[:extends] @@configs[name] = fetch_config(opts[:extends]).extend(blk) else @@configs[name] = Config.new(blk) end end def self.use_config(name) @@config = name rebuild! end def self.instance_for(klass) current_config.instance_for(klass) end def self.rebuild! current_config.rebuild! end def self.reset! @@configs = {} @@config = nil end private def self.current_config fetch_config(@@config) end def self.fetch_config(name) config = @@configs[name] if config config else raise ConfigNotDefinedError end end def self.check_options(opts, opt_hash) extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } if extra_keys.empty? true else raise InvalidOptionsError.new(extra_keys) end end end ## Instruction: Refactor Pharrell global object to use Environment instance :neckbeard: This means that the configuration state is all held within an instance that is held in one static reference rather than having multiple static variables hanging around. Might allow for a cleaner internal interface and a more modular setup. ## Code After: require 'pharrell/config' require 'pharrell/injectable' require 'pharrell/constructor' require 'pharrell/errors' module Pharrell @@environment = nil def self.config(name, opts = {}, &blk) environment.config(name, opts, &blk) end def self.use_config(name) environment.use_config(name) end def self.instance_for(klass) environment.instance_for(klass) end def self.rebuild! environment.rebuild! end def self.reset! environment.reset! end private def self.environment @@enironment ||= Environment.new end class Environment @configs = {} @config = nil def config(name, opts = {}, &blk) check_options([:extends], opts) if opts[:extends] @configs[name] = fetch_config(opts[:extends]).extend(blk) else @configs[name] = Config.new(blk) end end def use_config(name) @config = name rebuild! end def instance_for(klass) current_config.instance_for(klass) end def rebuild! current_config.rebuild! end def reset! @configs = {} @config = nil end private def current_config fetch_config(@config) end def fetch_config(name) config = @configs[name] if config config else raise ConfigNotDefinedError end end def check_options(opts, opt_hash) extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } if extra_keys.empty? true else raise InvalidOptionsError.new(extra_keys) end end end end
require 'pharrell/config' require 'pharrell/injectable' require 'pharrell/constructor' require 'pharrell/errors' module Pharrell + @@environment = nil - @@configs = {} - @@config = nil def self.config(name, opts = {}, &blk) + environment.config(name, opts, &blk) - check_options([:extends], opts) - - if opts[:extends] - @@configs[name] = fetch_config(opts[:extends]).extend(blk) - else - @@configs[name] = Config.new(blk) - end end def self.use_config(name) + environment.use_config(name) - @@config = name - rebuild! end def self.instance_for(klass) - current_config.instance_for(klass) ? ^^ ^ ------- + environment.instance_for(klass) ? ^^^^ ^^^ end def self.rebuild! - current_config.rebuild! + environment.rebuild! end def self.reset! + environment.reset! - @@configs = {} - @@config = nil end private - def self.current_config - fetch_config(@@config) + def self.environment + @@enironment ||= Environment.new end - def self.fetch_config(name) - config = @@configs[name] + class Environment + @configs = {} + @config = nil - if config - config + def config(name, opts = {}, &blk) + check_options([:extends], opts) + + if opts[:extends] + @configs[name] = fetch_config(opts[:extends]).extend(blk) - else + else ? ++ - raise ConfigNotDefinedError + @configs[name] = Config.new(blk) + end end - end - def self.check_options(opts, opt_hash) - extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } + def use_config(name) + @config = name + rebuild! + end + def instance_for(klass) + current_config.instance_for(klass) + end + + def rebuild! + current_config.rebuild! + end + + def reset! + @configs = {} + @config = nil + end + + private + + def current_config + fetch_config(@config) + end + + def fetch_config(name) + config = @configs[name] + + if config + config + else + raise ConfigNotDefinedError + end + end + + def check_options(opts, opt_hash) + extra_keys = opt_hash.keys.reject { |key| opts.include?(key) } + - if extra_keys.empty? + if extra_keys.empty? ? ++ - true + true ? ++ - else + else ? ++ - raise InvalidOptionsError.new(extra_keys) + raise InvalidOptionsError.new(extra_keys) ? ++ + end end end end
90
1.428571
60
30
2686c55bf06cb3b311ffa27733798be3b1826591
spec/spec_helper.rb
spec/spec_helper.rb
require "simplecov" SimpleCov.start # Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} SchemaComments.setup
require "simplecov" SimpleCov.start # Configure Rails Environment ENV["RAILS_ENV"] = "test" # Configure Rails Environment ENV["DB"] ||= "mysql" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} SchemaComments.setup
Set $DB mysql as default
Set $DB mysql as default
Ruby
mit
akm/schema_comments,akm/schema_comments,akm/schema_comments
ruby
## Code Before: require "simplecov" SimpleCov.start # Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} SchemaComments.setup ## Instruction: Set $DB mysql as default ## Code After: require "simplecov" SimpleCov.start # Configure Rails Environment ENV["RAILS_ENV"] = "test" # Configure Rails Environment ENV["DB"] ||= "mysql" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} SchemaComments.setup
require "simplecov" SimpleCov.start # Configure Rails Environment ENV["RAILS_ENV"] = "test" + + # Configure Rails Environment + ENV["DB"] ||= "mysql" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} SchemaComments.setup
3
0.214286
3
0
ca39cdb0b7710ea85d289ba9b128634fe9e986a9
app/models/due_item.rb
app/models/due_item.rb
class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar end
class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar def final_search_result self.calendar end end
Add due items to full text search results
Add due items to full text search results
Ruby
agpl-3.0
myplaceonline/myplaceonline_rails,myplaceonline/myplaceonline_rails,myplaceonline/myplaceonline_rails
ruby
## Code Before: class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar end ## Instruction: Add due items to full text search results ## Code After: class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar def final_search_result self.calendar end end
class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar + + def final_search_result + self.calendar + end end
4
0.8
4
0
d5b78824d385971638aea20c9c33026060b3bc1d
app/helpers/items_helper.rb
app/helpers/items_helper.rb
module ItemsHelper private def find_item @item = Item.find_by_id(params[:id]) end def item_params params.require(:item).permit(:name, :description, :image, :price, :quantity ) end end
module ItemsHelper private def find_item @item = Item.find_by_id(params[:id]) end def item_params params.require(:item).permit(:name, :description, :image, :price, :quantity, :category_id ) end end
Include category_id as an allowed param for items
Include category_id as an allowed param for items
Ruby
mit
benjaminhyw/rails-online-shop,benjaminhyw/rails-online-shop,benjaminhyw/rails-online-shop
ruby
## Code Before: module ItemsHelper private def find_item @item = Item.find_by_id(params[:id]) end def item_params params.require(:item).permit(:name, :description, :image, :price, :quantity ) end end ## Instruction: Include category_id as an allowed param for items ## Code After: module ItemsHelper private def find_item @item = Item.find_by_id(params[:id]) end def item_params params.require(:item).permit(:name, :description, :image, :price, :quantity, :category_id ) end end
module ItemsHelper private def find_item @item = Item.find_by_id(params[:id]) end def item_params - params.require(:item).permit(:name, :description, :image, :price, :quantity ) + params.require(:item).permit(:name, :description, :image, :price, :quantity, :category_id ) ? ++++++++++++++ end end
2
0.2
1
1
f3aa3219ce55cd410f58ae8068a856aee50903df
config/local-dist.php
config/local-dist.php
<?php /* * Template for a local configuration file that should not be committed to version control. * * Copy this file to local.php. */ $app['drivegal.client_id'] = ''; $app['drivegal.client_secret'] = ''; $app['drivegal.redirect_uri'] = '';
<?php /* * Template for a local configuration file with data that should not be committed to version control. * * Copy this to local.php and customize it for the local environment. */ // Credentials for Google Drive API. $app['drivegal.client_id'] = ''; $app['drivegal.client_secret'] = ''; $app['drivegal.redirect_uri'] = ''; // Credentials for Google OAuth2 login. $app['oauth.services'] = array( 'google' => array( 'key' => $app['drivegal.client_id'], 'secret' => $app['drivegal.client_secret'], 'scope' => array( 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ), 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo' ), ); $app['db.options'] = array( 'driver' => 'pdo_mysql', 'dbname' => '', 'host' => '', 'user' => '', 'password' => '', );
Update the local config template.
Update the local config template.
PHP
mit
jasongrimes/drivegal,jasongrimes/drivegal,jasongrimes/drivegal
php
## Code Before: <?php /* * Template for a local configuration file that should not be committed to version control. * * Copy this file to local.php. */ $app['drivegal.client_id'] = ''; $app['drivegal.client_secret'] = ''; $app['drivegal.redirect_uri'] = ''; ## Instruction: Update the local config template. ## Code After: <?php /* * Template for a local configuration file with data that should not be committed to version control. * * Copy this to local.php and customize it for the local environment. */ // Credentials for Google Drive API. $app['drivegal.client_id'] = ''; $app['drivegal.client_secret'] = ''; $app['drivegal.redirect_uri'] = ''; // Credentials for Google OAuth2 login. $app['oauth.services'] = array( 'google' => array( 'key' => $app['drivegal.client_id'], 'secret' => $app['drivegal.client_secret'], 'scope' => array( 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ), 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo' ), ); $app['db.options'] = array( 'driver' => 'pdo_mysql', 'dbname' => '', 'host' => '', 'user' => '', 'password' => '', );
<?php /* - * Template for a local configuration file that should not be committed to version control. + * Template for a local configuration file with data that should not be committed to version control. ? ++++++++++ * - * Copy this file to local.php. + * Copy this to local.php and customize it for the local environment. */ + // Credentials for Google Drive API. $app['drivegal.client_id'] = ''; $app['drivegal.client_secret'] = ''; $app['drivegal.redirect_uri'] = ''; + + // Credentials for Google OAuth2 login. + $app['oauth.services'] = array( + 'google' => array( + 'key' => $app['drivegal.client_id'], + 'secret' => $app['drivegal.client_secret'], + 'scope' => array( + 'https://www.googleapis.com/auth/userinfo.email', + 'https://www.googleapis.com/auth/userinfo.profile' + ), + 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo' + ), + ); + + $app['db.options'] = array( + 'driver' => 'pdo_mysql', + 'dbname' => '', + 'host' => '', + 'user' => '', + 'password' => '', + );
26
2.6
24
2
b361f2ca2d51038f00b64fba0cb96d1cf635dd55
commands/togethertube.js
commands/togethertube.js
const Command = require('../structures/command.js'); const request = require('request'); module.exports = class TogetherTube extends Command { constructor(client) { super(client); this.name = "togethertube"; this.aliases ["ttube", "ttb"]; } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); message.channel.startTyping(); request('https://togethertube.com/room/create', (error, response) => { if (error) { embed.setColor(this.client.config.colors.error); embed.setTitle(commandLang.error_title); embed.setDescription(commandLang.error_description); } else { embed.setDescription(response.request.uri.href); embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/'); message.channel.stopTyping(); message.channel.send({embed}); } }); } }
const Command = require('../structures/command.js'); const request = require('request'); module.exports = class TogetherTube extends Command { constructor(client) { super(client); this.name = "togethertube"; this.aliases = ["ttube", "ttb"]; } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); message.channel.startTyping(); request('https://togethertube.com/room/create', (error, response) => { if (error) { embed.setColor(this.client.config.colors.error); embed.setTitle(commandLang.error_title); embed.setDescription(commandLang.error_description); } else { embed.setDescription(response.request.uri.href); embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/'); } message.channel.stopTyping(); message.channel.send({embed}); }); } }
Fix aliases and error message.g
Fix aliases and error message.g
JavaScript
mit
pedrofracassi/deku
javascript
## Code Before: const Command = require('../structures/command.js'); const request = require('request'); module.exports = class TogetherTube extends Command { constructor(client) { super(client); this.name = "togethertube"; this.aliases ["ttube", "ttb"]; } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); message.channel.startTyping(); request('https://togethertube.com/room/create', (error, response) => { if (error) { embed.setColor(this.client.config.colors.error); embed.setTitle(commandLang.error_title); embed.setDescription(commandLang.error_description); } else { embed.setDescription(response.request.uri.href); embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/'); message.channel.stopTyping(); message.channel.send({embed}); } }); } } ## Instruction: Fix aliases and error message.g ## Code After: const Command = require('../structures/command.js'); const request = require('request'); module.exports = class TogetherTube extends Command { constructor(client) { super(client); this.name = "togethertube"; this.aliases = ["ttube", "ttb"]; } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); message.channel.startTyping(); request('https://togethertube.com/room/create', (error, response) => { if (error) { embed.setColor(this.client.config.colors.error); embed.setTitle(commandLang.error_title); embed.setDescription(commandLang.error_description); } else { embed.setDescription(response.request.uri.href); embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/'); } message.channel.stopTyping(); message.channel.send({embed}); }); } }
const Command = require('../structures/command.js'); const request = require('request'); module.exports = class TogetherTube extends Command { constructor(client) { super(client); - this.name = "togethertube"; + this.name = "togethertube"; ? +++ - this.aliases ["ttube", "ttb"]; + this.aliases = ["ttube", "ttb"]; ? ++ } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); message.channel.startTyping(); request('https://togethertube.com/room/create', (error, response) => { if (error) { embed.setColor(this.client.config.colors.error); embed.setTitle(commandLang.error_title); embed.setDescription(commandLang.error_description); } else { embed.setDescription(response.request.uri.href); embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/'); + } - message.channel.stopTyping(); ? -- + message.channel.stopTyping(); message.channel.send({embed}); - } }); } }
8
0.275862
4
4
a9d3e6a9c30d8c0ebf269efb188a307f21685a8f
src/Pingpong/Admin/Observers/VisitorObserver.php
src/Pingpong/Admin/Observers/VisitorObserver.php
<?php namespace Pingpong\Admin\Observers; class VisitorObserver { /** * Handle the specified event. * * @return void */ public function handle() { $isOnAdmin = Request::is('admin') || Request::is('admin/*'); if ( ! $isOnAdmin) Visitor::track(); } }
<?php namespace Pingpong\Admin\Observers; use Pingpong\Admin\Entities\Visitor; use Illuminate\Support\Facades\Request; class VisitorObserver { /** * Handle the specified event. * * @return void */ public function handle() { $isOnAdmin = Request::is('admin') || Request::is('admin/*'); if ( ! $isOnAdmin) Visitor::track(); } }
Fix Visitor class not found
Fix Visitor class not found
PHP
bsd-3-clause
matheusgomes17/admin,pingpong-labs/admin,choeng/admin,matheusgomes17/admin,Wangcankun/admin,choeng/admin,redbtn/admin,redbtn/admin,Wangcankun/admin,redbtn/admin,pingpong-labs/admin,matheusgomes17/admin,Wangcankun/admin,pingpong-labs/admin,choeng/admin
php
## Code Before: <?php namespace Pingpong\Admin\Observers; class VisitorObserver { /** * Handle the specified event. * * @return void */ public function handle() { $isOnAdmin = Request::is('admin') || Request::is('admin/*'); if ( ! $isOnAdmin) Visitor::track(); } } ## Instruction: Fix Visitor class not found ## Code After: <?php namespace Pingpong\Admin\Observers; use Pingpong\Admin\Entities\Visitor; use Illuminate\Support\Facades\Request; class VisitorObserver { /** * Handle the specified event. * * @return void */ public function handle() { $isOnAdmin = Request::is('admin') || Request::is('admin/*'); if ( ! $isOnAdmin) Visitor::track(); } }
<?php namespace Pingpong\Admin\Observers; + + use Pingpong\Admin\Entities\Visitor; + use Illuminate\Support\Facades\Request; class VisitorObserver { /** * Handle the specified event. * * @return void */ public function handle() { $isOnAdmin = Request::is('admin') || Request::is('admin/*'); if ( ! $isOnAdmin) Visitor::track(); } }
3
0.176471
3
0
a93739f55cd9594b6c0c3929ba881012743f8f75
bootstrap.sh
bootstrap.sh
echo "DATE ||| $(date)" # Swap out default Ubuntu mirror for a hopefully faster one sed -i.bak 's/archive.ubuntu.com/mirrors.rit.edu/' /etc/apt/sources.list apt-get update && apt-get install --assume-yes \ wget # Install Docker wget -qO- https://get.docker.com/ | sh # Add vagrant user to docker # https://docs.oracle.com/cd/E52668_01/E54669/html/section_rdz_hmw_2q.html groupadd docker service docker restart usermod -a -G docker vagrant
echo "DATE ||| $(date)" # Swap out default Ubuntu mirror for a hopefully faster one sed -i.bak 's/archive.ubuntu.com/mirrors.rit.edu/' /etc/apt/sources.list apt-get update && apt-get install --assume-yes \ apache2 \ apt-transport-https \ ca-certificates \ ccache \ gdebi \ git \ libcurl4-openssl-dev \ libmysqlclient-dev \ libpq-dev \ libssl-dev \ libx11-dev \ libxml2-dev \ linux-image-extra-$(uname -r) \ # for Docker lmodern \ mysql-client \ wget # Install Docker https://docs.docker.com/engine/installation/linux/ubuntulinux/ ## Add docker GPG key sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D ## Add docker APT Repository echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main\n"> /etc/apt/sources.list.d/docker.list apt-get update ## purge the old repo if it exists apt-get purge lxc-docker ## verify that APT is pulling from the right repo apt-cache policy docker-engine ## install the main docker package apt-get install docker engine service docker start # Add vagrant user to docker # https://docs.oracle.com/cd/E52668_01/E54669/html/section_rdz_hmw_2q.html groupadd docker service docker restart usermod -a -G docker vagrant
Add latest docker installation instructions
Add latest docker installation instructions
Shell
mit
briandk/manuscribble,briandk/manuscribble,briandk/manuscribble
shell
## Code Before: echo "DATE ||| $(date)" # Swap out default Ubuntu mirror for a hopefully faster one sed -i.bak 's/archive.ubuntu.com/mirrors.rit.edu/' /etc/apt/sources.list apt-get update && apt-get install --assume-yes \ wget # Install Docker wget -qO- https://get.docker.com/ | sh # Add vagrant user to docker # https://docs.oracle.com/cd/E52668_01/E54669/html/section_rdz_hmw_2q.html groupadd docker service docker restart usermod -a -G docker vagrant ## Instruction: Add latest docker installation instructions ## Code After: echo "DATE ||| $(date)" # Swap out default Ubuntu mirror for a hopefully faster one sed -i.bak 's/archive.ubuntu.com/mirrors.rit.edu/' /etc/apt/sources.list apt-get update && apt-get install --assume-yes \ apache2 \ apt-transport-https \ ca-certificates \ ccache \ gdebi \ git \ libcurl4-openssl-dev \ libmysqlclient-dev \ libpq-dev \ libssl-dev \ libx11-dev \ libxml2-dev \ linux-image-extra-$(uname -r) \ # for Docker lmodern \ mysql-client \ wget # Install Docker https://docs.docker.com/engine/installation/linux/ubuntulinux/ ## Add docker GPG key sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D ## Add docker APT Repository echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main\n"> /etc/apt/sources.list.d/docker.list apt-get update ## purge the old repo if it exists apt-get purge lxc-docker ## verify that APT is pulling from the right repo apt-cache policy docker-engine ## install the main docker package apt-get install docker engine service docker start # Add vagrant user to docker # https://docs.oracle.com/cd/E52668_01/E54669/html/section_rdz_hmw_2q.html groupadd docker service docker restart usermod -a -G docker vagrant
echo "DATE ||| $(date)" # Swap out default Ubuntu mirror for a hopefully faster one sed -i.bak 's/archive.ubuntu.com/mirrors.rit.edu/' /etc/apt/sources.list apt-get update && apt-get install --assume-yes \ + apache2 \ + apt-transport-https \ + ca-certificates \ + ccache \ + gdebi \ + git \ + libcurl4-openssl-dev \ + libmysqlclient-dev \ + libpq-dev \ + libssl-dev \ + libx11-dev \ + libxml2-dev \ + linux-image-extra-$(uname -r) \ # for Docker + lmodern \ + mysql-client \ wget - # Install Docker - wget -qO- https://get.docker.com/ | sh + # Install Docker https://docs.docker.com/engine/installation/linux/ubuntulinux/ + ## Add docker GPG key + sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D + ## Add docker APT Repository + echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main\n"> /etc/apt/sources.list.d/docker.list + apt-get update + ## purge the old repo if it exists + apt-get purge lxc-docker + ## verify that APT is pulling from the right repo + apt-cache policy docker-engine + ## install the main docker package + apt-get install docker engine + service docker start + # Add vagrant user to docker # https://docs.oracle.com/cd/E52668_01/E54669/html/section_rdz_hmw_2q.html groupadd docker service docker restart usermod -a -G docker vagrant
31
1.9375
29
2
6eb686028f2227c17519dd4c3f77761dec664244
src/Pingpong/Themes/Finder.php
src/Pingpong/Themes/Finder.php
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { return Json::make($file->getRealPath())->toArray(); } }
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { $attributes = Json::make($path = $file->getRealPath())->toArray(); $attributes['path'] = dirname($path); return $attributes; } }
Add path to theme attributes
Add path to theme attributes
PHP
bsd-3-clause
pingpong-labs/sky,pingpong-labs/sky,pingpong-labs/sky
php
## Code Before: <?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { return Json::make($file->getRealPath())->toArray(); } } ## Instruction: Add path to theme attributes ## Code After: <?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { $attributes = Json::make($path = $file->getRealPath())->toArray(); $attributes['path'] = dirname($path); return $attributes; } }
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { - return Json::make($file->getRealPath())->toArray(); ? ^^^^ + $attributes = Json::make($path = $file->getRealPath())->toArray(); ? ++++ ++++ ^^^ ++++++++ + + $attributes['path'] = dirname($path); + + return $attributes; } }
6
0.103448
5
1
086fe8b8c84fd12de5f6dc9f57dd68e6de0413c6
.travis.yml
.travis.yml
language: android jdk: oraclejdk8 env: matrix: - ANDROID_TARGET=android-23 ANDROID_ABI=x86 android: components: - platform-tools - tools - build-tools-27.0.2 - android-23 - extra-google-m2repository - extra-android-m2repository - extra-google-google_play_services before_install: - yes | sdkmanager "platforms;android-27" script: # Unit Test - ./gradlew -Pcoverage test jacocoTestReport after_success: - bash <(curl -s https://codecov.io/bash)
language: android jdk: oraclejdk8 env: matrix: - ANDROID_TARGET=android-23 ANDROID_ABI=x86 android: components: - platform-tools - tools - build-tools-27.0.2 - android-23 - extra-google-m2repository - extra-android-m2repository - extra-google-google_play_services before_install: - yes | sdkmanager "platforms;android-27" script: # Unit Test - ./gradlew -Pcoverage test jacocoTestReport after_success: - bash <(curl -s https://codecov.io/bash) before_cache: - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ cache: directories: - $HOME/.gradle/caches/ - $HOME/.gradle/wrapper/ - $HOME/.android/build-cache
Improve Travis build speed by storing build cache
Improve Travis build speed by storing build cache
YAML
agpl-3.0
jotomo/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,MilosKozak/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,PoweRGbg/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS
yaml
## Code Before: language: android jdk: oraclejdk8 env: matrix: - ANDROID_TARGET=android-23 ANDROID_ABI=x86 android: components: - platform-tools - tools - build-tools-27.0.2 - android-23 - extra-google-m2repository - extra-android-m2repository - extra-google-google_play_services before_install: - yes | sdkmanager "platforms;android-27" script: # Unit Test - ./gradlew -Pcoverage test jacocoTestReport after_success: - bash <(curl -s https://codecov.io/bash) ## Instruction: Improve Travis build speed by storing build cache ## Code After: language: android jdk: oraclejdk8 env: matrix: - ANDROID_TARGET=android-23 ANDROID_ABI=x86 android: components: - platform-tools - tools - build-tools-27.0.2 - android-23 - extra-google-m2repository - extra-android-m2repository - extra-google-google_play_services before_install: - yes | sdkmanager "platforms;android-27" script: # Unit Test - ./gradlew -Pcoverage test jacocoTestReport after_success: - bash <(curl -s https://codecov.io/bash) before_cache: - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ cache: directories: - $HOME/.gradle/caches/ - $HOME/.gradle/wrapper/ - $HOME/.android/build-cache
language: android jdk: oraclejdk8 env: matrix: - ANDROID_TARGET=android-23 ANDROID_ABI=x86 android: components: - platform-tools - tools - build-tools-27.0.2 - android-23 - extra-google-m2repository - extra-android-m2repository - extra-google-google_play_services before_install: - yes | sdkmanager "platforms;android-27" script: # Unit Test - ./gradlew -Pcoverage test jacocoTestReport after_success: - bash <(curl -s https://codecov.io/bash) + + before_cache: + - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + + cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ + - $HOME/.android/build-cache
10
0.416667
10
0
4957aeebad39f4dc1c3ed05e81a171d4ab213b15
TwIRCk/GLGInputParserDelegate.h
TwIRCk/GLGInputParserDelegate.h
// // GLGInputParserDelegate.h // TwIRCk // // Created by Tim Jarratt on 11/29/13. // Copyright (c) 2013 General Linear Group. All rights reserved. // #import <Foundation/Foundation.h> @protocol GLGInputParserDelegate <NSObject> - (void) didJoinChannel:(NSString *)channel rawCommand:(NSString *)rawCommand; - (void) didPartChannel:(NSString *)channel rawCommand:(NSString *)rawCommand; - (void) didChangeNick:(NSString *)newNick rawCommand:(NSString *)rawCommand; - (void) didChangePassword:(NSString *)newPassword rawCommand:(NSString *)rawCommand; @end
// // GLGInputParserDelegate.h // TwIRCk // // Created by Tim Jarratt on 11/29/13. // Copyright (c) 2013 General Linear Group. All rights reserved. // #import <Foundation/Foundation.h> @protocol GLGInputParserDelegate <NSObject> - (void) didJoinChannel:(NSString *)channel rawCommand:(NSString *)command; - (void) didPartChannel:(NSString *)channel rawCommand:(NSString *)channel; - (void) didChangeNick:(NSString *)newNick rawCommand:(NSString *)channel; - (void) didChangePassword:(NSString *)newPassword rawCommand:(NSString *)channel; @end
Revert "Name these protocol method variables better"
Revert "Name these protocol method variables better" This reverts commit 0dc63736e1b8398d1fc9692473f285076aa862ee.
C
mit
tjarratt/twIRCk,tjarratt/twIRCk,tjarratt/twIRCk
c
## Code Before: // // GLGInputParserDelegate.h // TwIRCk // // Created by Tim Jarratt on 11/29/13. // Copyright (c) 2013 General Linear Group. All rights reserved. // #import <Foundation/Foundation.h> @protocol GLGInputParserDelegate <NSObject> - (void) didJoinChannel:(NSString *)channel rawCommand:(NSString *)rawCommand; - (void) didPartChannel:(NSString *)channel rawCommand:(NSString *)rawCommand; - (void) didChangeNick:(NSString *)newNick rawCommand:(NSString *)rawCommand; - (void) didChangePassword:(NSString *)newPassword rawCommand:(NSString *)rawCommand; @end ## Instruction: Revert "Name these protocol method variables better" This reverts commit 0dc63736e1b8398d1fc9692473f285076aa862ee. ## Code After: // // GLGInputParserDelegate.h // TwIRCk // // Created by Tim Jarratt on 11/29/13. // Copyright (c) 2013 General Linear Group. All rights reserved. // #import <Foundation/Foundation.h> @protocol GLGInputParserDelegate <NSObject> - (void) didJoinChannel:(NSString *)channel rawCommand:(NSString *)command; - (void) didPartChannel:(NSString *)channel rawCommand:(NSString *)channel; - (void) didChangeNick:(NSString *)newNick rawCommand:(NSString *)channel; - (void) didChangePassword:(NSString *)newPassword rawCommand:(NSString *)channel; @end
// // GLGInputParserDelegate.h // TwIRCk // // Created by Tim Jarratt on 11/29/13. // Copyright (c) 2013 General Linear Group. All rights reserved. // #import <Foundation/Foundation.h> @protocol GLGInputParserDelegate <NSObject> - (void) didJoinChannel:(NSString *)channel - rawCommand:(NSString *)rawCommand; ? ^^^^ + rawCommand:(NSString *)command; ? ^ - (void) didPartChannel:(NSString *)channel - rawCommand:(NSString *)rawCommand; ? ^^^^^^^ ^ + rawCommand:(NSString *)channel; ? ^^ ^^^ - (void) didChangeNick:(NSString *)newNick - rawCommand:(NSString *)rawCommand; ? ^^^^^^^ ^ + rawCommand:(NSString *)channel; ? ^^ ^^^ - (void) didChangePassword:(NSString *)newPassword - rawCommand:(NSString *)rawCommand; ? ^^^^^^^ ^ + rawCommand:(NSString *)channel; ? ^^ ^^^ @end
8
0.380952
4
4
41b1d36a9d5fcb0dd2f6da53a7a0d4604b21a0eb
tests/query_test/test_scan_range_lengths.py
tests/query_test/test_scan_range_lengths.py
import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') elif vector.get_value('table_format').compression_codec != 'none': pytest.xfail(reason='IMPALA-122') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
Fix IMPALA-122: Lzo scanner with small scan ranges.
Fix IMPALA-122: Lzo scanner with small scan ranges. Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e Reviewed-on: http://gerrit.ent.cloudera.com:8080/140 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Python
apache-2.0
michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala
python
## Code Before: import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') elif vector.get_value('table_format').compression_codec != 'none': pytest.xfail(reason='IMPALA-122') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector) ## Instruction: Fix IMPALA-122: Lzo scanner with small scan ranges. Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e Reviewed-on: http://gerrit.ent.cloudera.com:8080/140 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com> ## Code After: import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') - elif vector.get_value('table_format').compression_codec != 'none': - pytest.xfail(reason='IMPALA-122') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
2
0.064516
0
2
e9d6b3358ac35901ccc6a4a5a317670fa469db25
arch/arm/include/asm/smp_scu.h
arch/arm/include/asm/smp_scu.h
unsigned int scu_get_core_count(void __iomem *); void scu_enable(void __iomem *); int scu_power_mode(void __iomem *, unsigned int); #endif #endif
static inline bool scu_a9_has_base(void) { return read_cpuid_part_number() == ARM_CPU_PART_CORTEX_A9; } static inline unsigned long scu_a9_get_base(void) { unsigned long pa; asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (pa)); return pa; } unsigned int scu_get_core_count(void __iomem *); void scu_enable(void __iomem *); int scu_power_mode(void __iomem *, unsigned int); #endif #endif
Add API to detect SCU base address from CP15
ARM: Add API to detect SCU base address from CP15 Add API to detect SCU base address from CP15. Signed-off-by: Hiroshi Doyu <7e37d737f0c384c0dce297667d084735fade9098@nvidia.com> Acked-by: Russell King <f6aa0246ff943bfa8602cdf60d40c481b38ed232@arm.linux.org.uk> Signed-off-by: Stephen Warren <5ef2a23ba3aff51d1cfc8c113c1ec34b608b3b13@nvidia.com>
C
apache-2.0
TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas
c
## Code Before: unsigned int scu_get_core_count(void __iomem *); void scu_enable(void __iomem *); int scu_power_mode(void __iomem *, unsigned int); #endif #endif ## Instruction: ARM: Add API to detect SCU base address from CP15 Add API to detect SCU base address from CP15. Signed-off-by: Hiroshi Doyu <7e37d737f0c384c0dce297667d084735fade9098@nvidia.com> Acked-by: Russell King <f6aa0246ff943bfa8602cdf60d40c481b38ed232@arm.linux.org.uk> Signed-off-by: Stephen Warren <5ef2a23ba3aff51d1cfc8c113c1ec34b608b3b13@nvidia.com> ## Code After: static inline bool scu_a9_has_base(void) { return read_cpuid_part_number() == ARM_CPU_PART_CORTEX_A9; } static inline unsigned long scu_a9_get_base(void) { unsigned long pa; asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (pa)); return pa; } unsigned int scu_get_core_count(void __iomem *); void scu_enable(void __iomem *); int scu_power_mode(void __iomem *, unsigned int); #endif #endif
+ + static inline bool scu_a9_has_base(void) + { + return read_cpuid_part_number() == ARM_CPU_PART_CORTEX_A9; + } + + static inline unsigned long scu_a9_get_base(void) + { + unsigned long pa; + + asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (pa)); + + return pa; + } + unsigned int scu_get_core_count(void __iomem *); void scu_enable(void __iomem *); int scu_power_mode(void __iomem *, unsigned int); #endif #endif
15
2.5
15
0
996a655d51b0359d46dfa0679aad28b042a19f21
src/main/java/org/puller/Comic.java
src/main/java/org/puller/Comic.java
package org.puller; public class Comic { private final String title; private final String price; public Comic(final String title, final String price) { this.title = title; this.price = price; } @Override public String toString() { return String.format("%s - %s", title, price); } }
package org.puller; public class Comic implements Comparable<Comic> { private static final String DOLLAR_SYMBOL = "\\$"; private final String title; private final String price; public Comic(final String title, final String price) { this.title = title; this.price = price; } public String getRawPrice() { return price.replaceAll(DOLLAR_SYMBOL, ""); } @Override public String toString() { return String.format("%s - %s", title, price); } @Override public int compareTo(Comic comic) { return title.compareTo(comic.title); } }
Add method to obtain raw comic price
Add method to obtain raw comic price
Java
bsd-2-clause
joow/Puller
java
## Code Before: package org.puller; public class Comic { private final String title; private final String price; public Comic(final String title, final String price) { this.title = title; this.price = price; } @Override public String toString() { return String.format("%s - %s", title, price); } } ## Instruction: Add method to obtain raw comic price ## Code After: package org.puller; public class Comic implements Comparable<Comic> { private static final String DOLLAR_SYMBOL = "\\$"; private final String title; private final String price; public Comic(final String title, final String price) { this.title = title; this.price = price; } public String getRawPrice() { return price.replaceAll(DOLLAR_SYMBOL, ""); } @Override public String toString() { return String.format("%s - %s", title, price); } @Override public int compareTo(Comic comic) { return title.compareTo(comic.title); } }
package org.puller; - public class Comic { + public class Comic implements Comparable<Comic> { + private static final String DOLLAR_SYMBOL = "\\$"; + private final String title; private final String price; public Comic(final String title, final String price) { this.title = title; this.price = price; } + public String getRawPrice() { + return price.replaceAll(DOLLAR_SYMBOL, ""); + } + @Override public String toString() { return String.format("%s - %s", title, price); } + + @Override + public int compareTo(Comic comic) { + return title.compareTo(comic.title); + } }
13
0.8125
12
1
64e3e9eb7430812ada6ab20cb6acf18fa12f6d0a
.circleci/config.yml
.circleci/config.yml
--- lint_and_unit: &lint_and_unit - delivery - danger - lint-yaml - lint-markdown version: 2.1 orbs: kitchen: sous-chefs/kitchen@2 workflows: kitchen: jobs: - kitchen/yamllint: name: lint-yaml - kitchen/mdlint: name: lint-markdown - kitchen/danger: name: danger context: Danger - kitchen/delivery: name: delivery - kitchen/dokken-single: name: default-centos-7 suite: default-centos-7 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1604 suite: default-ubuntu-1604 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1804 suite: default-ubuntu-1804 requires: *lint_and_unit - kitchen/dokken-single: name: uninstall-ubuntu-1804 suite: uninstall-ubuntu-1804 requires: *lint_and_unit
--- lint_and_unit: &lint_and_unit - delivery - danger - lint-yaml - lint-markdown version: 2.1 orbs: kitchen: sous-chefs/kitchen@2 workflows: kitchen: jobs: - kitchen/yamllint: name: lint-yaml - kitchen/mdlint: name: lint-markdown - kitchen/danger: name: danger context: Danger - kitchen/delivery: name: delivery - kitchen/dokken-single: name: default-centos-7 suite: default-centos-7 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1804 suite: default-ubuntu-1804 requires: *lint_and_unit - kitchen/dokken-single: name: uninstall-ubuntu-1804 suite: uninstall-ubuntu-1804 requires: *lint_and_unit
Remove the ubuntu 16.0 dokken tests from circleci
Remove the ubuntu 16.0 dokken tests from circleci
YAML
apache-2.0
jtimberman/vagrant-cookbook
yaml
## Code Before: --- lint_and_unit: &lint_and_unit - delivery - danger - lint-yaml - lint-markdown version: 2.1 orbs: kitchen: sous-chefs/kitchen@2 workflows: kitchen: jobs: - kitchen/yamllint: name: lint-yaml - kitchen/mdlint: name: lint-markdown - kitchen/danger: name: danger context: Danger - kitchen/delivery: name: delivery - kitchen/dokken-single: name: default-centos-7 suite: default-centos-7 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1604 suite: default-ubuntu-1604 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1804 suite: default-ubuntu-1804 requires: *lint_and_unit - kitchen/dokken-single: name: uninstall-ubuntu-1804 suite: uninstall-ubuntu-1804 requires: *lint_and_unit ## Instruction: Remove the ubuntu 16.0 dokken tests from circleci ## Code After: --- lint_and_unit: &lint_and_unit - delivery - danger - lint-yaml - lint-markdown version: 2.1 orbs: kitchen: sous-chefs/kitchen@2 workflows: kitchen: jobs: - kitchen/yamllint: name: lint-yaml - kitchen/mdlint: name: lint-markdown - kitchen/danger: name: danger context: Danger - kitchen/delivery: name: delivery - kitchen/dokken-single: name: default-centos-7 suite: default-centos-7 requires: *lint_and_unit - kitchen/dokken-single: name: default-ubuntu-1804 suite: default-ubuntu-1804 requires: *lint_and_unit - kitchen/dokken-single: name: uninstall-ubuntu-1804 suite: uninstall-ubuntu-1804 requires: *lint_and_unit
--- lint_and_unit: &lint_and_unit - delivery - danger - lint-yaml - lint-markdown version: 2.1 orbs: kitchen: sous-chefs/kitchen@2 workflows: kitchen: jobs: - kitchen/yamllint: name: lint-yaml - kitchen/mdlint: name: lint-markdown - kitchen/danger: name: danger context: Danger - kitchen/delivery: name: delivery - kitchen/dokken-single: name: default-centos-7 suite: default-centos-7 requires: *lint_and_unit - kitchen/dokken-single: - name: default-ubuntu-1604 - suite: default-ubuntu-1604 - requires: *lint_and_unit - - kitchen/dokken-single: name: default-ubuntu-1804 suite: default-ubuntu-1804 requires: *lint_and_unit - kitchen/dokken-single: name: uninstall-ubuntu-1804 suite: uninstall-ubuntu-1804 requires: *lint_and_unit
4
0.108108
0
4
cd9b68fdcc0c729354000b42937cf6d5c3f84e40
setup.cfg
setup.cfg
[tool:pytest] xfail_strict=true [flake8] # W504 line break after binary operator extend_ignore=W504 select=B901, B902 [isort] line_length=80 indent=' ' multi_line_output=3 known_first_party=notifications_utils,tests include_trailing_comma=True
[tool:pytest] xfail_strict=true [flake8] # W504 line break after binary operator extend_ignore=W504 select=B901, B902 [isort] line_length=80 indent=' ' multi_line_output=3 known_first_party=notifications_utils,tests include_trailing_comma=True use_parentheses=True
Update isort config to match that in API
Update isort config to match that in API As discussed in [1]. This has no effect on the existing imports. [1]: https://github.com/alphagov/notifications-api/pull/3175#issuecomment-795530323
INI
mit
alphagov/notifications-utils
ini
## Code Before: [tool:pytest] xfail_strict=true [flake8] # W504 line break after binary operator extend_ignore=W504 select=B901, B902 [isort] line_length=80 indent=' ' multi_line_output=3 known_first_party=notifications_utils,tests include_trailing_comma=True ## Instruction: Update isort config to match that in API As discussed in [1]. This has no effect on the existing imports. [1]: https://github.com/alphagov/notifications-api/pull/3175#issuecomment-795530323 ## Code After: [tool:pytest] xfail_strict=true [flake8] # W504 line break after binary operator extend_ignore=W504 select=B901, B902 [isort] line_length=80 indent=' ' multi_line_output=3 known_first_party=notifications_utils,tests include_trailing_comma=True use_parentheses=True
[tool:pytest] xfail_strict=true [flake8] # W504 line break after binary operator extend_ignore=W504 select=B901, B902 [isort] line_length=80 indent=' ' multi_line_output=3 known_first_party=notifications_utils,tests include_trailing_comma=True + use_parentheses=True
1
0.071429
1
0
324a0516d3028b0be61301a50e5699041b9561cf
lms/static/js/ajax-error.js
lms/static/js/ajax-error.js
$(document).ajaxError(function(event, jXHR) { if (jXHR.status === 403 && jXHR.responseText === 'Unauthenticated') { var message = gettext( 'You have been logged out of your edX account. ' + 'Click Okay to log in again now. ' + 'Click Cancel to stay on this page ' + '(you must log in again to save your work).' ); if (window.confirm(message)) { var currentLocation = window.location.pathname; window.location.href = '/login?next=' + encodeURIComponent(currentLocation); } } });
$(document).ajaxError(function(event, jXHR) { if (jXHR.status === 403) { var message = gettext( 'You have been logged out of your edX account. ' + 'Click Okay to log in again now. ' + 'Click Cancel to stay on this page ' + '(you must log in again to save your work).' ); if (window.confirm(message)) { var currentLocation = window.location.pathname; window.location.href = '/login?next=' + encodeURIComponent(currentLocation); } } });
Check only response code instead of code and response text
Check only response code instead of code and response text
JavaScript
agpl-3.0
edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform
javascript
## Code Before: $(document).ajaxError(function(event, jXHR) { if (jXHR.status === 403 && jXHR.responseText === 'Unauthenticated') { var message = gettext( 'You have been logged out of your edX account. ' + 'Click Okay to log in again now. ' + 'Click Cancel to stay on this page ' + '(you must log in again to save your work).' ); if (window.confirm(message)) { var currentLocation = window.location.pathname; window.location.href = '/login?next=' + encodeURIComponent(currentLocation); } } }); ## Instruction: Check only response code instead of code and response text ## Code After: $(document).ajaxError(function(event, jXHR) { if (jXHR.status === 403) { var message = gettext( 'You have been logged out of your edX account. ' + 'Click Okay to log in again now. ' + 'Click Cancel to stay on this page ' + '(you must log in again to save your work).' ); if (window.confirm(message)) { var currentLocation = window.location.pathname; window.location.href = '/login?next=' + encodeURIComponent(currentLocation); } } });
$(document).ajaxError(function(event, jXHR) { - if (jXHR.status === 403 && jXHR.responseText === 'Unauthenticated') { + if (jXHR.status === 403) { var message = gettext( 'You have been logged out of your edX account. ' + 'Click Okay to log in again now. ' + 'Click Cancel to stay on this page ' + '(you must log in again to save your work).' ); if (window.confirm(message)) { var currentLocation = window.location.pathname; window.location.href = '/login?next=' + encodeURIComponent(currentLocation); } } });
2
0.133333
1
1
eb92867d64cda0eb339fc84c0a289e97a21d637e
public/assets/css/index.css
public/assets/css/index.css
body { background-color: #e5e5ef; overflow-x: hidden; }
body { overflow-x: hidden; height:100%; background:center no-repeat fixed url('/assets/img/about/bg_suburb.jpg'); background-size: cover; }
Set image in body background
Set image in body background
CSS
mit
fabiohbarbosa/easy-schedule-ui,fabiohbarbosa/easy-schedule-ui
css
## Code Before: body { background-color: #e5e5ef; overflow-x: hidden; } ## Instruction: Set image in body background ## Code After: body { overflow-x: hidden; height:100%; background:center no-repeat fixed url('/assets/img/about/bg_suburb.jpg'); background-size: cover; }
body { - background-color: #e5e5ef; overflow-x: hidden; + height:100%; + background:center no-repeat fixed url('/assets/img/about/bg_suburb.jpg'); + background-size: cover; }
4
1
3
1
0c900cbfc27ed111a7697cdc25956a26e1a15c28
types/algos.js
types/algos.js
'use strict'; var _ = require('lodash'); var algos = { 'eddsa': 'eddsa', 'curve25519': 'curve25519', 'triplesec-v3': 'triplesec-v3', 'scrypt': 'scrypt', 'nacl easybox': 'nacl-easybox', 'nacl secretbox': 'nacl-secretbox', }; algos.name = function(b) { b = ''+b; // coerce to string var found = _.findKey(algos, function(val) { return val === b.toLowerCase(); }); if (found) { return found; } throw new Error('unrecognized algo'); }; algos.value = function(key) { var algo = algos[key.toString().toLowerCase()]; if (algo) { return algo; } throw new Error('unrecognized algo'); }; module.exports = algos;
'use strict'; var _ = require('lodash'); var algos = { 'eddsa': 'eddsa', 'curve25519': 'curve25519', 'triplesec-v3': 'triplesec-v3', 'scrypt': 'scrypt', 'nacl easybox': 'easybox', 'nacl secretbox': 'secretbox', }; algos.name = function(b) { b = ''+b; // coerce to string var found = _.findKey(algos, function(val) { return val === b.toLowerCase(); }); if (found) { return found; } throw new Error('unrecognized algo'); }; algos.value = function(key) { var algo = algos[key.toString().toLowerCase()]; if (algo) { return algo; } throw new Error('unrecognized algo'); }; module.exports = algos;
Rename alg value for easybox/secretbox
Rename alg value for easybox/secretbox
JavaScript
agpl-3.0
arigatomachine/common
javascript
## Code Before: 'use strict'; var _ = require('lodash'); var algos = { 'eddsa': 'eddsa', 'curve25519': 'curve25519', 'triplesec-v3': 'triplesec-v3', 'scrypt': 'scrypt', 'nacl easybox': 'nacl-easybox', 'nacl secretbox': 'nacl-secretbox', }; algos.name = function(b) { b = ''+b; // coerce to string var found = _.findKey(algos, function(val) { return val === b.toLowerCase(); }); if (found) { return found; } throw new Error('unrecognized algo'); }; algos.value = function(key) { var algo = algos[key.toString().toLowerCase()]; if (algo) { return algo; } throw new Error('unrecognized algo'); }; module.exports = algos; ## Instruction: Rename alg value for easybox/secretbox ## Code After: 'use strict'; var _ = require('lodash'); var algos = { 'eddsa': 'eddsa', 'curve25519': 'curve25519', 'triplesec-v3': 'triplesec-v3', 'scrypt': 'scrypt', 'nacl easybox': 'easybox', 'nacl secretbox': 'secretbox', }; algos.name = function(b) { b = ''+b; // coerce to string var found = _.findKey(algos, function(val) { return val === b.toLowerCase(); }); if (found) { return found; } throw new Error('unrecognized algo'); }; algos.value = function(key) { var algo = algos[key.toString().toLowerCase()]; if (algo) { return algo; } throw new Error('unrecognized algo'); }; module.exports = algos;
'use strict'; var _ = require('lodash'); var algos = { 'eddsa': 'eddsa', 'curve25519': 'curve25519', 'triplesec-v3': 'triplesec-v3', 'scrypt': 'scrypt', - 'nacl easybox': 'nacl-easybox', ? ----- + 'nacl easybox': 'easybox', - 'nacl secretbox': 'nacl-secretbox', ? ----- + 'nacl secretbox': 'secretbox', }; algos.name = function(b) { b = ''+b; // coerce to string var found = _.findKey(algos, function(val) { return val === b.toLowerCase(); }); if (found) { return found; } throw new Error('unrecognized algo'); }; algos.value = function(key) { var algo = algos[key.toString().toLowerCase()]; if (algo) { return algo; } throw new Error('unrecognized algo'); }; module.exports = algos;
4
0.117647
2
2
fc8212cf831781154afb25924542bbd89d1dfe22
README.md
README.md
[![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) # syntaxext_lint This crate provides common lints for use with making syntax extensions. ## Current Lints | Lint Name | Description | |-----------|-------------| | `dummy_span` | detects uses of `DUMMY_SP` |
[![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg?branch=master)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) # syntaxext_lint This crate provides common lints for use with making syntax extensions. ## Current Lints | Lint Name | Description | |-----------|-------------| | `dummy_span` | detects uses of `DUMMY_SP` |
Update travis badge to point to master branch
Update travis badge to point to master branch
Markdown
mit
mcoffin/syntaxext_lint,hugwijst/syntaxext_lint
markdown
## Code Before: [![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) # syntaxext_lint This crate provides common lints for use with making syntax extensions. ## Current Lints | Lint Name | Description | |-----------|-------------| | `dummy_span` | detects uses of `DUMMY_SP` | ## Instruction: Update travis badge to point to master branch ## Code After: [![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg?branch=master)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) # syntaxext_lint This crate provides common lints for use with making syntax extensions. ## Current Lints | Lint Name | Description | |-----------|-------------| | `dummy_span` | detects uses of `DUMMY_SP` |
- [![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) + [![Build Status](https://travis-ci.org/mcoffin/syntaxext_lint.svg?branch=master)](https://travis-ci.org/mcoffin/syntaxext_lint) [![](http://meritbadge.herokuapp.com/syntaxext_lint)](https://crates.io/crates/syntaxext_lint) ? ++++++++++++++ # syntaxext_lint This crate provides common lints for use with making syntax extensions. ## Current Lints | Lint Name | Description | |-----------|-------------| | `dummy_span` | detects uses of `DUMMY_SP` |
2
0.181818
1
1
5a2f848badcdf9bf968e23cfb55f53eb023d18a4
tests/helper.py
tests/helper.py
import unittest import os import yaml from functools import wraps from cmd import init_db, seed_db from models import db from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'] app.testing = True self.appx = app self.app = app.test_client() with app.app_context(): init_db(app, db) seed_db(db) def tearDown(self): with self.appx.app_context(): db.session.remove() db.drop_all() def use_data(file): def use_data_decorator(f): @wraps(f) def wrapper(*args): with open(os.path.join('fixtures/data', file), 'r') as stream: data = yaml.load(stream) args = args + (data, ) return f(*args) return wrapper return use_data_decorator
import unittest import os import yaml from functools import wraps from flask_jwt_simple import create_jwt from cmd import init_db, seed_db from models import db, Student from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'] app.testing = True self.appx = app self.app = app.test_client() student = Student( id=0, email='jdoe@scu.edu', first_name='John', last_name='Doe', university_id=1 ) ident = { 'id': student.id, 'email': student.email, 'first_name': student.first_name, 'last_name': student.last_name } with app.app_context(): db.drop_all() init_db(app, db) seed_db(db) db.session.add(student) db.session.commit() self.jwt = create_jwt(identity=ident) def tearDown(self): with self.appx.app_context(): db.session.remove() db.drop_all() def use_data(file): def use_data_decorator(f): @wraps(f) def wrapper(*args): with open(os.path.join('fixtures/data', file), 'r') as stream: data = yaml.load(stream) args = args + (data, ) return f(*args) return wrapper return use_data_decorator
Add authentication to base TestCase
Add authentication to base TestCase
Python
agpl-3.0
SCUEvals/scuevals-api,SCUEvals/scuevals-api
python
## Code Before: import unittest import os import yaml from functools import wraps from cmd import init_db, seed_db from models import db from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'] app.testing = True self.appx = app self.app = app.test_client() with app.app_context(): init_db(app, db) seed_db(db) def tearDown(self): with self.appx.app_context(): db.session.remove() db.drop_all() def use_data(file): def use_data_decorator(f): @wraps(f) def wrapper(*args): with open(os.path.join('fixtures/data', file), 'r') as stream: data = yaml.load(stream) args = args + (data, ) return f(*args) return wrapper return use_data_decorator ## Instruction: Add authentication to base TestCase ## Code After: import unittest import os import yaml from functools import wraps from flask_jwt_simple import create_jwt from cmd import init_db, seed_db from models import db, Student from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'] app.testing = True self.appx = app self.app = app.test_client() student = Student( id=0, email='jdoe@scu.edu', first_name='John', last_name='Doe', university_id=1 ) ident = { 'id': student.id, 'email': student.email, 'first_name': student.first_name, 'last_name': student.last_name } with app.app_context(): db.drop_all() init_db(app, db) seed_db(db) db.session.add(student) db.session.commit() self.jwt = create_jwt(identity=ident) def tearDown(self): with self.appx.app_context(): db.session.remove() db.drop_all() def use_data(file): def use_data_decorator(f): @wraps(f) def wrapper(*args): with open(os.path.join('fixtures/data', file), 'r') as stream: data = yaml.load(stream) args = args + (data, ) return f(*args) return wrapper return use_data_decorator
import unittest import os import yaml from functools import wraps + from flask_jwt_simple import create_jwt from cmd import init_db, seed_db - from models import db + from models import db, Student ? +++++++++ from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'] app.testing = True self.appx = app self.app = app.test_client() + student = Student( + id=0, + email='jdoe@scu.edu', + first_name='John', + last_name='Doe', + university_id=1 + ) + + ident = { + 'id': student.id, + 'email': student.email, + 'first_name': student.first_name, + 'last_name': student.last_name + } + with app.app_context(): + db.drop_all() init_db(app, db) seed_db(db) + + db.session.add(student) + db.session.commit() + + self.jwt = create_jwt(identity=ident) def tearDown(self): with self.appx.app_context(): db.session.remove() db.drop_all() def use_data(file): def use_data_decorator(f): @wraps(f) def wrapper(*args): with open(os.path.join('fixtures/data', file), 'r') as stream: data = yaml.load(stream) args = args + (data, ) return f(*args) return wrapper return use_data_decorator
24
0.631579
23
1
49ef8bf44f3b09244bbffc1cc1e65ea69f579555
core/src/test/scala/core/generator/Play2RouteGeneratorSpec.scala
core/src/test/scala/core/generator/Play2RouteGeneratorSpec.scala
package core.generator import core.ServiceDescription import org.scalatest.FlatSpec class Play2RouteGeneratorSpec extends FlatSpec { it should "generate routes" in { val json = io.Source.fromURL(getClass.getResource("/api.json")).getLines.mkString("\n") val generator = Play2RouteGenerator(ServiceDescription(json)) println(generator.generate()) } }
package core.generator import core.ServiceDescription import org.scalatest.FlatSpec class Play2RouteGeneratorSpec extends FlatSpec { it should "generate routes" in { val r = getClass.getResource("/api.json") if (r == null) { sys.error("Could not find resource named api.json") } val json = io.Source.fromURL(r).getLines.mkString("\n") val generator = Play2RouteGenerator(ServiceDescription(json)) println(generator.generate()) } }
Remove NPE if resource not found
Remove NPE if resource not found
Scala
mit
apicollective/apibuilder,Seanstoppable/apidoc,mbryzek/apidoc,gheine/apidoc,movio/apidoc,apicollective/apibuilder,movio/apidoc,movio/apidoc,mbryzek/apidoc,mbryzek/apidoc,apicollective/apibuilder,gheine/apidoc,Seanstoppable/apidoc,Seanstoppable/apidoc,gheine/apidoc
scala
## Code Before: package core.generator import core.ServiceDescription import org.scalatest.FlatSpec class Play2RouteGeneratorSpec extends FlatSpec { it should "generate routes" in { val json = io.Source.fromURL(getClass.getResource("/api.json")).getLines.mkString("\n") val generator = Play2RouteGenerator(ServiceDescription(json)) println(generator.generate()) } } ## Instruction: Remove NPE if resource not found ## Code After: package core.generator import core.ServiceDescription import org.scalatest.FlatSpec class Play2RouteGeneratorSpec extends FlatSpec { it should "generate routes" in { val r = getClass.getResource("/api.json") if (r == null) { sys.error("Could not find resource named api.json") } val json = io.Source.fromURL(r).getLines.mkString("\n") val generator = Play2RouteGenerator(ServiceDescription(json)) println(generator.generate()) } }
package core.generator import core.ServiceDescription import org.scalatest.FlatSpec class Play2RouteGeneratorSpec extends FlatSpec { it should "generate routes" in { + val r = getClass.getResource("/api.json") + if (r == null) { + sys.error("Could not find resource named api.json") + } - val json = io.Source.fromURL(getClass.getResource("/api.json")).getLines.mkString("\n") ? ----------------- --------------- + val json = io.Source.fromURL(r).getLines.mkString("\n") val generator = Play2RouteGenerator(ServiceDescription(json)) println(generator.generate()) } }
6
0.428571
5
1
8ee35fe46e978fcb17e99b50f045009ea8235067
tools/pdtools/pdtools/devices/camera.py
tools/pdtools/pdtools/devices/camera.py
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def __repr__(self): return "Camera({})".format(self.host) def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
Define __repr__ for pdtools Camera class.
Define __repr__ for pdtools Camera class.
Python
apache-2.0
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
python
## Code Before: import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None ## Instruction: Define __repr__ for pdtools Camera class. ## Code After: import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def __repr__(self): return "Camera({})".format(self.host) def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host + + def __repr__(self): + return "Camera({})".format(self.host) def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
3
0.1
3
0
d9e7f6653e1b86211d1ee4a54675bd8b3d7fa3f0
README.md
README.md
This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and lead the user through the step by step process required to upgrade their browser. Pull requests are accepted.
This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and offer that the user download Google Chrome or Mozilla Firefox ###Preview ![Preview](screenshots/1.png) ###How to use this element Simply include the element anywhere on the page. The element has `position: fixed` and has `visibility: hidden` as long as the user is not using Internet Explorer. Only if the element detects Internet Explorer will it change the visibility to `visibility: visible` and offer the user download options. ###Notes Pull requests are accepted.
Add preview and how to use
Add preview and how to use
Markdown
mit
intcreator/no-ie
markdown
## Code Before: This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and lead the user through the step by step process required to upgrade their browser. Pull requests are accepted. ## Instruction: Add preview and how to use ## Code After: This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and offer that the user download Google Chrome or Mozilla Firefox ###Preview ![Preview](screenshots/1.png) ###How to use this element Simply include the element anywhere on the page. The element has `position: fixed` and has `visibility: hidden` as long as the user is not using Internet Explorer. Only if the element detects Internet Explorer will it change the visibility to `visibility: visible` and offer the user download options. ###Notes Pull requests are accepted.
- This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and lead the user through the step by step process required to upgrade their browser. ? ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + This element will be invisibile unless Internet Explorer is [detected by a unique feature](http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser#answer-9851769), upon which this element will appear and offer that the user download Google Chrome or Mozilla Firefox ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + ###Preview + + ![Preview](screenshots/1.png) + + ###How to use this element + + Simply include the element anywhere on the page. The element has `position: fixed` and has `visibility: hidden` as long as the user is not using Internet Explorer. Only if the element detects Internet Explorer will it change the visibility to `visibility: visible` and offer the user download options. + + ###Notes Pull requests are accepted.
12
3
11
1
c7a170579bde39605acce55cc45169bd140d816c
app/graphql/scalar_types/date_time.rb
app/graphql/scalar_types/date_time.rb
ScalarTypes::DateTime = GraphQL::ScalarType.define do name "DateTime" coerce_input ->(value) { Time.zone.parse(value) } coerce_result ->(value) { value.iso8601 } end
ScalarTypes::DateTime = GraphQL::ScalarType.define do name "DateTime" coerce_input ->(value, _ctx) { Time.zone.parse(value) } coerce_result ->(value, _ctx) { value.iso8601 } end
Fix deprecation warning in coerce_input/coerce_result
Fix deprecation warning in coerce_input/coerce_result
Ruby
apache-2.0
annict/annict,annict/annict,annict/annict,annict/annict
ruby
## Code Before: ScalarTypes::DateTime = GraphQL::ScalarType.define do name "DateTime" coerce_input ->(value) { Time.zone.parse(value) } coerce_result ->(value) { value.iso8601 } end ## Instruction: Fix deprecation warning in coerce_input/coerce_result ## Code After: ScalarTypes::DateTime = GraphQL::ScalarType.define do name "DateTime" coerce_input ->(value, _ctx) { Time.zone.parse(value) } coerce_result ->(value, _ctx) { value.iso8601 } end
ScalarTypes::DateTime = GraphQL::ScalarType.define do name "DateTime" - coerce_input ->(value) { Time.zone.parse(value) } + coerce_input ->(value, _ctx) { Time.zone.parse(value) } ? ++++++ - coerce_result ->(value) { value.iso8601 } + coerce_result ->(value, _ctx) { value.iso8601 } ? ++++++ end
4
0.571429
2
2
329a2da550e6de5ad8c51f608cef65e551f332e6
ci/run_tests.sh
ci/run_tests.sh
CURRDIR=$(pwd) CONDA_ENV_PATH="${CURRDIR}"/../parserdev # remove the conda environment if it already exists [[ -d "${CONDA_ENV_PATH}" ]] && /opt/python/conda_default/bin/conda env remove -p "${CONDA_ENV_PATH}" # create the conda environment using the environment.yaml file /opt/python/conda_default/bin/conda env create -f environment.yaml -p "${CONDA_ENV_PATH}" -v # install the rstfinder package in development mode "${CONDA_ENV_PATH}"/bin/pip install -e . # link in the training JSON file that we need for the tests ln -s /home/nlp-text/dynamic/mheilman/discourse-parsing/rst_discourse_tb_edus_TRAINING_TRAIN.json . # run the tests and generate the coverage report "${CONDA_ENV_PATH}"/bin/nosetests --nologcapture tests --with-coverage --cover-package rstfinder --cover-html --with-xunit
CURRDIR=$(pwd) CONDA_ENV_PATH="${CURRDIR}"/../parserdev # set up ZPar and NLTK environment variables NLPTOOLS="/home/nlp-text/dynamic/NLPTools" ZPAR_MODEL_DIR="${NLPTOOLS}/zpar/models/english" NLTK_DATA="${NLPTOOLS}/nltk_data" # remove the conda environment if it already exists [[ -d "${CONDA_ENV_PATH}" ]] && /opt/python/conda_default/bin/conda env remove -p "${CONDA_ENV_PATH}" # create the conda environment using the environment.yaml file /opt/python/conda_default/bin/conda env create -f environment.yaml -p "${CONDA_ENV_PATH}" -v # install the rstfinder package in development mode "${CONDA_ENV_PATH}"/bin/pip install -e . # link in the training JSON file that we need for the tests ln -s /home/nlp-text/dynamic/mheilman/discourse-parsing/rst_discourse_tb_edus_TRAINING_TRAIN.json . # run the tests and generate the coverage report "${CONDA_ENV_PATH}"/bin/nosetests --nologcapture tests --with-coverage --cover-package rstfinder --cover-html --with-xunit
Update Bamboo CI script to set env vars.
Update Bamboo CI script to set env vars.
Shell
mit
EducationalTestingService/discourse-parsing,EducationalTestingService/discourse-parsing
shell
## Code Before: CURRDIR=$(pwd) CONDA_ENV_PATH="${CURRDIR}"/../parserdev # remove the conda environment if it already exists [[ -d "${CONDA_ENV_PATH}" ]] && /opt/python/conda_default/bin/conda env remove -p "${CONDA_ENV_PATH}" # create the conda environment using the environment.yaml file /opt/python/conda_default/bin/conda env create -f environment.yaml -p "${CONDA_ENV_PATH}" -v # install the rstfinder package in development mode "${CONDA_ENV_PATH}"/bin/pip install -e . # link in the training JSON file that we need for the tests ln -s /home/nlp-text/dynamic/mheilman/discourse-parsing/rst_discourse_tb_edus_TRAINING_TRAIN.json . # run the tests and generate the coverage report "${CONDA_ENV_PATH}"/bin/nosetests --nologcapture tests --with-coverage --cover-package rstfinder --cover-html --with-xunit ## Instruction: Update Bamboo CI script to set env vars. ## Code After: CURRDIR=$(pwd) CONDA_ENV_PATH="${CURRDIR}"/../parserdev # set up ZPar and NLTK environment variables NLPTOOLS="/home/nlp-text/dynamic/NLPTools" ZPAR_MODEL_DIR="${NLPTOOLS}/zpar/models/english" NLTK_DATA="${NLPTOOLS}/nltk_data" # remove the conda environment if it already exists [[ -d "${CONDA_ENV_PATH}" ]] && /opt/python/conda_default/bin/conda env remove -p "${CONDA_ENV_PATH}" # create the conda environment using the environment.yaml file /opt/python/conda_default/bin/conda env create -f environment.yaml -p "${CONDA_ENV_PATH}" -v # install the rstfinder package in development mode "${CONDA_ENV_PATH}"/bin/pip install -e . # link in the training JSON file that we need for the tests ln -s /home/nlp-text/dynamic/mheilman/discourse-parsing/rst_discourse_tb_edus_TRAINING_TRAIN.json . # run the tests and generate the coverage report "${CONDA_ENV_PATH}"/bin/nosetests --nologcapture tests --with-coverage --cover-package rstfinder --cover-html --with-xunit
CURRDIR=$(pwd) CONDA_ENV_PATH="${CURRDIR}"/../parserdev + + # set up ZPar and NLTK environment variables + NLPTOOLS="/home/nlp-text/dynamic/NLPTools" + ZPAR_MODEL_DIR="${NLPTOOLS}/zpar/models/english" + NLTK_DATA="${NLPTOOLS}/nltk_data" # remove the conda environment if it already exists [[ -d "${CONDA_ENV_PATH}" ]] && /opt/python/conda_default/bin/conda env remove -p "${CONDA_ENV_PATH}" # create the conda environment using the environment.yaml file /opt/python/conda_default/bin/conda env create -f environment.yaml -p "${CONDA_ENV_PATH}" -v # install the rstfinder package in development mode "${CONDA_ENV_PATH}"/bin/pip install -e . # link in the training JSON file that we need for the tests ln -s /home/nlp-text/dynamic/mheilman/discourse-parsing/rst_discourse_tb_edus_TRAINING_TRAIN.json . # run the tests and generate the coverage report "${CONDA_ENV_PATH}"/bin/nosetests --nologcapture tests --with-coverage --cover-package rstfinder --cover-html --with-xunit
5
0.294118
5
0
428d655e54fa511c9535be3107538627e3d07be5
.github/ISSUE_TEMPLATE/moderator_application.md
.github/ISSUE_TEMPLATE/moderator_application.md
--- name: Community Moderator Request about: Request moderator privileges on a Kubernetes property title: 'REQUEST: New moderator for <your-GH-handle> of <k8s property>' labels: area/community-management, sig/contributor-experience assignees: '' --- ### GitHub Username e.g. (at)github_user ### Property you'd like to Moderate e.g. discuss.k8s.io, kubernetes-dev ### Username on Property Requested e.g. (at)property_user ### Requirements - [ ] I am a Kubernetes Org member already - [ ] I have read and will abide by the policies mentioned in the [Moderation Guidelines](https://git.k8s.io/community/communication/moderation.md) - [ ] I have two sponsors that meet the sponsor requirements listed in the moderator guidelines - [ ] I have spoken to my sponsors ahead of this application, and they have agreed to sponsor my application ### Sponsors - (at)sponsor-1 - (at)sponsor-2 ### List of qualifications for this position - Prior moderation experience - Links to public discussions showing your moderation experience (if available) - Any other qualifications
--- name: Community Moderator Request about: Request moderator privileges on a Kubernetes property title: 'REQUEST: New moderator for <your-GH-handle> of <k8s property>' labels: area/community-management, sig/contributor-experience assignees: '' --- ### GitHub Username e.g. (at)github_user ### Property you'd like to Moderate e.g. discuss.k8s.io, kubernetes-dev ### Username on Property Requested e.g. (at)property_user ### Requirements - [ ] I am a Kubernetes Org member already - [ ] I have enabled 2FA on my account for the property I would like to moderate (if applicable). - [ ] I have read and will abide by the policies mentioned in the [Moderation Guidelines](https://git.k8s.io/community/communication/moderation.md) - [ ] I have two sponsors that meet the sponsor requirements listed in the moderator guidelines - [ ] I have spoken to my sponsors ahead of this application, and they have agreed to sponsor my application ### Sponsors - (at)sponsor-1 - (at)sponsor-2 ### List of qualifications for this position - Prior moderation experience - Links to public discussions showing your moderation experience (if available) - Any other qualifications
Add 2fa req to moderator template.
Add 2fa req to moderator template.
Markdown
apache-2.0
kubernetes/community,pwittrock/community,kubernetes/community,kubernetes/community,pwittrock/community
markdown
## Code Before: --- name: Community Moderator Request about: Request moderator privileges on a Kubernetes property title: 'REQUEST: New moderator for <your-GH-handle> of <k8s property>' labels: area/community-management, sig/contributor-experience assignees: '' --- ### GitHub Username e.g. (at)github_user ### Property you'd like to Moderate e.g. discuss.k8s.io, kubernetes-dev ### Username on Property Requested e.g. (at)property_user ### Requirements - [ ] I am a Kubernetes Org member already - [ ] I have read and will abide by the policies mentioned in the [Moderation Guidelines](https://git.k8s.io/community/communication/moderation.md) - [ ] I have two sponsors that meet the sponsor requirements listed in the moderator guidelines - [ ] I have spoken to my sponsors ahead of this application, and they have agreed to sponsor my application ### Sponsors - (at)sponsor-1 - (at)sponsor-2 ### List of qualifications for this position - Prior moderation experience - Links to public discussions showing your moderation experience (if available) - Any other qualifications ## Instruction: Add 2fa req to moderator template. ## Code After: --- name: Community Moderator Request about: Request moderator privileges on a Kubernetes property title: 'REQUEST: New moderator for <your-GH-handle> of <k8s property>' labels: area/community-management, sig/contributor-experience assignees: '' --- ### GitHub Username e.g. (at)github_user ### Property you'd like to Moderate e.g. discuss.k8s.io, kubernetes-dev ### Username on Property Requested e.g. (at)property_user ### Requirements - [ ] I am a Kubernetes Org member already - [ ] I have enabled 2FA on my account for the property I would like to moderate (if applicable). - [ ] I have read and will abide by the policies mentioned in the [Moderation Guidelines](https://git.k8s.io/community/communication/moderation.md) - [ ] I have two sponsors that meet the sponsor requirements listed in the moderator guidelines - [ ] I have spoken to my sponsors ahead of this application, and they have agreed to sponsor my application ### Sponsors - (at)sponsor-1 - (at)sponsor-2 ### List of qualifications for this position - Prior moderation experience - Links to public discussions showing your moderation experience (if available) - Any other qualifications
--- name: Community Moderator Request about: Request moderator privileges on a Kubernetes property title: 'REQUEST: New moderator for <your-GH-handle> of <k8s property>' labels: area/community-management, sig/contributor-experience assignees: '' --- ### GitHub Username e.g. (at)github_user ### Property you'd like to Moderate e.g. discuss.k8s.io, kubernetes-dev ### Username on Property Requested e.g. (at)property_user ### Requirements - [ ] I am a Kubernetes Org member already + - [ ] I have enabled 2FA on my account for the property I would like to moderate (if applicable). - [ ] I have read and will abide by the policies mentioned in the [Moderation Guidelines](https://git.k8s.io/community/communication/moderation.md) - [ ] I have two sponsors that meet the sponsor requirements listed in the moderator guidelines - [ ] I have spoken to my sponsors ahead of this application, and they have agreed to sponsor my application ### Sponsors - (at)sponsor-1 - (at)sponsor-2 ### List of qualifications for this position - Prior moderation experience - Links to public discussions showing your moderation experience (if available) - Any other qualifications
1
0.028571
1
0
18d64529bd4e49572ec21347c1cd163eff54b287
Formula/bash.rb
Formula/bash.rb
require 'formula' class Bash < Formula homepage 'http://www.gnu.org/software/bash/' url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz' mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz' sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8' version '4.2.20' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--with-installed-readline" system "make install" end end
require 'formula' class Bash < Formula homepage 'http://www.gnu.org/software/bash/' url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz' mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz' sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8' version '4.2.20' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--with-installed-readline" system "make install" end def caveats; <<-EOS.undent In order to use this build of bash as your login shell, it must be added to /etc/shells. EOS end end
Add caveat about using this Bash as login shell
Add caveat about using this Bash as login shell Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
Ruby
bsd-2-clause
phusion/homebrew-core,maxim-belkin/homebrew-core,bcg62/homebrew-core,filcab/homebrew-core,mvitz/homebrew-core,bigbes/homebrew-core,mvbattista/homebrew-core,j-bennet/homebrew-core,stgraber/homebrew-core,tkoenig/homebrew-core,forevergenin/homebrew-core,Homebrew/homebrew-core,kunickiaj/homebrew-core,spaam/homebrew-core,cblecker/homebrew-core,Moisan/homebrew-core,mbcoguno/homebrew-core,mahori/homebrew-core,jvillard/homebrew-core,chrisfinazzo/homebrew-core,FinalDes/homebrew-core,jvehent/homebrew-core,smessmer/homebrew-core,mvitz/homebrew-core,adamliter/homebrew-core,adam-moss/homebrew-core,ShivaHuang/homebrew-core,battlemidget/homebrew-core,Linuxbrew/homebrew-core,mahori/homebrew-core,edporras/homebrew-core,gserra-olx/homebrew-core,LinuxbrewTestBot/homebrew-core,Homebrew/homebrew-core,jabenninghoff/homebrew-core,spaam/homebrew-core,ilovezfs/homebrew-core,bcg62/homebrew-core,straxhaber/homebrew-core,bfontaine/homebrew-core,sjackman/homebrew-core,grhawk/homebrew-core,ylluminarious/homebrew-core,lembacon/homebrew-core,lembacon/homebrew-core,mvitz/homebrew-core,sdorra/homebrew-core,jvillard/homebrew-core,chrisfinazzo/homebrew-core,straxhaber/homebrew-core,gserra-olx/homebrew-core,moderndeveloperllc/homebrew-core,LinuxbrewTestBot/homebrew-core,nandub/homebrew-core,lemzwerg/homebrew-core,wolffaxn/homebrew-core,ylluminarious/homebrew-core,forevergenin/homebrew-core,rwhogg/homebrew-core,fvioz/homebrew-core,robohack/homebrew-core,lasote/homebrew-core,sjackman/homebrew-core,FinalDes/homebrew-core,lembacon/homebrew-core,dsXLII/homebrew-core,andyjeffries/homebrew-core,mfikes/homebrew-core,lemzwerg/homebrew-core,uyjulian/homebrew-core,JCount/homebrew-core,git-lfs/homebrew-core,Linuxbrew/homebrew-core,nandub/homebrew-core,reelsense/homebrew-core,nbari/homebrew-core,nbari/homebrew-core,jvillard/homebrew-core,moderndeveloperllc/homebrew-core,filcab/homebrew-core,ShivaHuang/homebrew-core,passerbyid/homebrew-core,smessmer/homebrew-core,jvehent/homebrew-core,bcg62/homebrew-core,edporras/homebrew-core,maxim-belkin/homebrew-core,andyjeffries/homebrew-core,j-bennet/homebrew-core,grhawk/homebrew-core,aabdnn/homebrew-core,aren55555/homebrew-core,robohack/homebrew-core,mbcoguno/homebrew-core,kuahyeow/homebrew-core,aren55555/homebrew-core,cblecker/homebrew-core,rwhogg/homebrew-core,passerbyid/homebrew-core,JCount/homebrew-core,wolffaxn/homebrew-core,adamliter/homebrew-core,DomT4/homebrew-core,bfontaine/homebrew-core,makigumo/homebrew-core,jdubois/homebrew-core,aabdnn/homebrew-core,kuahyeow/homebrew-core,phusion/homebrew-core,BrewTestBot/homebrew-core,adam-moss/homebrew-core,reelsense/homebrew-core,battlemidget/homebrew-core,tkoenig/homebrew-core,lasote/homebrew-core,wolffaxn/homebrew-core,zyedidia/homebrew-core,zmwangx/homebrew-core,DomT4/homebrew-core,jabenninghoff/homebrew-core,mfikes/homebrew-core,BrewTestBot/homebrew-core,mvbattista/homebrew-core,stgraber/homebrew-core,mbcoguno/homebrew-core,bigbes/homebrew-core,makigumo/homebrew-core,ilovezfs/homebrew-core,fvioz/homebrew-core,sdorra/homebrew-core,zmwangx/homebrew-core,jdubois/homebrew-core,dsXLII/homebrew-core,zyedidia/homebrew-core,kunickiaj/homebrew-core,Moisan/homebrew-core,jdubois/homebrew-core,uyjulian/homebrew-core,git-lfs/homebrew-core
ruby
## Code Before: require 'formula' class Bash < Formula homepage 'http://www.gnu.org/software/bash/' url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz' mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz' sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8' version '4.2.20' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--with-installed-readline" system "make install" end end ## Instruction: Add caveat about using this Bash as login shell Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com> ## Code After: require 'formula' class Bash < Formula homepage 'http://www.gnu.org/software/bash/' url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz' mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz' sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8' version '4.2.20' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--with-installed-readline" system "make install" end def caveats; <<-EOS.undent In order to use this build of bash as your login shell, it must be added to /etc/shells. EOS end end
require 'formula' class Bash < Formula homepage 'http://www.gnu.org/software/bash/' url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz' mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz' sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8' version '4.2.20' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--with-installed-readline" system "make install" end + + def caveats; <<-EOS.undent + In order to use this build of bash as your login shell, + it must be added to /etc/shells. + EOS + end end
6
0.285714
6
0
ef7590673b4acd89cc24ee43551bcf1c294cf6f3
api/admin/top/readevent/matchExec.js
api/admin/top/readevent/matchExec.js
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var eventID = params.eventid; function respondToServer(response,obj) { response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(obj)); }; sys.getEventData(response,eventID,respondToServer); } exports.cogClass = cogClass; })();
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var eventID = params.eventid; var role = null; var userObj = sys.admin[params.userkey]; if (userObj) { role = userObj.role; } function respondToServer(response,obj) { response.writeHead(200, {'Content-Type': 'application/json'}); obj.role = role; response.end(JSON.stringify(obj)); }; sys.getEventData(response,eventID,respondToServer); } exports.cogClass = cogClass; })();
Return role of caller when populating page from server
Return role of caller when populating page from server
JavaScript
unlicense
fbennett/newswriter
javascript
## Code Before: (function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var eventID = params.eventid; function respondToServer(response,obj) { response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(obj)); }; sys.getEventData(response,eventID,respondToServer); } exports.cogClass = cogClass; })(); ## Instruction: Return role of caller when populating page from server ## Code After: (function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var eventID = params.eventid; var role = null; var userObj = sys.admin[params.userkey]; if (userObj) { role = userObj.role; } function respondToServer(response,obj) { response.writeHead(200, {'Content-Type': 'application/json'}); obj.role = role; response.end(JSON.stringify(obj)); }; sys.getEventData(response,eventID,respondToServer); } exports.cogClass = cogClass; })();
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var eventID = params.eventid; + var role = null; + var userObj = sys.admin[params.userkey]; + if (userObj) { + role = userObj.role; + } + function respondToServer(response,obj) { response.writeHead(200, {'Content-Type': 'application/json'}); + obj.role = role; response.end(JSON.stringify(obj)); }; sys.getEventData(response,eventID,respondToServer); } exports.cogClass = cogClass; })();
7
0.411765
7
0
e890ef9e8fc6c36cccd9d6d940120d75b538e9e2
frontend/components/app.js
frontend/components/app.js
import React from 'react'; import Board from '../containers/board'; import { Grid, Row, Col } from 'react-flexbox-grid'; import BlackPieceStand from '../containers/blackPieceStand'; import WhitePieceStand from '../containers/whitePieceStand'; const App = () => { return ( <div> <Grid> <Row center="xs"> <Col xs={1}> <WhitePieceStand /> </Col> <Col xs={6}> <Board /> </Col> <Col xs={1}> <BlackPieceStand /> </Col> </Row> </Grid> </div> ); }; export default App;
import React from 'react'; import Board from '../containers/board'; import { Grid, Row, Col } from 'react-flexbox-grid'; import BlackPieceStand from '../containers/blackPieceStand'; import WhitePieceStand from '../containers/whitePieceStand'; const App = () => { return ( <div className="app" style={{padding: '4em'}}> <Grid> <Row center="xs"> <Col xs={1}> <WhitePieceStand /> </Col> <Col xs={6}> <Board /> </Col> <Col xs={1}> <BlackPieceStand /> </Col> </Row> </Grid> </div> ); }; export default App;
Add padding to inline styles.
Add padding to inline styles.
JavaScript
mit
mgi166/usi-front,mgi166/usi-front
javascript
## Code Before: import React from 'react'; import Board from '../containers/board'; import { Grid, Row, Col } from 'react-flexbox-grid'; import BlackPieceStand from '../containers/blackPieceStand'; import WhitePieceStand from '../containers/whitePieceStand'; const App = () => { return ( <div> <Grid> <Row center="xs"> <Col xs={1}> <WhitePieceStand /> </Col> <Col xs={6}> <Board /> </Col> <Col xs={1}> <BlackPieceStand /> </Col> </Row> </Grid> </div> ); }; export default App; ## Instruction: Add padding to inline styles. ## Code After: import React from 'react'; import Board from '../containers/board'; import { Grid, Row, Col } from 'react-flexbox-grid'; import BlackPieceStand from '../containers/blackPieceStand'; import WhitePieceStand from '../containers/whitePieceStand'; const App = () => { return ( <div className="app" style={{padding: '4em'}}> <Grid> <Row center="xs"> <Col xs={1}> <WhitePieceStand /> </Col> <Col xs={6}> <Board /> </Col> <Col xs={1}> <BlackPieceStand /> </Col> </Row> </Grid> </div> ); }; export default App;
import React from 'react'; import Board from '../containers/board'; import { Grid, Row, Col } from 'react-flexbox-grid'; import BlackPieceStand from '../containers/blackPieceStand'; import WhitePieceStand from '../containers/whitePieceStand'; const App = () => { return ( - <div> + <div className="app" style={{padding: '4em'}}> <Grid> <Row center="xs"> <Col xs={1}> <WhitePieceStand /> </Col> <Col xs={6}> <Board /> </Col> <Col xs={1}> <BlackPieceStand /> </Col> </Row> </Grid> </div> ); }; export default App;
2
0.074074
1
1
12846a30a5f1aac5e98bcdaac0a80e6a2d585124
.github/PULL_REQUEST_TEMPLATE.md
.github/PULL_REQUEST_TEMPLATE.md
Thanks for submittng a Pull Request to SwiftGen! Don't forget to add an entry in the `CHANGELOG.md` file to explain your changes and credit yourself! --- ## Important: ⚠️ Refactoring in progress ⚠️ SwiftGen has arrived to a point where it's big enough to deserve [its own GitHub organization](https://github.com/SwiftGen/), and will also be split into multiple repositories for better structure and flexibility. This means that SwiftGen's code will be subject to a big reorganizaton (see [#240](https://github.com/AliSoftware/SwiftGen/issues/240)) and that it may not be the best time to submit a new PR, as it will likely not be valid anymore after that refactoring. We still welcome new PRs very much of course, and are really glad you wish to contribute! But if your change is likely to be affected by this big reorganization, it might be easier for you to wait a few weeks until that refactoring is finished (It's not expected to last long — we hope to finish that big migration ASAP) before submitting your changes, to avoid doing the work twice. ---
* [ ] I've added an entry in the `CHANGELOG.md` file to explain my changes and credit myself * [ ] Add the entry in the appropriate section (Bug Fix / Nw Feature / Breaking Change / Internal Change) * [ ] Add a period and 2 spaces at the end of your short entry description * [ ] Add links to your GitHub profile to credit yourself and to the related PR and issue after your description ---
Remove warning about refactoring from the GitHub PR template
Remove warning about refactoring from the GitHub PR template
Markdown
mit
AliSoftware/SwiftGen,AliSoftware/SwiftGen,SwiftGen/SwiftGen,AliSoftware/SwiftGen,SwiftGen/SwiftGen
markdown
## Code Before: Thanks for submittng a Pull Request to SwiftGen! Don't forget to add an entry in the `CHANGELOG.md` file to explain your changes and credit yourself! --- ## Important: ⚠️ Refactoring in progress ⚠️ SwiftGen has arrived to a point where it's big enough to deserve [its own GitHub organization](https://github.com/SwiftGen/), and will also be split into multiple repositories for better structure and flexibility. This means that SwiftGen's code will be subject to a big reorganizaton (see [#240](https://github.com/AliSoftware/SwiftGen/issues/240)) and that it may not be the best time to submit a new PR, as it will likely not be valid anymore after that refactoring. We still welcome new PRs very much of course, and are really glad you wish to contribute! But if your change is likely to be affected by this big reorganization, it might be easier for you to wait a few weeks until that refactoring is finished (It's not expected to last long — we hope to finish that big migration ASAP) before submitting your changes, to avoid doing the work twice. --- ## Instruction: Remove warning about refactoring from the GitHub PR template ## Code After: * [ ] I've added an entry in the `CHANGELOG.md` file to explain my changes and credit myself * [ ] Add the entry in the appropriate section (Bug Fix / Nw Feature / Breaking Change / Internal Change) * [ ] Add a period and 2 spaces at the end of your short entry description * [ ] Add links to your GitHub profile to credit yourself and to the related PR and issue after your description ---
- Thanks for submittng a Pull Request to SwiftGen! - Don't forget to add an entry in the `CHANGELOG.md` file to explain your changes and credit yourself! ? ^^^ ^^^^^^ ---- --- --- - + * [ ] I've added an entry in the `CHANGELOG.md` file to explain my changes and credit myself ? ^^^^^^^ ^ ++ + + + * [ ] Add the entry in the appropriate section (Bug Fix / Nw Feature / Breaking Change / Internal Change) + * [ ] Add a period and 2 spaces at the end of your short entry description + * [ ] Add links to your GitHub profile to credit yourself and to the related PR and issue after your description - - --- - - ## Important: ⚠️ Refactoring in progress ⚠️ - - SwiftGen has arrived to a point where it's big enough to deserve [its own GitHub organization](https://github.com/SwiftGen/), and will also be split into multiple repositories for better structure and flexibility. - - This means that SwiftGen's code will be subject to a big reorganizaton (see [#240](https://github.com/AliSoftware/SwiftGen/issues/240)) and that it may not be the best time to submit a new PR, as it will likely not be valid anymore after that refactoring. - - We still welcome new PRs very much of course, and are really glad you wish to contribute! But if your change is likely to be affected by this big reorganization, it might be easier for you to wait a few weeks until that refactoring is finished (It's not expected to last long — we hope to finish that big migration ASAP) before submitting your changes, to avoid doing the work twice. --- +
17
1.214286
5
12
d6ed0e5925e0793bf4fc84b09e709b3a0d907f58
lc0525_contiguous_array.py
lc0525_contiguous_array.py
class Solution(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ pass def main(): pass if __name__ == '__main__': main()
class SolutionDiffsumIdxDict(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int Time complexity: O(n). Space complexity: O(n). """ # Edge case. if len(nums) <= 1: return 0 max_len = 0 # Create a dict:diffsum->idx. diffsum_idx_d = {0: -1} diffsum = 0 for idx, num in enumerate(nums): # Get diff by converting 0 to -1 and 1 to 1. diffsum += 2 * num - 1 # Check if diffsum exists, update max_len. if diffsum in diffsum_idx_d: max_len = max(max_len, idx - diffsum_idx_d[diffsum]) else: diffsum_idx_d[diffsum] = idx return max_len def main(): # Output: 2 nums = [0,1] print SolutionDiffsumIdxDict().findMaxLength(nums) # Output: 2 nums = [0,1,0] print SolutionDiffsumIdxDict().findMaxLength(nums) if __name__ == '__main__': main()
Complete diffsum idx dict sol w/ time/space complexity
Complete diffsum idx dict sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
python
## Code Before: class Solution(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ pass def main(): pass if __name__ == '__main__': main() ## Instruction: Complete diffsum idx dict sol w/ time/space complexity ## Code After: class SolutionDiffsumIdxDict(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int Time complexity: O(n). Space complexity: O(n). """ # Edge case. if len(nums) <= 1: return 0 max_len = 0 # Create a dict:diffsum->idx. diffsum_idx_d = {0: -1} diffsum = 0 for idx, num in enumerate(nums): # Get diff by converting 0 to -1 and 1 to 1. diffsum += 2 * num - 1 # Check if diffsum exists, update max_len. if diffsum in diffsum_idx_d: max_len = max(max_len, idx - diffsum_idx_d[diffsum]) else: diffsum_idx_d[diffsum] = idx return max_len def main(): # Output: 2 nums = [0,1] print SolutionDiffsumIdxDict().findMaxLength(nums) # Output: 2 nums = [0,1,0] print SolutionDiffsumIdxDict().findMaxLength(nums) if __name__ == '__main__': main()
- class Solution(object): + class SolutionDiffsumIdxDict(object): ? ++++++++++++++ def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int + + Time complexity: O(n). + Space complexity: O(n). """ - pass + # Edge case. + if len(nums) <= 1: + return 0 + + max_len = 0 + + # Create a dict:diffsum->idx. + diffsum_idx_d = {0: -1} + diffsum = 0 + for idx, num in enumerate(nums): + # Get diff by converting 0 to -1 and 1 to 1. + diffsum += 2 * num - 1 + + # Check if diffsum exists, update max_len. + if diffsum in diffsum_idx_d: + max_len = max(max_len, idx - diffsum_idx_d[diffsum]) + else: + diffsum_idx_d[diffsum] = idx + + return max_len def main(): - pass + # Output: 2 + nums = [0,1] + print SolutionDiffsumIdxDict().findMaxLength(nums) + + # Output: 2 + nums = [0,1,0] + print SolutionDiffsumIdxDict().findMaxLength(nums) if __name__ == '__main__': main()
34
2
31
3
0f980d283dfcda3cc140b706bc0a26eb65b889c2
_papers/0043.md
_papers/0043.md
--- layout: page number: 43 title: "Discontinuation versus continuation of renin-angiotensin-system inhibitors in COVID-19 (ACEI-COVID): a prospective, parallel group, randomised, controlled, open-label trial" authors: "Borena W, Bánki Z, Bates K, Winner H, Riepler L, Rössler A, Pipperger L, Theurl I, Falkensammer B, Ulmer H, Walser A, Pichler D, Baumgartner M, Schönherr S, Forer L, Knabl L, Würzner R, von Laer D, Paetzold J, Kimpel J." journal: "EBioMedicine" volume: "70" issue: "" pages: "" pmid: 34392147 pubdate: year: 2021 month: Aug day: 12 doi: 10.1016/j.ebiom.2021.103534 ---
--- layout: page number: 43 title: "Persistence of immunity to SARS-CoV-2 over time in the ski resort Ischgl" authors: "Borena W, Bánki Z, Bates K, Winner H, Riepler L, Rössler A, Pipperger L, Theurl I, Falkensammer B, Ulmer H, Walser A, Pichler D, Baumgartner M, Schönherr S, Forer L, Knabl L, Würzner R, von Laer D, Paetzold J, Kimpel J." journal: "EBioMedicine" volume: "70" issue: "" pages: "" pmid: 34392147 pubdate: year: 2021 month: Aug day: 12 doi: 10.1016/j.ebiom.2021.103534 ---
Fix wrong title in paper 43
Fix wrong title in paper 43
Markdown
mit
lukfor/lukfor.github.io,lukfor/lukfor.github.io
markdown
## Code Before: --- layout: page number: 43 title: "Discontinuation versus continuation of renin-angiotensin-system inhibitors in COVID-19 (ACEI-COVID): a prospective, parallel group, randomised, controlled, open-label trial" authors: "Borena W, Bánki Z, Bates K, Winner H, Riepler L, Rössler A, Pipperger L, Theurl I, Falkensammer B, Ulmer H, Walser A, Pichler D, Baumgartner M, Schönherr S, Forer L, Knabl L, Würzner R, von Laer D, Paetzold J, Kimpel J." journal: "EBioMedicine" volume: "70" issue: "" pages: "" pmid: 34392147 pubdate: year: 2021 month: Aug day: 12 doi: 10.1016/j.ebiom.2021.103534 --- ## Instruction: Fix wrong title in paper 43 ## Code After: --- layout: page number: 43 title: "Persistence of immunity to SARS-CoV-2 over time in the ski resort Ischgl" authors: "Borena W, Bánki Z, Bates K, Winner H, Riepler L, Rössler A, Pipperger L, Theurl I, Falkensammer B, Ulmer H, Walser A, Pichler D, Baumgartner M, Schönherr S, Forer L, Knabl L, Würzner R, von Laer D, Paetzold J, Kimpel J." journal: "EBioMedicine" volume: "70" issue: "" pages: "" pmid: 34392147 pubdate: year: 2021 month: Aug day: 12 doi: 10.1016/j.ebiom.2021.103534 ---
--- layout: page number: 43 - title: "Discontinuation versus continuation of renin-angiotensin-system inhibitors in COVID-19 (ACEI-COVID): a prospective, parallel group, randomised, controlled, open-label trial" + title: "Persistence of immunity to SARS-CoV-2 over time in the ski resort Ischgl" authors: "Borena W, Bánki Z, Bates K, Winner H, Riepler L, Rössler A, Pipperger L, Theurl I, Falkensammer B, Ulmer H, Walser A, Pichler D, Baumgartner M, Schönherr S, Forer L, Knabl L, Würzner R, von Laer D, Paetzold J, Kimpel J." journal: "EBioMedicine" volume: "70" issue: "" pages: "" pmid: 34392147 pubdate: year: 2021 month: Aug day: 12 doi: 10.1016/j.ebiom.2021.103534 ---
2
0.125
1
1
0e8afdfb17a691c1c139e265e4085d6c12797b7b
app/views/code_status/index.html.erb
app/views/code_status/index.html.erb
<h3>Revision <a href="https://github.com/Charcoal-SE/metasmoke/commit/<%= CurrentCommit %>"><code><%= CurrentCommit.first(7) %></code></a></h3> <hr> <details open><summary class="h3">Versions <%= link_to "Show ", "#", :id => "show-all-gem-versions" %></summary> <table class="table" id="gems-versions-table"> <thead> <tr> <th>Name</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td><%= link_to "Ruby", "https://www.ruby-lang.org/en/" %></td> <td><%= RUBY_VERSION %></td> </tr> <% @gem_versions.each do |g| %> <tr class="<% if !@important_gems.include? g.name %>minor hide<% end %>"> <td><%= link_to g.name.titleize, "https://rubygems.org/gems/#{g.name}" %></td> <td><%= g.version %></td> </tr> <% end %> </tbody> </table> </details>
<h3>Revision <%= link_to "https://github.com/Charcoal-SE/metasmoke/commit/#{CurrentCommit}" do %><code><%= CurrentCommit.first(7) %></code><% end %></h3> <hr> <details open><summary class="h3">Versions <%= link_to "Show ", "#", :id => "show-all-gem-versions" %></summary> <table class="table" id="gems-versions-table"> <thead> <tr> <th>Name</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td><%= link_to "Ruby", "https://www.ruby-lang.org/en/" %></td> <td><%= RUBY_VERSION %></td> </tr> <% @gem_versions.each do |g| %> <tr class="<% if !@important_gems.include? g.name %>minor hide<% end %>"> <td><%= link_to g.name.titleize, "https://rubygems.org/gems/#{g.name}" %></td> <td><%= g.version %></td> </tr> <% end %> </tbody> </table> </details>
Use `link_to` syntax for link
Use `link_to` syntax for link
HTML+ERB
cc0-1.0
j-f1/forked-metasmoke,angussidney/metasmoke,SulphurDioxide/metasmoke,Charcoal-SE/metasmoke,Charcoal-SE/metasmoke,SulphurDioxide/metasmoke,angussidney/metasmoke,j-f1/forked-metasmoke,j-f1/forked-metasmoke,Charcoal-SE/metasmoke,angussidney/metasmoke,SulphurDioxide/metasmoke,j-f1/forked-metasmoke,Charcoal-SE/metasmoke,angussidney/metasmoke
html+erb
## Code Before: <h3>Revision <a href="https://github.com/Charcoal-SE/metasmoke/commit/<%= CurrentCommit %>"><code><%= CurrentCommit.first(7) %></code></a></h3> <hr> <details open><summary class="h3">Versions <%= link_to "Show ", "#", :id => "show-all-gem-versions" %></summary> <table class="table" id="gems-versions-table"> <thead> <tr> <th>Name</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td><%= link_to "Ruby", "https://www.ruby-lang.org/en/" %></td> <td><%= RUBY_VERSION %></td> </tr> <% @gem_versions.each do |g| %> <tr class="<% if !@important_gems.include? g.name %>minor hide<% end %>"> <td><%= link_to g.name.titleize, "https://rubygems.org/gems/#{g.name}" %></td> <td><%= g.version %></td> </tr> <% end %> </tbody> </table> </details> ## Instruction: Use `link_to` syntax for link ## Code After: <h3>Revision <%= link_to "https://github.com/Charcoal-SE/metasmoke/commit/#{CurrentCommit}" do %><code><%= CurrentCommit.first(7) %></code><% end %></h3> <hr> <details open><summary class="h3">Versions <%= link_to "Show ", "#", :id => "show-all-gem-versions" %></summary> <table class="table" id="gems-versions-table"> <thead> <tr> <th>Name</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td><%= link_to "Ruby", "https://www.ruby-lang.org/en/" %></td> <td><%= RUBY_VERSION %></td> </tr> <% @gem_versions.each do |g| %> <tr class="<% if !@important_gems.include? g.name %>minor hide<% end %>"> <td><%= link_to g.name.titleize, "https://rubygems.org/gems/#{g.name}" %></td> <td><%= g.version %></td> </tr> <% end %> </tbody> </table> </details>
- <h3>Revision <a href="https://github.com/Charcoal-SE/metasmoke/commit/<%= CurrentCommit %>"><code><%= CurrentCommit.first(7) %></code></a></h3> ? ^ ^^^^^ ^^^^ -- ^^ + <h3>Revision <%= link_to "https://github.com/Charcoal-SE/metasmoke/commit/#{CurrentCommit}" do %><code><%= CurrentCommit.first(7) %></code><% end %></h3> ? ^^ ^^^^^^^^ ^^ +++++ ^^^^^^^ <hr> <details open><summary class="h3">Versions <%= link_to "Show ", "#", :id => "show-all-gem-versions" %></summary> <table class="table" id="gems-versions-table"> <thead> <tr> <th>Name</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td><%= link_to "Ruby", "https://www.ruby-lang.org/en/" %></td> <td><%= RUBY_VERSION %></td> </tr> <% @gem_versions.each do |g| %> <tr class="<% if !@important_gems.include? g.name %>minor hide<% end %>"> <td><%= link_to g.name.titleize, "https://rubygems.org/gems/#{g.name}" %></td> <td><%= g.version %></td> </tr> <% end %> </tbody> </table> </details>
2
0.074074
1
1
8d760a9023d8466caf8f31ee8284292fcfee631e
package.json
package.json
{ "name": "interrogator", "description": "Put the screws to your users. (Or just ask them nicely. I don't care, it's your software.)", "main": "./lib/interrogator", "author": { "name": "Corey Cossentino" }, "version": "0.0.8", "repository": { "type": "git", "url": "https://github.com/Dennovin/interrogator.git" }, "licenses": [ { "type": "MIT", "url": "https://raw.githubusercontent.com/Dennovin/interrogator/master/LICENSE" } ], "dependencies": { "sprintf": "latest", "validator": "latest", "heap": "latest", "read": "latest" } }
{ "name": "interrogator", "description": "Put the screws to your users. (Or just ask them nicely. I don't care, it's your software.)", "main": "./lib/interrogator", "author": { "name": "Corey Cossentino" }, "version": "0.0.8", "repository": { "type": "git", "url": "https://github.com/Dennovin/interrogator.git" }, "licenses": [ { "type": "MIT", "url": "https://raw.githubusercontent.com/Dennovin/interrogator/master/LICENSE" } ], "dependencies": { "sprintf": "0.1.5", "validator": "3.40.0", "heap": "latest", "read": "latest" } }
Change dependency versions of sprintf and validator
Change dependency versions of sprintf and validator Interrogator is used in the program cup, and having the sprintf and validator dependencies be latest is messing with cup and giving the user unmet dependencies.
JSON
mit
Dennovin/interrogator
json
## Code Before: { "name": "interrogator", "description": "Put the screws to your users. (Or just ask them nicely. I don't care, it's your software.)", "main": "./lib/interrogator", "author": { "name": "Corey Cossentino" }, "version": "0.0.8", "repository": { "type": "git", "url": "https://github.com/Dennovin/interrogator.git" }, "licenses": [ { "type": "MIT", "url": "https://raw.githubusercontent.com/Dennovin/interrogator/master/LICENSE" } ], "dependencies": { "sprintf": "latest", "validator": "latest", "heap": "latest", "read": "latest" } } ## Instruction: Change dependency versions of sprintf and validator Interrogator is used in the program cup, and having the sprintf and validator dependencies be latest is messing with cup and giving the user unmet dependencies. ## Code After: { "name": "interrogator", "description": "Put the screws to your users. (Or just ask them nicely. I don't care, it's your software.)", "main": "./lib/interrogator", "author": { "name": "Corey Cossentino" }, "version": "0.0.8", "repository": { "type": "git", "url": "https://github.com/Dennovin/interrogator.git" }, "licenses": [ { "type": "MIT", "url": "https://raw.githubusercontent.com/Dennovin/interrogator/master/LICENSE" } ], "dependencies": { "sprintf": "0.1.5", "validator": "3.40.0", "heap": "latest", "read": "latest" } }
{ "name": "interrogator", "description": "Put the screws to your users. (Or just ask them nicely. I don't care, it's your software.)", "main": "./lib/interrogator", "author": { "name": "Corey Cossentino" }, "version": "0.0.8", "repository": { "type": "git", "url": "https://github.com/Dennovin/interrogator.git" }, "licenses": [ { "type": "MIT", "url": "https://raw.githubusercontent.com/Dennovin/interrogator/master/LICENSE" } ], "dependencies": { - "sprintf": "latest", ? ^^^^^^ + "sprintf": "0.1.5", ? ^^^^^ - "validator": "latest", ? ^^^^^^ + "validator": "3.40.0", ? ^^^^^^ "heap": "latest", "read": "latest" } }
4
0.16
2
2
361e31dc14adca90fb260fd2f58e4412597c0680
js/templates/modals/purchase/shippingOptions.html
js/templates/modals/purchase/shippingOptions.html
<% if (ob.filteredShipping.length) { %> <div class="flexColRows boxList border borderStacked clrP clrBr"> <% ob.filteredShipping.forEach((option, i) => { %> <% option.services.forEach((service, j) => { %> <div> <div class="btnRadio width100"> <input type="radio" class="js-shippingOption" id="<%= `${i}${j}` %>" <% if (i===0 && j === 0) print('checked') %> data-name="<%= option.name %>" data-service="<%= service.name %>" name="shippingOption"> <label for="<%= `${i}${j}` %>" class="flex gutterH pad"> <div> <div class="tx5 rowSm txB"><%= service.name %></div> <div class="tx5b clrT2 txUnb"> <% const price = ob.convertAndFormatCurrency(service.price, ob.metadata.pricingCurrency, ob.displayCurrency) %> <%= ob.polyT('purchase.serviceDetails', { price, delivery: service.estimatedDelivery }) %> </div> </div> </label> </div> </div> <% }); %> <% }); %> </div> <% } else { %> <div class="padGi flexCent"> <h5><%= ob.polyT('purchase.noShippableAddresses') %></h5> </div> <% } %>
<% if (ob.filteredShipping.length) { %> <div class="flexColRows boxList border borderStacked clrP clrBr"> <% ob.filteredShipping.forEach((option, i) => { option.services = _.sortBy(option.services, 'price'); %> <% option.services.forEach((service, j) => { %> <div> <div class="btnRadio width100"> <input type="radio" class="js-shippingOption" id="<%= `${i}${j}` %>" <% if (i===0 && j === 0) print('checked') %> data-name="<%= option.name %>" data-service="<%= service.name %>" name="shippingOption"> <label for="<%= `${i}${j}` %>" class="flex gutterH pad"> <div> <div class="tx5 rowSm txB"><%= option.name %>: <%= service.name %></div> <div class="tx5b clrT2 txUnb"> <% const price = ob.convertAndFormatCurrency(service.price, ob.metadata.pricingCurrency, ob.displayCurrency) %> <%= ob.polyT('purchase.serviceDetails', { price, delivery: service.estimatedDelivery }) %> </div> </div> </label> </div> </div> <% }); %> <% }); %> </div> <% } else { %> <div class="padGi flexCent"> <h5><%= ob.polyT('purchase.noShippableAddresses') %></h5> </div> <% } %>
Add the option title to the name of the shipping option. Sort the services by the price within the option.
Add the option title to the name of the shipping option. Sort the services by the price within the option.
HTML
mit
OpenBazaar/openbazaar-desktop,OpenBazaar/openbazaar-desktop,jjeffryes/openbazaar-desktop,jashot7/openbazaar-desktop,jjeffryes/openbazaar-desktop,jjeffryes/openbazaar-desktop,jashot7/openbazaar-desktop,jashot7/openbazaar-desktop,OpenBazaar/openbazaar-desktop
html
## Code Before: <% if (ob.filteredShipping.length) { %> <div class="flexColRows boxList border borderStacked clrP clrBr"> <% ob.filteredShipping.forEach((option, i) => { %> <% option.services.forEach((service, j) => { %> <div> <div class="btnRadio width100"> <input type="radio" class="js-shippingOption" id="<%= `${i}${j}` %>" <% if (i===0 && j === 0) print('checked') %> data-name="<%= option.name %>" data-service="<%= service.name %>" name="shippingOption"> <label for="<%= `${i}${j}` %>" class="flex gutterH pad"> <div> <div class="tx5 rowSm txB"><%= service.name %></div> <div class="tx5b clrT2 txUnb"> <% const price = ob.convertAndFormatCurrency(service.price, ob.metadata.pricingCurrency, ob.displayCurrency) %> <%= ob.polyT('purchase.serviceDetails', { price, delivery: service.estimatedDelivery }) %> </div> </div> </label> </div> </div> <% }); %> <% }); %> </div> <% } else { %> <div class="padGi flexCent"> <h5><%= ob.polyT('purchase.noShippableAddresses') %></h5> </div> <% } %> ## Instruction: Add the option title to the name of the shipping option. Sort the services by the price within the option. ## Code After: <% if (ob.filteredShipping.length) { %> <div class="flexColRows boxList border borderStacked clrP clrBr"> <% ob.filteredShipping.forEach((option, i) => { option.services = _.sortBy(option.services, 'price'); %> <% option.services.forEach((service, j) => { %> <div> <div class="btnRadio width100"> <input type="radio" class="js-shippingOption" id="<%= `${i}${j}` %>" <% if (i===0 && j === 0) print('checked') %> data-name="<%= option.name %>" data-service="<%= service.name %>" name="shippingOption"> <label for="<%= `${i}${j}` %>" class="flex gutterH pad"> <div> <div class="tx5 rowSm txB"><%= option.name %>: <%= service.name %></div> <div class="tx5b clrT2 txUnb"> <% const price = ob.convertAndFormatCurrency(service.price, ob.metadata.pricingCurrency, ob.displayCurrency) %> <%= ob.polyT('purchase.serviceDetails', { price, delivery: service.estimatedDelivery }) %> </div> </div> </label> </div> </div> <% }); %> <% }); %> </div> <% } else { %> <div class="padGi flexCent"> <h5><%= ob.polyT('purchase.noShippableAddresses') %></h5> </div> <% } %>
<% if (ob.filteredShipping.length) { %> <div class="flexColRows boxList border borderStacked clrP clrBr"> - <% ob.filteredShipping.forEach((option, i) => { %> ? --- + <% ob.filteredShipping.forEach((option, i) => { + option.services = _.sortBy(option.services, 'price'); %> <% option.services.forEach((service, j) => { %> <div> <div class="btnRadio width100"> <input type="radio" class="js-shippingOption" id="<%= `${i}${j}` %>" <% if (i===0 && j === 0) print('checked') %> data-name="<%= option.name %>" data-service="<%= service.name %>" name="shippingOption"> <label for="<%= `${i}${j}` %>" class="flex gutterH pad"> <div> - <div class="tx5 rowSm txB"><%= service.name %></div> + <div class="tx5 rowSm txB"><%= option.name %>: <%= service.name %></div> ? ++++++++++++++++++++ <div class="tx5b clrT2 txUnb"> <% const price = ob.convertAndFormatCurrency(service.price, ob.metadata.pricingCurrency, ob.displayCurrency) %> <%= ob.polyT('purchase.serviceDetails', { price, delivery: service.estimatedDelivery }) %> </div> </div> </label> </div> </div> <% }); %> <% }); %> </div> <% } else { %> <div class="padGi flexCent"> <h5><%= ob.polyT('purchase.noShippableAddresses') %></h5> </div> <% } %>
5
0.15625
3
2
13501628dd1630923d9a5248b78d461371d746c8
workshops/personal_website.md
workshops/personal_website.md
Objective: * Teach students how to use HTML and CSS, and Javascript to build a basic website. Skills learned: * What HTML, CSS, and Javascript are and the difference between them. * How to apply HTML, CSS, and Javascript to build a website. * How to find help when building websites. * How to use Neocities to host a website. Tangible outcome: * A hosted website at a publicly accessible domain.
Objective: * Teach students how to use HTML and CSS, and Javascript to build a basic website. Skills learned: * What HTML, CSS, and Javascript are and the difference between them. * How to apply HTML, CSS, and Javascript to build a website. * How to find help when building websites. * How to use Neocities to host a website. Tangible outcome: * A hosted website at a publicly accessible domain. ## Actions 1. Download and install [Sublime Text](http://www.sublimetext.com/3). 2. Create a new directory where you want the website files to be. 3. Open Sublime Text and go to File > Open Folder. Open the directory you just created. 4. Right click on the folder to the left and click "New File". Go File > Save and name the file `index.html`. 5. Add the following to `index.html`. ``` <!doctype html> <html> <head> <title>Hello, World!</title> </head> <body> <p>Hello, World!</p> </body> </html> ``` 6. Right click anywhere in the file and select "Open in Browser".
Add actions for creating hello world website.
Add actions for creating hello world website.
Markdown
mit
saescapa/meta,ssun098/meta,paked/meta,hackedu/meta,ssun098/meta,saescapa/meta,paked/meta,hackedu/meta
markdown
## Code Before: Objective: * Teach students how to use HTML and CSS, and Javascript to build a basic website. Skills learned: * What HTML, CSS, and Javascript are and the difference between them. * How to apply HTML, CSS, and Javascript to build a website. * How to find help when building websites. * How to use Neocities to host a website. Tangible outcome: * A hosted website at a publicly accessible domain. ## Instruction: Add actions for creating hello world website. ## Code After: Objective: * Teach students how to use HTML and CSS, and Javascript to build a basic website. Skills learned: * What HTML, CSS, and Javascript are and the difference between them. * How to apply HTML, CSS, and Javascript to build a website. * How to find help when building websites. * How to use Neocities to host a website. Tangible outcome: * A hosted website at a publicly accessible domain. ## Actions 1. Download and install [Sublime Text](http://www.sublimetext.com/3). 2. Create a new directory where you want the website files to be. 3. Open Sublime Text and go to File > Open Folder. Open the directory you just created. 4. Right click on the folder to the left and click "New File". Go File > Save and name the file `index.html`. 5. Add the following to `index.html`. ``` <!doctype html> <html> <head> <title>Hello, World!</title> </head> <body> <p>Hello, World!</p> </body> </html> ``` 6. Right click anywhere in the file and select "Open in Browser".
Objective: * Teach students how to use HTML and CSS, and Javascript to build a basic website. Skills learned: * What HTML, CSS, and Javascript are and the difference between them. * How to apply HTML, CSS, and Javascript to build a website. * How to find help when building websites. * How to use Neocities to host a website. Tangible outcome: * A hosted website at a publicly accessible domain. + + ## Actions + + 1. Download and install [Sublime Text](http://www.sublimetext.com/3). + 2. Create a new directory where you want the website files to be. + 3. Open Sublime Text and go to File > Open Folder. Open the directory you just + created. + 4. Right click on the folder to the left and click "New File". Go File > Save + and name the file `index.html`. + 5. Add the following to `index.html`. + + ``` + <!doctype html> + <html> + <head> + <title>Hello, World!</title> + </head> + <body> + <p>Hello, World!</p> + </body> + </html> + ``` + + 6. Right click anywhere in the file and select "Open in Browser".
24
1.5
24
0
0e6b31b82553cf5f177d5ce8f0071b2ffc94d758
src/plugins/mk/interfaces.mk
src/plugins/mk/interfaces.mk
PLUGIN_VAPIS := \ plugins/shotwell-spit-1.0.vapi \ plugins/shotwell-transitions-1.0.vapi PLUGIN_HEADERS := $(PLUGIN_VAPIS:.vapi=.h) PLUGIN_DEPS := $(PLUGIN_VAPIS:.vapi=.deps) $(PLUGIN_HEADERS): %.h: %.vapi plugins/shotwell-spit-1.0.deps: plugins/shotwell-spit-1.0.vapi @echo "" > $@ plugins/shotwell-spit-1.0.vapi: src/plugins/SpitInterfaces.vala $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --includedir=plugins --vapi=$@ --header=$(basename $@).h $< plugins/shotwell-transitions-1.0.deps: plugins/shotwell-transitions-1.0.vapi @printf "gdk-2.0\nshotwell-spit-1.0\n" > $@ plugins/shotwell-transitions-1.0.vapi: src/plugins/TransitionsInterfaces.vala plugins/shotwell-spit-1.0.vapi $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --pkg=gdk-2.0 --pkg=shotwell-spit-1.0 --includedir=plugins --vapi=$@ --header=$(basename $@).h $<
PLUGIN_VAPIS := \ plugins/shotwell-spit-1.0.vapi \ plugins/shotwell-transitions-1.0.vapi PLUGIN_HEADERS := $(PLUGIN_VAPIS:.vapi=.h) PLUGIN_DEPS := $(PLUGIN_VAPIS:.vapi=.deps) $(PLUGIN_HEADERS): %.h: %.vapi plugins/shotwell-spit-1.0.deps: plugins/shotwell-spit-1.0.vapi @echo "" > $@ plugins/shotwell-spit-1.0.vapi: src/plugins/SpitInterfaces.vala $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --includedir=plugins --vapi=$@ --header=$(basename $@).h $< rm $(notdir $<).o plugins/shotwell-transitions-1.0.deps: plugins/shotwell-transitions-1.0.vapi @printf "gdk-2.0\nshotwell-spit-1.0\n" > $@ plugins/shotwell-transitions-1.0.vapi: src/plugins/TransitionsInterfaces.vala plugins/shotwell-spit-1.0.vapi $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --pkg=gdk-2.0 --pkg=shotwell-spit-1.0 --includedir=plugins --vapi=$@ --header=$(basename $@).h $< rm $(notdir $<).o
Build system now removes temp file leftover during VAPI creation.
Build system now removes temp file leftover during VAPI creation.
Makefile
lgpl-2.1
ritchiewilson/shotwell,ritchiewilson/shotwell,damianmoore/shotwell,abrauchli/shotwell,ritchiewilson/shotwell,polymeris/shotwell,polymeris/shotwell,Sanva/shotwell-gsoc,jimbonator/shotwell,Sanva/shotwell-gsoc,damianmoore/shotwell,abrauchli/shotwell,damianmoore/shotwell,h4ck3rm1k3/shotwell,jimbonator/shotwell,h4ck3rm1k3/shotwell,Sanva/shotwell-gsoc,jof/shotwell,jof/shotwell,jof/shotwell,abrauchli/shotwell,jimbonator/shotwell,polymeris/shotwell,h4ck3rm1k3/shotwell
makefile
## Code Before: PLUGIN_VAPIS := \ plugins/shotwell-spit-1.0.vapi \ plugins/shotwell-transitions-1.0.vapi PLUGIN_HEADERS := $(PLUGIN_VAPIS:.vapi=.h) PLUGIN_DEPS := $(PLUGIN_VAPIS:.vapi=.deps) $(PLUGIN_HEADERS): %.h: %.vapi plugins/shotwell-spit-1.0.deps: plugins/shotwell-spit-1.0.vapi @echo "" > $@ plugins/shotwell-spit-1.0.vapi: src/plugins/SpitInterfaces.vala $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --includedir=plugins --vapi=$@ --header=$(basename $@).h $< plugins/shotwell-transitions-1.0.deps: plugins/shotwell-transitions-1.0.vapi @printf "gdk-2.0\nshotwell-spit-1.0\n" > $@ plugins/shotwell-transitions-1.0.vapi: src/plugins/TransitionsInterfaces.vala plugins/shotwell-spit-1.0.vapi $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --pkg=gdk-2.0 --pkg=shotwell-spit-1.0 --includedir=plugins --vapi=$@ --header=$(basename $@).h $< ## Instruction: Build system now removes temp file leftover during VAPI creation. ## Code After: PLUGIN_VAPIS := \ plugins/shotwell-spit-1.0.vapi \ plugins/shotwell-transitions-1.0.vapi PLUGIN_HEADERS := $(PLUGIN_VAPIS:.vapi=.h) PLUGIN_DEPS := $(PLUGIN_VAPIS:.vapi=.deps) $(PLUGIN_HEADERS): %.h: %.vapi plugins/shotwell-spit-1.0.deps: plugins/shotwell-spit-1.0.vapi @echo "" > $@ plugins/shotwell-spit-1.0.vapi: src/plugins/SpitInterfaces.vala $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --includedir=plugins --vapi=$@ --header=$(basename $@).h $< rm $(notdir $<).o plugins/shotwell-transitions-1.0.deps: plugins/shotwell-transitions-1.0.vapi @printf "gdk-2.0\nshotwell-spit-1.0\n" > $@ plugins/shotwell-transitions-1.0.vapi: src/plugins/TransitionsInterfaces.vala plugins/shotwell-spit-1.0.vapi $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --pkg=gdk-2.0 --pkg=shotwell-spit-1.0 --includedir=plugins --vapi=$@ --header=$(basename $@).h $< rm $(notdir $<).o
PLUGIN_VAPIS := \ plugins/shotwell-spit-1.0.vapi \ plugins/shotwell-transitions-1.0.vapi PLUGIN_HEADERS := $(PLUGIN_VAPIS:.vapi=.h) PLUGIN_DEPS := $(PLUGIN_VAPIS:.vapi=.deps) $(PLUGIN_HEADERS): %.h: %.vapi plugins/shotwell-spit-1.0.deps: plugins/shotwell-spit-1.0.vapi @echo "" > $@ plugins/shotwell-spit-1.0.vapi: src/plugins/SpitInterfaces.vala $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --includedir=plugins --vapi=$@ --header=$(basename $@).h $< + rm $(notdir $<).o plugins/shotwell-transitions-1.0.deps: plugins/shotwell-transitions-1.0.vapi @printf "gdk-2.0\nshotwell-spit-1.0\n" > $@ plugins/shotwell-transitions-1.0.vapi: src/plugins/TransitionsInterfaces.vala plugins/shotwell-spit-1.0.vapi $(call check_valac_version) $(VALAC) -c $(VALAFLAGS) -X -I. --pkg=gdk-2.0 --pkg=shotwell-spit-1.0 --includedir=plugins --vapi=$@ --header=$(basename $@).h $< - + rm $(notdir $<).o
3
0.125
2
1
af0291fa07bed67f96e9e21611a9edab9aa7a770
test/bane/behaviors/servers/timeout_in_listen_queue_test.rb
test/bane/behaviors/servers/timeout_in_listen_queue_test.rb
require_relative '../../../test_helper' require 'socket' class TimeoutInListenQueueTest < Test::Unit::TestCase include LaunchableRoleTests include ServerTestHelpers def setup @object = Bane::Behaviors::Servers::TimeoutInListenQueue.make(IRRELEVANT_PORT, Bane::Behaviors::Servers::LOCALHOST) end def test_never_connects pend "Need to review after Ruby 2+ update; now returns Errno:ECONNREFUSED" run_server(Bane::Behaviors::Servers::TimeoutInListenQueue.make(port, Bane::Behaviors::Servers::LOCALHOST)) do assert_raise(Errno::ETIMEDOUT) { TCPSocket.new('localhost', port) } end end def port 4001 end end
require_relative '../../../test_helper' require 'socket' class TimeoutInListenQueueTest < Test::Unit::TestCase include LaunchableRoleTests include ServerTestHelpers def setup @object = Bane::Behaviors::Servers::TimeoutInListenQueue.make(IRRELEVANT_PORT, Bane::Behaviors::Servers::LOCALHOST) end def test_never_connects run_server(Bane::Behaviors::Servers::TimeoutInListenQueue.make(port, Bane::Behaviors::Servers::LOCALHOST)) do assert_raise(Errno::ECONNREFUSED) { TCPSocket.new('localhost', port) } end end def port 4001 end end
Revert to previous observed failure of TimeoutInListenQueue behavior
Revert to previous observed failure of TimeoutInListenQueue behavior
Ruby
bsd-2-clause
danielwellman/bane
ruby
## Code Before: require_relative '../../../test_helper' require 'socket' class TimeoutInListenQueueTest < Test::Unit::TestCase include LaunchableRoleTests include ServerTestHelpers def setup @object = Bane::Behaviors::Servers::TimeoutInListenQueue.make(IRRELEVANT_PORT, Bane::Behaviors::Servers::LOCALHOST) end def test_never_connects pend "Need to review after Ruby 2+ update; now returns Errno:ECONNREFUSED" run_server(Bane::Behaviors::Servers::TimeoutInListenQueue.make(port, Bane::Behaviors::Servers::LOCALHOST)) do assert_raise(Errno::ETIMEDOUT) { TCPSocket.new('localhost', port) } end end def port 4001 end end ## Instruction: Revert to previous observed failure of TimeoutInListenQueue behavior ## Code After: require_relative '../../../test_helper' require 'socket' class TimeoutInListenQueueTest < Test::Unit::TestCase include LaunchableRoleTests include ServerTestHelpers def setup @object = Bane::Behaviors::Servers::TimeoutInListenQueue.make(IRRELEVANT_PORT, Bane::Behaviors::Servers::LOCALHOST) end def test_never_connects run_server(Bane::Behaviors::Servers::TimeoutInListenQueue.make(port, Bane::Behaviors::Servers::LOCALHOST)) do assert_raise(Errno::ECONNREFUSED) { TCPSocket.new('localhost', port) } end end def port 4001 end end
require_relative '../../../test_helper' require 'socket' class TimeoutInListenQueueTest < Test::Unit::TestCase include LaunchableRoleTests include ServerTestHelpers def setup @object = Bane::Behaviors::Servers::TimeoutInListenQueue.make(IRRELEVANT_PORT, Bane::Behaviors::Servers::LOCALHOST) end def test_never_connects - pend "Need to review after Ruby 2+ update; now returns Errno:ECONNREFUSED" run_server(Bane::Behaviors::Servers::TimeoutInListenQueue.make(port, Bane::Behaviors::Servers::LOCALHOST)) do - assert_raise(Errno::ETIMEDOUT) { TCPSocket.new('localhost', port) } ? ^^^ --- + assert_raise(Errno::ECONNREFUSED) { TCPSocket.new('localhost', port) } ? ^^^^^^^^^ end end def port 4001 end end
3
0.12
1
2
9da9ec6618de8c9a1276e44e81c32639d42efada
setup.py
setup.py
from distutils.core import setup setup( name='hy-py', version='0.0.2', packages=['hy'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirements.txt').read().split(), )
from distutils.core import setup setup( name='hy-py', version='0.0.3', packages=['hy', 'hy.adapters'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirements.txt').read().split(), )
Include the serializer adapters in the PyPI package
Include the serializer adapters in the PyPI package
Python
mit
kalasjocke/hyp
python
## Code Before: from distutils.core import setup setup( name='hy-py', version='0.0.2', packages=['hy'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirements.txt').read().split(), ) ## Instruction: Include the serializer adapters in the PyPI package ## Code After: from distutils.core import setup setup( name='hy-py', version='0.0.3', packages=['hy', 'hy.adapters'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirements.txt').read().split(), )
from distutils.core import setup setup( name='hy-py', - version='0.0.2', ? ^ + version='0.0.3', ? ^ - packages=['hy'], + packages=['hy', 'hy.adapters'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirements.txt').read().split(), )
4
0.307692
2
2
92d25e86620fcdc415e94d5867cc22a95f88ca3a
mint/rest/db/awshandler.py
mint/rest/db/awshandler.py
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId, projectId) def notify_UserProductAdded(self, event, userId, projectId, userlevel = None): self.amiPerms.deleteMemberFromProject(userId, projectId) def notify_UserProductChanged(self, event, userId, projectId, oldLevel, newLevel): self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel) def notify_UserCancelled(self, userId): # yuck. awsFound, oldAwsAccountNumber = self.db.userData.getDataValue( userId, 'awsAccountNumber') self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None) def notify_ReleasePublished(self, releaseId): self.amiPerms.publishRelease(releaseId) def notify_ReleaseUnpublished(self, releaseId): self.amiPerms.unpublishRelease(releaseId)
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.deleteMemberFromProject(userId, projectId) def notify_UserProductAdded(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId, projectId) def notify_UserProductChanged(self, event, userId, projectId, oldLevel, newLevel): self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel) def notify_UserCancelled(self, userId): # yuck. awsFound, oldAwsAccountNumber = self.db.userData.getDataValue( userId, 'awsAccountNumber') self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None) def notify_ReleasePublished(self, releaseId): self.amiPerms.publishRelease(releaseId) def notify_ReleaseUnpublished(self, releaseId): self.amiPerms.unpublishRelease(releaseId)
Fix typo when setting up handler.
Fix typo when setting up handler.
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
python
## Code Before: from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId, projectId) def notify_UserProductAdded(self, event, userId, projectId, userlevel = None): self.amiPerms.deleteMemberFromProject(userId, projectId) def notify_UserProductChanged(self, event, userId, projectId, oldLevel, newLevel): self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel) def notify_UserCancelled(self, userId): # yuck. awsFound, oldAwsAccountNumber = self.db.userData.getDataValue( userId, 'awsAccountNumber') self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None) def notify_ReleasePublished(self, releaseId): self.amiPerms.publishRelease(releaseId) def notify_ReleaseUnpublished(self, releaseId): self.amiPerms.unpublishRelease(releaseId) ## Instruction: Fix typo when setting up handler. ## Code After: from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.deleteMemberFromProject(userId, projectId) def notify_UserProductAdded(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId, projectId) def notify_UserProductChanged(self, event, userId, projectId, oldLevel, newLevel): self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel) def notify_UserCancelled(self, userId): # yuck. awsFound, oldAwsAccountNumber = self.db.userData.getDataValue( userId, 'awsAccountNumber') self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None) def notify_ReleasePublished(self, releaseId): self.amiPerms.publishRelease(releaseId) def notify_ReleaseUnpublished(self, releaseId): self.amiPerms.unpublishRelease(releaseId)
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): - self.amiPerms.addMemberToProject(userId, projectId) ? - ^ ^ + self.amiPerms.deleteMemberFromProject(userId, projectId) ? ^^^^^ ^^ + def notify_UserProductAdded(self, event, userId, projectId, userlevel = None): - self.amiPerms.deleteMemberFromProject(userId, projectId) ? ^^^^^ ^^ - + self.amiPerms.addMemberToProject(userId, projectId) ? + ^ ^ def notify_UserProductChanged(self, event, userId, projectId, oldLevel, newLevel): self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel) def notify_UserCancelled(self, userId): # yuck. awsFound, oldAwsAccountNumber = self.db.userData.getDataValue( userId, 'awsAccountNumber') self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None) def notify_ReleasePublished(self, releaseId): self.amiPerms.publishRelease(releaseId) def notify_ReleaseUnpublished(self, releaseId): self.amiPerms.unpublishRelease(releaseId)
4
0.142857
2
2
3657cb270dc5d6bc05460e69e1017f24a127d722
lib/nightwatch/logger/slack.rb
lib/nightwatch/logger/slack.rb
require 'faraday' require 'json' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE module Nightwatch class SlackLogger def initialize(opts = {}) @url = opts[:url] if !@url raise Error, 'Webhook URL is required.' end end def log(records) texts = [] records.each do |record| exception = record[:exception] klass = exception[:class] message = exception[:message] text = "#{klass}: #{message}" top = exception[:stack].first if top text += " at #{top[:label]} in #{top[:path]}:#{top[:line]}" end texts << text end Faraday.new(:url => @url).post do |req| req.headers['Content-Type'] = 'application/json' req.body = JSON.dump({ username: 'Nightwatch', text: texts.join("\n") }) end end end end
require 'faraday' require 'json' module Nightwatch class SlackLogger def initialize(opts = {}) @url = opts[:url] if !@url raise Error, 'Webhook URL is required.' end end def log(records) texts = [] records.each do |record| exception = record[:exception] klass = exception[:class] message = exception[:message] text = "`#{klass}`: #{message}" top = exception[:stack].first if top text += " at `#{top[:label]}` in #{top[:path]}:#{top[:line]}" end texts << text end Faraday.new(:url => @url).post do |req| req.headers['Content-Type'] = 'application/json' req.body = JSON.dump({ username: 'Nightwatch', text: texts.join("\n") }) end end end end
Use code formatting for Slack messages.
Use code formatting for Slack messages.
Ruby
mit
schmich/nightwatch,schmich/nightwatch
ruby
## Code Before: require 'faraday' require 'json' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE module Nightwatch class SlackLogger def initialize(opts = {}) @url = opts[:url] if !@url raise Error, 'Webhook URL is required.' end end def log(records) texts = [] records.each do |record| exception = record[:exception] klass = exception[:class] message = exception[:message] text = "#{klass}: #{message}" top = exception[:stack].first if top text += " at #{top[:label]} in #{top[:path]}:#{top[:line]}" end texts << text end Faraday.new(:url => @url).post do |req| req.headers['Content-Type'] = 'application/json' req.body = JSON.dump({ username: 'Nightwatch', text: texts.join("\n") }) end end end end ## Instruction: Use code formatting for Slack messages. ## Code After: require 'faraday' require 'json' module Nightwatch class SlackLogger def initialize(opts = {}) @url = opts[:url] if !@url raise Error, 'Webhook URL is required.' end end def log(records) texts = [] records.each do |record| exception = record[:exception] klass = exception[:class] message = exception[:message] text = "`#{klass}`: #{message}" top = exception[:stack].first if top text += " at `#{top[:label]}` in #{top[:path]}:#{top[:line]}" end texts << text end Faraday.new(:url => @url).post do |req| req.headers['Content-Type'] = 'application/json' req.body = JSON.dump({ username: 'Nightwatch', text: texts.join("\n") }) end end end end
require 'faraday' require 'json' - - OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE module Nightwatch class SlackLogger def initialize(opts = {}) @url = opts[:url] if !@url raise Error, 'Webhook URL is required.' end end def log(records) texts = [] records.each do |record| exception = record[:exception] klass = exception[:class] message = exception[:message] - text = "#{klass}: #{message}" + text = "`#{klass}`: #{message}" ? + + top = exception[:stack].first if top - text += " at #{top[:label]} in #{top[:path]}:#{top[:line]}" + text += " at `#{top[:label]}` in #{top[:path]}:#{top[:line]}" ? + + end texts << text end Faraday.new(:url => @url).post do |req| req.headers['Content-Type'] = 'application/json' req.body = JSON.dump({ username: 'Nightwatch', text: texts.join("\n") }) end end end end
6
0.15
2
4
f607b366bf83b56294a67725ba07512071a5b111
.travis.yml
.travis.yml
language: php php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm # run build against php 7.0 but allow them to fail # http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail matrix: fast_finish: true allow_failures: - php: 7.0 before_script: - composer update script: phpunit
language: php sudo: false php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm # run build against php 7.0 but allow them to fail # http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail matrix: fast_finish: true allow_failures: - php: 7.0 before_script: - composer update script: phpunit
Switch to the docker-based infrastructure on Travis
Switch to the docker-based infrastructure on Travis
YAML
mit
cmpayments/jsonlint
yaml
## Code Before: language: php php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm # run build against php 7.0 but allow them to fail # http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail matrix: fast_finish: true allow_failures: - php: 7.0 before_script: - composer update script: phpunit ## Instruction: Switch to the docker-based infrastructure on Travis ## Code After: language: php sudo: false php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm # run build against php 7.0 but allow them to fail # http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail matrix: fast_finish: true allow_failures: - php: 7.0 before_script: - composer update script: phpunit
language: php + + sudo: false php: - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - hhvm # run build against php 7.0 but allow them to fail # http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail matrix: fast_finish: true allow_failures: - php: 7.0 before_script: - composer update script: phpunit
2
0.095238
2
0
f535468595a036df443c95a84e9a182fd572115c
reverse-words.js
reverse-words.js
// Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ function reverseWords(str){ var strArr = str.split(" "); var emptyWordArr = []; var emptyStrArr = []; var index = 0; strArr.forEach(function(word){ word = word.split(''); index = (word.length); while (index > -1){ emptyWordArr.push(word[index]) index--; } emptyStrArr.push(emptyWordArr.join('')); emptyWordArr = []; }); return emptyStrArr.join(' '); }
// Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ // This was my initial response, and it works fine! But could be slightly refactored for cleaner code. // function reverseWords(str){ // var strArr = str.split(" "); // var emptyWordArr = []; // var emptyStrArr = []; // var index = 0; // strArr.forEach(function(word){ // word = word.split(''); // index = (word.length); // while (index > -1){ // emptyWordArr.push(word[index]) // index--; // } // emptyStrArr.push(emptyWordArr.join('')); // emptyWordArr = []; // }); // return emptyStrArr.join(' '); // }
Comment out initial response to include refactored answer
Comment out initial response to include refactored answer
JavaScript
mit
benjaminhyw/javascript_algorithms
javascript
## Code Before: // Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ function reverseWords(str){ var strArr = str.split(" "); var emptyWordArr = []; var emptyStrArr = []; var index = 0; strArr.forEach(function(word){ word = word.split(''); index = (word.length); while (index > -1){ emptyWordArr.push(word[index]) index--; } emptyStrArr.push(emptyWordArr.join('')); emptyWordArr = []; }); return emptyStrArr.join(' '); } ## Instruction: Comment out initial response to include refactored answer ## Code After: // Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ // This was my initial response, and it works fine! But could be slightly refactored for cleaner code. // function reverseWords(str){ // var strArr = str.split(" "); // var emptyWordArr = []; // var emptyStrArr = []; // var index = 0; // strArr.forEach(function(word){ // word = word.split(''); // index = (word.length); // while (index > -1){ // emptyWordArr.push(word[index]) // index--; // } // emptyStrArr.push(emptyWordArr.join('')); // emptyWordArr = []; // }); // return emptyStrArr.join(' '); // }
// Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ + // This was my initial response, and it works fine! But could be slightly refactored for cleaner code. - function reverseWords(str){ - var strArr = str.split(" "); - var emptyWordArr = []; - var emptyStrArr = []; - var index = 0; + // function reverseWords(str){ + // var strArr = str.split(" "); + // var emptyWordArr = []; + // var emptyStrArr = []; + // var index = 0; + - strArr.forEach(function(word){ + // strArr.forEach(function(word){ ? +++ - word = word.split(''); + // word = word.split(''); ? +++ - index = (word.length); + // index = (word.length); ? +++ - while (index > -1){ + // while (index > -1){ ? +++ - emptyWordArr.push(word[index]) + // emptyWordArr.push(word[index]) ? +++ - index--; + // index--; ? +++ - } + // } ? +++ - emptyStrArr.push(emptyWordArr.join('')); + // emptyStrArr.push(emptyWordArr.join('')); ? +++ - emptyWordArr = []; + // emptyWordArr = []; ? +++ - }); + // }); ? +++ - return emptyStrArr.join(' '); + // return emptyStrArr.join(' '); ? +++ - } + // } + +
38
0.926829
21
17
e4bf7d3f5d093a71562799af5e15081b8a0c812c
setup.py
setup.py
from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2", "pyjwt"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2 == 0.7.1", "pyjwt==0.1.2"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
Add explicit versions for dependencies
Add explicit versions for dependencies
Python
mit
clearcare/twilio-python,Stackdriver/twilio-python,Mobii/twilio-python,supermanheng21/twilio-python,cinemapub/bright-response,cinemapub/bright-response,bcorwin/twilio-python,tysonholub/twilio-python,Stackdriver/twilio-python,twilio/twilio-python,Rosy-S/twilio-python,johannakate/twilio-python,YeelerG/twilio-python,RobSpectre/twilio-python
python
## Code Before: from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2", "pyjwt"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ ) ## Instruction: Add explicit versions for dependencies ## Code After: from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2 == 0.7.1", "pyjwt==0.1.2"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], - install_requires = ["httplib2", "pyjwt"], + install_requires = ["httplib2 == 0.7.1", "pyjwt==0.1.2"], ? +++++++++ +++++++ packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
2
0.055556
1
1
e4e030244b043182ca9b9dabaff47036153a3099
src/app/core/services/socket.service.ts
src/app/core/services/socket.service.ts
import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); this.sendMessage('message', {message: 'hello'}); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(this.socket) { console.log('SS >>>> ', this.socket.connected); this.socket.removeAllListeners(); this.socket.disconnect(); } if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
Add experimental/temporal control to avoid create new connections
Add experimental/temporal control to avoid create new connections
TypeScript
mit
semagarcia/javascript-kata-player,semagarcia/javascript-kata-player,semagarcia/javascript-kata-player
typescript
## Code Before: import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); this.sendMessage('message', {message: 'hello'}); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } } ## Instruction: Add experimental/temporal control to avoid create new connections ## Code After: import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { if(this.socket) { console.log('SS >>>> ', this.socket.connected); this.socket.removeAllListeners(); this.socket.disconnect(); } if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
import { Injectable } from '@angular/core'; import { environment } from './../../../environments/environment'; import { Observable } from 'rxjs'; import * as io from 'socket.io-client'; @Injectable() export class SocketService { url: string; socket: SocketIOClient.Socket; constructor() { + if(this.socket) { + console.log('SS >>>> ', this.socket.connected); + this.socket.removeAllListeners(); + this.socket.disconnect(); + } if(environment.production) { this.socket = io.connect({ transports: ['websocket'], upgrade: false }); } else { this.url = `${window.location.protocol}//${window.location.hostname}:3000`; this.socket = io.connect(this.url, { transports: ['websocket'], upgrade: false }); - this.sendMessage('message', {message: 'hello'}); } } getSocketId(): string { return (this.socket) ? this.socket.id : ''; } connectToStreaming(socketEventName) { return Observable.fromEvent(this.socket, socketEventName).share(); } sendMessage(type: string, payload: object) { this.socket.emit(type, payload); } }
6
0.176471
5
1
1b9b60839910e38c74bac6e7edf1b4324bd1fb54
lib/context/shared_behavior.rb
lib/context/shared_behavior.rb
module Context class SharedBehavior < Module def self.create_from_behavior(beh) mod = self.new mod.behavior = beh mod end def behavior=(beh) @behavior = beh end def behavior @behavior end def included(arg) @behavior.call end end end class Test::Unit::TestCase class << self def shared(name, &block) case name.class.name when "String" name = name.to_module_name when "Symbol" name = name.to_s.to_module_name else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group" end Object.const_set(name, Context::SharedBehavior.create_from_behavior(block)) end %w(shared_behavior share_as share_behavior_as shared_examples_for).each {|m| alias_method m, :shared} def use(shared_name) case shared_name.class.name when "Context::SharedBehavior", "Module" include shared_name when "String" include Object.const_get(shared_name.to_module_name) when "Symbol" include Object.const_get(shared_name.to_s.to_module_name) else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group or the module name" end end %w(uses it_should_behave_like behaves_like uses_examples_from).each {|m| alias_method m, :use} end end
module Context class SharedBehavior < Module def self.create_from_behavior(beh) mod = self.new mod._behavior = beh mod end def _behavior=(beh) @_behavior = beh end def included(arg) @_behavior.call end end end class Test::Unit::TestCase class << self def shared(name, &block) case name.class.name when "String" name = name.to_module_name when "Symbol" name = name.to_s.to_module_name else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group" end Object.const_set(name, Context::SharedBehavior.create_from_behavior(block)) end %w(shared_behavior share_as share_behavior_as shared_examples_for).each {|m| alias_method m, :shared} def use(shared_name) case shared_name.class.name when "Context::SharedBehavior", "Module" include shared_name when "String" include Object.const_get(shared_name.to_module_name) when "Symbol" include Object.const_get(shared_name.to_s.to_module_name) else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group or the module name" end end %w(uses it_should_behave_like behaves_like uses_examples_from).each {|m| alias_method m, :use} end end
Hide shared behavior a little better. Name clashes ftl.
Hide shared behavior a little better. Name clashes ftl.
Ruby
mit
jm/context
ruby
## Code Before: module Context class SharedBehavior < Module def self.create_from_behavior(beh) mod = self.new mod.behavior = beh mod end def behavior=(beh) @behavior = beh end def behavior @behavior end def included(arg) @behavior.call end end end class Test::Unit::TestCase class << self def shared(name, &block) case name.class.name when "String" name = name.to_module_name when "Symbol" name = name.to_s.to_module_name else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group" end Object.const_set(name, Context::SharedBehavior.create_from_behavior(block)) end %w(shared_behavior share_as share_behavior_as shared_examples_for).each {|m| alias_method m, :shared} def use(shared_name) case shared_name.class.name when "Context::SharedBehavior", "Module" include shared_name when "String" include Object.const_get(shared_name.to_module_name) when "Symbol" include Object.const_get(shared_name.to_s.to_module_name) else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group or the module name" end end %w(uses it_should_behave_like behaves_like uses_examples_from).each {|m| alias_method m, :use} end end ## Instruction: Hide shared behavior a little better. Name clashes ftl. ## Code After: module Context class SharedBehavior < Module def self.create_from_behavior(beh) mod = self.new mod._behavior = beh mod end def _behavior=(beh) @_behavior = beh end def included(arg) @_behavior.call end end end class Test::Unit::TestCase class << self def shared(name, &block) case name.class.name when "String" name = name.to_module_name when "Symbol" name = name.to_s.to_module_name else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group" end Object.const_set(name, Context::SharedBehavior.create_from_behavior(block)) end %w(shared_behavior share_as share_behavior_as shared_examples_for).each {|m| alias_method m, :shared} def use(shared_name) case shared_name.class.name when "Context::SharedBehavior", "Module" include shared_name when "String" include Object.const_get(shared_name.to_module_name) when "Symbol" include Object.const_get(shared_name.to_s.to_module_name) else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group or the module name" end end %w(uses it_should_behave_like behaves_like uses_examples_from).each {|m| alias_method m, :use} end end
module Context class SharedBehavior < Module def self.create_from_behavior(beh) mod = self.new - mod.behavior = beh + mod._behavior = beh ? + + mod end - def behavior=(beh) + def _behavior=(beh) ? + - @behavior = beh + @_behavior = beh ? + - end - - def behavior - @behavior end def included(arg) - @behavior.call + @_behavior.call ? + end end end class Test::Unit::TestCase class << self def shared(name, &block) case name.class.name when "String" name = name.to_module_name when "Symbol" name = name.to_s.to_module_name else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group" end Object.const_set(name, Context::SharedBehavior.create_from_behavior(block)) end %w(shared_behavior share_as share_behavior_as shared_examples_for).each {|m| alias_method m, :shared} def use(shared_name) case shared_name.class.name when "Context::SharedBehavior", "Module" include shared_name when "String" include Object.const_get(shared_name.to_module_name) when "Symbol" include Object.const_get(shared_name.to_s.to_module_name) else raise ArgumentError, "Provide a String or Symbol as the name of the shared behavior group or the module name" end end %w(uses it_should_behave_like behaves_like uses_examples_from).each {|m| alias_method m, :use} end end
13
0.236364
5
8
9631e5a03b1e9e271bd25f264311b933bb43a2d0
manifest-unversioned.yml
manifest-unversioned.yml
--- timeout: 180 instances: 1 memory: 512M env: SPRING_PROFILES_ACTIVE: cloud JAVA_OPTS: -Djava.security.egd=file:///dev/urandom JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }}]' applications: - name: portfolio random-route: true path: libs/portfolio-${version}.jar services: [ traderdb, discovery-service, circuit-breaker-dashboard, config-server ]
--- timeout: 180 instances: 1 memory: 512M env: SPRING_PROFILES_ACTIVE: cloud JAVA_OPTS: -Djava.security.egd=file:///dev/urandom JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }, memory_heuristics: {metaspace: 10, heap: 65, native: 20, permgen: 10, stack: 5} }]' applications: - name: portfolio random-route: true path: libs/portfolio-${version}.jar services: [ traderdb, discovery-service, circuit-breaker-dashboard, config-server ]
Fix OOM at container level issue
Fix OOM at container level issue
YAML
apache-2.0
pivotal-bank/portfolio-service,pivotal-bank/portfolio-service
yaml
## Code Before: --- timeout: 180 instances: 1 memory: 512M env: SPRING_PROFILES_ACTIVE: cloud JAVA_OPTS: -Djava.security.egd=file:///dev/urandom JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }}]' applications: - name: portfolio random-route: true path: libs/portfolio-${version}.jar services: [ traderdb, discovery-service, circuit-breaker-dashboard, config-server ] ## Instruction: Fix OOM at container level issue ## Code After: --- timeout: 180 instances: 1 memory: 512M env: SPRING_PROFILES_ACTIVE: cloud JAVA_OPTS: -Djava.security.egd=file:///dev/urandom JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }, memory_heuristics: {metaspace: 10, heap: 65, native: 20, permgen: 10, stack: 5} }]' applications: - name: portfolio random-route: true path: libs/portfolio-${version}.jar services: [ traderdb, discovery-service, circuit-breaker-dashboard, config-server ]
--- timeout: 180 instances: 1 memory: 512M env: SPRING_PROFILES_ACTIVE: cloud JAVA_OPTS: -Djava.security.egd=file:///dev/urandom - JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }}]' + JBP_CONFIG_OPEN_JDK_JRE: '[memory_calculator: { memory_sizes: { metaspace: 100m }, memory_heuristics: {metaspace: 10, heap: 65, native: 20, permgen: 10, stack: 5} }]' applications: - name: portfolio random-route: true path: libs/portfolio-${version}.jar services: [ traderdb, discovery-service, circuit-breaker-dashboard, config-server ]
2
0.153846
1
1
44316f4ac6ddf51fc3a4d7377a81ea06a7697726
rap-battle/app/views/songs/index.html.erb
rap-battle/app/views/songs/index.html.erb
<h1>Songs...To Be Continued.</h1> <%= form_tag("/", method: "get") do %> <%= label_tag("Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <% if @song %> <%= @song.title %> <% end %>
<h1>Songs...To Be Continued.</h1> <%= form_tag("/", method: "get") do %> <%= label_tag("Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <% if @song %> <%= @song.primary_artist.name %> <%= image_tag(@song.primary_artist.image_url, :alt => @song.primary_artist.name) %> <%= @song.title %> <% end %>
Add image and artist name
Add image and artist name
HTML+ERB
mit
aftaberski/rap-battle,aftaberski/rap-battle,aftaberski/rap-battle
html+erb
## Code Before: <h1>Songs...To Be Continued.</h1> <%= form_tag("/", method: "get") do %> <%= label_tag("Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <% if @song %> <%= @song.title %> <% end %> ## Instruction: Add image and artist name ## Code After: <h1>Songs...To Be Continued.</h1> <%= form_tag("/", method: "get") do %> <%= label_tag("Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <% if @song %> <%= @song.primary_artist.name %> <%= image_tag(@song.primary_artist.image_url, :alt => @song.primary_artist.name) %> <%= @song.title %> <% end %>
<h1>Songs...To Be Continued.</h1> <%= form_tag("/", method: "get") do %> <%= label_tag("Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <% if @song %> + <%= @song.primary_artist.name %> + <%= image_tag(@song.primary_artist.image_url, :alt => @song.primary_artist.name) %> <%= @song.title %> <% end %>
2
0.181818
2
0
2611c33df7ae567f98c7d7c44cfb578f7a1f9d52
.travis.yml
.travis.yml
language: node_js node_js: - "0.6" - "0.8" - "0.9" - "0.10" - "0.11" install: - sudo apt-get install cmake script: - cmake . - ctest -V --output-on-failure . notifications: email: on_success: change on_failure: always
language: node_js node_js: - "0.6" - "0.8" - "0.9" - "0.10" - "0.11" install: - sudo apt-get install cmake script: - npm install . - cmake . - ctest -V --output-on-failure . notifications: email: on_success: change on_failure: always
Use npm install in Travis config
Use npm install in Travis config
YAML
mit
editorconfig/editorconfig-core-js,jedmao/editorconfig-core-js,editorconfig/editorconfig-core-js,seka/editorconfig-core-js,slang800/editorconfig-core-js
yaml
## Code Before: language: node_js node_js: - "0.6" - "0.8" - "0.9" - "0.10" - "0.11" install: - sudo apt-get install cmake script: - cmake . - ctest -V --output-on-failure . notifications: email: on_success: change on_failure: always ## Instruction: Use npm install in Travis config ## Code After: language: node_js node_js: - "0.6" - "0.8" - "0.9" - "0.10" - "0.11" install: - sudo apt-get install cmake script: - npm install . - cmake . - ctest -V --output-on-failure . notifications: email: on_success: change on_failure: always
language: node_js node_js: - "0.6" - "0.8" - "0.9" - "0.10" - "0.11" install: - sudo apt-get install cmake script: + - npm install . - cmake . - ctest -V --output-on-failure . notifications: email: on_success: change on_failure: always
1
0.05
1
0
e3da80c8c57eaba6074c0543f5576e178eeffecb
vim/startup/functions/directories.vim
vim/startup/functions/directories.vim
function! Cdfile() cd %:h pwd endfunction " cd to the root of the current file's git directory function! Cdroot() cd %:h exec "cd " . Trim(system("git rev-parse --show-toplevel")) pwd endfunction
function! Cdfile() if expand('%') != '' cd %:h else echom "Not currently in a file." endif endfunction " cd to the root of the current file's git directory function! Cdroot() call Cdfile() exec "cd " . Trim(system("git rev-parse --show-toplevel")) echom expand('.') endfunction
Make Cdf and Cdr no-ops when not in a file
Make Cdf and Cdr no-ops when not in a file
VimL
mit
yarko3/dotfiles,yarko3/dotfiles
viml
## Code Before: function! Cdfile() cd %:h pwd endfunction " cd to the root of the current file's git directory function! Cdroot() cd %:h exec "cd " . Trim(system("git rev-parse --show-toplevel")) pwd endfunction ## Instruction: Make Cdf and Cdr no-ops when not in a file ## Code After: function! Cdfile() if expand('%') != '' cd %:h else echom "Not currently in a file." endif endfunction " cd to the root of the current file's git directory function! Cdroot() call Cdfile() exec "cd " . Trim(system("git rev-parse --show-toplevel")) echom expand('.') endfunction
function! Cdfile() + if expand('%') != '' - cd %:h + cd %:h ? ++++ - pwd + else + echom "Not currently in a file." + endif endfunction " cd to the root of the current file's git directory function! Cdroot() - cd %:h + call Cdfile() exec "cd " . Trim(system("git rev-parse --show-toplevel")) - pwd + echom expand('.') endfunction
11
1
7
4
3096988c7e9fe905646380c1e732bd8f5301fa67
institutions/institutions/templates/index.html
institutions/institutions/templates/index.html
{% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> {% leaflet_map "map" callback="main_map_init"%} <script type="text/javascript"> function main_map_init(map, options) { //Use Leaflet API here. var tracts_json_url = '{% url "tractsgeojson"%}?state_fips=17&county_fips=031'; console.log(tracts_json_url); $.getJSON(tracts_json_url, function(data) { var lat = data.features[0].properties.intptlat; var lon = data.features[0].properties.intptlon; map.panTo(new L.LatLng(lat, lon)); L.geoJson(data).addTo(map); }); } </script> </body> </html>
{% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> {% leaflet_map "map" callback="main_map_init"%} <script type="text/javascript"> function main_map_init(map, options) { //Use Leaflet API here. var tracts_json_url = '{% url "tractsgeojson"%}?state_fips=17&county_fips=031'; console.log(tracts_json_url); $.getJSON(tracts_json_url, function(data) { var lat = data.features[0].properties.intptlat; var lon = data.features[0].properties.intptlon; map.setView([lat, lon], 12); L.geoJson(data).addTo(map); }); } </script> </body> </html>
Use setView instead of panTo
Use setView instead of panTo
HTML
cc0-1.0
mehtadev17/mapusaurus,mehtadev17/mapusaurus,mehtadev17/mapusaurus
html
## Code Before: {% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> {% leaflet_map "map" callback="main_map_init"%} <script type="text/javascript"> function main_map_init(map, options) { //Use Leaflet API here. var tracts_json_url = '{% url "tractsgeojson"%}?state_fips=17&county_fips=031'; console.log(tracts_json_url); $.getJSON(tracts_json_url, function(data) { var lat = data.features[0].properties.intptlat; var lon = data.features[0].properties.intptlon; map.panTo(new L.LatLng(lat, lon)); L.geoJson(data).addTo(map); }); } </script> </body> </html> ## Instruction: Use setView instead of panTo ## Code After: {% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> {% leaflet_map "map" callback="main_map_init"%} <script type="text/javascript"> function main_map_init(map, options) { //Use Leaflet API here. var tracts_json_url = '{% url "tractsgeojson"%}?state_fips=17&county_fips=031'; console.log(tracts_json_url); $.getJSON(tracts_json_url, function(data) { var lat = data.features[0].properties.intptlat; var lon = data.features[0].properties.intptlon; map.setView([lat, lon], 12); L.geoJson(data).addTo(map); }); } </script> </body> </html>
{% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> {% leaflet_map "map" callback="main_map_init"%} <script type="text/javascript"> function main_map_init(map, options) { //Use Leaflet API here. var tracts_json_url = '{% url "tractsgeojson"%}?state_fips=17&county_fips=031'; console.log(tracts_json_url); $.getJSON(tracts_json_url, function(data) { var lat = data.features[0].properties.intptlat; var lon = data.features[0].properties.intptlon; - map.panTo(new L.LatLng(lat, lon)); + map.setView([lat, lon], 12); L.geoJson(data).addTo(map); }); } </script> </body> </html>
2
0.071429
1
1
ba262668d837c92cd6099147ad9e49540e83ed68
simple-dom-helper.js
simple-dom-helper.js
"use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.setAttributes( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
"use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.bulkEdit( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
Change create so it uses bulk edit, insteadt of just setAttributes
Change create so it uses bulk edit, insteadt of just setAttributes
JavaScript
mit
essenmitsosse/simple-dom-helper
javascript
## Code Before: "use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.setAttributes( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName }; ## Instruction: Change create so it uses bulk edit, insteadt of just setAttributes ## Code After: "use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.bulkEdit( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
"use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); - $element.setAttributes( args ); + $element.bulkEdit( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
2
0.039216
1
1
75486c41bd648e63f1baf118000300cb7dee164b
ovirt-guest-agent/setup.py
ovirt-guest-agent/setup.py
from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.package_version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
Add explicit package version to the oVirt GA executable
Add explicit package version to the oVirt GA executable We really need to track 2 different versions in case of oVirt GA: - the version of the oVirt GA package itself - RH(E)V specific version of the oVirt GA package This patch adds setting of the package_version. Change-Id: I2dea656facbf2aa33a733316136e0e4d1b8d4744 Signed-off-by: Lev Veyde <32edd3ccb8e9d69e90ee9ce8dbc368c1f61bdf7b@redhat.com>
Python
apache-2.0
oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent
python
## Code Before: from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None) ## Instruction: Add explicit package version to the oVirt GA executable We really need to track 2 different versions in case of oVirt GA: - the version of the oVirt GA package itself - RH(E)V specific version of the oVirt GA package This patch adds setting of the package_version. Change-Id: I2dea656facbf2aa33a733316136e0e4d1b8d4744 Signed-off-by: Lev Veyde <32edd3ccb8e9d69e90ee9ce8dbc368c1f61bdf7b@redhat.com> ## Code After: from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.package_version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" + self.package_version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
1
0.029412
1
0
24d7d5a14667db9b965defc552b304b0066d4572
spec/web/views/contributors/show_spec.rb
spec/web/views/contributors/show_spec.rb
require_relative '../../../../apps/web/views/contributors/show' RSpec.describe Web::Views::Contributors::Show do let(:exposures) { Hash[foo: 'bar'] } let(:template) { Hanami::View::Template.new('apps/web/templates/contributors/show.html.slim') } let(:view) { described_class.new(template, exposures) } let(:rendered) { view.render } describe '#project_name' do context 'when url contain project' do let(:commit) { Commit.new(url: 'github.com/hanami/hanami/') } it { expect(view.project_name(commit)).to eq 'hanami' } end context 'when url not contain project' do let(:commit) { Commit.new(url: '') } it { expect(view.project_name(commit)).to eq nil } end end describe 'navbar link css' do it { expect(view.all_time_page_class).to eq nil } it { expect(view.today_page_class).to eq nil } it { expect(view.this_week_page_class).to eq nil } it { expect(view.this_month_page_class).to eq nil } it { expect(view.this_year_page_class).to eq nil } it { expect(view.faq_page_class).to eq nil } end end
require_relative '../../../../apps/web/views/contributors/show' RSpec.describe Web::Views::Contributors::Show do let(:contributor) { Contributor.new(github: 'antondavydov') } let(:exposures) { Hash[contributor: contributor, commits: []] } let(:template) { Hanami::View::Template.new('apps/web/templates/contributors/show.html.slim') } let(:view) { described_class.new(template, exposures) } let(:rendered) { view.render } describe '#project_name' do context 'when url contain project' do let(:commit) { Commit.new(url: 'github.com/hanami/hanami/') } it { expect(view.project_name(commit)).to eq 'hanami' } end context 'when url not contain project' do let(:commit) { Commit.new(url: '') } it { expect(view.project_name(commit)).to eq nil } end end describe '#title' do it 'returns title' do expect(view.title).to eq('Commits for antondavydov') end end describe 'navbar link css' do it { expect(view.all_time_page_class).to eq nil } it { expect(view.today_page_class).to eq nil } it { expect(view.this_week_page_class).to eq nil } it { expect(view.this_month_page_class).to eq nil } it { expect(view.this_year_page_class).to eq nil } it { expect(view.faq_page_class).to eq nil } end end
Add test for title method in contributors show view
Add test for title method in contributors show view
Ruby
mit
hanami/contributors,hanami/contributors
ruby
## Code Before: require_relative '../../../../apps/web/views/contributors/show' RSpec.describe Web::Views::Contributors::Show do let(:exposures) { Hash[foo: 'bar'] } let(:template) { Hanami::View::Template.new('apps/web/templates/contributors/show.html.slim') } let(:view) { described_class.new(template, exposures) } let(:rendered) { view.render } describe '#project_name' do context 'when url contain project' do let(:commit) { Commit.new(url: 'github.com/hanami/hanami/') } it { expect(view.project_name(commit)).to eq 'hanami' } end context 'when url not contain project' do let(:commit) { Commit.new(url: '') } it { expect(view.project_name(commit)).to eq nil } end end describe 'navbar link css' do it { expect(view.all_time_page_class).to eq nil } it { expect(view.today_page_class).to eq nil } it { expect(view.this_week_page_class).to eq nil } it { expect(view.this_month_page_class).to eq nil } it { expect(view.this_year_page_class).to eq nil } it { expect(view.faq_page_class).to eq nil } end end ## Instruction: Add test for title method in contributors show view ## Code After: require_relative '../../../../apps/web/views/contributors/show' RSpec.describe Web::Views::Contributors::Show do let(:contributor) { Contributor.new(github: 'antondavydov') } let(:exposures) { Hash[contributor: contributor, commits: []] } let(:template) { Hanami::View::Template.new('apps/web/templates/contributors/show.html.slim') } let(:view) { described_class.new(template, exposures) } let(:rendered) { view.render } describe '#project_name' do context 'when url contain project' do let(:commit) { Commit.new(url: 'github.com/hanami/hanami/') } it { expect(view.project_name(commit)).to eq 'hanami' } end context 'when url not contain project' do let(:commit) { Commit.new(url: '') } it { expect(view.project_name(commit)).to eq nil } end end describe '#title' do it 'returns title' do expect(view.title).to eq('Commits for antondavydov') end end describe 'navbar link css' do it { expect(view.all_time_page_class).to eq nil } it { expect(view.today_page_class).to eq nil } it { expect(view.this_week_page_class).to eq nil } it { expect(view.this_month_page_class).to eq nil } it { expect(view.this_year_page_class).to eq nil } it { expect(view.faq_page_class).to eq nil } end end
require_relative '../../../../apps/web/views/contributors/show' RSpec.describe Web::Views::Contributors::Show do - let(:exposures) { Hash[foo: 'bar'] } + let(:contributor) { Contributor.new(github: 'antondavydov') } + let(:exposures) { Hash[contributor: contributor, commits: []] } let(:template) { Hanami::View::Template.new('apps/web/templates/contributors/show.html.slim') } let(:view) { described_class.new(template, exposures) } let(:rendered) { view.render } describe '#project_name' do context 'when url contain project' do let(:commit) { Commit.new(url: 'github.com/hanami/hanami/') } it { expect(view.project_name(commit)).to eq 'hanami' } end context 'when url not contain project' do let(:commit) { Commit.new(url: '') } it { expect(view.project_name(commit)).to eq nil } end end + describe '#title' do + it 'returns title' do + expect(view.title).to eq('Commits for antondavydov') + end + end + describe 'navbar link css' do it { expect(view.all_time_page_class).to eq nil } it { expect(view.today_page_class).to eq nil } it { expect(view.this_week_page_class).to eq nil } it { expect(view.this_month_page_class).to eq nil } it { expect(view.this_year_page_class).to eq nil } it { expect(view.faq_page_class).to eq nil } end end
9
0.290323
8
1
dfea1dd5fff99908f2075ee405681836af8d0011
saltcloud/deploy/Ubuntu.sh
saltcloud/deploy/Ubuntu.sh
mkdir -p /etc/salt/pki echo '{{ vm['priv_key'] }}' > /etc/salt/pki/minion.pem echo '{{ vm['pub_key'] }}' > /etc/salt/pki/minion.pub echo "{{ minion }}" > /etc/salt/minion apt-get update apt-get install -y python-software-properties echo | add-apt-repository ppa:saltstack/salt apt-get update apt-get install -y salt-minion
mkdir -p /etc/salt/pki echo '{{ vm['priv_key'] }}' > /etc/salt/pki/minion.pem echo '{{ vm['pub_key'] }}' > /etc/salt/pki/minion.pub echo "{{ minion }}" > /etc/salt/minion apt-get update apt-get install -y python-software-properties echo | add-apt-repository ppa:saltstack/salt apt-get update apt-get install -y salt-minion service salt-minion start
Remove the pending key when we accept the key
Remove the pending key when we accept the key
Shell
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
shell
## Code Before: mkdir -p /etc/salt/pki echo '{{ vm['priv_key'] }}' > /etc/salt/pki/minion.pem echo '{{ vm['pub_key'] }}' > /etc/salt/pki/minion.pub echo "{{ minion }}" > /etc/salt/minion apt-get update apt-get install -y python-software-properties echo | add-apt-repository ppa:saltstack/salt apt-get update apt-get install -y salt-minion ## Instruction: Remove the pending key when we accept the key ## Code After: mkdir -p /etc/salt/pki echo '{{ vm['priv_key'] }}' > /etc/salt/pki/minion.pem echo '{{ vm['pub_key'] }}' > /etc/salt/pki/minion.pub echo "{{ minion }}" > /etc/salt/minion apt-get update apt-get install -y python-software-properties echo | add-apt-repository ppa:saltstack/salt apt-get update apt-get install -y salt-minion service salt-minion start
mkdir -p /etc/salt/pki echo '{{ vm['priv_key'] }}' > /etc/salt/pki/minion.pem echo '{{ vm['pub_key'] }}' > /etc/salt/pki/minion.pub echo "{{ minion }}" > /etc/salt/minion apt-get update apt-get install -y python-software-properties echo | add-apt-repository ppa:saltstack/salt apt-get update apt-get install -y salt-minion + service salt-minion start
1
0.090909
1
0
a39ac66e6ca6702ab0b20c9bfd72ed4307bcbcf3
lib/cryptoexchange/exchanges/vinex/services/market.rb
lib/cryptoexchange/exchanges/vinex/services/market.rb
module Cryptoexchange::Exchanges module Vinex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Vinex::Market::API_URL}/markets" end def adapt_all(output) output["data"].map do |ticker| target, base = ticker['symbol'].split("_") market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Vinex::Market::NAME ) adapt(ticker, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Vinex::Market::NAME ticker.last = NumericHelper.to_d(output['lastPrice']) ticker.high = NumericHelper.to_d(output['high24h']) ticker.low = NumericHelper.to_d(output['low24h']) ticker.volume = NumericHelper.to_d(output['volume']) ticker.change = NumericHelper.to_d(output['change24h']) ticker.timestamp = nil ticker.payload = output ticker end end end end end
module Cryptoexchange::Exchanges module Vinex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Vinex::Market::API_URL}/markets" end def adapt_all(output) output["data"].map do |ticker| target, base = ticker['symbol'].split("_") market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Vinex::Market::NAME ) adapt(ticker, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Vinex::Market::NAME ticker.last = NumericHelper.to_d(output['lastPrice']) ticker.high = NumericHelper.to_d(output['high24h']) ticker.low = NumericHelper.to_d(output['low24h']) ticker.volume = NumericHelper.divide(NumericHelper.to_d(output['volume']), ticker.last) ticker.change = NumericHelper.to_d(output['change24h']) ticker.timestamp = nil ticker.payload = output ticker end end end end end
Fix Vinex volume by divide
Fix Vinex volume by divide
Ruby
mit
coingecko/cryptoexchange,coingecko/cryptoexchange
ruby
## Code Before: module Cryptoexchange::Exchanges module Vinex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Vinex::Market::API_URL}/markets" end def adapt_all(output) output["data"].map do |ticker| target, base = ticker['symbol'].split("_") market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Vinex::Market::NAME ) adapt(ticker, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Vinex::Market::NAME ticker.last = NumericHelper.to_d(output['lastPrice']) ticker.high = NumericHelper.to_d(output['high24h']) ticker.low = NumericHelper.to_d(output['low24h']) ticker.volume = NumericHelper.to_d(output['volume']) ticker.change = NumericHelper.to_d(output['change24h']) ticker.timestamp = nil ticker.payload = output ticker end end end end end ## Instruction: Fix Vinex volume by divide ## Code After: module Cryptoexchange::Exchanges module Vinex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Vinex::Market::API_URL}/markets" end def adapt_all(output) output["data"].map do |ticker| target, base = ticker['symbol'].split("_") market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Vinex::Market::NAME ) adapt(ticker, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Vinex::Market::NAME ticker.last = NumericHelper.to_d(output['lastPrice']) ticker.high = NumericHelper.to_d(output['high24h']) ticker.low = NumericHelper.to_d(output['low24h']) ticker.volume = NumericHelper.divide(NumericHelper.to_d(output['volume']), ticker.last) ticker.change = NumericHelper.to_d(output['change24h']) ticker.timestamp = nil ticker.payload = output ticker end end end end end
module Cryptoexchange::Exchanges module Vinex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Vinex::Market::API_URL}/markets" end def adapt_all(output) output["data"].map do |ticker| target, base = ticker['symbol'].split("_") market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Vinex::Market::NAME ) adapt(ticker, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Vinex::Market::NAME ticker.last = NumericHelper.to_d(output['lastPrice']) ticker.high = NumericHelper.to_d(output['high24h']) ticker.low = NumericHelper.to_d(output['low24h']) - ticker.volume = NumericHelper.to_d(output['volume']) + ticker.volume = NumericHelper.divide(NumericHelper.to_d(output['volume']), ticker.last) ? +++++++++++++++++++++ ++++++++++++++ ticker.change = NumericHelper.to_d(output['change24h']) ticker.timestamp = nil ticker.payload = output ticker end end end end end
2
0.039216
1
1
d118d864564c6d0a838ba51a409115fc3a4ba9a4
spec/ruby-function_spec.rb
spec/ruby-function_spec.rb
require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end end
require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end it "returns an instance of Proc" do func = recursive { |this| this.call } func.kind_of?(Proc).must_equal true end end
Add test to enforce that 'recursive' returns a Proc
Add test to enforce that 'recursive' returns a Proc
Ruby
mit
seadowg/matilda-function
ruby
## Code Before: require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end end ## Instruction: Add test to enforce that 'recursive' returns a Proc ## Code After: require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end it "returns an instance of Proc" do func = recursive { |this| this.call } func.kind_of?(Proc).must_equal true end end
require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end + + it "returns an instance of Proc" do + func = recursive { |this| this.call } + func.kind_of?(Proc).must_equal true + end end
5
0.3125
5
0
c5f995035af29ff4ac8f7c60b9a7e58b18820672
README.md
README.md
Satan is a daemon execution platform for Go apps.
Satan is a daemon execution platform for Go apps. * What is a daemon execution platform? * What does it provide? * How does it work? * What is a daemon? * What is an actor/task/process? * General example * Consumer example * Message queues * Dashboard
Add doc theses to readme
Add doc theses to readme
Markdown
mit
localhots/satan,localhots/satan,localhots/satan,localhots/satan
markdown
## Code Before: Satan is a daemon execution platform for Go apps. ## Instruction: Add doc theses to readme ## Code After: Satan is a daemon execution platform for Go apps. * What is a daemon execution platform? * What does it provide? * How does it work? * What is a daemon? * What is an actor/task/process? * General example * Consumer example * Message queues * Dashboard
Satan is a daemon execution platform for Go apps. + + * What is a daemon execution platform? + * What does it provide? + * How does it work? + * What is a daemon? + * What is an actor/task/process? + * General example + * Consumer example + * Message queues + * Dashboard
10
5
10
0
42a265bad5fbd33d95f483432b20a271343e79a3
examples/typescript/basic/src/output/YesNoOutput.ts
examples/typescript/basic/src/output/YesNoOutput.ts
import { BaseOutput, Output } from '@jovotech/framework'; import { OutputTemplate } from '@jovotech/output'; @Output() export class YesNoOutput extends BaseOutput { /* |-------------------------------------------------------------------------- | Output Template |-------------------------------------------------------------------------- | | This structured output is later turned into a native response | Learn more here: www.jovo.tech/docs/output | */ build(): OutputTemplate | OutputTemplate[] { return { quickReplies: ['yes', 'no'], listen: true, }; } }
import { BaseOutput, Output, OutputTemplate } from '@jovotech/framework'; @Output() export class YesNoOutput extends BaseOutput { /* |-------------------------------------------------------------------------- | Output Template |-------------------------------------------------------------------------- | | This structured output is later turned into a native response | Learn more here: www.jovo.tech/docs/output | */ build(): OutputTemplate | OutputTemplate[] { return { quickReplies: ['yes', 'no'], listen: true, }; } }
Fix invalid import in example
:bug: Fix invalid import in example
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
typescript
## Code Before: import { BaseOutput, Output } from '@jovotech/framework'; import { OutputTemplate } from '@jovotech/output'; @Output() export class YesNoOutput extends BaseOutput { /* |-------------------------------------------------------------------------- | Output Template |-------------------------------------------------------------------------- | | This structured output is later turned into a native response | Learn more here: www.jovo.tech/docs/output | */ build(): OutputTemplate | OutputTemplate[] { return { quickReplies: ['yes', 'no'], listen: true, }; } } ## Instruction: :bug: Fix invalid import in example ## Code After: import { BaseOutput, Output, OutputTemplate } from '@jovotech/framework'; @Output() export class YesNoOutput extends BaseOutput { /* |-------------------------------------------------------------------------- | Output Template |-------------------------------------------------------------------------- | | This structured output is later turned into a native response | Learn more here: www.jovo.tech/docs/output | */ build(): OutputTemplate | OutputTemplate[] { return { quickReplies: ['yes', 'no'], listen: true, }; } }
- import { BaseOutput, Output } from '@jovotech/framework'; + import { BaseOutput, Output, OutputTemplate } from '@jovotech/framework'; ? ++++++++++++++++ - import { OutputTemplate } from '@jovotech/output'; @Output() export class YesNoOutput extends BaseOutput { /* |-------------------------------------------------------------------------- | Output Template |-------------------------------------------------------------------------- | | This structured output is later turned into a native response | Learn more here: www.jovo.tech/docs/output | */ build(): OutputTemplate | OutputTemplate[] { return { quickReplies: ['yes', 'no'], listen: true, }; } }
3
0.142857
1
2
bf090bd2905fabe3346d1771618b99fa86dc588c
.travis.yml
.travis.yml
sudo: false language: node_js #cache: # directories: # - node_modules notifications: email: false node_js: - "6" - "8" env: global: - CXX=g++-4.8 - TWITTER_BEARER_TOKEN=123456789 matrix: allow_failures: - node_js: "6" addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 code_climate: repo_token: ${CODECLIMATE_REPO_TOKEN} # before_script: # - npm install --global snyk # - snyk auth ${SNYK_TOKEN} script: - npm run build # - npm run security_check - npm run lint - npm run test
sudo: false language: node_js #cache: # directories: # - node_modules notifications: email: false services: - redis-server node_js: - "8" - "9" env: global: - CXX=g++-4.8 - TWITTER_BEARER_TOKEN=123456789 matrix: allow_failures: - node_js: "9" addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 code_climate: repo_token: ${CODECLIMATE_REPO_TOKEN} rethinkdb: '2.3.6' # before_script: # - npm install --global snyk # - snyk auth ${SNYK_TOKEN} script: - npm run build # - npm run security_check - npm run test - npm run lint
Add Redis and RethinkDB required services, move build to Node.js versions 8 and 9 rather than 6 and 8. Move linting step to after testing step so it's easier to see test results.
Add Redis and RethinkDB required services, move build to Node.js versions 8 and 9 rather than 6 and 8. Move linting step to after testing step so it's easier to see test results.
YAML
mit
ocean/higgins,ocean/higgins
yaml
## Code Before: sudo: false language: node_js #cache: # directories: # - node_modules notifications: email: false node_js: - "6" - "8" env: global: - CXX=g++-4.8 - TWITTER_BEARER_TOKEN=123456789 matrix: allow_failures: - node_js: "6" addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 code_climate: repo_token: ${CODECLIMATE_REPO_TOKEN} # before_script: # - npm install --global snyk # - snyk auth ${SNYK_TOKEN} script: - npm run build # - npm run security_check - npm run lint - npm run test ## Instruction: Add Redis and RethinkDB required services, move build to Node.js versions 8 and 9 rather than 6 and 8. Move linting step to after testing step so it's easier to see test results. ## Code After: sudo: false language: node_js #cache: # directories: # - node_modules notifications: email: false services: - redis-server node_js: - "8" - "9" env: global: - CXX=g++-4.8 - TWITTER_BEARER_TOKEN=123456789 matrix: allow_failures: - node_js: "9" addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 code_climate: repo_token: ${CODECLIMATE_REPO_TOKEN} rethinkdb: '2.3.6' # before_script: # - npm install --global snyk # - snyk auth ${SNYK_TOKEN} script: - npm run build # - npm run security_check - npm run test - npm run lint
sudo: false language: node_js #cache: # directories: # - node_modules notifications: email: false + services: + - redis-server + node_js: - - "6" - "8" + - "9" env: global: - CXX=g++-4.8 - TWITTER_BEARER_TOKEN=123456789 matrix: allow_failures: - - node_js: "6" ? ^ + - node_js: "9" ? ^ addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 code_climate: repo_token: ${CODECLIMATE_REPO_TOKEN} + rethinkdb: '2.3.6' # before_script: # - npm install --global snyk # - snyk auth ${SNYK_TOKEN} script: - npm run build # - npm run security_check + - npm run test - npm run lint - - npm run test
10
0.25
7
3
2575e2de77f3f4e11f06dbb6e573126c56a1d1f3
.travis.yml
.travis.yml
language: cpp cache: apt os: - osx - linux compiler: - gcc - clang before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo ./install_deps.sh; fi - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update && brew upgrade cmake boost && brew install protobuf; fi script: - ./make.sh matrix: allow_failures: - os: osx exclude: - compiler: gcc os: osx notifications: slack: secure: bewLb+C2yiKmLUh0o/vftey+tl0XrmgkPi38uO+zbZ1kXJw/ByweJNrumgO/EJ4GDodb4cLHIUFuk4fNpkSUeV1CBSql7sm2cgQ9pIoQcdeEcANOeUmdepYwRh2xTOjRCeQnh0FYUkeyrQpzFwk1f+yybZrppw6dKu677v8CB1w=
language: cpp cache: apt os: - linux compiler: - gcc - clang before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo ./install_deps.sh; fi script: - "./make.sh" notifications: slack: secure: biLc1upxAuvnKJCNtvhnor8tAiqnydBPFm4yL2mDOq6AULKDpaipcnRrEVBEGSR2/DnIpZ25tUZ5fkl/HYExSJfZ5cAGypUhT53ER257BmQbqOEE/WC2ZCkScgIOopgPE8spaD+5xMo4CLHbnKUJ6Hu/1PMtH91GI6M1upyXa70=
Remove automated OS X builds for now
Remove automated OS X builds for now
YAML
mit
terry2012/codereason,chubbymaggie/codereason,chubbymaggie/codereason,chubbymaggie/codereason,terry2012/codereason,trailofbits/codereason,terry2012/codereason,terry2012/codereason,terry2012/codereason,trailofbits/codereason,trailofbits/codereason,trailofbits/codereason,chubbymaggie/codereason,trailofbits/codereason,chubbymaggie/codereason
yaml
## Code Before: language: cpp cache: apt os: - osx - linux compiler: - gcc - clang before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo ./install_deps.sh; fi - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update && brew upgrade cmake boost && brew install protobuf; fi script: - ./make.sh matrix: allow_failures: - os: osx exclude: - compiler: gcc os: osx notifications: slack: secure: bewLb+C2yiKmLUh0o/vftey+tl0XrmgkPi38uO+zbZ1kXJw/ByweJNrumgO/EJ4GDodb4cLHIUFuk4fNpkSUeV1CBSql7sm2cgQ9pIoQcdeEcANOeUmdepYwRh2xTOjRCeQnh0FYUkeyrQpzFwk1f+yybZrppw6dKu677v8CB1w= ## Instruction: Remove automated OS X builds for now ## Code After: language: cpp cache: apt os: - linux compiler: - gcc - clang before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo ./install_deps.sh; fi script: - "./make.sh" notifications: slack: secure: biLc1upxAuvnKJCNtvhnor8tAiqnydBPFm4yL2mDOq6AULKDpaipcnRrEVBEGSR2/DnIpZ25tUZ5fkl/HYExSJfZ5cAGypUhT53ER257BmQbqOEE/WC2ZCkScgIOopgPE8spaD+5xMo4CLHbnKUJ6Hu/1PMtH91GI6M1upyXa70=
language: cpp cache: apt os: - - osx - linux compiler: - gcc - clang before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo ./install_deps.sh; fi - - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update && brew upgrade cmake boost && brew install protobuf; fi script: - - ./make.sh + - "./make.sh" ? + + - matrix: - allow_failures: - - os: osx - exclude: - - compiler: gcc - os: osx notifications: slack: - secure: bewLb+C2yiKmLUh0o/vftey+tl0XrmgkPi38uO+zbZ1kXJw/ByweJNrumgO/EJ4GDodb4cLHIUFuk4fNpkSUeV1CBSql7sm2cgQ9pIoQcdeEcANOeUmdepYwRh2xTOjRCeQnh0FYUkeyrQpzFwk1f+yybZrppw6dKu677v8CB1w= + secure: biLc1upxAuvnKJCNtvhnor8tAiqnydBPFm4yL2mDOq6AULKDpaipcnRrEVBEGSR2/DnIpZ25tUZ5fkl/HYExSJfZ5cAGypUhT53ER257BmQbqOEE/WC2ZCkScgIOopgPE8spaD+5xMo4CLHbnKUJ6Hu/1PMtH91GI6M1upyXa70=
12
0.545455
2
10
6362db1ac458850822d2ac55a388ec10391af7a8
circle.yml
circle.yml
machine: timezone: America/Sao_Paulo # Set the timezone node: version: 6.2.1 test: pre: - bundle exec rake db:migrate deployment: production: branch: master commands: - ./bin/deploy.sh feature: branch: /add-.*/ commands: - ./bin/deploy.sh
machine: timezone: America/Sao_Paulo # Set the timezone node: version: 6.2.1 deployment: production: branch: master commands: - ./bin/deploy.sh feature: branch: /add-.*/ commands: - ./bin/deploy.sh
Remove unused pre test command
Remove unused pre test command
YAML
agpl-3.0
nossas/bonde-client,nossas/bonde-client,nossas/bonde-client
yaml
## Code Before: machine: timezone: America/Sao_Paulo # Set the timezone node: version: 6.2.1 test: pre: - bundle exec rake db:migrate deployment: production: branch: master commands: - ./bin/deploy.sh feature: branch: /add-.*/ commands: - ./bin/deploy.sh ## Instruction: Remove unused pre test command ## Code After: machine: timezone: America/Sao_Paulo # Set the timezone node: version: 6.2.1 deployment: production: branch: master commands: - ./bin/deploy.sh feature: branch: /add-.*/ commands: - ./bin/deploy.sh
machine: timezone: America/Sao_Paulo # Set the timezone node: version: 6.2.1 - - test: - pre: - - bundle exec rake db:migrate deployment: production: branch: master commands: - ./bin/deploy.sh feature: branch: /add-.*/ commands: - ./bin/deploy.sh
4
0.210526
0
4
c6f348aaaf75d6cc200ac7ed974b2a979e78c693
test/test_models.rb
test/test_models.rb
ActiveRecord::Schema.define(:version => 0) do create_table :settings, :force => true do |t| t.string :key t.text :value t.timestamps end add_index :settings, [:key], :unique => true, :name => 'key_udx' end class Setting < ActiveRecord::Base def_druthers :quest, :favourite_colour, :things, :hashish, :change serialize :value, CustomSerialize def self.default_quest "to find the holy grail" end def self.default_things [1, 2, 3] end def validate_favourite_colour errors.add(:value, "invalid is invalid WERD") if value == "invalid" end class CustomSerialize def self.load(val) ActiveRecord::Coders::YAMLColumn.new.load(val) end def self.dump(val) val = 'bar' if val == 'foo' ActiveRecord::Coders::YAMLColumn.new.dump(val) end end end
ActiveRecord::Schema.define(:version => 0) do create_table :settings, :force => true do |t| t.string :key t.text :value t.timestamps end add_index :settings, [:key], :unique => true, :name => 'key_udx' end class Setting < ActiveRecord::Base def_druthers :quest, :favourite_colour, :things, :hashish, :change def self.default_quest "to find the holy grail" end def self.default_things [1, 2, 3] end def validate_favourite_colour errors.add(:value, "invalid is invalid WERD") if value == "invalid" end class CustomSerialize def self.load(val) ActiveRecord::Coders::YAMLColumn.new.load(val) end def self.dump(val) val = 'bar' if val == 'foo' ActiveRecord::Coders::YAMLColumn.new.dump(val) end end serialize :value, CustomSerialize end
Move serialize method so class id defined
Move serialize method so class id defined
Ruby
mit
mceachen/druthers
ruby
## Code Before: ActiveRecord::Schema.define(:version => 0) do create_table :settings, :force => true do |t| t.string :key t.text :value t.timestamps end add_index :settings, [:key], :unique => true, :name => 'key_udx' end class Setting < ActiveRecord::Base def_druthers :quest, :favourite_colour, :things, :hashish, :change serialize :value, CustomSerialize def self.default_quest "to find the holy grail" end def self.default_things [1, 2, 3] end def validate_favourite_colour errors.add(:value, "invalid is invalid WERD") if value == "invalid" end class CustomSerialize def self.load(val) ActiveRecord::Coders::YAMLColumn.new.load(val) end def self.dump(val) val = 'bar' if val == 'foo' ActiveRecord::Coders::YAMLColumn.new.dump(val) end end end ## Instruction: Move serialize method so class id defined ## Code After: ActiveRecord::Schema.define(:version => 0) do create_table :settings, :force => true do |t| t.string :key t.text :value t.timestamps end add_index :settings, [:key], :unique => true, :name => 'key_udx' end class Setting < ActiveRecord::Base def_druthers :quest, :favourite_colour, :things, :hashish, :change def self.default_quest "to find the holy grail" end def self.default_things [1, 2, 3] end def validate_favourite_colour errors.add(:value, "invalid is invalid WERD") if value == "invalid" end class CustomSerialize def self.load(val) ActiveRecord::Coders::YAMLColumn.new.load(val) end def self.dump(val) val = 'bar' if val == 'foo' ActiveRecord::Coders::YAMLColumn.new.dump(val) end end serialize :value, CustomSerialize end
ActiveRecord::Schema.define(:version => 0) do create_table :settings, :force => true do |t| t.string :key t.text :value t.timestamps end add_index :settings, [:key], :unique => true, :name => 'key_udx' end class Setting < ActiveRecord::Base def_druthers :quest, :favourite_colour, :things, :hashish, :change + - serialize :value, CustomSerialize - def self.default_quest "to find the holy grail" end def self.default_things [1, 2, 3] end def validate_favourite_colour errors.add(:value, "invalid is invalid WERD") if value == "invalid" end class CustomSerialize def self.load(val) ActiveRecord::Coders::YAMLColumn.new.load(val) end def self.dump(val) val = 'bar' if val == 'foo' ActiveRecord::Coders::YAMLColumn.new.dump(val) end end + serialize :value, CustomSerialize + end
5
0.135135
3
2
0daec28d0e49aaeef2b8d6e28691ff935c990407
README.md
README.md
Overview ======== Garage Envoy is a system that provides an abstract HTTP JSON API (and accompanying mobile application) for garage doors. This API and GUI can be used by a variety of personal electronic devices (e.g. smartphones, tablets, laptops) to get status on the garage door, plus trigger it to open/close on demand. It is designed to be plug and play with minimal configuration required. Hardware ======== - Raspberry Pi Model B - 4GB SD card - 5.25v DC power adapter - 5v two channel relay - magnetic sensors x 2 Software ======== Server ------ - Python 3 - waitress WSGI server - bottle WSGI microframework - jsonschema JSON validator - RPIO interface library for GPIO Client ------ - HTML / CSS - Angular / JavaScript - Ionic / Cordova
Overview ======== Garage Envoy is a system that provides an abstract HTTP JSON API (and accompanying mobile application) for garage doors. This API and GUI can be used by a variety of personal electronic devices (e.g. smartphones, tablets, laptops) to get status on the garage door, plus trigger it to open/close on demand. It is designed to be plug and play with minimal configuration required. Hardware ======== - Raspberry Pi Model B - 4GB SD card - 5.25v DC power adapter - 5v two channel relay - magnetic sensors x 2 - vibration sensor Software ======== Server ------ - Python 3 - waitress WSGI server - bottle WSGI microframework - jsonschema JSON validator - RPIO interface library for GPIO Client ------ - HTML / CSS - Angular / JavaScript - Ionic / Cordova
Add vibration sensor to readme file.
Add vibration sensor to readme file.
Markdown
mit
lordjabez/garage-envoy,lordjabez/garage-envoy
markdown
## Code Before: Overview ======== Garage Envoy is a system that provides an abstract HTTP JSON API (and accompanying mobile application) for garage doors. This API and GUI can be used by a variety of personal electronic devices (e.g. smartphones, tablets, laptops) to get status on the garage door, plus trigger it to open/close on demand. It is designed to be plug and play with minimal configuration required. Hardware ======== - Raspberry Pi Model B - 4GB SD card - 5.25v DC power adapter - 5v two channel relay - magnetic sensors x 2 Software ======== Server ------ - Python 3 - waitress WSGI server - bottle WSGI microframework - jsonschema JSON validator - RPIO interface library for GPIO Client ------ - HTML / CSS - Angular / JavaScript - Ionic / Cordova ## Instruction: Add vibration sensor to readme file. ## Code After: Overview ======== Garage Envoy is a system that provides an abstract HTTP JSON API (and accompanying mobile application) for garage doors. This API and GUI can be used by a variety of personal electronic devices (e.g. smartphones, tablets, laptops) to get status on the garage door, plus trigger it to open/close on demand. It is designed to be plug and play with minimal configuration required. Hardware ======== - Raspberry Pi Model B - 4GB SD card - 5.25v DC power adapter - 5v two channel relay - magnetic sensors x 2 - vibration sensor Software ======== Server ------ - Python 3 - waitress WSGI server - bottle WSGI microframework - jsonschema JSON validator - RPIO interface library for GPIO Client ------ - HTML / CSS - Angular / JavaScript - Ionic / Cordova
Overview ======== Garage Envoy is a system that provides an abstract HTTP JSON API (and accompanying mobile application) for garage doors. This API and GUI can be used by a variety of personal electronic devices (e.g. smartphones, tablets, laptops) to get status on the garage door, plus trigger it to open/close on demand. It is designed to be plug and play with minimal configuration required. Hardware ======== - Raspberry Pi Model B - 4GB SD card - 5.25v DC power adapter - 5v two channel relay - magnetic sensors x 2 + - vibration sensor Software ======== Server ------ - Python 3 - waitress WSGI server - bottle WSGI microframework - jsonschema JSON validator - RPIO interface library for GPIO Client ------ - HTML / CSS - Angular / JavaScript - Ionic / Cordova
1
0.03125
1
0
710145ea0e86a59ba7911e29c6d83560b4750b16
app/src/sass/liveeditor.scss
app/src/sass/liveeditor.scss
.bolt-editable { outline: 2px #bef092 solid; }
.bolt-editable { outline: 2px #bef092 solid; min-height: 10px; }
Add min-height to editable content
Add min-height to editable content
SCSS
mit
lenvanessen/bolt,Raistlfiren/bolt,nantunes/bolt,winiceo/bolt,richardhinkamp/bolt,CarsonF/bolt,hugin2005/bolt,marcin-piela/bolt,HonzaMikula/bolt,nantunes/bolt,bolt/bolt,joshuan/bolt,skript-cc/bolt,Eiskis/bolt-base,rossriley/bolt,Calinou/bolt,rarila/bolt,richardhinkamp/bolt,pygillier/bolt,hugin2005/bolt,GDmac/bolt,hannesl/bolt,electrolinux/bolt,cdowdy/bolt,one988/cm,bolt/bolt,CarsonF/bolt,skript-cc/bolt,Intendit/bolt,xeddmc/bolt,joshuan/bolt,nikgo/bolt,marcin-piela/bolt,lenvanessen/bolt,Intendit/bolt,bywatersolutions/reports-site,codesman/bolt,kendoctor/bolt,hugin2005/bolt,romulo1984/bolt,electrolinux/bolt,GDmac/bolt,Raistlfiren/bolt,CarsonF/bolt,rarila/bolt,bywatersolutions/reports-site,Intendit/bolt,marcin-piela/bolt,HonzaMikula/masivnipostele,rarila/bolt,CarsonF/bolt,tekjava/bolt,GawainLynch/bolt,codesman/bolt,codesman/bolt,nikgo/bolt,richardhinkamp/bolt,rossriley/bolt,HonzaMikula/masivnipostele,lenvanessen/bolt,Eiskis/bolt-base,xeddmc/bolt,nantunes/bolt,pygillier/bolt,bolt/bolt,richardhinkamp/bolt,HonzaMikula/bolt,hannesl/bolt,GawainLynch/bolt,romulo1984/bolt,bywatersolutions/reports-site,marcin-piela/bolt,pygillier/bolt,Raistlfiren/bolt,joshuan/bolt,tekjava/bolt,bywatersolutions/reports-site,nikgo/bolt,GDmac/bolt,winiceo/bolt,nikgo/bolt,rossriley/bolt,HonzaMikula/masivnipostele,xeddmc/bolt,skript-cc/bolt,HonzaMikula/masivnipostele,hugin2005/bolt,Eiskis/bolt-base,GawainLynch/bolt,tekjava/bolt,Calinou/bolt,winiceo/bolt,xeddmc/bolt,Eiskis/bolt-base,one988/cm,pygillier/bolt,one988/cm,Calinou/bolt,hannesl/bolt,electrolinux/bolt,joshuan/bolt,kendoctor/bolt,GDmac/bolt,lenvanessen/bolt,one988/cm,kendoctor/bolt,cdowdy/bolt,tekjava/bolt,cdowdy/bolt,bolt/bolt,hannesl/bolt,romulo1984/bolt,winiceo/bolt,electrolinux/bolt,codesman/bolt,rarila/bolt,kendoctor/bolt,romulo1984/bolt,HonzaMikula/bolt,HonzaMikula/bolt,nantunes/bolt,Intendit/bolt,Raistlfiren/bolt,skript-cc/bolt,GawainLynch/bolt,rossriley/bolt,cdowdy/bolt,Calinou/bolt
scss
## Code Before: .bolt-editable { outline: 2px #bef092 solid; } ## Instruction: Add min-height to editable content ## Code After: .bolt-editable { outline: 2px #bef092 solid; min-height: 10px; }
.bolt-editable { outline: 2px #bef092 solid; + min-height: 10px; }
1
0.333333
1
0
40ba9fe366edb78467de0fceef979188421ef16a
Config/bootstrap.php
Config/bootstrap.php
<?php $cacheConfig = array( 'duration' => '+10 minutes', 'path' => CACHE . 'queries', 'engine' => 'File', ); Cache::config('switcher_default', $cacheConfig); Croogo::hookBehavior('Node', 'Switcher.Switcher'); Croogo::hookComponent('*', 'Switcher.Switcher'); Croogo::hookHelper('*', 'Switcher.Switcher'); Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node'); Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node'); CroogoNav::add('extensions.children.switcher', array( 'title' => 'Switcher', 'url' => '#', 'children' => array( 'paths' => array( 'title' => 'Paths', 'url' => array( 'admin' => true, 'plugin' => 'switcher', 'controller' => 'switcher_paths', 'action' => 'index', ), 'weight' => 10, ), 'nodes' => array( 'title' => 'Nodes', 'url' => array( 'admin' => true, 'plugin' => 'nodes', 'controller' => 'nodes', 'action' => 'index', ), 'weight' => 20, ), ), ));
<?php CroogoCache::config('switcher_default', array_merge( Configure::read('Cache.defaultConfig'), array('duration' => '+10 minutes') )); Croogo::hookBehavior('Node', 'Switcher.Switcher'); Croogo::hookComponent('*', 'Switcher.Switcher'); Croogo::hookHelper('*', 'Switcher.Switcher'); Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node'); Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node'); CroogoNav::add('extensions.children.switcher', array( 'title' => 'Switcher', 'url' => '#', 'children' => array( 'paths' => array( 'title' => 'Paths', 'url' => array( 'admin' => true, 'plugin' => 'switcher', 'controller' => 'switcher_paths', 'action' => 'index', ), 'weight' => 10, ), 'nodes' => array( 'title' => 'Nodes', 'url' => array( 'admin' => true, 'plugin' => 'nodes', 'controller' => 'nodes', 'action' => 'index', ), 'weight' => 20, ), ), ));
Update to use croogo default cache config
Update to use croogo default cache config
PHP
mit
rchavik/switcher
php
## Code Before: <?php $cacheConfig = array( 'duration' => '+10 minutes', 'path' => CACHE . 'queries', 'engine' => 'File', ); Cache::config('switcher_default', $cacheConfig); Croogo::hookBehavior('Node', 'Switcher.Switcher'); Croogo::hookComponent('*', 'Switcher.Switcher'); Croogo::hookHelper('*', 'Switcher.Switcher'); Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node'); Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node'); CroogoNav::add('extensions.children.switcher', array( 'title' => 'Switcher', 'url' => '#', 'children' => array( 'paths' => array( 'title' => 'Paths', 'url' => array( 'admin' => true, 'plugin' => 'switcher', 'controller' => 'switcher_paths', 'action' => 'index', ), 'weight' => 10, ), 'nodes' => array( 'title' => 'Nodes', 'url' => array( 'admin' => true, 'plugin' => 'nodes', 'controller' => 'nodes', 'action' => 'index', ), 'weight' => 20, ), ), )); ## Instruction: Update to use croogo default cache config ## Code After: <?php CroogoCache::config('switcher_default', array_merge( Configure::read('Cache.defaultConfig'), array('duration' => '+10 minutes') )); Croogo::hookBehavior('Node', 'Switcher.Switcher'); Croogo::hookComponent('*', 'Switcher.Switcher'); Croogo::hookHelper('*', 'Switcher.Switcher'); Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node'); Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node'); CroogoNav::add('extensions.children.switcher', array( 'title' => 'Switcher', 'url' => '#', 'children' => array( 'paths' => array( 'title' => 'Paths', 'url' => array( 'admin' => true, 'plugin' => 'switcher', 'controller' => 'switcher_paths', 'action' => 'index', ), 'weight' => 10, ), 'nodes' => array( 'title' => 'Nodes', 'url' => array( 'admin' => true, 'plugin' => 'nodes', 'controller' => 'nodes', 'action' => 'index', ), 'weight' => 20, ), ), ));
<?php - - $cacheConfig = array( + CroogoCache::config('switcher_default', array_merge( + Configure::read('Cache.defaultConfig'), - 'duration' => '+10 minutes', ? ^ + array('duration' => '+10 minutes') ? ++++++ ^ + )); - 'path' => CACHE . 'queries', - 'engine' => 'File', - ); - - Cache::config('switcher_default', $cacheConfig); Croogo::hookBehavior('Node', 'Switcher.Switcher'); Croogo::hookComponent('*', 'Switcher.Switcher'); Croogo::hookHelper('*', 'Switcher.Switcher'); Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node'); Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node'); CroogoNav::add('extensions.children.switcher', array( 'title' => 'Switcher', 'url' => '#', 'children' => array( 'paths' => array( 'title' => 'Paths', 'url' => array( 'admin' => true, 'plugin' => 'switcher', 'controller' => 'switcher_paths', 'action' => 'index', - ), ? - + ), 'weight' => 10, - ), ? - + ), 'nodes' => array( 'title' => 'Nodes', 'url' => array( 'admin' => true, 'plugin' => 'nodes', 'controller' => 'nodes', 'action' => 'index', - ), ? - + ), 'weight' => 20, - ), ), - )); + ), + ));
22
0.511628
9
13
cf218d1fec7c4f1dd10297498d000b824418cfba
composer.json
composer.json
{ "config": { "vendor-dir": "public_html/app/vendor" }, "require": { "mailgun/mailgun-php": "~1.7.2", "phpunit/phpunit": "^5.7" } }
{ "config": { "vendor-dir": "public_html/app/vendor" }, "require": { "mailgun/mailgun-php": "~1.7.2" }, "required-dev": { "phpunit/phpunit": "^5.7" } }
Load PHPUnit only on dev environment.
Load PHPUnit only on dev environment.
JSON
mit
sass-team/sass-app,sass-team/sass-app,sass-team/sass-app,sass-team/sass-app
json
## Code Before: { "config": { "vendor-dir": "public_html/app/vendor" }, "require": { "mailgun/mailgun-php": "~1.7.2", "phpunit/phpunit": "^5.7" } } ## Instruction: Load PHPUnit only on dev environment. ## Code After: { "config": { "vendor-dir": "public_html/app/vendor" }, "require": { "mailgun/mailgun-php": "~1.7.2" }, "required-dev": { "phpunit/phpunit": "^5.7" } }
{ "config": { "vendor-dir": "public_html/app/vendor" }, "require": { - "mailgun/mailgun-php": "~1.7.2", ? - + "mailgun/mailgun-php": "~1.7.2" + }, + "required-dev": { "phpunit/phpunit": "^5.7" } }
4
0.444444
3
1
8aff4502db960a58bac3c63c5e7ff69a1b620e8c
ReactiveCocoaTests/Swift/HotSignalSpec.swift
ReactiveCocoaTests/Swift/HotSignalSpec.swift
// // HotSignalSpec.swift // ReactiveCocoa // // Created by Alan Rogers on 30/10/2014. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class HotSignalSpec: QuickSpec { override func spec() { describe("replay") { var signal : HotSignal<Int>! var sink : SinkOf<Int>! var coldSignal : ColdSignal<Int>! beforeEach { let pipe = HotSignal<Int>.pipe() signal = pipe.0 sink = pipe.1 coldSignal = signal.replay(1) } it("should replay the first value to a subscriber") { sink.put(99) let result = coldSignal.first().value() expect(result).toNot(beNil()) expect(result).to(equal(99)) } } } }
// // HotSignalSpec.swift // ReactiveCocoa // // Created by Alan Rogers on 30/10/2014. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class HotSignalSpec: QuickSpec { override func spec() { describe("replay") { var signal : HotSignal<Int>! var sink : SinkOf<Int>! var replaySignal : ColdSignal<Int>! beforeEach { let pipe = HotSignal<Int>.pipe() signal = pipe.0 sink = pipe.1 replaySignal = signal.replay(1) } it("should replay the first value") { sink.put(99) let result = replaySignal.first().value() expect(result).toNot(beNil()) expect(result).to(equal(99)) } } } }
Rename some of the test vars.
Rename some of the test vars.
Swift
mit
mxxiv/ReactiveCocoa,Ricowere/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,zzqiltw/ReactiveCocoa,zhigang1992/ReactiveCocoa,rpowelll/ReactiveCocoa,DreamHill/ReactiveCocoa,hoanganh6491/ReactiveCocoa,natestedman/ReactiveCocoa,dskatz22/ReactiveCocoa,Rupert-RR/ReactiveCocoa,libiao88/ReactiveCocoa,wpstarnice/ReactiveCocoa,dz1111/ReactiveCocoa,hbucius/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,llb1119/test,dz1111/ReactiveCocoa,zhiwen1024/ReactiveCocoa,jrmiddle/ReactiveCocoa,ericzhou2008/ReactiveCocoa,KuPai32G/ReactiveCocoa,nikita-leonov/ReactiveCocoa,ikesyo/ReactiveCocoa,dskatz22/ReactiveCocoa,jaylib/ReactiveCocoa,bscarano/ReactiveCocoa,lixar/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,tornade0913/ReactiveCocoa,kaylio/ReactiveCocoa,ztchena/ReactiveCocoa,longv2go/ReactiveCocoa,zhenlove/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,zzqiltw/ReactiveCocoa,BrooksWon/ReactiveCocoa,hilllinux/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,natestedman/ReactiveCocoa,Ray0218/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,lixar/ReactiveCocoa,clg0118/ReactiveCocoa,vincentiss/ReactiveCocoa,eyu1988/ReactiveCocoa,tonyarnold/ReactiveCocoa,icepy/ReactiveCocoa,victorlin/ReactiveCocoa,kaylio/ReactiveCocoa,esttorhe/ReactiveCocoa,howandhao/ReactiveCocoa,SuPair/ReactiveCocoa,dachaoisme/ReactiveCocoa,mxxiv/ReactiveCocoa,lixar/ReactiveCocoa,mtxs007/ReactiveCocoa,ceekayel/ReactiveCocoa,cogddo/ReactiveCocoa,eyu1988/ReactiveCocoa,on99/ReactiveCocoa,liufeigit/ReactiveCocoa,sandyway/ReactiveCocoa,terry408911/ReactiveCocoa,KJin99/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,huiping192/ReactiveCocoa,pzw224/ReactiveCocoa,taylormoonxu/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,KJin99/ReactiveCocoa,tzongw/ReactiveCocoa,zhigang1992/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,nikita-leonov/ReactiveCocoa,kiurentu/ReactiveCocoa,OneSmallTree/ReactiveCocoa,beni55/ReactiveCocoa,liufeigit/ReactiveCocoa,BlessNeo/ReactiveCocoa,kevin-zqw/ReactiveCocoa,smilypeda/ReactiveCocoa,FelixYin66/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,fanghao085/ReactiveCocoa,vincentiss/ReactiveCocoa,jsslai/ReactiveCocoa,huiping192/ReactiveCocoa,LHDsimon/ReactiveCocoa,stupidfive/ReactiveCocoa,shaohung001/ReactiveCocoa,itschaitanya/ReactiveCocoa,Farteen/ReactiveCocoa,chieryw/ReactiveCocoa,j364960953/ReactiveCocoa,huiping192/ReactiveCocoa,valleyman86/ReactiveCocoa,howandhao/ReactiveCocoa,qq644531343/ReactiveCocoa,yonekawa/ReactiveCocoa,zhukaixy/ReactiveCocoa,victorlin/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,Khan/ReactiveCocoa,WEIBP/ReactiveCocoa,walkingsmarts/ReactiveCocoa,llb1119/test,bensonday/ReactiveCocoa,eyu1988/ReactiveCocoa,alvinvarghese/ReactiveCocoa,dullgrass/ReactiveCocoa,calebd/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,kiurentu/ReactiveCocoa,Rupert-RR/ReactiveCocoa,j364960953/ReactiveCocoa,Eveian/ReactiveCocoa,zxq3220122/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,chao95957/ReactiveCocoa,richeterre/ReactiveCocoa,imkerberos/ReactiveCocoa,zhukaixy/ReactiveCocoa,dskatz22/ReactiveCocoa,zhenlove/ReactiveCocoa,natan/ReactiveCocoa,natestedman/ReactiveCocoa,dachaoisme/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,jam891/ReactiveCocoa,qq644531343/ReactiveCocoa,ericzhou2008/ReactiveCocoa,jam891/ReactiveCocoa,xiaobing2007/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,ceekayel/ReactiveCocoa,xulibao/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,BlessNeo/ReactiveCocoa,zhaoguohui/ReactiveCocoa,kevin-zqw/ReactiveCocoa,emodeqidao/ReactiveCocoa,mattpetters/ReactiveCocoa,monkeydbobo/ReactiveCocoa,smilypeda/ReactiveCocoa,200895045/ReactiveCocoa,jackywpy/ReactiveCocoa,buildo/ReactiveCocoa,SuPair/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,tonyarnold/ReactiveCocoa,AlanJN/ReactiveCocoa,Eveian/ReactiveCocoa,ceekayel/ReactiveCocoa,ioshger0125/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,yoichitgy/ReactiveCocoa,windgo/ReactiveCocoa,rpowelll/ReactiveCocoa,Khan/ReactiveCocoa,kevin-zqw/ReactiveCocoa,Juraldinio/ReactiveCocoa,calebd/ReactiveCocoa,yizzuide/ReactiveCocoa,pzw224/ReactiveCocoa,jsslai/ReactiveCocoa,zzzworm/ReactiveCocoa,clg0118/ReactiveCocoa,nikita-leonov/ReactiveCocoa,longv2go/ReactiveCocoa,sujeking/ReactiveCocoa,sdhzwm/ReactiveCocoa,windgo/ReactiveCocoa,jeelun/ReactiveCocoa,tornade0913/ReactiveCocoa,dz1111/ReactiveCocoa,terry408911/ReactiveCocoa,wpstarnice/ReactiveCocoa,brasbug/ReactiveCocoa,AlanJN/ReactiveCocoa,takeshineshiro/ReactiveCocoa,sujeking/ReactiveCocoa,emodeqidao/ReactiveCocoa,valleyman86/ReactiveCocoa,gengjf/ReactiveCocoa,howandhao/ReactiveCocoa,zhaoguohui/ReactiveCocoa,jam891/ReactiveCocoa,SanChain/ReactiveCocoa,tonyli508/ReactiveCocoa,JohnJin007/ReactiveCocoa,ikesyo/ReactiveCocoa,emodeqidao/ReactiveCocoa,Juraldinio/ReactiveCocoa,tonyarnold/ReactiveCocoa,FelixYin66/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,bensonday/ReactiveCocoa,paulyoung/ReactiveCocoa,liufeigit/ReactiveCocoa,Ray0218/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,Ricowere/ReactiveCocoa,walkingsmarts/ReactiveCocoa,JohnJin007/ReactiveCocoa,dullgrass/ReactiveCocoa,jsslai/ReactiveCocoa,andersio/ReactiveCocoa,JohnJin007/ReactiveCocoa,yytong/ReactiveCocoa,jrmiddle/ReactiveCocoa,mtxs007/ReactiveCocoa,200895045/ReactiveCocoa,Ethan89/ReactiveCocoa,add715/ReactiveCocoa,terry408911/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,hilllinux/ReactiveCocoa,clg0118/ReactiveCocoa,zxq3220122/ReactiveCocoa,fhchina/ReactiveCocoa,Ricowere/ReactiveCocoa,tiger8888/ReactiveCocoa,LHDsimon/ReactiveCocoa,BlessNeo/ReactiveCocoa,sugar2010/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,taylormoonxu/ReactiveCocoa,richeterre/ReactiveCocoa,cnbin/ReactiveCocoa,wangqi211/ReactiveCocoa,dullgrass/ReactiveCocoa,hilllinux/ReactiveCocoa,jackywpy/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,almassapargali/ReactiveCocoa,takeshineshiro/ReactiveCocoa,itschaitanya/ReactiveCocoa,kiurentu/ReactiveCocoa,tonyli508/ReactiveCocoa,ShawnLeee/ReactiveCocoa,isghe/ReactiveCocoa,zhigang1992/ReactiveCocoa,monkeydbobo/ReactiveCocoa,ohwutup/ReactiveCocoa,rpowelll/ReactiveCocoa,ztchena/ReactiveCocoa,xiaoliyang/ReactiveCocoa,hbucius/ReactiveCocoa,towik/ReactiveCocoa,BrooksWon/ReactiveCocoa,yonekawa/ReactiveCocoa,ioshger0125/ReactiveCocoa,SuPair/ReactiveCocoa,cogddo/ReactiveCocoa,Pingco/ReactiveCocoa,cogddo/ReactiveCocoa,ddc391565320/ReactiveCocoa,Liquidsoul/ReactiveCocoa,Rupert-RR/ReactiveCocoa,esttorhe/ReactiveCocoa,tzongw/ReactiveCocoa,sandyway/ReactiveCocoa,huiping192/ReactiveCocoa,bscarano/ReactiveCocoa,chieryw/ReactiveCocoa,gengjf/ReactiveCocoa,Ray0218/ReactiveCocoa,shaohung001/ReactiveCocoa,mattpetters/ReactiveCocoa,hbucius/ReactiveCocoa,fhchina/ReactiveCocoa,CQXfly/ReactiveCocoa,nickcheng/ReactiveCocoa,libiao88/ReactiveCocoa,isghe/ReactiveCocoa,libiao88/ReactiveCocoa,BrooksWon/ReactiveCocoa,luerhouhou/ReactiveCocoa,Pingco/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,stupidfive/ReactiveCocoa,longv2go/ReactiveCocoa,ShawnLeee/ReactiveCocoa,200895045/ReactiveCocoa,andersio/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,richeterre/ReactiveCocoa,AlanJN/ReactiveCocoa,goodheart/ReactiveCocoa,KJin99/ReactiveCocoa,alvinvarghese/ReactiveCocoa,vincentiss/ReactiveCocoa,goodheart/ReactiveCocoa,natan/ReactiveCocoa,fanghao085/ReactiveCocoa,shaohung001/ReactiveCocoa,leelili/ReactiveCocoa,esttorhe/ReactiveCocoa,valleyman86/ReactiveCocoa,jackywpy/ReactiveCocoa,zxq3220122/ReactiveCocoa,LHDsimon/ReactiveCocoa,wpstarnice/ReactiveCocoa,sugar2010/ReactiveCocoa,yizzuide/ReactiveCocoa,zzzworm/ReactiveCocoa,tiger8888/ReactiveCocoa,Ricowere/ReactiveCocoa,monkeydbobo/ReactiveCocoa,zhiwen1024/ReactiveCocoa,loupman/ReactiveCocoa,yoichitgy/ReactiveCocoa,paulyoung/ReactiveCocoa,yonekawa/ReactiveCocoa,kaylio/ReactiveCocoa,FelixYin66/ReactiveCocoa,leichunfeng/ReactiveCocoa,Liquidsoul/ReactiveCocoa,WEIBP/ReactiveCocoa,chao95957/ReactiveCocoa,fhchina/ReactiveCocoa,Pingco/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,jaylib/ReactiveCocoa,takeshineshiro/ReactiveCocoa,alvinvarghese/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,wangqi211/ReactiveCocoa,wangqi211/ReactiveCocoa,icepy/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,andersio/ReactiveCocoa,ShawnLeee/ReactiveCocoa,OneSmallTree/ReactiveCocoa,stevielu/ReactiveCocoa,qq644531343/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,sujeking/ReactiveCocoa,hoanganh6491/ReactiveCocoa,paulyoung/ReactiveCocoa,beni55/ReactiveCocoa,DreamHill/ReactiveCocoa,jrmiddle/ReactiveCocoa,leichunfeng/ReactiveCocoa,stevielu/ReactiveCocoa,add715/ReactiveCocoa,xiaobing2007/ReactiveCocoa,luerhouhou/ReactiveCocoa,hj3938/ReactiveCocoa,towik/ReactiveCocoa,nickcheng/ReactiveCocoa,smilypeda/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,xiaoliyang/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,yytong/ReactiveCocoa,xumaolin/ReactiveCocoa,zhukaixy/ReactiveCocoa,cnbin/ReactiveCocoa,hj3938/ReactiveCocoa,ohwutup/ReactiveCocoa,mtxs007/ReactiveCocoa,jeelun/ReactiveCocoa,ericzhou2008/ReactiveCocoa,luerhouhou/ReactiveCocoa,JackLian/ReactiveCocoa,stevielu/ReactiveCocoa,hoanganh6491/ReactiveCocoa,towik/ReactiveCocoa,brasbug/ReactiveCocoa,zhenlove/ReactiveCocoa,on99/ReactiveCocoa,sugar2010/ReactiveCocoa,on99/ReactiveCocoa,hj3938/ReactiveCocoa,llb1119/test,JackLian/ReactiveCocoa,JackLian/ReactiveCocoa,bscarano/ReactiveCocoa,victorlin/ReactiveCocoa,tzongw/ReactiveCocoa,Ethan89/ReactiveCocoa,leelili/ReactiveCocoa,almassapargali/ReactiveCocoa,jaylib/ReactiveCocoa,yytong/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,xumaolin/ReactiveCocoa,SanChain/ReactiveCocoa,buildo/ReactiveCocoa,cstars135/ReactiveCocoa,beni55/ReactiveCocoa,Farteen/ReactiveCocoa,yoichitgy/ReactiveCocoa,brasbug/ReactiveCocoa,SanChain/ReactiveCocoa,OneSmallTree/ReactiveCocoa,sandyway/ReactiveCocoa,zzzworm/ReactiveCocoa,xulibao/ReactiveCocoa,bensonday/ReactiveCocoa,almassapargali/ReactiveCocoa,loupman/ReactiveCocoa,nickcheng/ReactiveCocoa,stupidfive/ReactiveCocoa,zhiwen1024/ReactiveCocoa,CQXfly/ReactiveCocoa,leelili/ReactiveCocoa,icepy/ReactiveCocoa,add715/ReactiveCocoa,fanghao085/ReactiveCocoa,KuPai32G/ReactiveCocoa,windgo/ReactiveCocoa,Farteen/ReactiveCocoa,Ethan89/ReactiveCocoa,tornade0913/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,natan/ReactiveCocoa,dachaoisme/ReactiveCocoa,WEIBP/ReactiveCocoa,itschaitanya/ReactiveCocoa,xulibao/ReactiveCocoa,isghe/ReactiveCocoa,tiger8888/ReactiveCocoa,jeelun/ReactiveCocoa,chieryw/ReactiveCocoa,imkerberos/ReactiveCocoa,sdhzwm/ReactiveCocoa,xumaolin/ReactiveCocoa,Liquidsoul/ReactiveCocoa,nickcheng/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,cstars135/ReactiveCocoa,mattpetters/ReactiveCocoa,xiaobing2007/ReactiveCocoa,calebd/ReactiveCocoa,goodheart/ReactiveCocoa,walkingsmarts/ReactiveCocoa,DreamHill/ReactiveCocoa,ddc391565320/ReactiveCocoa,gengjf/ReactiveCocoa,xiaoliyang/ReactiveCocoa,loupman/ReactiveCocoa,ioshger0125/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,Eveian/ReactiveCocoa,ddc391565320/ReactiveCocoa,imkerberos/ReactiveCocoa,jaylib/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,esttorhe/ReactiveCocoa,ztchena/ReactiveCocoa,buildo/ReactiveCocoa,cnbin/ReactiveCocoa,j364960953/ReactiveCocoa,yizzuide/ReactiveCocoa,pzw224/ReactiveCocoa,cstars135/ReactiveCocoa,zzqiltw/ReactiveCocoa,mxxiv/ReactiveCocoa,ohwutup/ReactiveCocoa,zhaoguohui/ReactiveCocoa,CQXfly/ReactiveCocoa,sdhzwm/ReactiveCocoa,leichunfeng/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,Khan/ReactiveCocoa,chao95957/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,Juraldinio/ReactiveCocoa,KuPai32G/ReactiveCocoa,tonyli508/ReactiveCocoa,taylormoonxu/ReactiveCocoa
swift
## Code Before: // // HotSignalSpec.swift // ReactiveCocoa // // Created by Alan Rogers on 30/10/2014. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class HotSignalSpec: QuickSpec { override func spec() { describe("replay") { var signal : HotSignal<Int>! var sink : SinkOf<Int>! var coldSignal : ColdSignal<Int>! beforeEach { let pipe = HotSignal<Int>.pipe() signal = pipe.0 sink = pipe.1 coldSignal = signal.replay(1) } it("should replay the first value to a subscriber") { sink.put(99) let result = coldSignal.first().value() expect(result).toNot(beNil()) expect(result).to(equal(99)) } } } } ## Instruction: Rename some of the test vars. ## Code After: // // HotSignalSpec.swift // ReactiveCocoa // // Created by Alan Rogers on 30/10/2014. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class HotSignalSpec: QuickSpec { override func spec() { describe("replay") { var signal : HotSignal<Int>! var sink : SinkOf<Int>! var replaySignal : ColdSignal<Int>! beforeEach { let pipe = HotSignal<Int>.pipe() signal = pipe.0 sink = pipe.1 replaySignal = signal.replay(1) } it("should replay the first value") { sink.put(99) let result = replaySignal.first().value() expect(result).toNot(beNil()) expect(result).to(equal(99)) } } } }
// // HotSignalSpec.swift // ReactiveCocoa // // Created by Alan Rogers on 30/10/2014. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class HotSignalSpec: QuickSpec { override func spec() { describe("replay") { var signal : HotSignal<Int>! var sink : SinkOf<Int>! - var coldSignal : ColdSignal<Int>! ? ^^ ^ + var replaySignal : ColdSignal<Int>! ? ^^^ ^^ beforeEach { let pipe = HotSignal<Int>.pipe() signal = pipe.0 sink = pipe.1 - coldSignal = signal.replay(1) ? ^^ ^ + replaySignal = signal.replay(1) ? ^^^ ^^ } - it("should replay the first value to a subscriber") { ? ---------------- + it("should replay the first value") { sink.put(99) + - let result = coldSignal.first().value() ? ^^ ^ + let result = replaySignal.first().value() ? ^^^ ^^ expect(result).toNot(beNil()) expect(result).to(equal(99)) } } } }
9
0.257143
5
4
2e6cfe56806a7fb07396293568c6c4449dccf188
gifer.js
gifer.js
'use strict'; function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return false; }; }; window.onload = init;
'use strict'; const videoClip = require('./movie.js'); function bindUI() { // Bind options to videoClip file. } function reset() { // Reset options to values of video file. } function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); videoClip.video = file.path; // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return true; }; } window.onload = init;
Add functions to be filled later
Add functions to be filled later
JavaScript
mit
mikkkee/gifer-electron,mikkkee/gifer-electron,mikkkee/gifer-electron
javascript
## Code Before: 'use strict'; function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return false; }; }; window.onload = init; ## Instruction: Add functions to be filled later ## Code After: 'use strict'; const videoClip = require('./movie.js'); function bindUI() { // Bind options to videoClip file. } function reset() { // Reset options to values of video file. } function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); videoClip.video = file.path; // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return true; }; } window.onload = init;
'use strict'; + + const videoClip = require('./movie.js'); + + function bindUI() { + // Bind options to videoClip file. + } + + function reset() { + // Reset options to values of video file. + } function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); - document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); - + videoClip.video = file.path; // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); - return false; ? ^^^^ + return true; ? ^^^ }; - }; + } window.onload = init;
17
0.34
13
4
7483349229ec40253efe72ffe4544043c92cb3fc
.travis.yml
.travis.yml
language: ruby sudo: false cache: bundler rvm: - 2.2.5 notifications: email: false install: - bundle install - npm install bower - npm install - bundle exec bower update
language: ruby sudo: false cache: bundler rvm: - 2.2.5 notifications: email: false install: - bundle install - npm install -g bower - npm install - bower update
Install bower globally on Travis
Install bower globally on Travis Travis changed the way of using $PATH so in order to work it is required to install bower globaly so the bower command become available to the shell. And do not use bundle exec for running bower commands since bower is not attached to bundler.
YAML
mit
moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough
yaml
## Code Before: language: ruby sudo: false cache: bundler rvm: - 2.2.5 notifications: email: false install: - bundle install - npm install bower - npm install - bundle exec bower update ## Instruction: Install bower globally on Travis Travis changed the way of using $PATH so in order to work it is required to install bower globaly so the bower command become available to the shell. And do not use bundle exec for running bower commands since bower is not attached to bundler. ## Code After: language: ruby sudo: false cache: bundler rvm: - 2.2.5 notifications: email: false install: - bundle install - npm install -g bower - npm install - bower update
language: ruby sudo: false cache: bundler rvm: - 2.2.5 notifications: email: false install: - bundle install - - npm install bower + - npm install -g bower ? +++ - npm install - - bundle exec bower update + - bower update
4
0.333333
2
2
f1594f436f13fac7723c64b641c5be4a80819420
transform.js
transform.js
var moment = require('moment'); // Returned format from original API is a bit strange and very deeply nested. // Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL function transform(data) { var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return { vehicles: vehicles.map(transformVehicle), responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp }; } function transformVehicle(vehicle) { var journey = vehicle.MonitoredVehicleJourney; return { id: journey.VehicleRef.value, line: journey.LineRef.value, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing, origin: journey.OriginName.value, destination: journey.DestinationName.value, operator: journey.OperatorRef.value, direction: journey.DirectionRef.value, validUntil: moment(vehicle.ValidUntilTime).toISOString() }; } module.exports = transform;
var moment = require('moment'); // Returned format from original API is a bit strange and very deeply nested. // Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL function transform(data) { var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return { vehicles: vehicles.map(transformVehicle), responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp }; } function transformVehicle(vehicle) { var journey = vehicle.MonitoredVehicleJourney; return { id: journey.VehicleRef.value, line: journey.LineRef.value, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing, operator: journey.OperatorRef.value, direction: journey.DirectionRef.value, validUntil: moment(vehicle.ValidUntilTime).toISOString() }; } module.exports = transform;
Remove origin and destination fields. They are not in Helsinki API
Remove origin and destination fields. They are not in Helsinki API
JavaScript
mit
kimmobrunfeldt/busse-api-helsinki
javascript
## Code Before: var moment = require('moment'); // Returned format from original API is a bit strange and very deeply nested. // Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL function transform(data) { var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return { vehicles: vehicles.map(transformVehicle), responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp }; } function transformVehicle(vehicle) { var journey = vehicle.MonitoredVehicleJourney; return { id: journey.VehicleRef.value, line: journey.LineRef.value, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing, origin: journey.OriginName.value, destination: journey.DestinationName.value, operator: journey.OperatorRef.value, direction: journey.DirectionRef.value, validUntil: moment(vehicle.ValidUntilTime).toISOString() }; } module.exports = transform; ## Instruction: Remove origin and destination fields. They are not in Helsinki API ## Code After: var moment = require('moment'); // Returned format from original API is a bit strange and very deeply nested. // Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL function transform(data) { var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return { vehicles: vehicles.map(transformVehicle), responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp }; } function transformVehicle(vehicle) { var journey = vehicle.MonitoredVehicleJourney; return { id: journey.VehicleRef.value, line: journey.LineRef.value, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing, operator: journey.OperatorRef.value, direction: journey.DirectionRef.value, validUntil: moment(vehicle.ValidUntilTime).toISOString() }; } module.exports = transform;
var moment = require('moment'); // Returned format from original API is a bit strange and very deeply nested. // Original API url: http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL function transform(data) { var vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return { vehicles: vehicles.map(transformVehicle), responseUnixTime: data.Siri.ServiceDelivery.ResponseTimestamp }; } function transformVehicle(vehicle) { var journey = vehicle.MonitoredVehicleJourney; return { id: journey.VehicleRef.value, line: journey.LineRef.value, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing, - origin: journey.OriginName.value, - destination: journey.DestinationName.value, operator: journey.OperatorRef.value, direction: journey.DirectionRef.value, validUntil: moment(vehicle.ValidUntilTime).toISOString() }; } module.exports = transform;
2
0.0625
0
2
28929cc0260ea14c2de5ec19874c6dbba00f9100
matchMedia.js
matchMedia.js
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { "use strict"; var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document ));
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia || (window.matchMedia = function() { "use strict"; var styleMedia = (window.styleMedia || window.media); // For those that doen't support matchMedium if (!styleMedia) { var style = document.createElement('style'), info = null, setStyle = function(text) { if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } }; style.type = 'text/css'; style.id = 'matchmediajs-test'; document.getElementsByTagName('head')[0].appendChild(style); info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle; styleMedia = { matchMedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }', match; // Add css text setStyle(text); match = info.width === '1px'; // remove css text setStyle(''); return match; } }; } return function(media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }());
Complete rewrite in an effort to gain performance
Complete rewrite in an effort to gain performance
JavaScript
mit
therealedsheenan/matchMedia.js,amitabhaghosh197/matchMedia.js,AndBicScadMedia/matchMedia.js,ababic/matchMedia.js,therealedsheenan/matchMedia.js,paulirish/matchMedia.js,zxfjessica/match-media-polyfill,CondeNast/matchMedia.js,CondeNast/matchMedia.js,ababic/matchMedia.js,dirajkumar/matchMedia.js,zxfjessica/match-media-polyfill,alejonext/matchMedia.js,dirajkumar/matchMedia.js,paulirish/matchMedia.js,alejonext/matchMedia.js,amitabhaghosh197/matchMedia.js,AndBicScadMedia/matchMedia.js
javascript
## Code Before: /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { "use strict"; var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); ## Instruction: Complete rewrite in an effort to gain performance ## Code After: /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia || (window.matchMedia = function() { "use strict"; var styleMedia = (window.styleMedia || window.media); // For those that doen't support matchMedium if (!styleMedia) { var style = document.createElement('style'), info = null, setStyle = function(text) { if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } }; style.type = 'text/css'; style.id = 'matchmediajs-test'; document.getElementsByTagName('head')[0].appendChild(style); info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle; styleMedia = { matchMedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }', match; // Add css text setStyle(text); match = info.width === '1px'; // remove css text setStyle(''); return match; } }; } return function(media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }());
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ - window.matchMedia = window.matchMedia || (function( doc, undefined ) { + window.matchMedia || (window.matchMedia = function() { + "use strict"; - "use strict"; + var styleMedia = (window.styleMedia || window.media); - var bool, - docElem = doc.documentElement, - refNode = docElem.firstElementChild || docElem.firstChild, - // fakeBody required for <FF4 when executed in <head> - fakeBody = doc.createElement( "body" ), - div = doc.createElement( "div" ); + // For those that doen't support matchMedium + if (!styleMedia) { + var style = document.createElement('style'), + info = null, + setStyle = function(text) { + if (style.styleSheet) { + style.styleSheet.cssText = text; + } else { + style.textContent = text; + } + }; + style.type = 'text/css'; + style.id = 'matchmediajs-test'; - div.id = "mq-test-1"; - div.style.cssText = "position:absolute;top:-100em"; - fakeBody.style.background = "none"; - fakeBody.appendChild(div); - return function(q){ + document.getElementsByTagName('head')[0].appendChild(style); + info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle; - div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; + styleMedia = { + matchMedium: function(media) { + var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }', + match; + // Add css text + setStyle(text); - docElem.insertBefore( fakeBody, refNode ); - bool = div.offsetWidth === 42; - docElem.removeChild( fakeBody ); + match = info.width === '1px'; + + // remove css text + setStyle(''); + + return match; + } + }; + + } + + return function(media) { - return { + return { ? ++++ - matches: bool, - media: q + matches: styleMedia.matchMedium(media || 'all'), + media: media || 'all' + }; }; + }()); - - }; - - }( document )); - -
67
1.861111
41
26