If you use ggplot2
the preferred way of saving is to use ggsave
. First you have to plot, after creating the plot you call ggsave
:
ggplot(...)
ggsave("plot.png")
The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave
, notably width
, height
, and dpi
.
plot
has a plot.function
method
plot(eq, 1, 1000)
Or
curve(eq, 1, 1000)
I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList
.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList
1 Step - Install a required extension
sudo apt-get install libz-dev -y
2 Step - Install the PHP extension
pecl install zlib zip
3 Step - Restart your Apache
sudo /etc/init.d/apache2 restart
If does not work you can check if the zip.ini is called in your phpinfo, to check if the zip.so was included.
npm uninstall --save package_name
or npm uninstall --save-dev package_name
npm unlink package_name
then follow step 1note rnpm as is deprecated
JavaScript:
<script>
/* jquery.form.min.js */
(function(e){"use strict";if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(typeof jQuery!="undefined"?jQuery:window.Zepto)}})(function(e){"use strict";function r(t){var n=t.data;if(!t.isDefaultPrevented()){t.preventDefault();e(t.target).ajaxSubmit(n)}}function i(t){var n=t.target;var r=e(n);if(!r.is("[type=submit],[type=image]")){var i=r.closest("[type=submit]");if(i.length===0){return}n=i[0]}var s=this;s.clk=n;if(n.type=="image"){if(t.offsetX!==undefined){s.clk_x=t.offsetX;s.clk_y=t.offsetY}else if(typeof e.fn.offset=="function"){var o=r.offset();s.clk_x=t.pageX-o.left;s.clk_y=t.pageY-o.top}else{s.clk_x=t.pageX-n.offsetLeft;s.clk_y=t.pageY-n.offsetTop}}setTimeout(function(){s.clk=s.clk_x=s.clk_y=null},100)}function s(){if(!e.fn.ajaxSubmit.debug){return}var t="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log){window.console.log(t)}else if(window.opera&&window.opera.postError){window.opera.postError(t)}}var t={};t.fileapi=e("<input type='file'/>").get(0).files!==undefined;t.formdata=window.FormData!==undefined;var n=!!e.fn.prop;e.fn.attr2=function(){if(!n){return this.attr.apply(this,arguments)}var e=this.prop.apply(this,arguments);if(e&&e.jquery||typeof e==="string"){return e}return this.attr.apply(this,arguments)};e.fn.ajaxSubmit=function(r){function k(t){var n=e.param(t,r.traditional).split("&");var i=n.length;var s=[];var o,u;for(o=0;o<i;o++){n[o]=n[o].replace(/\+/g," ");u=n[o].split("=");s.push([decodeURIComponent(u[0]),decodeURIComponent(u[1])])}return s}function L(t){var n=new FormData;for(var s=0;s<t.length;s++){n.append(t[s].name,t[s].value)}if(r.extraData){var o=k(r.extraData);for(s=0;s<o.length;s++){if(o[s]){n.append(o[s][0],o[s][1])}}}r.data=null;var u=e.extend(true,{},e.ajaxSettings,r,{contentType:false,processData:false,cache:false,type:i||"POST"});if(r.uploadProgress){u.xhr=function(){var t=e.ajaxSettings.xhr();if(t.upload){t.upload.addEventListener("progress",function(e){var t=0;var n=e.loaded||e.position;var i=e.total;if(e.lengthComputable){t=Math.ceil(n/i*100)}r.uploadProgress(e,n,i,t)},false)}return t}}u.data=null;var a=u.beforeSend;u.beforeSend=function(e,t){if(r.formData){t.data=r.formData}else{t.data=n}if(a){a.call(this,e,t)}};return e.ajax(u)}function A(t){function T(e){var t=null;try{if(e.contentWindow){t=e.contentWindow.document}}catch(n){s("cannot get iframe.contentWindow document: "+n)}if(t){return t}try{t=e.contentDocument?e.contentDocument:e.document}catch(n){s("cannot get iframe.contentDocument: "+n);t=e.document}return t}function k(){function f(){try{var e=T(v).readyState;s("state = "+e);if(e&&e.toLowerCase()=="uninitialized"){setTimeout(f,50)}}catch(t){s("Server abort: ",t," (",t.name,")");_(x);if(w){clearTimeout(w)}w=undefined}}var t=a.attr2("target"),n=a.attr2("action"),r="multipart/form-data",u=a.attr("enctype")||a.attr("encoding")||r;o.setAttribute("target",p);if(!i||/post/i.test(i)){o.setAttribute("method","POST")}if(n!=l.url){o.setAttribute("action",l.url)}if(!l.skipEncodingOverride&&(!i||/post/i.test(i))){a.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(l.timeout){w=setTimeout(function(){b=true;_(S)},l.timeout)}var c=[];try{if(l.extraData){for(var h in l.extraData){if(l.extraData.hasOwnProperty(h)){if(e.isPlainObject(l.extraData[h])&&l.extraData[h].hasOwnProperty("name")&&l.extraData[h].hasOwnProperty("value")){c.push(e('<input type="hidden" name="'+l.extraData[h].name+'">').val(l.extraData[h].value).appendTo(o)[0])}else{c.push(e('<input type="hidden" name="'+h+'">').val(l.extraData[h]).appendTo(o)[0])}}}}if(!l.iframeTarget){d.appendTo("body")}if(v.attachEvent){v.attachEvent("onload",_)}else{v.addEventListener("load",_,false)}setTimeout(f,15);try{o.submit()}catch(m){var g=document.createElement("form").submit;g.apply(o)}}finally{o.setAttribute("action",n);o.setAttribute("enctype",u);if(t){o.setAttribute("target",t)}else{a.removeAttr("target")}e(c).remove()}}function _(t){if(m.aborted||M){return}A=T(v);if(!A){s("cannot access response document");t=x}if(t===S&&m){m.abort("timeout");E.reject(m,"timeout");return}else if(t==x&&m){m.abort("server abort");E.reject(m,"error","server abort");return}if(!A||A.location.href==l.iframeSrc){if(!b){return}}if(v.detachEvent){v.detachEvent("onload",_)}else{v.removeEventListener("load",_,false)}var n="success",r;try{if(b){throw"timeout"}var i=l.dataType=="xml"||A.XMLDocument||e.isXMLDoc(A);s("isXml="+i);if(!i&&window.opera&&(A.body===null||!A.body.innerHTML)){if(--O){s("requeing onLoad callback, DOM not available");setTimeout(_,250);return}}var o=A.body?A.body:A.documentElement;m.responseText=o?o.innerHTML:null;m.responseXML=A.XMLDocument?A.XMLDocument:A;if(i){l.dataType="xml"}m.getResponseHeader=function(e){var t={"content-type":l.dataType};return t[e.toLowerCase()]};if(o){m.status=Number(o.getAttribute("status"))||m.status;m.statusText=o.getAttribute("statusText")||m.statusText}var u=(l.dataType||"").toLowerCase();var a=/(json|script|text)/.test(u);if(a||l.textarea){var f=A.getElementsByTagName("textarea")[0];if(f){m.responseText=f.value;m.status=Number(f.getAttribute("status"))||m.status;m.statusText=f.getAttribute("statusText")||m.statusText}else if(a){var c=A.getElementsByTagName("pre")[0];var p=A.getElementsByTagName("body")[0];if(c){m.responseText=c.textContent?c.textContent:c.innerText}else if(p){m.responseText=p.textContent?p.textContent:p.innerText}}}else if(u=="xml"&&!m.responseXML&&m.responseText){m.responseXML=D(m.responseText)}try{L=H(m,u,l)}catch(g){n="parsererror";m.error=r=g||n}}catch(g){s("error caught: ",g);n="error";m.error=r=g||n}if(m.aborted){s("upload aborted");n=null}if(m.status){n=m.status>=200&&m.status<300||m.status===304?"success":"error"}if(n==="success"){if(l.success){l.success.call(l.context,L,"success",m)}E.resolve(m.responseText,"success",m);if(h){e.event.trigger("ajaxSuccess",[m,l])}}else if(n){if(r===undefined){r=m.statusText}if(l.error){l.error.call(l.context,m,n,r)}E.reject(m,"error",r);if(h){e.event.trigger("ajaxError",[m,l,r])}}if(h){e.event.trigger("ajaxComplete",[m,l])}if(h&&!--e.active){e.event.trigger("ajaxStop")}if(l.complete){l.complete.call(l.context,m,n)}M=true;if(l.timeout){clearTimeout(w)}setTimeout(function(){if(!l.iframeTarget){d.remove()}else{d.attr("src",l.iframeSrc)}m.responseXML=null},100)}var o=a[0],u,f,l,h,p,d,v,m,g,y,b,w;var E=e.Deferred();E.abort=function(e){m.abort(e)};if(t){for(f=0;f<c.length;f++){u=e(c[f]);if(n){u.prop("disabled",false)}else{u.removeAttr("disabled")}}}l=e.extend(true,{},e.ajaxSettings,r);l.context=l.context||l;p="jqFormIO"+(new Date).getTime();if(l.iframeTarget){d=e(l.iframeTarget);y=d.attr2("name");if(!y){d.attr2("name",p)}else{p=y}}else{d=e('<iframe name="'+p+'" src="'+l.iframeSrc+'" />');d.css({position:"absolute",top:"-1000px",left:"-1000px"})}v=d[0];m={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(t){var n=t==="timeout"?"timeout":"aborted";s("aborting upload... "+n);this.aborted=1;try{if(v.contentWindow.document.execCommand){v.contentWindow.document.execCommand("Stop")}}catch(r){}d.attr("src",l.iframeSrc);m.error=n;if(l.error){l.error.call(l.context,m,n,t)}if(h){e.event.trigger("ajaxError",[m,l,n])}if(l.complete){l.complete.call(l.context,m,n)}}};h=l.global;if(h&&0===e.active++){e.event.trigger("ajaxStart")}if(h){e.event.trigger("ajaxSend",[m,l])}if(l.beforeSend&&l.beforeSend.call(l.context,m,l)===false){if(l.global){e.active--}E.reject();return E}if(m.aborted){E.reject();return E}g=o.clk;if(g){y=g.name;if(y&&!g.disabled){l.extraData=l.extraData||{};l.extraData[y]=g.value;if(g.type=="image"){l.extraData[y+".x"]=o.clk_x;l.extraData[y+".y"]=o.clk_y}}}var S=1;var x=2;var N=e("meta[name=csrf-token]").attr("content");var C=e("meta[name=csrf-param]").attr("content");if(C&&N){l.extraData=l.extraData||{};l.extraData[C]=N}if(l.forceSync){k()}else{setTimeout(k,10)}var L,A,O=50,M;var D=e.parseXML||function(e,t){if(window.ActiveXObject){t=new ActiveXObject("Microsoft.XMLDOM");t.async="false";t.loadXML(e)}else{t=(new DOMParser).parseFromString(e,"text/xml")}return t&&t.documentElement&&t.documentElement.nodeName!="parsererror"?t:null};var P=e.parseJSON||function(e){return window["eval"]("("+e+")")};var H=function(t,n,r){var i=t.getResponseHeader("content-type")||"",s=n==="xml"||!n&&i.indexOf("xml")>=0,o=s?t.responseXML:t.responseText;if(s&&o.documentElement.nodeName==="parsererror"){if(e.error){e.error("parsererror")}}if(r&&r.dataFilter){o=r.dataFilter(o,n)}if(typeof o==="string"){if(n==="json"||!n&&i.indexOf("json")>=0){o=P(o)}else if(n==="script"||!n&&i.indexOf("javascript")>=0){e.globalEval(o)}}return o};return E}if(!this.length){s("ajaxSubmit: skipping submit process - no element selected");return this}var i,o,u,a=this;if(typeof r=="function"){r={success:r}}else if(r===undefined){r={}}i=r.type||this.attr2("method");o=r.url||this.attr2("action");u=typeof o==="string"?e.trim(o):"";u=u||window.location.href||"";if(u){u=(u.match(/^([^#]+)/)||[])[1]}r=e.extend(true,{url:u,success:e.ajaxSettings.success,type:i||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},r);var f={};this.trigger("form-pre-serialize",[this,r,f]);if(f.veto){s("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(r.beforeSerialize&&r.beforeSerialize(this,r)===false){s("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var l=r.traditional;if(l===undefined){l=e.ajaxSettings.traditional}var c=[];var h,p=this.formToArray(r.semantic,c);if(r.data){r.extraData=r.data;h=e.param(r.data,l)}if(r.beforeSubmit&&r.beforeSubmit(p,this,r)===false){s("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[p,this,r,f]);if(f.veto){s("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var d=e.param(p,l);if(h){d=d?d+"&"+h:h}if(r.type.toUpperCase()=="GET"){r.url+=(r.url.indexOf("?")>=0?"&":"?")+d;r.data=null}else{r.data=d}var v=[];if(r.resetForm){v.push(function(){a.resetForm()})}if(r.clearForm){v.push(function(){a.clearForm(r.includeHidden)})}if(!r.dataType&&r.target){var m=r.success||function(){};v.push(function(t){var n=r.replaceTarget?"replaceWith":"html";e(r.target)[n](t).each(m,arguments)})}else if(r.success){v.push(r.success)}r.success=function(e,t,n){var i=r.context||this;for(var s=0,o=v.length;s<o;s++){v[s].apply(i,[e,t,n||a,a])}};if(r.error){var g=r.error;r.error=function(e,t,n){var i=r.context||this;g.apply(i,[e,t,n,a])}}if(r.complete){var y=r.complete;r.complete=function(e,t){var n=r.context||this;y.apply(n,[e,t,a])}}var b=e("input[type=file]:enabled",this).filter(function(){return e(this).val()!==""});var w=b.length>0;var E="multipart/form-data";var S=a.attr("enctype")==E||a.attr("encoding")==E;var x=t.fileapi&&t.formdata;s("fileAPI :"+x);var T=(w||S)&&!x;var N;if(r.iframe!==false&&(r.iframe||T)){if(r.closeKeepAlive){e.get(r.closeKeepAlive,function(){N=A(p)})}else{N=A(p)}}else if((w||S)&&x){N=L(p)}else{N=e.ajax(r)}a.removeData("jqxhr").data("jqxhr",N);for(var C=0;C<c.length;C++){c[C]=null}this.trigger("form-submit-notify",[this,r]);return this};e.fn.ajaxForm=function(t){t=t||{};t.delegation=t.delegation&&e.isFunction(e.fn.on);if(!t.delegation&&this.length===0){var n={s:this.selector,c:this.context};if(!e.isReady&&n.s){s("DOM not ready, queuing ajaxForm");e(function(){e(n.s,n.c).ajaxForm(t)});return this}s("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)"));return this}if(t.delegation){e(document).off("submit.form-plugin",this.selector,r).off("click.form-plugin",this.selector,i).on("submit.form-plugin",this.selector,t,r).on("click.form-plugin",this.selector,t,i);return this}return this.ajaxFormUnbind().bind("submit.form-plugin",t,r).bind("click.form-plugin",t,i)};e.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};e.fn.formToArray=function(n,r){var i=[];if(this.length===0){return i}var s=this[0];var o=this.attr("id");var u=n?s.getElementsByTagName("*"):s.elements;var a;if(u&&!/MSIE [678]/.test(navigator.userAgent)){u=e(u).get()}if(o){a=e(':input[form="'+o+'"]').get();if(a.length){u=(u||[]).concat(a)}}if(!u||!u.length){return i}var f,l,c,h,p,d,v;for(f=0,d=u.length;f<d;f++){p=u[f];c=p.name;if(!c||p.disabled){continue}if(n&&s.clk&&p.type=="image"){if(s.clk==p){i.push({name:c,value:e(p).val(),type:p.type});i.push({name:c+".x",value:s.clk_x},{name:c+".y",value:s.clk_y})}continue}h=e.fieldValue(p,true);if(h&&h.constructor==Array){if(r){r.push(p)}for(l=0,v=h.length;l<v;l++){i.push({name:c,value:h[l]})}}else if(t.fileapi&&p.type=="file"){if(r){r.push(p)}var m=p.files;if(m.length){for(l=0;l<m.length;l++){i.push({name:c,value:m[l],type:p.type})}}else{i.push({name:c,value:"",type:p.type})}}else if(h!==null&&typeof h!="undefined"){if(r){r.push(p)}i.push({name:c,value:h,type:p.type,required:p.required})}}if(!n&&s.clk){var g=e(s.clk),y=g[0];c=y.name;if(c&&!y.disabled&&y.type=="image"){i.push({name:c,value:g.val()});i.push({name:c+".x",value:s.clk_x},{name:c+".y",value:s.clk_y})}}return i};e.fn.formSerialize=function(t){return e.param(this.formToArray(t))};e.fn.fieldSerialize=function(t){var n=[];this.each(function(){var r=this.name;if(!r){return}var i=e.fieldValue(this,t);if(i&&i.constructor==Array){for(var s=0,o=i.length;s<o;s++){n.push({name:r,value:i[s]})}}else if(i!==null&&typeof i!="undefined"){n.push({name:this.name,value:i})}});return e.param(n)};e.fn.fieldValue=function(t){for(var n=[],r=0,i=this.length;r<i;r++){var s=this[r];var o=e.fieldValue(s,t);if(o===null||typeof o=="undefined"||o.constructor==Array&&!o.length){continue}if(o.constructor==Array){e.merge(n,o)}else{n.push(o)}}return n};e.fieldValue=function(t,n){var r=t.name,i=t.type,s=t.tagName.toLowerCase();if(n===undefined){n=true}if(n&&(!r||t.disabled||i=="reset"||i=="button"||(i=="checkbox"||i=="radio")&&!t.checked||(i=="submit"||i=="image")&&t.form&&t.form.clk!=t||s=="select"&&t.selectedIndex==-1)){return null}if(s=="select"){var o=t.selectedIndex;if(o<0){return null}var u=[],a=t.options;var f=i=="select-one";var l=f?o+1:a.length;for(var c=f?o:0;c<l;c++){var h=a[c];if(h.selected){var p=h.value;if(!p){p=h.attributes&&h.attributes.value&&!h.attributes.value.specified?h.text:h.value}if(f){return p}u.push(p)}}return u}return e(t).val()};e.fn.clearForm=function(t){return this.each(function(){e("input,select,textarea",this).clearFields(t)})};e.fn.clearFields=e.fn.clearInputs=function(t){var n=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var r=this.type,i=this.tagName.toLowerCase();if(n.test(r)||i=="textarea"){this.value=""}else if(r=="checkbox"||r=="radio"){this.checked=false}else if(i=="select"){this.selectedIndex=-1}else if(r=="file"){if(/MSIE/.test(navigator.userAgent)){e(this).replaceWith(e(this).clone(true))}else{e(this).val("")}}else if(t){if(t===true&&/hidden/.test(r)||typeof t=="string"&&e(this).is(t)){this.value=""}}})};e.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||typeof this.reset=="object"&&!this.reset.nodeType){this.reset()}})};e.fn.enable=function(e){if(e===undefined){e=true}return this.each(function(){this.disabled=!e})};e.fn.selected=function(t){if(t===undefined){t=true}return this.each(function(){var n=this.type;if(n=="checkbox"||n=="radio"){this.checked=t}else if(this.tagName.toLowerCase()=="option"){var r=e(this).parent("select");if(t&&r[0]&&r[0].type=="select-one"){r.find("option").selected(false)}this.selected=t}})};e.fn.ajaxSubmit.debug=false})
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('change', '.wpcf7-file', function (e) {
e.preventDefault();
var myParent = $(this).parent();
var filname= $('input[type=file]').val()
if (filname) {
$(this).parent().find('#progress-div').show();
$('#myform').ajaxSubmit({
// target: '#progress-div123',/**********only for response************/
beforeSubmit: function () {
myParent.find('#progress-bar').width('0%');
},
uploadProgress: function (event, position, total, percentComplete) {
myParent.find('#progress-bar').width(percentComplete + '%');
myParent.find('#progress-bar').html('<div id="progress-status">' + percentComplete + ' %</div>')
},
success: function showResponse(responseText, statusText, xhr, $form) {
//myParent.find('#progress-div').hide(10000);
},
resetForm: false
});
}
return false;
});
/***********Error msg if file not valid***************/
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(pdf|txt|jpg|png|doc|docx|xlx|xls|xlsx|jpg|ppt|pptx|tif|tiff|\n\
bmp|pcd|gif|bmp|zip|rar|odt|avi|ogg|m4a|mov|mp3|mp4|mpg|wav|wmv|stp|sldprt|sldasm|iges|igs|stl|x_t|step\n\
|stp|prt|asm|idw|iam|ipt|dxf|dwg|pdf|slddrw|dwf)$");
if (!(regex.test(val))) {
$(this).val('');
alert('Please select correct file format');
}
});
/*********End*****************/
});
</script>
Styles:
<style>
body{width:610px;}
#uploadForm {border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;}
#uploadForm label {margin:2px; font-size:1em; font-weight:bold;}
.demoInputBox{padding:5px; border:#F0F0F0 1px solid; border-radius:4px; background-color:#FFF;}
#progress-bar {background-color: #12CC1A;height:20px;color: #FFFFFF;width:0%;-webkit-transition: width .3s;-moz-transition: width .3s;transition: width .3s;}
.btnSubmit{background-color:#09f;border:0;padding:10px 40px;color:#FFF;border:#F0F0F0 1px solid; border-radius:4px;}
#progress-div
{
border: 1px solid #0fa015;
border-radius: 4px;
margin: -35px 2px 7px 295px;
padding: 5px 0;
text-align: center;
width: 277px;
}
#targetLayer{width:100%;text-align:center;}
</style>
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]
I would like to share 2 tips: (tip 1) create a csv file (tip 2) Load rows from a csv file into a table.
====[ (tip 1) SQLPLUS to create a csv file form an Oracle table ]====
I use SQLPLUS with the following commands:
set markup csv on
set lines 1000
set pagesize 100000 linesize 1000
set feedback off
set trimspool on
spool /MyFolderAndFilename.csv
Select * from MYschema.MYTABLE where MyWhereConditions ;
spool off
exit
====[tip 2 SQLLDR to load a csv file into a table ]====
I use SQLLDR and a csv ( comma separated ) file to add (APPEND) rows form the csv file to a table. the file has , between fields text fields have " before and after the text CRITICAL: if last column is null there is a , at the end of the line
Example of data lines in the csv file:
11,"aa",1001
22,"bb',2002
33,"cc",
44,"dd",4004
55,"ee',
This is the control file:
LOAD DATA
APPEND
INTO TABLE MYSCHEMA.MYTABLE
fields terminated by ',' optionally enclosed by '"'
TRAILING NULLCOLS
(
CoulmnName1,
CoulmnName2,
CoulmnName3
)
This is the command to execute sqlldr in Linux. If you run in Windows use \ instead of / c:
sqlldr userid=MyOracleUser/MyOraclePassword@MyOracleServerIPaddress:port/MyOracleSIDorService DATA=datafile.csv CONTROL=controlfile.ctl LOG=logfile.log BAD=notloadedrows.bad
Good luck !
Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)
public static void main(String[] args) throws ParseException {
java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date;
date = (Date)formatter.parse(fecha.toString());
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" +
(cal.get(Calendar.MONTH) + 1) +
"/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
}
This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.
jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.
Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.
The documentation from MDN explains how return false
in an event handler works
What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.
For further reading, see attachEvent on MSDN and the W3C DOM 2 Events documentation.
And
has precedence over Or
, so, even if a <=> a1 Or a2
Where a And b
is not the same as
Where a1 Or a2 And b,
because that would be Executed as
Where a1 Or (a2 And b)
and what you want, to make them the same, is the following (using parentheses to override rules of precedence):
Where (a1 Or a2) And b
Here's an example to illustrate:
Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0
Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F
For those who like to consult references (in alphabetic order):
Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.
function cleanInt(x) {
x = Number(x);
return x >= 0 ? Math.floor(x) : Math.ceil(x);
}
See results of below test cases.
console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));
result:
CleanInt: NaN ParseInt: NaN
CleanInt: NaN ParseInt: 123
CleanInt: 234 ParseInt: 234
CleanInt: -679 ParseInt: -679
CleanInt: 897 ParseInt: 897
CleanInt: Infinity ParseInt: NaN
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
I was looking for this answer:
import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
with open(filename, 'r') as f:
text = f.read()
print (filename)
print (len(text))
you can choose as well '*.txt' or other ends of your filename
Check your id
. Is it Identity? If it is then make sure it is declared as ID not null Identity(1,1)
And before creating your table , Drop table
and then create table
.
Check the apache User and Group setting in the httpd.conf. It should default to apache on AMI/RedHat or www-data on Debian.
grep '^Group\|^User' /etc/httpd/conf/httpd.conf
Then add the apache user to the group setting of your site's root directory.
sudo usermod -a -G <your-site-root-dir-group> apache
Select select = new Select(_element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
if(selectedOptions.size() > 0){
return true;
}else{
return false;
}
I am not saying that this is the best solution or a preferred solution to the given problem. However, it may be useful to remember that functions can return structs. Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it. This works for fixed length arrays.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef
struct
{
char v[10];
} CHAR_ARRAY;
CHAR_ARRAY returnArray(CHAR_ARRAY array_in, int size)
{
CHAR_ARRAY returned;
/*
. . . methods to pull values from array, interpret them, and then create new array
*/
for (int i = 0; i < size; i++ )
returned.v[i] = array_in.v[i] + 1;
return returned; // Works!
}
int main(int argc, char * argv[])
{
CHAR_ARRAY array = {1,0,0,0,0,1,1};
char arrayCount = 7;
CHAR_ARRAY returnedArray = returnArray(array, arrayCount);
for (int i = 0; i < arrayCount; i++)
printf("%d, ", returnedArray.v[i]); //is this correctly formatted?
getchar();
return 0;
}
I invite comments on the strengths and weaknesses of this technique. I have not bothered to do so.
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.
If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):
static class MutableInt {
int value = 1;
void inc() { ++value; }
int get() { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt>();
MutableInt value = map.get(key);
if (value == null) {
value = new MutableInt();
map.put(key, value);
} else {
value.inc();
}
If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned GNU Trove.
By the way, a good search term for this subject is "histogram".
I'm not sure about more efficient in terms of big-O but certainly using the unshift
method is more concise:
var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]
[Edit]
This jsPerf benchmark shows that unshift
is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:
a.slice().unshift(0); // Use "slice" to avoid mutating "a".
[Edit 2]
For completeness, the following function can be used instead of OP's example prependArray(...)
to take advantage of the Array unshift(...)
method:
function prepend(value, array) {
var newArray = array.slice();
newArray.unshift(value);
return newArray;
}
var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];
You can use the output value from stat_summary()
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
There is flexibility in using lambda as parameter. It enables functional programming in java. The basic syntax is
param -> method_body
Following is a way, you can define a method taking functional interface (lambda is used) as parameter.
a. if you wish to define a method declared inside a functional interface,
say, the functional interface is given as an argument/parameter to a method called from main()
@FunctionalInterface
interface FInterface{
int callMeLambda(String temp);
}
class ConcreteClass{
void funcUsesAnonymousOrLambda(FInterface fi){
System.out.println("===Executing method arg instantiated with Lambda==="));
}
public static void main(){
// calls a method having FInterface as an argument.
funcUsesAnonymousOrLambda(new FInterface() {
int callMeLambda(String temp){ //define callMeLambda(){} here..
return 0;
}
}
}
/***********Can be replaced by Lambda below*********/
funcUsesAnonymousOrLambda( (x) -> {
return 0; //(1)
}
}
FInterface fi = (x) -> { return 0; };
funcUsesAnonymousOrLambda(fi);
Here above it can be seen, how a lambda expression can be replaced with an interface.
Above explains a particular usage of lambda expression, there are more. ref Java 8 lambda within a lambda can't modify variable from outer lambda
This is the main difference between use git reset --hard and git reset --soft:
--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.
There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.
This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.
var app = angular.module('myApp', ['ui.bootstrap']);
app.service('MainService', function(){
var vm = this;
});
app.controller('MainCtrl', function(MainService){
var vm = this;
vm.ms = MainService;
});
app.directive('customStyle', function(MainService){
return {
restrict : 'A',
link : function(scope, element, attr){
var style = angular.element('<style></style>');
element.append(style);
scope.$watch(function(){ return MainService.theme; },
function(){
var css = '';
angular.forEach(MainService.theme, function(selector, key){
angular.forEach(MainService.theme[key], function(val, k){
css += key + ' { '+k+' : '+val+'} ';
});
});
style.html(css);
}, true);
}
};
});
#grad
{
background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*Safari 5.1-6*/
background: -o-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Opera 11.1-12*/
background: -moz-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Fx 3.6-15*/
background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); /*Standard*/
}
I found this in w3schools and suited my needs while I was looking for gradient and transparency. I am providing the link to refer to w3schools. Hope this helps if any one is looking for gradient and transparency.
http://www.w3schools.com/css/css3_gradients.asp
Also I tried it in w3schools to change the opacity pasting the link for it check it
http://www.w3schools.com/css/tryit.asp?filename=trycss3_gradient-linear_trans
Hope it helps.
You're looking for the onblur
event. Look here, for more details.
This worked for me: (bootstrap 3.3.6; jquery=1.11.3)
<a id="alertTooltip" href="#" data-html="true" class="tooltip" data-toggle="tooltip" title="Tooltip message"></a>
<script>
$('#alertTooltip').attr('title', "Tooltip new <br /> message").tooltip('fixTitle');
</script>
The attribute data-html="true"
allow to use html on the tooltip title.
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:
Build Project and save log to Build.log
SET Build_Opt=/flp:summary;logfile=Build.log;append=true
msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%
search for "0 Error" string in build log, set the result to var
FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
SET var=%%F
)
echo %var%
get the last character, which indicates how many lines contains the search string
set result=%var:~-1%
echo "%result%"
if string not found, then error > 0, build failed
if "%result%"=="0" ( echo "build failed" )
That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
Give a different alias
SELECT Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate
You can also use the mouse middle button to paste in insert mode (Linux only).
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
If you look in the AuthenticatesUsers trait you will see that in the sendLoginResponse method that there is a call made to $this->redirectPath()
. If you look at this method then you will discover that the redirectTo can either be a method or a variable.
This is what I now have in my auth controller.
public function redirectTo() {
$user = Auth::user();
switch(true) {
case $user->isInstructor():
return '/instructor';
case $user->isAdmin():
case $user->isSuperAdmin():
return '/admin';
default:
return '/account';
}
}
Some gotchas to watch out for:
If you double-click the batch file %0
will be surrounded by quotes. For example, if you save this file as c:\test.bat
:
@echo %0
@pause
Double-clicking it will open a new command prompt with output:
"C:\test.bat"
But if you first open a command prompt and call it directly from that command prompt, %0
will refer to whatever you've typed. If you type test.bat
Enter, the output of %0
will have no quotes because you typed no quotes:
c:\>test.bat
test.bat
If you type test
Enter, the output of %0
will have no extension too, because you typed no extension:
c:\>test
test
Same for tEsT
Enter:
c:\>tEsT
tEsT
If you type "test"
Enter, the output of %0
will have quotes (since you typed them) but no extension:
c:\>"test"
"test"
Lastly, if you type "C:\test.bat"
, the output would be exactly as though you've double clicked it:
c:\>"C:\test.bat"
"C:\test.bat"
Note that these are not all the possible values %0
can be because you can call the script from other folders:
c:\some_folder>/../teST.bAt
/../teST.bAt
All the examples shown above will also affect %~0
, because the output of %~0
is simply the output of %0
minus quotes (if any).
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
One solution is to first encode data and then decode it in the same file:
$string =json_encode($input, JSON_UNESCAPED_UNICODE) ;
echo $decoded = html_entity_decode( $string );
The specific instructions for what you are looking for are in here: https://support.google.com/docs/answer/3093281
Remember your Google Spreadsheets Formulas might use semicolon (;) instead of comma (,) depending on Regional Settings.
Once made the replacement on some examples would look like this:
=GoogleFinance("CURRENCY:USDEUR")
=INDEX(GoogleFinance("USDEUR","price",today()-30,TODAY()),2,2)
=SPARKLINE(GoogleFinance("USDEUR","price",today()-30,today()))
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.
the gps signal does indeed include a precise time signal, which is available with any "fix".
however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.
note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?
docker build
commandThe basic syntax of docker's build command is
docker build -t imagename:imagetag context_dir
The context is a directory and determines what the docker build process is going to see: From the Dockerfile's point of view, any file context_dir/mydir/myfile
in your filesystem will become /mydir/myfile
in the Dockerfile and hence during the build process.
If the dockerfile is called Dockerfile
and lives in the context, it will be found implicitly by naming convention.
That's nice, because it means you can usually find the Dockerfile in any docker container immediately.
If you insist on using different name, say "/tmp/mydockerfile", you can use -f
like this:
docker build -t imagename:imagetag -f /tmp/mydockerfile context_dir
but then the dockerfile will not be in the same folder or at least will be harder to find.
This answer was provided on Microsoft's website, last updated on 3/21/2018:
In short, here are the screenshots from the walkthrough:
Hope this helps.
This approach avoids the warnings while preserving the array-oriented evaluation.
import numpy as np
def isnat(x):
"""
datetime64 analog to isnan.
doesn't yet exist in numpy - other ways give warnings
and are likely to change.
"""
return x.astype('i8') == np.datetime64('NaT').astype('i8')
A simple Kotlin example
Assuming these gradle deps match or are higher version in your project:
kotlin_version = '1.3.41'
nav_version_ktx = '2.0.0'
Adapt this to your fragment classes:
/**
* A simple [Fragment] subclass.
*
* Updates the action bar title when onResume() is called on the fragment,
* which is called every time you navigate to the fragment
*
*/
class MyFragment : Fragment() {
private lateinit var mainActivity: MainActivity
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//[...]
mainActivity = this.activity as MainActivity
//[...]
}
override fun onResume() {
super.onResume()
mainActivity.supportActionBar?.title = "My Fragment!"
}
}
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
You can use class loader which will read from classpath as ROOT path (without "/" in the beginning)
InputStream in = getClass().getClassLoader().getResourceAsStream("file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
For those browsers that do support "position: fixed" you can simply use javascript (jQuery) to change the position to "fixed" when scrolling. This eliminates the jumpiness when scrolling with the $(window).scroll(function()) solutions listed here.
Ben Nadel demonstrates this in his tutorial: Creating A Sometimes-Fixed-Position Element With jQuery
If you have some process listening on port 8080 then you can always configure tomcat to listen on a different port. To change the listener port by editing your server.xml
located under tomcat server conf
directory.
Search for Connector port="8080"
in server.xml and change the port number to some other port.
In my case, it was something else. One day earlier I tried to install Magento using bitnami of xampp. And I deleted That Module
I opened the httpd.conf and found this line:
Include "C:/xampp/apps/magento/conf/httpd-prefix.conf"
I just commented it with #,
Now it's running fine. :)
I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:
If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.
In Linux and Mac there are not default shortcuts, so try to set your custom shortcut and be careful about don't choose a hotkey used (For example, CTRL+U is taken for uncomment)
In my case I have CTRL+U CTRL+U for transform to uppercase and CTRL+L CTRL+L for transform to lowercase
Just in case, for Mac instead of CTRL I used ?
Use the built-in MSDB.DBO.AGENT_DATETIME(20150119,0)
https://blog.sqlauthority.com/2015/03/13/sql-server-interesting-function-agent_datetime/
or an ORACLE version:
delete
from table_name
where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy')
As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.
It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?
I will try to explain the results of all the commands you tried.
scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)
First of all, List
is a type alias to scala.collection.immutable.List
(defined in Predef.scala).
Using the List companion object is more straightforward way to instantiate a List
. Ex: List(1.0,5.5)
scala> l
res0: List[Double] = List(1.0, 5.5)
scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)
:::
returns a list resulting from the concatenation of the given list prefix and this list
The original List is NOT modified
scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)
List(l)
is a List[List[Double]]
Definitely not what you want.
:+
returns a new list consisting of all elements of this list followed by elem.
The type is List[Any]
because it is the common superclass between List[Double]
and Double
scala> l
res3: List[Double] = List(1.0, 5.5)
l is left unmodified because no method on immutable.List
modified the List.
we solve this problem without using regex this query replace only exact match string.
update employee set
employee_firstname =
trim(REPLACE(concat(" ",employee_firstname," "),' jay ',' abc '))
Example:
emp_id employee_firstname
1 jay
2 jay ajay
3 jay
After executing query result:
emp_id employee_firstname
1 abc
2 abc ajay
3 abc
Sometimes, if you've a saturated cluster (too many partitions, or using encrypted topic data, or using SSL, or the controller is on a bad node, or the connection is flaky, it'll take a long time to purge said topic.
I follow these steps, particularly if you're using Avro.
1: Run with kafka tools :
bash kafka-configs.sh --alter --entity-type topics --zookeeper zookeeper01.kafka.com --add-config retention.ms=1 --entity-name <topic-name>
2: Run on Schema registry node:
kafka-avro-console-consumer --consumer-property security.protocol=SSL --consumer-property ssl.truststore.location=/etc/schema-registry/secrets/trust.jks --consumer-property ssl.truststore.password=password --consumer-property ssl.keystore.location=/etc/schema-registry/secrets/identity.jks --consumer-property ssl.keystore.password=password --consumer-property ssl.key.password=password --bootstrap-server broker01.kafka.com:9092 --topic <topic-name> --new-consumer --from-beginning
3: Set topic retention back to the original setting, once topic is empty.
bash kafka-configs.sh --alter --entity-type topics --zookeeper zookeeper01.kafka.com --add-config retention.ms=604800000 --entity-name <topic-name>
Hope this helps someone, as it isn't easily advertised.
This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
<?php
function rand_line($fileName) {
do{
$fileSize=filesize($fileName);
$fp = fopen($fileName, 'r');
fseek($fp, rand(0, $fileSize));
$data = fread($fp, 4096); // assumes lines are < 4096 characters
fclose($fp);
$a = explode("\n",$data);
}while(count($a)<2);
return $a[1];
}
echo rand_line("file.txt"); // change file name
?>
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
To prevent JUnit from instantiating your test base class just make it
public abstract class MyTestBaseClass { ... whatever... }
(@Ignore reports it as ignored which I reserve for temporarily ignored tests.)
For my needs I define static
array, instead of impossible const
and it works:
public static string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
If you need
inspect
on the objects in the Hash
inspect
method in your objects like you're supposed to... then this works great! (And gets better, the bigger and more nested your Hash object is.)
logger.error my_hash.pretty_inspect
For example:
class MyObject1
def inspect
"<#{'*' * 10} My Object 1 #{'*' * 10}>"
end
end
class MyObject2
def inspect
"<#{'*' * 10} My Object 2 #{'*' * 10}>"
end
end
my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }
Rails.logger.error my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}
# EW! ^
Rails.logger.error my_hash.pretty_inspect
# {:a=>1,
# :b=><********** My Object 1 **********>,
# <********** My Object 2 **********>=>3}
pretty_inspect
comes from PrettyPrint, which rails includes by default. So, no gems needed and no conversion to JSON needed.
If you're not in Rails or if the above fails for some reason, try using require "pp"
first. For example:
require "pp" # <-----------
class MyObject1
def inspect
"<#{'*' * 10} My Object 1 #{'*' * 10}>"
end
end
class MyObject2
def inspect
"<#{'*' * 10} My Object 2 #{'*' * 10}>"
end
end
my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }
puts my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}
# EW! ^
puts my_hash.pretty_inspect
# {:a=>1,
# :b=><********** My Object 1 **********>,
# <********** My Object 2 **********>=>3}
Big ol' pretty_inspect
ed Hash example from my project with project-specific text from my inspected objects redacted:
{<***::******************[**:****, ************************:****]********* * ****** ******************** **** :: *********** - *** ******* *********>=>
{:errors=>
["************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"************ ************ ********** ***** ****** ******** is invalid",
"************ ************ ********** is invalid",
"************ ************ is invalid",
"************ is invalid"],
:************=>
[{<***::**********[**:****, *************:**, ******************:*, ***********************:****] :: **** **** ****>=>
{:************=>
[{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ******* ***** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ********* - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ********** - ********** *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ******** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: **** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ********** ***** - *>=>
{}}]}},
{<***::**********[**:****, *************:**, ******************:*, ***********************:****] ******************** :: *** - *****>=>
{:errors=>
["************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"************ ********** ***** ****** ******** is invalid",
"************ ********** is invalid",
"************ is invalid"],
:************=>
[{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]*********** :: ****>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{:errors=>
["********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"********** ***** ****** ******** is invalid",
"********** is invalid"],
:**********************=>
[{<***::*******************[**:******, ************************:***]****-************ ******************** ***: * :: *** - ***** * ****** ** - ******* * **: *******>=>
{:errors=>
["***** ****** ******** **** ********** **** ***** ***** ******* ******",
"***** ****** ******** **** ********** is invalid"],
:***************=>
[{<***::********************************[**:******, *************:******, ***********:******, ***********:"************ ************"]** * *** * ****-******* * ******** * ********* ******************** *********************: ***** :: "**** *" -> "">=>
{:errors=>["**** ***** ***** ******* ******"],
:**********=>
{<***::*****************[**:******, ****************:["****** ***", "****** ***", "****** ****", "******* ***", "******* ****", "******* ***", "****"], **:""] :: "**** *" -> "">=>
{:errors=>
["***** ******* ******",
"***** ******* ******"]}}}}]}}]}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}}]}}]}}
You need install Queuelib
either via the Python Package Index (PyPI)
or from source.
To install using pip:-
$ pip install queuelib
To install using easy_install:-
$ easy_install queuelib
If you have downloaded a source tarball you can install it by running the following (as root):-
python setup.py install
You can use array slicing:
Entry.objects.all()[:1].get()
Which can be used with .filter()
:
Entry.objects.filter()[:1].get()
You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by()
to ensure you get the first you want.
Be sure to add the .get()
or else you will get a QuerySet back and not an object.
You Could try this
"Some Special Text Values".gsub(/[[:space:]]+/, "")
using :space: removes non breaking space along with regular space.
You want to use the stringizing operator:
#define STRING(s) #s
int main()
{
const char * cstr = STRING(abc); //cstr == "abc"
}
function formatDate(jsDate){
// add leading zeroes to jsDate when days or months are < 10..
// i.e.
// formatDate(new Date("1/3/2013"));
// returns
// "01/03/2103"
////////////////////
return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" +
((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" +
jsDate.getFullYear();
}
I have a solution.
I updated the file android_winusb.inf to reflect the VID and PID of the Nexus-5. Now it loads the generic driver and supports ADB in Eclipse.
Note, after any previous attempts you may have made, go to Device Manager and update the driver for the "Nexus 5" (showing with a yellow exclamation mark).
You have to navigate over to the USB driver directory, which on my machine was: C:\Users\Xxxxxxxxx\android-sdk\extras\google\usa_driver
In that directory, edit file android_winusb.inf in both the x86 and amd64 sections and insert one line:
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE1&MI_01
This was enough for me to get this to work.
Here is the content of my file:
;
; Android WinUsb driver installation.
;
;
;
; Includes FIX for the Nexus-5 ADB,
; --- jonovos ---
; --- petuniaPlatypus ---
; --- 2013-11-07 ---
;
; By snooping on the USB for the Nexus-5,
; it is known that the VID = 18D1 and PID = 4EE1.
; With this, we insert them into the GENERIC sections bwlow.
;
;
[Version]
Signature = "$Windows NT$"
Class = AndroidUsbDeviceClass
ClassGuid = {3F966BD9-FA04-4ec5-991C-D326973B5128}
Provider = %ProviderName%
DriverVer = 07/09/2013,8.0.0000.00000
CatalogFile.NTx86 = androidwinusb86.cat
CatalogFile.NTamd64 = androidwinusba64.cat
[ClassInstall32]
Addreg = AndroidWinUsbClassReg
[AndroidWinUsbClassReg]
HKR,,,0,%ClassName%
HKR,,Icon,,-1
[Manufacturer]
%ProviderName% = Google, NTx86, NTamd64
[Google.NTx86]
;Google Nexus One
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_0D02
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_0D02&MI_01
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E11
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E12&MI_01
;Google Nexus S
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E21
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E22&MI_01
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E23
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E24&MI_01
;Google Nexus 7
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4E40
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E42&MI_01
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E44&MI_01
;Google Nexus Q
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_2C10
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_2C11
;Google Nexus (generic)
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4EE0
;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-new-line-added:
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE1&MI_01
;;;;;;;;
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE2&MI_01
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE4&MI_02
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE6&MI_01
[Google.NTamd64]
;Google Nexus One
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_0D02
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_0D02&MI_01
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E11
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E12&MI_01
;Google Nexus S
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E21
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E22&MI_01
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_4E23
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E24&MI_01
;Google Nexus 7
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4E40
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E42&MI_01
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E44&MI_01
;Google Nexus Q
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_2C10
%SingleAdbInterface% = USB_Install, USB\VID_18D1&PID_2C11
;Google Nexus (generic)
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4EE0
;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-new-line-added:
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE1&MI_01
;;;;;;;;
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE2&MI_01
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE4&MI_02
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE6&MI_01
[USB_Install]
Include = winusb.inf
Needs = WINUSB.NT
[USB_Install.Services]
Include = winusb.inf
AddService = WinUSB,0x00000002,WinUSB_ServiceInstall
[WinUSB_ServiceInstall]
DisplayName = %WinUSB_SvcDesc%
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %12%\WinUSB.sys
[USB_Install.Wdf]
KmdfService = WINUSB, WinUSB_Install
[WinUSB_Install]
KmdfLibraryVersion = 1.9
[USB_Install.HW]
AddReg = Dev_AddReg
[Dev_AddReg]
HKR,,DeviceInterfaceGUIDs,0x10000,"{F72FE0D4-CBCB-407d-8814-9ED673D0DD6B}"
[USB_Install.CoInstallers]
AddReg = CoInstallers_AddReg
CopyFiles = CoInstallers_CopyFiles
[CoInstallers_AddReg]
HKR,,CoInstallers32,0x00010000,"WdfCoInstaller01009.dll,WdfCoInstaller","WinUSBCoInstaller2.dll"
[CoInstallers_CopyFiles]
WinUSBCoInstaller2.dll
WdfCoInstaller01009.dll
[DestinationDirs]
CoInstallers_CopyFiles=11
[SourceDisksNames]
1 = %DISK_NAME%,,,\i386
2 = %DISK_NAME%,,,\amd64
[SourceDisksFiles.x86]
WinUSBCoInstaller2.dll = 1
WdfCoInstaller01009.dll = 1
[SourceDisksFiles.amd64]
WinUSBCoInstaller2.dll = 2
WdfCoInstaller01009.dll = 2
[Strings]
ProviderName = "Google, Inc."
SingleAdbInterface = "Android ADB Interface"
CompositeAdbInterface = "Android Composite ADB Interface"
SingleBootLoaderInterface = "Android Bootloader Interface"
WinUSB_SvcDesc = "Android USB Driver"
DISK_NAME = "Android WinUsb installation disk"
ClassName = "Android Device"
Side note: if you want to get the sum of all digits, you can simply do
print sum(int(digit) for digit in raw_input('Enter a number:'))
As mentioned in other answers, by default div
will be rendered as a block element, while span
will be rendered inline within its context. But neither has any semantic value; they exist to allow you to apply styling and an identity to any given bit of content. Using styles, you can make a div
act like a span
and vice-versa.
One of the useful styles for div
is inline-block
Examples:
I have used inline-block
to a great success, in game web projects.
You just need to find out where is your PHP folder.
cd \xampp\php (FOR XAMPP)
cd \wamp\php (FOR WAMP)
php -v
PHP 5.6.11 (cli) (built: Jul 9 2015 20:55:40) Copyright (c) 1997-2015 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
Since the title didn't specify that it has to be programmatic I'll assume that it was a genuine debugging/privacy management issue and solution is browser dependent and requires a browser with built in detailed cookie management toll and/or a debugging module or a plug-in/extension. I'm going to list one and ask other people to write up on browsers they know in detail and please be precise with versions.
Chromium, Iron build (SRWare Iron 4.0.280)
The wrench(tool) menu: Options / Under The Hood / [Show cookies and website permissions] For related domains/sites type the suffix into the search box (like .foo.tv). Caveat: when you have a node (site or cookie) click-highlighted only use [Remove] to kill specific subtrees. Using [Remove All] will still delete cookies for all sites selected by search and waste your debugging session.
https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...
<?php
require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
$getID3 = new getID3();
$filename="/fire/My Documents/video/ferrari1.mpg";
$fileinfo = $getID3->analyze($filename);
$width=$fileinfo['video']['resolution_x'];
$height=$fileinfo['video']['resolution_y'];
echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
echo '<pre>';print_r($fileinfo);echo '</pre>';
?>
If you want to use the GUI... click/double-click the table and select the Data
tab. Click in the column value you want to set to (null)
. Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.
More info here:
How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data
public void goToLocationFromAddress(String strAddress) {
//Create coder with Activity context - this
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
//Get latLng from String
address = coder.getFromLocationName(strAddress, 5);
//check for null
if (address != null) {
//Lets take first possibility from the all possibilities.
try {
Address location = address.get(0);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//Animate and Zoon on that map location
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
} catch (IndexOutOfBoundsException er) {
Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is because, even though Var1
exists, you're also using an assignment statement on the name Var1
inside of the function (Var1 -= 1
at the bottom line). Naturally, this creates a variable inside the function's scope called Var1
(truthfully, a -=
or +=
will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1
should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.
Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:
global Var1, Var2
inside the top of your function. This will tell Python that you don't intend to define a Var1
or Var2
variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.
nonlocal
statement - check that out as well. decimal Total = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value);
}
labelName.Text = Total.ToString();
First of all, try toObject()
instead of toJSON()
maybe?
Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:
var flatUsers = users.map(function() {
return user.toObject();
})
return res.end(JSON.stringify(flatUsers));
It's a guess, but I hope it helps
...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?
If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:
Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
There's a function std::reverse
in the algorithm
header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
The simpliest way is to use something like this but note that it may not be that good.
input {
outline: none;
}
I hope you find this useful.
I was trying to import numpy in python 3.2.1 on windows 7.
Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it
cd numpy-1.6
python setup.py install
but got an error with a statement as below
unable to find vcvarsall.bat
For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.
In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"
Installation went smoothly and now I am able to import numpy without using mingW.
Long story short try using windows installer for numpy, if one is available.
This is sort of an indirect approach, but you could see if a website loads on your web browser of choice from whatever is running on port 80. Or you could telnet to port 80 and see if you get a response that gives you a clue as to what is running on that port and you can go shut it down. Since port 80 is the default port for http traffic chances are there is some sort of http server running there by default, but there's no guarantee.
I had a similar situation: I needed to purge postgresql 9.1 on a debian wheezy ( I had previously migrated from 8.4 and I was getting errors ).
What I did:
First, I deleted config and database
$ sudo pg_dropcluster --stop 9.1 main
Then removed postgresql
$ sudo apt-get remove --purge postgresql postgresql-9.1
and then reinstalled
$ sudo apt-get install postgresql postgresql-9.1
In my case I noticed /etc/postgresql/9.1 was empty, and running service postgresql start
returned nothing
So, after more googling I got to this command:
$ sudo pg_createcluster 9.1 main
With that I could start the server, but now I was getting log-related errors. After more searching, I ended up changing permissions to the /var/log/postgresql directory
$ sudo chown root.postgres /var/log/postgresql
$ sudo chmod g+wx /var/log/postgresql
That fixed the issue, Hope this helps
I only had to change one line of the file config.inc.php
located in C:\wamp\apps\phpmyadmin4.1.14
.
Put the right password here ...
$cfg['Servers'][$i]['password'] = 'Put_Password_Here';
With JDK/11, an alternate way of converting a Collection<Foo>
to an Foo[]
could be to make use of Collection.toArray(IntFunction<T[]> generator)
as:
Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11
As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0])
--
The upshot is that implementations that use
Arrays.copyOf(
) are the fastest, probably because it's an intrinsic.It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.
The implementation of the API within the JDK reads:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
The default implementation calls
generator.apply(0)
to get a zero-length array and then simply callstoArray(T[])
. This goes through theArrays.copyOf()
fast path, so it's essentially the same speed astoArray(new T[0])
.
Note:- Just that the API use shall be guided along with a backward incompatibility when used for code with null
values e.g. toArray(null)
since these calls would now be ambiguous because of existing toArray(T[] a)
and would fail to compile.
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
Where null is a valid response in terms of the contract; and
Where it isn't a valid response.
(2) is easy. Either use assert
statements (assertions) or allow failure (for example, NullPointerException). Assertions are a highly-underused Java feature that was added in 1.4. The syntax is:
assert <condition>
or
assert <condition> : <object>
where <condition>
is a boolean expression and <object>
is an object whose toString()
method's output will be included in the error.
An assert
statement throws an Error
(AssertionError
) if the condition is not true. By default, Java ignores assertions. You can enable assertions by passing the option -ea
to the JVM. You can enable and disable assertions for individual classes and packages. This means that you can validate code with the assertions while developing and testing, and disable them in a production environment, although my testing has shown next to no performance impact from assertions.
Not using assertions in this case is OK because the code will just fail, which is what will happen if you use assertions. The only difference is that with assertions it might happen sooner, in a more-meaningful way and possibly with extra information, which may help you to figure out why it happened if you weren't expecting it.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
Your questions:
Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText()
Where getText will return all text content of all children of your result.
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for.
Example:
<p1> <div/> </p1 <p2/>
The following to parent of the div is p2. This would be:
//div[@id='container'][1]/parent::*/following-sibling::*
or shorter
//div[@id='container'][1]/../following-sibling::*
If you are only looking for the first one extent the expression with an "predicate"
(e.g [1]
- for the first one. or [position() < 4]
for the first three)
If your are looking for the first child of the first div:
//div[@id='container'][1]/*[1]
If there is only one div with id an you are looking for the first child:
//div[@id='container']/*[1]
and so on.
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
What about replace the item if you know the position:
aList[0]=2014
Or if you don't know the position loop in the list, find the item and then replace it
aList = [123, 'xyz', 'zara', 'abc']
for i,item in enumerate(aList):
if item==123:
aList[i]=2014
break
print aList
Bringing my answer from another question.
From the C specification, section 6.7.2:
— unsigned, or unsigned int
Meaning that unsigned
, when not specified the type, shall default to unsigned int
. So writing unsigned a
is the same as unsigned int a
.
For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add
to do this will result in "fatal: remote origin already exists."
Nutshell:
git remote set-url origin https://github.com/username/repo
(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)
While Large Text File Viewer works great for just looking at a large file (and is free!), if the file is either a delimited or fixed-width file, then you should check out File Query. Not only can it open a file of any size (I have personally opened a 280GB file, but it can go larger), but it lets you query the file as though it was in a database as well, finding out any sort of information you could want from it.
It is not free though, so it is more for people that work with large files a lot, but if you have a one-off problem, you can just use the 30-day trial for free.
None of the answers or work-arounds helped me. Most were dealing with the tableView itself. What was causing the issue for me was the view I was adding the tableView or collectionView onto. This is what fixed it for me:
SWIFT 5
edgesForExtendedLayout = []
I put that in my viewDidLoad and the annoying gap went away. Hope this helps.
Following is my TypeScript code which can be converted easily into JavaScript and you can use
/**
* Convert BASE64 to BLOB
* @param base64Image Pass Base64 image data to convert into the BLOB
*/
private convertBase64ToBlob(base64Image: string) {
// Split into two parts
const parts = base64Image.split(';base64,');
// Hold the content type
const imageType = parts[0].split(':')[1];
// Decode Base64 string
const decodedData = window.atob(parts[1]);
// Create UNIT8ARRAY of size same as row data length
const uInt8Array = new Uint8Array(decodedData.length);
// Insert all character code into uInt8Array
for (let i = 0; i < decodedData.length; ++i) {
uInt8Array[i] = decodedData.charCodeAt(i);
}
// Return BLOB image after conversion
return new Blob([uInt8Array], { type: imageType });
}
For Android Studio on Mac :
Navigation Bar :
Android Studio > Preferences > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run
For Android Studio on Windows :
File > Settings > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run
I use to work on UNIX-like machines, but recently I have had to do some work with Java on a Windows 7 machine. I have had that problem and this is the I've solved it. It has worked right for me so I hope it can be used for whoever who may have this problem in the future.
These steps are exposed considering a default Java installation on drive C. You should change what it is necessary in case your installation is not a default one.
Suppose we have installed Java 8 but for whatever reason we want to keep with Java 7.
1- Start a cmd as administrator
2- Go to C:\ProgramData\Oracle\Java
3- Rename the current directory javapath to javapath_<version_it_refers_to>. E.g.: rename javapath javapath_1.8
4- Create a javapath_<version_you_want_by_default> directory. E.g.: mkdir javapath_1.7
5- cd into it and create the following links:
cd javapath_1.7
mklink java.exe "C:\Program Files\Java\jre7\bin\java.exe"
mklink javaw.exe "C:\Program Files\Java\jre7\bin\javaw.exe"
mklink javaws.exe "C:\Program Files\Java\jre7\bin\javaws.exe"
6- cd out and create a directory link javapath pointing to the desired javapath. E.g.: mklink /D javapath javapath_1.7
7- Open the register and change the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion to have the value 1.7
At this point if you execute java -version
you should see that you are using java version 1.7:
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)
8- Finally it is a good idea to create the environment variable JAVA_HOME. To do that I create a directory link named CurrentVersion in C:\Program Files\Java pointing to the Java version I'm interested in. E.g.:
cd C:\Program Files\Java\
mklink /D CurrentVersion .\jdk1.7.0_71
9- And once this is done:
Function using the approaches of Travis J, JLewkovich and Nick Craver...
// NOTE: Clears residual validation errors from the library "jquery.validate.js".
// By Travis J and Questor
// [Ref.: https://stackoverflow.com/a/16025232/3223785 ]
function clearJqValidErrors(formElement) {
// NOTE: Internal "$.validator" is exposed through "$(form).validate()". By Travis J
var validator = $(formElement).validate();
// NOTE: Iterate through named elements inside of the form, and mark them as
// error free. By Travis J
$(":input", formElement).each(function () {
// NOTE: Get all form elements (input, textarea and select) using JQuery. By Questor
// [Refs.: https://stackoverflow.com/a/12862623/3223785 ,
// https://api.jquery.com/input-selector/ ]
validator.successList.push(this); // mark as error free
validator.showErrors(); // remove error messages if present
});
validator.resetForm(); // remove error class on name elements and clear history
validator.reset(); // remove all error and success data
// NOTE: For those using bootstrap, there are cases where resetForm() does not
// clear all the instances of ".error" on the child elements of the form. This
// will leave residual CSS like red text color unless you call ".removeClass()".
// By JLewkovich and Nick Craver
// [Ref.: https://stackoverflow.com/a/2086348/3223785 ,
// https://stackoverflow.com/a/2086363/3223785 ]
$(formElement).find("label.error").hide();
$(formElement).find(".error").removeClass("error");
}
clearJqValidErrors($("#some_form_id"));
If your dictionary is not nested, you could make a frozenset with the dict's items and use hash()
:
hash(frozenset(my_dict.items()))
This is much less computationally intensive than generating the JSON string or representation of the dictionary.
UPDATE: Please see the comments below, why this approach might not produce a stable result.
You need to import time and then use time.time() method to know current time.
import time
start_time=time.time() #taking current time as starting time
#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
Example:
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time
#!/bin/bash
path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)
filename=log_$timestamp.txt
log=$path$filename
days=7
START_TIME=$(date +%s)
find $path -maxdepth 1 -name "*.txt" -type f -mtime +$days -print -delete >> $log
echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log
... code for backup ...or any other operation .... >> $log
END_TIME=$(date +%s)
ELAPSED_TIME=$(( $END_TIME - $START_TIME ))
echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time :: $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) " >> $log
The code adds a few things.
Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.
Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'
Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days
-mtime +$days ---> -mmin +$((60*24*$days))
We offer a tool called DocFlex/XML XSDDoc that allows you to enjoy both things at once:
The diagrams in fact are generated not by us, but by Altova XMLSpy. We implemented an Integration with XMLSpy (with the full support of all diagram hyperlinks):
Here you can see the full this doc: http://www.filigris.com/docflex-xml/xsddoc/examples/html/XMLSchema/index.html
The whole thing provides a functionality not offered by any single vendor right now on the market!
Some our customers were so impressed that they purchased an extra license for XMLSpy only because of our tool. (That's no joke!)
Currently, we've also implemented similar integrations with other XML editors:
See: http://www.filigris.com/docflex-xml/OxygenXML/demo/html/xslt20/index.html
See: http://www.filigris.com/docflex-xml/LiquidXML/demo/html/XMLSchema/index.html
Concerning what all those diagrams depict... Essentially, they are all about content model of XSD elements (as well as other XSD components that lead to elements: complexTypes, element/attribute groups). It seems, there are two approaches here:
I personally believe that the diagrams generated by XMLSpy are more useful.
Yet, there were no attempts so far (at least known to me) to depict graphically anything else contained in XML schemas, although one can imagine many...
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
I just added a padding-top to the div below the nav. Hope it helps. I'm new on this. C:
#nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
margin: 0 auto;
padding: 0;
background: url(../css/patterns/black_denim.png);
z-index: 9999;
}
#container {
display: block;
padding: 6em 0 3em;
}
StringUtils.isBlank
also returns true
for just whitespace:
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.
JPA service method for example:
@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
Query query = entitymanager.createQuery("SELECT u FROM User u");
return (List<User>)query.getResultList();
}
If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.
In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.
I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html
str = str.replace(/[^\w\s]|_/g, "")
.replace(/\s+/g, " ");
Removes everything except alphanumeric characters and whitespace, then collapses multiple adjacent characters to single spaces.
Detailed explanation:
\w
is any digit, letter, or underscore.\s
is any whitespace.[^\w\s]
is anything that's not a digit, letter, whitespace, or underscore.[^\w\s]|_
is the same as #3 except with the underscores added back in.in GuzzleHttp:
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return mixed
* @throws \InvalidArgumentException if the JSON cannot be decoded.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
'json_decode error: ' . json_last_error_msg());
}
return $data;
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @return string
* @throws \InvalidArgumentException if the JSON cannot be encoded.
* @link http://www.php.net/manual/en/function.json-encode.php
*/
function json_encode($value, $options = 0, $depth = 512)
{
$json = \json_encode($value, $options, $depth);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
'json_encode error: ' . json_last_error_msg());
}
return $json;
}
I tried almost anything but no help...
Everytime was just this
? ~ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e unauthorized
However I've managed to connect device!
There is tutor, step by step.
$ rm -v .android/adbkey*
.android/adbkey
.android/adbkey.pub
Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys
Now create new adb keypair
? ~ adb keygen .android/adbkey
adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey'
adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'
Manually copy from PC .android/adbkey.pub
(pubkic key) to Device on path /data/misc/adb/adb_keys
Reboot device and check adb devices
:
? ~ adb devices
List of devices attached
aeef5e4e device
Permissions of /data/misc/adb/adb_keys
are (766/-rwxrw-rw-)
on my device
I don't see anything in here to suggest that this is a web-app but I have experienced this issue myself - I've got two xcopy commands on a post-build event and only one of them was failing. Something had a lock on the file, and it wasn't Visual Studio (as I tried restarting it.)
The only other thing that would have used the dll I built was IIS. And lo and behold,
A simple iisreset
did the trick for me.
Something like this? Takes advantage of short-circuit evaluation. If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part.
os.path.exists("gogogo.php") and os.remove("gogogo.php")
You can try viewport units (CSS3):
canvas {
height: 100vh;
width: 100vw;
display: block;
}
When you don't want to write IEqualityComparer you can try something like following.
class Program
{
private static void Main(string[] args)
{
var items = new List<Item>();
items.Add(new Item {Id = 1, Name = "Item1"});
items.Add(new Item {Id = 2, Name = "Item2"});
items.Add(new Item {Id = 3, Name = "Item3"});
//Duplicate item
items.Add(new Item {Id = 4, Name = "Item4"});
//Duplicate item
items.Add(new Item {Id = 2, Name = "Item2"});
items.Add(new Item {Id = 3, Name = "Item3"});
var res = items.Select(i => new {i.Id, i.Name})
.Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();
// now res contains distinct records
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
adding express.urlencoded({ extended: true })
to the route solves the problem.
router.post('/save',express.urlencoded({ extended: true }), "your route");
Here is my version which adds the tcp port in case it's not 80 or 443:
function url(s) {
var l = window.location;
return ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + (((l.port != 80) && (l.port != 443)) ? ":" + l.port : "") + l.pathname + s;
}
Edit 1: Improved version as by suggestion of @kanaka :
function url(s) {
var l = window.location;
return ((l.protocol === "https:") ? "wss://" : "ws://") + l.host + l.pathname + s;
}
Edit 2: Nowadays I create the WebSocket
this:
var s = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/ws");
I developed an extension for this purpose, so you can easily put a decorator on your view function and see how many queries are executed.
To install:
$ pip install django-print-sql
To use as context manager:
from django_print_sql import print_sql
# set `count_only` to `True` will print the number of executed SQL statements only
with print_sql(count_only=False):
# write the code you want to analyze in here,
# e.g. some complex foreign key lookup,
# or analyzing a DRF serializer's performance
for user in User.objects.all()[:10]:
user.groups.first()
To use as decorator:
from django_print_sql import print_sql_decorator
@print_sql_decorator(count_only=False) # this works on class-based views as well
def get(request):
# your view code here
The answer, from this page in CSS:
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Doesn't SELECT DISTINCT
help? I suppose it would return the result you want.
Try this
<div id="divRegister"></div>
$(document).ready(function() {
location.hash = "divRegister";
});
It is actually called file:///android_asset/index.html
file:///android_assets/index.html
will give you a build error.
I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same "No module named site
" error. I've set PYTHONHOME to c:\Python27
and it's working. But the mystery remains why this is now needed when it wasn't with previous releases. And, if it is needed, why doesn't the installer set this var?
Change the frame size of viewcontroller.view.frame
, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]
Don't forget the padding and margins...
jQuery.fn.slideLeftHide = function(speed, callback) {
this.animate({
width: "hide",
paddingLeft: "hide",
paddingRight: "hide",
marginLeft: "hide",
marginRight: "hide"
}, speed, callback);
}
jQuery.fn.slideLeftShow = function(speed, callback) {
this.animate({
width: "show",
paddingLeft: "show",
paddingRight: "show",
marginLeft: "show",
marginRight: "show"
}, speed, callback);
}
With the speed/callback arguments added, it's a complete drop-in replacement for slideUp()
and slideDown()
.
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.
Combine Kim's answer with os:
p=Path(os.getcwd())
os.chdir(p.parent)
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
I rename the .gitconfig file as xyz.gitconfig, then git will generate a new .gitconfig file, that wokrd
Try this instead:
select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t
In my case, I have 64bit python, and it was lxml that was the wrong version--I should have been using the x64 version of that as well. I solved this by downloading the 64-bit version of lxml here:
https://pypi.python.org/pypi/lxml/3.4.1
lxml-3.4.1.win-amd64-py2.7.exe
This was the simplest answer to a frustrating issue.
It is an issue with bad sql execution which does not allow other queries to execute until the previous one gets suspended/rollback.
In PgAdmin4-4.24 there is an option of rollback, one can try this.
when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.
<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>
if the error still conitnue try to set form control for all of object(myObject) field.
between start <form> </form>
for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
Use max()
:
Using itemgetter()
:
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis,key=itemgetter(1))[0] #faster solution
Out[82]: 361
using lambda
:
In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)
In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
timeit
comparison:
In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
Gender :<br>
<input type="radio" name="g" value="male" <?php echo ($g=='Male')?'checked':'' ?>>male <br>
<input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
<?php echo $errors['g'];?>
Its a simple xml design. It looks like iOS switch, check this below image
You need to create custom_thumb.xml and custom_track.xml
This is my switch,I need a very big switch so added layout_width/layout_height parameter
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/swOnOff"
android:layout_width="@dimen/_200sdp"
android:layout_marginStart="@dimen/_50sdp"
android:layout_marginEnd="@dimen/_50sdp"
android:layout_marginTop="@dimen/_30sdp"
android:layout_gravity="center"
app:showText="true"
android:textSize="@dimen/_20ssp"
android:fontFamily="@font/opensans_bold"
app:track="@drawable/custom_track"
android:thumb="@drawable/custom_thumb"
android:layout_height="@dimen/_120sdp"/>
Now create custom_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#8c8c8c"/>
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#34c759"/>
</shape>
</item>
</selector>
Now create custom_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#ffffff" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#34c759" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
</selector>
You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
+-- __init__.py
+-- moduleB.py
In moduleB
:
from toplevel_package import moduleA
If you'd like to run moduleB.py
as a script then make sure that parent directory for toplevel_package
is in your sys.path
.
What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.
What type of server are you trying to communicate with? You may need to write a small service to respond to the request.
The concept is very well explained by the accepted answer, but I find that the more example one sees, the better it sinks in. Here's an incremental example:
1) Boss says "get me number of items we have in stock grouped by brand"
You say: "no problem"
SELECT
BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
Result:
+--------------+---------------+
| Brand | Count |
+--------------+---------------+
| H&M | 50 |
+--------------+---------------+
| Hugo Boss | 100 |
+--------------+---------------+
| No brand | 22 |
+--------------+---------------+
2) The boss says "Now get me a list of all items, with their brand AND number of items that the respective brand has"
You may try:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
But you get:
ORA-00979: not a GROUP BY expression
This is where the OVER (PARTITION BY BRAND)
comes in:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID) OVER (PARTITION BY BRAND)
FROM
ITEMS;
Whic means:
COUNT(ITEM_ID)
- get the number of itemsOVER
- Over the set of rows(PARTITION BY BRAND)
- that have the same brandAnd the result is:
+--------------+---------------+----------+
| Items | Brand | Count() |
+--------------+---------------+----------+
| Item 1 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 2 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 3 | No brand | 22 |
+--------------+---------------+----------+
| Item 4 | No brand | 22 |
+--------------+---------------+----------+
| Item 5 | H&M | 50 |
+--------------+---------------+----------+
etc...
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
SDK for Android
is enabled in API console.You can either: Write a server-side script page like PHP, JSP, ASP.net etc to generate this HTML dynamically
or
Setup the web-server that you are using (e.g. Apache) to do exactly that automatically for directories that doesn't contain welcome-page (e.g. index.html)
Specifically in apache read more here: Edit the httpd.conf: http://justlinux.com/forum/showthread.php?s=&postid=502789#post502789 (updated link: https://forums.justlinux.com/showthread.php?94230-Make-apache-list-directory-contents&highlight=502789)
or add the autoindex mod: http://httpd.apache.org/docs/current/mod/mod_autoindex.html
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
Changing the default python executable's version system-wide could break some applications that depend on python2.
However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put
alias python='python3'
in your ~/.profile
, and then source ~/.profile
in your ~/.bash_profile
and/or your~/.zsh_profile
with a line like:
[ -e ~/.profile ] && . ~/.profile
This way, your alias will work across shells.
With this, python
command now invokes python3
. If you want to invoke the "original" python (that refers to python2) on occasion, you can use command python
, which will leaving the alias untouched, and works in all shells.
If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:
alias 2='python2'
alias 3='python3'
Tip: For scripts, instead of using a shebang like:
#!/usr/bin/env python
use:
#!/usr/bin/env python3
This way, the system will use python3 for running python executables.
I have faced this similar issue and resolved it by using following steps :
sqlplus "/ as sysdba"
alter user HR identified by password account unlock
password
is the password that I have used. console.log( Object.keys( {'a':1,'b':2} ) );
It can be done in a single command. You need to set the IDENTITY property for "auto number":
ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY
More precisely, to set a named table level constraint:
ALTER TABLE MyTable
ADD MytableID int NOT NULL IDENTITY (1,1),
CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)
See ALTER TABLE and IDENTITY on MSDN
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
You can use this function to convert comma-delimited single character strings to list-
def stringtolist(x):
mylist=[]
for i in range(0,len(x),2):
mylist.append(x[i])
return mylist
String line;_x000D_
Process process = Runtime.getRuntime().exec("ps -e");_x000D_
process.getOutputStream().close();_x000D_
BufferedReader input =_x000D_
new BufferedReader(new InputStreamReader(process.getInputStream()));_x000D_
while ((line = input.readLine()) != null) {_x000D_
System.out.println(line); //<-- Parse data here._x000D_
}_x000D_
input.close();
_x000D_
We have to use process.getOutputStream.close()
otherwise it will get locked in while loop.
the next answer is for those who have a multi-level menu:
var url = window.location.href;
var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === url) {
el.classList.add("active");
var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent
parent.classList.add("active");
}
}
#define SWAP(type, a, b) \
do { type t=(a);(a)=(b);(b)=t; } while (0)
static void reverse_(int* a, int* b)
{
for ( --b; a < b; a++, b-- )
SWAP(int, *a, *b);
}
static int* rotate_(int* a, int* b, int* c)
/* swap the sequence [a,b) with [b,c). */
{
if (a != b && b != c)
{
reverse_(a, b);
reverse_(b, c);
reverse_(a, c);
}
return a + (c - b);
}
static int* lower_bound_(int* a, int* b, const int key)
/* find first element not less than @p key in sorted sequence or end of
* sequence (@p b) if not found. */
{
int i;
for ( i = b-a; i != 0; i /= 2 )
{
int* mid = a + i/2;
if (*mid < key)
a = mid + 1, i--;
}
return a;
}
static int* upper_bound_(int* a, int* b, const int key)
/* find first element greater than @p key in sorted sequence or end of
* sequence (@p b) if not found. */
{
int i;
for ( i = b-a; i != 0; i /= 2 )
{
int* mid = a + i/2;
if (*mid <= key)
a = mid + 1, i--;
}
return a;
}
static void ip_merge_(int* a, int* b, int* c)
/* inplace merge. */
{
int n1 = b - a;
int n2 = c - b;
if (n1 == 0 || n2 == 0)
return;
if (n1 == 1 && n2 == 1)
{
if (*b < *a)
SWAP(int, *a, *b);
}
else
{
int* p, * q;
if (n1 <= n2)
p = upper_bound_(a, b, *(q = b+n2/2));
else
q = lower_bound_(b, c, *(p = a+n1/2));
b = rotate_(p, b, q);
ip_merge_(a, p, b);
ip_merge_(b, q, c);
}
}
void mergesort(int* v, int n)
{
if (n > 1)
{
int h = n/2;
mergesort(v, h); mergesort(v+h, n-h);
ip_merge_(v, v+h, v+n);
}
}
Adds support code and modifications to accelerate the merge when an auxiliary buffer of any size is available (still works without additional memory). Uses forward and backward merging, ring rotation, small sequence merging and sorting, and iterative mergesort.
#include <stdlib.h>
#include <string.h>
static int* copy_(const int* a, const int* b, int* out)
{
int count = b - a;
if (a != out)
memcpy(out, a, count*sizeof(int));
return out + count;
}
static int* copy_backward_(const int* a, const int* b, int* out)
{
int count = b - a;
if (b != out)
memmove(out - count, a, count*sizeof(int));
return out - count;
}
static int* merge_(const int* a1, const int* b1, const int* a2,
const int* b2, int* out)
{
while ( a1 != b1 && a2 != b2 )
*out++ = (*a1 <= *a2) ? *a1++ : *a2++;
return copy_(a2, b2, copy_(a1, b1, out));
}
static int* merge_backward_(const int* a1, const int* b1,
const int* a2, const int* b2, int* out)
{
while ( a1 != b1 && a2 != b2 )
*--out = (*(b1-1) > *(b2-1)) ? *--b1 : *--b2;
return copy_backward_(a1, b1, copy_backward_(a2, b2, out));
}
static unsigned int gcd_(unsigned int m, unsigned int n)
{
while ( n != 0 )
{
unsigned int t = m % n;
m = n;
n = t;
}
return m;
}
static void rotate_inner_(const int length, const int stride,
int* first, int* last)
{
int* p, * next = first, x = *first;
while ( 1 )
{
p = next;
if ((next += stride) >= last)
next -= length;
if (next == first)
break;
*p = *next;
}
*p = x;
}
static int* rotate_(int* a, int* b, int* c)
/* swap the sequence [a,b) with [b,c). */
{
if (a != b && b != c)
{
int n1 = c - a;
int n2 = b - a;
int* i = a;
int* j = a + gcd_(n1, n2);
for ( ; i != j; i++ )
rotate_inner_(n1, n2, i, c);
}
return a + (c - b);
}
static void ip_merge_small_(int* a, int* b, int* c)
/* inplace merge.
* @note faster for small sequences. */
{
while ( a != b && b != c )
if (*a <= *b)
a++;
else
{
int* p = b+1;
while ( p != c && *p < *a )
p++;
rotate_(a, b, p);
b = p;
}
}
static void ip_merge_(int* a, int* b, int* c, int* t, const int ts)
/* inplace merge.
* @note works with or without additional memory. */
{
int n1 = b - a;
int n2 = c - b;
if (n1 <= n2 && n1 <= ts)
{
merge_(t, copy_(a, b, t), b, c, a);
}
else if (n2 <= ts)
{
merge_backward_(a, b, t, copy_(b, c, t), c);
}
/* merge without buffer. */
else if (n1 + n2 < 48)
{
ip_merge_small_(a, b, c);
}
else
{
int* p, * q;
if (n1 <= n2)
p = upper_bound_(a, b, *(q = b+n2/2));
else
q = lower_bound_(b, c, *(p = a+n1/2));
b = rotate_(p, b, q);
ip_merge_(a, p, b, t, ts);
ip_merge_(b, q, c, t, ts);
}
}
static void ip_merge_chunk_(const int cs, int* a, int* b, int* t,
const int ts)
{
int* p = a + cs*2;
for ( ; p <= b; a = p, p += cs*2 )
ip_merge_(a, a+cs, p, t, ts);
if (a+cs < b)
ip_merge_(a, a+cs, b, t, ts);
}
static void smallsort_(int* a, int* b)
/* insertion sort.
* @note any stable sort with low setup cost will do. */
{
int* p, * q;
for ( p = a+1; p < b; p++ )
{
int x = *p;
for ( q = p; a < q && x < *(q-1); q-- )
*q = *(q-1);
*q = x;
}
}
static void smallsort_chunk_(const int cs, int* a, int* b)
{
int* p = a + cs;
for ( ; p <= b; a = p, p += cs )
smallsort_(a, p);
smallsort_(a, b);
}
static void mergesort_lower_(int* v, int n, int* t, const int ts)
{
int cs = 16;
smallsort_chunk_(cs, v, v+n);
for ( ; cs < n; cs *= 2 )
ip_merge_chunk_(cs, v, v+n, t, ts);
}
static void* get_buffer_(int size, int* final)
{
void* p = NULL;
while ( size != 0 && (p = malloc(size)) == NULL )
size /= 2;
*final = size;
return p;
}
void mergesort(int* v, int n)
{
/* @note buffer size may be in the range [0,(n+1)/2]. */
int request = (n+1)/2 * sizeof(int);
int actual;
int* t = (int*) get_buffer_(request, &actual);
/* @note allocation failure okay. */
int tsize = actual / sizeof(int);
mergesort_lower_(v, n, t, tsize);
free(t);
}
open file, save as .csv and then apply
df = pd.read_csv('apps.csv', sep='\t')
for any other format also, just change the sep tag
This code works too:
$("input[reference=12345].myclass").css('border', '#000 solid 1px');
This really works - i had verified lot of sites and finally got the answer.
This may occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path.
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL
, there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA
folder .
That's it. Now start the MS SQL service and you are done.
The syntaxes
int[]
and
int[X] // Where X is a compile-time positive integer
are exactly the same as
int*
when in a function parameter list (I left out the optional names).
Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3]
and int secondarray[5]
decay to int*
s.
It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]
) yield an lvalue to the same element when you use the same index.
These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.
With quotes:
cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g'
gives output as:
"CentOS Linux 7 (Core)"
Without quotes:
cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g' | sed 's/"//g'
gives output as:
CentOS Linux 7 (Core)
You don't need the separate fill item. In fact, it's invalid. You just have to add a solid
block to the shape
. The subsequent stroke
draws on top of the solid
:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="1dip"
android:color="@color/bggrey" />
</shape>
You also don't need the layer-list
if you only have one shape
.
Some of it is possible, specifically accessing subtotals:
"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)
Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/
You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:
A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Stream.generate(() -> new A())
is like factory for separate A elements created in a way described by lambda, () -> new A()
which is implementation of Supplier<A>
- it describe how each new A instances should be created. limit(4)
sets amount of elements which stream will generatetoArray(A[]::new)
(can also be rewritten as toArray(size -> new A[size])
) - it lets us decide/describe type of array which should be returned.For some primitive types you can use DoubleStream
, IntStream
, LongStream
which additionally provide generators like range
rangeClosed
and few others.
Report Manager has been around for quite a few years. It's written in Delphi (at least it was originally) and has components that can be used in Delphi, but is usable via ActiveX or dll from just about any language. Now has a native .NET library too. Has a nifty report-serving webserver you can set up too. The designer gui looks and feels a little rough around the edges but it works. http://reportman.sourceforge.net/
Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.
The simplest solution is
h[:key] = "bar"
If you want a method, use store
:
h.store(:key, "bar")
If you really, really want to use a "shovel" operator (<<
), it is actually appending to the value of the hash as an array, and you must specify the key:
h[:key] << "bar"
The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:
h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"
You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:
class Hash
def <<(k,v)
self.store(k,v)
end
end
However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:
h << :key, "bar" #doesn't work
h.<< :key, "bar" #works
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
How do I add a junit 4 dependency correctly?
Assuming you're resolving against a standard Maven (or equivalent) repo:
dependencies {
...
testCompile "junit:junit:4.11" // Or whatever version
}
Run those tests in the folders of tests/model?
You define your test source set the same way:
sourceSets {
...
test {
java {
srcDirs = ["test/model"] // Note @Peter's comment below
}
}
}
Then invoke the tests as:
./gradlew test
EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.
One simple way using subplots
:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 4, sharex=True, sharey=True)
# add a big axes, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
plt.xlabel("common X")
plt.ylabel("common Y")
There is a tool usually used in MS Servers (as far as I can remember) called forfiles:
The link above contains help as well as a link to the microsoft download page.
should use get_home_url(), then your links are absolute, but it does not affect if you change the site url
Implement preferredStatusBarStyle
as you mentioned and call self.setNeedsStatusBarAppearanceUpdate()
in ViewDidLoad
and
also in Info.plist set UIViewControllerBasedStatusBarAppearance
to YES
(It's YES
by default)
It is not clear why it is not working.I need to check code.One other suggestion is
go with working code in viewDidLoad
UIApplication.sharedApplication().statusBarStyle = .LightContent
and change this to default when you view get disappeared viewWillDisappear
.
You can install the package gcolor2
for this:
sudo apt-get install gcolor2
Then:
Applications -> Graphics -> GColor2
Put the following code before int main()
:
using namespace std;
And you will be able to use cout
.
For example:
#include<iostream>
using namespace std;
int main(){
char t = 'f';
char *t1;
char **t2;
cout<<t;
return 0;
}
Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/
Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std;
at the top of your code. For detailed correct approach, please read the answers to this related SO question.
For python version 2.x you can simply use
pip install pillow
But for python version 3.X you need to specify
(sudo) pip3 install pillow
when you enter pip in bash hit tab and you will see what options you have
The easiest way i think is as provided by the android support library:
android.support.v4.widget.SwipeRefreshLayout;
once that is imported then you can have your layout defined as follows:
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/refresh"
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.v7.widget.RecyclerView
xmlns:recycler_view="http://schemas.android.com/apk/res-auto"
android:id="@android:id/list"
android:theme="@style/Theme.AppCompat.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/button_material_light"
>
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
I assume that you use recycler view instead of listview. However, listview still works so you just need to replace recyclerview with listview and update the references in the java code (Fragment).
In your activity fragment, you first implement the interface, SwipeRefreshLayout.OnRefreshListener
:
i,e
public class MySwipeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public void onRefresh(){
swipeRefreshLayout.setRefreshing(true);
refreshList();
}
refreshList(){
//do processing to get new data and set your listview's adapter, maybe reinitialise the loaders you may be using or so
//when your data has finished loading, cset the refresh state of the view to false
swipeRefreshLayout.setRefreshing(false);
}
}
Hope this helps the masses
This convention is used for special variables or methods (so-called “magic method”) such as __init__
and __len__
. These methods provides special syntactic features or do special things.
For example, __file__
indicates the location of Python file, __eq__
is executed when a == b
expression is executed.
A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__
that will be executed at first when an instance of a class is created).
class A:
def __init__(self, a): # use special method '__init__' for initializing
self.a = a
def __custom__(self): # custom special method. you might almost do not use it
pass
It iterates through the json objects, and searches each value you are concerned about, 'website', and if it equals "yahoo" you can then return that value or do whatever you like there. Right now it just logs that element to the console.
jsonObj.forEach(function (element, index) {
if(element['website'] === 'yahoo'){
console.log('found', element)
}
})
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
An idea is to have a static variable in your main activity, instantiated to be the package name. Then just reference that variable.
You will have to initialize it in the main activity's onCreate()
method:
Global to the class:
public static String PACKAGE_NAME;
Then..
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PACKAGE_NAME = getApplicationContext().getPackageName();
}
You can then access it via Main.PACKAGE_NAME
.
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
Did you try with setTransformationMethod? It's inherited from TextView and want a TransformationMethod as a parameter.
You can find more about TransformationMethods here.
It also has some cool features, like character replacing.
You can use readfile and output the image headers which you can get from getimagesize like this:
$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);
The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.
My problem occurs when I try to open https. I don't use SSL.
It's Tomcat bug.
Today 12/02/2017 newest official version from Debian repositories is Tomcat 8.0.14
Solution is to download from official site and install newest package of Tomcat 8, 8.5, 9 or upgrade to newest version(8.5.x) from jessie-backports
Add to /etc/apt/sources.list
deb http://ftp.debian.org/debian jessie-backports main
Then update and install Tomcat from jessie-backports
sudo apt-get update && sudo apt-get -t jessie-backports install tomcat8
Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.
Change your class to make an observable, that will emit results of new requests:
export class RecentDetectionComponent implements OnInit {
recentDetections$: Observable<Array<RecentDetection>>;
constructor(private recentDetectionService: RecentDetectionService) {
}
ngOnInit() {
this.recentDetections$ = Observable.interval(5000)
.exhaustMap(() => this.recentDetectionService.getJsonFromApi())
.do(recent => console.log(recent[0].macAddress));
}
}
And update your view to use AsyncPipe:
<tr *ngFor="let detected of recentDetections$ | async">
...
</tr>
Want to add, that it's better to make a service with a method that will take interval
argument, and:
exhaustMap
like in code above);UPDATE:
As the behaviour of spring.config.location now overrides the default instead of adding to it. You need to use spring.config.additional-location
to keep the defaults. This is a change in behaviour from 1.x to 2.x
When using Spring Boot the properties are loaded in the following order (see Externalized Configuration in the Spring Boot reference guide).
When resolving properties (i.e. @Value("${myprop}")
resolving is done in the reverse order (so starting with 9).
To add different files you can use the spring.config.location
properties which takes a comma separated list of property files or file location (directories).
-Dspring.config.location=your/config/dir/
The one above will add a directory which will be consulted for application.properties
files.
-Dspring.config.location=classpath:job1.properties,classpath:job2.properties
This will add the 2 properties file to the files that are loaded.
The default configuration files and locations are loaded before the additonally specified spring.config.location
ones meaning that the latter will always override properties set in the earlier ones. (See also this section of the Spring Boot Reference Guide).
If
spring.config.location
contains directories (as opposed to files) they should end in / (and will be appended with the names generated fromspring.config.name
before being loaded). The default search pathclasspath:,classpath:/config,file:,file:config/
is always used, irrespective of the value ofspring.config.location
. In that way you can set up default values for your application inapplication.properties
(or whatever other basename you choose withspring.config.name
) and override it at runtime with a different file, keeping the defaults.
Wrap your AND logic in parenthesis, like this:
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
You can do it like this:
class UsersController < ApplicationController
## Exception Handling
class NotActivated < StandardError
end
rescue_from NotActivated, :with => :not_activated
def not_activated(exception)
flash[:notice] = "This user is not activated."
Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
redirect_to "/"
end
def show
// Do something that fails..
raise NotActivated unless @user.is_activated?
end
end
What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.
Best wishes,
Fabian
There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
The above code inserts two rows, but you can extend it arbitrarily, until you hit the maximum number of prepared statement tokens (it might be $999, but I'm not 100% sure about that). Sometimes one cannot use COPY, and this is a worthy replacement for those situations.
If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.
enum TestStatus {
Available, // 0
Ready, // 1
Started, // 2
}
class Test {
status: TestStatus
}
var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
// and the sequence ID is automatic
The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available
. And Typescript will enforce the type when you pass those around.
You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.
class TestStatus {
id: number
name: string
constructor(id, name){
this.id = id;
this.name = name;
}
}
type Statuses = Array<TestStatus>;
var statuses: Statuses = [
new TestStatus(0, "Available"),
new TestStatus(1, "Ready"),
new TestStatus(2, "Started")
]
Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.
You can use :
basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables
Striped rows Table :
<table class="table table-striped" width="647">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
</tbody>
</table>
Condensed table :
Compacting a table you need to add class class=”table table-condensed” .
<table class="table table-condensed" width="647">
<thead>
<tr>
<th>#</th>
<th>Sample Name</th>
<th>Address</th>
<th>Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
<tr>
<td></td>
<td colspan="3" align="center"></td>
</tr>
</tbody>
</table>
Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial
List<string> nameslist = new List<string> {"one", "two", "three"} ?