lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | I am searching for a javascript alternative for the following code : I have never worked with javascript . This may be very simple for someone who 's more experienced with javascript . | $ ( ' a [ href*= '' vivo.sx/ '' ] ' ) .attr ( 'href ' ) | JavaScript version of this jQuery line |
JS | I am using a window of fixed position with horizontal and vertical scroll . And using position.top ( ) to find the particular position of the div.But when zoom is 1 or > 1 then it is working totally fine.But when zoom is < 1 then there are inconsistencies.Example Jsfiddle | var position = anchor.position ( ) .top ; | position ( ) .top inconsistencies when ( zoom < 1 ) |
JS | This is obviously a totally inefficient way to change the background color of a button , but I 'm wondering why this does n't work : If a variable is able to be used inside of a string ( e.g . $ { variable } ) why would n't it be able to be used in the above scenario ? | < button id= '' blueButton '' > Button < /button > var data = { } ; function changeColor ( e ) { data.e = `` blue '' ; $ ( ' # ' + e ) .css ( 'background-color ' , data.e ) ; } changeColor ( blueButton ) ; | Can a parameter be used to create a new object key and as a variable in the same function ? |
JS | I want to catch the load even of any iframe which is appended on the document at some point after loading the page.I tried using on ( `` load '' , `` iframe '' , fn ) , but that does n't seem to do it : While $ ( `` iframe '' ) .on ( `` load '' , fn ) , right after appending the iframe works , delegation on the documen... | function addIframe ( ) { $ ( `` < iframe src='https : //example.com ' > '' ) .appendTo ( $ ( `` body '' ) ) } // This does not work $ ( document ) .on ( `` load '' , `` iframe '' , function ( ) { alert ( `` loaded , caught via delegation '' ) } ) setTimeout ( function ( ) { addIframe ( ) // This works $ ( `` iframe '' ... | Catch the load event from iframes , using jQuery delegation |
JS | Think this is a simple question , but I am very new to web dev so I apologize : ) - > on an onSelect event , how do I grab the content of what was selected ? And is there a way to modify the text that was selected , such as highlighting ? This is what I have so far : in js : | < textarea id= '' text '' > Text to be highlighted < /textarea > let text_selection = document.getElementById ( `` text '' ) ; text_selection.addEventListener ( `` select '' , highlightText ) ; function highlightText ( ) { alert ( 'hello ' ) ; } | How to get text value of selected text from onSelect DOM event |
JS | Having a bi-dimensional array of this form : On each sub-array the first element is a string.I want to combine together the sub-arrays having the same end . In this case it will be two groups : -a and -b . The numerical values should be computed as sum based on idex.So the result would look like : my solution ( which d... | arr = [ [ `` 12325-a '' , 1 , 1 , 1 ] , [ `` 43858-b '' , 3 , 4 , 1 ] , [ `` 84329-a '' , 6 , 5 , 2 ] , [ `` 18767-b '' , 0 , 9 , 0 ] , [ `` 65888-b '' , 5 , 4 , 4 ] , ] ; arr = [ [ `` -a '' , 7 , 6 , 3 ] , [ `` -b '' , 8 , 17 , 5 ] , ] ; let arr = [ [ `` 12325-a '' , 1 , 1 , 1 ] , [ `` 43858-b '' , 3 , 4 , 1 ] , [ `` ... | Combine sub-arrays by using as a key a sub-string found in the first element of each sub-array |
JS | I need to update the object name based on the array of the string value and the last string value should be an array . I use array.forEach loop but I do n't know how to find the object inside an object if it exists and the myArray contain around 10,000 strings . final output should be | const myArray = [ '/unit/unit/225/unit-225.pdf ' , '/nit/nit-dep/4.11/nit-4.11.pdf ' , '/nit/nit-dep/4.12/nit-4.12.pdf ' , '/org/viti/viti-engine/5.1/viti-engine-5.1.pdf ' , '/org/viti/viti-spring/5.1/viti-spring-5.1.pdf ' ] ; var parentObject = { } myArray.forEach ( res = > { res = res.slice ( 1 , res.length ) ; var a... | Create a object i an object based on the array of string value |
JS | I have a html form which has the following fields to create a recipe : I have a button after the ingredients fields which ideally would add a new input field to add another ingredient to the table containing the ingredients for the recipe . At the moment , the button is calling the function correctly and the function d... | < form class= '' login-form '' action= '' < ? php echo htmlspecialchars ( basename ( $ _SERVER [ 'REQUEST_URI ' ] ) ) ; ? > '' method= '' post '' > < div class= '' form-group < ? php echo ( ! empty ( $ name_err ) ) ? 'has-error ' : `` ; ? > '' > < label > Name < /label > < input type= '' text '' name= '' name '' class=... | Submit button inside form without reloading form |
JS | I 'm trying to make a little game where the user can click on a place on the page , the circle will follow to the pointer 's position , and from there , the user can drag their mouse to make the circle move like a slingshot . I want the circle to be able to bounce off the walls.However , it seems that on the circle 's ... | let windowHeight = window.innerHeight ; let windowWidth = window.innerWidth ; //console.log ( ` Window height : $ { windowHeight } , Window width : $ { windowWidth } ` ) ; var $ = document.querySelector.bind ( document ) ; var $ on = document.addEventListener.bind ( document ) ; var mouseX , mouseY ; $ on ( 'mousedown ... | Javascript Object sticks to div object on collision |
JS | why notwindow.onresize = reportWindowSize ( ) ? it 's function call , I want to trigger it . but when I add the ( ) it 's not working . | const heightOutput = document.querySelector ( ' # height ' ) ; const widthOutput = document.querySelector ( ' # width ' ) ; function reportWindowSize ( ) { heightOutput.textContent = window.innerHeight ; widthOutput.textContent = window.innerWidth ; } window.onresize = reportWindowSize ; | What is the difference between assigning a variable value with functionName ( ) and just functionName ? |
JS | Reading the mdn documentation on the difference between Function constructor and function declaration . The example specified there works on the browser and also on the node.js repl , but on trying it through a file , the node.js process crashed with this errorReferenceError : x is not definedThis is the programWhat mi... | var x = `` bar '' ; function test ( ) { var x = `` baz '' ; return new Function ( `` return x ; '' ) ; } var t = test ( ) ; console.log ( t ( ) ) ; | ReferrenceError while trying to access variable inside of Function constructor |
JS | I saw this as a solution for a codewars challenge where you need to reverse an array without using the reverse method and using just 30 bits spare : Now the way I know to use map is something like this : So I dont really understand how map is used in that case , could somebody explain please ? | reverse=a= > [ ... a ] .map ( a.pop , a ) array.map ( item = > somethingelse ) | Can somebody explain this particular use of the method map ? |
JS | Hoping to get some ideas with current situation , honestly - I 'm poor on .js side , so hopefully you 'll be able to put me in a right way.Checkbox ( content is visible if checkbox checked , otherwise hidden ) : and .js function code : Probably I 'm using wrong syntax of checking is mentioned field required . Unless I ... | < input type= '' checkbox '' id= '' myCheck '' onclick= '' myFunction ( ) '' > { { text_company_purchase } } < div id= '' text '' style= '' display : none '' > < div class= '' form-group '' > < label class= '' control-label '' for= '' input-payment-company '' > { { entry_company } } < /label > < input type= '' text '' ... | Conditional .js function in OC 3.x template |
JS | I am trying to insert an object formatted like this : I tried using the following for loop : But it does n't seem to work . I am getting undefined everywhere . Does anyone have an idea on how to retrieve the data from that object row by row then insert the values to the service ? | $ scope.newObj = { 1 : `` N/A '' , 2 : `` KO '' , 3 : `` OK '' , 4 : `` OK '' , 5 : `` OK '' , 15 : `` N/A '' , 19 : `` OK '' } var objt = $ scope.newObject ; console.log ( $ scope.newObject [ 0 ] ) // undefinedfor ( i=0 ; i < $ scope.newObj.length ; i++ ) { $ http.post ( `` insert ? etat= '' + $ scope.newObject [ 0 ] ... | Inserting a JS object into $ http service |
JS | I have a table.I am trying to find out the summation as below : td ( 1 ) + td ( 2 ) + td ( 3 ) = td ( 4 ) , td ( 5 ) + td ( 6 ) + td ( 7 ) = td ( 8 ) , td ( 9 ) + td ( 10 ) + td ( 11 ) = td ( 12 ) .Here is my code : The code above works fine . But my problem is , I ca n't enter any thing to first column ( ie , td : eq ... | $ ( document ) .ready ( function ( ) { $ ( ' # table ' ) .on ( 'keyup ' , 'input ' , function ( ) { $ ( `` # table tr '' ) .slice ( 2 ) .find ( `` td : nth-child ( 4n + 1 ) '' ) .each ( function ( ) { var sum = 0 ; $ ( this ) .prevAll ( ' : lt ( 3 ) ' ) .find ( 'input ' ) .each ( function ( ) { sum += ( +this.value || ... | Summation of text fields on keyup causes issues in first field of a row |
JS | Updated example , as it did n't match to the object structure which was given in the postThere is an array , which has multiple objects like this : Now I need to sort the content in two ways : Sort all array elements by the text-fieldI would do like this : The content of the nested elements-array should also be sorted ... | { text : text , elements : [ { id : id , page : pageNumber } ] } array.sort ( function ( a , b ) { if ( a.text < b.text ) return -1 ; if ( a.text > b.text ) return 1 ; return 0 ; } ) ; [ { text : 'Some text ' , elements : [ { id : 1 , pages : '45-67 ' } , { id : 2 , pages : '12-34 ' } ] } , { text : 'Another text ' , e... | Sort object-array and additionally a nested array in these objects |
JS | Consider this code : It does nothing . Is there a way I can iterate over properties and public methods of Foo ? It would work if Foo was object literal , like this : But I would prefer for it to be a function instead.The reason I want to do this , I want to extend from Foo using mixin pattern.http : //jsfiddle.net/ChU2... | var Foo = function ( ) { this.bar = [ ] ; this.hello = function ( ) { this.name = `` world '' ; } ; } ; for ( var property in Foo ) { alert ( 111 ) ; } var Foo = { bar : [ ] , hello : function ( ) { this.name = `` world '' ; } } ; for ( var property in Foo ) { alert ( 111 ) ; } | Is there a way to iterate over public methods inside a function scope ? |
JS | I 'm trying out a simple CSRF attack and ran into an issue.If I have a dummy site containing this form : My original idea was to have this form `` self submitting '' by having a script tag call submit on the form on page load to automatically change the user 's password when they visit the page : This looked like it wo... | < form action= '' somewebsitetoexploit.com/someformpage '' method= '' GET '' hidden > < input type= '' password '' autocomplete= '' off '' name= '' password_new '' value= '' hacked '' > < br > < input type= '' password '' autocomplete= '' off '' name= '' password_conf '' value= '' hacked '' > < input type= '' submit ''... | Why does calling submit on a form and click on a submit button produce different GET parameters ? |
JS | I want to add vowels to chars in a textbox.I created inputs and a function which adds the value of the vowel into the textbox : The thing is - the function adds the vowel into the last char in the textbox . I want the vowel to be entered after where the keyboard cursor of the user is standing.For example : textbox : He... | < textarea dir= '' rtl '' id= '' text '' runat= '' server '' name= '' text '' rows= '' 5 '' cols= '' 30 '' '' > < /textarea > < br / > < input type= '' button '' style= '' height:28px ; width:42px ; '' id= '' Dagesh '' value= '' דגש '' onclick= '' AddNikud ( & # 39 ; ּ & # 39 ; ) '' / > < script > function AddNikud ( n... | Add value to textbox where user is standing |
JS | Hello I am pretty new at JavaScript and I am a little stuck right now.The point of the project I 'm doing is to create a card object and have methods that set a new face and suit . When I click the button to show my card it works however when I click the button to update my face and suit and reclick the button to show ... | < ! DOCTYPE html > < html > < head > < title > Object Oriented Programming < /title > < script > function Card ( suit , face ) { this.suit = suit ; this.face = face ; this.card = face + ' of ' + suit ; this.showCard = function ( ) { alert ( this.card ) ; } this.setSF = function ( newSuit , newFace ) { this.suit = newSu... | trouble with updating my object |
JS | Google Chrome and Firebug give me two different outputs with this example.if b gets global , then first should give me undefined and second one 14. right ? but in firebug , it gives two 14s and Chrome gives reference error . | function a ( ) { b = 14 ; } console.log ( b ) ; a ( ) ; console.log ( b ) ; | Javascript : Two output when not using var keyword |
JS | I am working on a school project and we have to do a virtual static menu for a restaurant . What I 've done until now is this : when I click on a button , a PopUp shows up and it 's contained within the div with the class= '' menu '' . The thing is , that I stored all the menu items in a JSON file and thus I do n't kno... | < div class= '' menu '' > < h2 > Our Menu < /h2 > < ul > < li > < label > < div class= '' svg-container '' > < img class= '' arrow '' src= '' right-arrow.svg '' / > < /div > < span class= '' title '' > Fried Fish With Souce < /span > < div class= '' description '' style= '' display : none ; '' > This is some internal c... | How to see which element of menu has been pressed ? |
JS | I have recently been working on a comment feature . By default , the height of the paragraph element containing the text is 80px . Overflow is set to hidden.I have another button ( labelled `` See More '' ) that expands the paragraph by changing height to 'auto ' . This button should only be visible if the paragraph co... | < div class= '' commentOwnerPost '' > < div class= '' commentPostHeader '' > < h4 class= '' commentOwnerName '' > < a href= '' '' > NavyFoxKid < /a > < /h4 > < h4 class= '' commentPostDate '' > 3 days ago < /h4 > < /div > < p class= '' commentText '' > lorem ipsum dolor sit amet consectur lorem ipsum dolor sit amet con... | How to show child element when other child element is overflowing with JQuery |
JS | I have a String and want to replace it with other String as given in mssqlFunctions object.My String is : DateDiff ( m , Abs ( 23 ) [ Emy ( ) ] ) This is my code to replace StringSo it gives Output as DATEDIFF ( minute , ABS ( 23 ) [ Eminuteyear ( ) ] ) But I do n't want to replace string which is in [ ] So the Output ... | var mssqlFunctions = { DateDiff : `` DATEDIFF '' , Abs : `` ABS '' , y : 'year ' , m : 'minute ' } ; var regularExpression = new RegExp ( Object.keys ( mssqlFunctions ) .join ( `` | '' ) , '' gi '' ) ; formula = formula.replace ( regularExpression , function ( matched ) { return mssqlFunctions [ matched ] ; } ) ; | Regular Expression except [ Value ] |
JS | What is the difference between when I add a method to all instances of a class in the constructor viaas opposed to defining the function right in the class body ? If I simply replace this.baz with this.baz in the constructor , both tests return true : | this.bar = function ( ) { } baz ( ) { } class Foo { constructor ( ) { this.bar = function ( ) { } ; } baz ( ) { } } console.log ( Object.prototype.hasOwnProperty.call ( new Foo , 'bar ' ) ) ; // trueconsole.log ( Object.prototype.hasOwnProperty.call ( new Foo , 'baz ' ) ) ; // false class Foo { constructor ( ) { this.b... | Difference of methods defined on this in contrast to defined in class body |
JS | Having a code like this , I 'm wondering if I ran this function a second time , which scenario will happen : When emptying the # deals tag , all btn inside will get wiped as well despite the event on them and life is good.I have to unsubscribe from those btn first , otherwise emptying the # deals tag leads to a memory ... | function test ( ) { var row = $ ( this ) .closest ( 'tr ' ) ; $ ( row ) .find ( ' # deals ' ) .empty ( ) ; $ ( result ) .find ( ' # tab li a ' ) .each ( function ( ) { var btn = $ ( ' < a/ > ' , { class : 'btn ' , href : ' # ' } ) ; $ ( row ) .find ( ' # deals ' ) .append ( btn ) ; btn.click ( function ( event ) { even... | When emptying a tag , do the event-attached-buttons inside get garbage collected ? |
JS | I want to extract the path out of a URL and I want to use regex for it.I 'm using this regex : ^ ( ? : https ? : \/\/ ) ? ( ? : [ ^ @ \n ] + @ ) ? ( ? : www\. ) ? ( [ ^ : \n\ ? \=ֿ\ # ] + ) and one side effect that the last / is captured.e.g . -how do I validate that the last character of a specific capture group is no... | domain.com/home/ = domain.com/home/domain.com/home ? param=value = domain.com/home | How to validate the last character in a capture group with regex |
JS | I 'm having issues using external resources in a Puppeteer job that I 'm running with a full Chrome executable ( not the default Chromium ) . Any help would be massively appreciated ! So for example , if I load a video with a public URL it fails even though it works fine if I hit it manually in the browser.Here 's my P... | const videoElement = document.createElement ( 'video ' ) ; videoElement.src = src ; videoElement.onloadedmetadata = function ( ) { console.log ( videoElement.duration ) ; } ; ( async ( ) = > { const browser = await puppeteer.launch ( { args : [ ' -- remote-debugging-port=9222 ' , ' -- autoplay-policy=no-user-gesture-re... | External resources in Puppeteer with Chrome executable fail to load ( net : :ERR_EMPTY_RESPONSE ) |
JS | I have a function that divides two input arguments : I have a second function that takes the divide function as its input argument and returns a new function . I am expecting the returned value to be 8 ( 24 / 3 ) . But I 'm getting a returned output of 'NaN ' . What am I doing wrong ? | const divide = ( x , y ) = > { return x / y ; } ; function test ( func ) { return function ( ) { return func ( ) ; } } const retFunction = test ( divide ) ; retFunction ( 24 , 3 ) | JavaScript : Accept Division Function as Argument Into Another Function That Returns New Function -- > Returns Quotient |
JS | How can I center text both horizontally and vertically on a D3.js SVG grid rect ? Here is the example I am trying to get working : https : //jsfiddle.net/djangofan/koc74p9x/4/And here is what it looks like . I want the 'Gm ' text to be centered in the first cell . If I try to adjust down , the text disappears as it pas... | var columnText = row.selectAll ( `` .column '' ) // select .column val from data .data ( function ( d ) { return d ; } ) .enter ( ) .append ( `` text '' ) .text ( function ( d ) { return d.chord ; } ) .attr ( `` x '' , function ( d ) { return d.x ; } ) .attr ( `` y '' , function ( d ) { return d.y ; } ) .style ( `` fil... | How can I center text on a D3.js SVG grid rect ? |
JS | I have several `` event '' classes covering some of my svg elements . I 'm assigning each class an event handler for mouseover and mouseout , and if an element has more than one class , I want both handlers to fire . How do I do this ? It seems that when I dothen when I hover over an element that has both classes , onl... | d3.selectAll ( `` .a-class '' ) .on ( `` mouseover '' , function ( ) { // do A } ) .etc ( ) ; d3.selectAll ( `` .another-class '' ) .on ( `` mouseover '' , function ( ) { // do B } ) .etc ( ) ; | Giving an element more than one event handler by selecting it using different selectors |
JS | I have a menu on my page and am currently writing the script that sets all the click events for the menu buttons . Each button will call its own method so it must be set explicitly.My question , quite simply , is which of the following two methods is better to use in this situation : Or : I would have thought option 1 ... | $ ( document ) .on ( 'click ' , ' # menu .button ' , function ( ) { switch ( $ ( this ) .attr ( 'id ' ) ) { case 'foo_button ' : // Set the event for the foo button break ; case 'bar_button ' : // Set the event for the bar button break ; // And the rest of the buttons } } ) ; $ ( document ) .on ( 'click ' , ' # foo_but... | Multiple on ( ) or switch ( ) within one on ( ) |
JS | I am trying to make only one h2 element to be open at a time . If I already have an open one and I click on another one , the previous one should hide itself . I have tried creating an Array and use for loop to check each h2 element if it 's open or not . My for loop checks only one h2 instead of all 3 how I can fix it... | `` use strict '' ; var $ = function ( id ) { return document.getElementById ( id ) ; } ; // the event handler for the click event of each h2 elementvar toggle = function ( ) { var h2 = this ; // clicked h2 tag var div = h2.nextElementSibling ; // h2 tag 's sibling div tag var hello = document.getElementsByTagName ( `` ... | How I can show one h2 at a time , if another h2 selected close current one ? |
JS | dataWrong gets the errorIn cases like above , how to get dataWrong infer right type in typescript ? Is type assertion ( better type guards ) the only way ? | interface CustomResponse { data : string ; status : number ; [ key : string ] : string | number ; } const RESPONSE_PROPS = { DATA : `` data '' , STATUS : `` status '' , } ; const response : CustomResponse = { data : `` test '' , status : 200 , } ; let dataWrong : string = response [ RESPONSE_PROPS.DATA ] ; let dataRigh... | Typescript type inference on dynamically accessed object properties |
JS | I am working on a simple slider , yet I am facing trouble to make it stop when it reaches its limits.So basically , I want the the lever element to stop in the top and bottom positions , even if the user tries to surpass it.I would like to avoid anything other than pure JS and/or ECMA code.Here 's my small project : | s_Title.innerHTML = `` mySlider '' ; dragSlider ( document.getElementById ( `` mySlider '' ) ) ; var maxPos = document.getElementById ( `` s_Groove '' ) .offsetTop - ( s_Lever.offsetHeight/2 ) ; var minPos = document.getElementById ( `` s_Groove '' ) .offsetTop + document.getElementById ( `` s_Groove '' ) .offsetHeight... | Limit top and bottom of a slider |
JS | Been reading the docs in Vutify for their v-simple-table and v-data-table and I am trying to figure out if there is a way to add a row highlight like you can for a v-data-table.Such as this ? Vuetify - How to highlight row on click in v-data-tableMy table body looks like this : I can hover a row and it will show that t... | < v-simple-table dense fixed-header height= '' 90vh '' > < template v-slot : default > < thead > < tr > < th style= '' font-size : 16px ; height : 40px ; '' width= ' 4 % ' class= '' black -- text '' > Location < /th > < template v-if= '' Object.keys ( arrAvailableDates ) .length '' > < th style= '' font-size : 17px ; `... | Vuetify v-simple-table Highlight Selected Row |
JS | I have a select Box for selecting country code : -It gets populated using javascript and gets options like follows : -Now I want to select the value only +91.I was trying this But this returns the Full value with Country.How can I achieve this ? | < div class= '' selectWrap '' > < select name= '' countryCode '' id= '' countryCode '' > < /select > < /div > < option data-phone-code= '' +91 '' > 91 & nbsp ( India ) < /option > var country = document.getElementById ( `` countryCode '' ) ; var prefix = country.options [ country.selectedIndex ] .value ; | selecting proper value from attribute |
JS | I believe intellisense can solve a lot of time and bugs . Lets say I make an ajax call and I know I will get an array of cars.I need something that will return true in visual studio editor and false in the browser . if ( document.designMode ) returns true in VS and in the browser so the line car = { type : `` '' , mode... | $ .ajax ( { type : `` POST '' , url : `` GetCars.aspx '' , success : function ( cars ) { for ( var i = 0 ; i < cars.length ; i++ ) { var car = cars [ i ] ; if ( document.designMode ) { car = { type : `` '' , model : 0 , colors : new Array ( ) } ; } // Intelissense wors great in here ! // car . `` the moment I type the ... | How to know if JS code is executing in browser or in design mode |
JS | I have tried the code before , but when I hold down W it repeats the code , but I want to so if I hold it down , it will only execute the code one . | window.addEventListener ( `` keydown '' , checkKeyPressW , false ) ; var player = document.getElementById ( `` player '' ) ; var leftMarginCounter = 0 ; var bottomMarginCounter = 0 ; var leftMarginCounterToString = `` '' ; function checkKeyPressA_D ( keyPressed ) { if ( keyPressed.keyCode == `` 97 '' ) { if ( player.st... | How can I fire a event when a key is pressed down |
JS | While I was just playing around with JS , I wrote following snippet : I see output as `` 3 `` , however I was expecting out put as `` overloaded 3 '' . But I does not happen , however if I just swap the postions of those method , it does happen.Whats the rationale behind it ? | function checkArgs ( abc , nbn , jqrs ) { console.log ( `` overloaded `` +arguments.length ) ; } function checkArgs ( abc ) { console.log ( arguments.length ) ; } checkArgs ( `` aa '' , '' lll '' , '' pp '' ) ; function checkArgs ( abc ) { console.log ( arguments.length ) ; } function checkArgs ( abc , nbn , jqrs ) { c... | Does Javascript choose nearest method physically when it comes to overloading ? |
JS | This is some event handling for a list of items in my dom . Using event delegation , the click handler is on the parent containerAny ideas ? Any help is appreciated . | $ ( `` # list '' ) .on ( `` click '' , `` a '' , ( event ) = > { event.preventDefault ( ) ; event.stopImmediatePropagation ( ) ; let text = $ ( this ) .parent ( ) .children ( ) .last ( ) .text ( ) ; // The following HAS content ( seen in the dev tools debugger ! ! ! ! ) // $ ( this ) .parent ( ) .children ( ) .last ( )... | Ca n't assign text value to a variable from JQuery element in event handler |
JS | From my Chrome interpreter : Of course , a is not an object , and I can not assign new members to something that is n't an object . But , why does the interpreter swallows the a.f assignment if after that the method or the member does n't even exist ? | a = 3 ; // OK , of course.a.f = function ( ) { return 4 ; } ; // OK. To a number ? Oka ; // Prints 3a.f ( ) ; // f is not a function.a.f ; // Undefined | Assigning a function to a member of a number , why is that not a failure ? |
JS | Equal heights and baseline are not a problem . However , if I 'd like a hover effect on the element that displays the text with a differing font size , it is shifted out of alignment . I 'm willing to use Javascript or any other solution , but am having trouble finding a way to fix the element that has the hover effect... | .wrapper { height : 50px ; display : flex ; align-items : baseline ; } .column { height : 100 % ; display : flex ; align-items : center ; } .span1 , .span2 { height : 100 % ; display : inline-flex ; align-items : flex-end ; } .span1 : hover , .span2 : hover { background-color : gray ; } .span1 { justify-content : flex-... | Is there any way to have flexbox equal height columns with baseline font alignment of text with varying font sizes and font familys ? |
JS | I need to incorporate some JS in my php.html page , and I am having a difficult time trying to debug . I have been googling but ca n't seem to find how to print line numbers , like __LINE__ in php . Is there a way to achieve this seemingly useful feat easily enough ? Another problem I have is , I am trying to debug a s... | function alertDebug ( linesToDisable ) { var newLinesToDisable = new String ( ) ; for ( var n = 0 ; n < linesToDisable.length ; n++ ) { if ( n % 100 == 0 ) newLinesToDisable += `` \n '' ; newLinesToDisable += aString [ n ] ; } alert ( newLinesToDisable ) ; } alertDebug ( linesToDisable ) ; | trouble printing line numbers and ` alert ` ing long string vars to debug JS script block |
JS | I am importing data from json like thiswhere data.json looks somewhat similar to thisso to use it in my file I 'd usually do something like data.data [ 0 ] .title which in my opinion is not the cleanest way , ideally I 'd like to use it like data [ 0 ] .title is there a way I can include or edit my json file to acheive... | import data from './data.json ' { `` data '' : [ { `` title '' : `` Some title '' , `` text '' : `` Some text '' } , { `` title '' : `` Some title '' , `` text '' : `` Some text '' } , { `` title '' : `` Some title '' , `` text '' : `` Some text '' } ] } | Cleaning up json includes and usage |
JS | i want to get each link 's text and add it to link as ID . here is my navbar code : | < div class= '' navbar '' > < ul > < li > < a href= '' # '' > link1 < /a > < /li > < li > < a href= '' # '' > link2 < /a > < /li > < li > < a href= '' # '' > link3 < /a > < /li > < li > < a href= '' # '' > link4 < /a > < /li > < li > < a href= '' # '' > link5 < /a > < /li > < /ul > < /div > | getting each line text in navbar and add as id |
JS | I developed a UI where you will click a card it will pop up but inside that card there are two links on which when I click it should not pop back . I know that those links are part of that card and I put an event on the card selector . So I want to achieve this scenario : When user clicks on a card no matter where ... ... | var card = $ ( '.card ' ) ; card.click ( function ( ) { if ( $ ( this ) .hasClass ( 'gravitate ' ) ) { $ ( this ) .removeClass ( 'gravitate ' ) ; $ ( this ) .addClass ( 'levitate ' ) ; } else { $ ( this ) .addClass ( 'gravitate ' ) ; $ ( this ) .removeClass ( 'levitate ' ) ; } } ) ; * { padding : 0 ; margin : 0 ; } bod... | On clicking on a specific child a different jQuery should run |
JS | Given the following code , why does n't ( obj.foo ) ( ) receive window as this ? It seems to me like the parentheses are ignored , rather than treated as an expression that evaluates to foo ? | window.bar = 'window ' ; const obj = { bar : 'obj ' } ; obj.foo = function ( ) { console.log ( ` Called through $ { this.bar } ` ) ; } obj.foo ( ) ; // Called through obj ( obj.foo ) ( ) ; // Called through obj - Why ? ( 0 , obj.foo ) ( ) ; // Called through window ( true & & obj.foo ) ( ) ; // Called through window | Are parentheses ignored if they only contain a property accessor ? |
JS | React NOOB issue I 'm having : I have a JSX file that uses Axios to make an API call : fetch-api-data.jsx : I have a component that references that API call : share-my-story.jsxHowever , when webpack compiles the items and they are run in the browser , I get the following error : TypeError : Can not read property 'shar... | import * as axios from 'axios ' ; export class FetchApiData { constructor ( ) { console.log ( 'FetchAPIData loaded ' ) ; } shareMyStoryData ( URL ) { return axios.get ( URL ) .then ( function ( response ) { console.log ( response.data ) ; } ) .catch ( function ( error ) { console.log ( error ) ; } ) ; } } import * as R... | Trouble Loading Method in React Component |
JS | Working on my Project for class , and I have came across an issue . I debugged the issue , but I 'm unsure why it happens . The issue seem to only limit the img showed to two all the time during the process of creating the table . ieIt removes the first img and append it to the created cell . Sorry if I 'm not making a... | < tr > < td > img < /td > < td > img2 < /td > < /tr > < tr > < td > < /td > < td > img2 < /td > < td > img < /td > < /tr > var ImgSrcB = document.createElement ( `` img '' ) ; ImgSrcB.src = `` Black.png '' ; var ImgSrcW = document.createElement ( `` img '' ) ; ImgSrcW.src = `` White.png '' ; var body = document.body , ... | Javascript Img Table Creation Issue |
JS | I am trying to get the value of very next element of the current/selected element for example here is the listFrom the above code I am trying to get the value of `` a '' tag which is very next to the selected li , in above case I am try to get the value of a tag which is test1 and this `` a '' tag is within the very ne... | < ul > < li class= '' abc selected '' > < a href= '' www.test.com '' > test < /a > < /li > < li class= '' abc '' > < a href= '' www.test1.com '' > test1 < /a > < /li > < li class= '' abc '' > < a href= '' www.test2.com '' > test2 < /a > < /li > < /ul > var linktext1= jQuery ( `` .selected '' ) .next ( `` li a '' ) .tex... | Trying to get the value of very next element of the current selected element using jQuery |
JS | Please see this PlunkerI have an html that uses custom angular directiveand my directive looks like this : In my opinion , the pre of compile should execute bofore the template is returned and value should be set to `` Sample Attribute '' . But it 's not getting evaluated.Expected OutputActual OutputIs there any other ... | < body ng-controller= '' myCtrl '' > < h1 > Hello Plunker ! < /h1 > < div > < sample attributeone= '' Sample Attribute '' > < /sample > < /div > < /body > myApp.directive ( 'sample ' , function ( ) { var value = `` '' ; return { replace : true , restrict : ' E ' , scope : false , template : ' < div > This is a sample P... | Directive 's template does n't get value that 's set by compile |
JS | After a very long search i have found this strange behaviour : See fiddle : https : //jsfiddle.net/723xhcrf/When you create an element with params the width and height ( maybe more ) are added to the style argument like so : GivesBut when you already have a style something strange happens based on the order of the keys... | $ ( ' < div > ' , { 'width ' : '50px ' , 'height ' : '50px ' } ) ; < div style= '' width : 50px ; height : 50px ; '' > $ ( ' < div > ' , { 'width ' : '50px ' , 'style ' : 'background-color : blue ; ' , 'height ' : '50px ' } ) < div style= '' background-color : blue ; height : 50px ; '' > $ ( ' < div > ' , { 'height ' :... | jQuery element creation removes witdh and height when style attribute is ordered after width or height |
JS | I have worked with javascript during 2 years now , but I have never seen an expression like this one . in google chrome console I have typed thisthen I typed this and the result was 989can someone tell me what is this expression for , and why is the result 989 ? | var a=456 ; var b=789 ; a|=b | what is this javascript expression for |
JS | I create the class user where i just only define the get method but when i call the class in middleware and use it , it not show any error but when i run the code it show server not found . when i del this line app.use ( userRoute ) my server work.users.tsapp.ts | import { NextFunction , Request , Response } from 'express ' ; import { Controller , Get , Req , Res } from 'routing-controllers ' @ Controller ( ) class User { @ Get ( '/signup ' ) signUP ( @ Req ( ) req : Request , @ Res ( ) res : Response , next : NextFunction ) { return res.render ( 'signup ' ) } ; } export { User ... | how can Export the class and define middleware in typescript |
JS | While working on this example at MDN site explaining the filter method : This gets output in FireBug , as expected : But I initially , errantly but intentionally typed the first console.log ( ) ; statement as : and got this FireBug output : Why the different outputs ? | var arr = [ { id : 15 } , { id : -1 } , { id : 0 } , { id : 3 } , { id : 12.2 } , { } , { id : null } , { id : NaN } , { id : 'undefined ' } ] ; var invalidEntries = 0 ; function isNumber ( obj ) { return obj ! == undefined & & typeof ( obj ) === 'number ' & & ! isNaN ( obj ) ; } function filterByID ( item ) { if ( isN... | two different outputs using the + vs , concatenating methods |
Python | I want to draw a 3D line of points with different color in the Z turn.I use the Visual Studio 2013 with Python and I have to read an .json ( XML-Style ) file and draw it ( X , Y , Z ) to a 3D Diagram.So I got a curve with one color : I want to have it like this : I have a 3 dimension numpy array , but when I write this... | matrix_array = [ [ 0,0,0 ] ] ... - > write data in array ... .matrix_array = np.array ( matrix_array ) fig = pyplot.figure ( ) ax3d = fig.add_subplot ( 111 , projection='3d ' ) N = len ( matrix_array [ : ,2 ] ) # Z ( N now about 14689 ) for i in xrange ( N-2 ) : ax3d.plot ( matrix_array [ i+2,0 ] , matrix_array [ i+2,1... | Line colour of 3D curve from an array with matplotlib |
Python | First off , apologies for the confusing title . What I am trying to achieve is the following : Suppose I have some function foo which takes a function and an integer as input . e.g . Now , I 'd like to wrap this function in a python extension module . So I start writing my interface : Now , when it comes time to parse ... | int foo ( int ( *func ) ( ) , int i ) { int n = func ( ) + i ; return n ; } # include < Python.h > extern `` C '' { static PyObject* foo ( PyObject* self , PyObject* args ) ; } static PyMethodDef myMethods [ ] = { { `` foo '' , foo , METH_VARARGS , `` Runs foo '' } , { NULL , NULL , 0 , NULL } } // Define the modulesta... | When writing a python extension in C , how does one pass a python function in to a C function ? |
Python | The problem is : I try to play Fast Tracker module in infinite loop , but doing so just replay music from start , instead of following repeat position . Example : ( here 's the source for module https : //api.modarchive.org/downloads.php ? moduleid=153915 # zeta_force_level_2.xm ) What I 'm trying to achieve : Play mod... | import pygamepygame.mixer.init ( ) pygame.mixer.music.load ( '/path/to/zeta_force_level_2.xm ' ) pygame.mixer.music.play ( -1 ) | pygame.mixer.music.play ( ) does n't recognize Fast Tracker ( .xm music format ) repeat position |
Python | I 'm new using pyparsing , but I ca n't find how to solve this quite easy issue . I have ( for the moment ) a simple grammar , but I can ' t find the way to discriminate the result of parsing according the types I defined in my grammar.Maybe it ' d be easier to explain it with an example . Supposing this element : When... | elem = foo | bar elem.parseString ( `` ... '' ) | Type checking on results with pyparsing |
Python | I have a vtk file containing a 3d model , I would like to extract the point coordinates and the facets.Here is a minimal working example : This works as numpy_nodescontains the x , y , z coordinates of all points , but I am at loss to retrieve the list that relates the facets of this model to the corresponding points.I... | import vtkimport numpyfrom vtk.util.numpy_support import vtk_to_numpyreader = vtk.vtkPolyDataReader ( ) reader.SetFileName ( 'test.vtk ' ) reader.Update ( ) polydata = reader.GetOutput ( ) points = polydata.GetPoints ( ) array = points.GetData ( ) numpy_nodes = vtk_to_numpy ( array ) facets= polydata.GetPolys ( ) array... | Retrieving facets and point from VTK file in python |
Python | I 'm trying to find the location of a substring within a string that contains wildcards . For example : thank you in advance | substring = 'ABCDEF'large_string = 'QQQQQABC.EFQQQQQ'start = string.find ( substring , large_string ) print ( start ) 5 | String Matching with wildcard in Python |
Python | I 'm experimenting with pydub , which I like very much , however I am having a problem when splitting/joining an mp3 file.I need to generate a series of small snippets of audio on the server , which will be sent in sequence to a web browser and played via an < audio/ > element . I need the audio playback to be 'seamles... | song = AudioSegment.from_mp3 ( 'my.mp3 ' ) song_pos = 0while song_pos < 100 : p1 = song_pos * 1000 p2 = p1 + 1000 segment = song [ p1 : p2 ] # 1 second of audio output = StringIO.StringIO ( ) segment.export ( output , format= '' mp3 '' ) client_data = output.getvalue ( ) # send this to client song_pos += 1 socket.send ... | pydub audio glitches when splitting/joining mp3 |
Python | I 'm learning pyramid and it seems they are trying to get people to use chameleon instead of mako so I thought I 'd give chameleon a chance . I like it so far and I can do basic things in the template such as if and for loops but I 'm not sure how to get message flashes to appear.In the pyramid tutorial they do this in... | % if request.session.peek_flash ( ) : < div id= '' flash '' > < % flash = request.session.pop_flash ( ) % > % for message in flash : $ { message } < br > % endfor < /div > % endif | How can my chameleon template accept message flashes from the pyramid framework ? |
Python | How can I get subprocess.check_call to give me the raw binary output of a command , it seems to be encoding it incorrectly somewhere.Details : I have a command that returns text like this : ( Those quotes are unicode e2809d ) Here 's how I 'm calling the command : The problem is I get this : ( And if I call 'ord ' the ... | some output text “ quote ” ... f_output = SpooledTemporaryFile ( ) subprocess.check_call ( cmd , shell=True , stdout=f_output ) f_output.seek ( 0 ) output = f_output.read ( ) > > > repr ( output ) some output text ? quote ? ... > > > type ( output ) < str > | Python not getting raw binary from subprocess.check_call |
Python | I have a problem with my python code . What I want is that each process writes in one dictionary . What I get is that every process writes into his own dictionary.To make it clear : After running the code : I get this output : What I want is : Here is my sample Code : It 'd be great if you could tell me what 's going w... | P 0 : { 0 : 1 } P 2 : { 2 : 1 } P 4 : { 4 : 1 } P 6 : { 6 : 1 } P 8 : { 8 : 1 } All : { } P 0 : { 0 : 1 } P 2 : { 2 : 1 } P 4 : { 4 : 1 } P 6 : { 6 : 1 } P 8 : { 8 : 1 } All : { 0 : 1 , 2 : 1 , 4 : 1 , 6 : 1 , 8 : 1 } from multiprocessing import Process , Lock , cpu_countclass multiprocessingExample ( ) : global d d = ... | How to gather results from multiprocesses ? |
Python | Using the attrs libary and Python 3.6 , I thought the following would allow me to specify that x and y can only contain integers : Both of the commented lines throw a NameError : name 'List ' is not defined.The reasons I expected that to work are these : ( 1 ) The types section of the attr documentation includes the fo... | import attr @ attr.sclass C : x : List [ int ] = attr.ib ( ) # not working y = attr.ib ( type=List [ int ] ) # not working either @ attr.sclass C : x = attr.ib ( type=int ) y : int = attr.ib ( ) | How to specify that an attribute must be a list of ( say ) integers , not just a list ? |
Python | I 'm working on a python project that uses cython and c to speed up time sensitive operations . In a few of our cython routines , we use openmp to further speed up an operation if idle cores are available.This leads to a bit of an annoying situation on OS X since the default compiler for recent OS versions ( llvm/clang... | clang : error : linker command failed with exit code 1 ( use -v to see invocation ) error : Command `` cc -bundle -undefined dynamic_lookup -L/usr/local/lib -L/usr/local/opt/sqlite/lib build/temp.macosx-10.8-x86_64-2.7/yt/utilities/lib/geometry_utils.o -lm -o yt/utilities/lib/geometry_utils.so -fopenmp '' failed with e... | Programatically testing for openmp support from a python setup script |
Python | Trying to strip the `` 0b1 '' from the left end of a binary number.The following code results in stripping all of binary object . ( not good ) So I did the .lstrip ( ) in two steps : What 's the deal ? Thanks again for solving this in one simple step . ( see my previous question ) | > > > bbn = '0b1000101110100010111010001 ' # converted bin ( 2**24+**2^24/11 ) > > > aan=bbn.lstrip ( `` 0b1 '' ) # Try stripping all left-end junk at once. > > > print aan # oops all gone . '' > > > bbn = '0b1000101110100010111010001 ' # Same fraction expqansion > > > aan=bbn.lstrip ( `` 0b '' ) # Had done this before... | Removing a prefix from a string |
Python | If I define my function as below : then myfunc == myfunc will return TrueBut functools.partial ( myfunc , arg2=1 ) == functools.partial ( myfunc , arg2=1 ) will return False.For unittest purpose , is there an easy way to test if the partial function is the one I expect ? | def myfunc ( arg1 , arg2 ) : pass | How to compare wrapped functions with functools.partial ? |
Python | I am asking here because I have n't gotten any help from the OpenCV developers so far . I reduced the problem to a very simple test case so probably anyone with some background with CPython could help here.This C code does not leak : This Python code does leak : I searched through the CPython code ( of OpenCVs current ... | int main ( ) { while ( true ) { int hist_size [ ] = { 40 } ; float range [ ] = { 0.0f,255.0f } ; float* ranges [ ] = { range } ; CvHistogram* hist = cvCreateHist ( 1 , hist_size , CV_HIST_ARRAY , ranges , 1 ) ; cvReleaseHist ( & hist ) ; } } while True : cv.CreateHist ( [ 40 ] , cv.CV_HIST_ARRAY , [ [ 0,255 ] ] , 1 ) s... | OpenCV : memory leak with Python interface but not in the C version |
Python | I have the following code for logging in on a site and post something in a forumWhen I try and use another browser ( like firefox ) it works fine , but with phantom nothing is posted.What I believe could be the problem is that phantom does n't fill in the tinymce textarea as i want it to . is there any fix for this pro... | driver = webdriver.PhantomJS ( ) Username = `` username '' Password = `` password '' driver.get ( LoginPage ) WebDriverWait ( driver , 10 ) .until ( EC.presence_of_element_located ( ( By.ID , `` login '' ) ) ) driver.find_element_by_name ( `` usr '' ) .send_keys ( Username ) driver.find_element_by_name ( `` pas '' ) .s... | handle tinymce window with python , selenium and phantomjs |
Python | I am trying to repeat the following curl request : with poster usage : But looks like image field is passed as single field , when array should be passed . Usage of image [ 0 ] as name does n't help.How can I fix it ? | curl -i -k -H `` Content-Type : multipart/form-data '' \ -F `` method=uploadphoto '' \ -F `` version=1.2.3 '' \ -F `` format=json '' \ -F `` image [ 0 ] = @ /Users/user/Downloads/file.jpeg '' \ https : //example.com/api from poster.encode import multipart_encode , MultipartParamfile_content = open ( '/Users/user/Downlo... | How to upload file as array element with poster ? |
Python | These are the logical steps that I need to perform on my list of listssort the list of lists in such a way that the output looks something liketake the coordinates of the sorted elements in the original list , which in this case should produce as outputI tried using of sort , sorted and argwhere in different ways but I... | a = [ [ 5,2 ] , [ 7,4 ] , [ 0,3 ] ] 7,5,4,3,2,0 ( 1,0 ) ( 0,0 ) ( 1,1 ) ( 2,1 ) ( 0,1 ) ( 2,0 ) | sorting list of lists and getting indices in unsorted list |
Python | I have written some physics simulation code in C++ and parsing the input text files is a bottleneck of it . As one of the input parameters , the user has to specify a math function which will be evaluated many times at run-time . The C++ code has some pre-defined function classes for this ( they are actually quite comp... | f = WrappedCPPGaussianFunctionClass ( sigma=0.5 ) WrappedCPPAlgorithm ( f ) | Passing C++ object to C++ code through Python ? |
Python | It would appear that in Python , list += x works for any iterable x : Is this behaviour documented anywhere ? To contrast this with list + x , the latter only works if x is also a list . This is spelled out in the documentation . | In [ 6 ] : l = [ ] In [ 7 ] : l += [ 1 ] In [ 8 ] : l += ( 2 , 3 ) In [ 9 ] : l += xrange ( 5 ) In [ 10 ] : lOut [ 10 ] : [ 1 , 2 , 3 , 0 , 1 , 2 , 3 , 4 ] | Is the behaviour of Python 's list += iterable documented anywhere ? |
Python | I want to slice a multi-index pandas dataframehere is the code to obtain my test data : gives : Now I can get only sum for A or B using which gives How can I get both sum and count for only A or B | import pandas as pdtestdf = { 'Name ' : { 0 : ' H ' , 1 : ' H ' , 2 : ' H ' , 3 : ' H ' , 4 : ' H ' } , 'Division ' : { 0 : ' C ' , 1 : ' C ' , 2 : ' C ' , 3 : ' C ' , 4 : ' C ' } , 'EmployeeId ' : { 0 : 14 , 1 : 14 , 2 : 14 , 3 : 14 , 4 : 14 } , 'Amt1 ' : { 0 : 124.39 , 1 : 186.78 , 2 : 127.94 , 3 : 258.35000000000002... | pandas slicing multiindex dataframe |
Python | My project includes a large C++ library and Python bindings ( via Boost.Python ) . The test suite is mostly written on top of the Python bindings , and I would like to run it with sanitizers , starting with ASAN.I 'm running macOS ( 10.13.1 FWIW , but I had the problem with previous versions too ) , and I ca n't seem t... | // hello_ext.cc # include < boost/python.hpp > char const* greet ( ) { auto* res = new char [ 100 ] ; std : :strcpy ( res , `` Hello , world ! `` ) ; delete [ ] res ; return res ; } BOOST_PYTHON_MODULE ( hello_ext ) { using namespace boost : :python ; def ( `` greet '' , greet ) ; } // MakefileCXX = clang++-mp-4.0CXXFL... | Address sanitizing Boost.Python modules |
Python | I 'm using BeautifulSoup to build xml files.It seems like my two are options are 1 ) no formatting i.e.or 2 ) with prettify i.e.But i would really prefer it to look like this : I realise i could hack bs4 to achieve this result but i would like to hear if any options exist.I 'm less bothered about the 4-space indent ( a... | < root > < level1 > < level2 > < field1 > val1 < /field1 > < field2 > val2 < /field2 > < field3 > val3 < /field3 > < /level2 > < /level1 > < /root > < root > < level1 > < level2 > < field1 > val1 < /field1 > < field2 > val2 < /field2 > < field3 > val3 < /field3 > < /level2 > < /level1 > < /root > < root > < level1 > < ... | BeautifulSoup Prettify custom new line option |
Python | I have a vector of size = N where each element i can have values from 0 to possible_values [ i ] -1 . I want to do a function that iterates me through all those values.I was able to do that in Python using a recursive generator : Example output : Since C++ does n't have the Python 's yield I do n't know what is the rig... | def all_values ( size , values , pos=0 ) : if pos == size : yield [ ] else : for v in xrange ( values [ pos ] ) : for v2 in all_values ( size , values , pos+1 ) : v2.insert ( 0 , v ) yield v2possible_values= [ 3,2,2 ] for v in all_values ( 3 , possible_values ) : print v [ 0 , 0 , 0 ] [ 0 , 0 , 1 ] [ 0 , 1 , 0 ] [ 0 , ... | Recursive generator in C++ |
Python | I have 4 modules : entry_point.pyutils.pyrunner.pyclient.pyI use argparse in utils.py and I want to be able to retrieve the value of one of those arguments in client.py . Entry point module ( the one that gets called from console ) : utils.py module : runner.py module : client.py module : I do n't want to pass url as a... | import utilsdef main ( ) : console_args = utils.parse_arguments ( ) # Get command-line arguments runner.run ( console_args ) # The main function in the programif __name__ == '__main__ ' : main ( ) def parse_arguments ( ) : parser = argparse.ArgumentParser ( ) parser.add_argument ( # Several arguments , one of which sho... | Access argparse variables from external module |
Python | In general , Python sets do n't seem to be designed for retrieving items by key . That 's obviously what dictionaries are for . But is there anyway that , given a key , you can retrieve an instance from a set which is equal to the key ? Again , I know this is exactly what dictionaries are for , but as far as I can see ... | class Person : def __init__ ( self , firstname , lastname , age ) : self.firstname = firstname self.lastname = lastname self.age = age | Python : Retrieve items from a set |
Python | I have a rather long text parsed by Spacy into a Doc instance : doc here becomes a Doc class instance . Now , since the text is huge , I would like to process , experiment and visualize in a Jupyter notebook using only just one part of the document - for instance , first 100 sentences . How can I slice and create a new... | import spacynlp = spacy.load ( 'en_core_web_lg ' ) doc = nlp ( content ) | Extracting a part of a Spacy document as a new document |
Python | I want to use next to skip one or more items returned from a generator . Here is a simplified example designed to skip one item per loop ( in actual use , I 'd test n and depending on the result , may repeat the next ( ) and the generator is from a package I do n't control ) : I expected the result to beetc.Instead I g... | def gen ( ) : for i in range ( 10 ) : yield ifor g in gen ( ) : n = next ( gen ( ) ) print ( g , n ) 0 12 3 0 01 0 | Python : next in for loop |
Python | I 'm using the new print from Python 3.x and I observed that the following code does not compile due to the end= ' '.How can I continue using the new syntax but make the script fails nicely ? Is it mandatory to call another script and use only safe syntax in this one ? | from __future__ import print_functionimport sysif sys.hexversion < 0x02060000 : raise Exception ( `` py too old '' ) ... print ( `` x '' , end= '' `` ) # fails to compile with py24 | How to write a Python 2.6+ script that gracefully fails with older Python ? |
Python | I have a form , after entering the information , based on infomation it filters the database and do some calculation and finally displays the result to a redirected url.I can indeed redirect to another url and displays the result successfully . But the issue is in the form it can not display any data submitted by user ... | url ( r'^result_list/ $ ' , ResultView.as_view ( ) , name='result ' ) , url ( r'^input/ $ ' , InputFormView.as_view ( ) , name='input ' ) , class InputFormView ( request ) : # class InputFormView ( FormView ) : template_name = 'inputform.html ' form_class = InputForm response = HttpResponse ( 'result ' ) request_form_d... | django- why after redirecting , the form display `` None '' |
Python | I want to make a legend where I specify the value for the markers and the value for the lines but not the combination of both.This example should help to illustrate my goal : The resulting figure is the followingWhat I wanted is a function_to_split to automatically end up with a legend like this : | import matplotlib.pyplot as pltimport numpy as nppi=3.14xx=np.linspace ( 0,2*pi,100 ) fig = plt.figure ( ) ax = fig.add_subplot ( 111 ) phases= [ 0 , pi/4 , pi/2 ] markers= [ 's ' , ' o ' , '^ ' ] for phase , mk in zip ( phases , markers ) : labeltext='Sine ' + '* ' + str ( phase ) F= [ np.sin ( x+phase ) for x in xx ]... | Split marker and line in Legend - Matplotlib |
Python | I 've extracted keywords based on 1-gram , 2-gram , 3-gram within a tokenized sentenceI 've obtained keywords list as How can I simply the results by removing all substring within the list and remain : | list_of_keywords = [ ] for i in range ( 0 , len ( stemmed_words ) ) : temp = [ ] for j in range ( 0 , len ( stemmed_words [ i ] ) ) : temp.append ( [ ' '.join ( x ) for x in list ( everygrams ( stemmed_words [ i ] [ j ] , 1 , 3 ) ) if ' '.join ( x ) in set ( New_vocabulary_list ) ] ) list_of_keywords.append ( temp ) [ ... | Python : Check if string and its substring are existing in the same list |
Python | I 'm fairly new to matplotlib and python in general and what I 'm trying to do is rather basic . However , even after quite some googling time I can not find a solution for this : Here is the problem : I 'd like to draw a circle with different color of the border and the face , i.e . set edgecolor and facecolor differe... | from matplotlib import pyplot as pltpoint = ( 1.0 , 1.0 ) c = plt.Circle ( point , 1 , facecolor='green ' , edgecolor='orange ' , linewidth=15.0 , alpha=0.5 ) fig , ax = plt.subplots ( ) ax.add_artist ( c ) plt.show ( ) | matplotlib Circle patch with alpha produces overlap of edge and facecolor |
Python | I have a string in python of the following form : You can get the idea . It actually takes a very similar form to python code itself , in that there is a line , and below that line , indentations indicate part of a block , headed by the most recent line of a lesser indentation.What I need to do is parse this code into ... | line aline b line ba line bb line bba line bcline c line ca line caaline d { 'line a ' = > { } , 'line b ' = > { 'line ba ' = > { } , 'line bb ' = > { 'line bba ' = > { } } , 'line bc ' = > { } } , 'line c ' = > { 'line ca ' = > { 'line caa ' = > { } } , } , 'line d ' = > { } } def parse_message_to_tree ( message ) : b... | converting a string to a tree structure in python |
Python | I have an API Key for a Google API that I would like to use in all my requests to it . Some of these requests will originate from within a Google App Engine ( Python 2.7 ) application . I had planned to use the UrlFetch library to complete the POST request , basically as follows : I had set a referrer restriction on my... | headers = { 'Content-Type ' : 'application/json ' } payload = { 'longUrl ' : request.long_url } result = urlfetch.fetch ( [ API_REQUEST_URL ] , method=urlfetch.POST , payload=json.dumps ( payload ) , headers=headers ) json_result = json.loads ( result.content ) | API Key Restriction for Google API Called from URL Fetch within App Engine |
Python | So I can create a reverse iterator on a list : I assume this simply calls getitem from index len ( ... ) -1 to 0 . But then I can not also do this : Now I am a bit confused . Does this create the list from xrange ( 4 ) and then reverse it ? If not , how does it know what the last element is and how to go backwards ? I ... | list ( reversed ( [ 0,1,2,3 ] ) ) [ 3 , 2 , 1 , 0 ] list ( reversed ( xrange ( 4 ) ) ) [ 3 , 2 , 1 , 0 ] | Does reverse actually reverse a Python iterator ? |
Python | I have : I want to multiply ( pairwise ) every element of a with bHere 's my code so far : so my plan of attack was to get all the lists in one list and then multiply everything together . I have seen that lambda work for multiplying lists pairwise but I ca n't get it to work for the one list . | a = [ [ 1,2 ] , [ 3,4 ] , [ 7,10 ] ] b = [ [ 8,6 ] , [ 1,9 ] , [ 2,1 ] , [ 8,8 ] ] 1*8+2*6+1*1+2*9+ ... ..+1*8+2*8+3*8+4*6+ ... ... +7*8+10*8 def f ( a , b ) : new = [ x for x in a or x in b ] newer = [ ] for tuple1 , tuple2 in new : newer.append ( map ( lambda s , t : s*t , new , new ) ) return sum ( newer ) | multiplying lists of lists with different lengths |
Python | I have the following dictionary { 44 : [ 0 , 1 , 0 , 3 , 6 ] } and need to convert this to dict1 = { 44 : { 0:0 , 1:1 , 2:0 , 3:3 , 4:6 } } but my current for loop does n't work : Can you help me ? Thanks in advance . | maxnumbers = 5 # this is how many values are within the listfor i in list ( range ( maxnumbers ) ) : for k in list ( dict1.keys ( ) ) : for g in dict1 [ k ] : newdict [ i ] = gprint ( num4 ) | Dictionary of lists to nested dictionary |
Python | I 'm having documentation bloat on me , as anytime I encounter a complex duck-type , I need some way to say `` this duck type '' but instead get caught in an endless cycle of `` your function requires this of this input , but does n't document it '' , and then documenting it . This results in bloated , repetitive docum... | def Foo ( arg ) : `` '' '' Args : arg : An object that supports X functionality , and Y functionality , and can be passed to Z other functionality. `` '' '' # Insert code here.def Bar ( arg ) : `` '' '' Args : arg : An object that supports X functionality , and Y functionality , and can be passed to Z other functionali... | How to document a duck type ? |
Python | This is the observed behavior : The expected output of list ( y [ 1 ] ) is [ 0,1,2,3,4,5,6,7,8,9 ] What 's going on here ? I observed this on cpython 3.4.2 , but others have seen this with cpython 3.5 and IronPython 2.9.9a0 ( 2.9.0.0 ) on Mono 4.0.30319.17020 ( 64-bit ) .The observed behavior on Jython 2.7.0 and pypy : | In [ 4 ] : x = itertools.groupby ( range ( 10 ) , lambda x : True ) In [ 5 ] : y = next ( x ) In [ 6 ] : next ( x ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -StopIteration Traceback ( most recent call last ) < ipython-input-6-5e4e57af3a97 > in < modu... | Unexpected Behavior of itertools.groupby |
Python | Motivation : I am trying to make a basic AI agent that can play chess against an opponent . The goal is to see how good it can become through the use of machine learning later on and also learn a the fine details in chess that are hidden from us when we just play it , such as evaluation parameters . Code : Here is what... | import chess , chess.pgn , time , math , ioimport numpy as np from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.action_chains import ActionChainsfrom selenium.webdriver.support.ui import Selectpiece_values = { ' P ' : 10 , ' N ' : 30 , ' B ' : 30 , ' R ' : 50 , ... | Python chess minimax algorithm - How to play with black pieces ( Bot has white ) |
Python | It seems that entities imported using two different PYTHONPATHs are not the same objects.I have encouneted a little problem in my code and I want to explain it with a little testcase.I created the source tree : in example.py : and from the parent of folder a , I run python and this test : So the question is : why the r... | a/ __init__.py b/ __init__.py example.py class Example : pass > > > import sys > > > sys.path.append ( `` /home/marco/temp/a '' ) > > > > > > import a.b.example as example1 > > > import b.example as example2 > > > > > > example1.Example is example2.ExampleFalse | Class imported from two different paths is not equal ? |
Python | What is the time complexity of checking membership in dict.items ( ) ? According to the documentation : Keys views are set-like since their entries are unique and hashable.If all values are hashable , so that ( key , value ) pairs are unique andhashable , then the items view is also set-like . ( Values views are nottre... | from timeit import timeitdef membership ( val , container ) : val in containerr = range ( 100000 ) s = set ( r ) d = dict.fromkeys ( r , 1 ) d2 = { k : [ 1 ] for k in r } items_list = list ( d2.items ( ) ) print ( 'set'.ljust ( 12 ) , end= '' ) print ( timeit ( lambda : membership ( -1 , s ) , number=1000 ) ) print ( '... | What is the time complexity of checking membership in dict.items ( ) ? |
Python | When I run this Python script with os.system on Ubuntu 12.04 : , and then I send SIGABRT to the script process many times within 5 seconds , I get the following output : This indicates that the signal delivery was blocked until sleep 5 exited , and then only a single signal was delivered.However , with subprocess.call ... | import os , signalsignal.signal ( signal.SIGABRT , lambda *args : os.write ( 2 , 'HANDLER\n ' ) ) print 'status= % r ' % os.system ( 'sleep 5 ' ) status=0HANDLER import os , signal , subprocesssignal.signal ( signal.SIGABRT , lambda *args : os.write ( 2 , 'HANDLER\n ' ) ) print 'cstatus= % r ' % subprocess.call ( 'slee... | How is Python blocking signals while os.system ( `` sleep ... '' ) ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.