Skip to content

Commit c8b1fe4

Browse files
authored
Merge branch 'master' into search
2 parents e577f58 + 144daca commit c8b1fe4

13 files changed

+105
-33
lines changed

.DS_Store

2 KB
Binary file not shown.

schema/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
{
44
"command": "codeSnippet:save-as-snippet",
55
"keys": ["Accel Shift A"],
6-
"selector": ".jp-Cell"
6+
"selector": ".jp-Notebook"
77
},
88
{
99
"command": "codeSnippet:save-as-snippet",

snippets/gdp_calculator.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"gdp_calculator","description":"Calculate total GDP, in trillions of dollars, by region, over time","language":"R","code":["gdp_regions <- nations %>%"," mutate(gdp = gdp_percap * population,"," gdp_tn = gdp/1000000000000) %>%"," group_by(region, year) %>%"," summarize(total_gdp_tn = sum(gdp_tn, na.rm = TRUE))",""],"id":11,"tags":["Countries Project"]}
1+
{"name":"gdp_calculator","description":"Calculate total GDP, in trillions of dollars, by region, over time","language":"R","code":["gdp_regions <- nations %>%"," mutate(gdp = gdp_percap * population,"," gdp_tn = gdp/1000000000000) %>%"," group_by(region, year) %>%"," summarize(total_gdp_tn = sum(gdp_tn, na.rm = TRUE))",""],"id":10,"tags":["Countries Project"]}

snippets/generate_hundred.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"generate_hundred","description":"Scala program to print numbers from 1 to 100 using for loop with until to determine loop range.","language":"Scala","code":["object ExampleForLoop2 {"," def main(args: Array[String]) {"," var counter: Int=0;"," "," for(counter <- 1 until 101)"," print(counter + \" \");"," "," // to print new line"," println();"," }","}"],"id":13,"tags":["math"]}
1+
{"name":"generate_hundred","description":"Scala program to print numbers from 1 to 100 using for loop with until to determine loop range.","language":"Scala","code":["object ExampleForLoop2 {"," def main(args: Array[String]) {"," var counter: Int=0;"," "," for(counter <- 1 until 101)"," print(counter + \" \");"," "," // to print new line"," println();"," }","}"],"id":12,"tags":["math"]}

snippets/life_exp_eur_asia.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"life_exp_eur_asia","description":"Find countries in North America or Europe and Central Asia with a life expectancy in 2016 of 75 to 80.","language":"R","code":["eur_na_75_80 <- longevity %>%"," filter(life_expect > 75 & life_expect < 80 & (region == \"Europe & Central Asia\" | region == \"North America\")) %>%"," arrange(desc(life_expect))"],"id":9,"tags":["Countries Project"]}
1+
{"name":"life_exp_eur_asia","description":"Find countries in North America or Europe and Central Asia with a life expectancy in 2016 of 75 to 80.","language":"R","code":["eur_na_75_80 <- longevity %>%"," filter(life_expect > 75 & life_expect < 80 & (region == \"Europe & Central Asia\" | region == \"North America\")) %>%"," arrange(desc(life_expect))"],"id":8,"tags":["Countries Project"]}

snippets/parallel_strings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"parallel_strings","description":"A simple queue function to generate four random strings in parallel.","language":"Python","code":["import multiprocessing as mp","import random","import string","","random.seed(123)","","# Define an output queue","output = mp.Queue()","","# define a example function","def rand_string(length, output):"," \"\"\" Generates a random string of numbers, lower- and uppercase chars. \"\"\""," rand_str = ''.join(random.choice("," string.ascii_lowercase "," + string.ascii_uppercase "," + string.digits)"," for i in range(length))"," output.put(rand_str)","","# Setup a list of processes that we want to run","processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]","","# Run processes","for p in processes:"," p.start()","","# Exit the completed processes","for p in processes:"," p.join()","","# Get process results from the output queue","results = [output.get() for p in processes]","","print(results)"],"id":8,"tags":["multiprocessing"]}
1+
{"name":"parallel_strings","description":"A simple queue function to generate four random strings in parallel.","language":"Python","code":["import multiprocessing as mp","import random","import string","","random.seed(123)","","# Define an output queue","output = mp.Queue()","","# define a example function","def rand_string(length, output):"," \"\"\" Generates a random string of numbers, lower- and uppercase chars. \"\"\""," rand_str = ''.join(random.choice("," string.ascii_lowercase "," + string.ascii_uppercase "," + string.digits)"," for i in range(length))"," output.put(rand_str)","","# Setup a list of processes that we want to run","processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]","","# Run processes","for p in processes:"," p.start()","","# Exit the completed processes","for p in processes:"," p.join()","","# Get process results from the output queue","results = [output.get() for p in processes]","","print(results)"],"id":16,"tags":["multiprocessing"]}

snippets/progress_bar.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"progress_bar","description":"Create a progress bar.","language":"Python","code":["class ProgressBar():"," def __init__(self, width=50):"," self.pointer = 0"," self.width = width",""," def __call__(self,x):"," # x in percent"," self.pointer = int(self.width*(x/100.0))"," return \"|\" + \"#\"*self.pointer + \"-\"*(self.width-self.pointer)+\\"," \"|\\n %d percent done\" % int(x) "],"id":10,"tags":["Time"]}
1+
{"name":"progress_bar","description":"Create a progress bar.","language":"Python","code":["class ProgressBar():"," def __init__(self, width=50):"," self.pointer = 0"," self.width = width",""," def __call__(self,x):"," # x in percent"," self.pointer = int(self.width*(x/100.0))"," return \"|\" + \"#\"*self.pointer + \"-\"*(self.width-self.pointer)+\\"," \"|\\n %d percent done\" % int(x) "],"id":9,"tags":["Time"]}

snippets/sum_array.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"name":"sum_array","description":"Scala program of array. Declare, print, and calculate sum of all elements.","language":"Scala","code":["object ExampleArray1 {"," "," def main(args: Array[String]) {"," "," var numbers = Array(10,20,30,40,50);"," var N:Int=0;"," "," //print all array elements"," println(\"All array elements: \");"," for ( N <- numbers ) {"," println(N);"," }"," //calculating SUM of all elements"," var sum: Int=0;"," for ( N <- numbers ) {"," sum+=N;"," } "," println(\"Sum of all array elements: \"+sum);",""," }","}"],"id":12,"tags":["math"]}
1+
{"name":"sum_array","description":"Scala program of array. Declare, print, and calculate sum of all elements.","language":"Scala","code":["object ExampleArray1 {"," "," def main(args: Array[String]) {"," "," var numbers = Array(10,20,30,40,50);"," var N:Int=0;"," "," //print all array elements"," println(\"All array elements: \");"," for ( N <- numbers ) {"," println(N);"," }"," //calculating SUM of all elements"," var sum: Int=0;"," for ( N <- numbers ) {"," sum+=N;"," } "," println(\"Sum of all array elements: \"+sum);",""," }","}"],"id":11,"tags":["math"]}

src/CodeSnippetDisplay.tsx

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ const CODE_SNIPPET_CREATE_NEW_BTN = 'jp-createSnippetBtn';
106106
/**
107107
* The threshold in pixels to start a drag event.
108108
*/
109-
const DRAG_THRESHOLD = 5;
109+
const DRAG_THRESHOLD = 3;
110110

111111
/**
112112
* A class used to indicate a snippet item.
@@ -460,6 +460,9 @@ export class CodeSnippetDisplay extends React.Component<
460460
target.addEventListener('mouseup', this._evtMouseUp, true);
461461
target.addEventListener('mousemove', this.handleDragMove, true);
462462

463+
// since a browser has its own drag'n'drop support for images and some other elements.
464+
target.ondragstart = () => false;
465+
463466
event.preventDefault();
464467
}
465468

@@ -475,6 +478,9 @@ export class CodeSnippetDisplay extends React.Component<
475478
}
476479

477480
private handleDragMove(event: MouseEvent): void {
481+
event.preventDefault();
482+
event.stopPropagation();
483+
478484
const data = this._dragData;
479485

480486
if (
@@ -489,7 +495,12 @@ export class CodeSnippetDisplay extends React.Component<
489495
const idx = (event.target as HTMLElement).id;
490496
const codeSnippet = this.state.codeSnippets[parseInt(idx)];
491497

492-
this.startDrag(data.dragImage, codeSnippet, event.clientX, event.clientY);
498+
void this.startDrag(
499+
data.dragImage,
500+
codeSnippet,
501+
event.clientX,
502+
event.clientY
503+
);
493504
}
494505
}
495506

@@ -510,7 +521,7 @@ export class CodeSnippetDisplay extends React.Component<
510521
): boolean {
511522
const dx = Math.abs(nextX - prevX);
512523
const dy = Math.abs(nextY - prevY);
513-
return dx >= DRAG_THRESHOLD || dy >= DRAG_THRESHOLD;
524+
return dx >= 0 || dy >= DRAG_THRESHOLD;
514525
}
515526

516527
private async startDrag(
@@ -561,13 +572,22 @@ export class CodeSnippetDisplay extends React.Component<
561572
}
562573

563574
//Set the position of the preview to be next to the snippet title.
575+
564576
private _setPreviewPosition(id: number): void {
565577
const realTarget = document.getElementsByClassName(TITLE_CLASS)[id];
578+
const newTarget = document.getElementsByClassName(CODE_SNIPPET_ITEM)[id];
566579
// distDown is the number of pixels to shift the preview down
567-
let distDown: number = realTarget.getBoundingClientRect().top - 43;
568-
if (realTarget.getBoundingClientRect().top > window.screen.height / 2) {
569-
distDown = distDown - 66;
570-
}
580+
const distDown: number = realTarget.getBoundingClientRect().top - 43; //this is bumping it up
581+
const elementSnippet = newTarget as HTMLElement;
582+
const heightSnippet = elementSnippet.clientHeight;
583+
const heightPreview = heightSnippet.toString(10) + 'px';
584+
document.documentElement.style.setProperty(
585+
'--preview-max-height',
586+
heightPreview
587+
);
588+
// if (realTarget.getBoundingClientRect().top > window.screen.height / 2) {
589+
// distDown = distDown - 66; //this is bumping it up further if it's close to the end of the screen
590+
// }
571591
const final = distDown.toString(10) + 'px';
572592
document.documentElement.style.setProperty('--preview-distance', final);
573593
}

src/CodeSnippetEditor.tsx

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -234,11 +234,38 @@ export class CodeSnippetEditor extends ReactWidget {
234234
{`"${this._codeSnippetEditorMetaData.name}" has unsaved changes, close without saving?`}{' '}
235235
</p>
236236
),
237-
buttons: [Dialog.cancelButton(), Dialog.okButton()]
237+
buttons: [
238+
Dialog.cancelButton(),
239+
Dialog.warnButton({ label: 'Discard' }),
240+
Dialog.okButton({ label: 'Save' })
241+
]
238242
}).then((response: any): void => {
243+
console.log(response.button);
239244
if (response.button.accept) {
240-
this.dispose();
241-
super.onCloseRequest(msg);
245+
if (response.button.label === 'Discard') {
246+
this.dispose();
247+
super.onCloseRequest(msg);
248+
} else if (response.button.label === 'Save') {
249+
const name = (document.querySelector(
250+
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
251+
) as HTMLInputElement).value;
252+
const description = (document.querySelector(
253+
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_DESC_INPUT}`
254+
) as HTMLInputElement).value;
255+
const language = (document.querySelector(
256+
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_LANG_INPUT}`
257+
) as HTMLSelectElement).value;
258+
259+
const validity = this.validateInputs(name, description, language);
260+
if (validity) {
261+
this.updateSnippet().then(value => {
262+
if (value) {
263+
this.dispose();
264+
super.onCloseRequest(msg);
265+
}
266+
});
267+
}
268+
}
242269
}
243270
});
244271
} else {
@@ -348,7 +375,7 @@ export class CodeSnippetEditor extends ReactWidget {
348375
return status;
349376
}
350377

351-
async updateSnippet(): Promise<void> {
378+
async updateSnippet(): Promise<boolean> {
352379
const name = (document.querySelector(
353380
`.${CODE_SNIPPET_EDITOR}-${this._codeSnippetEditorMetaData.id} .${CODE_SNIPPET_EDITOR_NAME_INPUT}`
354381
) as HTMLInputElement).value;
@@ -363,8 +390,6 @@ export class CodeSnippetEditor extends ReactWidget {
363390
this._codeSnippetEditorMetaData.description = description;
364391
this._codeSnippetEditorMetaData.language = language;
365392

366-
this.saved = true;
367-
368393
const newPath =
369394
'snippets/' + this._codeSnippetEditorMetaData.name + '.json';
370395

@@ -379,9 +404,9 @@ export class CodeSnippetEditor extends ReactWidget {
379404
await showDialog({
380405
title: 'Duplicate Name of Code Snippet',
381406
body: <p> {`"${newPath}" already exists.`} </p>,
382-
buttons: [Dialog.cancelButton()]
407+
buttons: [Dialog.okButton({ label: 'Dismiss' })]
383408
});
384-
return;
409+
return false;
385410
}
386411

387412
// set new name as an old name
@@ -396,18 +421,20 @@ export class CodeSnippetEditor extends ReactWidget {
396421
await showDialog({
397422
title: 'Duplicate Name of Code Snippet',
398423
body: <p> {`"${newPath}" already exists.`} </p>,
399-
buttons: [Dialog.cancelButton()]
424+
buttons: [Dialog.okButton({ label: 'Dismiss' })]
400425
});
401426
}
402427
})
403428
.catch(() => {
404429
nameCheck = true;
405430
});
406431
if (!nameCheck) {
407-
return;
432+
return false;
408433
}
409434
}
410435

436+
this.saved = true;
437+
411438
await this.contentsService.save(newPath, {
412439
type: 'file',
413440
format: 'text',
@@ -446,6 +473,7 @@ export class CodeSnippetEditor extends ReactWidget {
446473
if (this._codeSnippetEditorMetaData.fromScratch) {
447474
this.dispose();
448475
}
476+
return true;
449477
}
450478

451479
handleChangeOnTag(selectedTags: string[], allTags: string[]): void {

0 commit comments

Comments
 (0)