Created
June 19, 2016 17:16
-
-
Save bwiernik/3e515f368872943ec12de524753217d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Based on batch editing script from zuphilip | |
How does this work? | |
0) make a backup copy | |
1) create a collection of all entries you want to randomly sample | |
(maybe use a smart search or drag and drop, delete individual items) | |
2) check that you have exactly the items you want to change in your collection | |
3) choose one example here and adapt it to your needs | |
4) run the code | |
5) save the log if needed | |
*/ | |
// Example 1: set a fixed value in a field | |
// (the field must be a simple field) | |
var action = 'set'; | |
var field = 'callNumber'; // puts the sample index in the Call Number field | |
var weights = [0.96, 0.04]; // enter the probablity of being not-sampled and sampled (sum to 1) | |
var results = [0, 1]; // values for not-sampled and sampled | |
function getRandom () { | |
var num = Math.random(), | |
s = 0, | |
lastIndex = weights.length - 1; | |
for (var i = 0; i < lastIndex; ++i) { | |
s += weights[i]; | |
if (num < s) { | |
return results[i]; | |
} | |
} | |
return results[lastIndex]; | |
}; | |
var items = []; | |
var fieldID = Zotero.ItemFields.getID(field); | |
var selectedCollection = ZoteroPane.getSelectedCollection(); | |
var selectedSavedSearch = ZoteroPane.getSelectedSavedSearch(); | |
if (!selectedCollection && !selectedSavedSearch) { | |
alert('Select a Collection or Saved Search first'); | |
} | |
if (selectedCollection) { | |
items = selectedCollection.getChildItems(); | |
if (!confirm('Do you want to change these ' + items.length + ' items in collection ' + selectedCollection.name + '?')) { | |
items = []; | |
} | |
} | |
if (selectedSavedSearch) { | |
var ids = selectedSavedSearch.search(); | |
for (var k=0; k<ids.length; k++) { | |
items[k] = Zotero.Items.get(ids[k]); | |
} | |
if (!confirm('Do you want to change these ' + items.length + ' items in collection ' + selectedSavedSearch.name + '?')) { | |
items = []; | |
} | |
} | |
for (var i=0; i<items.length; i++) { | |
//set single fields | |
if ( fieldID && Zotero.ItemFields.isValidForType(fieldID, items[i].itemTypeID) ) { | |
var content = items[i].getField(field); | |
var updatedValue = getRandom(); | |
console.log(items[i].itemID + ' : ' + field + ' : ' + content + ' -> ' + updatedValue); | |
items[i].setField(field, updatedValue); | |
items[i].save(); | |
continue; | |
} | |
console.log(items[i].itemID + ' : type ' + items[i].itemTypeID + ' : field ' + field + ' untouched' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment