language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
2,603
2.953125
3
[]
no_license
Since version **1.39.0** the Scanbot SDK for Android provides a simple and convenient API ([`PDFRenderer`](https://scanbotsdk.github.io/documentation/android/api/io.scanbot.sdk/io/scanbot/sdk/process/PDFRenderer.html)) to create PDF document files. The `PDFRenderer` supports multi-page PDFs where each given image will be stored as a PDF page. Furthermore you can specify the physical output page size (e.g. A4, US Letter, Auto). Get an instance of `PDFRenderer` from `ScanbotSDK`: ``` import io.scanbot.sdk.ScanbotSDK; import io.scanbot.sdk.process.PDFRenderer; import io.scanbot.sdk.process.PDFPageSize; PDFRenderer pdfRenderer = new ScanbotSDK(this).pdfRenderer(); ``` Then you can create a PDF file from `Page` objects stored by our **RTU UI** components (e.g. result from the `DocumentScannerActivity`): ``` List<io.scanbot.sdk.persistence.Page> pages = ...; File pdfFile = pdfRenderer.renderDocumentFromPages(pages, PDFPageSize.FIXED_A4); ``` Please note: The PDF Renderer uses the **document image** (cropped image) of a `Page` object. So make sure all `Page` objects contain document images. Or alternatively create a PDF file from arbitrary image files (JPG or PNG) provided as file URIs: ``` List<android.net.Uri> imageFileUris = ...; // ["file:///some/path/file1.jpg", "file:///some/path/file2.jpg", ...] File pdfFile = pdfRenderer.renderDocumentFromImages(imageFileUris, PDFPageSize.FIXED_A4); ``` You can specify one of the following [`PDFPageSize`s](https://scanbotsdk.github.io/documentation/android/api/io.scanbot.sdk/io/scanbot/sdk/process/PDFPageSize.html) as output size: - `A4`: The page has the aspect ratio of the image, but is fitted into A4 size. Whether portrait or landscape depends on the images aspect ratio. - `FIXED_A4`: The page has A4 size. The image is fitted and centered within the page. Whether portrait or landscape depends on the images aspect ratio. - `US_LETTER`: The page has the aspect ratio of the image, but is fitted into US letter size. Whether portrait or landscape depends on the images aspect ratio. - `FIXED_US_LETTER`: The page has US letter size. The image is fitted and centered within the page. Whether portrait or landscape depends on the images aspect ratio. - `AUTO`: For each page the best matching format (A4 or US letter) is used. Whether portrait or landscape depends on the images aspect ratio. - `AUTO_LOCALE`: Each page of the result PDF will be of US letter or A4 size depending on the current locale. Whether portrait or landscape depends on the images aspect ratio. - `FROM_IMAGE`: Each page is as large as its image at 72 dpi.
JavaScript
UTF-8
36,220
2.640625
3
[]
no_license
var numShownConcert = 0; function drawSeatCurve(){ var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.lineWidth="5"; ctx.strokeStyle="green"; ctx.moveTo(150,50); ctx.arcTo(150,250,250,250,100); ctx.arcTo(350,250,350,150,100); ctx.lineTo(350,50); ctx.stroke(); } function showSeatInfo2(seatdiv){ var seatinfodiv = document.getElementById("seatinfo"); //alert(seatinfostr); //seatinfodiv.innerHTML = seatinfostr; //doesn't work if passing this as the parameter // the problem lies in "title", which is to be replaced by "data-title" /* var seatinfostr = seatdiv.getAttribute("title"); */ var seatinfostr = seatdiv.getAttribute("data-title"); seatinfodiv.children[1].innerHTML = seatinfostr + "<br />Price: $" + document.getElementById('priceNum').value; seatinfodiv.style.display = "block"; var seatint = seatdiv.id.substring(seatdiv.id.lastIndexOf('_') + 1, seatdiv.id.length); document.getElementById("currentSeatint").value = seatint; //pass the integer value of seatid var lastseatid = document.getElementById("currentSeatid").value; document.getElementById("currentSeatid").value = seatdiv.id; $('#seatinfo').css("display", "block"); document.getElementById(seatdiv.id).style.background = "green"; document.getElementById(lastseatid).style.background = "silver"; // this statement is not effective for the first time running, and should never be followed by any other statements. /* var currentseatid = seatdiv.getAttribute("data-id"); */ /* $('#seatinfo').css("display", "none"); */ /* document.getElementById("btnAddToCart").setAttribute("data-id") = "" + currentseatid; */ //setAttribute seems not work } function showSeatInfo(seatinfostr){ var seatinfodiv = document.getElementById("seatinfo"); //alert(seatinfostr); //seatinfodiv.innerHTML = seatinfostr; //doesn't work if passing this as the parameter seatinfodiv.children[1].innerHTML = seatinfostr; seatinfodiv.style.display = "block"; } function addSeatDot(){ var seatbody = document.getElementById("modal-body"); var seatdiv; seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:110px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 1"); seatdiv.setAttribute("data-id", "1"); seatdiv.setAttribute("id", "seat1_1"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:130px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 2"); seatdiv.setAttribute("data-id", "2"); seatdiv.setAttribute("id", "seat1_2_2"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:150px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 3"); seatdiv.setAttribute("data-id", "3"); seatdiv.setAttribute("id", "seat1_3_3"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:170px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 4"); seatdiv.setAttribute("data-id", "4"); seatdiv.setAttribute("id", "seat1_4_4"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:190px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 5"); seatdiv.setAttribute("data-id", "5"); seatdiv.setAttribute("id", "seat1_5_5"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:210px;left:330px;"); seatdiv.setAttribute("data-title", "Row 1, Column 6"); seatdiv.setAttribute("data-id", "6"); seatdiv.setAttribute("id", "seat1_6_6"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:230px;left:335px;"); seatdiv.setAttribute("data-title", "Row 1, Column 7"); seatdiv.setAttribute("data-id", "7"); seatdiv.setAttribute("id", "seat1_7_7"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:248px;left:344px;"); seatdiv.setAttribute("data-title", "Row 1, Column 8"); seatdiv.setAttribute("data-id", "8"); seatdiv.setAttribute("id", "seat1_8_8"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:265px;left:355px;"); seatdiv.setAttribute("data-title", "Row 1, Column 9"); seatdiv.setAttribute("data-id", "9"); seatdiv.setAttribute("id", "seat1_9_9"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:280px;left:368px;"); seatdiv.setAttribute("data-title", "Row 1, Column 10"); seatdiv.setAttribute("data-id", "10"); seatdiv.setAttribute("id", "seat1_10_10"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:293px;left:386px;"); seatdiv.setAttribute("data-title", "Row 1, Column 11"); seatdiv.setAttribute("data-id", "11"); seatdiv.setAttribute("id", "seat1_11_11"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:303px;left:406px;"); seatdiv.setAttribute("data-title", "Row 1, Column 12"); seatdiv.setAttribute("data-id", "12"); seatdiv.setAttribute("id", "seat1_12_12"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:308px;left:432px;"); seatdiv.setAttribute("data-title", "Row 1, Column 13"); seatdiv.setAttribute("data-id", "13"); seatdiv.setAttribute("id", "seat1_13_13"); seatbody.appendChild(seatdiv); //seat on the right seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:110px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 26"); seatdiv.setAttribute("data-id", "26"); seatdiv.setAttribute("id", "seat1_26_26"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:130px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 25"); seatdiv.setAttribute("data-id", "25"); seatdiv.setAttribute("id", "seat1_25_25"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:150px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 24"); seatdiv.setAttribute("data-id", "24"); seatdiv.setAttribute("id", "seat1_24_24"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:170px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 23"); seatdiv.setAttribute("data-id", "23"); seatdiv.setAttribute("id", "seat1_23_23"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:190px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 22"); seatdiv.setAttribute("data-id", "22"); seatdiv.setAttribute("id", "seat1_22_22"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:210px;left:560px;"); seatdiv.setAttribute("data-title", "Row 1, Column 21"); seatdiv.setAttribute("data-id", "21"); seatdiv.setAttribute("id", "seat1_21_21"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:230px;left:555px;"); seatdiv.setAttribute("data-title", "Row 1, Column 20"); seatdiv.setAttribute("data-id", "20"); seatdiv.setAttribute("id", "seat1_20_20"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:248px;left:546px;"); seatdiv.setAttribute("data-title", "Row 1, Column 19"); seatdiv.setAttribute("data-id", "19"); seatdiv.setAttribute("id", "seat1_19_19"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:265px;left:535px;"); seatdiv.setAttribute("data-title", "Row 1, Column 18"); seatdiv.setAttribute("data-id", "18"); seatdiv.setAttribute("id", "seat1_18_18"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:280px;left:522px;"); seatdiv.setAttribute("data-title", "Row 1, Column 17"); seatdiv.setAttribute("data-id", "17"); seatdiv.setAttribute("id", "seat1_17_17"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:293px;left:504px;"); seatdiv.setAttribute("data-title", "Row 1, Column 16"); seatdiv.setAttribute("data-id", "16"); seatdiv.setAttribute("id", "seat1_16_16"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:303px;left:484px;"); seatdiv.setAttribute("data-title", "Row 1, Column 15"); seatdiv.setAttribute("data-id", "15"); seatdiv.setAttribute("id", "seat1_15_15"); seatbody.appendChild(seatdiv); seatdiv = document.createElement("div"); seatdiv.setAttribute("class", "seatdot"); seatdiv.setAttribute("style", "top:308px;left:458px;"); seatdiv.setAttribute("data-title", "Row 1, Column 14"); seatdiv.setAttribute("data-id", "14"); seatdiv.setAttribute("id", "seat1_14_14"); seatbody.appendChild(seatdiv); var seatdivs = document.getElementsByClassName("seatdot"); for(var i = 0; i < seatdivs.length; i++) { /* var seatinfostr = "Row 1, Column " + (i+1); */ var seatinfostr = seatdivs[i].getAttribute('title'); seatdivs[i].setAttribute("data-toggle", "tooltip"); /* seatdivs[i].setAttribute("title", seatinfostr); */ /* seatdivs[i].setAttribute("onclick", "showSeatInfo('" + seatinfostr + "<br />Price:" + "');"); */ seatdivs[i].setAttribute("onclick", "showSeatInfo2(this);"); } } function showOrderHistory(){ var userid = ''; $.ajax({ url: 'php/getUserid.php', async: false, success: function(data) { userid = data; } }); $.get("php/getOrderHistory.php", {userid:userid}, function(mydata){ if (mydata != ' '){ var jsonarray = mydata.split('<br>'); for(var i=0;i<jsonarray.length; i++){ // get the information of order var sorder = JSON.parse(jsonarray[i]); var sorder_oid = sorder.orderid; var sorder_pay = sorder.paytime; $.get("php/getAllSuborder.php", {orderid:sorder_oid}, function(mydata){ if (mydata != ' '){ showOrderHistorySub(mydata); } else{ window.location.href = "index.html"; //alert('Your cart is empty.'); } }); } } else{ alert('Your order history is empty.'); } }); } function showOrderHistorySub(mydata){ var jsonarray = mydata.split('<br>'); var concertInfo = JSON.parse(jsonarray[0]); var sorder_oid = concertInfo.orderid; var sorder_pay = concertInfo.paytime; var n = jsonarray.length; var nt = n-1; var content = ''; var totalPrice = 0; for(var i=0;i<nt; i++){ var concertInfo = JSON.parse(jsonarray[i]); var sorder_cname = concertInfo.concertname; var sorder_row = concertInfo.row; var sorder_col = concertInfo.col; var sorder_price = concertInfo.price; totalPrice += parseInt(sorder_price); var content_s = "Concert Name: " + sorder_cname + "<br>" +"Seat Row: " + sorder_row + "<br>Seat Column: " + sorder_col + "<br>Price: $" + sorder_price + "<br>"; content += content_s; } var order_1 = document.createElement("div"); order_1.className = "panel panel-primary"; var order_2 = document.createElement("div"); order_2.className = "panel-heading"; order_2.innerHTML = "Order Number: " + sorder_oid; var order_3 = document.createElement("div"); order_3.className = "panel-body"; order_3.style.background = "white"; var order_4 = document.createElement("div"); order_4.className = "row"; var order_5 = document.createElement("div"); order_5.className = "col-sm-2"; var order_6 = document.createElement("p"); order_6.innerHTML = "Total Price: <br>$"+totalPrice+"<br>Pay Time: <br>"+sorder_pay; order_6.style.color = "black"; var order_7 = document.createElement("div"); order_7.className = "col-sm-10"; var order_8 = document.createElement("div"); order_8.className = "panel panel-info"; var order_9 = document.createElement("p"); order_9.innerHTML = content; order_9.style.color = "black"; order_9.style.marginLeft = "10px"; order_1.appendChild(order_2); order_2.appendChild(order_3); order_3.appendChild(order_4); order_4.appendChild(order_5); order_4.appendChild(order_7); order_5.appendChild(order_6); order_7.appendChild(order_8); order_8.appendChild(order_9); document.getElementById("historyShowContainer").appendChild(order_1); } // show selected suborders total price function showSelectedOrder(isChecked, concertPriceT){ //alert(concertPrice); var price = document.getElementById("priceSum").innerHTML; var ticket = document.getElementById("ticketSum").innerHTML; var concertPrice = concertPriceT.substring(7); if (isChecked == true){ var addSum = +price + +concertPrice; document.getElementById("priceSum").innerHTML = addSum; var addSumTicket = parseInt(ticket) + 1; document.getElementById("ticketSum").innerHTML = addSumTicket.toString(); }else{ var redSum = +price - +concertPrice; document.getElementById("priceSum").innerHTML = redSum; var redSumTicket = parseInt(ticket) - 1; document.getElementById("ticketSum").innerHTML = redSumTicket.toString(); } } function checkOut() { var orderid = ''; $.ajax({ url: 'php/getorderid.php', async: false, success: function(data) { orderid = data; } }); // alert(orderid); $.get("php/getCart.php", {orderid:orderid}, function(mydata){ if (mydata != ' '){ var checklist = document.getElementsByClassName("cartSelect"); var selected = 0; for(var i = 0; i < checklist.length; i++){ // remove those unselected suborder if(checklist[i].checked){ selected = selected + 1; } } if (selected == 0){ alert("Please select tickets you want to buy."); } else{ for(var i = 0; i < checklist.length; i++){ if(!checklist[i].checked){ var totalInfo = checklist[i].getAttribute("value"); var removeinfo = totalInfo.substring(0,6); deleteSuborder(removeinfo); } } checkOutUpdate(orderid); } } else{ window.location.href = "index.html"; //alert('Your cart is empty.'); } }); } // checkout order, change status = 1, and increase the max orderid by 1, a new order. function checkOutUpdate(orderid){ $.get("php/checkOut.php", {orderid:orderid}, function(mydata){ if (mydata != 'true'){ alert('Check out error: ' + mydata); } else{ $.get("php/updateOrderid.php", function(mydata){ window.open('success.html', '_self',false); }); } }); } // remove suborder and refresh the page function deleteSuborder(mydata){ var concertid = mydata.substring(0,3); var seatid = mydata.substring(4,6); $.get("php/deleteConcert.php", {concertid:concertid,seatid:seatid}, function(mydata){ if (mydata == "true") { //alert("Your ticket has been deleted."); //window.location.reload(true); } else{ alert('error deleting suborder: ' + mydata); window.location.reload(true); } }); } // get current unpaid suborders in cart function showCart() { var orderid = ''; $.ajax({ url: 'php/getorderid.php', async: false, success: function(data) { orderid = data; } }); $.get("php/getCart.php", {orderid:orderid}, function(mydata){ if (mydata != ' '){ var jsonarray = mydata.split('<br>'); for(var i=0;i<jsonarray.length; i++){ // get the information of order var sorder = JSON.parse(jsonarray[i]); var sorder_oid = sorder.orderid; var sorder_cid = sorder.concertid; var sorder_sid = sorder.seatid; showOrder(sorder_cid, sorder_sid); } } else{ window.location.href = "index.html"; //alert('Your cart is empty.'); } }); } // show each unpaid orders in cart function showOrder(sorder_cid, sorder_sid){ var seat_row = ''; var seat_col = ''; // get seat information $.get("php/getSeatInfo.php", {seatid:sorder_sid}, function(mydata){ if (mydata != ' '){ //alert(mydata); var jsonarray_s = mydata.split('<br>'); var seatIF = JSON.parse(jsonarray_s[0]); seat_row = seatIF.row; seat_col = seatIF.col; } else{ alert('Can not find the seat.'); } }); // get concert information $.get("php/getConcert.php", {concertid:sorder_cid}, function(mydata){ if (mydata != ' '){ var jsonarray_c = mydata.split('<br>'); // only one concert info. var concertInfo = JSON.parse(jsonarray_c[0]); var concertName = concertInfo.concertname; var concertImage = concertInfo.image; var concertPrice = concertInfo.price; var order_1 = document.createElement("div"); order_1.className = "panel panel-info"; var order_2 = document.createElement("div"); order_2.className = "panel-heading"; order_2.innerHTML = concertName; var order_3 = document.createElement("div"); order_3.className = "checkbox"; order_3.style.cssFloat = "right"; order_3.style.marginTop = "3px"; var order_4 = document.createElement("div"); order_4.style.cssFloat = "right"; order_4.style.marginTop = "3px"; order_4.style.marginRight = "40px"; var order_5 = document.createElement("input"); order_5.setAttribute("type", "checkbox"); order_5.setAttribute("class", "cartSelect"); order_5.setAttribute("value", sorder_cid+","+sorder_sid+","+concertPrice); order_5.setAttribute("onclick", "showSelectedOrder(this.checked, this.value);"); var order_6 = document.createElement("button"); order_6.setAttribute("class", "glyphicon glyphicon-remove-sign cartRemove"); order_6.setAttribute("style", "float:right;margin-top:3px;margin-right:20px;"); order_6.setAttribute("value", sorder_cid+","+sorder_sid); order_6.setAttribute("onclick", "deleteSuborder(this.value);"); var order_12 = document.createElement("span"); order_12.innerHTML = "Delete"; order_12.setAttribute("style", "float:right;margin-top:3px;margin-right:5px;"); var order_13 = document.createElement("p"); order_13.innerHTML = "Select"; order_13.setAttribute("style", "float:right;margin-top:3px;margin-right:80px;"); var order_7 = document.createElement("div"); order_7.className = "panel-body"; var order_8 = document.createElement("img"); order_8.src = concertImage; //alert(order_8.src); order_8.className = "img-responsive"; order_8.height = "30px"; order_8.alt = "IMAGE"; var order_9 = document.createElement("div"); order_9.className = "panel-footer"; order_9.style.textAlign = "right"; var order_10 = document.createElement("button"); order_10.innerHTML="View Seat"; order_10.setAttribute("data-target", "#myModal"); order_10.setAttribute("data-toggle", "modal"); order_10.setAttribute("class", "btn btn-warning btnSeat"); order_10.setAttribute("data-id", sorder_cid); var order_11 = document.createElement("span"); order_11.innerHTML = "SEAT ROW: " + seat_row + ", SEAT COLUMN: " + seat_col + ", PRICE: $" + concertPrice; order_11.style.cssFloat = "left"; order_1.appendChild(order_2); order_2.appendChild(order_3); order_2.appendChild(order_4); order_3.appendChild(order_6); order_3.appendChild(order_12); order_3.appendChild(order_13); order_3.appendChild(order_5); order_2.appendChild(order_7); order_7.appendChild(order_8); order_2.appendChild(order_9); order_9.appendChild(order_11); order_9.appendChild(order_10); document.getElementById("orderShowContainer").appendChild(order_1); $('.btnSeat').click(function(){ bindSeatClick($(this)); }); } else{ alert('Can not find the the concert.'); } }); } function bindSeatClick(thisone){ $('#seatinfo').css("display", "none"); $.get("php/isloggedin.php", function(mydata){ if (mydata != "true") { alert('You have to Login!'); window.open('login.html'); window.location.reload(true); return; } }); var concertid = thisone.data('id'); /* $('#musicTitle').text('Concert ID: ' + concertid); */ $('#currentConcertId').val('' + concertid); $('.seatdot').css("background", "silver").css("pointer-events", "auto"); var orderid = ''; $.ajax({ url: 'php/getorderid.php', async: false, success: function(data) { orderid = data; } }); $.get("php/seatinfo.php", {id:concertid}, function(mydata){ /* $('#musicTitle').text(data); */ var jsonarray = mydata.split('<br>'); /* $('#musicTitle').text(mydata); */ var musicdata = JSON.parse(jsonarray[0]); $('#musicTitle').text(musicdata.concertname); $('#priceNum').val(musicdata.price); for(var i=1;i<jsonarray.length; i++) { var seatinfo = JSON.parse(jsonarray[i]); var seatid = 'seat1_' + seatinfo.seatid + '_' + seatinfo.seatid; // check seat table to determine the row and col id $('#' + seatid).css("background", "#EDE275").css("pointer-events", "none"); if (orderid == seatinfo.orderid) { $('#' + seatid).css("background", "green").css("pointer-events", "none"); } } }); } //Anqi function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function getNumOfShownConcert(filename, parameter){ $.ajax({ data: {value: parameter}, type: "POST", url: filename, async: false, success: function(data){ var jsonarray = data.split('<br>'); numShownConcert = jsonarray.length - 1; }, error: function () { alert("fail"); } }); } function loadConcert(pageNum, filename, parameter){ var concertList = $(".concert_block"); for(var i = 0; i < concertList.length; ++i){ $(concertList[i]).hide(); $(".concertName").hide(); } $.ajax({ data: {value: parameter}, type: "POST", url: filename, async: false, success: function(data){ var jsonarray = data.split('<br>'); for(var j = 0, i = (pageNum - 1)*4; j < concertList.length && i < jsonarray.length - 1; ++i, ++j){ var obj = JSON.parse(jsonarray[i]); var qs = "editproduct.html?concertid="+obj.concertid; $(concertList[j]).find("img").attr('data-id', obj.concertid); $(concertList[j]).find("img").attr('src',obj.image); $(concertList[j]).find("button").attr('data-id', obj.concertid); $(concertList[j]).find("a").attr('href', qs); $(concertList[j]).find("a").attr('data-id', obj.concertid); var concertname = $('<span>'); concertname.addClass("concertName"); concertname.append(obj.concertname); $(concertList[j]).find("a").after(concertname); $(concertList[j]).show(); } }, error: function () { alert("error loading concert info"); } }); } function getCurrentPageNum(){ var s = getUrlVars(); if(window.location.href.indexOf('?') !== -1 && typeof(s['page']) !== 'undefined' ){ return parseInt(s['page']); } else{ return 1; } } function getCurrentTimeInterval(){ var s = getUrlVars(); if(window.location.href.indexOf('?') !== -1 && typeof(s['interval']) !== 'undefined'){ return parseInt(s['interval']); } else{ return -1; } } function getCurrentKeyWord(){ var s = getUrlVars(); if(window.location.href.indexOf('?') !== -1 && typeof(s['keyword']) !== 'undefined'){ var keyword = s['keyword']; var s = decodeURIComponent(keyword); s = $.trim(s); return s; } else{ return ""; } } function createPageButton(tag, numPage){ var list = document.createElement("li"); list.setAttribute("class", "pageButton"); var link = document.createElement("a"); var interval = getCurrentTimeInterval(); var keyword = getCurrentKeyWord(); link.innerHTML = tag; if(tag === '&laquo'){ var num = getCurrentPageNum(); if(num === 1){ num = numPage; } else{ num = num - 1; } link.setAttribute("href", "index.html?page="+num+"&interval="+interval+"&keyword="+keyword); } else if(tag === '&raquo'){ var num = getCurrentPageNum(); if(num === numPage){ num = 1; } else { num = num + 1; } link.setAttribute("href", "index.html?page="+num+"&interval="+interval+"&keyword="+keyword); } else{ if(getCurrentPageNum() === tag){ link.style.color = "red";; } else{ link.setAttribute("href", "index.html?page="+tag+"&interval="+interval+"&keyword="+keyword); } } list.appendChild(link); var page = document.getElementById("page"); page.appendChild(list); return link; } function createPagination(numPage){ createPageButton('&laquo', numPage); for(var i = 0; i < numPage; ++i){ createPageButton(i+1, numPage); } createPageButton('&raquo', numPage); } function hidePagination(){ var pageButtonList = $(".pageButton"); for(var i = 0; i < pageButtonList.length; ++i){ $(pageButtonList[i]).hide(); } } function loadConcertChoice(){ var interval = getCurrentTimeInterval(); var keyword = getCurrentKeyWord(); if(interval === -1 && keyword === ''){ //time interval and search keyword not set getNumOfShownConcert('php/loadConcertInfo.php'); if(numShownConcert % 4 === 0){ numPage = numShownConcert / 4; } else{ numPage = Math.floor(numShownConcert / 4) + 1; } //get current page number var pageNum = getCurrentPageNum(); //load all concert info for selected page loadConcert(pageNum, 'php/loadConcertInfo.php', interval); } else if(keyword === ''){ //time interval set, keyword not set getNumOfShownConcert('php/filterConcert_time.php', interval); if(numShownConcert % 4 === 0){ numPage = numShownConcert / 4; } else{ numPage = Math.floor(numShownConcert / 4) + 1; } var pageNum = getCurrentPageNum(); loadConcert(pageNum, 'php/filterConcert_time.php', interval); if(interval === 3){ $("#location").html("Within 3 days"); } else if(interval === 7){ $("#location").html("Within a week"); } else if(interval === 30){ $("#location").html("Within a months"); } else if(interval === 90){ $("#location").html("Within 3 months"); } else{ $("#location").html("Within 6 months"); } var span = $('<span />').addClass('caret'); $("#location").append(span); } else{ //keyword set, time interval not set getNumOfShownConcert('php/filterConcert_keyword.php', keyword); if(numShownConcert % 4 === 0){ numPage = numShownConcert / 4; } else{ numPage = Math.floor(numShownConcert / 4) + 1; } var pageNum = getCurrentPageNum(); loadConcert(pageNum, 'php/filterConcert_keyword.php', keyword); $("#keyword").val(keyword); } } $(document).ready(function(){ loadConcertChoice(); $("#searchButton").click(function(){ var keyword = $("#keyword").val(); var s = encodeURIComponent(keyword); window.location.href = "index.html?keyword="+s; }); $('[data-toggle="tooltip"]').tooltip(); $('#location').next().find("a").click(function(){ $('#location').html($(this).text() + '<span class=\'caret\'></span>'); }); //$("#login").hide(); //$("#logout").hide(); //$("#AddConcert").hide(); //$("#loadCart").hide(); //$("#loadHistory").hide(); //alert('hide'); $.ajax({ url: 'php/welcome.php', success: function(data){ if($.trim(data) === 'Login'){ //$("#login").show(); $(".btnEdit").html('Learn more'); $("#login").css('display', 'block'); $("#loadCart").css('display', 'none'); $("#loadHistory").css('display', 'none'); $("#logout").css('display', 'none'); } else{ $("#logout").append(data); //$("#logout").show(); $("#login").css('display', 'none'); $("#logout").css('display', 'block'); $("#loadCart").css('display', 'block'); $("#loadHistory").css('display', 'block'); $.ajax({ url: 'php/check_authority.php', success:function(data){ if($.trim(data) === 'admin'){ //$("#AddConcert").show(); $("#AddConcert").css('display', 'block'); } else{ $(".btnEdit").html('Learn more'); $("#AddConcert").css('display', 'none'); } }, error: function (data) { //alert('error checking authority: ' + data); } }); } }, error: function (data) { alert('error loading welcome info: ' + data); } }); $("#logout").click(function(){ $.ajax({ url: 'php/session_destroy.php', success: function(){ window.location.href = "index.html"; }, error: function (data) { alert('error logout: ' + data); } }); }); $('#rangePrice').change(function(){ $('#txtPrice').val($(this).val()); }); $('#txtPrice').blur(function(){ $('#rangePrice').val($(this).val()); }); $('.btnSeat').click(function(){ bindSeatClick($(this)); }); $('#btnAddToCart').click(function(){ $.get("php/isloggedin.php", function(mydata){ if (mydata != "true") { alert('You have to Login Again!'); window.open('login.html'); return; } }); var concertid = $('#currentConcertId').val(); var seatint = $('#currentSeatint').val(); $.get("php/addtocart.php", {concert:concertid, seat:seatint}, function(mydata){ if (mydata == 'true') { alert('Your seat is added to cart'); window.location.reload(true); /* window.opener.history.go(0);window.close(); */ } else { alert('error when adding to cart: ' + mydata); } }); }); // qianying $('#loadCart').click(function(){ $.get("php/isloggedin.php", function(mydata){ if (mydata != "true") { alert('You have to Login Again!'); window.open('login.html'); window.location.reload(true); return; } }); window.open('cart.html','_self',false); }); $('#loadHistory').click(function(){ $.get("php/isloggedin.php", function(mydata){ if (mydata != "true") { alert('You have to Login Again!'); window.open('login.html'); window.location.reload(true); return; } }); window.open('history.html','_self',false); }); // change the number item in cart $.ajax({ url: 'php/getCartno.php', async: false, success: function(data) { $("#cartno").html(data); //alert(data); } }); });
Go
UTF-8
969
3.515625
4
[ "Apache-2.0" ]
permissive
package gomock import ( "github.com/golang/mock/gomock" "testing" "time" ) func TestFoo(t *testing.T) { ctrl := gomock.NewController(t) // Assert that Bar() is invoked. defer ctrl.Finish() m := NewMockFoo(ctrl) // Asserts that the first and only call to Bar() is passed 99. // Anything else will fail. m. EXPECT(). Bar(gomock.Eq(99)). Return(101) r := SUT(m) if r != 101 { t.Fail() } } func TestFoo2(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := NewMockFoo(ctrl) // Does not make any assertions. Executes the anonymous functions and returns // its result when Bar is invoked with 99. m. EXPECT(). Bar(gomock.Eq(99)). DoAndReturn(func(_ int) int { time.Sleep(1 * time.Second) return 101 }). AnyTimes() // Does not make any assertions. Returns 103 when Bar is invoked with 101. m. EXPECT(). Bar(gomock.Eq(101)). Return(103). AnyTimes() r := SUT(m) if r != 101 { t.Fail() } }
PHP
UTF-8
3,383
3.078125
3
[]
no_license
<?php //$conn is connection function in db_connect.php for connection //DataBase name 'trial'.'trial1' //name of Content in data base are id,Email, Name, Message, Date include('config/db_connect.php'); $email=$name=$message=''; $errors=array('email'=>'','name'=>'','message'=>''); if(isset($_POST['submit'])) { $email=htmlspecialchars($_POST['email']); $name=htmlspecialchars($_POST['name']); $message=htmlspecialchars($_POST['message']); //Check Email if(empty($_POST['email'])) { $errors['email']='A e-mail is required'; } //check name Should not be empty or Number OR Special Characters if(empty($_POST['name'])) { $errors['name']='A name is required'; } else{ if(!preg_match('/^[a-zA-Z\s]+$/',$name)){ $errors['name']='A valid name is require'; } } //Check message Should Not be Empty if(empty($_POST['message'])) { $errors['message']='A message is required'; } //Checking all Errors if(array_filter($errors)) { //echo 'Some Error in Form'; }else{ $email=mysqli_real_escape_string($conn,$_POST['email']); $name=mysqli_real_escape_string($conn,$_POST['name']); $message=mysqli_real_escape_string($conn,$_POST['message']); //create sql for data entry $sql="INSERT INTO trial1(Email,name,message) VALUES('$email','$name','$message')"; //Send Data to DataBase then move to submit.php to display if(mysqli_query($conn,$sql)){ header('Location:submit.php'); }else{ echo 'Failed to Inserted'.mysqli_error($conn); } // if form Completetly valid Move To submit.php header('Location:submit.php'); } } ?> <!--PHP End--> <!--HTML Page Start--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="./css/style.css"> <title>form</title> </head> <body> <h1 class="text-center">Form using PHP</h1> <form class="container form border" action="index.php" method="POST"> <div class="form-group"> <label for="exampleInputEmail1">Email address:</label> <input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> <div class="text-danger"><?php echo $errors['email'];?></div> </div> <div class="form-group"> <label for="exampleInputtext1">Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <div class="text-danger"><?php echo $errors['name'];?></div> </div> <div class="form-group"> <label for="exampleInputtext1">Message:</label> <input type="text" class="form-control" id="message" name="message" placeholder="Enter Your Meassage"> <div class="text-danger"><?php echo $errors['message'];?></div> </div> <button type="submit" name="submit"class="btn btn-primary">Submit</button> </form> </body> </html>
Java
UTF-8
1,802
3.3125
3
[]
no_license
package GameLogic.State; import GameLogic.UI.Log; import GameLogic.UI.UIColors; public abstract class Unit { protected String name; protected int maxHP; protected int currHP; protected transient Log log; protected int baseAttack; protected int baseDamageRange; public Unit(String name, int maxHP, int baseAttack, int baseDamageRange, Log log){ this.name = name; this.maxHP = maxHP; this.currHP = maxHP; this.baseAttack = baseAttack; this.baseDamageRange = baseDamageRange; this.log = log; } public void takeDamage(int dmg) throws YouDied{ takeDamage(dmg, ""); } public void takeDamage(int dmg, String attackTarget) throws YouDied{ int taken = calculateDamageTaken(dmg, attackTarget); this.currHP -= taken; log.print(name + " took "); log.printlnColored(taken + " damage", UIColors.DAMAGE_RED); if(currHP <= 0) { log.println(name+" was slain"); throw new YouDied(this); } } protected void restoreHP(int amount){ currHP+=amount; if(currHP > maxHP) currHP = maxHP; } public void reportStats(){ int colorPick = (int)(((double)currHP)/((double)maxHP) * 10)-1; System.out.println(colorPick); log.printlnColored("HP: "+currHP+"/"+maxHP, UIColors.HEALTH_GRADIENT[colorPick]); log.println("Weapon: "+calculateDamageDealt()+" attack"); if(this instanceof Player) log.println("Armor: "+((Player)this).calculateDefenseValue()); } public String getName() { return name; } public abstract int calculateDamageDealt(); public abstract int calculateDamageTaken(int dmg, String attackTarget) throws YouDied; }
C++
UTF-8
5,366
2.609375
3
[ "BSD-3-Clause" ]
permissive
// Include files // ============================================================================ // STD&STL // ============================================================================ #include <functional> // ============================================================================ // ROOT // ============================================================================ #include "TH1.h" #include "TGraph.h" #include "TAxis.h" // ============================================================================ // Ostap // ============================================================================ #include "Ostap/HistoHash.h" // ============================================================================ // Local // ============================================================================ #include "local_hash.h" // ============================================================================ /** @file * implementation file for function from the file Ostap/HistoHash.h * @date 2021-04-09 * @author Vanya Belyaev Ivan.Belyaev@itep.ru */ // ============================================================================ /* get hash for the given graph * @param graph the graphs * @return hash value */ // ============================================================================ std::size_t Ostap::Utils::hash_graph ( const TGraph* graph ) { if ( nullptr == graph ) { return 0 ; } const Int_t N = graph->GetN() ; // std::size_t seed = N ; // const Double_t* X = graph->GetX () ; if ( X ) { seed = std::hash_combine ( seed , std::hash_range ( X , X + N ) ) ; } // const Double_t* Y = graph->GetY () ; if ( Y ) { seed = std::hash_combine ( seed , std::hash_range ( Y , Y + N ) ) ; } // const Double_t* EX = graph->GetEX () ; if ( EX ) { seed = std::hash_combine ( seed , std::hash_range ( EX , EX + N ) ) ; } // const Double_t* EY = graph->GetEY () ; if ( EY ) { seed = std::hash_combine ( seed , std::hash_range ( EY , EY + N ) ) ; } // const Double_t* EXh = graph->GetEXhigh () ; if ( EXh ) { seed = std::hash_combine ( seed , std::hash_range ( EXh , EXh + N ) ) ; } // const Double_t* EXl = graph->GetEXlow () ; if ( EXl ) { seed = std::hash_combine ( seed , std::hash_range ( EXl , EXl + N ) ) ; } // const Double_t* EYh = graph->GetEYhigh () ; if ( EYh ) { seed = std::hash_combine ( seed , std::hash_range ( EYh , EYh + N ) ) ; } // const Double_t* EYl = graph->GetEYlow () ; if ( EYl ) { seed = std::hash_combine ( seed , std::hash_range ( EYl , EYl + N ) ) ; } // const Double_t* EXhd = graph->GetEXhighd () ; if ( EXhd ) { seed = std::hash_combine ( seed , std::hash_range ( EXhd , EXhd + N ) ) ; } // const Double_t* EXld = graph->GetEXlowd () ; if ( EXld ) { seed = std::hash_combine ( seed , std::hash_range ( EXld , EXld + N ) ) ; } // const Double_t* EYhd = graph->GetEYhighd () ; if ( EYhd ) { seed = std::hash_combine ( seed , std::hash_range ( EYhd , EYhd + N ) ) ; } // const Double_t* EYld = graph->GetEYlowd () ; if ( EYld ) { seed = std::hash_combine ( seed , std::hash_range ( EYld , EYld + N ) ) ; } // return seed ; } // ============================================================================ /* get hash for the given axis * @param axis the axis * @return hash value */ // ============================================================================ std::size_t Ostap::Utils::hash_axis ( const TAxis* axis ) { if ( nullptr == axis ) { return 0 ; } // std::size_t seed = std::hash_combine ( axis -> GetNbins () , axis -> GetXmin () , axis -> GetXmax () ) ; // const TArrayD* A = axis->GetXbins() ; if ( A ) { const Double_t* a = A->GetArray() ; if ( a ) { seed = std::hash_combine ( seed , a , a + A ->GetSize () ) ; } } // return seed ; } // ============================================================================ /* get hash for the given histogram * @param histo the historgam * @return hash value */ // ============================================================================ std::size_t Ostap::Utils::hash_histo ( const TH1* histo ) { if ( nullptr == histo ) { return 0 ; } // const Int_t NX = histo -> GetNbinsX () ; const Int_t NY = histo -> GetNbinsY () ; const Int_t NZ = histo -> GetNbinsZ () ; // std::size_t seed = std::hash_combine ( histo->Hash() , NX , NY , NZ ) ; // seed = std::hash_combine ( seed , hash_axis ( histo->GetXaxis() ) ) ; seed = std::hash_combine ( seed , hash_axis ( histo->GetYaxis() ) ) ; seed = std::hash_combine ( seed , hash_axis ( histo->GetZaxis() ) ) ; // for ( int ix = 1 ; ix <= NX ; ++ix ) { for ( int iy = 1 ; iy <= NY ; ++iy ) { for ( int iz = 1 ; iz <= NZ ; ++iz ) { seed = std::hash_combine ( seed , histo->GetBinContent ( ix , iy , iz ) , histo->GetBinError ( ix , iy , iz ) ) ; } } } // return seed ; } // ============================================================================ // The END // ============================================================================
Markdown
UTF-8
1,500
2.734375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: DevCon Dp_delete description: Deletes a third-party (OEM) driver package from the driver store on the local computer. This command deletes the INF file, the PNF file, and the associated catalog file (.cat). keywords: - DevCon Dp_delete Driver Development Tools topic_type: - apiref ms.topic: reference api_name: - DevCon Dp_delete api_type: - NA ms.date: 10/28/2022 --- # DevCon Dp_delete > [!NOTE] > [PnPUtil](pnputil.md) ships with every release of Windows and makes use of the most reliable and secure APIs available. We recommend using PnPUtil instead of DevCon. See the [Recommended replacement](#recommended-replacement) below and [Replacing DevCon](devcon-migration.md) for more information. Deletes a third-party (OEM) driver package from the driver store on the local computer. This command deletes the INF file, the PNF file, and the associated catalog file (.cat). ```command devcon [-f] dp_delete inf ``` ## Parameters **-f** This parameter deletes the driver package even if a device is using it at the time. *inf* The OEM\*.inf file name of the INF file. Windows assigns a file name with this format to the INF file when you add the driver package to the driver store, such as by using [**DevCon dp_add**](devcon-dp-add.md). ## Recommended replacement ``` console pnputil /delete-driver inf ``` For more recommended replacements, see [Replacing DevCon](devcon-migration.md). ## Sample usage ```command devcon dp_delete oem2.inf devcon -f dp_delete oem0.inf ```
Markdown
UTF-8
1,309
2.59375
3
[]
no_license
--- layout: page title: People permalink: /people/ --- We have some great people working at the Dean Lab - meet some of them below. {% raw %} <div class="container"> <div class="row"> {% endraw %} {% for person in site.people %} {% if person.imageid %} {% capture imageurl %}https://res.cloudinary.com/{{site.cloudinary_id}}/image/upload/b_rgb:4892d1,c_lpad,h_350,q_100,w_500/{{person.imageid}}{% endcapture %} {% elsif person.imageurl %} {% capture imageurl %}{{person.imageurl}}{% endcapture %} {% else %}{% capture imageurl %}http://res.cloudinary.com/codegaucho/image/upload/c_scale,w_256/v1381379684/ecibwsnz20ljfshmscy5{% endcapture %} {% endif %} <div class="col-sm-4"> <div class="card"> <img alt="100%x200" class="card-img-top img-responsive" style="display: block;" src="{{ imageurl }}"> <div class="card-block"> <h3 class="card-title"><a href="{{ person.permalink }}">{{ person.name }}</a></h3> <h4>{{ person.title }}</h4> <p class="card-text">{{ person.description }}</p> <p class="card-text"><small class="text-muted"><a href="{{ person.permalink }}">More...</a></small></p> </div><!-- card-block --> </div><!-- card --> </div><!-- col-sm-4 --> {% endfor %} {% raw %} </div><!-- row --> </div><!-- container --> {% endraw %}
C#
UTF-8
2,980
2.765625
3
[]
no_license
using Discord.Commands; using Discord.Models; using Discord.WebSocket; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Discord { public class PersonaService { private readonly SemaphoreSlim SlowStuffSemaphore = new SemaphoreSlim(1, 1); private string _dataDirectory { get; } private string _personaFile => Path.Combine(_dataDirectory, "personas.json"); // DiscordSocketClient and CommandService are injected automatically from the IServiceProvider public PersonaService() { _dataDirectory = Path.Combine(AppContext.BaseDirectory, "data"); if (!Directory.Exists(_dataDirectory)) Directory.CreateDirectory(_dataDirectory); if (!File.Exists(_personaFile)) File.Create(_personaFile).Dispose(); } public AddStatus AddPersona(ulong userId, string eauserId, string personaId) { SlowStuffSemaphore.WaitAsync(); var result = AddStatus.Success; try { // Deserialize current personas var personas = JsonConvert.DeserializeObject<List<Persona>>(File.ReadAllText(_personaFile)); // Null check personas = personas ?? new List<Persona>(); // Check if current user already has a persona saved var persona = personas.FirstOrDefault(x => x.DiscordUserId == userId); if (persona != null) { persona.PersonaId = personaId; persona.EAUserId = eauserId; result = AddStatus.Overwritten; } else { personas.Add(new Persona { DiscordUserId = userId, EAUserId = eauserId, PersonaId = personaId }); result = AddStatus.Success; } // Save the changes File.WriteAllText(_personaFile, JsonConvert.SerializeObject(personas)); } catch (Exception e) { Console.WriteLine(e.Message); result = AddStatus.Fail; } finally { SlowStuffSemaphore.Release(); } return result; } public bool TryGetPersonaId(ulong userId, out Persona persona) { try { // Deserialize current personas var personas = JsonConvert.DeserializeObject<List<Persona>>(File.ReadAllText(_personaFile)); // Search for persona persona = personas.FirstOrDefault(x => x.DiscordUserId == userId); return persona != null; } catch (Exception e) { Console.WriteLine(e.Message); persona = null; return false; } } } }
Python
UTF-8
3,182
2.609375
3
[]
no_license
import re import os import datetime from ._base import Reader from .post import Post import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter class MyRenderer(mistune.Renderer): def block_code(self, code, lang=None): if not lang: return '\n<pre><code>%s</code></pre>\n' % \ mistune.escape(code) try: lexer = get_lexer_by_name(lang, stripall=True) except: lexer = get_lexer_by_name('javascript', stripall=True) formatter = HtmlFormatter() return highlight(code, lexer, formatter) class MarkDownReader(Reader): """ Parse *.mkd """ renderer = MyRenderer() md = mistune.Markdown(renderer) __allow_suffix__ = ['.md', '.mkd', '.mdown', '.markdown'] title_pattern = re.compile(ur'<h1>(.+?)</h1>') meta_pattern = re.compile(ur'<li>(.+?)</li>', re.M) def run(self): input_files = filter(lambda f: (os.path.splitext(f)[-1] in self.__allow_suffix__) and (not os.path.basename(f).startswith('_')), self.input_files) for f in input_files: parsed = self._parse_content(f) p = Post(parsed) p.set_perm_link(self.calc_perm_link(p)) self.app.posts.append(p) self.app.posts.sort(key=lambda post: post.meta.get('_date'), reverse=True) def _parse_content(self, file_path): fd = open(file_path, 'rb') header = '' body = '' recording = True for line in fd: if recording and line.startswith('---'): recording = False elif recording: header += line.decode('utf-8') else: body += line.decode('utf-8') fd.close() header = mistune.markdown(header) body = self.md.render(body) try: title = self.title_pattern.findall(header)[0] meta = self.meta_pattern.findall(header) except: from ._base import MarkDownReaderException e = MarkDownReaderException('Post parse exception on file: %s' % file_path) raise e meta_dict = dict(title=title) for m in meta: try: key, value = m.split(':', 2) # only * key: value will be saved as Post attribute if key == 'date': date = self._parse_date(value.strip()) meta_dict['_date'] = date meta_dict['date'] = date.strftime('%Y-%m-%d') meta_dict['year'] = date.year meta_dict['month'] = date.month meta_dict['day'] = date.day meta_dict[key.strip()] = value.strip() except: pass meta_dict.setdefault('file_name', os.path.basename(file_path)) return dict( meta=meta_dict, body=body ) @staticmethod def _parse_date(s): date = datetime.datetime.strptime(s, '%Y-%m-%d') return date
Python
UTF-8
469
2.640625
3
[]
no_license
import unittest from december17 import Solver class TestDec17(unittest.TestCase): def test_examples(self): (one, two) = Solver(from_file='input/dec17-sample.in').solve(25) self.assertEqual(one, 4) self.assertEqual(two, 3) def test_solution(self): (one, two) = Solver(from_file='input/dec17.in').solve(150) self.assertEqual(one, 4372) self.assertEqual(two, 4) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
1,792
2.984375
3
[]
no_license
DFS: ~~~python # 递归: visited = set() def dfs(node, visited): # terminator if node in visited: # already visited return # not visited visited.add(node) # process current node ... for next_node in node.children(): if next_node not in visited: dfs(next_node, visited) # 非递归 def DFS(self, root): if root is None: return [] visited, stack = set(), [root] while stack: node = stack.pop() visited.add(node) process(node) nodes = generate_related_nodes(node) stack.push(nodes) ~~~ BFS: ~~~python def BFS(graph, start, end): visited = set() queue = collections.deque() queue.append([start]) while queue: node = queue.pop() visited.add(node) process(node) nodes = generate_related_nodes(node) queue.append(nodes) .... ~~~ 贪心算法: 在每一步选择中都采取在当前状态下最好或最优的选择,从而希望导致结果是全局最好或最优的算法 贪心算法与动态规划的不同在于它对每个子问题的解决方案都做出选择,不能回退,动态规划则会`保存`以前的运算结果,并根据`以前的结果`对当前选择,有回退功能。 贪心:当下做出局部最优判断 回溯:能够回退 动态规划:最优判断 + 回退 贪心:图中的最小生成树、哈夫曼编码,一般做一些辅助算法。 二分查找: ~~~python left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if target == nums[mid]: # find target elif target < nums[mid]: right = mid - 1 else: left = mid + 1 ~~~
C#
UTF-8
1,373
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Prototype { class Program { static void Main(string[] args) { #region Ver 1 var resume1 = new Resume("Adam"); resume1.SetPersonalInfo("Male", "29"); resume1.SetWorkExperience("1998-2000", "HP"); var resume2 = new Resume("Scott"); resume2.SetPersonalInfo("Male", "29"); resume2.SetWorkExperience("1998-2000", "Microsoft"); var resume3 = new Resume("Jason"); resume3.SetPersonalInfo("Male", "29"); resume3.SetWorkExperience("1998-2000", "EMC"); resume1.Display(); resume2.Display(); resume3.Display(); #endregion #region Ver 2 & 3 & 4 //var resume1 = new Resume("Adam"); //resume1.SetPersonalInfo("Male", "29"); //resume1.SetWorkExperience("1998-2000", "HP"); //var resume2 = (Resume)resume1.Clone(); //resume2.SetWorkExperience("1998-2000", "Microsoft"); //var resume3 = (Resume)resume1.Clone(); ; //resume3.SetPersonalInfo("Male", "24"); //resume1.Display(); //resume2.Display(); //resume3.Display(); #endregion } } }
Java
UTF-8
281
2.5625
3
[]
no_license
package May18; public class Person { String name; float height; char gender; static String race = "Human"; static int counter ; //int counter ; public Person() { counter++ ; } public Person(String name, float height, char gender) { this.name = name; } }
C#
UTF-8
1,130
2.90625
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private WeaponFactory weaponFactory = new WeaponFactory(); private IWeapon _currentWeapon; private List<IWeapon> _allMyWeapons = new List<IWeapon>(); public WeaponsType WeaponsType; void Start() { _allMyWeapons.Add(weaponFactory.CreateItem(5,WeaponsType.ClassicWeapon)); _allMyWeapons.Add(weaponFactory.CreateItem(10,WeaponsType.M16)); _currentWeapon = _allMyWeapons [0]; } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { _currentWeapon.Interact(); } if (Input.GetKeyDown(KeyCode.Q)) { AddBullets(10,WeaponsType); } } private void AddBullets(int bullets,WeaponsType type) { foreach (var item in _allMyWeapons) { if (item.WeaponsType == type) { item.CurrentBulletsCount += bullets; Debug.Log("Add " + bullets + " bulets to" + type); } } } }
Java
UTF-8
1,921
2.296875
2
[]
no_license
//--------------------------------------------------------------------------------------- // Copyright (c) 2001-2013 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- package pdftron.PDF.Tools; import android.app.AlertDialog; import android.content.Context; import android.widget.CheckBox; import android.widget.LinearLayout; class DialogTextSearchOption extends AlertDialog { private Context mContext; private CheckBox mWholeWord; private CheckBox mCaseSensitive; private CheckBox mUseReg; public DialogTextSearchOption(Context context) { super(context); mContext = context; setTitle("Text Search Options"); LinearLayout main_layout = new LinearLayout(mContext); main_layout.setOrientation(LinearLayout.VERTICAL); main_layout.setPadding(5, main_layout.getPaddingTop(), main_layout.getPaddingRight(), main_layout.getPaddingRight()); mWholeWord = new CheckBox(mContext); mWholeWord.setText("Whole word"); mCaseSensitive = new CheckBox(mContext); mCaseSensitive.setText("Case sensitive"); mUseReg = new CheckBox(mContext); mUseReg.setText("Regular expressions"); main_layout.addView(mCaseSensitive); main_layout.addView(mWholeWord); main_layout.addView(mUseReg); setView(main_layout); } public boolean getWholeWord() { return mWholeWord.isChecked(); } public boolean getCaseSensitive() { return mCaseSensitive.isChecked(); } public boolean getRegExps() { return mUseReg.isChecked(); } public void setWholeWord(boolean flag) { mWholeWord.setChecked(flag); } public void setCaseSensitive(boolean flag) { mCaseSensitive.setChecked(flag); } public void setRegExps(boolean flag) { mUseReg.setChecked(flag); } }
SQL
UTF-8
107
2.640625
3
[]
no_license
select books.title from books, publisher where publisher.id = books.publisher and publisher.name = "PHI";
Java
UTF-8
958
3.65625
4
[]
no_license
package com.liad.guessnumber; import java.util.Scanner; /* * Author: Liad Hermelin */ public class GuessNumberMenu { // asks for limit, starts game public static void main(String[] args) { boolean shouldContinue = true; GuessNumber guesser = new GuessNumber(); Scanner kboard = new Scanner(System.in); do { System.out.print("Would you like to play? ---> "); switch (kboard.next().toUpperCase()) { case "YES": case "YE": case "YS": case "Y": System.out.print("Enter an end-value for the random number (exclusive) ---> "); int max = kboard.nextInt(); int randNum = guesser.getRandom(max); guesser.guess(randNum, max); break; case "NOPE": case "NAH": case "NO": case "N": System.out.println("Quitting now."); kboard.close(); shouldContinue = false; break; default: System.out.println("I'm sorry, that wasn't an option! Please try again."); } } while (shouldContinue); } }
JavaScript
UTF-8
120
2.8125
3
[]
no_license
let coding= ["coding15","coding16","coding17",] console.log(coding) let prenom= coding.push("Seb") console.log(prenom)
C
UTF-8
664
3.359375
3
[]
no_license
// main source code https://stackoverflow.com/questions/3585846/color-text-in-terminal-applications-in-unix #include <stdio.h> #define RED "\x1B[31m" #define GRN "\x1B[32m" #define YEL "\x1B[33m" #define BLU "\x1B[34m" #define MAG "\x1B[35m" #define CYN "\x1B[36m" #define WHT "\x1B[5;37m" #define RESET "\x1B[0m" int main() { printf(RED "red\n" RESET); printf(GRN "green\n" RESET); printf(YEL "yellow\n" RESET); printf(BLU "blue\n" RESET); printf(MAG "magenta\n" RESET); printf(CYN "cyan\n" RESET); printf(WHT "white\n" RESET); printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n"); return 0; }
Java
UTF-8
712
3.4375
3
[]
no_license
package rushikesh.string; public class StringPro2 { void getCountOfRepeat(String input){ String[] arr=input.split(" "); int maxFrequency=0; int count=0; String repeatWord = "", tempVar; for(int index=0;index<arr.length;index++) { count=0; tempVar = arr[index]; for(int index1=0;index1<arr.length;index1++) { if(tempVar.equals(arr[index1])) count++; } if(maxFrequency<count) { maxFrequency=count; repeatWord=arr[index]; } } System.out.println(repeatWord+"-"+maxFrequency); } public static void main(String[] args) { StringPro2 stringPro1=new StringPro2(); String input = "Hi Hello Hi Techno Hello Hi"; stringPro1.getCountOfRepeat(input); } }
C#
UTF-8
3,929
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using DBI_Grading.Model.Teacher; namespace DBI_Grading.Utils { internal static class StringUtils { internal static string GetNumbers(this string input) { while (input.Length > 0 && !char.IsDigit(input[input.Length - 1])) input = input.RemoveAt(input.Length - 1); var position = input.Length - 1; if (position == -1) return input; while (position != -1) { position--; if (position == -1) break; if (!char.IsNumber(input[position])) break; } return position == -1 ? input : input.Remove(0, position + 1); } internal static string RemoveAt(this string s, int index) { return s.Remove(index, 1); } /// <summary> /// </summary> /// <param name="input"></param> /// <param name="oldValue">in lowercase</param> /// <param name="newValue"></param> /// <returns></returns> public static string ReplaceByLine(string input, string oldValue, string newValue) { var list = input.Split('\n'); var output = ""; for (var i = 0; i < list.Length; i++) { var tmp = Regex.Replace(list[i], @"\s+", ""); if (tmp.ToLower().Equals(oldValue)) list[i] = newValue; output = string.Concat(output, "\n", list[i]); } return output; } internal static int GetHammingDistance(string s, string t) { if (s.Length != t.Length) throw new Exception("Strings must be equal length"); var distance = s.ToCharArray() .Zip(t.ToCharArray(), (c1, c2) => new {c1, c2}) .Count(m => m.c1 != m.c2); return distance; } public static List<TestCase> GetTestCases(string input, Candidate candidate) { var matchPoint = Regex.Match(input, @"(/\*(.|[\r\n])*?\*/)|(--(.*|[\r\n]))", RegexOptions.Singleline); var matchQuery = Regex.Match(input + "/*", @"(\*/(.|[\r\n])*?/\*)|(--(.*|[\r\n]))", RegexOptions.Multiline); var queryList = new List<string>(); while (matchQuery.Success) { queryList.Add(matchQuery.Value.Split('/')[1].Trim()); matchQuery = matchQuery.NextMatch(); } var tcpList = new List<TestCase>(); var count = 0; var tcp = new TestCase(); while (matchPoint.Success) { var matchFormatted = matchPoint.Value.Split('*')[1]; if (count++ % 2 == 0) { tcp.RatePoint = double.Parse(matchFormatted, CultureInfo.InvariantCulture); } else { tcp.Description = matchFormatted; tcp.TestQuery = queryList.ElementAt(count - 1); tcpList.Add(tcp); tcp = new TestCase(); } matchPoint = matchPoint.NextMatch(); } if (tcpList.Count == 0) tcpList.Add(new TestCase { TestQuery = input, Description = "", RatePoint = candidate.Point }); return tcpList; } public class TestCase { public double RatePoint { get; set; } public string Description { get; set; } public string TestQuery { get; set; } } } }
C++
UTF-8
4,186
2.65625
3
[]
no_license
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->actionExit->setText("Exit"); ui->actionLoad->setText("Load"); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(close())); connect(ui->actionLoad, SIGNAL(triggered()), this,SLOT(loadButton())); connect(ui->actionClear, SIGNAL(triggered()), this, SLOT(clearButton())); connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(saveButton())); connect(ui->tableWidget, SIGNAL( cellPressed (int, int) ), this, SLOT( cellSelected( int, int ) ) ); clearButton(); } void MainWindow::cellSelected(int nRow, int nCol) { if(mode == 0){ printAndSave(nRow, nCol, 0); } if(mode == 1){ printAndSave(nRow, nCol, 1); } if(mode == 2){ printAndSave(nRow, nCol, 2); } } MainWindow::~MainWindow(){ delete ui; } void MainWindow::clearButton(){ for(int i = 0; i< MAX ; i++){ for(int j = 0; j < MAX; j++){ printOnScreen(i, j, Qt::white); printAndSave(i,j,0); } } } void MainWindow::loadButton(){ QString charFromMap; int x = 0; int y = 0; filename = QFileDialog::getOpenFileName(this, ("Open File"), NULL, ("Data (*.txt)")); QFile file(filename); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); while(!file.atEnd()) { QString line = in.readAll(); for(int i = 0; i < line.length(); i++) { charFromMap = line.at(i); charFromMap.remove("\n"); if(x >= MAX) { x = 0; y++; } int number = charFromMap.toStdString().c_str()[0] - '0'; if(number == FREE || number == OBSTACLE || number == ATW) { MapObjects[x][y] = number; x++; \ } } } file.close(); } showOnBoard(); } void MainWindow::saveButton(){ filename = QFileDialog::getSaveFileName(this, ("Save File"), NULL, tr("Data (*.txt)")); QFile output(filename); output.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&output); QString type; int enter = 0; for(int y = 0; y < MAX; y++) { for(int x = 0; x < MAX; x++) { if(enter == MAX){ out << '\n'; enter = 0; } out << QString::fromStdString(std::to_string(MapObjects[x][y])) << ' '; enter++; } } } void MainWindow::printOnScreen(int x, int y, QColor color){ ui->tableWidget->setItem(x,y, new QTableWidgetItem()); ui->tableWidget->item(x,y)->setBackgroundColor(color); } void MainWindow::showOnBoard(){ for(int y = 0; y < MAX; y++){ for(int x = 0; x < MAX; x++){ if(MapObjects[x][y] == FREE){ printOnScreen(x, y, Qt::white); } else if(MapObjects[x][y] == OBSTACLE) { printOnScreen(x, y, Qt::red); } else if(MapObjects[x][y] == ATW){ printOnScreen(x,y, Qt::black); } } } } void MainWindow::on_radioButton_clicked(bool checked) //set cell free { if(checked){ mode = 0; } else{ mode = 10; } } void MainWindow::on_radioButton_2_clicked(bool checked) //set obstacle {\ if(checked){ mode = 1; } else{ mode = 10; } } void MainWindow::on_radioButton_3_clicked(bool checked) //set Atv in cell { if(checked){ mode = 2; } else{ mode = 10; } } void MainWindow::printAndSave(int x, int y, int color){ if(color == 1){ printOnScreen(x, y, Qt::red); MapObjects[x][y] = 1; } if(color == 0){ printOnScreen(x, y, Qt::white); MapObjects[x][y] = 0; } if(color == 2){ printOnScreen(x, y, Qt::black); MapObjects[x][y] = 2; } }
Python
UTF-8
345
4.34375
4
[]
no_license
#Factorial Function def factorial(n): #End Loop if n == 0: return 1 #Recursively Multiply else: return n * factorial(n - 1) #Initial SUM = 0 #Find 100! and convert to string x = str(factorial(100)) #Length of x leng = len(x) #Iterate Over Digits for i in range(leng): SUM += int(x[i]) #Output print SUM
Java
UTF-8
3,160
2.34375
2
[]
no_license
package database.DAO; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Transaction; import androidx.room.Update; import java.util.ArrayList; import model.Exercice; import model.referencesClass.CalculAndUtilisateur; import model.referencesClass.ExerciceAndUtilisateur; import model.referencesClass.QCMAndUtilisateur; import model.referencesClass.UtilisateurAndCalcul; import model.referencesClass.UtilisateurAndExercice; import model.referencesClass.UtilisateurAndQCM; import model.referencesClass.UtilisateurExerciceCrossReference; @Dao public abstract class UtilisateurExerciceCrossRefDAO { @Insert public abstract void insert(UtilisateurExerciceCrossReference utilisateurExerciceCrossReference); @Insert public abstract long[] insertAll(UtilisateurExerciceCrossReference... utilisateurExerciceCrossReference); @Delete public abstract void delete(UtilisateurExerciceCrossReference utilisateurExerciceCrossReference); @Update public abstract void update(UtilisateurExerciceCrossReference utilisateurExerciceCrossReference); // Partie Utilistaurs -> Exercices // @Transaction public UtilisateurAndExercice getUtilisateurWithExercice(String nom, String prenom) { UtilisateurAndExercice retour = new UtilisateurAndExercice(); retour.exercices = new ArrayList<>(); UtilisateurAndCalcul calculs = getUtilisteurAndCalcul(nom, prenom); if(calculs != null) { retour.exercices.addAll(calculs.calculs); } UtilisateurAndQCM qcms = getUtilisateurAndQCM(nom, prenom); if(qcms != null) { retour.exercices.addAll(qcms.qcms); } return retour; } @Transaction @Query("SELECT * FROM utilisateur WHERE nom = :nom AND prenom = :prenom") abstract UtilisateurAndCalcul getUtilisteurAndCalcul(String nom, String prenom); @Transaction @Query("SELECT * FROM utilisateur WHERE nom = :nom AND prenom = :prenom") abstract UtilisateurAndQCM getUtilisateurAndQCM(String nom, String prenom); // Partie Exercices -> Utilisateurs // @Transaction public ExerciceAndUtilisateur getExerciceWithUtilisateur(int exerciceId) { ExerciceAndUtilisateur retour = new ExerciceAndUtilisateur(); retour.utilisateurs = new ArrayList<>(); CalculAndUtilisateur calculsUtilisateurs = getCalculWithUtilisateur(exerciceId); if(calculsUtilisateurs != null) { retour.utilisateurs.addAll(calculsUtilisateurs.utilisateurs); } QCMAndUtilisateur qcmAndUtilisateur = getQCMWithUtilisateur(exerciceId); if(qcmAndUtilisateur != null) { retour.utilisateurs.addAll(qcmAndUtilisateur.utilisateurs); } return retour; } @Query("SELECT * FROM calcul WHERE exerciceId = :exerciceId") abstract CalculAndUtilisateur getCalculWithUtilisateur(int exerciceId); @Query("SELECT * FROM qcm WHERE exerciceId = :exerciceId") abstract QCMAndUtilisateur getQCMWithUtilisateur(int exerciceId); }
Markdown
UTF-8
6,577
3.25
3
[]
no_license
# Frontend Submission In this document, I'll be describing some design decisions I made during this process. ## Tools Used I decided to use the following tools to complete this project: - HTML5 + CSS3 - JavaScript (ES5) + jQuery ## The Approach Both HTML5 and CSS3 have broad cross-browser support these days, so that's what I decided to use. I also made sure to run the CSS code through an Autoprefixer (PostCSS) to maximize cross-browser compatibility. Running the code through PostCSS is something I usually do in a build step with a tool such as Webpack. I avoided, however, bringing those tools into this project to keep things simple. Ah -- and speaking of tools I didn't get to use, I must admit I missed working with a CSS preprocessor such as Sass. But again, for the sake of simplicity, I left it out as well. ### About semantic markup and technical decisions I also ran the code through a few automated accessibility auditing tools. Those are always helpful to make sure we're not robbing users who require extra assistance from having a fantastic experience. My main concern about accessibility in a project like this is its dynamic nature (such as dynamically navigating through the Baby Steps). If we were in an SPA environment (or even an entirely server-side rendered web page), then screen readers would know to parse the new content once our URLs change. When we don't, however, have a formal indication that the page was updated, things get trickier for screen readers to do their job correctly and help visually impaired users to take full advantage of our app. To address this concern, I also opted to keep things simple. The page is fully operational without CSS or JavaScript running. I am using URL hash-links to navigate through the different portions of the content. Using hash-links to jump through content is a feature that has been available in web browsers for several decades, so I thought that was a safe choice. ### CSS Decisions Within the CSS, I decided to use a style for naming classes that resembles the BEM architecture. I use the word resembles very loosely here as it doesn't include the long class names BEM often requires. Semantical component hierarchy, however, was still kept on top of mind, while keeping the naming of elements straightforward (e.g., `.babysteps`, and `.babysteps-content`). I also tried to resemble the feel of using Bootstrap 4, by including a few utility classes. I like utility classes because they make it easy to customize the styling of one-off elements without having to create a whole new rule to avoid collision with similar elements. ### Le JavaScripts I kept all of the JavaScript code compliant with ES5 standards so that it would run well in older browsers such as IE9. I also ran the code through a linter, to make sure I didn't miss any semicolons or polyfills that would have prevented the page from running for some users in a real-life app. For production apps, I use automated tools in a build step and a CI environment to assist me with this type of mundane tasks, so I'm able to focus on delivering a fantastic experience to our final users and let computers do what computers do best -- repetitive tasks. That said, this experience made me realize how far we have come with our tooling and even the evolution of the JavaScript language itself. ES2015+ makes me a more productive engineer, which is fun to acknowledge now looking in hindsight and thinking of how much I hesitated before adopting it for most of my projects. jQuery, by the way, is a life saver. I thought for a little bit about not using it at all and just relying on some `document.querySelector()` calls to get the work done. I probably could have done that, but adopting jQuery made me move a lot faster without having to worry about browser compatibility or polyfills. ### Code Organization I tried my best to organize my code in a way that was easy to understand. In other circumstances, I would have separated some of those function calls into separate files and would have also further divided the maintenance of application state and data handling from tasks that have to do with updating the view. The way I usually approach these things, even when the tools aren't available, is I try my best to imagine I was unit-testing my code. I have found that writing tests tend to make some necessary abstractions more obvious. One example of that in this project was when I had to sort the list of friends by their last names. It would have been easy to do it inline where the XHR call was made and not think much of it. But then I thought "what if I were writing this in TDD fashion?". If that were the case, I would have wanted to write a test for the friends sorting functionality in isolation so that we can test that feature independently of others. This was how I concluded that it needed to be in its own function that did one job, and one job only. ## Compromises Even though I tried my best to maximize cross-browser compatibility, there were a few places where I intentionally made it so that the experience was a little more geared towards modern browsers. Once particular place where that happened were the animations of the Baby Step links on the left menu. You see, I've been taking advantage of this little trick lately where you use box-shadows instead of background-colors for hover and/or active states. Box-shadows are cool because they're easy to do simple animations with using CSS transitions (you can see some examples on my personal website, try hovering any underlined links on https://sergio.io). The trick itself worked well in all of the browsers -- you can't tell we're using a `box-shadow` to change the color of the background instead of the `background-color` property just by looking at it. What didn't work in IE9 specifically was the button animation when the app state updates from one Baby Step to another. The content itself animates perfectly as it relies on jQuery to scroll between elements. ## Browser Support I used BrowserStack to test this app on the following browsers: - Chrome (latest) - Firefox (latest) - Safari (latest, _PS: I swear Safari is the "new internet explorer," I wouldn't be surprised if there were older versions of Safari that I didn't get to test_) - Internet Explorer (v. 9+) - Microsoft Edge (latest) ## Feedback Got any feedback? Please feel free to reach out to me about them. I'd love a chance to make things right if there was anything I missed. ## Thank you Thanks for your time in reading this and reviewing the code!
Markdown
UTF-8
764
2.84375
3
[]
no_license
# Learn jQuery - it's fun! ## Instructions #### Complete these tasks using jQuery. No adding classes or IDs! (but...there's a bug. Where art thou, jQuery?) 1. Change the page title text's font 2. Make a button that changes the background color 3. Change Snow White's picture when you hover over her 4. Add a horizontal line after all of the paragraphs 5. Make something happen every two seconds 6. Make the text of the first paragraph the same as the last paragraph 7. Make a text box, and change the background to the value of that text box when the button from #3 is clicked 8. If the background color is green, change the image and if it's not green, keep the original image 9. Use a jQuery plugin 10. Make the picture draggable using jQuery UI
Python
UTF-8
4,951
3.734375
4
[]
no_license
import os from math import gcd from random import randint def is_prime(n): """ This function receives a number - n. It returns whether n is prime or not. Time complexity is O(n**0.5) in the worst case. """ if n == 2 or n == 3: return True elif n < 2 or n % 2 == 0 or n % 3 == 0: return False # Looping until i reaches the square root of n for i in range(4, int(n ** 0.5) + 1): if n % i == 0: return False return True def write_list_to_file(l, file): """ This function receives two parameters - l and file. l is a list which will be written to the file . """ for item in l: file.write(str(item) + ",") def generate_prime_file(a, path=''): """ This function creates a list of prime numbers under the upper boundary denoted as a. It will also write the list to a file. If the path parameter is not passed in, it will create a new text file in the working directory. Otherwise, the list will be written to the path passed in. """ prime_list = [i for i in range(a + 1) if is_prime(i)] if path == '': try: primes_file = open("primes.txt", "wt", encoding='utf-8') except Exception as e: print(e) else: write_list_to_file(prime_list, primes_file) finally: primes_file.close() else: if os.path.exists(path): try: primes_file = open(path, "wt", encoding='utf-8') except Exception as e: print(e) else: write_list_to_file(prime_list, primes_file) finally: primes_file.close() else: try: primes_file = open("primes.txt", "wt", encoding='utf-8') except Exception as e: print(e) else: write_list_to_file(prime_list, primes_file) finally: primes_file.close() def generate_primes(path): """ This function receives a path of a file. The file will contain prime numbers which will be read into a list. The function returns two different random prime numbers - p and q. If an error occurs, p and q will be -1 in default. """ p, q = -1, -1 try: file = open(path, "rt", encoding='utf-8') except Exception as e: print(e) else: chunk_size = 256 prime_list = file.read(chunk_size) while True: content = file.read(chunk_size) if not content: break prime_list += content prime_list = prime_list.split(',') prime_list = prime_list[:-2] while True: q = int(prime_list[randint(0, len(prime_list) - 1)]) p = int(prime_list[randint(0, len(prime_list) - 1)]) if p != q: break finally: file.close() return p, q def generate_keys(): """ This function generates the private and public keys. It uses the generate_primes function. """ path = input("Enter the path of the file you are reading from the prime numbers:\t") p, q = generate_primes(path) # Creating the modulus - n n = p * q # Creating the totient - phi phi = (p - 1) * (q - 1) # Creating the public key e = randint(2, phi - 1) # Looping until e is relatively prime to phi while True: if gcd(e, phi) == 1: break e = randint(2, phi - 1) # Creating the private key k = 1 while True: d = (1 + k * phi) / e if d - int(d) == 0: d = int(d) break k += 1 return (e, n), (d, n) def encrypt(message, pub_key): """ This function receives a message to encrypt and a public-key(denoted by pub_key). It returns a string which represents the encrypted message. """ e, n = pub_key cipher = [ord(c) for c in message] cipher = [(c ** e % n) for c in cipher] string_cipher = [chr(c) for c in cipher] string_cipher = ''.join(string_cipher) return string_cipher def decrypt(string_cipher, pri_key): """ This function receives a message(string_cipher) to decrypt and a private-key(pri_key). It returns a string which represents the original message. """ d, n = pri_key cipher = [ord(s) for s in string_cipher] cipher = [(s ** d % n) for s in cipher] decrypted_data = [chr(s) for s in cipher] decrypted_data = ''.join(decrypted_data) return decrypted_data def main(): generate_prime_file(800) pri_key, pub_key = generate_keys() message = input("Enter a message to decrypt:\t") encrypted_data = encrypt(message, pub_key) print("Encrypted data:\t{}".format(encrypted_data)) print("Decrypted data:\t{}".format(decrypt(encrypted_data, pri_key))) if __name__ == '__main__': main()
PHP
UTF-8
593
2.671875
3
[ "MIT" ]
permissive
<?php namespace App\Services; use Illuminate\Support\Facades\DB; class AutoBrowserService { /** * 获取所有浏览器 */ public function getBrowsers() { return DB::select ( "select id,chrBrowserName as browserName,chrBrowserENName browserENName from auto_exec_browsers where intFlag=0" ); } /** * 根据浏览器ID 查询指定的某些浏览器 * * @param unknown $browserIds */ public function getBrowserByID($browserIds) { return DB::select ( "select id,chrBrowserENName browserENName from auto_exec_browsers where id in ($browserIds)" ); } } ?>
C#
UTF-8
1,867
3.53125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BankAccount { class Program { static void Main(string[] args) { var account = new Account("David", 5000, 13); Console.WriteLine($"Account {account.AccountNumber} was created for {account.Owner} with {account.Balance} balance."); account.MakeWithdrawal(500, DateTime.Now, "Rent payment"); account.MakeDeposit(100, DateTime.Now, "friend paid me back"); account.AddInterests(0.10, DateTime.Now, "rate is increese 10"); Console.WriteLine(account.AccountHistory()); // Test exceptions try { var invalidAccount = new Account("invalid", -80, 12); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Exception caught creating account with negative balance"); Console.WriteLine(e.ToString()); } // Test for a negative balance try { account.MakeWithdrawal(750, DateTime.Now, "Attempt to overdraw"); } catch (InvalidOperationException e) { Console.WriteLine("Exception caught trying to overdraw"); Console.WriteLine(e.ToString()); } try { account.AddInterests(23, DateTime.Now, "Interest rate is out of range!"); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Exception caught using high rate"); Console.WriteLine(e.ToString()); } Console.ReadLine(); } } }
Java
UTF-8
4,124
1.609375
2
[]
no_license
package com.askgps.personaltrackercore; import com.askgps.personaltrackercore.config.ConfigKt; import com.askgps.personaltrackercore.database.model.EmptyResponse; import java.security.Security; import java.util.concurrent.TimeUnit; import kotlin.Metadata; import kotlin.Unit; import kotlin.jvm.internal.Intrinsics; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.conscrypt.Conscrypt; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Query; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000,\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\u0006\n\u0002\b\u0002\n\u0002\u0010\u0002\n\u0002\b\u0002\bf\u0018\u0000 \r2\u00020\u0001:\u0001\rJ6\u0010\u0002\u001a\b\u0012\u0004\u0012\u00020\u00040\u00032\b\b\u0001\u0010\u0005\u001a\u00020\u00062\b\b\u0001\u0010\u0007\u001a\u00020\u00062\b\b\u0001\u0010\b\u001a\u00020\t2\b\b\u0001\u0010\n\u001a\u00020\tH'J\u0018\u0010\u000b\u001a\b\u0012\u0004\u0012\u00020\f0\u00032\b\b\u0001\u0010\u0005\u001a\u00020\u0006H'¨\u0006\u000e"}, d2 = {"Lcom/askgps/personaltrackercore/GaskarApi;", "", "start", "Lretrofit2/Call;", "Lcom/askgps/personaltrackercore/database/model/EmptyResponse;", "imei", "", "idxid", "latitude", "", "longitude", "stop", "", "Factory", "personaltrackercore_release"}, k = 1, mv = {1, 1, 16}) /* compiled from: GaskarApi.kt */ public interface GaskarApi { public static final Factory Factory = Factory.$$INSTANCE; @GET("/card/rest/workshift/start") Call<EmptyResponse> start(@Query("deviceEUI") String str, @Query("idxid") String str2, @Query("latitude") double d, @Query("longitude") double d2); @GET("/card/rest/workshift/stop") Call<Unit> stop(@Query("deviceEUI") String str); @Metadata(bv = {1, 0, 3}, d1 = {"\u0000*\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\t\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0000\b†\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002J\u000e\u0010\t\u001a\u00020\n2\u0006\u0010\u000b\u001a\u00020\fR\u000e\u0010\u0003\u001a\u00020\u0004X‚T¢\u0006\u0002\n\u0000R\u000e\u0010\u0005\u001a\u00020\u0006X‚\u0004¢\u0006\u0002\n\u0000R\u000e\u0010\u0007\u001a\u00020\bX‚\u0004¢\u0006\u0002\n\u0000¨\u0006\r"}, d2 = {"Lcom/askgps/personaltrackercore/GaskarApi$Factory;", "", "()V", "TIMEOUT", "", "httpClient", "Lokhttp3/OkHttpClient;", "logging", "Lokhttp3/logging/HttpLoggingInterceptor;", "getInstance", "Lcom/askgps/personaltrackercore/GaskarApi;", "url", "", "personaltrackercore_release"}, k = 1, mv = {1, 1, 16}) /* compiled from: GaskarApi.kt */ public static final class Factory { static final /* synthetic */ Factory $$INSTANCE = new Factory(); private static final long TIMEOUT = 10000; private static final OkHttpClient httpClient = new OkHttpClient.Builder().readTimeout(10000, TimeUnit.MILLISECONDS).writeTimeout(10000, TimeUnit.MILLISECONDS).addInterceptor(logging).build(); private static final HttpLoggingInterceptor logging; static { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new GaskarApi$Factory$logging$1()); httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BASIC); logging = httpLoggingInterceptor; } private Factory() { } public final GaskarApi getInstance(String str) { Intrinsics.checkParameterIsNotNull(str, "url"); Security.insertProviderAt(Conscrypt.newProvider(), 1); Object create = new Retrofit.Builder().baseUrl(ConfigKt.BUILDER_GASKAR_HOST).addConverterFactory(GsonConverterFactory.create()).client(httpClient).build().create(GaskarApi.class); Intrinsics.checkExpressionValueIsNotNull(create, "Retrofit.Builder()\n// …te(GaskarApi::class.java)"); return (GaskarApi) create; } } }
Python
UTF-8
1,092
4
4
[]
no_license
import time import random this_list = random.sample(range(100),60) print "Orginal List...." print this_list """ Divide and conquer recursively """ def merge_sort(unsorted_list): list_length = len(unsorted_list) if list_length == 1: return unsorted_list sublist1 = unsorted_list[0:list_length/2] sublist2 = unsorted_list[list_length/2:] sublist1 = merge_sort(sublist1) sublist2 = merge_sort(sublist2) return mergeit(sublist1,sublist2) """ Merge given two lists in sorted order of their elements """ def mergeit(list1,list2): length = min(len(list1),len(list2)) merged_list = list() while (len(list1) > 0 and len(list2) > 0): if list1[0] > list2[0]: merged_list.append(list2[0]) del list2[0] else: merged_list.append(list1[0]) del list1[0] if len(list1) > len(list2): merged_list.extend(list1) elif len(list2) > len(list1): merged_list.extend(list2) return merged_list this_list = merge_sort(this_list) print "Sorted List...." print this_list
Java
UTF-8
694
3.078125
3
[ "MIT" ]
permissive
package com.htc.io.serialize; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import com.htc.io.serialize.Employee; public class SerializeDemo { public static void main(String[] args) { Employee emp = new Employee(101, "Charles", 50000.0); try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SerializedEmployees.txt")); oos.writeObject(emp); oos.close(); System.out.println("Object Serialized"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Swift
UTF-8
1,036
3.015625
3
[]
no_license
// // DateFromStringConverter.swift // yleSearch // // Created by Oleksandr Shcherbonos on 4/9/18. // Copyright © 2018 Oleksandr Shcherbonos. All rights reserved. // import Foundation extension Date { var timeAgoAsString: String { let day = 3600*24 let week = day*7 let month = day*30 let year = month*12 let secondsAgo = Int(Date().timeIntervalSince(self)) switch secondsAgo { case 0...day: return "today" case day...(2*day): return "1 day ago" case day...week: return "\(secondsAgo/day) days ago" case week...(2*week): return "1 week ago" case week...month: return "\(secondsAgo/week) weeks ago" case month...(2*month): return "1 month ago" case month...year: return "\(secondsAgo/month) months ago" case year...(2*year): return "1 year ago" default: return "\(secondsAgo/year) years ago" } } }
Java
UTF-8
1,721
2.296875
2
[]
no_license
package com.monitor.core.bean.model; import java.util.List; import com.monitor.core.orm.Page; /** * 前台分页数据结果 * @author ibett * */ public class PageModel { private Long total; private Integer pageSize; private Integer pageNumber; private Long totalPages; private List<?> rows; private List<?> footer; public PageModel() { super(); } public PageModel(Page<?> page) { super(); this.total = page.getTotalCount(); this.pageNumber = page.getPageNo(); this.pageSize = page.getPageSize(); this.totalPages = page.getTotalPages(); this.rows = page.getResult(); } public PageModel(Long total, List<?> rows) { super(); this.total = total; this.rows = rows; } public PageModel(Long total, List<?> rows, List<?> footer) { super(); this.total = total; this.rows = rows; this.footer = footer; } public Long getTotal() { return total; } public PageModel setTotal(Long total) { this.total = total; return this; } public Integer getPageSize() { return pageSize; } public PageModel setPageSize(Integer pageSize) { this.pageSize = pageSize; return this; } public Integer getPageNumber() { return pageNumber; } public PageModel setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; return this; } public Long getTotalPages() { return totalPages; } public PageModel setTotalPages(Long totalPages) { this.totalPages = totalPages; return this; } public List<?> getRows() { return rows; } public PageModel setRows(List<?> rows) { this.rows = rows; return this; } public List<?> getFooter() { return footer; } public PageModel setFooter(List<?> footer) { this.footer = footer; return this; } }
JavaScript
UTF-8
1,005
2.953125
3
[]
no_license
/* // Esperar que el DOM esté listo con JavaScript Nativo document.addEventListener('DOMContentLoaded', function(){ console.log("ESTOY LISTO"); }); // Esperar que el DOM esté listo con JQuery $(document).ready(function(){ console.log("ESTOY LISTO CON JQUERY"); }); $(document).on('DOMContentLoaded', function(){ console.log("ESTOY LISTO TAMBIÉN"); }); */ $(document).ready(function(){ // Descendiente directo var img = $("aside > img"); console.log(img[0].ownerDocument.URL); // Desvanecer un elemento // $("aside > img").fadeOut(5000); // $("aside > img").fadeOut('slow'); // Búsqueda de elementos // $("a span").css("color", "red"); // var span = $("a span"); // console.log(span); // console.log(span.length); // Selectores Múltiples => la próxima sentencia por lo que entiendo es para desaparecer el elemento visiblemente // $("a, span, p").slideToggle(); // Pseudo Clases P:last first even odd $("p:odd").css({ 'font-weight': 'bold', 'color': 'goldenrod' }); });
Java
UTF-8
2,061
2.203125
2
[ "MIT", "Apache-2.0", "GPL-1.0-or-later", "LGPL-2.0-or-later" ]
permissive
package org.cbioportal.genome_nexus.web; import org.cbioportal.genome_nexus.model.CuriousCases; import org.cbioportal.genome_nexus.service.CuriousCasesService; import org.cbioportal.genome_nexus.service.exception.CuriousCasesNotFoundException; import org.cbioportal.genome_nexus.service.exception.CuriousCasesWebServiceException; import org.cbioportal.genome_nexus.web.config.InternalApi; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @InternalApi @RestController // shorthand for @Controller, @ResponseBody @CrossOrigin(origins="*") // allow all cross-domain requests @RequestMapping(value= "/") @Api(tags = "curious-cases-controller", description = "Curious Cases Controller") public class CuriousCasesController { private final CuriousCasesService curiousCasesService; @Autowired public CuriousCasesController(CuriousCasesService curiousCasesService) { this.curiousCasesService = curiousCasesService; } @ApiOperation(value = "Retrieves Curious Cases info by a genomic location", nickname = "fetchCuriousCasesGET") @RequestMapping(value = "curious_cases/{genomicLocation}", method = RequestMethod.GET, produces = "application/json") public CuriousCases fetchCuriousCasesGET( @ApiParam(value = "Genomic location, for example: 7,116411883,116411905,TTCTTTCTCTCTGTTTTAAGATC,-", required = true, allowMultiple = false) @PathVariable String genomicLocation) throws CuriousCasesNotFoundException, CuriousCasesWebServiceException { return curiousCasesService.getCuriousCases(genomicLocation); } }
C++
UTF-8
959
2.515625
3
[ "Apache-2.0", "MIT" ]
permissive
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <bond/core/config.h> #include "output_buffer.h" #include <bond/core/blob.h> #include <stdio.h> #include <stdint.h> namespace bond { class StdioOutputStream { public: StdioOutputStream(FILE* file) : _file(file) {} template<typename T> void Write(const T& value) { Write(&value, sizeof(value)); } void Write(const blob& buffer) { Write(buffer.data(), buffer.length()); } void Write(const void* value, uint32_t size) { fwrite(value, size, 1, _file); } protected: FILE* _file; }; // Returns a default OutputBuffer since StdioOutputStream is not capable // of holding a memory buffer. inline OutputBuffer CreateOutputBuffer(const StdioOutputStream& /*other*/) { return OutputBuffer(); } }
C++
UTF-8
8,883
3.09375
3
[]
no_license
// Jeff DiMarco, March 2014 // Peg jumping game solver // // This program runs all combinations of triangular peg solitaire // for a given number of total rows. The indexing starts from the // top single index of the triangle and goes down. #include <iostream> #include <vector> #include "Peg.hpp" #define TRIANGLE_ROWS 5 #define DEBUG false void init(); void solvePegProblem(std::vector<Peg>, int); void printBoard(std::vector<Peg>); int getRow(int); int getCol(int); int getPosition(int, int); int getLandingIndex(int, int); std::vector<Peg> pegList; std::vector<int> solutionsList; std::vector<int> attemptsList; int numSolutions = 0; int numAttempts = 0; int main(){ // Initialize Pegs, positions, and neighbors init(); // Run through each starting position for(int i = 0; i < pegList.size(); ++i){ for(int j = 0; j < pegList.size(); ++j){ pegList[j].hasPeg = true; } pegList[i].hasPeg = false; solutionsList[i] = 0; attemptsList[i] = 0; solvePegProblem(pegList, i); } std::cout << "Finished. Number of solutions: " << numSolutions << std::endl; std::cout << "Number of attempts : " << numAttempts << std::endl; for(int i = 0; i < pegList.size(); ++i){ std::cout << "Solutions for hole " << i << ": " << solutionsList[i] << " "; std::cout << "Attempts for hole " << i << ": " << attemptsList[i] << " Perc: "; std::cout << (float)solutionsList[i]/(float)attemptsList[i] << std::endl; } } // Recursively solves a board state with brute force search void solvePegProblem(std::vector<Peg> inputPegList, int startingHole){ // Check for possible jumps for(int i = 0; i < inputPegList.size(); ++i){ // Consider jumping into each missing slot if(!inputPegList[i].hasPeg){ // Check neighbors that could be jumped for(int j = 0; j < inputPegList[i].neighborList.size(); ++j){ int jumpedIndex = inputPegList[i].neighborList[j]; // The neighbor's neighbors will be considered as the jumper for(int k = 0; k < inputPegList[jumpedIndex].neighborList.size(); ++k){ int jumperIndex = inputPegList[jumpedIndex].neighborList[k]; int landingIndex = inputPegList[i].position; // If the empty slot can be jumped into with these conditions, push a new state to solve if(getLandingIndex(jumpedIndex, jumperIndex) == landingIndex && inputPegList[jumpedIndex].hasPeg && inputPegList[jumperIndex].hasPeg && !inputPegList[landingIndex].hasPeg){ std::vector<Peg> temp = inputPegList; temp[jumpedIndex].hasPeg = false; temp[jumperIndex].hasPeg = false; temp[landingIndex].hasPeg = true; // Recurse with next board using this jump solvePegProblem(temp, startingHole); } } } } } // No jumps remain int hasPegCount = 0; for(int i = 0; i < inputPegList.size(); ++i){ if(inputPegList[i].hasPeg){ hasPegCount++; } } // Stats numAttempts++; attemptsList[startingHole]++; if(hasPegCount == 1){ numSolutions++; solutionsList[startingHole] += 1; } return; } // Determines the row of the given position int getRow(int inputPosition){ int currRow = 0; int runningSum = 1; while(currRow < TRIANGLE_ROWS){ if(inputPosition < runningSum){ return currRow; }else{ currRow++; runningSum += (currRow+1); } } std::cerr << "Error: Couldn't find row for position: " << inputPosition << std::endl; return -1; } // Determines the col of the given position int getCol(int inputPosition){ int currRow = 0; int currCol = 0; int runningSum = 0; int prevRunningSum = runningSum; runningSum += (currRow+1); while(currRow < TRIANGLE_ROWS){ if(inputPosition < runningSum){ return inputPosition - prevRunningSum; }else{ currRow++; prevRunningSum = runningSum; runningSum += (currRow+1); } } std::cerr << "Error: Couldn't find column for position: " << inputPosition << std::endl; return -1; } // Gives the integer position for a given row and column int getPosition(int inputRow, int inputCol){ int currRow = 0; int runningSum = 0; while(currRow < inputRow){ currRow++; runningSum += currRow; } runningSum += inputCol; return runningSum; } // Returns index after jump is completed. -1 if not possible int getLandingIndex(int inputJumped, int inputJumper){ int jumpedRow = getRow(inputJumped); int jumpedCol = getCol(inputJumped); int jumperRow = getRow(inputJumper); int jumperCol = getCol(inputJumper); // Case jumped is row above if(jumpedRow == jumperRow-1){ if(jumpedCol == jumperCol){ // Jumping up and right if(jumpedCol <= jumpedRow-1){ return getPosition(jumpedRow-1, jumpedCol); } else { // Above and to the right is off board return -1; } } if(jumpedCol == jumperCol - 1){ // Jumping up and left if(jumpedCol-1 >= 0){ return getPosition(jumpedRow-1, jumpedCol-1); } else { // Above and to the left is off board return -1; } } } // Case jumped is same row if(jumpedRow == jumperRow){ if(jumpedCol < jumperCol){ // Jumping left if(jumpedCol > 0){ return getPosition(jumpedRow, jumpedCol-1); } else { // Jumped is on left edge return -1; } } if(jumpedCol > jumperCol){ // Jumping right if(jumpedCol < jumpedRow){ return getPosition(jumpedRow, jumpedCol+1); } else { // Jumped is on right edge return -1; } } } // Case jumped is row below if(jumpedRow == jumperRow+1){ if(jumpedCol == jumperCol + 1){ // Jumping down and right if(jumpedRow+1 < TRIANGLE_ROWS){ return getPosition(jumpedRow+1, jumpedCol+1); } else { // Below is off board return -1; } } if(jumpedCol == jumperCol){ // Jumping down and left if(jumpedRow+1 < TRIANGLE_ROWS){ return getPosition(jumpedRow+1, jumpedCol); } else { // Below is off board return -1; } } } return -1; } void init(){ // Set up peg positions int currPeg = 0; for(int i = 0; i < TRIANGLE_ROWS; ++i){ for(int j = 0; j <= i; ++j){ pegList.push_back(Peg(currPeg, i, j)); // Neighbor(s) above if(i-1 >= 0){ if(j-1 >= 0){ // Neighbor above to the left pegList[currPeg].neighborList.push_back(getPosition(i-1, j-1)); } if(j-1 < i-1){ // Neighbor above to the right pegList[currPeg].neighborList.push_back(getPosition(i-1, j)); } } // Neighbors in same row if(j >= 1){ pegList[currPeg].neighborList.push_back(getPosition(i, j-1)); } if(j+1 < i+1){ pegList[currPeg].neighborList.push_back(getPosition(i, j+1)); } // Neighbor(s) below if(i+1 < TRIANGLE_ROWS){ pegList[currPeg].neighborList.push_back(getPosition(i+1, j)); pegList[currPeg].neighborList.push_back(getPosition(i+1, j+1)); } currPeg++; } } solutionsList.resize(pegList.size()); attemptsList.resize(pegList.size()); return; } // Used for debugging. Prints the board state void printBoard(std::vector<Peg> inputPegList){ std::cout << "Current Board:" << std::endl; for(int i = 0; i < TRIANGLE_ROWS; ++i){ int numSpaces = TRIANGLE_ROWS - i; for(int printSpaces = 0; printSpaces < numSpaces; ++printSpaces) std::cout << " "; for(int j = 0; j <= i; ++j){ if(inputPegList[getPosition(i,j)].hasPeg){ std::cout << 1 << " "; }else{ std::cout << 0 << " "; } } std::cout << std::endl; } }
Markdown
UTF-8
622
2.625
3
[]
no_license
# BSM-Decision-support-methods The problem at hand is a multiple attribute decision-making problem where the set of identified decision attributes are a mixture of quantitative and qualitative attributes. It is assumed that the preference of the decision-maker concerning the identified attributes, fulfills the independence conditions required for the use of the additive model. Following the additive model, the weight corresponding to each attribute will be calculated, the value functions for each attribute will be defined and the weighted sum method will be employed to calculate each alternative’s overall score.
C++
UTF-8
677
2.9375
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; float f(float x) { float Y; Y = x*x*x + 5 * x*x + 16 * x - 60; return(Y); } float df(float x) { float y; y = 3 * x*x + 10 * x + 16; return(y); } void main() { int i, n = 50; float p0, p1, Y, y, err = 0.001, relerr = 0.001, delta = 0.001; cout << "input the initial approximation to a zero of f:" << endl; cin >> p0; for (i = 0; i<n; i++) { Y = f(p0); y = df(p0); if (y != 0) p1 = p0 - Y / y; err = fabs(p1 - p0); relerr = 2 * err / (fabs(p1) + delta); if (err<delta || relerr<delta || fabs(Y)<delta) break; p0 = p1; } cout << "the root of the f(x)=0 is:" << p0 << endl; system("pause"); }
Java
UTF-8
1,848
3.078125
3
[]
no_license
package com.candycrush.main; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class LevelReader { private static final String path = "res/level"; private final List<boolean[][]> LEVEL_GRID = new ArrayList<>(); public LevelReader() { File folder; File[] fileList; Scanner scanner; try { folder = new File(path); fileList = folder.listFiles(); if (fileList != null) { for (File file : fileList) { scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("empty")) { line = line.replace("empty", ""); line = line.replace("=",""); readGrid(line); } } } } } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } private void readGrid(String line) { String[] cells = line.split("\\s"); boolean[][] grid = new boolean[9][9]; for (boolean[] row : grid) { Arrays.fill(row, true); } for (String str : cells) { if (!str.equals("")) { int cellNum = Integer.parseInt(str); if ((cellNum % 9) == 0) { grid[8][(cellNum / 9) - 1] = false; } else { grid[(cellNum % 9) - 1][(cellNum / 9)] = false; } } } LEVEL_GRID.add(grid); } public boolean[][] getLevelGrid(int levelNum) { return LEVEL_GRID.get(levelNum); } }
Python
UTF-8
2,628
2.953125
3
[]
no_license
__author__ = 'Natasha' import os import PySide.QtGui as QtGui class FileBrowseWidget(QtGui.QWidget): ''' Creates a widget that contains a label and a file browser ''' def __init__(self, labelName, fileName, outfile): ''' Creates the elements of the widget. :param labelName: Name of the label ''' super(FileBrowseWidget, self).__init__() self.layout = QtGui.QGridLayout() self.setLayout(self.layout) hLayout = QtGui.QHBoxLayout() fileLabel = QtGui.QLabel(labelName) hLayout.addWidget(fileLabel) self.fileEdit = QtGui.QLineEdit(fileName) self.fileEdit.setReadOnly(True) self.fileEdit.setToolTip('Click to select a file') self.saveFilePath = outfile hLayout.addWidget(self.fileEdit) self.layout.addLayout(hLayout,1,0) def addOpenFileDialogEvent(self): self.fileEdit.mousePressEvent = self.openFileDialog def addSaveFileDialogEvent(self): self.fileEdit.mousePressEvent = self.saveFileDialog def openFileDialog(self, event): ''' Opens a file browser when the text box is clicked. :param event: Event triggered when the text box is clicked. :return: ''' dialog = QtGui.QFileDialog() filename, fileType = dialog.getOpenFileName(self, "Select File", os.path.dirname(self.fileEdit.text()), options= QtGui.QFileDialog.DontUseNativeDialog) self.fileEdit.setText(str(filename)) def saveFileDialog(self, event): ''' Opens a file browser when the text box is clicked. :param event: Event triggered when the text box is clicked. :return: ''' dialog = QtGui.QFileDialog() filename, fileType = dialog.getSaveFileName(self, "Save File", self.saveFilePath, options= QtGui.QFileDialog.DontUseNativeDialog) if not str(filename).endswith('.mov'): filename = str(filename) + '.mov' self.fileEdit.setText(str(filename)) def getFilePath(self): ''' :return: The file selected by the user. ''' return self.fileEdit.text() def setFilePath(self, filename): ''' :param filename: The text box is set with this filename ''' filename = str(filename) newFilename = filename.split('/')[-1].split('.')[0] if self.saveFilePath == '': self.saveFilePath = os.path.dirname(filename) newFilePath = '%s/%s.mov' % (os.path.dirname(self.saveFilePath), newFilename) self.fileEdit.setText(newFilePath)
Markdown
UTF-8
1,730
2.71875
3
[]
no_license
```yaml area: Hertfordshire og: description: Police are appealing for witnesses and information after a number of vehicles were damaged in Hertford. publish: date: 22 May 2019 title: Damage to cars in Hertford url: https://www.herts.police.uk/news-and-appeals/damage-to-cars-in-hertford-0259a ``` * ### Around 30 vehicles were damaged. * ### A windscreen was smashed and mirrors were damaged. * ### Officers are asking anyone with information to come forward. Police are appealing for witnesses and information after a number of vehicles were damaged in Hertford. At around 7am on Sunday, May 5, a member of the public reported to police that around 30 vehicles had been targeted while parked in a car park in Mead Lane. It is believed the damage had been caused overnight. One of the vehicles had its windscreen smashed, while several others had mirrors or windscreen wipers damaged. Detective Constable Charlotte Slaney, from the East Herts Local Crime Unit, said: "This senseless behaviour has left a number of people with hefty repair bills, which they are understandably very upset about. "I am appealing for anyone with information about the damage to please come forward. Did you see or hear anything suspicious in the area? Any information could assist our enquiries." Anyone with information should contact DC Slaney by emailing or by calling the non-emergency number 101, quoting crime number 41/40384/19. You can also report information online _._ Alternatively, you can stay 100% anonymous by contacting the independent charity Crimestoppers on 0800 555 111 or via their untraceable online form. For over 30 years, Crimestoppers has always kept its promise of anonymity to everyone who contacts them.
Markdown
UTF-8
1,391
2.734375
3
[ "MIT" ]
permissive
--- title: Redirecting from a Context Menu Selection page_title: Redirecting from a Context Menu Selection | RadTreeView for ASP.NET AJAX Documentation description: Redirecting from a Context Menu Selection slug: treeview/application-scenarios/context-menus/redirecting-from-a-context-menu-selection tags: redirecting,from,a,context,menu,selection published: True position: 0 --- # Redirecting from a Context Menu Selection ## To redirect to another web page based on clicking a Context Menu, set the **OnClientContextMenuClicking** property to a JavaScript function that takes two arguments: * **sender:** a reference to the **RadTreeView** * **eventArgs:** contains a reference to the clicked Menu Item, the Node under the Context Menu and the **set_cancel()** function used for aborting the Context Menu click. The example below gets the Context Menu Item and sets the window url. ````ASPNET <telerik:RadTreeView ID="RadTreeView1" runat="server" EnableDragAndDrop="True" OnClientContextMenuItemClicking="clientContextMenuClicking" Skin="Vista"> </telerik:RadTreeView> ```` ````JavaScript function clientContextMenuClicking(sender, eventArgs) { var menuItem = eventArgs.get_menuItem(); window.location.href = "http://en.wikipedia.org/wiki/" + menuItem.get_text(); } ````
C
UTF-8
4,533
2.921875
3
[]
no_license
/* ps.c A set with pointer values (pointer set) Tool Chain Editor Copyright (C) 2016 olikraus@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <assert.h> #include "ps.h" #define PS_EXPAND 16 ps_t *ps_Open() { ps_t *ps; int i; ps = (ps_t *)malloc(sizeof(ps_t)); if ( ps != NULL ) { ps->list_ptr = (void **)malloc(PS_EXPAND*sizeof(void *)); if ( ps->list_ptr != NULL ) { for( i = 0; i < PS_EXPAND; i++ ) ps->list_ptr[i] = NULL; ps->list_max = PS_EXPAND; ps->list_cnt = 0; ps->search_pos_start = 0; return ps; } free(ps); } return NULL; } void ps_Clear(ps_t *ps) { int i; for( i = 0; i < ps->list_max; i++ ) ps->list_ptr[i] = NULL; ps->list_cnt = 0; } void ps_Close(ps_t *ps) { ps_Clear(ps); assert ( ps->list_ptr != NULL ); free(ps->list_ptr); free(ps); } int ps_IsValid(ps_t *ps, int pos) { if ( pos < 0 ) return 0; if ( pos >= ps->list_max ) return 0; if ( ps->list_ptr[pos] == NULL ) return 0; return 1; } static int _ps_expand(ps_t *ps) { void *ptr; int pos; assert(ps != NULL); assert(ps->list_ptr != NULL); assert((ps->list_max % PS_EXPAND) == 0); ptr = (void *)realloc(ps->list_ptr, sizeof(void *)*(ps->list_max + PS_EXPAND)); if ( ptr == NULL ) return 0; ps->list_ptr = ptr; pos = ps->list_max; ps->search_pos_start = ps->list_max; ps->list_max += PS_EXPAND; while( pos < ps->list_max ) { ps->list_ptr[pos] = NULL; pos++; } return 1; } static int ps_find_empty(ps_t *ps) { int i; for( i = ps->search_pos_start; i < ps->list_max; i++ ) { if ( ps->list_ptr[i] == NULL ) { ps->search_pos_start = i + 1; if ( ps->search_pos_start >= ps->list_max ) ps->search_pos_start = 0; return i; } } assert(ps->search_pos_start < ps->list_max); for( i = 0; i < ps->search_pos_start; i++ ) { if ( ps->list_ptr[i] == NULL ) { ps->search_pos_start = i + 1; if ( ps->search_pos_start >= ps->list_max ) ps->search_pos_start = 0; return i; } } return -1; } /* returns access handle or -1 */ int ps_Add(ps_t *ps, void *ptr) { int pos; assert(ps != NULL); assert(ps->list_ptr != NULL); assert(ptr != NULL); assert(ps->list_max >= ps->list_cnt); pos = ps_find_empty(ps); if ( pos < 0 ) { if ( _ps_expand(ps) == 0 ) return -1; pos = ps_find_empty(ps); if ( pos < 0 ) return -1; } ps->list_ptr[pos] = ptr; ps->list_cnt++; return pos; } int ps_Set(ps_t *ps, int pos, void *ptr) { while(ps->list_max <= pos) if ( _ps_expand(ps) == 0 ) return 0; assert(pos >= 0); assert(pos < ps->list_max); if ( ps->list_ptr[pos] == NULL && ptr != NULL ) ps->list_cnt++; if ( ps->list_ptr[pos] != NULL && ptr == NULL ) ps->list_cnt--; ps->list_ptr[pos] = ptr; return 1; } /* delete a pointer by its access handle */ void ps_Del(ps_t *ps, int pos) { assert(pos >= 0); assert(pos < ps->list_max); assert(ps->list_ptr[pos] != NULL); assert(ps->list_cnt > 0 ); ps->list_ptr[pos] = NULL; ps->list_cnt--; } int ps_Next(ps_t *ps, int pos) { for(;;) { pos++; if ( pos >= ps->list_max ) return -1; if ( ps->list_ptr[pos] != NULL ) return pos; } } int ps_First(ps_t *ps) { return ps_Next(ps, -1); } /* *pos must be initilized with -1 */ int _ps_WhileLoop(ps_t *ps, int *pos) { *pos = ps_Next(ps, *pos); if ( *pos < 0 ) return 0; return 1; } /* *pos must be initilized with -1 */ int ps_WhileLoop(ps_t *ps, int *pos_ptr) { int pos = *pos_ptr; for(;;) { pos++; if ( pos >= ps->list_max ) { *pos_ptr = -1; return 0; } if ( ps->list_ptr[pos] != NULL ) { *pos_ptr = pos; return 1; } } } size_t ps_GetMemUsage(ps_t *ps) { size_t m = sizeof(ps_t); m += sizeof(void *)*ps->list_max; return m; }
C++
UTF-8
461
2.609375
3
[]
no_license
// // Created by daniel on 12/17/18. // #include <thread> #include "SymbolTable.h" /** * this method set the args of the value * if the flag is on it means that we came from the setCommand and we want to update the plane simiulator * @param key * @param num * @param flag true from set false from others */ void SymbolTable::setDoubleValue(string &key, double num, bool flag) { lock_guard<std::mutex> lock(myLock); this->symbolTable[key] = num; }
Java
UTF-8
591
3.1875
3
[]
no_license
class Simplify Path{ public String simplifyPath(String path) { LinkedList<String> stack = new LinkedList<String>(); String[] paths = path.split("/"); for(String s:paths){ if(s.equals("..")){ if(!stack.isEmpty()) stack.pop(); } else if(s.equals(".")|| s.equals("")) continue; else stack.push(s); } String res = ""; if(stack.isEmpty()) return "/"; while(!stack.isEmpty()){ res = "/" + stack.pop() + res; } return res; } }
Python
UTF-8
3,307
2.84375
3
[]
no_license
""" tf——idf+余弦距离进行计算 KMeans没准要自己实现 """ import model.TF_IDFAdapter as tfidf import data.data_util as du import numpy as np import cluster.cluster_result as cr import cmath def cal_Cosine_distance(vec0, vec1): # 计算余弦相似度,越接近1越相似,参数为两个向量list # dot为叉乘 vec0 = np.array(vec0) vec1 = np.array(vec1) vector0Mod = np.sqrt(vec0.dot(vec0)) vector1Mod = np.sqrt(vec1.dot(vec1)) if vector0Mod != 0 and vector1Mod != 0: similarity = abs((vec0.dot(vec1))) / (vector0Mod * vector1Mod) else: similarity = 0 return similarity def qt(doc_vec, tmp, threshold=0.6): # 说白了就是设置对应阈值,阈值内的都塞到一个簇中,再将最大的那份给拿出来 # 返回为最大的那份簇群 candidate = [] for i in range(len(doc_vec)): i_cluster = [] for j in range(len(doc_vec)): if i == j: continue if (i in tmp) and (j in tmp): ij_sim = cal_Cosine_distance(doc_vec[i], doc_vec[j]) if ij_sim > threshold: i_cluster.append(j) candidate.append(i_cluster) # 找到最大的簇返回 num_s = [len(x) for x in candidate] max_num = max(num_s) index = num_s.index(max_num) return candidate[index] def eliminate(e, whole_num): # 剔除之前簇中元素,whole_num为总的文档数量 tmp = [] for i in range(0, whole_num): if i in e: continue else: tmp.append(i) return tmp def clusterResult_qt(k, doc): # 没整完就直接扔了算了 threshold = 0.05 whole_num = len(doc) remain = list(range(whole_num)) # 总之先把tf-idf矩阵求出来 word_dic, weight = tfidf.cal_tf_idf(doc) t = 0 used = [] s_num = 0 cluster_result = [] out_remain = [] while t < k - 1: candidate = qt(weight, remain, threshold) # 当前剩余元素中最大簇 used += candidate remain = eliminate(used, whole_num) # 剔除已用 out_remain = remain s_num += len(candidate) print("{}, {}".format(t, len(candidate))) cluster_result.append(candidate) t += 1 print("{}, {}".format(t, len(out_remain))) cluster_result.append(out_remain) print(s_num) # 将结果转为可进行评估的方式,未被聚类的设置为-1 result = [-1] * whole_num for i in range(whole_num): for x in range(len(cluster_result)): if i in cluster_result[x]: result[i] = x break return result if __name__ == "__main__": k = 12 filename = "data1322.csv" # 4 diping 3 8,12 diping 5 doc = du.getDocAsWordArray(filename,5) cluster_result = clusterResult_qt(k, doc) former = du.getFormerCategory(filename) # print(former) # 将数据转为能直接进行准确度判定的形式 c_r_result = [] f_r = [] for i in range(len(cluster_result)): if cluster_result[i] != -1: c_r_result.append(cluster_result[i]) f_r.append(former[i]) # print(len(c_r_result)) # print(len(f_r)) r = cr.printResult(k, c_r_result, f_r) print(r)
Java
UTF-8
3,410
2.046875
2
[]
no_license
package cn.edu.dgut.epidemic.service; import java.io.InputStream; import java.util.List; import java.util.Map; import org.activiti.engine.repository.Deployment; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.task.Comment; import org.activiti.engine.task.Task; import cn.edu.dgut.epidemic.pojo.CampusUserInfo; import cn.edu.dgut.epidemic.pojo.VolunteerEnroll; import cn.edu.dgut.epidemic.pojo.VolunteerService; public interface ActivitiService { /** * 部署流程 * * @param in * @param filename */ void saveNewDeploy(InputStream in, String filename); /** * 启动流程(待办人) * * @param id * @param name * @param sponsor * @param flag:1为活动审核流程,2为报名流程 */ String startProcess(Integer id, String name, String sponsor, Integer flag); /** * 根据待办人查询任务 * * @param name * @param flag * @return */ List<Task> findTaskListByName(String name, Integer flag); /** * 根据taskId获取活动信息 * * @param taskId * @return */ VolunteerService findVolunteerServiceByTaskId(String taskId); /** * 根据taskId获取报名信息 * * @param taskId * @return */ VolunteerEnroll findVolunteerEnrollByTaskId(String taskId); /** * 办理任务 * * @param id * @param taskId * @param comemnt * @param outcome * @param sponsor * @param userInfo * @param flag */ void submitTask(Integer id, String taskId, String comemnt, String outcome, String sponsor, CampusUserInfo userInfo, Integer flag); /** * 使用任务对象获取流程定义ID,查询流程定义对象 * * @param taskId * @return */ ProcessDefinition findProcessDefinitionByTaskId(String taskId); /** * 查看当前活动,获取当期活动对应的坐标x,y,width,height,将4个值存放到Map<String,Object>中 * * @param taskId * @return */ Map<String, Object> findCoordingByTask(String taskId); /** * 获取资源文件表(act_ge_bytearray)中资源图片输入流InputStream * * @param deploymentId * @param imageName * @return */ InputStream findImageInputStream(String deploymentId, String imageName); /** * 根据BUSSINESS_KEY查询出任务信息 * * @param bUSSINESS_KEY * @return */ Task findTaskByBussinessKey(String bUSSINESS_KEY); /** * 查询部署对象信息,对应表(act_re_deployment) * * @return */ List<Deployment> findDeploymentList(); /** * 查询流程定义的信息,对应表(act_re_procdef) * * @return */ List<ProcessDefinition> findProcessDefinitionList(); /** * 使用ID,查询历史的批注信息 * * @param id * @return */ List<Comment> findCommentById(Integer id, Integer flag); /** * 根据taskId获取批注信息 * * @param taskId * @return */ List<Comment> findCommentListByTaskId(String taskId); /** * 获取对应身份的审核功能信息 * * @param taskId * @return */ List<String> findOutComeListByTaskId(String taskId); /** * 使用部署对象ID,删除流程定义 * * @param deploymentId */ void deleteProcessDefinitionByDeploymentId(String deploymentId); // List<Comment> findCommentByTaskId(String taskId); }
Shell
UTF-8
2,782
3.859375
4
[]
no_license
#!/bin/bash echo "hello world" # for tracing, do #!/bin/bash -x # sysinfo_page - A script to produce an HTML file #To create a variable, put a line in your script that contains the name of the variable followed immediately by an equal sign ("="). No spaces are allowed. After the equal sign, assign the information you wish to store. title="My System Information" # $ sign for substitution ... command/variable # right_now=$(date+"%x %y %Z") #$right_now #constants in CAPITAL LETTERS. variables in small letters. # <<- to ignore tabs # cat <<- '_EOF_' #to disable interpretation within this code block # function definition should appear before function call # func(){ # stubbing # echo "Function stub" # } #function call: $(func) # exit code 0 always = success # $? ... last exit code. if 0, success else fail # if root, then id -u = 0 # test : [] #if [ expr ]; # space after if, then [, then space, then expr, then space, then ] then; # if my script successful, exit 0 else exit 1 #-d file True if file is a directory. #-e file True if file exists. #-f file True if file exists and is a regular file. #-L file True if file is a symbolic link. #-r file True if file is a file readable by you. #-w file True if file is a file writable by you. #-x file True if file is a file executable by you. #file1 -nt file2 True if file1 is newer than (according to modification time) file2 #file1 -ot file2 True if file1 is older than file2 #-z string True if string is empty. #-n string True if string is not empty. #string1 = string2 True if string1 equals string2. #string1 != string2 True if string1 does not equal string2. if [ -f .bash_profile ] then echo "You have a .bash_profile. Things are fine." else echo "Yikes! You have no .bash_profile!" fi cat <<- _EOF_ <html> <head> <title> $title </title> </head> <body> <h1> $title </h1> </body> </html> _EOF_ # read text # read input from user and put it in text # read -t 3 text # read input within 3 seconds...timer! # read -s text # dont display text on screen...secret like password! # echo -n "Text on the same line. no carriage return" # arithmatic in double parenthesis $((expression)) # # refresh shell: source ~/.bashrc # sthg disappears/export path each time you open terminal? add path to ~/.profile first_num=0 second_num=0 echo -n "Enter the first number --> " read first_num echo -n "Enter the second number -> " read second_num echo "first number + second number = $((first_num + second_num))" echo "first number - second number = $((first_num - second_num))" echo "first number * second number = $((first_num * second_num))" echo "first number / second number = $((first_num / second_num))" echo "first number % second number = $((first_num % second_num))"
Java
UTF-8
1,666
2.6875
3
[]
no_license
/* * Zemian Deng 2014 */ package zemian.servlet3example.service; import java.io.Reader; import java.util.HashSet; import java.util.Properties; import java.util.Set; import zemian.service.logging.Logger; /** * User DAO that uses Properties file to store users info. * * @author zedeng */ public class UserService implements Service { private static final Logger LOGGER = new Logger(UserService.class); // Username and password store private Properties usersProps = new Properties(); /** * Load $HOME/java-ee-example/servlet3example-users.properties if exists, else it will * use the one in classpath under "/zemian/servlet3example/service/servlet3example-users.properties". * * @throws RuntimeException - if both file and resource name not found. */ @Override public void init() { FileUtils.loadOptionalFile("servlet3example-users.properties", getClass().getPackage().getName(), new FileUtils.ReaderAction() { @Override public void onReader(Reader reader) throws Exception { usersProps.load(reader); } }); } @Override public void destroy() { // Do nothing. } public boolean validate(String username, String password) { String storedPassword = usersProps.getProperty(username); return storedPassword != null && storedPassword.equals(password); } public Set<String> getUsers() { Set<String> result = new HashSet<>(); for (String username : usersProps.stringPropertyNames()) result.add(username); return result; } }
Swift
UTF-8
1,220
3.046875
3
[ "MIT" ]
permissive
import Foundation public typealias PatternIdentifier = Int public enum RouteEdge { case dot case slash case literal(String) } extension RouteEdge: Equatable, Hashable, CustomDebugStringConvertible, CustomStringConvertible { public var description: String { switch self { case .literal(let value): return value case .dot: return "." case .slash: return "/" } } public var debugDescription: String { return self.description } public var hashValue: Int { return self.description.hashValue } } public func == (lhs: RouteEdge, rhs: RouteEdge) -> Bool { return lhs.hashValue == rhs.hashValue } open class RouteVertex { open var nextRoutes: [RouteEdge: RouteVertex] = [:] open var epsilonRoute: (String, RouteVertex)? open var patternIdentifier: PatternIdentifier? public init(patternIdentifier: PatternIdentifier? = nil) { self.patternIdentifier = patternIdentifier } open var isTerminal: Bool { return self.patternIdentifier != nil } open var isFinale: Bool { return self.nextRoutes.isEmpty && self.epsilonRoute == nil } }
C#
UTF-8
2,492
2.84375
3
[ "MIT" ]
permissive
namespace BusinessLib.Models { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Xml.Serialization; public class MetaLocationModel { #region fields private readonly ObservableCollection<MetaLocationModel> _Children = null; #endregion fields #region constructors /// <summary> /// Parameterized Class Constructor /// </summary> public MetaLocationModel( MetaLocationModel parent , int id , string iso , string localName , LocationType type , long in_Location , double geo_lat , double geo_lng , string db_id ) : this() { Parent = parent; ID = id; ISO = iso; LocalName = localName; Type = type; In_Location = in_Location; Geo_lat = geo_lat; Geo_lng = geo_lng; DB_id = db_id; } /// <summary> /// Class Constructor /// </summary> public MetaLocationModel() { _Children = new ObservableCollection<MetaLocationModel>(); } #endregion constructors #region properties [XmlIgnore] public MetaLocationModel Parent { get; private set; } public int ID { get; set; } public string ISO { get; set; } public string LocalName { get; set; } public LocationType Type { get; set; } public long In_Location { get; set; } public double Geo_lat { get; set; } public double Geo_lng { get; set; } public string DB_id { get; set; } [XmlIgnore] public IEnumerable<MetaLocationModel> Children { get { return _Children; } } #endregion properties #region methods public int ChildrenCount => _Children.Count; public void ChildrenAdd(MetaLocationModel child) { _Children.Add(child); } public void ChildrenRemove(MetaLocationModel child) { _Children.Remove(child); } public void ChildrenClear() { _Children.Clear(); } public void SetParent(MetaLocationModel parent) { Parent = parent; } #endregion methods } }
C
UTF-8
3,812
3.171875
3
[]
no_license
#pragma once #include "vector.h" #include <stdio.h> #include <stdlib.h> #define TILE_HALF_WIDTH_PX 16 #define TILE_HALF_DEPTH_PX TILE_HALF_WIDTH_PX / 2 #define TILE_HEIGHT_PX 18 #define CELL_HAS_ENTITY_FLAG 0x80 typedef struct Level { Vector3 size; char *tiles; Vector3 start_positions[3]; // TODO: number of enemies and such uint32_t entities_count; } Level; int setFlagAt(Vector3 position, Level *level) { if (position.x >= 0 && position.x < level->size.x && position.y >= 0 && position.y < level->size.y && position.z >= 0 && position.z < level->size.z) { level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x] |= CELL_HAS_ENTITY_FLAG; return 1; } else return 0; } int clearFlagAt(Vector3 position, Level *level) { if (position.x >= 0 && position.x < level->size.x && position.y >= 0 && position.y < level->size.y && position.z >= 0 && position.z < level->size.z) { level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x] &= (char)~CELL_HAS_ENTITY_FLAG; return 1; } else return 0; } // remember to free the last level before running again int loadLevel(Level *level, const char *path) { FILE *level_file = fopen(path, "r"); if (!level_file) { return 0; } // first thing to read is the size fread(&level->size, sizeof(Vector3), 1, level_file); // the number of bytes to copy will be the product of x, y, and z size_t next_copy_size = level->size.x * level->size.y * level->size.z; level->tiles = calloc(next_copy_size, 1); fread(level->tiles, sizeof(char), next_copy_size, level_file); // now, copy the start position fread(&level->start_positions, sizeof(Vector3), sizeof(level->start_positions) / sizeof(Vector3), level_file); fclose(level_file); return 1; } int saveLevel(Level *level, const char *path) { // clear all entity flags for (int x = 0; x < level->size.x; x++) { for (int y = 0; y < level->size.y; y++) { for (int z = 0; z < level->size.z; z++) { Vector3 world = { x, y, z }; clearFlagAt(world, level); } } } FILE *level_file = fopen(path, "w+"); if (!level_file) { return 0; } // first write the size fwrite(&level->size, sizeof(Vector3), 1, level_file); fwrite(level->tiles, sizeof(char), level->size.x * level->size.y * level->size.z, level_file); fwrite(&level->start_positions, sizeof(Vector3), sizeof(level->start_positions) / sizeof(Vector3), level_file); fclose(level_file); return 1; } char getTileAt(Vector3 position, Level *level) { if (position.x >= 0 && position.x < level->size.x && position.y >= 0 && position.y < level->size.y && position.z >= 0 && position.z < level->size.z) { return level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x]; } puts("Out of bounds access"); return 0; } char getTileAtUnsafe(Vector3 position, Level *level) { return level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x]; } int setTileAt(char tile, Vector3 position, Level *level) { tile &= (char)~CELL_HAS_ENTITY_FLAG; if (position.x >= 0 && position.x < level->size.x && position.y >= 0 && position.y < level->size.y && position.z >= 0 && position.z < level->size.z) { level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x] &= CELL_HAS_ENTITY_FLAG; level->tiles[position.y + position.x * level->size.y + position.z * level->size.y * level->size.x] |= tile; return 1; } else return 0; }
Java
UTF-8
2,794
2.1875
2
[]
no_license
package com.supermap.egispservice.lbs.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.supermap.egispservice.lbs.dao.AlarmTypeDao; import com.supermap.egispservice.lbs.entity.AlarmType; @Transactional @Service("alarmTypeService") public class AlarmTypeServiceImpl implements AlarmTypeService { @Autowired AlarmTypeDao alarmTypeDao; @Override public List<AlarmType> queryAlarmType(HashMap<String, Object> hm) { final String name=(String) (hm.get("name")==null?"":hm.get("name"));//名称 final String type=(String) (hm.get("type")==null?"":hm.get("type"));//类型 final String code=(String) (hm.get("code")==null?"":hm.get("code"));//code Specification<AlarmType> spec=new Specification<AlarmType>(){ @Override public Predicate toPredicate(Root<AlarmType> root, CriteriaQuery<?> query, CriteriaBuilder builder) { List<Predicate> predicateList=new ArrayList<Predicate>(); Path<String> namepath=root.get("name"); Path<String> typepath=root.get("type"); Path<String> codepath=root.get("code"); //name if (StringUtils.isNoneEmpty(name)) { Predicate p=builder.like(namepath, "%"+name+"%"); predicateList.add(p); } //车辆id if (StringUtils.isNoneEmpty(type)) { Predicate p=builder.equal(typepath, type); predicateList.add(p); } //车辆id if (StringUtils.isNoneEmpty(code)) { Predicate p=builder.equal(codepath, code); predicateList.add(p); } Predicate [] predicates=new Predicate[predicateList.size()]; predicateList.toArray(predicates); query.where(predicates); return null; } }; Sort sort = new Sort(Direction.DESC,new String[]{"code"}); List<AlarmType> result=this.alarmTypeDao.findAll(spec,sort); return result; } @Override public AlarmType getAlarmType(String id) { return this.alarmTypeDao.findByid(id); } @Override public AlarmType getAlarmTypeByCode(Integer code) { return this.alarmTypeDao.findOneByCode(code.toString()); } }
Java
UTF-8
356
1.929688
2
[ "Apache-2.0" ]
permissive
package com.orange.net.controller; import com.orange.net.interfaces.IMessage; public class AcceptFileTransfer_ResponseMessage implements IMessage{ /** * */ private static final long serialVersionUID = 1L; private String mJobId; public String getJobId() { return mJobId; } public void setJobId(String mJobId) { this.mJobId = mJobId; } }
Markdown
UTF-8
15,958
3.078125
3
[]
no_license
# MapReduce :Simplified Data Processing on Large Clusters ## Abstract **What is MapReduce?** MapReduce is a programming model and an associated implementation for processing and generating large data sets. **Map:** process a key/value pair to generate a set of **intermediate** key/value pairs. **Reduce:** merge **all** intermediate values associated with the same intermediate keys. Advantage: high scalable , easy to use , fault tolerance ## Introduction **Computations in the past for special purpose:** process large amount of raw data(crawled documents, web request logs , etc),to compute various derived data (inverted indices, various representations of the graph structure of web documents, summaries of the number of pages crawled per host). **Why we use need Map Reduce?** When the input data is very large and the computations have to be distributed across hundreds or thousands of machines to finish in a reasonable amount time. **A new abstraction** We cam express simple computations while we hide the messy details of parallelization , fault-tolerance,data distribution and load balancing in library. **Map and Reduce Primitives** Map and Reduce help us parallelize large computations easily and to use **re-execution as the primary** **mechanism** for fault tolerance. ## Programming Model The computation takes a set of input key/value pairs, and produces a set of output key/value pairs. * Map: written by user, take an input pair and produces a set of intermediate key/value pairs. The MapReduce library **groups together all intermediate values associated with the same intermediate key *I* ** and passes them to the **Reduce** function. * Reduce: accepts an intermediate key *I* and a set of values for that key. It merges together these values to form a possibly smaller set of values. The intermediate values are supplied to the user’s reduce function via an iterator . This allows us to handle lists of values that are too large to fit in memory. Examples : count number of occurrence , distributed grep, count of URL access frequency, reverse web-link graph, term-vector per host, inverted index , distributed sort. ## Implementation The implementation depends on the environment. * large clusters of commodity PCs connected together with switched Ethernet * machines are typically dual-processor x86 processors running linux * commodity networking hardware * consist of hundreds of machines * storage is provided by inexpensive disks . A distributed file system developed in-house is used to manage the data stored on these disks. * user submit jobs to a scheduling system ### Execution Overview <img src="C:\Users\15524\AppData\Roaming\Typora\typora-user-images\image-20210126202103661.png" alt="image-20210126202103661" style="zoom:50%;" /> The **Map invocations** are distributed across multiple machines by automatically partitioning the input data into a set of **M** splits. The input splits can be processed in parallel by different machines. **Reduce invocations** are distributed by **partitioning the intermediate key space into R piece**s using a partition function (Mod R?). 1. The MapReduce library in the user program first splits the input files into **M** pieces (16-64MB). It then **starts up many copies of the program** on a cluster of machines. 2. **One of the copies of the program is special : master!** The rest are **workers** are assigned work by the **master.** There are **M** map tasks and **R** reduce tasks to assign. The **master** picks an idle worker and assign a map task or a reduce task. 3. The worker that is running **map** task reads the contents of the corresponding input split. **It parses key/value pairs out of the input data and passes each pair to the user-defined Map function**. The intermediate key/value pair is buffered in memory. 4. Periodically , the buffered pairs are written to local disk , partitioned into **R** regions by the partition function .The location of these buffered pairs on the local disk are passed back to the **master** who is responsible for forwarding these locations to the reduce workers. 5. When a reduce worker is notified by the master about the locations, it uses **remote procedure calls(RPC)** to read the buffered data from the local disks of the map workers. **When the reduce worker has read all intermediate data , it sorts it by the intermediate keys so that all occurrences of the same key are grouped together.** The sorting is needed because typically **many different keys map to the same reduce tasks.** If the amount of intermediate data is too large to fit in memory , an external sort is used.(DB ) 6. The reduce worker iterates over the sorted intermediate data and for each unique intermediate key encountered, it passes the key and the corresponding set of intermediate values to the user’s Reduce function . The output of **Reduce** function is **appended** to **a final output file for this reduce partition.**(**GFS**) 7. When **all** map and reduce tasks have been completed, the master wakes up the user program. At this point , the **MapReduce** call in the user program back to the user code. After successful completion ,the output of the **MapReduce** is available in the **R** output files (one per reduce task,with file names as specified by the user). **What is next?** The **R** out put files do not need to merge , because they often will be passed as the input files as another **MapReduce or other distributed applications**. ### Master Data Structure * **The state(idle ,in-progress or completed)** of each map and reduce task and the identity of the worker machine. * **Conduit** through which the location of intermediate file regions is propagated from map tasks to reduce tasks. Therefore , for each completed map task, **the master stores the locations and sizes** of the **R** intermediate files regions **produced by the map task**. **Updates** to this location and size information are **received** as map tasks are completed. The information is **pushed** incrementally to workers that have *in-progress* reduce tasks. ### Fault Tolerance #### Worker Failure **How to know the worker fails?** The **master** pings every worker periodically . If no response is received from a worker in a certain amount of time , the **master** marks the worker failed.(heart beat message.) **Different situations for worker failure.** * any map tasks completed by the worker are reset back to their initial **idle** state and need to re-executed ,because their output is stored on the local disks that is inaccessible because the worker failure. * any map or reduce task in progress on a failed worker is also **reset** to **idle** state and becomes eligible for rescheduling * Completed **reduce** task do not need to be re-executed since their output is stored in a global file system. **What we need to do when reschedule.** When map task A is executed first by worker A and then later executed by worker B (A failed), **all workers executing reduce tasks are notified of the re-execution,because they may read the data of the local disk in A **. Any reduce task must read data from worker B. **MapReduce is resilient to large-scale worker failures.** #### Master Failure It is easy to make the master write periodic checkpoints of the master data structures described above. If there is only one master , the client can check for this condition and retry the **MapReduce** operation if they desire. #### Semantics in the Presence of Failures When the user-supplied map and reduce operators are **deterministic functions** of their input values, our distributed implementation **produces the same output as would have been produced by a non-faulting sequential execution of the entire program.** We **rely on atomic commits** of map and reduce task outputs to achieve this property. ? When the map and/or reduce operators are nondeterministic, we provide **weaker but still reasonable** semantics. In the presence of non-deterministic operators, **the output of a particular reduce task R1 is equivalent to the output for R1 produced by a sequential execution of the non-deterministic program.** However, t**he output for a different reduce task R2 may correspond to the output for R2 produced by a different sequential execution of the non-deterministic program.** Consider map task M and reduce tasks R1 and R2. Let e(Ri) be the execution of Ri that committed (there is exactly one such execution). **The weaker semantics arise because e(R1) may have read the output produced** **by one execution of M and e(R2) may have read the output produced by a different execution of M.** ? ### Locality Read data from local disk (which is the machine that has the replica) **Network Bandwidth** is a relatively scarce resource in our computing environment. We converse network by taking advantage of the fact that the input data (**managed by GFS**) is **stored on the local disks of the machine** that make up out cluster. **GFS** divides each file into 64MB block, and store several replicas on different machines . The **MapReduce** master takes the location of the input files into account (which is managed by GFS master) and attempts to schedule a **map task** on the machine that has the **replica of the corresponding input data.** If we can not do that , the master attempts to assign the **map** task to the **machine which is near the replica of the data**. (i.e. on a worker machine that is on the same network switch as the machine containing the data). ### Task Granularity **Map: M pieces Reduce: R pieces** Ideally,M and R should be much larger than the number of worker machines. Advantages: * each worker perform many different tasks improve dynamic load balancing * speed up recovery when worker failure, the task is small ;the many map tasks it has completed can be spread out across all the other worker machines **Practical bounds for M and R** Master must make **O(M+R) schedule** and keeps **O(M*R) state in memory** (the constant factors for memory usage are small : per map task one byte.) **R** is considered by user , are R separated files may be used by distributed applications or MapReduce. **M** ranges roughly from 16MB - 64 MB considering about locality ,because the chunk size is 64MB. M = 200000 R =5000 using 2000worker ### Backup Tasks **How to lengthen the total time taken for a MapReduce operation?** **Straggler.** a machine that takes an **unusually long time** to complete **one of the last few map or reduce tasks in the computation.** **Why straggler?** * a machine with a bad disk may experience frequent correctable errors that slow its read performance from 30 MB/s to 1 MB/s. * The cluster scheduling system may have scheduled other tasks on the machine, causing it to execute the MapReduce code more slowly due to competition for CPU, memory, local disk, or network bandwidth. * a **bug** in machine initialization code that caused processor caches to be disabled: computations on affected machines slowed down by over a factor of one hundred. **How to alleviate the problem?** * When a MapReduce operation is close to completion, the master schedules **backup executions of the remaining in-progress tasks. **The task is marked as completed whenever either the primary or the backup execution completes. * We have tuned this mechanism so that it typically increases the computational resources used by the operation by no more than a few percent. We have found that this significantly reduces the time to complete large MapReduce operations. ## Refinements ### Partitioning Function The usually partition function is **Mod** depends on the number of output files that user want. If we deal with the URL and we want all entries for a single host to end up in the same output file , we may need **Hash( Host Name ( Url Key))**. ### Ordering Guarantees We **guarantee** that within a given partition, **the intermediate key/value pairs are processed in increasing key order.** This ordering guarantee **makes it easy to generate a sorted output file format** needs to support efficient random access lookups by key , or user of the output find it convenient to have the data sorted. ### Combiner Function The combiner function is executed on each machine that performs a map task. Typically the same code is used on the reduce function. **The different** How the **MapReduce** Library handles the output of the function. * The output of the reduce function is written to the final output file * The output of a combiner function is written to an intermediate file that will be sent to a reduce task. In the case of the word count , many words in each map task will produce the record “word,1” , these records will be merge in the reduce task finally , cost much. We need to combine it after the finish of the map and before sending it to the reduce. ### Input and Output Types Input types: * **Text:** treat each line as a key/value pair ; * the key is the offset in the file * the value is the contents of the line. * Another format : a sequence of key/value pairs sorted by key * add supported format through implementing the interface **reader** It is similar in output types. ### Side - effects In some cases , users of MapReduce have found it **convenient to produce auxiliary files** as **additional outputs** from their map and/or reduce operators. We rely on the application writer to **make such side-effects atomic and idempotent.** Typically the application writes to a temporary file and **atomically renames** this file once it has been fully generated . We do not provide support for atomic two-phase commits of multiple output files produced by a single task. Therefore , tasks that produce multiple output files with cross-file consistency requirements should be **deterministic** . (每次输出都需要相同)This restriction has never been an issue in practice. ### Skipping Bad Records Sometimes there are bugs in user code that cause the **Map or Reduce** to crash deterministically on certain record. * fix the bug , sometimes it not feasible ,perhaps the bug is in the third-party library * ignore a few records that cause the bug Each worker process **installs a signal handler that catches segmentation violations and bus errors**. Before invoking a user Map or Reduce operation, the MapReduce library **stores the sequence number of the argument in a global variable** . If the user code generates a signal, **the signal handler sends a “last gasp” UDP packet that contains the sequence number to the MapReduce master**. When the master has seen more than one failure on a particular record, it indicates that **the record should be skipped when it issues the next re-execution of the corresponding Map or Reduce task**. ### Local Execution help debugging profiling , small-scale test The implementation of MapReduce support that we can sequentially execute all of the work for a MapReduce operation on the local machine. ### Status Information The master runs an internal HTTP server and exports a set of status pages for human consumption. * the progress of computation such as how many tasks have been completed , how many are in progress , bytes of input , bytes of intermediate data , bytes of output * links to standard error and standard output files generated by each task * top-level status page shows which worker have failed , and which map and reduce tasks they were processing when they failed The user can use these data to predict how long the computation will cost and whether or not more resources should be added to the computation. These pages can also be used to figure out when the computation is much slower than expected ### Counters The MapReduce library provides a counter facility to count the occurrences of various events.
C++
UTF-8
4,042
3.59375
4
[]
no_license
#include "bst.h" namespace dk{ BSTNode* GetNewNode(int value){ BSTNode* node = new BSTNode; node->data=value; node->left=nullptr; node->right=nullptr; return node; } BSTNode* BSTNodeExists(BSTNode* node, int value){ if(node==nullptr){ return node; } else if(value > node->data){ return BSTNodeExists(node->right, value); } else if(value < node->data){ return BSTNodeExists(node->left, value); } else{ return node; } } BSTNode* Insert(BSTNode * node, int value){ if(node==nullptr){ node=GetNewNode(value); return node; } if(value >= node->data){ node->right=Insert(node->right, value); } else if(value < node->data){ node->left=Insert(node->left, value); } return node; } void DeleteTree(BSTNode* node){ if(node==nullptr){ return; } if(node->left!=nullptr){ DeleteTree(node->left); } if(node->right!=nullptr){ DeleteTree(node->right); } delete node; } int GetMin(BSTNode* node){ if(node==nullptr){ std::cout<<"Empty in min!"; return -1; } if(node->left!=nullptr){ return GetMin(node->left); } else{ return node->data; } } int GetMax(BSTNode* node){ if(node==nullptr){ return -1; } if(node->right!=nullptr){ return dk::GetMax(node->right); } else{ return node->data; } } int GetHeight(BSTNode* node){ if(node==nullptr){ return 0; } else{ return 1 + std::max(GetHeight(node->left),GetHeight(node->right)); } } void PrintBFS(BSTNode* node){ std::queue<BSTNode*> nodes; nodes.push(node); BSTNode* current; while(!nodes.empty()){ current=nodes.front(); nodes.pop(); if(current!=nullptr){ std::cout<<current->data<<" "; } if(current->left!=nullptr){ nodes.push(current->left); } if(current->right!=nullptr){ nodes.push(current->right); } } std::cout<<std::endl; } void PrintInOrder(BSTNode* node){ if(node==nullptr){ return; } PrintInOrder(node->left); std::cout<<node->data<<" "; PrintInOrder(node->right); } bool IsBinarySearchTree(BSTNode* node){ return IsBetween(node,INT_MAX,INT_MIN); } bool IsBetween(BSTNode* node, int max, int min){ if(node==nullptr){ return true; } if(node->data>min && node->data<max && IsBetween(node->left, node->data, min) && IsBetween(node->right, max, node->data)){ return true; } else{ return false; } } BSTNode* GetMinNode(BSTNode* node){ if(node==nullptr){return node;} if(node->left!=nullptr){ GetMinNode(node->left); } else{ return node; } } BSTNode* DeleteValue(BSTNode* node, int value){ if(node==nullptr){return node;} if(value>node->data){ node->right=DeleteValue(node->right, value); } else if(value<node->data){ node->left=DeleteValue(node->left, value); } else{ //node is the node to delete //leaf node if(node->left==nullptr && node->right==nullptr){ delete node; node=nullptr; } //One child: right else if(node->left==nullptr){ BSTNode* todelete=node; node=node->right; delete todelete; } //One child: left else if(node->right==nullptr){ BSTNode* todelete=node; node=node->left; delete todelete; } //Two children else{ BSTNode* toswap=GetMinNode(node->right); node->data=toswap->data; node->right=DeleteValue(node->right, toswap->data); } } } BSTNode* GetSuccessor(BSTNode* node, int value){ BSTNode* value_node=BSTNodeExists(node, value); if(value_node==nullptr){return value_node;} if(value_node->right != nullptr){ return GetMinNode(value_node->right); } else{ //Deepest node with value_node in it's left subtree BSTNode* successor=nullptr; BSTNode* ancestor=node; while(ancestor!=nullptr){ if(value < ancestor->data){ successor=ancestor; ancestor=ancestor->left; } else{ ancestor=ancestor->right; } } return successor; } } } //namespace dk
Markdown
UTF-8
4,084
2.53125
3
[ "MIT" ]
permissive
# History <!-- Overview --> <!-- from Google Drive document, 'RCOS History-June 2017' --> <!-- RCOS was founded in 2006 from a generous donation of $2,000,000 from Mr. Sean O’Sullivan ‘85. I think that Dr. P. Hajela (Dean of Undergraduate education at that time) and Dr. F. Luk (Professor of Computer Science) were instrumental in getting the fund. You will see a document describing RCOS Rationale in this directory. --> <!-- Initial donation was to the tune of $250,000. Dr. Luk was the first director of this center (I think). On Dr. Luk’s resignation in 2007, a call for directorship went to a few CS Faculty Advisors in March 2007. The directorship has to be joint between Computer Science Department and Computer and Systems Engineering Department. Dr. B. Roysam was appointed from computer systems engineering department I was appointed from the computer science department. (I was the only person who volunteered ) --> <!-- > NOTE - almost all the content below was taking from the following [RCOS OverviewJan16,2018-old presentation](https://docs.google.com/presentation/d/1mX6wNaIBUDo1RnLvu1POPQGLMi4wp8OA44SbA5C7xHM/edit#slide=id.g827926ff0_0_0). It needs to be refined a bit more now that it's been ported to the RCOS handbook. --> ### Overview RCOS was founded in 2006 by a generous $2M donation from [Sean O'Sullivan](https://sosf.us/rensselaer/). Past and current leadership: - 2006-2007: Frank Luk, Director - 2007-2010: Badri Roysam, Mukkai Krishnamoorthy, co-Directors - 2010-2013: Mukkai Krishnamoorthy, Director - 2013-2016: Mukkai Krishnamoorthy, David Goldschmidt, co-Directors - 2016-2018: Mukkai Krishnamoorthy, David Goldschmidt, Wes Turner, co-Directors/Advisor - 2018-2022: David Goldschmidt, Wes Turner, co-Directors/Advisor - 2022-present: Konstantin Kuzmin, David Goldschmidt, Wes Turner, co-Directors/Advisor The program gained momentum in 2007 with launch of Open Source Software course. Funding was rejuvenated by Red Hat in 2015. <!-- ### Mission Statement --> <!-- > To provide a creative, intellectual, and entrepreneurial outlet for students to use the latest open-source software platforms to develop applications that solve societal problems. --> <!-- ###### --> <!-- ### Hack Prizes (sampling) --> <!-- Chris Sprague (RCOS member) and his team team won an award in the Spark Innovation competition held on March 25, 2017 at Syracuse. --> <!-- Charlie You’18 Third place in the Change the World Challenge, Spring 2017 for Chloe.a --> <!-- Kathleen Burkhardt'19 for her RedFlag Project in HackRPI 2016 which won an award Best Domain and HackHarassment Project --> <!-- Josh Makkinen '16 won Google API Prize (Bose Speaker) and the Best Hardware Hack (ssd) in HackRPI 2015. --> <!-- Jim Boulter '17 and Kiana McNellis '17 won the jetblue API award at YHack 2015 --> <!-- Eric Zhang ‘17 won the grandprize in YHack 2015 --> <!-- Aaron Perl '18 won the "Best Hardware Hack" in the HackRU 2015 (Hackathon at Rutgers University). --> <!-- Jacob Martin, Noah Goldman, Erin Quin, Satoshi Masura are finalists in HackUMass’15 --> <!-- ### OSI Membership --> <!-- We Became an Affiliate Member of OSI --> ### RedHat Funding (2014-2015) Thrust: To improve the overall quality of RCOS projects and to increase diversity - Funding Level $180,000 - Funds two RCOS projects per year - Funds the development of two (one CS and one HASS) freshmen/sophomore-level courses on Open Source - Funds Undergraduate Mentors for two new courses ### RedHat Funding (contd) - Diversity Hackathon - April 16-17, 2016 - Primarily Hackathon for women students in Capital District universities, colleges and high schools - Coordinated jointly with Pearlhacks and RedHat - CSCI 296x Introduction to Open Source was taught in Fall 2015 and Spring 2016. - Aimed at Freshmen and Sophomores - Enrollment around 35 students - Bring students up to speed to join RCOS - Syllabus and Other details may be found at http://rcos.github.io/CSCI2961-01/ and https://github.com/rcos/CSCI2961-01 ### Going Forward - Sustain projects over semesters - Provide resources for Project Leads - Increase the sophistication of RCOS Projects - Increase the diversity of participants - Increase projects using new hardware - Increased interaction with OSI and other universities
C++
UTF-8
1,415
2.734375
3
[]
no_license
#pragma once #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #include <unistd.h> #include <time.h> #include <string> #include <vector> namespace base { class UnixSocket { public: typedef enum { eSocketType_None = 0, eSocketType_Stream, eSocketType_Dgram, } SOCKETTYPE; UnixSocket(); UnixSocket(SOCKETTYPE eSocketType); UnixSocket(SOCKETTYPE eSocketType, int fd); UnixSocket(const UnixSocket& o); UnixSocket(const UnixSocket&& o); virtual ~UnixSocket(); UnixSocket& operator=(const UnixSocket& o); bool isValid(); void reset(); // true: success. // false: fail. bool create(SOCKETTYPE socketType = eSocketType_None); bool setRemoteAddr(const std::string& addr); bool setLocalAddr(const std::string& ipaddr); bool listen(); bool bind(const std::string& addr = ""); bool connect(const std::string& addr = ""); UnixSocket accept(); int fd(); std::string getRemoteAddr(); std::string getLocalAddr(); int recv(void * buf, size_t len); int send(const void * buf, size_t len); const char * lastErrorMessage(); public: virtual void onReadData(const void * buf, int len) {} virtual void onDisconnected(void) {} private: int mSock; SOCKETTYPE mSockType; sockaddr_un mRemote; sockaddr_un mLocal; }; } // namespace base
Java
UTF-8
372
1.796875
2
[ "Apache-2.0" ]
permissive
package com.example.msonasath.instaclient.models; /** * Created by m.sonasath on 12/1/2015. */ public class InstaPhoto { public String username; public String caption; public String imageUrl; public int imageHeight; public int likesCount; public String userImageUrl; public String userFullName; public long createdTime; }
Java
UTF-8
1,133
2.546875
3
[]
no_license
/** * ----------------------------------------------------------------------- * Copyright 2010 ShepHertz Technologies Pvt Ltd. All rights reserved. * ----------------------------------------------------------------------- */ package com.spring.revisited.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.revisited.bean.xml.TextEditor; /** * @author Vishnu Garg * @created On Aug 4, 2018 * */ public class XMLAutowiringExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans_autowiring.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); //spellChecker bean id should be same as the name refrence in TextEditot te.spellCheck(); //byName bean id should be same as property Name defined in text editot //byType it will search for the class that is injected no need whether id and property name are same or not // constructor same as by type } }
Java
UTF-8
3,179
1.859375
2
[]
no_license
package com.calculatedfun.bean.wms.de; import java.util.Date; public class IReceiptConfim { private int sid; private String company; private String wareHouse; private String receiptId; private String receiptType; private Date receiptDate; private String remark; private int totalCount; private int status; private int extimes; private Date updatetime; private Date createtime; private String item; private String itemName; private Integer itemCount; private String inventorySts; private String expirationDate; public IReceiptConfim() { } public IReceiptConfim(IReceiptConfim iReceiptConfim) { this.company = iReceiptConfim.company; this.wareHouse = iReceiptConfim.wareHouse; this.receiptId = iReceiptConfim.receiptId; this.receiptType = iReceiptConfim.receiptType; this.receiptDate = iReceiptConfim.receiptDate; this.remark = iReceiptConfim.remark; this.totalCount = iReceiptConfim.totalCount; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getwareHouse() { return wareHouse; } public void setwareHouse(String warehouse) { this.wareHouse = warehouse; } public String getreceiptId() { return receiptId; } public void setreceiptId(String receiptid) { this.receiptId = receiptid; } public String getreceiptType() { return receiptType; } public void setreceiptType(String receipttype) { this.receiptType = receipttype; } public Date getreceiptDate() { return receiptDate; } public void setreceiptDate(Date receiptdate) { this.receiptDate = receiptdate; } public String getremark() { return remark; } public void setremark(String remark) { this.remark = remark; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getExtimes() { return extimes; } public void setExtimes(int extimes) { this.extimes = extimes; } public Date getUpdatetime() { return updatetime; } public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getitemName() { return itemName; } public void setitemName(String itemName) { this.itemName = itemName; } public Integer getitemCount() { return itemCount; } public void setitemCount(Integer itemCount) { this.itemCount = itemCount; } public String getinventorySts() { return inventorySts; } public void setinventorySts(String inventorySts) { this.inventorySts = inventorySts; } public int gettotalCount() { return totalCount; } public void settotalCount(int totalCount) { this.totalCount = totalCount; } public String getexpirationDate() { return expirationDate; } public void setexpirationDate(String expirationDate) { this.expirationDate = expirationDate; } }
C++
UTF-8
39,956
2.53125
3
[]
no_license
#include "Evento.h" #include "Mensaje.h" #define PI 3.14159265 Evento::Evento(double X1, double X2, double X3, map<int, vector<double> > mapaDistros, long tiempo){ this->tiempoSimulacion = tiempo; this->idMensajeGlobal = 0; this->arriboCompu1C3 = 0; this->arriboCompu1P1 = 0; this->arriboCompu1P2 = 0; this-> arriboCompu2 = 0; this->arriboCompu3 = 0; this->X1 = X1; this->X2 = X2; this->X3 = X3; this->proc1 = false; //El proc1 esta desocupado al inicio this->idMensajeP1 = -1; this->proc2 = false; //El proc1 esta desocupado al inicio this->idMensajeP2 = -1; this->proc3 = false; //El proc1 esta desocupado al inicio this->idMensajeP3 = -1; this->proc4 = false; //El proc1 esta desocupado al inicio this->idMensajeP4 = -1; //Inicializacion para las probas this->mapaD = mapaDistros; //Estadisticas this->tiemposProcesadores.resize(4,0); this->tiempoProc1Perdidos = 0; this->tiempoProc4Perdidos = 0; this->mensajesEliminados = 0; this->sumatoriaTiemposMensajes = 0; this->sumatoriaVecesDevuelto = 0; this->tiempoColas = 0; this->tiempoTransmicion = 0; this->sumatoriaTiempoReal = 0; srand(time(0)); } Evento::~Evento(){} /*@Funcion: limpia todas las variables utilizadas en la simulacion para cada vez que se corre y no queden variables con contenido de corridas anteriores que afecten los calculos */ void Evento::LimpiarSimulacion(){ this->idMensajeGlobal = 0; this->arriboCompu1C3 = 0; this->arriboCompu1P1 = 0; this->arriboCompu1P2 = 0; this-> arriboCompu2 = 0; this->arriboCompu3 = 0; this->proc1 = false; //El proc1 esta desocupado al inicio this->idMensajeP1 = -1; this->proc2 = false; //El proc1 esta desocupado al inicio this->idMensajeP2 = -1; this->proc3 = false; //El proc1 esta desocupado al inicio this->idMensajeP3 = -1; this->proc4 = false; //El proc1 esta desocupado al inicio this->idMensajeP4 = -1; //Estadisticas for (int i = 0; i < tiemposProcesadores.size(); ++i) { tiemposProcesadores[i] = 0; } this->tiempoProc1Perdidos = 0; this->tiempoProc4Perdidos = 0; this->mensajesEliminados = 0; this->sumatoriaTiemposMensajes = 0; this->sumatoriaVecesDevuelto = 0; this->tiempoColas = 0; this->tiempoTransmicion = 0; this->sumatoriaTiempoReal = 0; this->mensajes.clear(); // Colas de transmicion this->colaTransmicion1.clear(); this->colaTransmicion2.clear(); this->colaTransmicion3.clear(); //Colas de mensajes en espera this->colaProc1.clear(); this->colaProc2.clear(); this->colaProc4.clear(); } /* @Funcion: simula el evento "Finalizacion de procesamiento del mensaje de la computadora 1" donde se toma en cuenta cuando se tiene que regresar tanto a la computadora 2 como a la 3 o si se tiene que devolver a su destino. Ademas revisa si hay algun mensaje esperando en su cola para atenderlo. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::FC1 ( long tiempoEvento, vector<long> *eventos){ long relojEvento = tiempoEvento ; //srand(time(NULL)); //Calculos probabilisticos long tiempoRealProc = relojEvento - mensajes[this->idMensajeP1].tiempoInicioTrabajo; mensajes[this->idMensajeP1].tiempoRealProc += tiempoRealProc; mensajes[this->idMensajeP1].tiempoProc1 += tiempoRealProc; //cout<<"------------- soy el mensaje: "<<this->idMensajeP1<<"-------------------" <<endl; double num = drand48(); if (mensajes[this->idMensajeP1].tiempoProc4 == 0){ //printf("Me llego un mensaje de la cpmputadora 2\n"); //cout<<"Tiempo proc4: "<< mensajes[this->idMensajeP1].tiempoProc4<<"Tiempo proc2: "<< mensajes[this->idMensajeP1].tiempoProc2 <<" Tiempo proc3: "<< mensajes[this->idMensajeP1].tiempoProc3 <<endl; //El mensaje proviene de la compu 2 if (num <= this->X1){ //El mensaje se va a reenviar a la compu 2 long tiempollegada = tiempoEvento + 3; mensajes[this->idMensajeP1].tiempoTransmicion += 3; mensajes[this->idMensajeP1].tiempoLlegada = tiempollegada; mensajes[this->idMensajeP1].vecesDevuelto++; colaTransmicion2.push_back(this->idMensajeP1); if (eventos->at(4) == this->tiempoSimulacion*4){ //Ponemos que el primero de la cola de transicion es el que debe de llegar eventos->at(4) = mensajes[colaTransmicion2[0]].tiempoLlegada; this->arriboCompu2 = colaTransmicion2[0]; colaTransmicion2.erase(colaTransmicion2.begin()); } }else { //Se envia al destino(sale del sistema todo meco) mensajes[this->idMensajeP1].estado = 2; this->tiemposProcesadores[0] += mensajes[this->idMensajeP1].tiempoProc1; // Almacena tiempo en proc1 this->tiemposProcesadores[1] += mensajes[this->idMensajeP1].tiempoProc2; // Almacena tiempo en proc2 this->tiemposProcesadores[2] += mensajes[this->idMensajeP1].tiempoProc3; // Almacena tiempo en proc3 this->sumatoriaTiemposMensajes += (mensajes[this->idMensajeP1].tiempoTransmicion + mensajes[this->idMensajeP1].tiempoRealProc + mensajes[this->idMensajeP1].tiempoEnColas); this->sumatoriaVecesDevuelto += mensajes[this->idMensajeP1].vecesDevuelto; this->tiempoColas += mensajes[this->idMensajeP1].tiempoEnColas; this->tiempoTransmicion += mensajes[this->idMensajeP1].tiempoTransmicion; this->sumatoriaTiempoReal += mensajes[this->idMensajeP1].tiempoRealProc; } }else if (mensajes[this->idMensajeP1].tiempoProc2 == 0 && mensajes[this->idMensajeP1].tiempoProc3 == 0){ //El mensaje proviene de la compu 3 if (num <= this->X3){ //Reenvia a la compu 3 //printf("Voy a reenviar el mensaje a la compu 3\n"); mensajes[this->idMensajeP1].tiempoTransmicion += 3; long tiempollegada = tiempoEvento + 3; mensajes[this->idMensajeP1].tiempoLlegada = tiempollegada; mensajes[this->idMensajeP1].vecesDevuelto++; colaTransmicion3.push_back(this->idMensajeP1); if (eventos->at(9) == this->tiempoSimulacion*4){ //Ponemos que el primero de la cola de transicion es el que debe de llegar eventos->at(9) = mensajes[colaTransmicion3[0]].tiempoLlegada; this->arriboCompu3 = colaTransmicion3[0]; colaTransmicion3.erase(colaTransmicion3.begin()); } }else { //Se envia al destino (sale del sistema todo meco) //printf("Voy a enviar el mensaje a su destino\n"); mensajes[this->idMensajeP1].estado = 2; this->tiemposProcesadores[0] += mensajes[this->idMensajeP1].tiempoProc1; // Almacena tiempo en proc1 this->tiemposProcesadores[3] += mensajes[this->idMensajeP1].tiempoProc4; // Almacena tiempo en proc4 this->sumatoriaTiemposMensajes += (mensajes[this->idMensajeP1].tiempoTransmicion + mensajes[this->idMensajeP1].tiempoRealProc + mensajes[this->idMensajeP1].tiempoEnColas); this->sumatoriaVecesDevuelto += mensajes[this->idMensajeP1].vecesDevuelto; this->tiempoColas += mensajes[this->idMensajeP1].tiempoEnColas; this->tiempoTransmicion += mensajes[this->idMensajeP1].tiempoTransmicion; this->sumatoriaTiempoReal += mensajes[this->idMensajeP1].tiempoRealProc; } } eventos->at(0) =this->tiempoSimulacion*4;//Desprograma evento 1 this->proc1 = false; mensajes[this->idMensajeP1].tiempoInicioTrabajo = 0; this->idMensajeP1 =-1; //Revisar la cola(proc) para atender a un mensaje que espera a ser atendido if (this->colaProc1.size() != 0){ //Existen mensajes esperando en la cola de la computadora 1 /*if (relojEvento < mensajes[colaProc1[0]].tiempoEntradaCola ){ cout << "tiempo evento : "<<tiempoEvento << ", tiempoEntradaCola : "<< mensajes[colaProc1[0]].tiempoEntradaCola<<endl; }*/ long tiempoEnCola = tiempoEvento - mensajes[colaProc1[0]].tiempoEntradaCola; mensajes[colaProc1[0]].tiempoEnColas += tiempoEnCola; this->proc1 = true; //El proc1 vuelve a estar ocupado this->idMensajeP1 = colaProc1[0]; map<int , vector<double> >::iterator map = mapaD.find(6); eventos->at(0) = relojEvento + Manejador((*map).second); mensajes[colaProc1[0]].tiempoInicioTrabajo = relojEvento; colaProc1.erase(colaProc1.begin()); // quitamos el consumido } return relojEvento; } /* @Funcion: simula el evento "Arribo de un mensaje a la computadora 1 del proc 1 de la computadora 2" en donde se si el procesador 1 esta ocupado lo agrega a la cola y si no lo procesa donde se considera la distribucion indicada por el usuario. Ademas se revisa la cola de transicion del procesador 1 en caso de que no este vacia se asigna el proximo en llegar al sistema @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC1P1C2(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; //Revisamos el proc1 a ver su estado if(proc1){ //El proc1 esta ocupado por lo que el mensaje que llega lo metemos en la cola colaProc1.push_back(this->arriboCompu1P1); // añadimos el id a la cola mensajes[this->arriboCompu1P1].tiempoEntradaCola = relojEvento; }else{ //El proc1 estaba disponible proc1 = true; this->idMensajeP1 = arriboCompu1P1; map<int , vector<double> >::iterator map = mapaD.find(6); eventos->at(0) = relojEvento + Manejador((*map).second); // Programamos el fin de trabajo mensajes[idMensajeP1].tiempoInicioTrabajo = relojEvento; } eventos->at(2) = this->tiempoSimulacion*4;// Desprograma el evento //Debemos revisar la cola de transicion para poder asignar el proximo arribo if (!colaTransmicion1.empty()){ this->arriboCompu1P1 = colaTransmicion1[0]; // asignamos cual sera el proximo en llegar eventos->at(2) = mensajes[colaTransmicion1[0]].tiempoLlegada ; // programamos la llegada a este evento por parte de un mensajeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee colaTransmicion1.erase(colaTransmicion1.begin()); } return relojEvento; } /* @Funcion: simula el evento "Arribo de un mensaje a la computadora 1 del proc 2 de la computadora 2" en donde si el procesador 1 esta ocupado agrega el mensaje actual a la cola y si no, lo procesa de una vez donde se considera la distribucion indicada por el usuario del tiempo que tarda en atender a ese mensaje. Ademas se revisa la cola de transicion del procesador 1 y en caso de que no este vacia se asigna el proximo en llegar al sistema @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC1P2C2(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; //Revisamos el proc1 a ver su estado if(proc1){ //El proc1 esta ocupado por lo que el mensaje que llega lo metemos en la cola colaProc1.push_back(this->arriboCompu1P2); // añadimos el id a la cola mensajes[this->arriboCompu1P2].tiempoEntradaCola = relojEvento; }else{ //El proc1 estaba disponible proc1 = true; this->idMensajeP1 = arriboCompu1P2; map<int , vector<double> >::iterator map = mapaD.find(6); eventos->at(0) = relojEvento + Manejador((*map).second); // Programamos el fin de trabajo mensajes[idMensajeP1].tiempoInicioTrabajo = relojEvento; } eventos->at(3) = this->tiempoSimulacion*4;// Desprograma el evento //Debemos revisar la cola de transicion para poder asignar el proximo arribo if (!colaTransmicion1.empty()){ this->arriboCompu1P2 = colaTransmicion1[0]; // asignamos cual sera el proximo en llegar eventos->at(3) = mensajes[colaTransmicion1[0]].tiempoLlegada; // programamos la llegada a este evento por parte de un mensajeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee colaTransmicion1.erase(colaTransmicion1.begin()); } return relojEvento; } /* @Funcion: simula el evento "Arribo de un mensaje a la computadora 1 de la computadora 3" en donde se revisa si el procesador 1 esta ocupado, si lo esta agrega el mensaje actual a la cola y si no, lo procesa de una vez donde se considera la distribucion indicada por el usuario del tiempo que tarda en atender a ese mensaje asi como se asigna el tiempo inicial en el que comienza a ser atendido. Ademas se revisa la cola de transicion del procesador 1 y en caso de que no este vacia se asigna el proximo en llegar al sistema. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC1C3( long tiempoEvento, vector<long> *eventos){ long relojEvento = tiempoEvento; //Se revisa para ver si el proc1 esta ocupado o no if (proc1){ //El proc esta ocupado colaProc1.push_back(this->arriboCompu1C3); mensajes[arriboCompu1C3].tiempoEntradaCola = relojEvento; }else{ //El proc1 no esta ocupado proc1 = true; this->idMensajeP1 = arriboCompu1C3; // Asignamos el mensaje en que esta siendo atendido por P1 map<int , vector<double> >::iterator map = mapaD.find(6); eventos->at(0) = tiempoEvento + Manejador((*map).second); mensajes[idMensajeP1].tiempoInicioTrabajo = relojEvento; } eventos->at(1) = this->tiempoSimulacion*4; // Se desprograma este evento //Se revisa la cola de transicion para ver si hay mensajes que vienen de camino y si los hay ponemos ese valor como evento[1] if (!colaTransmicion1.empty()){ eventos->at(1) = mensajes[colaTransmicion1[0]].tiempoLlegada; // RePrograma el arribo this->arriboCompu1C3 = colaTransmicion1[0]; // Se asigna id del mensaje para poder trabajar colaTransmicion1.erase(colaTransmicion1.begin()); } return relojEvento; } /* @Funcion: simula el evento "Arribo de un mensaje a la computadora 2 de la computadora 1" en donde se revisan los procesadores de la compuatdora 2 para ver si alguno esta disponible, en cuyo caso se calcula el tiempo que tarda en ser procesado con las distribuciones asi como se marca el incio de tiempo en donde comienza ser realmente procesado por el procesador correspondiente, si no es asi se pone en la cola y se marca el tiempo en el que entro a la cola. Ademas tambien se revisa si hay algun mensaje en la cola de transicion que tenga que ser procesada. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC2C1(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; //revisamos los proc2 y proc3 if (proc2 && proc3){ //Ambos proc estan ocupados entonces el mensaje ah de ir a la cola colaProc2.push_back(this->arriboCompu2); mensajes[this->arriboCompu2].tiempoEntradaCola = relojEvento; }else if (proc2 && !proc3){ //El proc3 esta desocupado el mensaje se puede meter ahi proc3 = true; // El proc3 ahora esta ocupado this->idMensajeP3 = this->arriboCompu2; // almacenamos el idMensaje map<int , vector<double> >::iterator map = mapaD.find(3); eventos->at(7) = relojEvento + Manejador((*map).second); // Alistamos el evento de salida mensajes[this->arriboCompu2].tiempoInicioTrabajo = relojEvento; }else if (proc3 && !proc2){ //El proc2 esta desocupado el mensaje se puede meter ahi proc2 = true; this->idMensajeP2 = this->arriboCompu2; // asignamos el mensaje map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(6) = relojEvento + Manejador((*map).second); mensajes[this->arriboCompu2].tiempoInicioTrabajo = relojEvento; }else { //Si ambos estan desocupados se debe decidir a cual de los dos va a entrar //srand(time(NULL)); double num = drand48() ; if (num <= 0.5 ){ //Lo ponemos en el proc2 proc2 = true; this->idMensajeP2 = this->arriboCompu2; // asignamos el mensaje map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(6) = relojEvento + Manejador((*map).second); mensajes[this->arriboCompu2].tiempoInicioTrabajo = relojEvento; }else{ //lo ponemos en el proc3 proc3 = true; // El proc3 ahora esta ocupado this->idMensajeP3 = this->arriboCompu2; // almacenamos el idMensaje map<int , vector<double> >::iterator map = mapaD.find(3); eventos->at(7)= relojEvento + Manejador((*map).second); // Alistamos el evento de salida mensajes[this->arriboCompu2].tiempoInicioTrabajo = relojEvento; } } eventos->at(4) = this->tiempoSimulacion*4; // Desprogramamos el arribo //Revisamos la cola de transmicion para "reprogramar el arribo desde la comp1" if (colaTransmicion2.size() != 0){ // La cola no esta vacia o sea podemos reprogramar un arribo eventos->at(4) = mensajes[colaTransmicion2[0]].tiempoLlegada; // Reprogramamos el arribo this->arriboCompu2 = colaTransmicion2[0]; colaTransmicion2.erase(colaTransmicion2.begin()); // elimnamos de la cola de transmicion } return relojEvento; } /* @Funcion: simula el evento "Arribo de un mensaje a la computadora 2 desde afuera" en donde se revisan los procesadores de la computadora 2 para ver si alguno esta disponible, en cuyo caso se calcula el tiempo que tarda en ser procesado con las distribuciones asi como se marca el incio de tiempo en donde comienza ser realmente procesado por el procesador correspondiente, si no es asi se pone en la cola y se marca el tiempo en el que entro a la cola. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC2F(long tiempoEvento,vector<long> *eventos){ //printf("Entre al evento 5\n"); long relojEvento = tiempoEvento; //Se revisan los procesadores a ver si alguno esta desocupado Mensaje mensaje(this->idMensajeGlobal); long idMensaje = idMensajeGlobal; this->idMensajeGlobal++; // Se creo un mensaje nuevo this->mensajes.push_back(mensaje); if (proc2 && proc3){ //Ambos proc estan ocupados entonces el mensaje ah de ir a la cola colaProc2.push_back(idMensaje); mensajes[idMensaje].tiempoEntradaCola = relojEvento; }else if (proc2 && !proc3){ //El proc3 esta desocupado el mensaje se puede meter ahi proc3 = true; // El proc3 ahora esta ocupado this->idMensajeP3 = idMensaje; // almacenamos el idMensaje map<int , vector<double> >::iterator map = mapaD.find(3); eventos->at(7) = relojEvento + Manejador((*map).second); // Alistamos el evento de salida mensajes[idMensaje].tiempoInicioTrabajo = relojEvento; }else if (proc3 && !proc2){ //El proc2 esta desocupado el mensaje se puede meter ahi proc2 = true; this->idMensajeP2 = idMensaje; // asignamos el mensaje map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(6) = relojEvento + Manejador((*map).second); mensajes[idMensaje].tiempoInicioTrabajo = relojEvento; }else { //Si ambos estan desocupados se debe decidir a cual de los dos va a entrar //srand(time(NULL)); double num = drand48(); if (num <= 0.5 ){ //Lo ponemos en el proc2 proc2 = true; this->idMensajeP2 = idMensaje; // asignamos el mensaje map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(6) = relojEvento + Manejador((*map).second); mensajes[idMensaje].tiempoInicioTrabajo = relojEvento; }else{ //lo ponemos en el proc3 proc3 = true; // El proc3 ahora esta ocupado this->idMensajeP3 = idMensaje; // almacenamos el idMensaje map<int , vector<double> >::iterator map = mapaD.find(3); eventos->at(7) = relojEvento + Manejador((*map).second); // Alistamos el evento de salida mensajes[idMensaje].tiempoInicioTrabajo = relojEvento; } } map<int , vector<double> >::iterator map = mapaD.find(1); eventos->at(5) = relojEvento + Manejador((*map).second); //cout<<"El evento 5 volvera a pasar en el tiempo: "<<eventos->at(5)<<endl; //cout <<"El reloj es de : "<< relojEvento<< endl; return relojEvento; } /* @Funcion: simula el evento "Finalizacion de procesamiento del mensaje en el proc 1 de la computadora 2" en donde se marca la hora a la cual llegara el mensaje a la computadora 1, asi como se marca el momento en el que se termina de utilizar el procesador 1 de la computadora 2 y se acumula en la variable tiempo realproc2. Ademas se calcula el tiempo de transicion que tarda en llegar a la computadora 1 y se revisa la cola de este procesador para saber si hay algun mensaje para ser procesado y si es así lo procesa y luego lo borra de la cola. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::FC2P1(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; //Se envia un mensaje a la computadora 1 mensajes[idMensajeP2].tiempoTransmicion += 20; // estadisico colaTransmicion1.push_back(idMensajeP2); mensajes[idMensajeP2].tiempoLlegada = relojEvento +20; // Importanteeeee //Comprobamos si ya se programo el arribo a la computadora 1 if (eventos->at(2) == this->tiempoSimulacion*4) { //Hemos de progrmar el siguiete arribo eventos->at(2) = mensajes[colaTransmicion1[0]].tiempoLlegada; // Programamos this->arriboCompu1P1 = colaTransmicion1[0]; colaTransmicion1.erase(colaTransmicion1.begin()); } //Calculos estadisticos long tiempoRealProc = relojEvento - mensajes[idMensajeP2].tiempoInicioTrabajo; mensajes[idMensajeP2].tiempoRealProc += tiempoRealProc; mensajes[idMensajeP2].tiempoProc2 += tiempoRealProc; //Desprogramos valores de la simulacion eventos->at(6) = this->tiempoSimulacion*4; // Desprogrmamos el evento proc2 = false; // ya no esta ocupado mensajes[idMensajeP2].tiempoInicioTrabajo = 0; // por si acaso this->idMensajeP2 = -1; // quitamos el mensaje actual //Revisamos la cola de la compu2 a ver si hay algun mensaje en espera if(colaProc2.size() != 0){ //existen mensajes esperando a ser atendidos /*if (relojEvento < mensajes[colaProc2[0]].tiempoEntradaCola ){ cout << "tiempo evento : "<<tiempoEvento << ", tiempoEntradaCola : "<< mensajes[colaProc2[0]].tiempoEntradaCola<<endl; }*/ long tiempoEnCola = relojEvento - mensajes[colaProc2[0]].tiempoEntradaCola; mensajes[colaProc2[0]].tiempoEnColas += tiempoEnCola; proc2 = true; // Se ocupa el proc2 this->idMensajeP2 = colaProc2[0]; map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(6) = relojEvento + Manejador((*map).second); mensajes[idMensajeP2].tiempoInicioTrabajo = relojEvento; colaProc2.erase(colaProc2.begin()); } return relojEvento; } /* @Funcion: simula el evento "FFinalizacion de procesamiento del mensaje en el proc 2 de la computadora 2" en donde se marca la hora a la cual llegara el mensaje a la computadora 1, asi como se marca el momento en el que se termina de utilizar el procesador 2 de la computadora 2 y se acumula en la variable tiempoRealproc3. Ademas se calcula el tiempo de transicion que tarda en llegar a la computadora 1 y se revisa la cola de este procesador para saber si hay algun mensaje para ser procesado y si es así lo procesa y luego lo borra de la cola. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ // long Evento::FC2P2(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; //Se envia un mensaje a la computadora 1 mensajes[idMensajeP3].tiempoTransmicion += 20; // estadisico colaTransmicion1.push_back(idMensajeP3); mensajes[idMensajeP3].tiempoLlegada = relojEvento +20; //Comprobamos si ya se programo el arribo a la computadora 1 if (eventos->at(3) == this->tiempoSimulacion*4) { //Hemos de progrmar el siguiete arribo eventos->at(3) = mensajes[colaTransmicion1[0]].tiempoLlegada; // Programamos this->arriboCompu1P2 = colaTransmicion1[0]; colaTransmicion1.erase(colaTransmicion1.begin()); } //Calculos estadisticos long tiempoRealProc = relojEvento - mensajes[idMensajeP3].tiempoInicioTrabajo; mensajes[idMensajeP3].tiempoRealProc += tiempoRealProc; mensajes[idMensajeP3].tiempoProc3 += tiempoRealProc; //Desprogramos valores de la simulacion eventos->at(7) = this->tiempoSimulacion*4; // Desprogrmamos el evento proc3 = false; // ya no esta ocupado mensajes[idMensajeP3].tiempoInicioTrabajo = 0; // por si acaso this->idMensajeP3 = -1; // quitamos el mensaje actual //Revisamos la cola de la compu2 a ver si hay algun mensaje en espera if(colaProc2.size() != 0){ //existen mensajes esperando a ser atendidos /*if (relojEvento < mensajes[colaProc2[0]].tiempoEntradaCola ){ cout << "tiempo evento : "<<tiempoEvento << ", tiempoEntradaCola : "<< mensajes[colaProc2[0]].tiempoEntradaCola<<endl; }*/ long tiempoEnCola = relojEvento - mensajes[colaProc2[0]].tiempoEntradaCola; mensajes[colaProc2[0]].tiempoEnColas += tiempoEnCola; proc3 = true; // Se ocupa el proc2 this->idMensajeP3 = colaProc2[0]; map<int , vector<double> >::iterator map = mapaD.find(2); eventos->at(7) = relojEvento + Manejador((*map).second); mensajes[idMensajeP3].tiempoInicioTrabajo = relojEvento; colaProc2.erase(colaProc2.begin()); } return relojEvento; } /* @Funcion: simula el evento de arribo de un mensaje ala computadora 3 de la computadora 1, en este metodo se revisa el procesador de la computadora 3 para revisar si se encuentra ocupado, de estarlo el mensaje que acaba de arribar se pone en la cola del procesador y se empieza el contador de este mensaje para calcular el tiempo que ha estado en cola. De no se asi, si el procesador esta desocupado se pone al mensaje que arribo a trabajar en este procesador, se determina el tiempo de finalizacion de trabajo del procesador y se hace una toma de tiempo del momento en el que el mensaje empezo el tiempo real de procesamiento para su posterior uso en estadisticas. Tambien revisa la cola de mensajes en transicion para programar el proximo arribo. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC3C1( long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; // Adelantamos el relo //Revisar el proc4 if (proc4){ //Esta ocupado el proc4 debemos meter el mensaje en la cola de espera colaProc4.push_back(this->arriboCompu3); mensajes[this->arriboCompu3].tiempoEntradaCola = relojEvento; }else{ //Si encuentra el proc desocupado lo ponemos a trabajar proc4 = true; this->idMensajeP4 = arriboCompu3; // guardamos el valor del id del mensaje que esta en el procesador map<int , vector<double> >::iterator map = mapaD.find(5); eventos->at(8)= relojEvento + Manejador((*map).second); // Programamos la salida mensajes[idMensajeP4].tiempoInicioTrabajo = relojEvento; // Iniciamos una toma del tiempo para el tiempo real y otros } eventos->at(9) = this->tiempoSimulacion*4; //Se revisa la cola de transicion para ver si hay mensajes que vienen de camino y si los hay ponemos ese valor como evento[1] if (!colaTransmicion3.empty()){ eventos->at(9) = mensajes[colaTransmicion3[0]].tiempoLlegada; // RePrograma el arribo this->arriboCompu3 = colaTransmicion3[0];// Se asigna id del mensaje para poder trabajar colaTransmicion3.erase(colaTransmicion3.begin()); } return relojEvento; } /* @Funcion: simula el evento de la llegada de un mensaje a la computadora 3 desde afuera del sistema. En este mentodo se revisa el procesador de la computadora 3 para revisar si se encuentra ocupado, de estarlo el mensaje que acaba de arribar se pone en la cola del procesador y se empieza el contador de este mensaje para calcular el tiempo que ha estado en cola. De no se asi, si el procesador esta desocupado se pone al mensaje que arribo a trabajar en este procesador, se determina el tiempo de finalizacion de trabajo del procesador y se hace una toma de tiempo del momento en el que el mensaje empezo el tiempo real de procesamiento para su posterior uso en estadisticas. Ademas se reprograma este mismo evento usando la distribucion. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::AMC3F(long tiempoEvento,vector<long> *eventos){ long relojEvento = tiempoEvento; Mensaje mensaje(this->idMensajeGlobal); long idMensaje = idMensajeGlobal; this->idMensajeGlobal++; // Se creo un mensaje nuevo this->mensajes.push_back(mensaje); //Revisamos el proc4 if (proc4){ //El procesador esta ocupado hemos de poner el mensaje en cola colaProc4.push_back(idMensaje); mensajes[idMensaje].tiempoEntradaCola = relojEvento; }else{ //Si el proc4 esta libre lo ponemos a trabajar //printf("Entre en donde es pa\n"); proc4 = true; this->idMensajeP4 = idMensaje; map<int , vector<double> >::iterator map = mapaD.find(5); eventos->at(8) = relojEvento + Manejador((*map).second); mensajes[idMensajeP4].tiempoInicioTrabajo = relojEvento; } map<int , vector<double> >::iterator map = mapaD.find(4); eventos->at(10) = relojEvento +Manejador((*map).second); //Reprograma este mismo evento //cout <<"Cantidad de mensajes en el vector"<<this->mensajes.size()<<endl; //cout <<"El tiempo en el que volvere a pasar es : "<< eventos->at(10) <<endl; return relojEvento; } /* @Funcion: simula el evento "Finalizacion de procesamiento del mensaje de la computadora 3" en donde se determina primeramente si el mensaje sera eliminado o si sera enviado a la computadora 1, en caso de ser eliminado se guardan todos los datos de ese mensaje, relacionados con las estadisticas, en variable que lo acumulan para obtener las estadisticas finales. Mientras que si es el caso en que se envian a la computadora 1 primero se programa el tiempo de transmision y luego la hora de llegada a la computadora 1. Por ultimo se revisa si hay algun mensaje en su cola y si es asi lo procesa y lo borra de la cola. @Param tiempoEvento: reloj principal del sistema @Param eventos: es un vector donde se van modificando los tiempos en los que pasa un determinado evento. @Return: retorna la hora que tomara el reloj principal de la simulacion */ long Evento::FC3 (long tiempoEvento,vector<long> *eventos){ //cout<<"------------- soy el mensaje: "<<this->idMensajeP4<<"-------------------" <<endl; long relojEvento = tiempoEvento; //srand(time(NULL)); //Calculos estadisticos long tiempoRealProc = relojEvento - mensajes[idMensajeP4].tiempoInicioTrabajo; //cout<<"Valores tiempoRealProc: "<<relojEvento<<", "<<mensajes[idMensajeP4].tiempoInicioTrabajo <<endl; mensajes[idMensajeP4].tiempoRealProc += tiempoRealProc; mensajes[idMensajeP4].tiempoProc4 += tiempoRealProc; double num = drand48(); if(num <= this->X2){ //printf("Eliminado\n"); //Se elimina el mensaje mensajes[idMensajeP4].estado = 0; this->tiemposProcesadores[0] += mensajes[this->idMensajeP4].tiempoProc1; // Almacena tiempo en proc1 //cout<<"Tiempo que pase en proc1: "<<this->mensajes[this->idMensajeP4].tiempoProc1 <<"----------------------------------------------------------------------------" <<endl; this->tiemposProcesadores[3] += mensajes[this->idMensajeP4].tiempoProc4; // Almacena tiempo en proc3 this->tiempoProc1Perdidos += mensajes[this->idMensajeP4].tiempoProc1; //Almacena tiempo desperdiciado por proc1 //cout<<"Tiempo perdido proc1: "<<mensajes[this->idMensajeP4].tiempoProc1 <<"------------- soy el mensaje: "<<this->idMensajeP4<<"-------------------" <<endl; this->tiempoProc4Perdidos += mensajes[this->idMensajeP4].tiempoProc4; //Almacena tiempo desperdiciado por proc4 this->mensajesEliminados++; // Aumentamos la cantidad de mensajes eliminados this->sumatoriaTiemposMensajes += (mensajes[this->idMensajeP4].tiempoTransmicion + mensajes[this->idMensajeP4].tiempoRealProc + mensajes[this->idMensajeP4].tiempoEnColas); this->sumatoriaVecesDevuelto += mensajes[this->idMensajeP4].vecesDevuelto; this->tiempoColas += mensajes[this->idMensajeP4].tiempoEnColas; this->tiempoTransmicion += mensajes[this->idMensajeP4].tiempoTransmicion; this->sumatoriaTiempoReal += mensajes[this->idMensajeP4].tiempoRealProc; }else{ //Se envia a el mensaje a la computadora 1 //printf("A la comp1\n"); mensajes[idMensajeP4].tiempoTransmicion += 20; mensajes[idMensajeP4].tiempoLlegada = relojEvento +20; // a esta hora va a llegar colaTransmicion1.push_back(idMensajeP4); //Ponemos el mensaje en la cola de envios "canal" if (eventos->at(1) == this->tiempoSimulacion*4 ){ //Se debe asignar el tiempo del primer elemento de la cola de transicion1 a este evento eventos->at(1) = mensajes[colaTransmicion1[0]].tiempoLlegada; this->arriboCompu1C3 = colaTransmicion1[0]; // el mensaje que va a llegar sera el que este de primero colaTransmicion1.erase(colaTransmicion1.begin()); } } //Desprogramamos valores de la simulacion eventos->at(8) = this->tiempoSimulacion*4; this->proc4 = false ; //el proc4 ya no esta ocupado mensajes[idMensajeP4].tiempoInicioTrabajo = 0; this->idMensajeP4 = -1; // Se desprogama el id // Revision de la cola de mensajes en espera por ser atendidos a ver si podemos sacar a uno if (colaProc4.size() != 0){ //Existen mensajes esperando a ser atendidos por el prov4 /*if (relojEvento < mensajes[colaProc4[0]].tiempoEntradaCola ){ cout << "tiempo evento : "<<tiempoEvento << ", tiempoEntradaCola : "<< mensajes[colaProc4[0]].tiempoEntradaCola<<endl; }*/ long tiempoEnCola = relojEvento - mensajes[colaProc4[0]].tiempoEntradaCola; mensajes[colaProc4[0]].tiempoEnColas += tiempoEnCola; //Programamos valores utiles para el funcionamiento de la simulacion proc4 = true; // el proc4 esta ocupado this->idMensajeP4 = colaProc4[0]; map<int , vector<double> >::iterator map = mapaD.find(5); eventos->at(8) = relojEvento + Manejador((*map).second); mensajes[this->idMensajeP4].tiempoInicioTrabajo = relojEvento; colaProc4.erase(colaProc4.begin()); } return relojEvento; } /* @Funcion: calcula la funcion de distribucion normal con metodo directo utilizando los miu y varianza indicados por el usuario al inicio del programa @Param miu: parametro para estadisticas (indicado por el usuario) @Param varianza: parametro para estadisticas (indicado por el usuario) @Return: retorna el resultado final de aplicar el metodo directo con los parametros indicados */ double Evento::DistribucionNormalMetodoDirecto(int miu, int varianza ){ double num1 = drand48() ; //cout <<"num1"<< num1 <<endl; double num2 = drand48() ; //cout <<"num1"<< num2 <<endl; long z = (-2* log(num1)) * cos( (num2 * 2*PI)* PI /180.0) ; //cout <<"z: "<< z <<endl; double retorno = sqrt(varianza) * z + miu ; return retorno; } /* @Funcion: Metodo que se encarga de calcular un valor aleatorio usando el metodo de la distribucion normal mediante el metodo del teorema del limite central @Param miu: parametro necesario para calculos estadisticos @Param varianza: parametro necesario para calculos estadisticos @Return: retorna el valor aleatorio creado */ double Evento::DistribucionNormalMetodoTLC(int miu, int varianza){ double retorno ; double z = 0; //srand(time(NULL)); //Sumatoria for (int i = 1; i <= 12; ++i) { double num1 = drand48() ; z += num1 ; } //cout<<"El valor de la sumatoria es de : "<< z <<endl; z = z -6; retorno = sqrt(varianza) * z + miu; //cout<<"Este es el valor del metodo TLC: "<< retorno <<endl; return retorno; } /* @Funcion: Metodo que se encarga de calcular un valor aleatorio usando el metodo de la distribucion uniforme @Param miu: parametro necesario para calculos estadisticos, define el valor inferior del intervalo. @Param varianza: parametro necesario para calculos estadisticos, define el valor superior del intervalo. @Return: retorna el valor aleatorio creado */ double Evento::DistribucionUniforme(int a, int b) { //srand(time(NULL)); double num1 =drand48() ; double retorno = num1*(b - a)+a; //cout<<"Este es el valor de la uniforme "<< retorno <<endl; return retorno; } /* @Funcion: calcula un valor aleatorio utilizando la funcion de distribucion exponencial utilizando el lamda indicado por el usuario @Param lamda: parametro para estadisticas (indicado por el usuario) @Return: retorna el resultado final (numero aleatorio) de aplicar la distribucion exponencial con los parametros indicados */ double Evento::DistribucionExponencialParametro(double lambda){ double retorno ; //srand(time(NULL)); double num1 = drand48() ; if(num1 != 1){ retorno = (-log(1-num1)) / lambda; }else if (num1 != 0){ retorno = (-log(num1)) / lambda; } return retorno; } /* @Funcion: calcula un valor aleatorio utilizando la funcion de distribucion de densidad haciendo uso del metodo inverso. @Param k: parametro para estadisticas (indicado por el usuario) @Param a: parametro para estadisticas (indicado por el usuario) para el rango inferior @Param b: parametro para estadisticas (indicado por el usuario) para el rango superior @Return: retorna el resultado final (numero aleatorio) obtenido de aplicar la distribucion de densidad con los parametros indicados */ double Evento::DistribucionDensidad(double k, int a , int b){ //srand(time(NULL)); double num1 = drand48() ; //cout<<"Este es el valor de num1 del de densidad : "<< num1 <<endl; double division = 2* num1 / k; //cout<<"Este es el valor de de la division del de densidad : "<< division <<endl; double suma = division + (a*a); //cout<<"Este es el valor de suma del de densidad : "<< suma <<endl; double retorno = sqrt(suma); //cout<<"Este es el valor de retorno del de densidad : "<< retorno <<endl; return retorno; } /* @Funcion: Metodo que se encarga de decidir a cual de los metodos de generacion de valores aleatorios basado en distrubuciones llamar, esto lo hace mediante la informacion del vector que recibe por parametro. Se llama a este metodo siempre que se quiere crear un valor nuevo. @Param v: vector que utiliza par consultar los datos de las estadisticas. @Return: retorna el valor aleatorio creado */ double Evento::Manejador(vector<double> v){ int caso = v[0]; double valor; switch(caso){ case 1: valor = DistribucionNormalMetodoDirecto(v[1],v[2]); //cout<<"Este es el valor del metodo directo: "<< valor <<endl; while (valor < -1){ //cout<<"Este es el valor del metodo directo: "<< valor <<endl; valor = DistribucionNormalMetodoDirecto(v[1],v[2]); } break; case 2: valor = DistribucionNormalMetodoTLC(v[1], v[2]); //cout<<"Este es el valor del metodo TLC: "<< valor <<endl; while(valor < -1){ //cout<<"Este es el valor del metodo TLC: "<< valor <<endl; valor = DistribucionNormalMetodoTLC(v[1], v[2]); } break; case 3: valor = DistribucionUniforme(v[1], v[2]); break; case 4 : valor = DistribucionExponencialParametro(v[1]); break; case 5 : valor = DistribucionDensidad(v[1],v[2],v[3]); //cout<<"Este es el valor del metodo de densidad: "<< valor <<endl; //exit(0); break; default: printf("default\n"); } return valor; }
C#
UTF-8
483
2.984375
3
[]
no_license
using System; namespace ProgramCod { class Program1 { static void Main(string[] args) { Console.WriteLine("\nПриклад 9. Операції з числами 2"); int a = 1_003; Console.WriteLine($"a={a}"); Console.WriteLine($"a / 10={a / 10}");// Not 100,3 Console.WriteLine($"a % 10 ={a % 10}"); Console.ReadKey(); } } }
Java
UTF-8
391
1.804688
2
[ "Apache-2.0" ]
permissive
package org.caps.spring.cloud.alibaba.service.fallback; import org.caps.spring.cloud.alibaba.service.ResetService; import org.springframework.stereotype.Component; import java.util.*; /** * @author Caps * @date 2019/8/15 */ @Component public class ResetServiceFallback implements ResetService { @Override public List initPuzzle() { return Arrays.asList("500"); } }
Shell
UTF-8
462
3.03125
3
[]
no_license
#!/bin/sh export HOME_JOBS="${HOME}/workspace/dbp_pilot/jobs" source ${HOME_JOBS}/library/bash/loader.sh export HOME_JOB="${HOME_JOBS}/LP_set/daily" function run_daily { export TARGET_DATABASE="loc" export END_DT=$1 run_python "${HOME_JOB}/runner.py" } function run_monthly { curr_dt=20170501 end_dt=20170528 while [ ${curr_dt} -le ${end_dt} ] do run_daily "${curr_dt}" curr_dt=$((curr_dt+1)) done } run_daily "20170508" #run_monthly
Markdown
UTF-8
27,128
2.6875
3
[]
no_license
1、说明:创建数据库 CREATE DATABASE database-name 2、说明:删除数据库 drop database dbname 3、说明:备份sql server --- 创建 备份数据的 device USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' --- 开始 备份 BACKUP DATABASE pubs TO testBack 4、说明:创建新表 create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) 根据已有的表创建新表: A:create table tab_new like tab_old (使用旧表创建新表) B:create table tab_new as select col1,col2… from tab_old definition only 5、说明:删除新表 drop table tabname 6、说明:增加一个列 Alter table tabname add column col type 注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 7、说明:添加主键: Alter table tabname add primary key(col) 说明:删除主键: Alter table tabname drop primary key(col) 8、说明:创建索引:create [unique] index idxname on tabname(col….) 删除索引:drop index idxname 注:索引是不可更改的,想更改必须删除重新建。 9、说明:创建视图:create view viewname as select statement 删除视图:drop view viewname 10、说明:几个简单的基本的sql语句 选择:select * from table1 where 范围 插入:insert into table1(field1,field2) values(value1,value2) 删除:delete from table1 where 范围 更新:update table1 set field1=value1 where 范围 查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料! 排序:select * from table1 order by field1,field2 [desc] 总数:select count as totalcount from table1 求和:select sum(field1) as sumvalue from table1 平均:select avg(field1) as avgvalue from table1 最大:select max(field1) as maxvalue from table1 最小:select min(field1) as minvalue from table1 11、说明:几个高级查询运算词 A: UNION 运算符 UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 B: EXCEPT 运算符 EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 C: INTERSECT 运算符 INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 注:使用运算词的几个查询结果行必须是一致的。 12、说明:使用外连接 A、left (outer) join: 左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c B:right (outer) join: 右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 C:full/cross (outer) join: 全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 12、分组:Group by: 一张表,一旦分组完成后,查询后只能得到组相关的信息。 组相关的信息:(统计信息) count,sum,max,min,avg 分组的标准) 在SQLServer中分组时:不能以text,ntext,image类型的字段作为分组依据 在selecte统计函数中的字段,不能和普通的字段放在一起; 13、对数据库进行操作: 分离数据库: sp_detach_db; 附加数据库:sp_attach_db 后接表明,附加需要完整的路径名 14.如何修改数据库的名称: sp_renamedb 'old_name', 'new_name' 二、提升 1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) 法一:select * into b from a where 1<>1(仅用于SQlServer) 法二:select top 0 * into b from a 2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) insert into b(a, b, c) select d,e,f from b; 3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件 例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. 4、说明:子查询(表名1:a 表名2:b) select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3) 5、说明:显示文章、提交人和最后回复时间 select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b 6、说明:外连接查询(表名1:a 表名2:b) select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 7、说明:在线视图查询(表名1:a ) select * from (SELECT a,b,c FROM a) T where t.a > 1; 8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 select * from table1 where time between time1 and time2 select a,b,c, from table1 where a not between 数值1 and 数值2 9、说明:in 的使用方法 select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’) 10、说明:两张关联表,删除主表中已经在副表中没有的信息 delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) 11、说明:四表联查问题: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where ..... 12、说明:日程安排提前五分钟提醒 SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 13、说明:一条sql 语句搞定数据库分页 select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 具体实现: 关于数据库分页: declare @start int,@end int @sql nvarchar(600) set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’ exec sp_executesql @sql 注意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特殊的处理。Rid为一个标识列,如果top后还有具体的字段,这样做是非常有好处的。因为这样可以避免 top的字段如果是逻辑索引的,查询的结果后实际表中的不一致(逻辑索引中的数据有可能和数据表中的不一致,而查询时如果处在索引则首先查询索引) 14、说明:前10条记录 select top 10 * form table1 where 范围 15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 (select a from tableA ) except (select a from tableB) except (select a from tableC) 17、说明:随机取出10条数据 select top 10 * from tablename order by newid() 18、说明:随机选择记录 select newid() 19、说明:删除重复记录 1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) 2),select distinct * into temp from tablename delete from tablename insert into tablename select * from temp 评价: 这种操作牵连大量的数据的移动,这种做法不适合大容量但数据操作 3),例如:在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,这样只有在下一次全部导入,这样也就产生好多重复的字段,怎样删除重复字段 alter table tablename --添加一个自增列 add column_b int identity(1,1) delete from tablename where column_b not in( select max(column_b) from tablename group by column1,column2,...) alter table tablename drop column column_b 20、说明:列出数据库里所有的表名 select name from sysobjects where type='U' // U代表用户 21、说明:列出表里的所有的列名 select name from syscolumns where id=object_id('TableName') 22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type 显示结果: type vender pcs 电脑 A 1 电脑 A 1 光盘 B 2 光盘 A 2 手机 B 3 手机 C 3 23、说明:初始化表table1 TRUNCATE TABLE table1 24、说明:选择从10到15的记录 select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc 三、技巧 1、1=1,1=2的使用,在SQL语句组合时用的较多 “where 1=1” 是表示选择全部 “where 1=2”全部不选, 如: if @strWhere !='' begin set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere end else begin set @strSQL = 'select count(*) as Total from [' + @tblName + ']' end 我们可以直接写成 错误!未找到目录项。 set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere 2、收缩数据库 --重建索引 DBCC REINDEX DBCC INDEXDEFRAG --收缩数据和日志 DBCC SHRINKDB DBCC SHRINKFILE 3、压缩数据库 dbcc shrinkdatabase(dbname) 4、转移数据库给新用户以已存在用户权限 exec sp_change_users_login 'update_one','newname','oldname' go 5、检查备份集 RESTORE VERIFYONLY from disk='E:\dvbbs.bak' 6、修复数据库 ALTER DATABASE [dvbbs] SET SINGLE_USER GO DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK GO ALTER DATABASE [dvbbs] SET MULTI_USER GO 7、日志清除 SET NOCOUNT ON DECLARE @LogicalFileName sysname, @MaxMinutes INT, @NewSize INT USE tablename -- 要操作的数据库名 SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 @MaxMinutes = 10, -- Limit on time allowed to wrap log. @NewSize = 1 -- 你想设定的日志文件的大小(M) Setup / initialize DECLARE @OriginalSize int SELECT @OriginalSize = size FROM sysfiles WHERE name = @LogicalFileName SELECT 'Original Size of ' + db_name() + ' LOG is ' + CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' FROM sysfiles WHERE name = @LogicalFileName CREATE TABLE DummyTrans (DummyColumn char (8000) not null) DECLARE @Counter INT, @StartTime DATETIME, @TruncLog VARCHAR(255) SELECT @StartTime = GETDATE(), @TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' DBCC SHRINKFILE (@LogicalFileName, @NewSize) EXEC (@TruncLog) -- Wrap the log if necessary. WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) AND (@OriginalSize * 8 /1024) > @NewSize BEGIN -- Outer loop. SELECT @Counter = 0 WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) BEGIN -- update INSERT DummyTrans VALUES ('Fill Log') DELETE DummyTrans SELECT @Counter = @Counter + 1 END EXEC (@TruncLog) END SELECT 'Final Size of ' + db_name() + ' LOG is ' + CONVERT(VARCHAR(30),size) + ' 8K pages or ' + CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' FROM sysfiles WHERE name = @LogicalFileName DROP TABLE DummyTrans SET NOCOUNT OFF 8、说明:更改某个表 exec sp_changeobjectowner 'tablename','dbo' 9、存储更改全部表 CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch @OldOwner as NVARCHAR(128), @NewOwner as NVARCHAR(128) AS DECLARE @Name as NVARCHAR(128) DECLARE @Owner as NVARCHAR(128) DECLARE @OwnerName as NVARCHAR(128) DECLARE curObject CURSOR FOR select 'Name' = name, 'Owner' = user_name(uid) from sysobjects where user_name(uid)=@OldOwner order by name OPEN curObject FETCH NEXT FROM curObject INTO @Name, @Owner WHILE(@@FETCH_STATUS=0) BEGIN if @Owner=@OldOwner begin set @OwnerName = @OldOwner + '.' + rtrim(@Name) exec sp_changeobjectowner @OwnerName, @NewOwner end -- select @name,@NewOwner,@OldOwner FETCH NEXT FROM curObject INTO @Name, @Owner END close curObject deallocate curObject GO 10、SQL SERVER中直接循环写入数据 declare @i int set @i=1 while @i<30 begin insert into test (userid) values(@i) set @i=@i+1 end 案例: 有如下表,要求就裱中所有沒有及格的成績,在每次增長0.1的基礎上,使他們剛好及格: Name score Zhangshan 80 Lishi 59 Wangwu 50 Songquan 69 while((select min(score) from tb_table)<60) begin update tb_table set score =score*1.01 where score<60 if (select min(score) from tb_table)>60 break else continue end 数据开发-经典 1.按姓氏笔画排序: Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多 2.数据库加密: select encrypt('原始密码') select pwdencrypt('原始密码') select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 encrypt('原始密码') select pwdencrypt('原始密码') select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 3.取回表中字段: declare @list varchar(1000), @sql nvarchar(1000) select @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='表A' set @sql='select '+right(@list,len(@list)-1)+' from 表A' exec (@sql) 4.查看硬盘分区: EXEC master..xp_fixeddrives 5.比较A,B表是否相等: if (select checksum_agg(binary_checksum(*)) from A) = (select checksum_agg(binary_checksum(*)) from B) print '相等' else print '不相等' 6.杀掉所有的事件探察器进程: DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses WHERE program_name IN('SQL profiler',N'SQL 事件探查器') EXEC sp_msforeach_worker '?' 7.记录搜索: 开头到N条记录 Select Top N * From 表 ------------------------------- N到M条记录(要有主索引ID) Select Top M-N * From 表 Where ID in (Select Top M ID From 表) Order by ID Desc ---------------------------------- N到结尾记录 Select Top N * From 表 Order by ID Desc 案例 例如1:一张表有一万多条记录,表的第一个字段 RecID 是自增长字段, 写一个SQL语句,找出表的第31到第40个记录。 select top 10 recid from A where recid not in(select top 30 recid from A) 分析:如果这样写会产生某些问题,如果recid在表中存在逻辑索引。 select top 10 recid from A where……是从索引中查找,而后面的select top 30 recid from A则在数据表中查找,这样由于索引中的顺序有可能和数据表中的不一致,这样就导致查询到的不是本来的欲得到的数据。 解决方案 1, 用order by select top 30 recid from A order by ricid 如果该字段不是自增长,就会出现问题 2, 在那个子查询中也加条件:select top 30 recid from A where recid>-1 例2:查询表中的最后以条记录,并不知道这个表共有多少数据,以及表结构。 set @s = 'select top 1 * from T where pid not in (select top ' + str(@count-1) + ' pid from T)' print @s exec sp_executesql @s 9:获取当前数据库中的所有用户表 select Name from sysobjects where xtype='u' and status>=0 10:获取某一个表的所有字段 select name from syscolumns where id=object_id('表名') select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '表名') 两种方式的效果相同 11:查看与某一个表相关的视图、存储过程、函数 select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%' 12:查看当前数据库中所有存储过程 select name as 存储过程名称 from sysobjects where xtype='P' 13:查询用户创建的所有数据库 select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa') 或者 select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01 14:查询某一个表的字段和数据类型 select column_name,data_type from information_schema.columns where table_name = '表名' 15:不同服务器数据库之间的数据操作 --创建链接服务器 exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 ' exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, '用户名 ', '密码 ' --查询示例 select * from ITSV.数据库名.dbo.表名 --导入示例 select * into 表 from ITSV.数据库名.dbo.表名 --以后不再使用时删除链接服务器 exec sp_dropserver 'ITSV ', 'droplogins ' --连接远程/局域网数据(openrowset/openquery/opendatasource) --1、openrowset --查询示例 select * from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) --生成本地表 select * into 表 from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) --把本地表导入远程表 insert openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) select *from 本地表 --更新本地表 update b set b.列A=a.列A from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)as a inner join 本地表 b on a.column1=b.column1 --openquery用法需要创建一个连接 --首先创建一个连接创建链接服务器 exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 ' --查询 select * FROM openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ') --把本地表导入远程表 insert openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ') select * from 本地表 --更新本地表 update b set b.列B=a.列B FROM openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ') as a inner join 本地表 b on a.列A=b.列A --3、opendatasource/openrowset SELECT * FROM opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陆名;Password=密码 ' ).test.dbo.roy_ta --把本地表导入远程表 insert opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陆名;Password=密码 ').数据库.dbo.表名 select * from 本地表 SQL Server基本函数 SQL Server基本函数 1.字符串函数 长度与分析用 1,datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格 2,substring(expression,start,length) 取子串,字符串的下标是从“1”,start为起始位置,length为字符串长度,实际应用中以len(expression)取得其长度 3,right(char_expr,int_expr) 返回字符串右边第int_expr个字符,还用left于之相反 4,isnull( check_expression , replacement_value )如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作类 5,Sp_addtype 自定義數據類型 例如:EXEC sp_addtype birthday, datetime, 'NULL' 6,set nocount {on|off} 使返回的结果中不包含有关受 Transact-SQL 语句影响的行数的信息。如果存储过程中包含的一些语句并不返回许多实际的数据,则该设置由于大量减少了网络流量,因此可显著提高性能。SET NOCOUNT 设置是在执行或运行时设置,而不是在分析时设置。 SET NOCOUNT 为 ON 时,不返回计数(表示受 Transact-SQL 语句影响的行数)。 SET NOCOUNT 为 OFF 时,返回计数 常识 在SQL查询中:from后最多可以跟多少张表或视图:256 在SQL语句中出现 Order by,查询时,先排序,后取 在SQL中,一个字段的最大容量是8000,而对于nvarchar(4000),由于nvarchar是Unicode码。 SQLServer2000同步复制技术实现步骤 一、 预备工作 1.发布服务器,订阅服务器都创建一个同名的windows用户,并设置相同的密码,做为发布快照文件夹的有效访问用户 --管理工具 --计算机管理 --用户和组 --右键用户 --新建用户 --建立一个隶属于administrator组的登陆windows的用户(SynUser) 2.在发布服务器上,新建一个共享目录,做为发布的快照文件的存放目录,操作: 我的电脑--D:\ 新建一个目录,名为: PUB --右键这个新建的目录 --属性--共享 --选择"共享该文件夹" --通过"权限"按纽来设置具体的用户权限,保证第一步中创建的用户(SynUser) 具有对该文件夹的所有权限 --确定 3.设置SQL代理(SQLSERVERAGENT)服务的启动用户(发布/订阅服务器均做此设置) 开始--程序--管理工具--服务 --右键SQLSERVERAGENT --属性--登陆--选择"此账户" --输入或者选择第一步中创建的windows登录用户名(SynUser) --"密码"中输入该用户的密码 4.设置SQL Server身份验证模式,解决连接时的权限问题(发布/订阅服务器均做此设置) 企业管理器 --右键SQL实例--属性 --安全性--身份验证 --选择"SQL Server 和 Windows" --确定 5.在发布服务器和订阅服务器上互相注册 企业管理器 --右键SQL Server组 --新建SQL Server注册... --下一步--可用的服务器中,输入你要注册的远程服务器名 --添加 --下一步--连接使用,选择第二个"SQL Server身份验证" --下一步--输入用户名和密码(SynUser) --下一步--选择SQL Server组,也可以创建一个新组 --下一步--完成 6.对于只能用IP,不能用计算机名的,为其注册服务器别名(此步在实施中没用到) (在连接端配置,比如,在订阅服务器上配置的话,服务器名称中输入的是发布服务器的IP) 开始--程序--Microsoft SQL Server--客户端网络实用工具 --别名--添加 --网络库选择"tcp/ip"--服务器别名输入SQL服务器名 --连接参数--服务器名称中输入SQL服务器ip地址 --如果你修改了SQL的端口,取消选择"动态决定端口",并输入对应的端口号 二、 正式配置 1、配置发布服务器 打开企业管理器,在发布服务器(B、C、D)上执行以下步骤: (1) 从[工具]下拉菜单的[复制]子菜单中选择[配置发布、订阅服务器和分发]出现配置发布和分发向导 (2) [下一步] 选择分发服务器 可以选择把发布服务器自己作为分发服务器或者其他sql的服务器(选择自己) (3) [下一步] 设置快照文件夹 采用默认\\servername\Pub (4) [下一步] 自定义配置 可以选择:是,让我设置分发数据库属性启用发布服务器或设置发布设置 否,使用下列默认设置(推荐) (5) [下一步] 设置分发数据库名称和位置 采用默认值 (6) [下一步] 启用发布服务器 选择作为发布的服务器 (7) [下一步] 选择需要发布的数据库和发布类型 (8) [下一步] 选择注册订阅服务器 (9) [下一步] 完成配置 2、创建出版物 发布服务器B、C、D上 (1)从[工具]菜单的[复制]子菜单中选择[创建和管理发布]命令 (2)选择要创建出版物的数据库,然后单击[创建发布] (3)在[创建发布向导]的提示对话框中单击[下一步]系统就会弹出一个对话框。对话框上的内容是复制的三个类型。我们现在选第一个也就是默认的快照发布(其他两个大家可以去看看帮助) (4)单击[下一步]系统要求指定可以订阅该发布的数据库服务器类型, SQLSERVER允许在不同的数据库如 orACLE或ACCESS之间进行数据复制。 但是在这里我们选择运行"SQL SERVER 2000"的数据库服务器 (5)单击[下一步]系统就弹出一个定义文章的对话框也就是选择要出版的表 注意: 如果前面选择了事务发布 则再这一步中只能选择带有主键的表 (6)选择发布名称和描述 (7)自定义发布属性 向导提供的选择: 是 我将自定义数据筛选,启用匿名订阅和或其他自定义属性 否 根据指定方式创建发布 (建议采用自定义的方式) (8)[下一步] 选择筛选发布的方式 (9)[下一步] 可以选择是否允许匿名订阅 1)如果选择署名订阅,则需要在发布服务器上添加订阅服务器 方法: [工具]->[复制]->[配置发布、订阅服务器和分发的属性]->[订阅服务器] 中添加 否则在订阅服务器上请求订阅时会出现的提示:改发布不允许匿名订阅 如果仍然需要匿名订阅则用以下解决办法 [企业管理器]->[复制]->[发布内容]->[属性]->[订阅选项] 选择允许匿名请求订阅 2)如果选择匿名订阅,则配置订阅服务器时不会出现以上提示 (10)[下一步] 设置快照 代理程序调度 (11)[下一步] 完成配置 当完成出版物的创建后创建出版物的数据库也就变成了一个共享数据库 有数据 srv1.库名..author有字段:id,name,phone, srv2.库名..author有字段:id,name,telphone,adress 要求: srv1.库名..author增加记录则srv1.库名..author记录增加 srv1.库名..author的phone字段更新,则srv1.库名..author对应字段telphone更新 --*/ --大致的处理步骤 --1.在 srv1 上创建连接服务器,以便在 srv1 中操作 srv2,实现同步 exec sp_addlinkedserver 'srv2','','SQLOLEDB','srv2的sql实例名或ip' exec sp_addlinkedsrvlogin 'srv2','false',null,'用户名','密码' go --2.在 srv1 和 srv2 这两台电脑中,启动 msdtc(分布式事务处理服务),并且设置为自动启动 。我的电脑--控制面板--管理工具--服务--右键 Distributed Transaction Coordinator--属性--启动--并将启动类型设置为自动启动 go --然后创建一个作业定时调用上面的同步处理存储过程就行了 企业管理器 --管理 --SQL Server代理 --右键作业 --新建作业 --"常规"项中输入作业名称 --"步骤"项 --新建 --"步骤名"中输入步骤名 --"类型"中选择"Transact-SQL 脚本(TSQL)" --"数据库"选择执行命令的数据库 --"命令"中输入要执行的语句: exec p_process --确定 --"调度"项 --新建调度 --"名称"中输入调度名称 --"调度类型"中选择你的作业执行安排 --如果选择"反复出现" --点"更改"来设置你的时间安排 然后将SQL Agent服务启动,并设置为自动启动,否则你的作业不会被执行 设置方法: 我的电脑--控制面板--管理工具--服务--右键 SQLSERVERAGENT--属性--启动类型--选择"自动启动"--确定. --3.实现同步处理的方法2,定时同步 --在srv1中创建如下的同步处理存储过程 create proc p_process as --更新修改过的数据 update b set name=i.name,telphone=i.telphone from srv2.库名.dbo.author b,author i where b.id=i.id and (b.name <> i.name or b.telphone <> i.telphone) --插入新增的数据 insert srv2.库名.dbo.author(id,name,telphone) select id,name,telphone from author i where not exists( select * from srv2.库名.dbo.author where id=i.id) --删除已经删除的数据(如果需要的话) delete b from srv2.库名.dbo.author b where not exists( select * from author where id=b.id) go
C#
UTF-8
1,414
2.90625
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace SampleCodeTasks.Test { [TestClass] public class ComputeFibonacciSeriesTaskTests { [TestMethod] public async Task TestNegativeNumbers() { var task = new ComputeFibonacciSeriesTask(); string result = await task.ExecuteAsync("-5"); Assert.AreEqual("", result); result = await task.ExecuteAsync("-1"); Assert.AreEqual("", result); } [TestMethod] public async Task TestZero() { var task = new ComputeFibonacciSeriesTask(); string result = await task.ExecuteAsync("0"); Assert.AreEqual("", result); } [TestMethod] public async Task TestOne() { var task = new ComputeFibonacciSeriesTask(); string result = await task.ExecuteAsync("1"); Assert.AreEqual("0", result); } [TestMethod] public async Task TestTwo() { var task = new ComputeFibonacciSeriesTask(); string result = await task.ExecuteAsync("2"); Assert.AreEqual("0 1", result); result = await task.ExecuteAsync("5"); Assert.AreEqual("0 1 1 2 3", result); } [TestMethod] public async Task TestFive() { var task = new ComputeFibonacciSeriesTask(); string result = await task.ExecuteAsync("5"); Assert.AreEqual("0 1 1 2 3", result); } } }
PHP
UTF-8
433
2.5625
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Variant extends Model { protected $table = 'variants'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['variant']; /** * Get the product to which the product belongs. */ public function products() { return $this->belongsTo('App\Product'); } }
Python
UTF-8
2,579
2.9375
3
[]
no_license
import tkinter as tk import pandas as pd from bs4 import BeautifulSoup import requests import twstock # 股票main # 基本設定 window = tk.Tk() window.geometry('640x480') window.title('股票盤後查看') input_fm = tk.Frame(window, width=640, height=120) input_fm.pack() lb = tk.Label(input_fm, bg='#36688D', fg='white', text="請輸入股票代號", font=('微軟正黑體', 12),width=640, height=120) lb.place(rely=0.25, relx=0.5, anchor='center') # 取得Url的框框 stock_url = tk.StringVar() entry = tk.Entry(input_fm, textvariable=stock_url, width=50) entry.place(rely=0.5, relx=0.5, anchor='center') # 按鈕事件 def click_func(): def get_setting(): res = [] try: pds = pd.read_csv('stock_number.csv') s = pds["股票代號"].tolist() for i in s: res.append(i) except: print('load error') return res def get_price(stockid): price = "" try: res = requests.get("https://invest.cnyes.com/twstock/TWS/" + str(stockid)) soup = BeautifulSoup(res.text, "html.parser") finds = soup.find("div", class_="jsx-2941083017 info-lp") price = finds.text except: print("connect get_price error!") return price def get_best(stockid): stock = twstock.Stock(str(stockid)) bp = twstock.BestFourPoint(stock).best_four_point() if (bp): return (str(stockid), '買進' if bp[0] else '賣出', bp[1]) else: return (False, False) stock = get_setting() stock2 = get_setting() for i in stock: get_price(i) for i in stock2: listbox.insert(0, get_best(i)) btn = tk.Button(input_fm, text='查詢', command=click_func, bg='#F18904', fg='Black', font=('微軟正黑體', 10)) btn.place(rely=0.5, relx=0.85, anchor='center') # 清單區域 dload_fm = tk.Frame(window, width=640, height=480-120) dload_fm.pack() # lable lb = tk.Label(dload_fm, text="查詢結果", fg='black', font=('微軟正黑體', 10), width=640, height=120) lb.place(rely=0.25, relx=0.5, anchor='center') # listlabel listbox = tk.Listbox(dload_fm, width=65, height=15) listbox.place(rely=0.5, relx=0.5, anchor='center') # Scrollbar sbar = tk.Scrollbar(dload_fm) sbar.place(rely=0.5, relx=0.87, anchor='center', relheight=0.7) # Scrollbar cross List listbox.config(yscrollcommand=sbar.set) sbar.config(command=listbox.yview) window.mainloop() # lb.pack() # window.mainloop()
Go
UTF-8
178
3.265625
3
[]
no_license
package main import "fmt" func zero(z *int) { fmt.Println("zero function", z) *z = 0 } func main() { x := 5 fmt.Println("main", &x) zero(&x) fmt.Println("main", x) }
Swift
UTF-8
646
2.515625
3
[ "MIT" ]
permissive
import Fluent struct CreateParticipant: Migration { func prepare(on database: Database) -> EventLoopFuture<Void> { database.schema(Participant.schema) .id() .field("user_id", .uuid, .references(User.schema, "id", onDelete: .cascade)) .field("food_id", .uuid, .references(Food.schema, "id", onDelete: .cascade)) .field("approved", .bool) .field("created_at", .datetime) .field("updated_at", .datetime) .create() } func revert(on database: Database) -> EventLoopFuture<Void> { database.schema(Participant.schema).delete() } }
Python
UTF-8
1,063
3.578125
4
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ __author__ = 'huash' import sys import os import collections import math import itertools class Solution: # @param {integer[]} nums # @return {integer} def longestConsecutive(self, nums): if not nums: return 0 nums = set(nums) maxLen = 0 while nums: num = nums.pop() count = 1 r = num + 1 while r in nums: count += 1 nums.remove(r) r += 1 l = num - 1 while l in nums: count += 1 nums.remove(l) l -= 1 maxLen = max(maxLen, count) return maxLen s = Solution() print(s.longestConsecutive([100, 4, 200, 1, 3, 2]))
Java
UTF-8
6,305
2.125
2
[]
no_license
package net.earthcomputer.enchcrack; import java.util.List; import java.util.Map; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SoundHandler; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSlot; import net.minecraft.util.math.MathHelper; public class GuiSlotEnchantment extends GuiSlot { private List<EnchantmentInstance> enchantments; private Map<EnchantmentInstance, GuiButton> wantedButtons; private Map<EnchantmentInstance, GuiButton> unwantedButtons; private Map<EnchantmentInstance, GuiButton> dontCareButtons; public GuiSlotEnchantment(Minecraft mc, int width, int height, int top, int bottom, int slotHeight, int left, List<EnchantmentInstance> enchantments, Map<EnchantmentInstance, GuiButton> wantedButtons, Map<EnchantmentInstance, GuiButton> unwantedButtons, Map<EnchantmentInstance, GuiButton> dontCareButtons) { super(mc, width, height, top, bottom, slotHeight); setSlotXBoundsFromLeft(left); this.enchantments = enchantments; this.wantedButtons = wantedButtons; this.unwantedButtons = unwantedButtons; this.dontCareButtons = dontCareButtons; } @Override protected int getSize() { return enchantments.size(); } @Override public void handleMouseInput() { if (this.isMouseYWithinSlotBounds(this.mouseY)) { if (Mouse.isButtonDown(0) && this.getEnabled()) { if (this.initialClickY == -1) { boolean flag1 = true; if (this.mouseY >= this.top && this.mouseY <= this.bottom) { int j2 = left + (this.width - this.getListWidth()) / 2; int k2 = left + (this.width + this.getListWidth()) / 2; int l2 = this.mouseY - this.top - this.headerPadding + (int) this.amountScrolled - 4; int i1 = l2 / this.slotHeight; if (i1 < this.getSize() && this.mouseX >= j2 && this.mouseX <= k2 && i1 >= 0 && l2 >= 0) { boolean flag = i1 == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; this.elementClicked(i1, flag, this.mouseX, this.mouseY); this.selectedElement = i1; this.lastClicked = Minecraft.getSystemTime(); } else if (this.mouseX >= j2 && this.mouseX <= k2 && l2 < 0) { this.clickedHeader(this.mouseX - j2, this.mouseY - this.top + (int) this.amountScrolled - 4); flag1 = false; } int i3 = this.getScrollBarX(); int j1 = i3 + 6; if (this.mouseX >= i3 && this.mouseX <= j1) { this.scrollMultiplier = -1.0F; int k1 = this.getMaxScroll(); if (k1 < 1) { k1 = 1; } int l1 = (int) ((float) ((this.bottom - this.top) * (this.bottom - this.top)) / (float) this.getContentHeight()); l1 = MathHelper.clamp(l1, 32, this.bottom - this.top - 8); this.scrollMultiplier /= (float) (this.bottom - this.top - l1) / (float) k1; } else { this.scrollMultiplier = 1.0F; } if (flag1) { this.initialClickY = this.mouseY; } else { this.initialClickY = -2; } } else { this.initialClickY = -2; } } else if (this.initialClickY >= 0) { this.amountScrolled -= (float) (this.mouseY - this.initialClickY) * this.scrollMultiplier; this.initialClickY = this.mouseY; } } else { this.initialClickY = -1; } int i2 = Mouse.getEventDWheel(); if (i2 != 0) { if (i2 > 0) { i2 = -1; } else if (i2 < 0) { i2 = 1; } this.amountScrolled += (float) (i2 * this.slotHeight / 2); } } } @Override protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) { EnchantmentInstance ench = enchantments.get(slotIndex); GuiButton wantedButton = wantedButtons.get(ench); GuiButton unwantedButton = unwantedButtons.get(ench); GuiButton dontCareButton = dontCareButtons.get(ench); SoundHandler sh = Minecraft.getMinecraft().getSoundHandler(); if (wantedButton.isMouseOver()) { wantedButton.enabled = false; unwantedButton.enabled = true; dontCareButton.enabled = true; wantedButton.playPressSound(sh); } if (unwantedButton.isMouseOver()) { wantedButton.enabled = true; unwantedButton.enabled = false; dontCareButton.enabled = true; unwantedButton.playPressSound(sh); } if (dontCareButton.isMouseOver()) { wantedButton.enabled = true; unwantedButton.enabled = true; dontCareButton.enabled = false; dontCareButton.playPressSound(sh); } } @Override protected boolean isSelected(int slotIndex) { return false; } @Override protected void drawBackground() { } @Override public void drawScreen(int mouseXIn, int mouseYIn, float partialTicks) { GL11.glEnable(GL11.GL_SCISSOR_TEST); Minecraft mc = Minecraft.getMinecraft(); GuiScreen gui = mc.currentScreen; GL11.glScissor(left * mc.displayWidth / gui.width, top * mc.displayHeight / gui.height, width * mc.displayWidth / gui.width, height * mc.displayHeight / gui.height); super.drawScreen(mouseXIn, mouseYIn, partialTicks); GL11.glDisable(GL11.GL_SCISSOR_TEST); } @Override protected void drawSlot(int slotIndex, int xPos, int yPos, int heightIn, int mouseXIn, int mouseYIn, float partialTicks) { EnchantmentInstance ench = enchantments.get(slotIndex); Minecraft.getMinecraft().fontRenderer.drawString(ench.enchantment.getTranslatedName(ench.enchantmentLevel), xPos + 5, yPos + 5, 0xffffff); GuiButton wantedButton = wantedButtons.get(ench); wantedButton.x = xPos + width - 66; wantedButton.y = yPos + 16; GuiButton unwantedButton = unwantedButtons.get(ench); unwantedButton.x = xPos + width - 46; unwantedButton.y = yPos + 16; GuiButton dontCareButton = dontCareButtons.get(ench); dontCareButton.x = xPos + width - 26; dontCareButton.y = yPos + 16; wantedButton.drawButton(mc, mouseXIn, mouseYIn, partialTicks); unwantedButton.drawButton(mc, mouseXIn, mouseYIn, partialTicks); dontCareButton.drawButton(mc, mouseXIn, mouseYIn, partialTicks); } @Override public int getScrollBarX() { return left + width - 10; } @Override public int getListWidth() { return width; } @Override public void overlayBackground(int startY, int endY, int startAlpha, int endAlpha) { } }
Markdown
UTF-8
2,540
2.734375
3
[ "Apache-2.0" ]
permissive
--- date: '2021-09-01' menu: corda-5-dev-preview: parent: corda-5-dev-preview-1-cordacli weight: 200 section_menu: corda-5-dev-preview title: Installing Corda CLI --- Instructions on how to install the Corda CLI tool. ## Automated installation Use the bash installation script to automate the manual steps. This script downloads Corda CLI, adds it to the path, and sets the auto-completion for Corda CLI to your bash/zsh profile. On Windows the script can run on a git-bash terminal. Run the bash script: ``` curl "https://download.corda.net/corda-cli/1.0.0-DevPreview/get-corda-cli.sh" | bash ``` ## Manual installation ### Before you start If a previous installation of Corda CLI exists, remove it. See [Deleting Corda CLI](deleting-corda-cli.md). ### Steps 1. Download either the <a href="https://download.corda.net/corda-cli/1.0.0-DevPreview/corda-cli.tar">`.tar`</a> or <a href="https://download.corda.net/corda-cli/1.0.0-DevPreview/corda-cli.zip">`.zip`</a> file. 2. Create a new `bin/corda-cli` directory under the current users home directory. 3. Extract the previously-downloaded archive into this new directory. Once extracted, your folder structure should be: ```text bin/corda-cli ├───bin │ └───complete └───lib ``` 4. **Windows:** Add Corda CLI to PATH: a. Go to the **Edit the system environment variables** Control Panel setting. b. Edit the **Path** user variable and add the Corda CLI bin directory extracted in the previous step as a new entry. For example, `C:\Users\username\bin\corda-cli\bin`. c. If you are using Git Bash, update your home directory `username/.bashrc` file with the code: ```shell # Corda-CLI default path export PATH="$HOME/bin/corda-cli/bin:$PATH" if [[ -f $HOME/bin/corda-cli/bin/complete/corda-cli_completion.sh ]]; then source $HOME/bin/corda-cli/bin/complete/corda-cli_completion.sh fi ``` 5. **Linux or macOS**: Add Corda CLI to PATH by adding this code to the `~/.bashrc` (Linux) or `~/.zshrc` file (macOS): ```shell # Corda-CLI default path export PATH="$HOME/bin/corda-cli/bin:$PATH" if [[ -f $HOME/bin/corda-cli/bin/complete/corda-cli_completion.sh ]]; then source $HOME/bin/corda-cli/bin/complete/corda-cli_completion.sh fi ``` 6. Verify installation by opening a new terminal session and running `corda-cli -v`. **Step result:** If successful, this will output details of the installed Corda CLI version.
C++
UTF-8
1,462
3
3
[]
no_license
#pragma once #include "grid.h" #include "player.h" #include <vector> #include <memory> #include <future> class Enemy{ public: // constructor Enemy(int a, int b): x(a), y(b){} // position int x; int y; // virtual function to move enemy virtual void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) = 0; }; // blue enemy uses random algorithm to move class BlueEnemy : public Enemy{ public: BlueEnemy(int a, int b): Enemy(a, b){} void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) override; private: int prev_x = 0; int prev_y = 0; void RunRandomAlgorithmAndMove(Grid& grid); bool Random_valid_cell(int x, int y, Grid& grid); }; // red enemy uses a-star search (player chase) to move class RedEnemy : public Enemy{ public: RedEnemy(int a, int b): Enemy(a, b){} void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) override; // node for a-star search algorithm struct Node{ int x; int y; int g; int h; std::shared_ptr<Node> parent = nullptr; }; // save the ai path for the renderer to show std::vector<std::vector<int>> ai_path; // frame for render animation int frame = 0; private: // functions for a-star algorithm void RunAStarSearchAndMove(int start_x, int start_y, int goal_x, int goal_y, Grid& grid); int Heuristic(int x1, int y1, int x2, int y2); bool AStar_CheckValidCell(int x, int y, Grid& grid, int(&visited_nodes)[19][23]); };
C++
UTF-8
1,541
2.640625
3
[]
no_license
/************************************************************************* > File Name: testMaxConn.cpp > Author: JieTrancender > Mail: jie-email@jie-trancender.org > Created Time: Fri Sep 8 16:24:06 2017 ************************************************************************/ #include "helper.h" #include <iostream> using namespace std; int main() { int count = 0; while (true) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { sleep(5); cerr << "socket error" << endl; exit(1); } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8000); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int ret = connect_timeout(sockfd, &serverAddr, 5); if (ret == -1 && errno == ETIMEDOUT) { cerr << "timeout..." << endl; cerr << "connect_timeout error" << endl; exit(1); } else if (ret == -1) { cerr << "connect_timeout error" <<endl; exit(1); } struct sockaddr_in peerAddr; socklen_t peerlen = sizeof(peerAddr); if (getpeername(sockfd, (struct sockaddr*)&peerAddr, &peerlen) == -1) { cerr << "getpeername error" << endl; exit(1); } cout << "server information: " << inet_ntoa(peerAddr.sin_addr) << ", " << ntohs(peerAddr.sin_port) << endl; cout << "count = " << ++count << endl; } }
Markdown
UTF-8
1,240
2.796875
3
[ "MIT" ]
permissive
# Remote Select Box # > This extension provides a simple combo box field that uses values from a remote source, via ajax. ### REQUIREMENTS ### - Symphony CMS version 2.3.3 and up (as of the day of the last release of this extension) ### INSTALLATION ### - `git clone` / download and unpack the tarball file - Put into the extension directory - Enable/install just like any other extension See <http://getsymphony.com/learn/tasks/view/install-an-extension/> *Voila !* Come say hi! -> <http://www.deuxhuithuit.com/> ### HOW TO USE ### - Add a Remote Select Box field to your section. - Set the `data url` options with a valid url - This url must return an array of JSON objects - Those object must have a `value` and a `text` member, i.e. ````js [{"value":"the saved value","text":"the text the user sees"}, {...}] ```` - You can use XMLHttpRequest friendly external sources or even a frontend page as your data source. ### KNOWN LIMITATIONS ### - When updating an entry, the value will be deleted if it can't find it in the datasource or if the datasource is broken. - Only the value is saved, not the text. - Only the value is displayed in the table view If you feel that this is wrong, do no hesitate to fork an improve it!
Markdown
UTF-8
2,147
3.859375
4
[]
no_license
# golang中的位运算 2021年10月26日 > 在阅读golang标准库的时候,发现代码中使用了很多位运算技巧,然而平时开发过程中使用很少,此文章前半部分做基础讲解,后半部分记录位运算各种操作,持续更新。 ## 概述 计算机中的数在内存中都是以二进制形式进行存储,用位运算就是直接对整数在内存中的二进制位进行操作,因此执行效率非常高,用位运算会大大提高程序的性能。 ## 操作符 | 运算符 | 含义 | 备注 | | ------ | -------------------- | ----------------------------------------------- | | & | 与运算(有0则0) | 相比较的两位都是1时结果为1,否则为0 | | \| | 或运算(有1则1) | 两者都为0才为0,否则为1 | | ^ | 异或运算(相同为0) | 相同为0,不同为1 | | ~ | 取反运算(0,1互换) | 0变1,1变0 | | << | 左移(进位,变大) | 高位丢弃,低位补0 | | >> | 右移(退位,变小) | 无符号:高位补0,低位丢弃;有符号:高位补符号位 | demo ```go // 与运算 & 10011 &11001 10001 // 或运算 | 10011 |11001 11011 // 异或运算^ 10011 ^11001 01010 // 取反运算~ ~10011 01100 // 左移 << a := 8 a << 3 before: 0000 1000 after: 0100 0000 // 右移 >> 无符号 a := uint8(9) a >> 3 before: 0000 1001 after: 0000 0001 // 右移 >> 有符号 // TODO ``` ## 常用操作 1.判断数字奇偶性 ```go func isEvenNumber(a int) bool { return a & 1 == 0 } // &运算,有0则0。a转换成二进制,最后一位为1时肯定是奇数,那么&1肯定不为0,最后一位为0时肯定肯定是偶数 // &1肯定为0 ``` ## 标准库中操作 ## 参考 [神级运算——位运算 - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/102277869) [(位运算有什么奇技淫巧? - 知乎 (zhihu.com)](https://www.zhihu.com/question/38206659)
Go
UTF-8
1,456
2.546875
3
[]
no_license
package actions import ( "net/http" "github.com/manugupt1/certmanager/models" ) func toByte(str string) []byte { return []byte(str) } func (as *ActionSuite) Test_CreateCustomer() { expectValidationErrors := []models.Customer{ models.Customer{Name: "M", Email: "manu@example.com", Password: toByte("")}, models.Customer{Name: "Manu", Email: "", Password: toByte("Gupta")}, models.Customer{Name: "", Email: "manu@example.com", Password: toByte("Gupta")}, models.Customer{Name: "M", Email: "manuexample.com", Password: toByte("G")}, } for _, customer := range expectValidationErrors { res := as.JSON("/customer").Post(customer) as.Equal(http.StatusBadRequest, res.Code) } expectSuccess := []models.Customer{ models.Customer{Name: "M", Email: "manu3@example.com", Password: toByte("password")}, models.Customer{Name: "M", Email: "manu4@example.com", Password: toByte("password")}, } for _, customer := range expectSuccess { res := as.JSON("/customer").Post(customer) as.Equal(http.StatusOK, res.Code, res.Body.String()) as.Empty(res.Body) } duplicateEmail := []models.Customer{ models.Customer{Name: "M", Email: "manu4@example.com", Password: toByte("password")}, } res := as.JSON("/customer").Post(duplicateEmail[0]) as.Equal(http.StatusBadRequest, res.Code, res.Body.String()) } //Test_CustomerList tests getting a list of customers func (as *ActionSuite) Test_ListCustomer() { res := as.JSON("/customer").Get() as.Equal(http.StatusOK, res.Code) }
PHP
UTF-8
2,380
2.640625
3
[]
no_license
<?php use Core\UserCenter\Exception\Unauthorized; use Core\UserCenter\Security; use Phalcon\Validation; use Phalcon\Validation\Validator\Numericality; use Phalcon\Validation\Validator\PresenceOf; class LaminationPriceHistory extends Model { /** * @var string */ protected $tableName = 'lamination_price_history'; /** * @var int * * @Column(type="integer", length=11, nullable=false) */ public $lamination_id; /** * @var int * * @Column(type="integer", length=11, nullable=false) */ public $department_id; /** * @var int * * @Column(type="integer", length=11, nullable=false) */ public $user_id; /** * @var int * * @Column(type="integer", length=32, nullable=false) */ public $price; /** * @var string * * @Column(type="string", nullable=false) */ public $datetime_from; /** * @var string * * @Column(type="string", nullable=true) */ public $datetime_to; public function initialize(): void { parent::initialize(); $this->belongsTo('lamination_id', '\Lamination', 'id', ['alias' => 'Lamination']); $this->belongsTo('user_id', '\User', 'id', ['alias' => 'User']); } public function validation(): bool { $validator = new Validation(); $validator->add( 'lamination_id', new Numericality( [ 'message' => 'Id размера ламинации должно быть числом', ] ) ); $validator->add( 'user_id', new Numericality( [ 'message' => 'Id пользователя должно быть числом', ] ) ); $validator->add( 'price', new Numericality( [ 'message' => 'Цена должна быть числом', ] ) ); $validator->add( 'lamination_id', new PresenceOf( [ 'message' => 'Id размера обязательное поле', ] ) ); $validator->add( 'user_id', new PresenceOf( [ 'message' => 'Id пользователя обезательное поле', ] ) ); $validator->add( 'price', new PresenceOf( [ 'message' => 'Цена обезательное поле', ] ) ); return $this->validate($validator); } /** * @throws Unauthorized */ public function beforeSave(): void { $user = Security::getUser(); $this->user_id = $user->id; $this->department_id = $user->department_id; } }
Java
UTF-8
1,368
2.53125
3
[]
no_license
package com.khsrd.springboot.controller; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadFileController { @GetMapping("/file") public String upload() { return "upload"; } private String UPLOADED_FOLDER ="/images/"; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, Model model) { System.out.println(file.getOriginalFilename()); try { byte[] bytes = file.getBytes(); String fileName = generateFileName(file.getOriginalFilename()); Path path = Paths.get(UPLOADED_FOLDER+ fileName); Files.write(path, bytes); model.addAttribute("fileName",fileName); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); e.printStackTrace(); } return "upload"; } public String generateFileName(String file) { String ext = file.substring(file.lastIndexOf(".")); String fileName = System.currentTimeMillis()+ext; System.out.println(fileName); return fileName; } }
C
UTF-8
2,322
3.015625
3
[]
no_license
#include <sys/inotify.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <malloc.h> typedef struct _name_watch_t { char * file; int descriptor; struct _name_watch_t * next; } name_watch_t; name_watch_t * name_watch_alloc(char * file, int descriptor, name_watch_t * next) { name_watch_t * w = malloc(sizeof(name_watch_t)); w->file = file; w->descriptor = descriptor; w->next = next; return w; } char * file_name(name_watch_t * watch, int descriptor) { if (watch == NULL) return NULL; if (watch->descriptor == descriptor) return watch->file; return file_name(watch->next, descriptor); } name_watch_t * name_watch_remove(name_watch_t * w, int descriptor) { name_watch_t * n; if (w == NULL) { return NULL; } else if (w->descriptor == descriptor) { n = w->next; free(w); return n; } else { w->next = name_watch_remove(w->next, descriptor); return w; } } int main(int argc, char ** argv) { int fd, i, wd; struct inotify_event evt; char * s; struct stat st; name_watch_t * head = NULL; if ((fd = inotify_init()) >= 0) { for (i = 1; i < argc; i++) { if ((wd = inotify_add_watch(fd, argv[i], IN_MODIFY|IN_DELETE_SELF)) >= 0) { head = name_watch_alloc(argv[i], wd, head); } else { fprintf(stderr, "Could not add watch on %s\n", argv[i]); return -1; } } while (read(fd, &evt, sizeof(struct inotify_event)) == sizeof(struct inotify_event)) { s = file_name(head, evt.wd); if (evt.mask & IN_DELETE_SELF) { head = name_watch_remove(head, evt.wd); inotify_rm_watch(fd, evt.wd); if (stat(s, &st) == 0 && (wd = inotify_add_watch(fd, s, IN_MODIFY|IN_DELETE_SELF)) >= 0) { head = name_watch_alloc(s, wd, head); } else { fprintf(stderr, "%s was removed\n", s); s = NULL; } } if (s) { printf("%s\n", s); fflush(stdout); } } } else { perror("inotify_init"); return -1; } return 0; }
Shell
UTF-8
1,301
3.453125
3
[ "Apache-2.0" ]
permissive
#!/bin/sh set -eu cd "$(dirname "$0")" . ../igr_functions.sh rm -f "$IGR_OUTPUT"/env-record RUSER=$(id -nu) RUID=$(id -u) RGID=$(id -g) # unset variables to make sure the values seen in the test service were initialised by dinit: for var in USER LOGNAME SHELL; do unset $var done # Ignore errors from unsetting UID & GID; some shells (bash, zsh) make them readonly. for var in UID GID; do unset $var > /dev/null 2>&1 || : done # test whether vars from global environment propagate export TEST_VAR="helloworld" spawn_dinit_oneshot -e env-dinit checkenv USER="$RUSER" # we try to override this one in env-dinit, but it should be set per-service LOGNAME="$USER" # these are overriden in env files SHELL="/bogus/value" if ! compare_text "$IGR_OUTPUT"/env-record "$(echo helloworld;\ echo hello;\ echo override;\ echo "$USER";\ echo "$LOGNAME";\ echo "$SHELL";\ echo "$RUID";\ echo "$RGID")" then error "$IGR_OUTPUT/env-record didn't contain expected result!" fi exit 0
Java
UTF-8
4,279
2.46875
2
[]
no_license
package db; import java.math.BigDecimal; import java.sql.*; import org.json.JSONObject; public class UpdateData { public static int UpdateFoodList(JSONObject json) { /*向菜品表插入数据*/ Connection conn = JDBCUtil.getConn(); PreparedStatement ps = null; int ans = 0; //向字段赋值 String id = json.getString("id"), name = json.getString("name"), intro = json.getString("intro"), simple_name = json.getString("simple_name"), food_clazz = json.getString("food_clazz"), rest = json.getString("rest"), discount = json.getString("discount"), pic_url = json.getString("pic_url"); Boolean state = json.getBoolean("state"); BigDecimal food_price = new BigDecimal(json.getString("food_price")); //sql String sql = "update food_list set name='"+name+ "',intro='"+intro+"',simple_name='"+simple_name+ "',food_clazz='"+food_clazz+"',rest='"+rest+"',discount='"+discount+ "',state='"+state+"',pic_url='"+pic_url+"',food_price='"+food_price+"' where id= '"+id+"'"; try { ps = conn.prepareStatement(sql); ans = ps.executeUpdate(sql); }catch(SQLException e) { e.printStackTrace(); return -1; /*失败*/ }finally { JDBCUtil.close(ps, conn); } return ans; } public static int UpdateOrderList(JSONObject json) { /*向订单表插入数据*/ Connection conn = JDBCUtil.getConn(); PreparedStatement ps = null; int ans = 0; /*向字段赋值*/ String id = json.getString("id"), order_no = json.getString("order_no"), order_info = json.getString("order_info"), usr_name = json.getString("usr_name"); BigDecimal order_price = new BigDecimal(json.getString("order_price")); Boolean order_state = json.getBoolean("order_state"); Timestamp order_create_time = new Timestamp(json.getLong("order_create_time")); /*时间戳,精确到秒*/ //sql String sql = "update order_list set order_no='"+order_no+ "',order_info='"+order_info+"',order_info='"+order_info+ "',order_price='"+order_price+"',order_state='"+order_state+"',usr_name='"+usr_name+"',order_create_time='"+order_create_time+ "' where id= '"+id+"'"; try { ps = conn.prepareStatement(sql); ans = ps.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); return -1; }finally { JDBCUtil.close(ps, conn); } return ans; } public static int UpdateAdminList(JSONObject json) { /*?向管理员表插入数据*/ Connection conn = JDBCUtil.getConn(); PreparedStatement ps = null; int ans = 0; /*向字段赋值*/ String admin_id = json.getString("admin_id"), password = json.getString("password"), email = json.getString("email"); /*sql插入语句*/ String sql = "update admin_list set email='"+email+ "',password='"+password+"' where admin_id= '"+admin_id+"'"; try { ps = conn.prepareStatement(sql); ans = ps.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); return -1; }finally { JDBCUtil.close(ps, conn); } return ans; } public static int UpdateUsrList(JSONObject json) { /*向用户表插入数据*/ Connection conn = JDBCUtil.getConn(); PreparedStatement ps = null; int ans = 0; /*向字段赋值*/ String id = json.getString("id"), name = json.getString("name"), usr_password = json.getString("usr_password"), order_no = json.getString("order_no"); BigDecimal usr_balance = new BigDecimal(json.getString("usr_balance")); BigDecimal usr_discount = new BigDecimal(json.getString("usr_discount")); Boolean state = json.getBoolean("state"); /*sql插入语句*/ String sql = "update usr_list set name='"+name+"',order_no='"+order_no+ "',usr_password='"+usr_password+"',usr_balance='"+usr_balance+ "',state='"+state+"',usr_discount='"+usr_discount+"' where id= '"+id+"'"; try { ps = conn.prepareStatement(sql); ans = ps.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); return -1; }finally{ JDBCUtil.close(ps, conn); } return ans; } // public static void main(String[] args) { // JSONObject obj = new JSONObject(); // int flag1 = 0; // // obj.put("admin_id","13"); // obj.put("email","jack"); // obj.put("password","1s"); // flag1 = UpdateData.UpdateAdminList(obj); // System.out.println(flag1); // } }
C#
UTF-8
3,429
2.75
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using FormulaEvaluator; namespace FormulaEvaluatorTest1 { [TestClass] public class EvaluatorClassTest { [TestMethod()] public void Test1() { Assert.AreEqual(9, Evaluator.Evaluate("8+1", s => 0)); } [TestMethod()] public void Test2() { Assert.AreEqual(8, Evaluator.Evaluate("B2-2", s => 10)); } [TestMethod()] public void Test3() { Assert.AreEqual(-2, Evaluator.Evaluate("6-8", s => 0)); } [TestMethod()] public void Test4() { Assert.AreEqual(1, Evaluator.Evaluate("A3", s => 1)); } [TestMethod()] public void Test5() { Assert.AreEqual(1815, Evaluator.Evaluate("55*33", s => 0)); } [TestMethod()] public void Test6() { Assert.AreEqual(1, Evaluator.Evaluate("5/5", s => 0)); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test7() { Evaluator.Evaluate("(10*10*", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test8() { Evaluator.Evaluate("8+8*8)", s => 0); } [TestMethod()] public void Test9() { Assert.AreEqual(6, Evaluator.Evaluate("1*2*3", s => 0)); } [TestMethod()] public void Test10() { Assert.AreEqual(625, Evaluator.Evaluate("5*5*5*5", s => 0)); } [TestMethod()] public void Test11() { Assert.AreEqual(0, Evaluator.Evaluate("s7-s7*s7/s7", s => 1)); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test12() { Evaluator.Evaluate("++2", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test13() { Evaluator.Evaluate("++-18)", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test14() { Evaluator.Evaluate("", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test15() { Evaluator.Evaluate("8++*22", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test16() { Evaluator.Evaluate("as", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test17() { Evaluator.Evaluate("0/0", s => 0); } [TestMethod()] public void Test18() { Assert.AreEqual(18, Evaluator.Evaluate("x1+(1+(2+(x2+(13))))", s => 1)); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test19() { Evaluator.Evaluate("55--44++22**18", s => 0); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Test20() { Evaluator.Evaluate("(A1)4+88", s => 0); } } }
Ruby
UTF-8
1,136
2.953125
3
[]
no_license
describe AccountHolder do test_details = { 'id' => 'testguid', 'firstname' => 'first', 'lastname' => 'last', 'email' => 'test@test.com', 'telephone' => '0123456789', 'balance' => '100.00' } subject { described_class.new(test_details) } # describe '#account_details' do # it 'should be initialized with a hash of details' do # expect(subject.account_details['id']).to eq 'testguid' # expect(subject.account_details['firstname']).to eq 'first' # expect(subject.account_details['lastname']).to eq 'last' # expect(subject.account_details['email']).to eq 'test@test.com' # expect(subject.account_details['telephone']).to eq '0123456789' # expect(subject.account_details['balance']).to eq '100.00' # end # end describe '#display_balance' do it "should return the account's balance" do expect(subject.display_balance).to eq '£100.00' end end describe '#show_account_details' do it "should return a list of the account holder's details" do expect(subject.show_account_details).to eq ['first', 'last', 'test@test.com', '0123456789'] end end end
Python
UTF-8
302
3
3
[ "MIT" ]
permissive
import sys,os import os.path as path def dedup(itr): l = [] for item in itr: if item not in l: l.append(item) return l PATH = os.environ['PATH'] paths = PATH.split(':') paths = filter(path.exists,paths) paths = dedup(paths) new_PATH = ':'.join(paths) print (new_PATH)
PHP
UTF-8
1,379
3.234375
3
[]
no_license
<?php namespace Gof\Sistema\Formulario\Validar; use Gof\Sistema\Formulario\Interfaz\Campo; use Gof\Sistema\Formulario\Interfaz\Errores; use Gof\Sistema\Formulario\Mediador\Campo\Error; /** * Valida si un campo existe dentro de los datos recibidos del formulario * * Verifica que el nombre del campo exista dentro del array de datos del formulario. * * @package Gof\Sistema\Formulario\Validar */ class ValidarExistencia { /** * @var string Mensaje de error que indica que el campo está vacío. */ public const ERROR_MENSAJE = 'Campo vacío'; /** * @var bool Almacena el estado de la existencia del campo. */ private bool $existe = true; /** * Constructor * * @param Campo $campo Instancia del campo a validar. * @param array $datos Datos del formulario de referencia. */ public function __construct(Campo $campo, array $datos) { if( isset($datos[$campo->clave()]) === false ) { Error::reportar($campo, self::ERROR_MENSAJE, Errores::ERROR_CAMPO_INEXISTENTE); $this->existe = false; } } /** * Indica si existe o no el campo en los datos recibidos del formulario * * @return bool Devuelve **true** si el campo existe o **false** de lo contrario. */ public function existe(): bool { return $this->existe; } }
Java
UTF-8
2,760
1.976563
2
[]
no_license
package com.empresa.monitoraLog.recebeLog.repository; import java.sql.Date; import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.empresa.monitoraLog.recebeLog.domain.ErrosRecorrentesPeriodo; import com.empresa.monitoraLog.recebeLog.domain.StackTrace; import com.empresa.monitoraLog.recebeLog.domain.TotalErrosPeriodo; public interface StackTraceRepository extends JpaRepository<StackTrace, Long>{ // TODO: COLOCAR ESSAS QUERYS NUM LUGAR DECENTE List<StackTrace> findByApplicationName(@Param("name")String appReference); @Query("select s from StackTrace s where s.applicationName = :appName and s.date between :startDate and :endDate") List<StackTrace> findByDate( @Param("appName") String appName, @Param("startDate") Date startDate, @Param("endDate") Date endDate); @Query("select count(s) from StackTrace s where date between :startDate and :endDate and s.applicationName = :appName") Long findTotalErrosPorPeriodo( @Param("appName") String appName, @Param("startDate") Date startDate, @Param("endDate") Date endDate); @Query("select new com.empresa.monitoraLog.recebeLog.domain.TotalErrosPeriodo(s.date, count(s)) " + "from StackTrace s " + "where date between :startDate and :endDate " + "and s.applicationName = :appName "+ "group by year(s.date), month(s.date), day(s.date) order by s.date desc") List<TotalErrosPeriodo> findTotalErrosPorDia( @Param("appName") String appName, @Param("startDate") Date startDate, @Param("endDate") Date endDate); @Query("select new com.empresa.monitoraLog.recebeLog.domain.ErrosRecorrentesPeriodo(s.exceptionType, count(s)) " + "from StackTrace s " + "where date between :startDate and :endDate " + "and s.applicationName = :appName "+ "group by s.exceptionType order by count(s) desc") List<ErrosRecorrentesPeriodo> findErrosMaisRecorrentesPeriodo( @Param("appName") String appName, @Param("startDate") Date startDate, @Param("endDate") Date endDate, Pageable pageable); @Query("select s.exceptionClass as exceptionClass, count(s.exceptionClass) as total " + "from StackTrace s " + "where date between :startDate and :endDate " + "and s.applicationName = :appName "+ "group by s.exceptionClass order by count(s.exceptionClass) desc") List<StackTrace> findClassesMaisRecorrentesPeriodo( @Param("appName") String appName, @Param("startDate") Date startDate, @Param("endDate") Date endDate, Pageable pageable); }
TypeScript
UTF-8
338
2.796875
3
[ "MIT" ]
permissive
import { hashSync, genSaltSync, compareSync } from 'bcryptjs'; export function obfuscatePassword(rawPass: string, rounds: number = 12): string { const salt = genSaltSync(rounds); return hashSync(rawPass, salt); } export function validatePassword(rawPass: string, hashPass: string): boolean { return compareSync(rawPass, hashPass); }
C++
UTF-8
1,408
3.921875
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <list> using namespace std; int main(){ // Los vectores son utilizados para manejar datos que no se conoce su dimension. // vector de 5 enteros vector <int> vector5int(5); cout<< "Implementation of a vector of INTS"<< endl; for(int x: vector5int){ // para cada valor del vector vector 5 int se agrega en x cout << x <<endl; } // string string arr[]={ "first", "Second", "Third", "Fourth", "Fifth" }; cout<< "Implementation of a vector of STRING" << endl; vector <string> vector_str(arr,arr+ 5); //sizeof tamano en bytes //vector <string> vector_str(5); for(string str: vector_str){ cout<< str << endl; } // LIST cout <<" Implementation vector with a LIST"<< endl; list <string> listofSTR; listofSTR.push_back("first"); listofSTR.push_back("second"); listofSTR.push_back("third"); listofSTR.push_back("fourth"); listofSTR.push_back("fifth"); vector<string> vector_str_list(listofSTR.begin(),listofSTR.end()); for(string i: vector_str_list){ cout<< i<<endl; } cout<< "Assign one vector to another" << endl; vector<string> second_vector(vector_str); int n = second_vector.size(); cout<< " Size of the vector is "<< n<< endl; return 0; }
PHP
UTF-8
221
2.765625
3
[]
no_license
<?php $salery = (int) readline("Add meg a fizetsed Ft-ban: "); if ($salery < 200000){ echo "Fizetesed alacsony"; } elseif ($salery <= 400000) { echo "Fizetesed atlagos"; } else{ echo "Fizetesed magas!Gratulalok"; }
Java
UTF-8
109,551
2.578125
3
[ "Artistic-2.0" ]
permissive
/* Minpack_f77.java copyright claim: This software is based on the public domain MINPACK routines. It was translated from FORTRAN to Java by a US government employee on official time. Thus this software is also in the public domain. The translator's mail address is: Steve Verrill USDA Forest Products Laboratory 1 Gifford Pinchot Drive Madison, Wisconsin 53705 The translator's e-mail address is: steve@www1.fpl.fs.fed.us *********************************************************************** DISCLAIMER OF WARRANTIES: THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. THE TRANSLATOR DOES NOT WARRANT, GUARANTEE OR MAKE ANY REPRESENTATIONS REGARDING THE SOFTWARE OR DOCUMENTATION IN TERMS OF THEIR CORRECTNESS, RELIABILITY, CURRENCY, OR OTHERWISE. THE ENTIRE RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE IS ASSUMED BY YOU. IN NO CASE WILL ANY PARTY INVOLVED WITH THE CREATION OR DISTRIBUTION OF THE SOFTWARE BE LIABLE FOR ANY DAMAGE THAT MAY RESULT FROM THE USE OF THIS SOFTWARE. Sorry about that. *********************************************************************** History: Date Translator Changes 11/3/00 Steve Verrill Translated */ package optimizers; /** * *<p> *This class contains Java translations of the MINPACK nonlinear least *squares routines. As of November 2000, it does not yet contain *the MINPACK solvers of systems of nonlinear equations. They should *be added in the Spring of 2001.<p> *The original FORTRAN MINPACK package was produced by *Burton S. Garbow, Kenneth E. Hillstrom, and Jorge J. More *as part of the Argonne National Laboratory MINPACK project, March 1980. * *<p> *<b>IMPORTANT:</b> The "_f77" suffixes indicate that these routines use *FORTRAN style indexing. For example, you will see *<pre> * for (i = 1; i <= n; i++) *</pre> *rather than *<pre> * for (i = 0; i < n; i++) *</pre> *To use the "_f77" routines you will have to declare your vectors *and matrices to be one element larger (e.g., v[101] rather than *v[100], and a[101][101] rather than a[100][100]), and you will have *to fill elements 1 through n rather than elements 0 through n - 1. *Versions of these programs that use C/Java style indexing might *eventually be available. They would end with the suffix "_j". * *<p> *This class was translated by a statistician from FORTRAN versions of *lmder and lmdif. It is NOT an official translation. It wastes *memory by failing to use the first elements of vectors. When *public domain Java optimization routines become available *from the people who produced MINPACK, then <b>THE CODE PRODUCED *BY THE NUMERICAL ANALYSTS SHOULD BE USED</b>. * *<p> *Meanwhile, if you have suggestions for improving this *code, please contact Steve Verrill at steve@www1.fpl.fs.fed.us. * *@author (translator)Steve Verrill *@version .5 --- November 3, 2000 * */ public class Minpack_f77 extends Object { // epsmch is the machine precision static final double epsmch = 2.22044604926e-16; // minmag is the smallest magnitude static final double minmag = 2.22507385852e-308; static final double zero = 0.0; static final double one = 1.0; static final double p0001 = .0001; static final double p001 = .001; static final double p05 = .05; static final double p1 = .1; static final double p25 = .25; static final double p5 = .5; static final double p75 = .75; /** * *<p> *The lmder1_f77 method minimizes the sum of the squares of *m nonlinear functions in n variables by a modification of the *Levenberg-Marquardt algorithm. This is done by using the more *general least-squares solver lmder_f77. The user must provide a *method which calculates the functions and the Jacobian. *<p> *Translated by Steve Verrill on November 17, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param nlls A class that implements the Lmder_fcn interface * (see the definition in Lmder_fcn.java). See * LmderTest_f77.java for an example of such a class. * The class must define a method, fcn, that must * have the form * * public static void fcn(int m, int n, double x[], * double fvec[], double fjac[][], int iflag[]) * * If iflag[1] equals 1, fcn calculates the values of * the m functions [residuals] at x and returns this * vector in fvec. If iflag[1] equals 2, fcn calculates * the Jacobian at x and returns this matrix in fjac * (and does not alter fvec). * * The value of iflag[1] should not be changed by fcn unless * the user wants to terminate execution of lmder_f77. * In this case set iflag[1] to a negative integer. * *@param m A positive integer set to the number of functions * [number of observations] *@param n A positive integer set to the number of variables * [number of parameters]. n must not exceed m. *@param x On input, it contains the initial estimate of * the solution vector [the least squares parameters]. * On output it contains the final estimate of the * solution vector. *@param fvec An output vector that contains the m functions * [residuals] evaluated at x. *@param fjac An output m by n array. The upper n by n submatrix * of fjac contains an upper triangular matrix R with * diagonal elements of nonincreasing magnitude such that *<pre> * t t t * P (jac jac)P = R R, *</pre> * where P is a permutation matrix and jac is the final * calculated Jacobian. Column j of P is column ipvt[j] * of the identity matrix. The lower trapezoidal * part of fjac contains information generated during * the computation of R. *@param tol tol is a nonnegative input variable. Termination occurs * when the algorithm estimates either that the relative * error in the sum of squares is at most tol or that * the relative error between x and the solution is at * most tol. *@param info An integer output variable. If the user has * terminated execution, info is set to the (negative) * value of iflag[1]. See description of fcn. Otherwise, * info is set as follows. * * info = 0 improper input parameters. * * info = 1 algorithm estimates that the relative error * in the sum of squares is at most tol. * * info = 2 algorithm estimates that the relative error * between x and the solution is at most tol. * * info = 3 conditions for info = 1 and info = 2 both hold. * * info = 4 fvec is orthogonal to the columns of the * Jacobian to machine precision. * * info = 5 number of calls to fcn with iflag[1] = 1 has * reached 100*(n+1). * * info = 6 tol is too small. No further reduction in * the sum of squares is possible. * * info = 7 tol is too small. No further improvement in * the approximate solution x is possible. *@param ipvt An integer output array of length n. ipvt * defines a permutation matrix P such that jac*P = QR, * where jac is the final calculated Jacobian, Q is * orthogonal (not stored), and R is upper triangular * with diagonal elements of nonincreasing magnitude. * Column j of P is column ipvt[j] of the identity matrix. * */ public static void lmder1_f77(Lmder_fcn nlls, int m, int n, double x[], double fvec[], double fjac[][], double tol, int info[], int ipvt[]) { /* Here is a copy of the lmder1 FORTRAN documentation: subroutine lmder1(fcn,m,n,x,fvec,fjac,ldfjac,tol,info,ipvt,wa, * lwa) integer m,n,ldfjac,info,lwa integer ipvt(n) double precision tol double precision x(n),fvec(m),fjac(ldfjac,n),wa(lwa) external fcn c ********** c c subroutine lmder1 c c the purpose of lmder1 is to minimize the sum of the squares of c m nonlinear functions in n variables by a modification of the c levenberg-marquardt algorithm. this is done by using the more c general least-squares solver lmder. the user must provide a c subroutine which calculates the functions and the jacobian. c c the subroutine statement is c c subroutine lmder1(fcn,m,n,x,fvec,fjac,ldfjac,tol,info, c ipvt,wa,lwa) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions and the jacobian. fcn must c be declared in an external statement in the user c calling program, and should be written as follows. c c subroutine fcn(m,n,x,fvec,fjac,ldfjac,iflag) c integer m,n,ldfjac,iflag c double precision x(n),fvec(m),fjac(ldfjac,n) c ---------- c if iflag = 1 calculate the functions at x and c return this vector in fvec. do not alter fjac. c if iflag = 2 calculate the jacobian at x and c return this matrix in fjac. do not alter fvec. c ---------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of lmder1. c in this case set iflag to a negative integer. c c m is a positive integer input variable set to the number c of functions. c c n is a positive integer input variable set to the number c of variables. n must not exceed m. c c x is an array of length n. on input x must contain c an initial estimate of the solution vector. on output x c contains the final estimate of the solution vector. c c fvec is an output array of length m which contains c the functions evaluated at the output x. c c fjac is an output m by n array. the upper n by n submatrix c of fjac contains an upper triangular matrix r with c diagonal elements of nonincreasing magnitude such that c c t t t c p *(jac *jac)*p = r *r, c c where p is a permutation matrix and jac is the final c calculated jacobian. column j of p is column ipvt(j) c (see below) of the identity matrix. the lower trapezoidal c part of fjac contains information generated during c the computation of r. c c ldfjac is a positive integer input variable not less than m c which specifies the leading dimension of the array fjac. c c tol is a nonnegative input variable. termination occurs c when the algorithm estimates either that the relative c error in the sum of squares is at most tol or that c the relative error between x and the solution is at c most tol. c c info is an integer output variable. if the user has c terminated execution, info is set to the (negative) c value of iflag. see description of fcn. otherwise, c info is set as follows. c c info = 0 improper input parameters. c c info = 1 algorithm estimates that the relative error c in the sum of squares is at most tol. c c info = 2 algorithm estimates that the relative error c between x and the solution is at most tol. c c info = 3 conditions for info = 1 and info = 2 both hold. c c info = 4 fvec is orthogonal to the columns of the c jacobian to machine precision. c c info = 5 number of calls to fcn with iflag = 1 has c reached 100*(n+1). c c info = 6 tol is too small. no further reduction in c the sum of squares is possible. c c info = 7 tol is too small. no further improvement in c the approximate solution x is possible. c c ipvt is an integer output array of length n. ipvt c defines a permutation matrix p such that jac*p = q*r, c where jac is the final calculated jacobian, q is c orthogonal (not stored), and r is upper triangular c with diagonal elements of nonincreasing magnitude. c column j of p is column ipvt(j) of the identity matrix. c c wa is a work array of length lwa. c c lwa is a positive integer input variable not less than 5*n+m. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... lmder c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int maxfev,mode,nprint; int nfev[] = new int[2]; int njev[] = new int[2]; double diag[] = new double[n+1]; double qtf[] = new double[n+1]; // double factor,ftol,gtol,xtol,zero; double factor,ftol,gtol,xtol; factor = 1.0e+2; // zero = 0.0; info[1] = 0; // Check the input parameters for errors. if (n <= 0 || m < n || tol < zero) { return; } else { // Call lmder_f77. maxfev = 100*(n + 1); ftol = tol; xtol = tol; gtol = zero; mode = 1; nprint = 0; Minpack_f77.lmder_f77(nlls,m,n,x,fvec,fjac,ftol,xtol,gtol,maxfev, diag,mode,factor,nprint,info,nfev,njev,ipvt,qtf); if (info[1] == 8) info[1] = 4; return; } } /** * *<p> *The lmder_f77 method minimizes the sum of the squares of *m nonlinear functions in n variables by a modification of *the Levenberg-Marquardt algorithm. The user must provide a *method which calculates the functions and the Jacobian. *<p> *Translated by Steve Verrill on November 3, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param nlls A class that implements the Lmder_fcn interface * (see the definition in Lmder_fcn.java). See * LmderTest_f77.java for an example of such a class. * The class must define a method, fcn, that must * have the form * * public static void fcn(int m, int n, double x[], * double fvec[], double fjac[][], int iflag[]) * * If iflag[1] equals 1, fcn calculates the values of * the m functions [residuals] at x and returns this * vector in fvec. If iflag[1] equals 2, fcn calculates * the Jacobian at x and returns this matrix in fjac * (and does not alter fvec). * * The value of iflag[1] should not be changed by fcn unless * the user wants to terminate execution of lmder_f77. * In this case set iflag[1] to a negative integer. * *@param m A positive integer set to the number of functions * [number of observations] *@param n A positive integer set to the number of variables * [number of parameters]. n must not exceed m. *@param x On input, it contains the initial estimate of * the solution vector [the least squares parameters]. * On output it contains the final estimate of the * solution vector. *@param fvec An output vector that contains the m functions * [residuals] evaluated at x. *@param fjac An output m by n array. The upper n by n submatrix * of fjac contains an upper triangular matrix R with * diagonal elements of nonincreasing magnitude such that *<pre> * t t t * P (jac jac)P = R R, *</pre> * where P is a permutation matrix and jac is the final * calculated Jacobian. Column j of P is column ipvt[j] * of the identity matrix. The lower trapezoidal * part of fjac contains information generated during * the computation of R. *@param ftol A nonnegative input variable. Termination * occurs when both the actual and predicted relative * reductions in the sum of squares are at most ftol. * Therefore, ftol measures the relative error desired * in the sum of squares. *@param xtol A nonnegative input variable. Termination * occurs when the relative error between two consecutive * iterates is at most xtol. Therefore, xtol measures the * relative error desired in the approximate solution. *@param gtol A nonnegative input variable. Termination * occurs when the cosine of the angle between fvec and * any column of the Jacobian is at most gtol in absolute * value. Therefore, gtol measures the orthogonality * desired between the function vector and the columns * of the Jacobian. *@param maxfev A positive integer input variable. Termination * occurs when the number of calls to fcn with iflag[1] = 1 * has reached maxfev. *@param diag An vector of length n. If mode = 1 (see * below), diag is internally set. If mode = 2, diag * must contain positive entries that serve as * multiplicative scale factors for the variables. *@param mode If mode = 1, the * variables will be scaled internally. If mode = 2, * the scaling is specified by the input diag. Other * values of mode are equivalent to mode = 1. *@param factor A positive input variable used in determining the * initial step bound. This bound is set to the product of * factor and the euclidean norm of diag*x if nonzero, or else * to factor itself. In most cases factor should lie in the * interval (.1,100). 100 is a generally recommended value. *@param nprint An integer input variable that enables controlled * printing of iterates if it is positive. In this case, * fcn is called with iflag[1] = 0 at the beginning of the first * iteration and every nprint iterations thereafter and * immediately prior to return, with x, fvec, and fjac * available for printing. fvec and fjac should not be * altered. If nprint is not positive, no special calls * of fcn with iflag[1] = 0 are made. *@param info An integer output variable. If the user has * terminated execution, info is set to the (negative) * value of iflag[1]. See description of fcn. Otherwise, * info is set as follows. * * info = 0 improper input parameters. * * info = 1 both actual and predicted relative reductions * in the sum of squares are at most ftol. * * info = 2 relative error between two consecutive iterates * is at most xtol. * * info = 3 conditions for info = 1 and info = 2 both hold. * * info = 4 the cosine of the angle between fvec and any * column of the Jacobian is at most gtol in * absolute value. * * info = 5 number of calls to fcn with iflag[1] = 1 has * reached maxfev. * * info = 6 ftol is too small. no further reduction in * the sum of squares is possible. * * info = 7 xtol is too small. no further improvement in * the approximate solution x is possible. * * info = 8 gtol is too small. fvec is orthogonal to the * columns of the Jacobian to machine precision. * *@param nfev An integer output variable set to the number of * calls to fcn with iflag[1] = 1. *@param njev An integer output variable set to the number of * calls to fcn with iflag[1] = 2. *@param ipvt An integer output array of length n. ipvt * defines a permutation matrix P such that jac*P = QR, * where jac is the final calculated Jacobian, Q is * orthogonal (not stored), and R is upper triangular * with diagonal elements of nonincreasing magnitude. * column j of P is column ipvt[j] of the identity matrix. * *@param qtf An output array of length n which contains * the first n elements of the vector (Q transpose)fvec. * * */ /* Note that since Java passes primitive types by value rather than by reference, if they need to return a value, they need to be passed as arrays (here we place the actual value in location [1]). For example, info is passed as info[]. */ public static void lmder_f77(Lmder_fcn nlls, int m, int n, double x[], double fvec[], double fjac[][], double ftol, double xtol, double gtol, int maxfev, double diag[], int mode, double factor, int nprint,int info[], int nfev[], int njev[], int ipvt[], double qtf[]) { /* Here is a copy of the lmder FORTRAN documentation: subroutine lmder(fcn,m,n,x,fvec,fjac,ldfjac,ftol,xtol,gtol, * maxfev,diag,mode,factor,nprint,info,nfev,njev, * ipvt,qtf,wa1,wa2,wa3,wa4) integer m,n,ldfjac,maxfev,mode,nprint,info,nfev,njev integer ipvt(n) double precision ftol,xtol,gtol,factor double precision x(n),fvec(m),fjac(ldfjac,n),diag(n),qtf(n), * wa1(n),wa2(n),wa3(n),wa4(m) c c subroutine lmder c c the purpose of lmder is to minimize the sum of the squares of c m nonlinear functions in n variables by a modification of c the Levenberg-Marquardt algorithm. the user must provide a c subroutine which calculates the functions and the Jacobian. c c the subroutine statement is c c subroutine lmder(fcn,m,n,x,fvec,fjac,ldfjac,ftol,xtol,gtol, c maxfev,diag,mode,factor,nprint,info,nfev, c njev,ipvt,qtf,wa1,wa2,wa3,wa4) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions and the Jacobian. fcn must c be declared in an external statement in the user c calling program, and should be written as follows. c c subroutine fcn(m,n,x,fvec,fjac,ldfjac,iflag) c integer m,n,ldfjac,iflag c double precision x(n),fvec(m),fjac(ldfjac,n) c ---------- c if iflag = 1 calculate the functions at x and c return this vector in fvec. do not alter fjac. c if iflag = 2 calculate the Jacobian at x and c return this matrix in fjac. do not alter fvec. c ---------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of lmder. c in this case set iflag to a negative integer. c c m is a positive integer input variable set to the number c of functions. c c n is a positive integer input variable set to the number c of variables. n must not exceed m. c c x is an array of length n. on input x must contain c an initial estimate of the solution vector. on output x c contains the final estimate of the solution vector. c c fvec is an output array of length m which contains c the functions evaluated at the output x. c c fjac is an output m by n array. the upper n by n submatrix c of fjac contains an upper triangular matrix r with c diagonal elements of nonincreasing magnitude such that c c t t t c p *(jac *jac)*p = r *r, c c where p is a permutation matrix and jac is the final c calculated Jacobian. column j of p is column ipvt(j) c (see below) of the identity matrix. the lower trapezoidal c part of fjac contains information generated during c the computation of r. c c ldfjac is a positive integer input variable not less than m c which specifies the leading dimension of the array fjac. c c ftol is a nonnegative input variable. termination c occurs when both the actual and predicted relative c reductions in the sum of squares are at most ftol. c therefore, ftol measures the relative error desired c in the sum of squares. c c xtol is a nonnegative input variable. termination c occurs when the relative error between two consecutive c iterates is at most xtol. therefore, xtol measures the c relative error desired in the approximate solution. c c gtol is a nonnegative input variable. termination c occurs when the cosine of the angle between fvec and c any column of the Jacobian is at most gtol in absolute c value. therefore, gtol measures the orthogonality c desired between the function vector and the columns c of the Jacobian. c c maxfev is a positive integer input variable. termination c occurs when the number of calls to fcn with iflag = 1 c has reached maxfev. c c diag is an array of length n. if mode = 1 (see c below), diag is internally set. if mode = 2, diag c must contain positive entries that serve as c multiplicative scale factors for the variables. c c mode is an integer input variable. if mode = 1, the c variables will be scaled internally. if mode = 2, c the scaling is specified by the input diag. other c values of mode are equivalent to mode = 1. c c factor is a positive input variable used in determining the c initial step bound. this bound is set to the product of c factor and the euclidean norm of diag*x if nonzero, or else c to factor itself. in most cases factor should lie in the c interval (.1,100.).100. is a generally recommended value. c c nprint is an integer input variable that enables controlled c printing of iterates if it is positive. in this case, c fcn is called with iflag = 0 at the beginning of the first c iteration and every nprint iterations thereafter and c immediately prior to return, with x, fvec, and fjac c available for printing. fvec and fjac should not be c altered. if nprint is not positive, no special calls c of fcn with iflag = 0 are made. c c info is an integer output variable. if the user has c terminated execution, info is set to the (negative) c value of iflag. see description of fcn. otherwise, c info is set as follows. c c info = 0 improper input parameters. c c info = 1 both actual and predicted relative reductions c in the sum of squares are at most ftol. c c info = 2 relative error between two consecutive iterates c is at most xtol. c c info = 3 conditions for info = 1 and info = 2 both hold. c c info = 4 the cosine of the angle between fvec and any c column of the Jacobian is at most gtol in c absolute value. c c info = 5 number of calls to fcn with iflag = 1 has c reached maxfev. c c info = 6 ftol is too small. no further reduction in c the sum of squares is possible. c c info = 7 xtol is too small. no further improvement in c the approximate solution x is possible. c c info = 8 gtol is too small. fvec is orthogonal to the c columns of the Jacobian to machine precision. c c nfev is an integer output variable set to the number of c calls to fcn with iflag = 1. c c njev is an integer output variable set to the number of c calls to fcn with iflag = 2. c c ipvt is an integer output array of length n. ipvt c defines a permutation matrix p such that jac*p = q*r, c where jac is the final calculated Jacobian, q is c orthogonal (not stored), and r is upper triangular c with diagonal elements of nonincreasing magnitude. c column j of p is column ipvt(j) of the identity matrix. c c qtf is an output array of length n which contains c the first n elements of the vector (q transpose)*fvec. c c wa1, wa2, and wa3 are work arrays of length n. c c wa4 is a work array of length m. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... dpmpar,enorm,lmpar,qrfac c c fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c */ int i,iter,j,l; // double actred,delta,dirder,fnorm,fnorm1,gnorm, // one,pnorm,prered,p1,p5,p25,p75,p0001,ratio, // sum,temp,temp1,temp2,xnorm,zero; double actred,delta,dirder,fnorm,fnorm1,gnorm, pnorm,prered,ratio, sum,temp,temp1,temp2,xnorm; double par[] = new double[2]; boolean doneout,donein; int iflag[] = new int[2]; double wa1[] = new double[n+1]; double wa2[] = new double[n+1]; double wa3[] = new double[n+1]; double wa4[] = new double[m+1]; // Java compiler complains if delta and xnorm are not initialized delta = 0.0; xnorm = 0.0; // one = 1.0; // p1 = .1; // p5 = .5; // p25 = .25; // p75 = .75; // p0001 = .0001; // zero = 0.0; info[1] = 0; iflag[1] = 0; nfev[1] = 0; njev[1] = 0; // Check the input parameters for errors. if (n <= 0 || m < n || ftol < zero || xtol < zero || gtol < zero || maxfev <= 0 || factor <= zero) { // Termination if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } if (mode == 2) { for (j = 1; j <= n; j++) { if (diag[j] <= zero) { // Termination if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } } } // Evaluate the function at the starting point // and calculate its norm. iflag[1] = 1; nlls.fcn(m,n,x,fvec,fjac,iflag); nfev[1] = 1; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } fnorm = Minpack_f77.enorm_f77(m,fvec); // Initialize Levenberg-Marquardt parameter and iteration counter. par[1] = zero; iter = 1; // Beginning of the outer loop. doneout = false; while (!doneout) { // 30 continue // Calculate the Jacobian matrix. iflag[1] = 2; nlls.fcn(m,n,x,fvec,fjac,iflag); njev[1]++; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } // If requested, call fcn to enable printing of iterates. if (nprint > 0) { iflag[1] = 0; if ((iter-1)%nprint == 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; nlls.fcn(m,n,x,fvec,fjac,iflag); return; } } // Compute the qr factorization of the Jacobian. Minpack_f77.qrfac_f77(m,n,fjac,true,ipvt,wa1,wa2,wa3); // On the first iteration and if mode is 1, scale according // to the norms of the columns of the initial Jacobian. if (iter == 1) { if (mode != 2) { for (j = 1; j <= n; j++) { diag[j] = wa2[j]; if (wa2[j] == zero) diag[j] = one; } } // On the first iteration, calculate the norm of the scaled x // and initialize the step bound delta. for (j = 1; j <= n; j++) { wa3[j] = diag[j]*x[j]; } xnorm = Minpack_f77.enorm_f77(n,wa3); delta = factor*xnorm; if (delta == zero) delta = factor; } // Form (q transpose)*fvec and store the first n components in // qtf. for (i = 1; i <= m; i++) wa4[i] = fvec[i]; for (j = 1; j <= n; j++) { if (fjac[j][j] != zero) { sum = zero; for (i = j; i <= m; i++) sum += fjac[i][j]*wa4[i]; temp = -sum/fjac[j][j]; for (i = j; i <= m; i++) wa4[i] += fjac[i][j]*temp; } fjac[j][j] = wa1[j]; qtf[j] = wa4[j]; } // Compute the norm of the scaled gradient. gnorm = zero; if (fnorm != zero) { for (j = 1; j <= n; j++) { l = ipvt[j]; if (wa2[l] != zero) { sum = zero; for (i = 1; i <= j; i++) sum += fjac[i][j]*(qtf[i]/fnorm); gnorm = Math.max(gnorm,Math.abs(sum/wa2[l])); } } } // Test for convergence of the gradient norm. if (gnorm <= gtol) info[1] = 4; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } // Rescale if necessary. if (mode != 2) { for (j = 1; j <= n; j++) { diag[j] = Math.max(diag[j],wa2[j]); } } // Beginning of the inner loop. donein = false; while (!donein) { // 200 continue // Determine the Levenberg-Marquardt parameter. Minpack_f77.lmpar_f77(n,fjac,ipvt,diag,qtf,delta,par,wa1,wa2, wa3,wa4); // Store the direction p and x + p. calculate the norm of p. for (j = 1; j <= n; j++) { wa1[j] = -wa1[j]; wa2[j] = x[j] + wa1[j]; wa3[j] = diag[j]*wa1[j]; } pnorm = Minpack_f77.enorm_f77(n,wa3); // On the first iteration, adjust the initial step bound. if (iter == 1) delta = Math.min(delta,pnorm); // Evaluate the function at x + p and calculate its norm. iflag[1] = 1; nlls.fcn(m,n,wa2,wa4,fjac,iflag); nfev[1]++; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } fnorm1 = Minpack_f77.enorm_f77(m,wa4); // Compute the scaled actual reduction. actred = -one; if (p1*fnorm1 < fnorm) actred = one - (fnorm1/fnorm)*(fnorm1/fnorm); // Compute the scaled predicted reduction and // the scaled directional derivative. for (j = 1; j <= n; j++) { wa3[j] = zero; l = ipvt[j]; temp = wa1[l]; for (i = 1; i <= j; i++) wa3[i] += fjac[i][j]*temp; } temp1 = Minpack_f77.enorm_f77(n,wa3)/fnorm; temp2 = (Math.sqrt(par[1])*pnorm)/fnorm; prered = temp1*temp1 + temp2*temp2/p5; dirder = -(temp1*temp1 + temp2*temp2); // Compute the ratio of the actual to the predicted // reduction. ratio = zero; if (prered != zero) ratio = actred/prered; // Update the step bound. if (ratio <= p25) { if (actred >= zero) { temp = p5; } else { temp = p5*dirder/(dirder + p5*actred); } if (p1*fnorm1 >= fnorm || temp < p1) temp = p1; delta = temp*Math.min(delta,pnorm/p1); par[1] /= temp; } else { if (par[1] == zero || ratio >= p75) { delta = pnorm/p5; par[1] *= p5; } } // Test for successful iteration. if (ratio >= p0001) { // Successful iteration. Update x, fvec, and their norms. for (j = 1; j <= n; j++) { x[j] = wa2[j]; wa2[j] = diag[j]*x[j]; } for (i = 1; i <= m; i++) fvec[i] = wa4[i]; xnorm = Minpack_f77.enorm_f77(n,wa2); fnorm = fnorm1; iter++; } // Tests for convergence. if (Math.abs(actred) <= ftol && prered <= ftol && p5*ratio <= one) info[1] = 1; if (delta <= xtol*xnorm) info[1] = 2; if (Math.abs(actred) <= ftol && prered <= ftol && p5*ratio <= one && info[1] == 2) info[1] = 3; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } // Tests for termination and stringent tolerances. if (nfev[1] >= maxfev) info[1] = 5; if (Math.abs(actred) <= epsmch && prered <= epsmch && p5*ratio <= one) info[1] = 6; if (delta <= epsmch*xnorm) info[1] = 7; if (gnorm <= epsmch) info[1] = 8; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,fjac,iflag); } return; } // End of the inner loop. Repeat if iteration unsuccessful. if (ratio >= p0001) donein = true; } // End of the outer loop. } } /** * *<p> *The enorm_f77 method calculates the Euclidean norm of a vector. *<p> *Translated by Steve Verrill on November 14, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param n The length of the vector, x. *@param x The vector whose Euclidean norm is to be calculated. * */ public static double enorm_f77(int n, double x[]) { /* Here is a copy of the enorm FORTRAN documentation: double precision function enorm(n,x) integer n double precision x(n) c ********** c c function enorm c c given an n-vector x, this function calculates the c euclidean norm of x. c c the euclidean norm is computed by accumulating the sum of c squares in three different sums. the sums of squares for the c small and large components are scaled so that no overflows c occur. non-destructive underflows are permitted. underflows c and overflows do not occur in the computation of the unscaled c sum of squares for the intermediate components. c the definitions of small, intermediate and large components c depend on two constants, rdwarf and rgiant. the main c restrictions on these constants are that rdwarf**2 not c underflow and rgiant**2 not overflow. the constants c given here are suitable for every known computer. c c the function statement is c c double precision function enorm(n,x) c c where c c n is a positive integer input variable. c c x is an input array of length n. c c subprograms called c c fortran-supplied ... dabs,dsqrt c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i; // double agiant,floatn,one,rdwarf,rgiant,s1,s2,s3,xabs, // x1max,x3max,zero; double agiant,floatn,rdwarf,rgiant,s1,s2,s3,xabs, x1max,x3max; double enorm; // one = 1.0; // zero = 0.0; rdwarf = 3.834e-20; rgiant = 1.304e+19; s1 = zero; s2 = zero; s3 = zero; x1max = zero; x3max = zero; floatn = n; agiant = rgiant/floatn; for (i = 1; i <= n; i++) { xabs = Math.abs(x[i]); if (xabs <= rdwarf || xabs >= agiant) { if (xabs > rdwarf) { // Sum for large components. if (xabs > x1max) { s1 = one + s1*(x1max/xabs)*(x1max/xabs); x1max = xabs; } else { s1 += (xabs/x1max)*(xabs/x1max); } } else { // Sum for small components. if (xabs > x3max) { s3 = one + s3*(x3max/xabs)*(x3max/xabs); x3max = xabs; } else { if (xabs != zero) s3 += (xabs/x3max)*(xabs/x3max); } } } else { // Sum for intermediate components. s2 += xabs*xabs; } } // Calculation of norm. if (s1 != zero) { enorm = x1max*Math.sqrt(s1+(s2/x1max)/x1max); } else { if (s2 != zero) { if (s2 >= x3max) { enorm = Math.sqrt(s2*(one+(x3max/s2)*(x3max*s3))); } else { enorm = Math.sqrt(x3max*((s2/x3max)+(x3max*s3))); } } else { enorm = x3max*Math.sqrt(s3); } } return enorm; } /** * *<p> *The qrfac_f77 method uses Householder transformations with column *pivoting (optional) to compute a QR factorization of the *m by n matrix A. That is, qrfac_f77 determines an orthogonal *matrix Q, a permutation matrix P, and an upper trapezoidal *matrix R with diagonal elements of nonincreasing magnitude, *such that AP = QR. *<p> *Translated by Steve Verrill on November 17, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param m The number of rows of A. *@param n The number of columns of A. *@param a A is an m by n array. On input A contains the matrix for * which the QR factorization is to be computed. On output * the strict upper trapezoidal part of A contains the strict * upper trapezoidal part of R, and the lower trapezoidal * part of A contains a factored form of Q. *@param pivot pivot is a logical input variable. If pivot is set true, * then column pivoting is enforced. If pivot is set false, * then no column pivoting is done. *@param ipvt ipvt is an integer output array. ipvt * defines the permutation matrix P such that A*P = Q*R. * Column j of P is column ipvt[j] of the identity matrix. * If pivot is false, ipvt is not referenced. *@param rdiag rdiag is an output array of length n which contains the * diagonal elements of R. *@param acnorm acnorm is an output array of length n which contains the * norms of the corresponding columns of the input matrix A. *@param wa wa is a work array of length n. * * */ public static void qrfac_f77(int m, int n, double a[][], boolean pivot, int ipvt[], double rdiag[], double acnorm[], double wa[]) { /* Here is a copy of the qrfac FORTRAN documentation: subroutine qrfac(m,n,a,lda,pivot,ipvt,lipvt,rdiag,acnorm,wa) integer m,n,lda,lipvt integer ipvt(lipvt) logical pivot double precision a(lda,n),rdiag(n),acnorm(n),wa(n) c ********** c c subroutine qrfac c c this subroutine uses householder transformations with column c pivoting (optional) to compute a qr factorization of the c m by n matrix a. that is, qrfac determines an orthogonal c matrix q, a permutation matrix p, and an upper trapezoidal c matrix r with diagonal elements of nonincreasing magnitude, c such that a*p = q*r. the householder transformation for c column k, k = 1,2,...,min(m,n), is of the form c c t c i - (1/u(k))*u*u c c where u has zeros in the first k-1 positions. the form of c this transformation and the method of pivoting first c appeared in the corresponding linpack subroutine. c c the subroutine statement is c c subroutine qrfac(m,n,a,lda,pivot,ipvt,lipvt,rdiag,acnorm,wa) c c where c c m is a positive integer input variable set to the number c of rows of a. c c n is a positive integer input variable set to the number c of columns of a. c c a is an m by n array. on input a contains the matrix for c which the qr factorization is to be computed. on output c the strict upper trapezoidal part of a contains the strict c upper trapezoidal part of r, and the lower trapezoidal c part of a contains a factored form of q (the non-trivial c elements of the u vectors described above). c c lda is a positive integer input variable not less than m c which specifies the leading dimension of the array a. c c pivot is a logical input variable. if pivot is set true, c then column pivoting is enforced. if pivot is set false, c then no column pivoting is done. c c ipvt is an integer output array of length lipvt. ipvt c defines the permutation matrix p such that a*p = q*r. c column j of p is column ipvt(j) of the identity matrix. c if pivot is false, ipvt is not referenced. c c lipvt is a positive integer input variable. if pivot is false, c then lipvt may be as small as 1. if pivot is true, then c lipvt must be at least n. c c rdiag is an output array of length n which contains the c diagonal elements of r. c c acnorm is an output array of length n which contains the c norms of the corresponding columns of the input matrix a. c if this information is not needed, then acnorm can coincide c with rdiag. c c wa is a work array of length n. if pivot is false, then wa c can coincide with rdiag. c c subprograms called c c minpack-supplied ... dpmpar,enorm c c fortran-supplied ... dmax1,dsqrt,min0 c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i,j,jp1,k,kmax,minmn; // double ajnorm,one,p05,sum,temp,zero; double ajnorm,sum,temp; double fac; double tempvec[] = new double[m+1]; // one = 1.0; // p05 = .05; // zero = 0.0; // Compute the initial column norms and initialize several arrays. for (j = 1; j <= n; j++) { for (i = 1; i <= m; i++) { tempvec[i] = a[i][j]; } // acnorm[j] = Minpack_f77.enorm_f77(m,a[1][j]); acnorm[j] = Minpack_f77.enorm_f77(m,tempvec); rdiag[j] = acnorm[j]; wa[j] = rdiag[j]; if (pivot) ipvt[j] = j; } // Reduce A to R with Householder transformations. minmn = Math.min(m,n); for (j = 1; j <= minmn; j++) { if (pivot) { // Bring the column of largest norm into the pivot position. kmax = j; for (k = j; k <= n; k++) { if (rdiag[k] > rdiag[kmax]) kmax = k; } if (kmax != j) { for (i = 1; i <= m; i++) { temp = a[i][j]; a[i][j] = a[i][kmax]; a[i][kmax] = temp; } rdiag[kmax] = rdiag[j]; wa[kmax] = wa[j]; k = ipvt[j]; ipvt[j] = ipvt[kmax]; ipvt[kmax] = k; } } // Compute the Householder transformation to reduce the // j-th column of A to a multiple of the j-th unit vector. for (i = j; i <= m; i++) { tempvec[i - j + 1] = a[i][j]; } // ajnorm = Minpack_f77.enorm_f77(m-j+1,a[j][j]); ajnorm = Minpack_f77.enorm_f77(m-j+1,tempvec); if (ajnorm != zero) { if (a[j][j] < zero) ajnorm = -ajnorm; for (i = j; i <= m; i++) { a[i][j] /= ajnorm; } a[j][j] += one; // Apply the transformation to the remaining columns // and update the norms. jp1 = j + 1; if (n >= jp1) { for (k = jp1; k <= n; k++) { sum = zero; for (i = j; i <= m; i++) { sum += a[i][j]*a[i][k]; } temp = sum/a[j][j]; for (i = j; i <= m; i++) { a[i][k] -= temp*a[i][j]; } if (pivot && rdiag[k] != zero) { temp = a[j][k]/rdiag[k]; rdiag[k] *= Math.sqrt(Math.max(zero,one-temp*temp)); fac = rdiag[k]/wa[k]; if (p05*fac*fac <= epsmch) { for (i = jp1; i <= m; i++) { tempvec[i - j] = a[i][k]; } // rdiag[k] = Minpack_f77.enorm_f77(m-j,a[jp1][k]); rdiag[k] = Minpack_f77.enorm_f77(m-j,tempvec); wa[k] = rdiag[k]; } } } } } rdiag[j] = -ajnorm; } return; } /** * *<p> *Given an m by n matrix A, an n by n diagonal matrix D, *and an m-vector b, the problem is to determine an x which *solves the system *<pre> * Ax = b , Dx = 0 , *</pre> *in the least squares sense. *<p> *This method completes the solution of the problem *if it is provided with the necessary information from the *QR factorization, with column pivoting, of A. That is, if *AP = QR, where P is a permutation matrix, Q has orthogonal *columns, and R is an upper triangular matrix with diagonal *elements of nonincreasing magnitude, then qrsolv_f77 expects *the full upper triangle of R, the permutation matrix P, *and the first n components of (Q transpose)b. The system *<pre> * Ax = b, Dx = 0, is then equivalent to * * t t * Rz = Q b, P DPz = 0 , *</pre> *where x = Pz. If this system does not have full rank, *then a least squares solution is obtained. On output qrsolv_f77 *also provides an upper triangular matrix S such that *<pre> * t t t * P (A A + DD)P = S S . *</pre> *S is computed within qrsolv_f77 and may be of separate interest. *<p> *Translated by Steve Verrill on November 17, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param n The order of r. *@param r r is an n by n array. On input the full upper triangle * must contain the full upper triangle of the matrix R. * On output the full upper triangle is unaltered, and the * strict lower triangle contains the strict upper triangle * (transposed) of the upper triangular matrix S. *@param ipvt ipvt is an integer input array of length n which defines the * permutation matrix P such that AP = QR. Column j of P * is column ipvt[j] of the identity matrix. *@param diag diag is an input array of length n which must contain the * diagonal elements of the matrix D. *@param qtb qtb is an input array of length n which must contain the first * n elements of the vector (Q transpose)b. *@param x x is an output array of length n which contains the least * squares solution of the system Ax = b, Dx = 0. *@param sdiag sdiag is an output array of length n which contains the * diagonal elements of the upper triangular matrix S. *@param wa wa is a work array of length n. * * */ public static void qrsolv_f77(int n, double r[][], int ipvt[], double diag[], double qtb[], double x[], double sdiag[], double wa[]) { /* Here is a copy of the qrsolv FORTRAN documentation: subroutine qrsolv(n,r,ldr,ipvt,diag,qtb,x,sdiag,wa) integer n,ldr integer ipvt(n) double precision r(ldr,n),diag(n),qtb(n),x(n),sdiag(n),wa(n) c ********** c c subroutine qrsolv c c given an m by n matrix a, an n by n diagonal matrix d, c and an m-vector b, the problem is to determine an x which c solves the system c c a*x = b , d*x = 0 , c c in the least squares sense. c c this subroutine completes the solution of the problem c if it is provided with the necessary information from the c qr factorization, with column pivoting, of a. that is, if c a*p = q*r, where p is a permutation matrix, q has orthogonal c columns, and r is an upper triangular matrix with diagonal c elements of nonincreasing magnitude, then qrsolv expects c the full upper triangle of r, the permutation matrix p, c and the first n components of (q transpose)*b. the system c a*x = b, d*x = 0, is then equivalent to c c t t c r*z = q *b , p *d*p*z = 0 , c c where x = p*z. if this system does not have full rank, c then a least squares solution is obtained. on output qrsolv c also provides an upper triangular matrix s such that c c t t t c p *(a *a + d*d)*p = s *s . c c s is computed within qrsolv and may be of separate interest. c c the subroutine statement is c c subroutine qrsolv(n,r,ldr,ipvt,diag,qtb,x,sdiag,wa) c c where c c n is a positive integer input variable set to the order of r. c c r is an n by n array. on input the full upper triangle c must contain the full upper triangle of the matrix r. c on output the full upper triangle is unaltered, and the c strict lower triangle contains the strict upper triangle c (transposed) of the upper triangular matrix s. c c ldr is a positive integer input variable not less than n c which specifies the leading dimension of the array r. c c ipvt is an integer input array of length n which defines the c permutation matrix p such that a*p = q*r. column j of p c is column ipvt(j) of the identity matrix. c c diag is an input array of length n which must contain the c diagonal elements of the matrix d. c c qtb is an input array of length n which must contain the first c n elements of the vector (q transpose)*b. c c x is an output array of length n which contains the least c squares solution of the system a*x = b, d*x = 0. c c sdiag is an output array of length n which contains the c diagonal elements of the upper triangular matrix s. c c wa is a work array of length n. c c subprograms called c c fortran-supplied ... dabs,dsqrt c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i,j,jp1,k,kp1,l,nsing; // double cos,cotan,p5,p25,qtbpj,sin,sum,tan,temp,zero; double cos,cotan,qtbpj,sin,sum,tan,temp; // p5 = .5; // p25 = .25; // zero = 0.0; // Copy R and (Q transpose)b to preserve input and initialize S. // In particular, save the diagonal elements of R in x. for (j = 1; j <= n; j++) { for (i = j; i <= n; i++) { r[i][j] = r[j][i]; } x[j] = r[j][j]; wa[j] = qtb[j]; } // Eliminate the diagonal matrix D using a Givens rotation. for (j = 1; j <= n; j++) { // Prepare the row of D to be eliminated, locating the // diagonal element using P from the QR factorization. l = ipvt[j]; if (diag[l] != zero) { for (k = j; k <= n; k++) { sdiag[k] = zero; } sdiag[j] = diag[l]; // The transformations to eliminate the row of D // modify only a single element of (Q transpose)b // beyond the first n, which is initially zero. ?????? qtbpj = zero; for (k = j; k <= n; k++) { // Determine a Givens rotation which eliminates the // appropriate element in the current row of D. if (sdiag[k] != zero) { if (Math.abs(r[k][k]) < Math.abs(sdiag[k])) { cotan = r[k][k]/sdiag[k]; sin = p5/Math.sqrt(p25+p25*cotan*cotan); cos = sin*cotan; } else { tan = sdiag[k]/r[k][k]; cos = p5/Math.sqrt(p25+p25*tan*tan); sin = cos*tan; } // Compute the modified diagonal element of R and // the modified element of ((Q transpose)b,0). r[k][k] = cos*r[k][k] + sin*sdiag[k]; temp = cos*wa[k] + sin*qtbpj; qtbpj = -sin*wa[k] + cos*qtbpj; wa[k] = temp; // Accumulate the tranformation in the row of S. kp1 = k + 1; for (i = kp1; i <= n; i++) { temp = cos*r[i][k] + sin*sdiag[i]; sdiag[i] = -sin*r[i][k] + cos*sdiag[i]; r[i][k] = temp; } } } } // Store the diagonal element of S and restore // the corresponding diagonal element of R. sdiag[j] = r[j][j]; r[j][j] = x[j]; } // Solve the triangular system for z. if the system is // singular, then obtain a least squares solution. nsing = n; for (j = 1; j <= n; j++) { if (sdiag[j] == zero && nsing == n) nsing = j - 1; if (nsing < n) wa[j] = zero; } // if (nsing >= 1) { for (k = 1; k <= nsing; k++) { j = nsing - k + 1; sum = zero; jp1 = j + 1; // if (nsing >= jp1) { for (i = jp1; i <= nsing; i++) { sum += r[i][j]*wa[i]; } // } wa[j] = (wa[j] - sum)/sdiag[j]; } // } // Permute the components of z back to components of x. for (j = 1; j <= n; j++) { l = ipvt[j]; x[l] = wa[j]; } return; } /** * *<p> *Given an m by n matrix A, an n by n nonsingular diagonal *matrix D, an m-vector b, and a positive number delta, *the problem is to determine a value for the parameter *par such that if x solves the system *<pre> * A*x = b , sqrt(par)*D*x = 0 *</pre> *in the least squares sense, and dxnorm is the Euclidean *norm of D*x, then either par is zero and *<pre> * (dxnorm-delta) <= 0.1*delta , *</pre> * or par is positive and *<pre> * abs(dxnorm-delta) <= 0.1*delta . *</pre> *This method (lmpar_f77) completes the solution of the problem *if it is provided with the necessary information from the *QR factorization, with column pivoting, of A. That is, if *AP = QR, where P is a permutation matrix, Q has orthogonal *columns, and R is an upper triangular matrix with diagonal *elements of nonincreasing magnitude, then lmpar_f77 expects *the full upper triangle of R, the permutation matrix P, *and the first n components of (Q transpose)b. On output *lmpar_f77 also provides an upper triangular matrix S such that *<pre> * t t t * P (A A + par*DD)P = S S . *</pre> *S is employed within lmpar_f77 and may be of separate interest. *<p> *Only a few iterations are generally needed for convergence *of the algorithm. If, however, the limit of 10 iterations *is reached, then the output par will contain the best *value obtained so far. *<p> *Translated by Steve Verrill on November 17, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param n The order of r. *@param r r is an n by n array. On input the full upper triangle * must contain the full upper triangle of the matrix R. * On output the full upper triangle is unaltered, and the * strict lower triangle contains the strict upper triangle * (transposed) of the upper triangular matrix S. *@param ipvt ipvt is an integer input array of length n which defines the * permutation matrix P such that AP = QR. Column j of P * is column ipvt[j] of the identity matrix. *@param diag diag is an input array of length n which must contain the * diagonal elements of the matrix D. *@param qtb qtb is an input array of length n which must contain the first * n elements of the vector (Q transpose)b. *@param delta delta is a positive input variable which specifies an upper * bound on the Euclidean norm of Dx. *@param par par is a nonnegative variable. On input par contains an * initial estimate of the Levenberg-Marquardt parameter. * On output par contains the final estimate. *@param x x is an output array of length n which contains the least * squares solution of the system Ax = b, sqrt(par)*Dx = 0, * for the output par. *@param sdiag sdiag is an output array of length n which contains the * diagonal elements of the upper triangular matrix S. *@param wa1 wa1 is a work array of length n. *@param wa2 wa2 is a work array of length n. * * */ public static void lmpar_f77(int n, double r[][], int ipvt[], double diag[], double qtb[], double delta, double par[], double x[], double sdiag[], double wa1[], double wa2[]) { /* Here is a copy of the lmpar FORTRAN documentation: subroutine lmpar(n,r,ldr,ipvt,diag,qtb,delta,par,x,sdiag,wa1, * wa2) integer n,ldr integer ipvt(n) double precision delta,par double precision r(ldr,n),diag(n),qtb(n),x(n),sdiag(n),wa1(n), * wa2(n) c ********** c c subroutine lmpar c c given an m by n matrix a, an n by n nonsingular diagonal c matrix d, an m-vector b, and a positive number delta, c the problem is to determine a value for the parameter c par such that if x solves the system c c a*x = b , sqrt(par)*d*x = 0 , c c in the least squares sense, and dxnorm is the euclidean c norm of d*x, then either par is zero and c c (dxnorm-delta) .le. 0.1*delta , c c or par is positive and c c abs(dxnorm-delta) .le. 0.1*delta . c c this subroutine completes the solution of the problem c if it is provided with the necessary information from the c qr factorization, with column pivoting, of a. that is, if c a*p = q*r, where p is a permutation matrix, q has orthogonal c columns, and r is an upper triangular matrix with diagonal c elements of nonincreasing magnitude, then lmpar expects c the full upper triangle of r, the permutation matrix p, c and the first n components of (q transpose)*b. on output c lmpar also provides an upper triangular matrix s such that c c t t t c p *(a *a + par*d*d)*p = s *s . c c s is employed within lmpar and may be of separate interest. c c only a few iterations are generally needed for convergence c of the algorithm. if, however, the limit of 10 iterations c is reached, then the output par will contain the best c value obtained so far. c c the subroutine statement is c c subroutine lmpar(n,r,ldr,ipvt,diag,qtb,delta,par,x,sdiag, c wa1,wa2) c c where c c n is a positive integer input variable set to the order of r. c c r is an n by n array. on input the full upper triangle c must contain the full upper triangle of the matrix r. c on output the full upper triangle is unaltered, and the c strict lower triangle contains the strict upper triangle c (transposed) of the upper triangular matrix s. c c ldr is a positive integer input variable not less than n c which specifies the leading dimension of the array r. c c ipvt is an integer input array of length n which defines the c permutation matrix p such that a*p = q*r. column j of p c is column ipvt(j) of the identity matrix. c c diag is an input array of length n which must contain the c diagonal elements of the matrix d. c c qtb is an input array of length n which must contain the first c n elements of the vector (q transpose)*b. c c delta is a positive input variable which specifies an upper c bound on the euclidean norm of d*x. c c par is a nonnegative variable. on input par contains an c initial estimate of the levenberg-marquardt parameter. c on output par contains the final estimate. c c x is an output array of length n which contains the least c squares solution of the system a*x = b, sqrt(par)*d*x = 0, c for the output par. c c sdiag is an output array of length n which contains the c diagonal elements of the upper triangular matrix s. c c wa1 and wa2 are work arrays of length n. c c subprograms called c c minpack-supplied ... dpmpar,enorm,qrsolv c c fortran-supplied ... dabs,dmax1,dmin1,dsqrt c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i,iter,j,jm1,jp1,k,l,nsing; // double dxnorm,dwarf,fp,gnorm,parc,parl,paru,p1,p001, // sum,temp,zero; double dxnorm,dwarf,fp,gnorm,parc,parl,paru, sum,temp; boolean loop; // p1 = .1; // p001 = .001; // zero = 0.0; // dwarf is the smallest positive magnitude. dwarf = minmag; // Compute and store in x the Gauss-Newton direction. If the // Jacobian is rank-deficient, obtain a least squares solution. nsing = n; for (j = 1; j <= n; j++) { wa1[j] = qtb[j]; if (r[j][j] == zero && nsing == n) nsing = j - 1; if (nsing < n) wa1[j] = zero; } // if (nsing >= 1) { for (k = 1; k <= nsing; k++) { j = nsing - k + 1; wa1[j] /= r[j][j]; temp = wa1[j]; jm1 = j - 1; // if (jm1 >= 1) { for (i = 1; i <= jm1; i++) { wa1[i] -= r[i][j]*temp; } // } } // } for (j = 1; j <= n; j++) { l = ipvt[j]; x[l] = wa1[j]; } // Initialize the iteration counter. // Evaluate the function at the origin, and test // for acceptance of the Gauss-Newton direction. iter = 0; for (j = 1; j <= n; j++) { wa2[j] = diag[j]*x[j]; } dxnorm = Minpack_f77.enorm_f77(n,wa2); fp = dxnorm - delta; if (fp <= p1*delta) { par[1] = zero; return; } // If the Jacobian is not rank deficient, the Newton // step provides a lower bound, parl, for the zero of // the function. Otherwise set this bound to zero. parl = zero; if (nsing >= n) { for (j = 1; j <= n; j++) { l = ipvt[j]; wa1[j] = diag[l]*(wa2[l]/dxnorm); } for (j = 1; j <= n; j++) { sum = zero; jm1 = j - 1; // if (jm1 >= 1) { for (i = 1; i <= jm1; i++) { sum += r[i][j]*wa1[i]; } // } wa1[j] = (wa1[j] - sum)/r[j][j]; } temp = Minpack_f77.enorm_f77(n,wa1); parl = ((fp/delta)/temp)/temp; } // Calculate an upper bound, paru, for the zero of the function. for (j = 1; j <= n; j++) { sum = zero; for (i = 1; i <= j; i++) { sum += r[i][j]*qtb[i]; } l = ipvt[j]; wa1[j] = sum/diag[l]; } gnorm = Minpack_f77.enorm_f77(n,wa1); paru = gnorm/delta; if (paru == zero) paru = dwarf/Math.min(delta,p1); // If the input par lies outside of the interval (parl,paru), // set par to the closer endpoint. par[1] = Math.max(par[1],parl); par[1] = Math.min(par[1],paru); if (par[1] == zero) par[1] = gnorm/dxnorm; // Beginning of an iteration. loop = true; while (loop) { iter++; // Evaluate the function at the current value of par. if (par[1] == zero) par[1] = Math.max(dwarf,p001*paru); temp = Math.sqrt(par[1]); for (j = 1; j <= n; j++) { wa1[j] = temp*diag[j]; } Minpack_f77.qrsolv_f77(n,r,ipvt,wa1,qtb,x,sdiag,wa2); for (j = 1; j <= n; j++) { wa2[j] = diag[j]*x[j]; } dxnorm = Minpack_f77.enorm_f77(n,wa2); temp = fp; fp = dxnorm - delta; // If the function is small enough, accept the current value // of par. Also test for the exceptional cases where parl // is zero or the number of iterations has reached 10. if (Math.abs(fp) <= p1*delta || parl == zero && fp <= temp && temp < zero || iter == 10) { // Termination if (iter == 0) par[1] = zero; return; } // Compute the Newton correction. for (j = 1; j <= n; j++) { l = ipvt[j]; wa1[j] = diag[l]*(wa2[l]/dxnorm); } for (j = 1; j <= n; j++) { wa1[j] /= sdiag[j]; temp = wa1[j]; jp1 = j + 1; for (i = jp1; i <= n; i++) { wa1[i] -= r[i][j]*temp; } } temp = Minpack_f77.enorm_f77(n,wa1); parc = ((fp/delta)/temp)/temp; // Depending on the sign of the function, update parl or paru. if (fp > zero) parl = Math.max(parl,par[1]); if (fp < zero) paru = Math.min(paru,par[1]); // Compute an improved estimate for par[1]. par[1] = Math.max(parl,par[1]+parc); // End of an iteration. } } /** * *<p> *The lmdif1_f77 method minimizes the sum of the squares of *m nonlinear functions in n variables by a modification of the *Levenberg-Marquardt algorithm. This is done by using the more *general least-squares solver lmdif. The user must provide a *method that calculates the functions. The Jacobian is *then calculated by a forward-difference approximation. *<p> *Translated by Steve Verrill on November 24, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param nlls A class that implements the Lmdif_fcn interface * (see the definition in Lmdif_fcn.java). See * LmdifTest_f77.java for an example of such a class. * The class must define a method, fcn, that must * have the form * * public static void fcn(int m, int n, double x[], * double fvec[], int iflag[]) * * The value of iflag[1] should not be changed by fcn unless * the user wants to terminate execution of lmdif_f77. * In this case set iflag[1] to a negative integer. * *@param m A positive integer set to the number of functions * [number of observations] *@param n A positive integer set to the number of variables * [number of parameters]. n must not exceed m. *@param x On input, it contains the initial estimate of * the solution vector [the least squares parameters]. * On output it contains the final estimate of the * solution vector. *@param fvec An output vector that contains the m functions * [residuals] evaluated at x. *@param tol tol is a nonnegative input variable. Termination occurs * when the algorithm estimates either that the relative * error in the sum of squares is at most tol or that * the relative error between x and the solution is at * most tol. *@param info An integer output variable. If the user has * terminated execution, info is set to the (negative) * value of iflag[1]. See description of fcn. Otherwise, * info is set as follows. * * info = 0 improper input parameters. * * info = 1 algorithm estimates that the relative error * in the sum of squares is at most tol. * * info = 2 algorithm estimates that the relative error * between x and the solution is at most tol. * * info = 3 conditions for info = 1 and info = 2 both hold. * * info = 4 fvec is orthogonal to the columns of the * Jacobian to machine precision. * * info = 5 number of calls to fcn has * reached or exceeded 200*(n+1). * * info = 6 tol is too small. No further reduction in * the sum of squares is possible. * * info = 7 tol is too small. No further improvement in * the approximate solution x is possible. * */ public static void lmdif1_f77(Lmdif_fcn nlls, int m, int n, double x[], double fvec[], double tol, int info[]) { /* Here is a copy of the lmdif1 FORTRAN documentation: subroutine lmdif1(fcn,m,n,x,fvec,tol,info,iwa,wa,lwa) integer m,n,info,lwa integer iwa(n) double precision tol double precision x(n),fvec(m),wa(lwa) external fcn c ********** c c subroutine lmdif1 c c the purpose of lmdif1 is to minimize the sum of the squares of c m nonlinear functions in n variables by a modification of the c levenberg-marquardt algorithm. this is done by using the more c general least-squares solver lmdif. the user must provide a c subroutine which calculates the functions. the jacobian is c then calculated by a forward-difference approximation. c c the subroutine statement is c c subroutine lmdif1(fcn,m,n,x,fvec,tol,info,iwa,wa,lwa) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions. fcn must be declared c in an external statement in the user calling c program, and should be written as follows. c c subroutine fcn(m,n,x,fvec,iflag) c integer m,n,iflag c double precision x(n),fvec(m) c ---------- c calculate the functions at x and c return this vector in fvec. c ---------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of lmdif1. c in this case set iflag to a negative integer. c c m is a positive integer input variable set to the number c of functions. c c n is a positive integer input variable set to the number c of variables. n must not exceed m. c c x is an array of length n. on input x must contain c an initial estimate of the solution vector. on output x c contains the final estimate of the solution vector. c c fvec is an output array of length m which contains c the functions evaluated at the output x. c c tol is a nonnegative input variable. termination occurs c when the algorithm estimates either that the relative c error in the sum of squares is at most tol or that c the relative error between x and the solution is at c most tol. c c info is an integer output variable. if the user has c terminated execution, info is set to the (negative) c value of iflag. see description of fcn. otherwise, c info is set as follows. c c info = 0 improper input parameters. c c info = 1 algorithm estimates that the relative error c in the sum of squares is at most tol. c c info = 2 algorithm estimates that the relative error c between x and the solution is at most tol. c c info = 3 conditions for info = 1 and info = 2 both hold. c c info = 4 fvec is orthogonal to the columns of the c jacobian to machine precision. c c info = 5 number of calls to fcn has reached or c exceeded 200*(n+1). c c info = 6 tol is too small. no further reduction in c the sum of squares is possible. c c info = 7 tol is too small. no further improvement in c the approximate solution x is possible. c c iwa is an integer work array of length n. c c wa is a work array of length lwa. c c lwa is a positive integer input variable not less than c m*n+5*n+m. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... lmdif c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int maxfev,mode,nprint; // double epsfcn,factor,ftol,gtol,xtol,zero; double epsfcn,factor,ftol,gtol,xtol; double diag[] = new double[n+1]; int nfev[] = new int[2]; double fjac[][] = new double[m+1][n+1]; int ipvt[] = new int[n+1]; double qtf[] = new double[n+1]; factor = 100.0; // zero = 0.0; info[1] = 0; // Check the input parameters for errors. if (n <= 0 || m < n || tol < zero) { return; } // Call lmdif. maxfev = 200*(n + 1); ftol = tol; xtol = tol; gtol = zero; epsfcn = zero; mode = 1; nprint = 0; Minpack_f77.lmdif_f77(nlls,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,diag, mode,factor,nprint,info,nfev,fjac, ipvt,qtf); if (info[1] == 8) info[1] = 4; return; } /** * *<p> *The lmdif_f77 method minimizes the sum of the squares of *m nonlinear functions in n variables by a modification of *the Levenberg-Marquardt algorithm. The user must provide a *method that calculates the functions. The Jacobian is *then calculated by a forward-difference approximation. *<p> *Translated by Steve Verrill on November 20, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param nlls A class that implements the Lmdif_fcn interface * (see the definition in Lmdif_fcn.java). See * LmdifTest_f77.java for an example of such a class. * The class must define a method, fcn, that must * have the form * * public static void fcn(int m, int n, double x[], * double fvec[], int iflag[]) * * The value of iflag[1] should not be changed by fcn unless * the user wants to terminate execution of lmdif_f77. * In this case set iflag[1] to a negative integer. * *@param m A positive integer set to the number of functions * [number of observations] *@param n A positive integer set to the number of variables * [number of parameters]. n must not exceed m. *@param x On input, it contains the initial estimate of * the solution vector [the least squares parameters]. * On output it contains the final estimate of the * solution vector. *@param fvec An output vector that contains the m functions * [residuals] evaluated at x. *@param ftol A nonnegative input variable. Termination * occurs when both the actual and predicted relative * reductions in the sum of squares are at most ftol. * Therefore, ftol measures the relative error desired * in the sum of squares. *@param xtol A nonnegative input variable. Termination * occurs when the relative error between two consecutive * iterates is at most xtol. Therefore, xtol measures the * relative error desired in the approximate solution. *@param gtol A nonnegative input variable. Termination * occurs when the cosine of the angle between fvec and * any column of the Jacobian is at most gtol in absolute * value. Therefore, gtol measures the orthogonality * desired between the function vector and the columns * of the Jacobian. *@param maxfev A positive integer input variable. Termination * occurs when the number of calls to fcn is at least * maxfev by the end of an iteration. *@param epsfcn An input variable used in determining a suitable * step length for the forward-difference approximation. This * approximation assumes that the relative errors in the * functions are of the order of epsfcn. If epsfcn is less * than the machine precision, it is assumed that the relative * errors in the functions are of the order of the machine * precision. *@param diag An vector of length n. If mode = 1 (see * below), diag is internally set. If mode = 2, diag * must contain positive entries that serve as * multiplicative scale factors for the variables. *@param mode If mode = 1, the * variables will be scaled internally. If mode = 2, * the scaling is specified by the input diag. Other * values of mode are equivalent to mode = 1. *@param factor A positive input variable used in determining the * initial step bound. This bound is set to the product of * factor and the euclidean norm of diag*x if nonzero, or else * to factor itself. In most cases factor should lie in the * interval (.1,100). 100 is a generally recommended value. *@param nprint An integer input variable that enables controlled * printing of iterates if it is positive. In this case, * fcn is called with iflag[1] = 0 at the beginning of the first * iteration and every nprint iterations thereafter and * immediately prior to return, with x and fvec * available for printing. If nprint is not positive, * no special calls of fcn with iflag[1] = 0 are made. *@param info An integer output variable. If the user has * terminated execution, info is set to the (negative) * value of iflag[1]. See description of fcn. Otherwise, * info is set as follows. * * info = 0 improper input parameters. * * info = 1 both actual and predicted relative reductions * in the sum of squares are at most ftol. * * info = 2 relative error between two consecutive iterates * is at most xtol. * * info = 3 conditions for info = 1 and info = 2 both hold. * * info = 4 the cosine of the angle between fvec and any * column of the Jacobian is at most gtol in * absolute value. * * info = 5 number of calls to fcn with iflag[1] = 1 has * reached maxfev. * * info = 6 ftol is too small. no further reduction in * the sum of squares is possible. * * info = 7 xtol is too small. no further improvement in * the approximate solution x is possible. * * info = 8 gtol is too small. fvec is orthogonal to the * columns of the Jacobian to machine precision. * *@param nfev An integer output variable set to the number of * calls to fcn. *@param fjac An output m by n array. The upper n by n submatrix * of fjac contains an upper triangular matrix R with * diagonal elements of nonincreasing magnitude such that * * t t t * P (jac *jac)P = R R, * * where P is a permutation matrix and jac is the final * calculated Jacobian. Column j of P is column ipvt[j] * (see below) of the identity matrix. The lower trapezoidal * part of fjac contains information generated during * the computation of R. *@param ipvt An integer output array of length n. ipvt * defines a permutation matrix P such that jac*P = QR, * where jac is the final calculated Jacobian, Q is * orthogonal (not stored), and R is upper triangular * with diagonal elements of nonincreasing magnitude. * column j of P is column ipvt[j] of the identity matrix. * *@param qtf An output array of length n which contains * the first n elements of the vector (Q transpose)fvec. * * */ public static void lmdif_f77(Lmdif_fcn nlls, int m, int n, double x[], double fvec[], double ftol, double xtol, double gtol, int maxfev, double epsfcn, double diag[], int mode, double factor, int nprint, int info[], int nfev[], double fjac[][], int ipvt[], double qtf[]) { /* Here is a copy of the lmdif FORTRAN documentation: subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn, * diag,mode,factor,nprint,info,nfev,fjac,ldfjac, * ipvt,qtf,wa1,wa2,wa3,wa4) integer m,n,maxfev,mode,nprint,info,nfev,ldfjac integer ipvt(n) double precision ftol,xtol,gtol,epsfcn,factor double precision x(n),fvec(m),diag(n),fjac(ldfjac,n),qtf(n), * wa1(n),wa2(n),wa3(n),wa4(m) external fcn c ********** c c subroutine lmdif c c the purpose of lmdif is to minimize the sum of the squares of c m nonlinear functions in n variables by a modification of c the levenberg-marquardt algorithm. the user must provide a c subroutine which calculates the functions. the jacobian is c then calculated by a forward-difference approximation. c c the subroutine statement is c c subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn, c diag,mode,factor,nprint,info,nfev,fjac, c ldfjac,ipvt,qtf,wa1,wa2,wa3,wa4) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions. fcn must be declared c in an external statement in the user calling c program, and should be written as follows. c c subroutine fcn(m,n,x,fvec,iflag) c integer m,n,iflag c double precision x(n),fvec(m) c ---------- c calculate the functions at x and c return this vector in fvec. c ---------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of lmdif. c in this case set iflag to a negative integer. c c m is a positive integer input variable set to the number c of functions. c c n is a positive integer input variable set to the number c of variables. n must not exceed m. c c x is an array of length n. on input x must contain c an initial estimate of the solution vector. on output x c contains the final estimate of the solution vector. c c fvec is an output array of length m which contains c the functions evaluated at the output x. c c ftol is a nonnegative input variable. termination c occurs when both the actual and predicted relative c reductions in the sum of squares are at most ftol. c therefore, ftol measures the relative error desired c in the sum of squares. c c xtol is a nonnegative input variable. termination c occurs when the relative error between two consecutive c iterates is at most xtol. therefore, xtol measures the c relative error desired in the approximate solution. c c gtol is a nonnegative input variable. termination c occurs when the cosine of the angle between fvec and c any column of the jacobian is at most gtol in absolute c value. therefore, gtol measures the orthogonality c desired between the function vector and the columns c of the jacobian. c c maxfev is a positive integer input variable. termination c occurs when the number of calls to fcn is at least c maxfev by the end of an iteration. c c epsfcn is an input variable used in determining a suitable c step length for the forward-difference approximation. this c approximation assumes that the relative errors in the c functions are of the order of epsfcn. if epsfcn is less c than the machine precision, it is assumed that the relative c errors in the functions are of the order of the machine c precision. c c diag is an array of length n. if mode = 1 (see c below), diag is internally set. if mode = 2, diag c must contain positive entries that serve as c multiplicative scale factors for the variables. c c mode is an integer input variable. if mode = 1, the c variables will be scaled internally. if mode = 2, c the scaling is specified by the input diag. other c values of mode are equivalent to mode = 1. c c factor is a positive input variable used in determining the c initial step bound. this bound is set to the product of c factor and the euclidean norm of diag*x if nonzero, or else c to factor itself. in most cases factor should lie in the c interval (.1,100.). 100. is a generally recommended value. c c nprint is an integer input variable that enables controlled c printing of iterates if it is positive. in this case, c fcn is called with iflag = 0 at the beginning of the first c iteration and every nprint iterations thereafter and c immediately prior to return, with x and fvec available c for printing. if nprint is not positive, no special calls c of fcn with iflag = 0 are made. c c info is an integer output variable. if the user has c terminated execution, info is set to the (negative) c value of iflag. see description of fcn. otherwise, c info is set as follows. c c info = 0 improper input parameters. c c info = 1 both actual and predicted relative reductions c in the sum of squares are at most ftol. c c info = 2 relative error between two consecutive iterates c is at most xtol. c c info = 3 conditions for info = 1 and info = 2 both hold. c c info = 4 the cosine of the angle between fvec and any c column of the jacobian is at most gtol in c absolute value. c c info = 5 number of calls to fcn has reached or c exceeded maxfev. c c info = 6 ftol is too small. no further reduction in c the sum of squares is possible. c c info = 7 xtol is too small. no further improvement in c the approximate solution x is possible. c c info = 8 gtol is too small. fvec is orthogonal to the c columns of the jacobian to machine precision. c c nfev is an integer output variable set to the number of c calls to fcn. c c fjac is an output m by n array. the upper n by n submatrix c of fjac contains an upper triangular matrix r with c diagonal elements of nonincreasing magnitude such that c c t t t c p *(jac *jac)*p = r *r, c c where p is a permutation matrix and jac is the final c calculated jacobian. column j of p is column ipvt(j) c (see below) of the identity matrix. the lower trapezoidal c part of fjac contains information generated during c the computation of r. c c ldfjac is a positive integer input variable not less than m c which specifies the leading dimension of the array fjac. c c ipvt is an integer output array of length n. ipvt c defines a permutation matrix p such that jac*p = q*r, c where jac is the final calculated jacobian, q is c orthogonal (not stored), and r is upper triangular c with diagonal elements of nonincreasing magnitude. c column j of p is column ipvt(j) of the identity matrix. c c qtf is an output array of length n which contains c the first n elements of the vector (q transpose)*fvec. c c wa1, wa2, and wa3 are work arrays of length n. c c wa4 is a work array of length m. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... dpmpar,enorm,fdjac2,lmpar,qrfac c c fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i,iter,j,l; // double actred,delta,dirder,fnorm,fnorm1,gnorm, // one,pnorm,prered,p1,p5,p25,p75,p0001,ratio, // sum,temp,temp1,temp2,xnorm,zero; double actred,delta,dirder,fnorm,fnorm1,gnorm, pnorm,prered,ratio, sum,temp,temp1,temp2,xnorm; double par[] = new double[2]; boolean doneout,donein; int iflag[] = new int[2]; double wa1[] = new double[n+1]; double wa2[] = new double[n+1]; double wa3[] = new double[n+1]; double wa4[] = new double[m+1]; // The Java compiler complaines if delta and xnorm have not been // initialized. delta = 0.0; xnorm = 0.0; // one = 1.0; // p1 = .1; // p25 = .25; // p5 = .5; // p75 = .75; // p0001 = .0001; // zero = 0.0; info[1] = 0; iflag[1] = 0; nfev[1] = 0; // Check the input parameters for errors. if (n <= 0 || m < n || ftol < zero || xtol < zero || gtol < zero || maxfev <= 0 || factor <= zero) { // Termination if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } if (mode == 2) { for (j = 1; j <= n; j++) { if (diag[j] <= zero) { // Termination if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } } } // Evaluate the function at the starting point // and calculate its norm. iflag[1] = 1; nlls.fcn(m,n,x,fvec,iflag); nfev[1] = 1; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } fnorm = Minpack_f77.enorm_f77(m,fvec); // Initialize Levenberg-Marquardt parameter and iteration counter. par[1] = zero; iter = 1; // Beginning of the outer loop. doneout = false; while (!doneout) { // Calculate the Jacobian matrix. iflag[1] = 2; Minpack_f77.fdjac2_f77(nlls,m,n,x,fvec,fjac,iflag,epsfcn,wa4); nfev[1] += n; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } // If requested, call fcn to enable printing of iterates. if (nprint > 0) { iflag[1] = 0; if ((iter-1)%nprint == 0) { nlls.fcn(m,n,x,fvec,iflag); } if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; nlls.fcn(m,n,x,fvec,iflag); return; } } // Compute the qr factorization of the Jacobian. Minpack_f77.qrfac_f77(m,n,fjac,true,ipvt,wa1,wa2,wa3); // On the first iteration and if mode is 1, scale according // to the norms of the columns of the initial Jacobian. if (iter == 1) { if (mode != 2) { for (j = 1; j <= n; j++) { diag[j] = wa2[j]; if (wa2[j] == zero) diag[j] = one; } } // On the first iteration, calculate the norm of the scaled x // and initialize the step bound delta. for (j = 1; j <= n; j++) { wa3[j] = diag[j]*x[j]; } xnorm = Minpack_f77.enorm_f77(n,wa3); delta = factor*xnorm; if (delta == zero) delta = factor; } // Form (q transpose)*fvec and store the first n components in // qtf. for (i = 1; i <= m; i++) wa4[i] = fvec[i]; for (j = 1; j <= n; j++) { if (fjac[j][j] != zero) { sum = zero; for (i = j; i <= m; i++) sum += fjac[i][j]*wa4[i]; temp = -sum/fjac[j][j]; for (i = j; i <= m; i++) wa4[i] += fjac[i][j]*temp; } fjac[j][j] = wa1[j]; qtf[j] = wa4[j]; } // Compute the norm of the scaled gradient. gnorm = zero; if (fnorm != zero) { for (j = 1; j <= n; j++) { l = ipvt[j]; if (wa2[l] != zero) { sum = zero; for (i = 1; i <= j; i++) sum += fjac[i][j]*(qtf[i]/fnorm); gnorm = Math.max(gnorm,Math.abs(sum/wa2[l])); } } } // Test for convergence of the gradient norm. if (gnorm <= gtol) info[1] = 4; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } // Rescale if necessary. if (mode != 2) { for (j = 1; j <= n; j++) { diag[j] = Math.max(diag[j],wa2[j]); } } // Beginning of the inner loop. donein = false; while (!donein) { // Determine the Levenberg-Marquardt parameter. Minpack_f77.lmpar_f77(n,fjac,ipvt,diag,qtf,delta,par,wa1,wa2, wa3,wa4); // Store the direction p and x + p. Calculate the norm of p. for (j = 1; j <= n; j++) { wa1[j] = -wa1[j]; wa2[j] = x[j] + wa1[j]; wa3[j] = diag[j]*wa1[j]; } pnorm = Minpack_f77.enorm_f77(n,wa3); // On the first iteration, adjust the initial step bound. if (iter == 1) delta = Math.min(delta,pnorm); // Evaluate the function at x + p and calculate its norm. iflag[1] = 1; nlls.fcn(m,n,wa2,wa4,iflag); nfev[1]++; if (iflag[1] < 0) { // Termination info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } fnorm1 = Minpack_f77.enorm_f77(m,wa4); // Compute the scaled actual reduction. actred = -one; if (p1*fnorm1 < fnorm) actred = one - (fnorm1/fnorm)*(fnorm1/fnorm); // Compute the scaled predicted reduction and // the scaled directional derivative. for (j = 1; j <= n; j++) { wa3[j] = zero; l = ipvt[j]; temp = wa1[l]; for (i = 1; i <= j; i++) wa3[i] += fjac[i][j]*temp; } temp1 = Minpack_f77.enorm_f77(n,wa3)/fnorm; temp2 = (Math.sqrt(par[1])*pnorm)/fnorm; prered = temp1*temp1 + temp2*temp2/p5; dirder = -(temp1*temp1 + temp2*temp2); // Compute the ratio of the actual to the predicted // reduction. ratio = zero; if (prered != zero) ratio = actred/prered; // Update the step bound. if (ratio <= p25) { if (actred >= zero) { temp = p5; } else { temp = p5*dirder/(dirder + p5*actred); } if (p1*fnorm1 >= fnorm || temp < p1) temp = p1; delta = temp*Math.min(delta,pnorm/p1); par[1] /= temp; } else { if (par[1] == zero || ratio >= p75) { delta = pnorm/p5; par[1] *= p5; } } // Test for successful iteration. if (ratio >= p0001) { // Successful iteration. Update x, fvec, and their norms. for (j = 1; j <= n; j++) { x[j] = wa2[j]; wa2[j] = diag[j]*x[j]; } for (i = 1; i <= m; i++) fvec[i] = wa4[i]; xnorm = Minpack_f77.enorm_f77(n,wa2); fnorm = fnorm1; iter++; } // Tests for convergence. if (Math.abs(actred) <= ftol && prered <= ftol && p5*ratio <= one) info[1] = 1; if (delta <= xtol*xnorm) info[1] = 2; if (Math.abs(actred) <= ftol && prered <= ftol && p5*ratio <= one && info[1] == 2) info[1] = 3; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } // Tests for termination and stringent tolerances. if (nfev[1] >= maxfev) info[1] = 5; if (Math.abs(actred) <= epsmch && prered <= epsmch && p5*ratio <= one) info[1] = 6; if (delta <= epsmch*xnorm) info[1] = 7; if (gnorm <= epsmch) info[1] = 8; if (info[1] != 0) { // Termination if (iflag[1] < 0) info[1] = iflag[1]; iflag[1] = 0; if (nprint > 0) { nlls.fcn(m,n,x,fvec,iflag); } return; } // End of the inner loop. Repeat if iteration unsuccessful. if (ratio >= p0001) donein = true; } // End of the outer loop. } } /** * *<p> *The fdjac2 method computes a forward-difference approximation *to the m by n Jacobian matrix associated with a specified *problem of m functions in n variables. *<p> *Translated by Steve Verrill on November 24, 2000 *from the FORTRAN MINPACK source produced by Garbow, Hillstrom, and More.<p> * * *@param nlls A class that implements the Lmdif_fcn interface * (see the definition in Lmdif_fcn.java). See * LmdifTest_f77.java for an example of such a class. * The class must define a method, fcn, that must * have the form * * public static void fcn(int m, int n, double x[], * double fvec[], int iflag[]) * * The value of iflag[1] should not be changed by fcn unless * the user wants to terminate execution of fdjac2_f77. * In this case iflag[1] should be set to a negative integer. *@param m A positive integer set to the number of functions * [number of observations] *@param n A positive integer set to the number of variables * [number of parameters]. n must not exceed m. *@param x An input array. *@param fvec An input array that contains the functions * evaluated at x. *@param fjac An output m by n array that contains the * approximation to the Jacobian matrix evaluated at x. *@param iflag An integer variable that can be used to terminate * the execution of fdjac2. See the description of nlls. *@param epsfcn An input variable used in determining a suitable * step length for the forward-difference approximation. This * approximation assumes that the relative errors in the * functions are of the order of epsfcn. If epsfcn is less * than the machine precision, it is assumed that the relative * errors in the functions are of the order of the machine * precision. *@param wa A work array. * */ public static void fdjac2_f77(Lmdif_fcn nlls, int m, int n, double x[], double fvec[], double fjac[][], int iflag[], double epsfcn, double wa[]) { /* Here is a copy of the fdjac2 FORTRAN documentation: subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) integer m,n,ldfjac,iflag double precision epsfcn double precision x(n),fvec(m),fjac(ldfjac,n),wa(m) c ********** c c subroutine fdjac2 c c this subroutine computes a forward-difference approximation c to the m by n jacobian matrix associated with a specified c problem of m functions in n variables. c c the subroutine statement is c c subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) c c where c c fcn is the name of the user-supplied subroutine which c calculates the functions. fcn must be declared c in an external statement in the user calling c program, and should be written as follows. c c subroutine fcn(m,n,x,fvec,iflag) c integer m,n,iflag c double precision x(n),fvec(m) c ---------- c calculate the functions at x and c return this vector in fvec. c ---------- c return c end c c the value of iflag should not be changed by fcn unless c the user wants to terminate execution of fdjac2. c in this case set iflag to a negative integer. c c m is a positive integer input variable set to the number c of functions. c c n is a positive integer input variable set to the number c of variables. n must not exceed m. c c x is an input array of length n. c c fvec is an input array of length m which must contain the c functions evaluated at x. c c fjac is an output m by n array which contains the c approximation to the jacobian matrix evaluated at x. c c ldfjac is a positive integer input variable not less than m c which specifies the leading dimension of the array fjac. c c iflag is an integer variable which can be used to terminate c the execution of fdjac2. see description of fcn. c c epsfcn is an input variable used in determining a suitable c step length for the forward-difference approximation. this c approximation assumes that the relative errors in the c functions are of the order of epsfcn. if epsfcn is less c than the machine precision, it is assumed that the relative c errors in the functions are of the order of the machine c precision. c c wa is a work array of length m. c c subprograms called c c user-supplied ...... fcn c c minpack-supplied ... dpmpar c c fortran-supplied ... dabs,dmax1,dsqrt c c argonne national laboratory. minpack project. march 1980. c burton s. garbow, kenneth e. hillstrom, jorge j. more c c ********** */ int i,j; // double eps,h,temp,zero; double eps,h,temp; // zero = 0.0; eps = Math.sqrt(Math.max(epsfcn,epsmch)); for (j = 1; j <= n; j++) { temp = x[j]; h = eps*Math.abs(temp); if (h == zero) h = eps; x[j] = temp + h; nlls.fcn(m,n,x,wa,iflag); if (iflag[1] < 0) { return; } x[j] = temp; for (i = 1; i <= m; i++) { fjac[i][j] = (wa[i] - fvec[i])/h; } } return; } }
Java
UTF-8
863
3.390625
3
[]
no_license
import java.util.List; import java.util.ArrayList; import java.util.Collections; class Puzzle5{ public static void main(String[] args){ String[] input = Reader.read("input5"); List<Integer> list = new ArrayList<Integer>(); for(String seat : input){ seat = seat.replace("B", "1").replace("F", "0").replace("R", "1").replace("L", "0"); int row = Integer.parseInt(seat.substring(0, 7), 2); int column = Integer.parseInt(seat.substring(7, 10), 2); int id = row*8 + column; list.add(id); } Collections.sort(list); System.out.println("The highest seat ID: " + list.get(list.size() - 1)); for(int i=0; i<list.size()-1; i++){ int a = list.get(i); int b = list.get(i+1); if((b-a) == 2){ System.out.println("The missing seat ID is between " + a + " and " + b + " = " + (a+1)); break; } } } }
PHP
UTF-8
3,091
2.921875
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use App\Exceptions\Area\AllAreaException; use App\Exceptions\Area\CreateAreaException; use App\Exceptions\Area\UpdateAreaException; use App\Exceptions\Area\DeleteAreaException; use App\Models\Area; abstract class AreaRepository implements RepositoryInterface { private $model; public function __construct(Area $area) { $this->model = $area; } public function create(array $data) { try { $area = $this->model->create($data); return [ 'area' => $this->find($area->id) ]; } catch (\Exception $exception) { return $exception->getMessage(); } } public function delete($id) { try { if(!$temp = $this->model->find($id)) { return [ 'success' => false, 'message' => 'Could`nt find area', ]; } $this->model->destroy($id); return [ 'success' => true, 'message' => 'Deleted successfully', 'deletedArea' => $temp, ]; } catch (\Exception $exception) { throw new DeleteAreaException($exception->getMessage()); } } public function update(array $data, $id) { try { if(!$temp = $this->model->find($id)) { return [ 'success' => false, 'message' => 'Could`nt find area', ]; } $temp->update($data); $temp->save(); return [ 'success' => true, 'message' => 'Updated successfully!', 'updated_area' => $this->find($temp->id), ]; } catch (\Exception $exception) { throw new UpdateAreaException($exception->getMessage()); } } public function find($id) { try { $area = $this->model::with('markets.customers', 'vendors')->find($id); if(!$area) { return [ 'success' => false, 'message' => 'Could`nt find area', ]; } return [ 'success' => true, 'area' => $area, ]; } catch (\Exception $exception) { } } public function all() { try { return $this->model::with('markets.customers', 'vendors')->get(); } catch (\Exception $exception) { throw new AllAreaException($exception->getMessage()); } } public function paginate($pagination) { try { return $this->model::orderBy('created_at', 'DESC')->paginate($pagination); } catch (\Exception $exception) { throw new AllAreaException($exception->getMessage()); } } }
Java
ISO-8859-1
8,963
2.640625
3
[]
no_license
package database.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import database.ChinookDatabase; import model.Genre; import model.MediaType; import model.Song; public class SongDao { private ChinookDatabase db = new ChinookDatabase(); public Song getSong(long songId) { Connection conn = db.connect(); PreparedStatement getSong = null; ResultSet results = null; try { getSong = conn.prepareStatement("SELECT TrackId, Name, MediaTypeId, GenreId, Milliseconds, UnitPrice, AlbumId FROM Track WHERE TrackId = ?"); getSong.setLong(1, songId); results = getSong.executeQuery(); if(results.next()){ String name = results.getString("Name"), unitPrice = results.getString("UnitPrice"); Genre genre = getGenre(results.getLong("GenreId")); MediaType mediaType = getMediaType(results.getLong("MediaTypeId")); long trackId = results.getLong("TrackId"), songLength = results.getLong("Milliseconds"), albumId = results.getLong("AlbumId"); Song a = new Song(trackId, name, genre, mediaType, songLength, unitPrice); a.setAlbumId(albumId); return a; } else { return null; } } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(results, getSong, conn); } } public List<Genre> getGenres() { Connection conn = db.connect(); PreparedStatement getGenres = null; ResultSet results = null; List<Genre> genres = new ArrayList<Genre>(); try { getGenres = conn.prepareStatement("SELECT * FROM Genre"); results = getGenres.executeQuery(); while(results.next()) { Genre genre = new Genre(results.getLong("GenreId"), results.getString("Name")); genres.add(genre); } } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(results, getGenres, conn); } return genres; } public List<MediaType> getMediaTypes() { Connection conn = db.connect(); PreparedStatement getMediaTypes = null; ResultSet results = null; List<MediaType> types = new ArrayList<MediaType>(); try { getMediaTypes = conn.prepareStatement("SELECT * FROM MediaType"); results = getMediaTypes.executeQuery(); while(results.next()) { MediaType type = new MediaType(results.getLong("MediaTypeId"), results.getString("Name")); types.add(type); } } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(results, getMediaTypes, conn); } return types; } public long createSong(long albumId, String name, long genreId, long mediaTypeId, long milliSeconds, String unitPrice) { Connection conn = db.connect(); PreparedStatement createSong = null; ResultSet keys = null; try { createSong = conn.prepareStatement("INSERT INTO Track (AlbumId, Name, GenreId, MediaTypeId, Milliseconds, UnitPrice) VALUES (?, ?, ?, ?, ?, ?)"); createSong.setLong(1, albumId); createSong.setString(2, name); createSong.setLong(3, genreId); createSong.setLong(4, mediaTypeId); createSong.setLong(5, milliSeconds); createSong.setString(6, unitPrice); createSong.executeUpdate(); keys = createSong.getGeneratedKeys(); keys.next(); return keys.getInt(1); } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(keys, createSong, conn); } } // Tajusin liian myhn, ett tss olisi voinut hydynt stmt.setObject public long modifySong(long songId, String name, long genreId, long mediaTypeId, long seconds, String unitPrice) { Connection conn = db.connect(); PreparedStatement modifySong = null; ResultSet keys = null; // Get current song Song song = getSong(songId); // Update only if changed data is different String sql = "UPDATE Track SET"; Map<String, List<String>> parameters = new HashMap<>(); if(!song.getName().equals(name)) { List<String> a = new ArrayList<>(); a.add("Name"); a.add(name); parameters.put("String", a); } if(song.getGenre().getId() != genreId) { List<String> a = new ArrayList<>(); a.add("GenreId"); a.add(Long.toString(genreId)); parameters.put("Long", a); } if(song.getMediaType().getId() != mediaTypeId) { List<String> a = new ArrayList<>(); a.add("MediaTypeId"); a.add(Long.toString(mediaTypeId)); parameters.put("Long", a); } if(song.getSongLengthInSeconds() != seconds) { String milliSeconds = Long.toString(song.secondsInMilliseconds(seconds)); List<String> a = new ArrayList<>(); a.add("MilliSeconds"); a.add(milliSeconds); parameters.put("Long", a); } if(!song.getUnitPrice().equals(unitPrice)) { List<String> a = new ArrayList<>(); a.add("UnitPrice"); a.add(unitPrice); parameters.put("String", a); } for (Map.Entry<String, List<String>> p : parameters.entrySet()) { sql = sql + " " + p.getValue().get(0) + " = ?,"; } if(sql.endsWith(",")){ sql = sql.substring(0, sql.length() - 1); } sql += " WHERE TrackId = ?"; // If no changes if(parameters.size() == 0) { System.out.println("No changes made"); return song.getAlbumId(); } try { modifySong = conn.prepareStatement(sql); int position = 1; for (Map.Entry<String, List<String>> p : parameters.entrySet()) { if(p.getKey().equals("String")) { modifySong.setString(position, p.getValue().get(1)); } else if (p.getKey().equals("Long")) { modifySong.setLong(position, Long.parseLong(p.getValue().get(1))); } position++; } modifySong.setLong(position, songId); modifySong.executeUpdate(); return song.getAlbumId(); } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(keys, modifySong, conn); } } public boolean removeSong(long songId) { Connection conn = db.connect(); PreparedStatement removeSong = null; ResultSet resultSet = null; try { removeSong = conn.prepareStatement("DELETE FROM Track WHERE TrackId = ?"); removeSong.setLong(1, songId); removeSong.executeUpdate(); return true; } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(resultSet, removeSong, conn); } } public Genre getGenre(long genreId) { Connection conn = db.connect(); PreparedStatement getGenre = null; ResultSet results = null; try { getGenre = conn.prepareStatement("SELECT Name FROM Genre WHERE GenreId = ?"); getGenre.setLong(1, genreId); results = getGenre.executeQuery(); if(results.next()) { return new Genre(genreId, results.getString("Name")); } else { return null; } } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(results, getGenre, conn); } } public MediaType getMediaType(long mediaTypeId) { Connection conn = db.connect(); PreparedStatement getMediaType = null; ResultSet results = null; try { getMediaType = conn.prepareStatement("SELECT Name FROM MediaType WHERE MediaTypeId = ?"); getMediaType.setLong(1, mediaTypeId); results = getMediaType.executeQuery(); if(results.next()) { return new MediaType(mediaTypeId, results.getString("Name")); } else { return null; } } catch (SQLException e) { throw new RuntimeException(e); } finally { db.close(results, getMediaType, conn); } } }
Java
UTF-8
2,463
2.328125
2
[]
no_license
package com.company.photocatch.DTO; import com.company.photocatch.domain.User; import java.util.List; public class TaskDTO { private Long id; private String taskname; private String product; private String description; private String address; private String taskstatus; private User user; private List<String> photonames; public TaskDTO(Long id, String taskname, String product, String description, String address, String taskstatus, User user, List<String> photonames) { this.id = id; this.taskname = taskname; this.product = product; this.description = description; this.address = address; this.taskstatus = taskstatus; this.user = user; this.photonames = photonames; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTaskname() { return taskname; } public void setTaskname(String taskname) { this.taskname = taskname; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTaskstatus() { return taskstatus; } public void setTaskstatus(String taskstatus) { this.taskstatus = taskstatus; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<String> getPhotonames() { return photonames; } public void setPhotonames(List<String> photonames) { this.photonames = photonames; } @Override public String toString() { return "TaskDTO{" + "id=" + id + ", taskname='" + taskname + '\'' + ", product='" + product + '\'' + ", description='" + description + '\'' + ", address='" + address + '\'' + ", taskstatus='" + taskstatus + '\'' + ", user=" + user + ", photonames=" + photonames + '}'; } }