id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23538600
I'm also attaching my xml layout file <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_calc" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.sameer.coolcalc.CalcActivity" tools:background="@android:color/background_light"> <LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:weightSum="6" android:layout_width="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:background="@android:color/holo_blue_bright" android:weightSum="1"> <EditText android:layout_width="match_parent" android:layout_height="match_parent" android:inputType="numberDecimal" android:ems="10" android:id="@+id/editText4" android:text="567" android:textSize="60sp" android:gravity="center_vertical|end" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:weightSum="4"> <Button android:text="7" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button14" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <Button android:text="8" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button13" android:layout_weight="1" android:textSize="36sp" android:textColor="@android:color/black" android:background="@android:color/background_light" /> <Button android:text="9" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button12" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <ImageButton android:layout_height="match_parent" app:srcCompat="@drawable/divide" android:id="@+id/imageButton6" android:layout_weight="1" android:layout_width="match_parent" android:background="@android:color/background_light" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> <Button android:text="4" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button3" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <Button android:text="5" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button2" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <Button android:text="6" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" app:srcCompat="@drawable/multiply" android:id="@+id/imageButton" android:layout_weight="1" android:background="@android:color/background_light" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:weightSum="4"> <Button android:text="1" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button6" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <Button android:text="2" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button5" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <Button android:text="3" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/button4" android:layout_weight="1" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" app:srcCompat="@drawable/subtract" android:id="@+id/imageButton3" android:layout_weight="1" android:background="@android:color/background_light" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> <LinearLayout android:orientation="horizontal" android:layout_height="match_parent" android:background="@android:color/background_light" android:layout_width="205dp" android:gravity="center"> <Button android:text="clear" android:id="@+id/button15" android:background="@android:color/holo_blue_bright" android:layout_width="170dp" android:layout_height="50dp" android:textSize="30sp" /> </LinearLayout> <Button android:text="0" android:layout_height="match_parent" android:id="@+id/button11" android:layout_width="103dp" android:background="@android:color/background_light" android:textColor="@android:color/black" android:textSize="36sp" /> <ImageButton android:layout_width="103dp" android:layout_height="match_parent" app:srcCompat="@drawable/add" android:id="@+id/imageButton5" android:background="@android:color/background_light" /> </LinearLayout> </LinearLayout> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/equal" android:id="@+id/imageButton7" android:background="@android:color/transparent" android:layout_alignParentEnd="true" android:layout_marginTop="140dp" /> </RelativeLayout> A: Use android:src instead of app:srcCompat.This will solve your problem for now. app:srcCompat comes from Android Support Library, also the support Vector Drawables and Animated Vector Drawables. If you want to use app:srCompat you should configure your gradle. android { defaultConfig { vectorDrawables.useSupportLibrary = true } } When using AppCompat with ImageView (or subclasses such as ImageButton and FloatingActionButton), you’ll be able to use the new app:srcCompat attribute to reference vector drawables (as well as any other drawable available to android:src) More info here: https://android-developers.googleblog.com/2016/02/android-support-library-232.html
doc_23538601
* *// "this->" can be omitted before first data[0] and *// Compile error, if "this->" is omitted before first data[0] and *// likewise, "this->" is required. I don't know why sometimes "this->" can be omitted, and sometime can't. The compile error is: main.cpp:19:3: error: 'data' was not declared in this scope Is it just a compiler bug? My compiler is GCC v4.8.1 and v4.8.2. Thanks. BTW, QtCreator's default intelli-sense, in fact, can recognize 'data[0]' without "this->" in all three places. Here's the code list: template <typename T> struct Vec3_ { T data[3]; inline Vec3_<T> & operator =(const Vec3_<T> & rhs) { if (this != &rhs) { data[0] = rhs.data[0]; // "this->" can be omitted before first data[0] data[1] = rhs.data[1]; data[2] = rhs.data[2]; } return *this; } }; template <typename T> struct Vec3i_: Vec3_<T> { inline Vec3i_<T> & operator ^=(const Vec3i_<T> & rhs) { data[0] ^= rhs.data[0]; // Compile error, if "this->" is omitted before first data[0] this->data[1] ^= rhs.data[1]; this->data[2] ^= rhs.data[2]; return *this; } inline Vec3i_<T> operator ^(const Vec3i_<T> & rhs) const { Vec3i_<T> tmp; tmp[0] = this->data[0] ^ rhs.data[0]; // likewise, "this->" is required. tmp[1] = this->data[1] ^ rhs.data[1]; tmp[2] = this->data[2] ^ rhs.data[2]; return tmp; } }; Vec3i_<int> A; int main(int, char**) { return 0; } == update == Since someone has pointed out a very similar question (may possibly a duplicate) and answers, and the title of that question is even descriptive, I changed my title similar to that one (except the parameter dependency difference) Yet after reading the answers to that question, I am still confused. The answers pointed to an FAQ [link here] saying that if a variable is a nondependent name, the compiler will not search for the name in the base template class. However, in this example, the variable (data) is a dependent name, since it is of type T, and T is the template variable. I am still open for answers.
doc_23538602
A: You can pass PhysicalResourceId of a resource to desribe_stack_resources and get the stack information if it belongs to a CF stack To find an EC2 host for example cf = boto3.client('cloudformation') cf.describe_stack_resources(PhysicalResourceId="i-07bd92638b049ccc4") AWS Documentation on this http://boto3.readthedocs.io/en/latest/reference/services/cloudformation.html#CloudFormation.Client.describe_stack_resources A: There is no single API to determine which stack a resource belongs to, however, a resource will be constructed with tags reflecting the origin stack. (AWS tagging is done through an internal service all the services communicate with, and they then expose that service through their own API.) Some resources don't support tagging at all, so you'd have to scan stacks for those. Three tags are added to resources generated by Cloudformation, and all of these names are reserved by AWS: * *aws:cloudformation:stack-name *aws:cloudformation:stack-id *aws:cloudformation:logical-id Cloudformation will let you look up a stack by its name or its ID. We shouldn't use the name, however. Preferably, you want to look up by stack-id and check the stack status to see if it's a live stack. The stack-id lets us handle stack deletion correctly, because once a stack with a given stack-id is DELETE_COMPLETE, it never exits that state. Consider this scenario: We create a stack named ExampleStack with an AWS::HypotheticalResource. The Hypothetical will be tagged with the name ExampleStack and ID arn:...:1234. Say we mark that resource to be retained during deletion, and then delete the stack. Now we recreate the stack, same template, same name. Now there's a new Hypothetical, and it's tagged with the name ExampleStack and the ID arn:...:4567. If we look up arn:...:1234, Cloudformation will tell us the stack state is "DELETE_COMPLETE" so we know it once was associated with a live stack. If we searched by the stack name, that would falsely direct us to the new stack. If we look up arn:...:4567, we can see the stack status is "CREATE_COMPLETE" so it is associated with a live stack. We can further inspect the logical-id to match it to the logical ID in the stack's resources, and determine if the specific resource had a failure, e.g. it could be in a DELETE_FAILED state. Relevant APIs There's no standard way to get tags, and often you have to create the correct ARNs, unfortunately. As an example, one API is ListTagsOfResource for DynamoDB, but sometimes it's in their describe method. Generally, just search the service's page in boto's docs for "tags" and you should find it pretty easily. The Cloudformation tags themselves are standard as far as I know. The DescribeStacks API; note that StackName is the argument you pass the ID to, and it should be (IIRC) the UUID portion of the ARN. A: You can also use the AWS CLI to determine which stack a resource belongs to: aws cloudformation describe-stack-resources --physical-resource-id "resourceId" A: Yes. Boto3 CF client has methods to get the information you want. cf = boto3.client('cloudformation' stacks = cf.list_stacks(StackStatusFilter=['CREATE_COMPLETE'])['StackSummaries'] will return the stack summary for completed stacks. Change the filter to suit your needs. Get the names of the stacks names = [stack['StackName'] for stack in stacks] Then get all stack resources for a given stack for name in names: resources = cf.describe_stack_resources(StackName=name)['StackResources']
doc_23538603
/** * this is a comment * this is a co * */ When I type co I want to get tips in some words that like: com, comm, comment …… Is there any plugin that can do this? A: You can try Tabnine, although it uses a lot of memory and slows down your computer.
doc_23538604
A: It's a great question John. My suggestion would be to start in the Getting Started content for Visual Studio Team Services: https://www.visualstudio.com/docs/overview Additionally, there are books available for Team Foundation Server 2013 & Visual Studio Team Services. I can selfishly recommend Professional Team Foundation Server 2013 from Wrox as one of those printed resources.
doc_23538605
According to the documentation we need to use the command: dspace packager -s -t AIP -e eperson -p parent-handle file-path But it returns an error: dspace is not a command Anyone could help me transfer my local database to my remote repo? Thanks! A: Moving publications to a new repository will be a more substantial undertaking! But your recent problem seems just that you are either not on the right container or in the right directory for executing the dspace command. Thus it is "not found". Make sure to execute dspace on the dspace container and specify the right/complete path. The dspace command is located in /path/to/your/dspace-deployement-directory/bin.
doc_23538606
I do not want to reload the site but only the function. When I press enter now the speed increases. You can se the the game by clicking the link DEMO press ENTER to start the game Code: var canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); var tileldig = Math.floor((Math.random() * 300) + 1); var tekst = document.getElementById("tekst") var kuler = [{ r: 10, x: canvas.width / 2, y: canvas.height - 100, f: "red", dy: 0 }, ] var fiender = [{ r: 20, x: tileldig, y: -20, vx: 0, vy: 1, }, ] var snd = new Audio("Skudd.m4a"); var poeng = 0; var høyre = 0; var venstre = 0; var opp = 0; var ned = 0; document.onkeydown = function tast(e) { if (e.keyCode == 39) { // høyre høyre = 1; } if (e.keyCode == 37) { // venstre venstre = 1; } if (e.keyCode == 38) { // opp opp = 1; } if (e.keyCode == 40) { // ned ned = 1; } if (e.keyCode == 32) { newskudd(); snd.play(); console.log("hit space") } if (e.keyCode == 13) { spill(); } } document.onkeyup = function tast2(e) { if (e.keyCode == 39) { // høyre høyre = 0; } if (e.keyCode == 37) { // venstre venstre = 0; } if (e.keyCode == 38) { // opp opp = 0; } if (e.keyCode == 40) { // ned ned = 0; } } function spill() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < kuler.length; i++) { kuler[i].x += 0; kuler[i].y += kuler[i].dy; ctx.fillStyle = kuler[i].f; ctx.beginPath(); ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2 * Math.PI, 0); ctx.closePath(); ctx.fill(); if (kuler[0].x >= canvas.width - kuler[0].r) { kuler[0].x = canvas.width - kuler[0].r }; if (kuler[0].x <= 0 + kuler[0].r) { kuler[0].x = 0 + kuler[0].r }; if (kuler[0].y >= canvas.height - kuler[0].r) { kuler[0].y = canvas.height - kuler[0].r }; if (kuler[0].y <= 0 + kuler[0].r) { kuler[0].y = 0 + kuler[0].r }; for (var j = 0; j < fiender.length; j++) { ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(fiender[j].x, fiender[j].y, fiender[j].r, 2 * Math.PI, 0); ctx.closePath(); ctx.fill(); if (fiender[j].x >= canvas.width - fiender[j].r) { fiender[j].x = canvas.width - fiender[j].r; }; if (fiender[j].x <= 0 + fiender[j].r) { fiender[j].x = 0 + fiender[j].r; }; if (fiender[j].vy >= 2) { fiender[j].vy = 2; }; var distanceFromCenters = Math.sqrt(Math.pow(Math.abs(fiender[j].x - kuler[i].x), 2) + Math.pow(Math.abs(fiender[j].y - kuler[i].y), 2)); // you have a collision if (distanceFromCenters <= (fiender[j].r + kuler[i].r)) { fiender.splice(j, 1); kuler.splice(i, 1); poeng += 1; } else if (fiender[j].y > canvas.height) { fiender.splice(j, 1) } if (j > 1) { fiender.splice(j, 1) } tekst.innerHTML = ("Poeng: " + poeng) } } for (var j = 0; j < fiender.length; j++) { fiender[j].y += fiender[j].vy; } if (venstre == 1) { kuler[0].x -= 4; } if (høyre == 1) { kuler[0].x += 4;; } if (opp == 1) { kuler[0].y -= 4; } if (ned == 1) { kuler[0].y += 4; } requestAnimationFrame(spill); return; } function newskudd() { var nyttskudd = { x: kuler[0].x, y: kuler[0].y, r: 5, dy: -5, f: "white" }; kuler.push(nyttskudd); }; setInterval(function() { fiender.push({ r: 20, x: Math.floor((Math.random() * 300) + 1), y: -20, vx: 0, vy: 1, f: "green" }); }, 1000); A: An easy way to do this would be to simply refresh the page with location.reload() when a key is pressed. You could also create a gameIsInProgress variable to change to false when the game ends, and test for that value before allowing the page to reload. A: First, initialize then run spill ... if (e.keyCode == 13) { init(); spill(); } Here's an init ... function init() { kuler = [{ r: 10, x: canvas.width / 2, y: canvas.height - 100, f: "red", dy: 0 }, ]; fiender = [{ r: 20, x: tileldig, y: -20, vx: 0, vy: 1, }, ]; poeng = 0; høyre = 0; venstre = 0; opp = 0; ned = 0; } Running here ... jsFiddle
doc_23538607
EAR |- helloworldejb.jar | |- helloworldwebapp Thanks, Siva Kumar A: Actually in liberty server the EAR/WAR applications are lazy loading which means the application will load only when the request receives which is not in the case of Websphere application server. So here the required injection properties are injected in WAR level and the WAR module will only load when request receives and then inject the properties. So for the first time when EAR module receives the request , WAR module will not load during this time, . If we want to stop lazy loading then we need to have the below configuration in sever.xml , which helps to load all the initialization during startup of the server. Find the below configuration details and documentation related to the configuration. Config details : <webContainer deferServletLoad="false"/> URL : http://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_servlet_load.html
doc_23538608
Here is my code <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script> <script> var $inputs = $('#myclass'); $('#select').change(function(){ $inputs.prop('disabled', $(this).val() === '4'); }); </script> <title>Choose one</title> </head> <body> <select id="select"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> </select> <input type="text" id="myclass"/> </body> </html> The code above is not working. Can anyone help me to solve this problem? A: The DOM isn't ready : $(function() { $('#select').on('change', function(){ $('#myclass').prop('disabled', this.value == '4'); }); }); A: Your JavaScript code is being executed before the DOM is rendered. Quick fix: place your JavaScript code at the end of the <body> tag. Like this: <!DOCTYPE html> <html> <head> <title>Choose one</title> </head> <body> <select id="select"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> </select> <input type="text" id="myclass"/> <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script> <script> var $inputs = $('#myclass'); $('#select').change(function(){ $inputs.prop('disabled', $(this).val() === '4'); }); </script> </body> </html> Another option is making JavaScript code to be executed when document is ready, but the "Quick fix" approach is quite popular nowadays. This would be the different (classical?) approach: <script> $(document).ready(function () { var $inputs = $('#myclass'); $('#select').change(function(){ $inputs.prop('disabled', $(this).val() === '4'); }); }); </script>
doc_23538609
<li> <span font-color="#2b91bf">FIRST FACT</span> </li> <li> <span font-color="#2b91bf">SECOND FACT</span> </li> <li> <span font-color="#2b91bf">THIRD FACT</span> <b>hi</b> </li> <b> bold text <b> Desired output: <ul><li> <span style="color:#2574A9;">FIRST FACT</span> </li> <li> <span style="color:#2574A9;">SECOND FACT</span> </li> <li> <span style="color:#2574A9;">THIRD FACT</span> <strong>hi</strong> </li> </ul> <strong>bold text</strong> Output which i'm getting: <b> tag inside the li are not converted to strong and also font-color attribute also not converted into style but the attributes or tags which are outside the li tag are converted properly. Is this because of <xsl:copy-of>? <ul><li> <span font-color="#2b91bf">FIRST FACT</span> </li> <li> <span font-color="#2b91bf">SECOND FACT</span> </li> <li> <span font-color="#2b91bf">THIRD FACT</span> <b>hi</b> </li></ul> <b> bold text <b> I'm using below xsl to process the above snippet. <xsl:template match="b"> <strong> <xsl:apply-templates/> </strong> <xsl:template match="span"> <span> <xsl:attribute name="style"> <xsl:choose> <xsl:when test="contains(./@font-color, '#4f5967')">color:#4D4F52;</xsl:when> <xsl:when test="contains(./@font-color, '#acb3bf')">color:#6B6E70;</xsl:when> <xsl:when test="contains(./@font-color, '#2b91bf')">color:#2574A9;</xsl:when> <xsl:when test="contains(./@font-color, '#0077a7')">color:#21219A;</xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="contains(./@font-face, 'baskerville')" >font-family:'EB Garamond', serif;</xsl:when> <xsl:when test="contains(./@font-face, 'courier')" >font-family:'Space Mono', monospace;</xsl:when> <xsl:when test="contains(./@font-face, 'museo')" >font-family:'Work Sans', sans-serif;</xsl:when> <xsl:when test="contains(./@font-face, 'proxima')" >font-family:Overlock, sans-serif;</xsl:when> </xsl:choose> </xsl:attribute> <xsl:apply-templates/> </span> </xsl:template> <—- below lines of code will add ul tag as parent to those li tags which neither has it’s parent as ol nor ul —-> <xsl:key name="li-group" match="*[not(self::ol | self::ul)]/li[preceding-sibling::*[1][self::li]]" use="generate-id(preceding-sibling::li[not(preceding-sibling::*[1][self::li])][1])"/> <xsl:template match="*[not(self::ol | self::ul)]/li[not(preceding-sibling::*[1][self::li])]"> <ul> <xsl:copy-of select=". | key('li-group', generate-id())"/> </ul> </xsl:template> <xsl:template match="*[not(self::ol | self::ul)]/li[preceding-sibling::*[1][self::li]]"/> A: Instead of <xsl:copy-of select=". | key('li-group', generate-id())"/> you can use <xsl:apply-templates select=". | key('li-group', generate-id())" mode="li"/> and then <xsl:template match="li" mode="li"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template>
doc_23538610
Possible Duplicates: How can I reseed an identity column in a T-SQL table variable? Is there anyway to reset the identity of a Table Variable? Please go through the below sample and clarify my Question ? Declare @temp table (sno int identity, myname varchar(30)) insert into @temp (myname) values ('Ravi') insert into @temp (myname) values ('visu') insert into @temp (myname) values ('pranesh') delete from @temp insert into @temp (myname) values ('Ravi') select * from @temp I am inserting 3 values in @temp table which has auto increment. And later deleting the Value. Immediately adding another value. In this the Auto increment value id jumped to 4. I need to clear the auto increment value with out using dbcc statement. Can anyone help me ? Your suggestions are highly appreciated. Thank You. A: You cannot insert explicit values into an identity column for table variable
doc_23538611
Currently the JSON object array ( not sure I'm saying that right) looks like this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ "name": "CPE", "type": "Electric", "ldcCode": "CPE", "accountNumberTypeName": "ESI ID" }], "program": [{ "programId": 2090 }] }]; However, I need to modify with Javascript this JSON object data to append it So I was trying to create a new nested JSON object to then push into the existing json object array? var newOrder = [{ "program": { "accountNumberType": { "accountNumberTypeName": "ESI ID" }, "programId": 2090 }, }]; orderDetails.push(orderDetails.program.accountNumberType.accountNumberTypeName = newOrder); That ends up in an error * *Is it possible to update my existing JSON object? *Will a push work? My fiddle of it https://jsfiddle.net/j6L4s9mg/ I essentially want END RESULT to look like this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ "name": "CPE", "type": "Electric", "ldcCode": "CPE", "accountNumberTypeName": "ESI ID" }], "program": [{ "accountNumberType": { "accountNumberTypeName": "ESI ID" }, "programId": 2090 }] }]; A: Just make orderDetails[0].program = newOrder[0].program; check this fiddle A: Push will work fine but the orderDetails itself is an array. So first iterate the orderDetails array and then push the code like this orderDetails.program.push(newOrder.program); if orderDetails is var orderDetails = { "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ "name": "CPE", "type": "Electric", "ldcCode": "CPE", "accountNumberTypeName": "ESI ID" }], "program": [{ "programId": 2090 }] }; newOrder also is an array so iterate it again and then push. For demo I kept both as object instead of array. Just put a looping statement and you will get what you need. :) Working demo is here - https://jsfiddle.net/vishalsrinivasan/5eLxj2bq/
doc_23538612
$attr = array('color'=>array('red','pink','yello','white','black','light-yellow','maroon','neal'),"brand"=>array('nike','adidas','dg','puma','neaon'),"size"=>array(8,10,11,12,13,14,15)); And I need result like red-nike-8 red-nike-9 red-nike-10 red-nike-11 red-nike-12 red-nike-13 red-nike-14 red-nike-15 red-adidas-8 red-adidas-9 red-adidas-10 red-adidas-11 red-adidas-12 red-adidas-13 red-adidas-14 red-adidas-15 red-dg-8 red-dg-9 red-dg-10 red-dg-11 red-dg-12 red-dg-13 red-dg-14 red-dg-15 red-puma-8 red-puma-9 red-puma-10 red-puma-11 red-puma-12 red-puma-13 red-puma-14 red-puma-15 red-neaon-8 red-neaon-9 red-neaon-10 red-neaon-11 red-neaon-12 red-neaon-13 red-neaon-14 red-neaon-15 pink-nike-8 pink-nike-9 pink-nike-10 pink-nike-11 pink-nike-12 pink-nike-13 pink-nike-14 pink-nike-15 pink-adidas-8 pink-adidas-9 pink-adidas-10 pink-adidas-11 pink-adidas-12 pink-adidas-13 pink-adidas-14 pink-adidas-15........ Below is my code, This work for static but I need to developed to create dynamic structure. $attr_color = array('red','pink','yello','white','black','light-yellow','maroon','neal'); $attr_brand = array('nike','adidas','dg','puma','neaon'); $attr_size = array(8,10,11,12,13,14,15); $array = array(); foreach ($attr_color as $key => $value_one) { foreach ($attr_brand as $key => $value_two) { foreach ($attr_size as $key => $value_three) { $array[] = array($value_one,$value_two,$value_three); } } } A: As you have mentioned dynamic array in initial, considering that it's a array of depth two containing multiple subarrays, like below code. You can add any other subarray in this, Like I have added others array. $attr = [ [ 'color1', 'color2', 'color3', ], [ 'brand1', 'brand2', 'brand3', ], [ 'size1', 'size2', 'size3', ], [ 'other1', 'other2', 'other3', ], ]; You have to loop like this to achieve the desired result. function combinations($arrays, $i = 0) { if (!isset($arrays[$i])) { return []; } if ($i == count($arrays) - 1) { return $arrays[$i]; } // get combinations from subsequent arrays $tmp = combinations($arrays, $i + 1); $result = []; // concat each array from tmp with each element from $arrays[$i] foreach ($arrays[$i] as $v) { foreach ($tmp as $t) { $result[] = is_array($t) ? array_merge([$v], $t) : [$v, $t]; } } $finalArray = []; foreach($result as $k => $val){ $finalArray[$k] = implode("-",$val); } return $finalArray; } $result = combinations($attr); print_r($result); Final result is listed below. Array ( [0] => color1-brand1-size1-other1 [1] => color1-brand1-size1-other2 [2] => color1-brand1-size1-other3 [3] => color1-brand1-size2-other1 [4] => color1-brand1-size2-other2 [5] => color1-brand1-size2-other3 [6] => color1-brand1-size3-other1 [7] => color1-brand1-size3-other2 [8] => color1-brand1-size3-other3 [9] => color1-brand2-size1-other1 [10] => color1-brand2-size1-other2 [11] => color1-brand2-size1-other3 [12] => color1-brand2-size2-other1 [13] => color1-brand2-size2-other2 [14] => color1-brand2-size2-other3 [15] => color1-brand2-size3-other1 [16] => color1-brand2-size3-other2 [17] => color1-brand2-size3-other3 [18] => color1-brand3-size1-other1 [19] => color1-brand3-size1-other2 [20] => color1-brand3-size1-other3 [21] => color1-brand3-size2-other1 [22] => color1-brand3-size2-other2 [23] => color1-brand3-size2-other3 [24] => color1-brand3-size3-other1 [25] => color1-brand3-size3-other2 [26] => color1-brand3-size3-other3 [27] => color2-brand1-size1-other1 [28] => color2-brand1-size1-other2 [29] => color2-brand1-size1-other3 [30] => color2-brand1-size2-other1 [31] => color2-brand1-size2-other2 [32] => color2-brand1-size2-other3 [33] => color2-brand1-size3-other1 [34] => color2-brand1-size3-other2 [35] => color2-brand1-size3-other3 [36] => color2-brand2-size1-other1 [37] => color2-brand2-size1-other2 [38] => color2-brand2-size1-other3 [39] => color2-brand2-size2-other1 [40] => color2-brand2-size2-other2 [41] => color2-brand2-size2-other3 [42] => color2-brand2-size3-other1 [43] => color2-brand2-size3-other2 [44] => color2-brand2-size3-other3 [45] => color2-brand3-size1-other1 [46] => color2-brand3-size1-other2 [47] => color2-brand3-size1-other3 [48] => color2-brand3-size2-other1 [49] => color2-brand3-size2-other2 [50] => color2-brand3-size2-other3 [51] => color2-brand3-size3-other1 [52] => color2-brand3-size3-other2 [53] => color2-brand3-size3-other3 [54] => color3-brand1-size1-other1 [55] => color3-brand1-size1-other2 [56] => color3-brand1-size1-other3 [57] => color3-brand1-size2-other1 [58] => color3-brand1-size2-other2 [59] => color3-brand1-size2-other3 [60] => color3-brand1-size3-other1 [61] => color3-brand1-size3-other2 [62] => color3-brand1-size3-other3 [63] => color3-brand2-size1-other1 [64] => color3-brand2-size1-other2 [65] => color3-brand2-size1-other3 [66] => color3-brand2-size2-other1 [67] => color3-brand2-size2-other2 [68] => color3-brand2-size2-other3 [69] => color3-brand2-size3-other1 [70] => color3-brand2-size3-other2 [71] => color3-brand2-size3-other3 [72] => color3-brand3-size1-other1 [73] => color3-brand3-size1-other2 [74] => color3-brand3-size1-other3 [75] => color3-brand3-size2-other1 [76] => color3-brand3-size2-other2 [77] => color3-brand3-size2-other3 [78] => color3-brand3-size3-other1 [79] => color3-brand3-size3-other2 [80] => color3-brand3-size3-other3 ) Thanks
doc_23538613
.main { background: transparent; border-radius: 10px; max-width: 50%; width: auto; text-align: center; position: absolute; top: 420px; left: 640px; } @media screen and (max-width: 600px) { .main { max-width: 100%; width: auto; display: flex; flex-direction: column; justify-content: center; align-items: center; } } .main div img { max-width: 100%; width: auto; } A: display:flex and flex-direction: column only affects the inner arrangement of your div. In order to change your div's position, you'll have to change the top and left values. For example: .main { background: transparent; border-radius: 10px; max-width: 50%; width: auto; text-align: center; position: absolute; top: 420px; left: 640px; display: flex; } @media screen and (max-width: 600px) { .main { max-width: 100%; width: auto; display: flex; flex-direction: column; justify-content: center; align-items: center; top: 100px; left: 100px; } } .main div img { max-width: 100%; width: auto; } <div class="main"> <div>First div</div> <div>Second div</div> </div>
doc_23538614
However, it seems that the client's token is cached, since the webbrowser control does not prompt for credentials anymore after the first logon. Can anyone point out how to implement a logout method? A: The Facebook credentials are stored in a cookie, so if the implementation of a logout method simply consists of clearing cookies. If your app targets Windows Phone 8, there is a new simple API for doing that: ClearCookiesAsync. Sample code: await new WebBrowser().ClearCookiesAsync(); Here is a tutorial that makes use of it: http://www.developer.nokia.com/Community/Wiki/Integrate_Facebook_to_Your_Windows_Phone_Application
doc_23538615
To include it, I can do the following: find_package(pybind11 REQUIRED) However, this does not work on my machine. So, I attempted to give find_package a hint as per the user guide: SET(pybind11_DIR, "C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/Lib/site-packages/pybind11") That did not work either. The Cmake error suggested it may need to be the specific location of files like pybind11Config.cmake. So, I tried being more specific: SET(pybind11_DIR, "C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/Lib/site-packages/pybind11/share/cmake/pybind11") That doesn't work either. I get the exact same error in Cmake: CMake Error at lib/(our project name)/CMakeLists.txt:30 (find_package): By not providing "Findpybind11.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "pybind11", but CMake did not find one. Could not find a package configuration file provided by "pybind11" with any of the following names: pybind11Config.cmake pybind11-config.cmake Add the installation prefix of "pybind11" to CMAKE_PREFIX_PATH or set "pybind11_DIR" to a directory containing one of the above files. If "pybind11" provides a separate development package or SDK, be sure it has been installed. I double checked, Python itself is being found: Python_FOUND:TRUE Python_VERSION:3.7.4 Python_Development_FOUND:TRUE Python_LIBRARIES:C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/libs/python37.lib Python_INCLUDE_DIRS: (Though weirdly, include_dirs is empty) What am I doing wrong? A: One way is to find Python3 first and then use the sitelib as a hint: find_package(Python3 REQUIRED) find_package(pybind11 REQUIRED HINTS "${Python3_SITELIB}") A: pip install "pybind11[global]" fixed it. It may not be recommended, but it works. Found the recommendation from here: How to make cmake find pybind11
doc_23538616
I would like to get the portlet setup preferences to the theme. Is there an idea to do it? Liferay versio: 6.1.2 A: Since you're embedding the portlet you'll have the portlet id. Using that and the layout id you can get all of the portlet preferences like this: #set ($portletPreferenceService = $serviceLocator.findService("com.liferay.portal.service.PortletPreferencesLocalService")) #set (portletPreferences = $portletPreferenceService.getPortletPreferences($theme_display.getLayout().getPlid(), "yourEmbeddedPortletId"))
doc_23538617
I tried formatting it with Carbon php: {{ \Carbon\Carbon::createFromFormat('Y-m-d H', '2017-02-06T22:25:12Z')->toDateTimeString() }} But this not works, I want this date format: 06-02-17 22:25:12 A: You can use the parse method to get a quick and dirty conversion Carbon::parse('2017-02-06T22:25:12Z')->format('d-m-y H:i:s'); If you are using a model to return this date you could also look at making it return as a Carbon object by adding it to the protected $dates[] array A: If you add dates to your migration, be sure to mutate them on your model. So on your model add the following: /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'your_date' ]; https://laravel.com/docs/5.4/eloquent-mutators#date-mutators If you mutate your date, it becomes a Carbon instance, which means you can use all carbon formatting tools. From the docs: By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON. So if you would like to change the formatting everywhere use $dateFormat on your model like so: protected $dateFormat = 'd-m-y H:i:s'; If you only want to format your date inside your view , you can do it like so: {{ $your_date->format('d-m-y H:i:s') }} For more advanced formatting you can take a look at the carbon docs: http://carbon.nesbot.com/docs/
doc_23538618
will be put on the env. I will share Access Token to my customer. Once they enter the access token then can view the model and can use Extensions also. Could someone help me to get the code. I just don't want to share client id and Client secret as per the youtube link https://www.youtube.com/watch?v=dekLGw6PndI . The rest things will be same as per the youtube link. Thank you in advance. A: Please note that even without sharing the client Id and client Secret, with the token, the user will be able to perform all the actions granted by the scopes for one hour. That said, here's one sample where we limit the public token to viewables:read scope, so the user can only access derivatives for a specific model that needs to be shared. In this case, we're using AWS Lambda with API Gateway to retrieve the token here. This sample is using a function like this one to obtain the token.
doc_23538619
try: from django.core.management ^^^^^^^^^^^^^^^^^^^^^^ A: * *first you need to add the python path to your variable environnement *Second navigate to your django project and use terminal with this command : python manage.py runserver *use Docs
doc_23538620
This is my adapter; class RadioListAdapters(private var radioList: ArrayList<RadioListModel>, private val listener: Listener,private var radioFilterList : List<RadioListModel>) : RecyclerView.Adapter<RadioListAdapters.AdapterHolder>() , Filterable { interface Listener { fun startRadio(radio: RadioListModel) { } fun stopRadio(radio: RadioListModel) { } } class AdapterHolder(val binding: RecyclerRowBinding) : RecyclerView.ViewHolder(binding.root) { private var player = MediaPlayerSingleton.player fun bind(radio: RadioListModel, listener: Listener) { player = MediaPlayer() binding.radioPlayButton.setOnClickListener { if (player != null && !player!!.isPlaying) { itemView.setOnClickListener { listener.startRadio(radio) if (player!!.isPlaying) { binding.radioPlayButton.setBackgroundResource(R.drawable.pause) } } }else if (player!!.isPlaying) { listener.stopRadio(radio) if (!player!!.isPlaying) { binding.radioPlayButton.setBackgroundResource(R.drawable.play) } } } } This is my fragment: listener method; override fun startRadio(radio: RadioListModel) { super.startRadio(radio) var player = MediaPlayerSingleton.player binding.recyclerProgres.visibility = View.VISIBLE val name = radio.name val streamUrl = radio.streamLink val imageUrl = radio.imageLink val position = radio.id if (player != null && player!!.isPlaying) { player!!.pause() player!!.release() Shared.Constant.clearPlay(requireContext()) } try { if (player != null) { player!!.release() Shared.Constant.clearPlay(requireContext()) } player = MediaPlayer() player!!.setAudioStreamType(AudioManager.STREAM_MUSIC) player!!.setDataSource(Uri.parse(streamUrl).toString()) player!!.setOnPreparedListener(MediaPlayer.OnPreparedListener { player!!.start() if (player!!.isPlaying) { if (name != null && streamUrl != null) { Shared.Constant.setPlaying(requireContext(), name, streamUrl, imageUrl!!, position!! ) Toast.makeText(activity, "Playing ${radio.name}", Toast.LENGTH_SHORT).show() binding.recyclerProgres.visibility = View.GONE radioListAdapters!!.notifyData(radioFilterList) } } }) player!!.setOnCompletionListener(MediaPlayer.OnCompletionListener { if (player!!.release().run { true }) return@OnCompletionListener }) player!!.setOnErrorListener(MediaPlayer.OnErrorListener { mp, what, extra -> player!!.reset() Shared.Constant.clearPlay(requireContext()) true }) player?.prepareAsync() } catch (e: IllegalArgumentException) { e.printStackTrace() } catch (e: SecurityException) { e.printStackTrace() } catch (e: IllegalStateException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } Except this, I'm trying save radio properties to a shared preferences singleton and need to compare with get method in playing Example => when play button clicked; if -> setData == getData dont do anything else if -> setData != getData pause radio and start new, if you help me for do this I will be glad! Thank you in advance.
doc_23538621
I have this error only in my edit page of my nifty_scaffold. This is _form.html.erb <% form_for @progress do |f| %> <%= f.error_messages %> <p> <%= f.label :date %><br /> <%= f.date_select :date %> </p> <p> <%= f.label :description %><br /> <%= f.text_area :description %> </p> <p> <%= f.label :weight %><br /> <%= f.text_field :weight %> </p> <p> <%= f.label :fatpercentage %><br /> <%= f.text_field :fatpercentage %> </p> <p> <%= f.label :height %><br /> <%= f.text_field :height %> </p> <p><%= f.submit "Submit" %></p> <% end %> This is edit.html.erb <% title "Edit Progress" %> <%= render :partial => 'form' %> And this is my controller: class ProgressesController < ApplicationController def new @progress = Progress.new end def create @progress = Progress.new(params[:progress]) if @progress.save flash[:notice] = "Successfully created progress." redirect_to progresses_url else render :action => 'new' end end def edit @progress = Progress.find(params[:id]) end def update @progress = Progress.find(params[:id]) if @progress.update_attributes(params[:progress]) flash[:notice] = "Successfully updated progress." redirect_to progresses_url else render :action => 'edit' end end def index @progresses = Progress.all end end What could be wrong? I can't seem to find my error :-S. It seems that it: - fetches the data correctly - can't insert the db-values into the "edit view" fields. I'm using :float, :string and :date as data types in the scaffold. Just for the completed post, this is my error: NoMethodError in Progresses#edit Showing app/views/progresses/edit.html.erb where line #3 raised: undefined method `to_sym' for nil:NilClass Extracted source (around line #3): 1: <% title "Edit Progress" %> 2: 3: <% form_for @progress do |f| %> 4: <%= f.error_messages %> 5: <p> 6: <%= f.label :date %><br /> At line 6 the log of the code ends... Edit: It seems to be an error in my routes.rb. This is currently commented: map.edit_progress "edit_progress", :controller => "progresses", :action => "edit" when i uncomment it, it gives an error also in my index view. For some reason, this is called: 'http://127.0.0.1:3001/progresses/1/edit', shouldn't it be: 'http://127.0.0.1:3001/progresses/edit/1' ? Even though it seem's that the "edit view" is called... Perhaps this is the reason why the values aren't filled in, in my view... What could be my solution? A: I will suggest two step debugging here: * *Remove all your code from the edit view and a add some plain text in it, then access your page in the browser and see if you get any error or new error or no error *If you get any new error then it might help you in solving the issue or in your controller edit action raise the @progress to see whether it is being set def edit @progress = Progress.find(params[:id]) raise @progress.inspect end These two steps might help you in resolving the issue.
doc_23538622
( Also note that I'm new to Unit testing as such, so I'm not sure if this is a good approach as how to test such component. ) For starters, I only wanted to check, if the initial value of #username input element is empty. But I couldn't even make the spec to work due to the below reported issues: Chrome 55.0.2883 (Windows 7 0.0.0) LoginComponent Username field should be empty FAILED Failed: Unexpected value 'Http' imported by the module 'DynamicTestModule' Error: Unexpected value 'Http' imported by the module 'DynamicTestModule' TypeError: Cannot read property 'detectChanges' of undefined Chrome 55.0.2883 (Windows 7 0.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.348 secs) When I tried deleting the Http module, I got this error : Chrome 55.0.2883 (Windows 7 0.0.0) LoginComponent Username field should be empty FAILED Error: DI Error Error: Uncaught (in promise): Error: No provider for Http! TypeError: Cannot read property 'detectChanges' of undefined Chrome 55.0.2883 (Windows 7 0.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.456 secs) login.component.html <div class="login jumbotron center-block"> <h1>Login</h1> <form (ngSubmit)="onSubmit($event)" #loginForm="ngForm"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" [(ngModel)]="model.username" name="username" placeholder="Username" #username="ngModel" required> <div [hidden]="username.valid || username.pristine" class="alert alert-danger"> Username is required </div> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" [(ngModel)]="model.password" name="password" placeholder="Password" #password="ngModel" required> <div [hidden]="password.valid || password.pristine" class="alert alert-danger"> Password is required </div> </div> <button type="submit" class="btn btn-default" [disabled]="!loginForm.form.valid" >Submit</button> <a [routerLink]="['/signup']">Click here to Signup</a> </form> </div> login.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { LoginService } from '../services/login.service'; import { User } from '../extensions/user.class'; @Component({ moduleId: module.id, selector: 'login', templateUrl: '../templates/login.component.html', styleUrls: [ '../styles/login.component.css' ], providers: [ LoginService ] }) export class LoginComponent { private submitted = false; private model = new User(); constructor( private router: Router, private loginService: LoginService ) {} public onSubmit(event: any): void { event.preventDefault(); if ( ! this.submitted ) { this.submitted = true; if ( this.model.username && this.model.password ) { this.loginService.login(this.model).then( (token) => { localStorage.setItem('id_token', token.id); this.router.navigate(['home']); }).catch( (error) => this.onLoginFailed(error) ); } else { console.warn('No username or password provided'); } } } private onLoginFailed( error: any ): void { //// errors are already handled in login-service //// console.error(error); this.submitted = false; /// reset form submit funcitonality /// } public signup(event: any): void { event.preventDefault(); this.router.navigate(['signup']); } } login.component.spec.ts import { async } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { LoginComponent } from './login.component'; import { LoginService } from '../services/login.service'; import { Http } from '@angular/http'; import { User } from '../extensions/user.class'; @Component({ template: '' }) class DummyComponent{} class LoginServiceStub { login( user: User ){ return true; } } describe('LoginComponent', () => { let comp: LoginComponent; let fixture: ComponentFixture<LoginComponent>; let de: DebugElement; let el: HTMLElement; let location: Location; // async beforeEach beforeEach( async(() => { TestBed.configureTestingModule({ declarations: [ LoginComponent, DummyComponent ], // declare the test component providers: [ { provide: LoginService, useClass: LoginServiceStub } ], imports: [ FormsModule , RouterTestingModule.withRoutes([ { path: 'singup', component: DummyComponent } ]) ] }).compileComponents() // compile template and css .then( () => { fixture = TestBed.createComponent(LoginComponent); comp = fixture.componentInstance; // LoginComponent test instance de = fixture.debugElement.query(By.css('input[name="username"]')); el = de.nativeElement; }); })); it('Username field should be empty', () => { fixture.detectChanges(); expect(el.textContent).toContain(''); }); }); A: The problem is that the LoginService is declared at the component level @Component({ providers: [ LoginService ] }) This will supersede any same service declared at the module level, which is where you declare the mock in the test. There are a couple things you can do: * *Don't declare the service at the component level. If there is not good reason to scope it to the component, then just declare it at the @NgModule.providers and make it a singleton. *Override the @Component.providers in the test. TestBed.configureTestingModule({}) TestBed.overrideComponent(LoginComponent, { set: { providers: [ { provide: LoginService, useClass: LoginServiceStub } ] } }); A: Alexus, Have you tried importing the Http module into your test component and adding it to the "providers" array? I think you would have to specify all of your dependencies in this case. I'm assuming your LoginService is requiring {Http} as a provision, but your test component does not register {Http} so it can't find an instance to use. EDIT: TestBed.configureTestingModule({ declarations: [ LoginComponent, DummyComponent ], // declare the test component providers: [ { provide: LoginService, useClass: LoginServiceStub }, Http, ], imports: [ FormsModule , RouterTestingModule.withRoutes([ { path: 'singup', component: DummyComponent } ]) ] DOUBLE EDIT!: In addition, you'll probably want to mock out the Http module, as you won't actually want to send a request during your unit test. "MockBackend" from @angular/http/testing is sufficient for this -- in this case, you would want to use the "provide" syntax you uses with the Login Service to provide an Http module that uses the MockBackend to generate responses.
doc_23538623
So far the initial schema is: Items_table item_id total_points (lots of other fields unrelated to voting) Voting_table voting_id item_id user_id vote (1 = up; 0 = down) month_cast year_cast So I'm wondering if it's going to be a case of selecting all information from voting table where month = currentMonth & year = currentYear, somehow running a count and grouping by item_id; if so, how would I go about doing so? Or would I be better off creating a separate table for monthly charts which is updated with each vote, but then should I be concerned with the requirement to update 3 database tables per vote? I'm not particularly competent – if it shows – so would really love any help / guidance someone could provide. Thanks, _just_me A: I wouldn't add separate tables for monthly charts; to prevent users from casting more than one vote per item, you could use a unique key on voting_table(item_id, user_id). As for the summary, you should be able to use a simple query like select item_id, vote, count(*), month, year from voting_table group by item_id, vote, month, year A: I would use a voting table similar to this: create table votes( item_id ,user_id ,vote_dtm ,vote ,primary key(item_id, user_id) ,foreign key(item_id) references item(item_id) ,foreign key(user_id) references users(user_id) )Engine=InnoDB; Using a composite key on a innodb table will cluster the data around the items, making it much faster to find the votes related to an item. I added a column vote_dtm which would hold the timestamp for when the user voted. Then I would create one or several views, used for reporting purposes. create view votes_monthly as select item_id ,year(vote_dtm) as year ,month(vote_dtm) as month ,sum(vote) as score ,count(*) as num_votes from votes group by item_id ,year(vote_dtm) ,month(vote_dtm); If you start having performance issues, you can replace the view with a table containing pre-computed values without even touching the reporting code. Note that I used both count(*) and sum(vote). The count(*) would return the number of cast votes, whereas the sum would return the number of up-votes. Howver, if you changed the vote column to use +1 for upvotes and -1 for downvotes, a sum(vote) would return a score much like the votes on stackoverflow are calculated.
doc_23538624
Question 1: How to get the multiple UOM of a Product ? Question 2: How to get Branch wise Qty of a Product ? I am using the url https://sandbox.kimballinc.com/AcumaticaERP/entity/Default/18.200.001/StockItem?$filter=InventoryID eq '12345' A: To get Qty of the product per warehouse you can use expand = warehouseDetails parameter {{sitename}}/entity/Default/18.200.001/StockItem?$expand=WarehouseDetails&$filter=InventoryID eq '12345' As for UOM, you get them right away with you initial request. If you are talking about UOM conversions, you use expand = UOMConversions {{sitename}}/entity/Default/18.200.001/StockItem?$expand=UOMConversions&$filter=InventoryID eq '12345' If you need more details about entity schema, you can observe endpoint schema on Web Service Endpoints form inside Acumatica ERP. However, if you want to retrieve both of them at the same time in Acumatica ERP 219r1 or earlier, you will have to change the request and use retrieval of record by key fields request: https://help-2019r1.acumatica.com/(W(13))/Help?ScreenId=ShowWiki&pageid=52c97a83-1fa1-40e9-8219-52a89a91f2da (Starting from 2019r2 version you can retrieve both using filter) So, instead of $filter parameter, you modify url itself, like that: {{sitename}}/entity/Default/18.200.001/StockItem/12345?$expand=UOMConversions,WarehouseDetails (12345 here is Inventory ID)
doc_23538625
* *I need to built a scheduled task for posting once per day, a log about users session information (log in/log off/session lock/session unlock...). I have created a WCF service, a database, and functions for getting theses infos. The last step is to built a PowerShell script for posting to the service, this log, from users pc's. *In my console application I'm using ConfigItem dataclass for my list and then I pass this List with the two otjers string arguments to service. I don't understand how I could do the same thing in the PS script, using the same arguments and post them to the service. My service method: public void RecordActivity(string user, string pc, List<ConfigItem> act) { var USR = new Users() { UserName = user }; var PC = new Pc() { PcName = pc }; act.ToList().ForEach(p => { int id = (from t in context.Activity where t.ActivityName==p.Activity select t.ActivityId).SingleOrDefault(); var RF = new AuditActivity() { Date = p.Date,ActivityId=id}; USR.AuditActivity.Add(RF); PC.AuditActivity.Add(RF); context.Set<Pc>().Add(PC); context.Set<Users>().Add(USR); }); context.SaveChanges(); } Data class in service : [DataContract] public class ConfigItem { [DataMember] public DateTime Date { get; set; } [DataMember] public string Activity { get; set; } } Function to get users informations and post them in service (working in a console app) AuditServiceTestClient sve = new AuditServiceTestClient(); string machine = Environment.MachineName; string userName = WindowsIdentity.GetCurrent().Name; List<ConfigItem> cfg = new List<ConfigItem>(); const char fieldSeparator = ';'; string filePath = @"h:\csv\Activity.csv"; using (StreamReader SR = new StreamReader(filePath)) { while (!SR.EndOfStream) { var CSValues = SR.ReadLine().Split(fieldSeparator); ConfigItem c = new ConfigItem(); c.Date = Convert.ToDateTime(CSValues[0]); c.Activity = CSValues[1]; cfg.Add(c); } } sve.RecordActivity(userName, machine, cfg); My PowerShell script : $WebSvcURL= “http://xxx/AuditServiceTest.svc” #Create the Web Service Proxy Object $proxy = New-WebServiceProxy -Uri $WebSvcURL -Namespace ExportTool -Class Program -UseDefaultCredential $proxy Write-host -ForegroundColor DarkBlue ===successfullyconnected to the WCF Web Service $proxy A: I'm not sure where your ConfigItem comes from, so New-Object's invocations may differ: $WebSvcURL = 'http://xxx/AuditServiceTest.svc' #Create the Web Service Proxy Object $proxy = New-WebServiceProxy -Uri $WebSvcURL -Namespace ExportTool -Class Program -UseDefaultCredential # Get machine and user name $userName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $machine = [System.Environment]::MachineName # Create new list of ConfigItems $cfg = New-Object -TypeName System.Collections.Generic.List``1[ConfigItem] # Import CSV, add values to list of ConfigItems Import-Csv -Path 'h:\csv\Activity.csv' | ForEach-Object { # Create new ConfigItem $item = New-Object -TypeName ConfigItem # Set properties $item.Date = $_.Date $item.Activity = $_.Activity # add item to list $cfg.Add($item) } # Call service method $proxy.RecordActivity($userName, $machine, $cfg) References * *Powershell Generic Collections
doc_23538626
I'm using Python and GTK3 with GObject introspection. A: Here's an example of how to do that, inspired by this answer for C. from gi.repository import Gtk from gi.repository import GdkPixbuf store = Gtk.ListStore(str, GdkPixbuf.Pixbuf) pb = GdkPixbuf.Pixbuf.new_from_file_at_size("picture.png", 32, 32) store.append(["Test", pb]) combo = Gtk.ComboBox.new_with_model(store) renderer = Gtk.CellRendererText() combo.pack_start(renderer, True) combo.add_attribute(renderer, "text", 0) renderer = Gtk.CellRendererPixbuf() combo.pack_start(renderer, False) combo.add_attribute(renderer, "pixbuf", 1) window = Gtk.Window() window.add(combo) window.show_all() window.connect('delete-event', lambda w, e: Gtk.main_quit()) Gtk.main() A: The same example in GTK2, inspired by your code: import pygtk pygtk.require('2.0') import gtk import gtk.gdk import gobject import gc store = gtk.ListStore(str, gtk.gdk.Pixbuf) pb = gtk.gdk.pixbuf_new_from_file("picture.png") store.append(["Test", pb]) combo = gtk.ComboBox(store) renderer = gtk.CellRendererText() combo.pack_start(renderer, True) combo.add_attribute(renderer, "text", 0) renderer = gtk.CellRendererPixbuf() combo.pack_start(renderer, False) combo.add_attribute(renderer, "pixbuf", 1) window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.add(combo) window.show_all() window.connect('delete-event', lambda w, e: gtk.main_quit()) gtk.main()
doc_23538627
this is a text it automatically becomes: 'this is a text' I have some texts that have special characters and they have to be inside single quotes, I'd love to have single quotes automatically added when I input those texts. A: Do you mean something like this? userText = raw_input("Enter some text:") quatedText = "'" + userText + "'"
doc_23538628
However, Firefox keeps giving me a Network error when awaiting a response from the Server. Other browsers such as Chrome, Safari, Opera work just fine. Code for the request: export function postLoginDetails(username, password, token) { const url = ENV.host + "/login"; return axios({ method: 'post', url: url, withCredentials: true, headers: { "X-CSRFToken": token }, data: { username: username, password: password, }, responseType: 'json' }).catch(e => console.log(e)) } Heres the code where the error occurs: res is undefined. postLoginDetails(username, password, this.token).then((res) => { if (res.data.success) { this.isAuthenticated.set(true) cb(); } else { this.error.set(true); this.errorText = observable('Fehler aufgetreten'); this.name = observable(''); } this.loginLoading.set(false); }) Heres the error in Firefox A: For others experiencing this issue, I can't speak to the pre-flight option stuff, but I do know that firefox is telling axios to kill the request. If you look at the section of axios that handles the error, you see the comment: // Handle browser request cancellation (as opposed to a manual cancellation) So it's some sort of browser quirk. I wasn't using a button to trigger the request, but an anchor tag <a>. It started working when I changed that to a <span> instead. Why, firefox?
doc_23538629
so I created an example small project to try this: * *creating of phone brand and save into brands.pkl text fields: "brand name" *creating of phone model with selecting a brand from previous created brand via dropdown and save into models.pkl text fields: phone name dropdown: brand from created. But I haven't found a solution to relation it (in sql I can use foreign key by id). Thank you. Here is my example code: def phones(self): saved_phones= util.load_phones() return json.dumps(saved_phones) @cherrypy.expose def new_brands(self, *args, **kwargs): try: saved_brands = util.load_brands() brand = {'name': kwargs['brand_name']} try: brand['id'] = saved_brands[-1]['id'] + 1 except IndexError: brand['id'] = 1 saved_brands.append(brand) util.save_brands(saved_brands) return json.dumps(brand) except Exception as e: return json.dumps({'error': str(e)}) @cherrypy.expose def new_phones(self, *args, **kwargs): try: saved_phones = util.load_phones() phone = {'model': kwargs['phone_model']} try: phone['id'] = saved_module[-1]['id'] + 1 except IndexError: phone['id'] = 1 saved_phones.append(phone) util.save_phones(saved_phones) return json.dumps(phone) except Exception as e: return json.dumps({'error': str(e)}) def save_phones(phones): pickle.dump(phones, open('phones.pkl', 'wb')) def load_phones(): try: saved_phones = pickle.load(open('phones.pkl', 'rb')) except IOError: saved_phones = [] return saved_phones def get_modul(phones, phone_id): for phone in phones: if phone['id'] == phone_id: return phone # if # for return None def save_brands(brands): pickle.dump(brands, open('brands.pkl', 'wb')) def load_brands(): try: saved_brands = pickle.load(open('brands.pkl', 'rb')) except IOError: saved_brands = [] return saved_brands def get_modul(brands, brand_id): for brand in brands: if brand['id'] == brand_id: return brand # if # for return None A: pickle might be a lousy fit for the problem you seem to be trying to solve. pickle makes some sense when you want to persist or transmit a bundle of related objects all in one shot. maybe you really do want a sql database? sqlite3 bindings are provided with python out of the box, and you can transition to a more robust database when the time comes with minimal effort.
doc_23538630
Does anybody know how to build only the libs necessary for a subset of headers? I'm doing a bcp along the lines of this bcp.exe --scan C:\path\to\my\files\main.cpp C:\path\to\my\files\someOtherCppFilesToo.cpp C:\path\to\reduced\boost The internet seems to think I can do something like this cd C:\path\to\reduced\boost bootstrap.exe b2.exe Now the problem is that I can't figure out if there's some way to copy over the compile/bootstrap/jam/whatever configuration so that boost.build and bootstrap know how to configure/compile everything. I obviously don't want to copy every file from the boost directory, because that would defeat the whole purpose of reducing the boost includes. A: Well, I believe you were close to it: bcp.exe --scan --boost=path_to_boost_dir main.cpp someOtherCppFilesToo.cpp myboost bcp.exe --boost=path_to_boost_dir build myboost cd myboost bootstrap.bat b2 the_modules_you_want_to_build
doc_23538631
However it seems that it uses a standard single line NSTextField when it is in editing mode. If I just could access that object I could change it to multiline but it seems that PDFAnnotationTextWidget does not expose this object. https://developer.apple.com/library/mac/documentation/graphicsimaging/Reference/QuartzFramework/Classes/PDFAnnotationTextWidget_Class/Reference/Reference.html Any ideas? The only example I found is the example project for PDFKit from 2006, but it also only support single line annotations. https://developer.apple.com/library/mac/samplecode/PDFAnnotationEditor/Introduction/Intro.html If not possible, is there a way to create custom PDFKit annotations, and in that case, how? A: It seems that there is no public method to access that NSTextField. You can access it only swizzling some methods, like I did in this example (please note: the code has a lot of warnings because it's old) In my example you can write multiple lines in the NSTextField, but when you exit editing mode all goes on a single line: there is a reason why Apple used a single line text field for Widget annotations, AFAIK Widget annotations in PDF supports only single line, but this is a limitation on the PDF annotations and not in the Apple SDK. If you save the document after the annotation is added, you can access it from any other pdf editor...and in that case you will see only a single line (that is not an NSTextField but the own implementation of the pdf reader). If you want to permit to the user to write text on multiple lines, and to visualize it over the PDF (but without the possibility for the other pdf readers to change your annotations), you have to subclass PDFAnnotation and create your own class. In this case, have a look a the MyStampAnnotation file. You can create a similar class, inheriting from PDFAnnotation. When the user clicks on the annotation (in editing mode), add your own textfield, then write the text directly on the document using something like CGContextShowTextAtPoint in the drawWithBox: method
doc_23538632
$base_config['base_url'] = 'http://localhost/sg-cms/'; $base_config['db_host'] = 'localhost'; $base_config['db_name'] = 'sg-cms'; $base_config['db_user'] = 'root'; $base_config['db_pass'] = ''; $base_config['theme'] = 'basic'; $base_config['allow_5_4'] = false; $base_config['salt'] = 'dfsfdsfdsfasfafasfsfadfvdfdfsfa'; $base_config['encryption_key'] = 'bjAdffdsfdfadfaJv'; when going to loclhost I see the follwoing error: Fatal error: Incorrect base_url: 'http://localhost/sg-cms/' does not match 'http://localhost/SWEBSITES/t_m/website/index.php' in C:\wamp\www\SWEBSITES\t_m\website\includes\routing.php on line 277 what is going wrong here exactly because it seems like when I fix something another thing gets corrupted!
doc_23538633
The proto file package tutorial; option java_package = "com.example.tutorial"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } message AddressBook { repeated Person person = 1; } I already have a Person object : Person john = Person .newBuilder() .setId(1234) .setName("John Doe") .setEmail("[email protected]") .addPhone( Person.PhoneNumber.newBuilder().setNumber("555-4321") .setType(Person.PhoneType.HOME)).build(); Now let's suppose Ive read that object from a stream( working fine) , and now I want to update the Email : The example here says to : So I tried to get the email builder but I only see this : Question How can I edit this person of myne , and why does the exact code , doesn't work ? A: The email is not defined as a sub message in your proto file, is a String. Protoc generates the messages as java classes, each generated class has a Builder sub class who extends com.google.protobuf.GeneratedMessage.Builder and implements all necesary methods to work and the builder is accesible via the appropiate getter. That's the reason why you cant get the PhoneNumber builder john.toBuilder().getPhoneBuilder(index); and set the PhoneNumber fields, because is defined as a sub message and has his own Builder message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } and you can not get the email Builder, because the email does not exists as message sub class (with his own builder), is defined as a String and the builder is the Person Class builder optional string email = 3; If you want to change the email you can do john.toBuilder().setEmail("[email protected]").buid(); It is a bit confused but hope this helps.
doc_23538634
here the code program: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define MYPORT 4950 #define MAXBUFLEN 100 int sockfd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; struct hostent *he; int addr_len, numbytes; char dt[30]; char buf[MAXBUFLEN]; int main() { printf("‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐\n"); if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){ perror("socket"); exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); my_addr.sin_addr.s_addr = INADDR_ANY; memset(&(my_addr.sin_zero),'\0',8); if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1){ perror("bind"); exit(1); } while(1){ addr_len = sizeof(struct sockaddr); if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&addr_len))==-1) { perror("recvfrom"); exit(1);} buf[numbytes]='\0'; printf("%s : \"%s\"\n", inet_ntoa(their_addr.sin_addr), buf); if (buf[0]==1) { printf("oke\n");} printf("Me : "); scanf("%s", dt); if((numbytes=sendto(sockfd,dt,strlen(dt),0,(struct sockaddr*)&their_addr,sizeof(struct sockaddr)))==-1) { perror("sendto"); exit(1); } } close(sockfd); return 0; } when I put "1" in client side the result is: ‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐ 130.130.66.76 : "1" Me : even in the program there are: if (buf[0]==1) { printf("oke\n");} why the program cannot access to inside of if? A: Try if (buf[0]=='1') Number characters map to different ASCII values than their number, so, for example, '1'==49.
doc_23538635
At line:1 char:24 + set NODE_ENV=production&&npm run server + ~~ The token '&&' is not a valid statement separator in this version. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidEndOfLine A: If you are using VS Code terminal or Windows PowerShell(VS Code also uses PowerShell on the Windows) set NODE_ENV=production; npm run server and for Mac/Linux NODE_ENV=production npm run server A: If you're trying to run this in a script in package.json then cross-env is a good way to set it so that it works on any OS. So that the script would be like cross-env NODE_ENV=production && npm run server A: If you are using windows 10 and using vs terminal. It will be work for you. set NODE_ENV=production; node server or set NODE_ENV=production node server Instead of using: NODE_ENV=production node server
doc_23538636
from selenium import webdriver from selenium.webdriver.common.by import By import time import urllib import urllib.request import time import os #driver = webdriver.Chrome(executable_path=r"C:\Users\umesh.kumar\Downloads\Codes\chromedriver.exe") username = "ABCD.kumar" password = "X0XX" driver = webdriver.Chrome() driver.get("http://propadmin.99acres.com/propadmin/index.htm") urls = ["https://propadmin.99acres.com/do/seller/ProcessSellerForms/getDeletedPhotos?prop_id=A18056415", "https://propadmin.xxxxxxx.com/do/seller/ProcessSellerForms/getDeletedPhotos?prop_id=A56063622"] driver.maximize_window() driver.find_element(By.ID, "username").send_keys(username) driver.find_element(By.ID, "password").send_keys(password) driver.find_element_by_name("login").click() for posts in range(len(urls)): print(posts) driver.get(urls[posts]) if(posts!=len(urls)-1): driver.execute_script("window.open('');") chwd = driver.window_handles driver.switch_to.window(chwd[-1]) elems = driver.find_elements_by_tag_name('a') for elem in elems: href = elem.get_attribute('href') if href is not None: print(href)
doc_23538637
What I would like to know is: how can there be few objects which are not tracked and a few which are tracked? Can someone share the code snippet which shows that this entity is not tracked by a context. According to MSDN: Detached: the entity is not being tracked by the context https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113).aspx According to following post which I read: http://blog.maskalik.com/entity-framework/2013/12/23/entity-framework-updating-database-from-detached-objects/ var entry = _context.Entry<T>(entity); if (entry.State == EntityState.Detached) { _context.Set<T>().Attach(entity); entry.State = EntityState.Modified; } Detached objects, or objects that are created outside of Entity Framework (EF), don’t have automatic tracking enabled. And creating a POCO class in code-first approach is one such example of a detached entity. Is this the only scenario? A: There are more scenarios for the Detached Object. 1.You dont want to track an entity. var entity= context.MyEntities.AsNoTracking().Where(...).FirsOrDefault(); In this query entities retrieved are not tracked hence any changes on the entities will not be recorded to database. Consider this. entity.Name = "1"; context.SaveChanges(); As this entities are not tracked the changes will not be saved unless you attach this. var entry = _context.Entry<T>(entity); if (entry.State == EntityState.Detached) { _context.Set<T>().Attach(entity); entry.State = EntityState.Modified; } 2.Consider your working on disconnected architecture (API,Web). Consider an employee API which have PUT endpoint. This would attach the employee to the context and update the entity as context is not aware of this entity. Advantage : No need to fetch the employee entity from the database. Disadvantage : Someother user changes the entity between the transaction might be losed (you can still update property that are only changed) public void UpdateEmployee(Employee entity) { var entry = _context.Entry<Employee>(entity); if (entry.State == EntityState.Detached) { _context.Attach(entity); entry.State = EntityState.Modified; } Context.SaveChanges() } Second Version public void UpdateEmployee(Employee entity) { var dbItem = context.EmployeeEnities.FirstOrDefault(g=>g.Id==entity.Id); //Context is already have track of this entity, you can just update properties you have changed. dbItem.Name = entity.Name; Context.SaveChanges() }
doc_23538638
Reading the man pages for tar made it seem like the -I option is what I wanted. This is what I've tried from the dir in question: find . -name "*.class" >> ~/includes.txt tar cvf ~/classfiles.tar -I ~/includes.txt From that I get: tar: Removing leading `/' from member names /home/myhomedir/includes.txt And the ~/classfiles.tar files is garbage. I don't have write permission on the dir where the *.class files are so I need to have the tar written to my home dir. Could someone tell me where I have gone wrong? What tar magic should I use? A: Check which tar you are running. That message about removing the leading slash is a gtar (GNU tar) message, and the -I option you are trying to use is a Sun tar option (which lives in /bin/tar). (at least the above is all true on my Solaris machine)
doc_23538639
I am trying to properly display Bootstrap's modal box, but for some reason, it will work some of the time when I test it. I clicked on a button that was suppose to trigger the modal box, showing a gray fade/shadow (the background when the modal box is open) and disappears fast. I debugged and saw a lot of errors saying Declaration dropped. Another thing I noticed, The URL C://.../test.html did not make the modal box appear correctly, however adding C://.../test.html# made the box function correctly. Now, this makes me wonder, since I have a couple of hashtags in my overall html document, does it have anything to do with those hashtags? Maybe, this line of code in particular? <button class="btn btn-primary" data-toggle="modal" data-target="#myModal"> If not, what is the root cause for the problem as to why a hashtag at the end of url string made it work and how can I fix it? HTML: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Login Test</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]--> <style> /*{border:1px dotted blue;}*/ footer{margin-top:20px;} </style> </head> <body> <!-- Skip Navigation --> <a href="#PrintReady" class="offscreen" style="display:none;">Skip to Main Content Area</a> <div id="container"> <div class="container"> <div class="bannerLogoArea" style="padding:20px 0;"> <span class="bannerSiteAreaText">Login Test</span> </div> <!-- PlaceBar --> <div class="nav-cntr"> <!-- Static navbar --> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a class="wpsUnSelectedPlaceLink" href='#'>&nbsp;Home&nbsp;</a></li> <li><a class="wpsUnSelectedPlaceLink" href='#'>&nbsp;Account&nbsp;</a></li> <li><a class="wpsUnSelectedPlaceLink" href='#'>&nbsp;Contact Us&nbsp;</a></li> <li class="active"><a class="wpsSelectedPlaceLink" href='#'>&nbsp;Login Test&nbsp;</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#"><strong>Login or Register</strong></a></li> </ul> </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </div> </div><!--/.nav-cntr --> <div id="PrintReady"> <table border="0" width="100%" cellpadding="0" cellspacing="0" align="center"> <tr height="100%"> <td valign="top" > <table border="0" width="100%" cellpadding="0" cellspacing="0" align="center"> <tr> <td width="100%" valign="top"> <div class="default-skin"> <div class="row"> <div class="col-sm-12"> <h1>Member Registration</h1> <p>Please complete the following fields and click 'Continue.'</p> </div> </div> <div class="row"> <div class="col-sm-10"> <form class="form-horizontal" role="form"> <!--Button trigger modal--> <button class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Read & Accept Lorem Ipsum </button> </form> <!--Modal--> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> </div> </td> </tr> </table> </td> </tr> </table> </div><!-- /PrintReady --> </div> <!-- /container --> </div> </body> </html> A: Oh I figured it out. Move the modal outside of your form! move this <div class="modal fade" id="myModal" ....> outside of <form class="form-horizontal" role="form"> below it. Its true though that div's inside form are perfectly acceptable somehow though bootstrap.js has a hard time with it. its a known bug! A: Remove the form element that surrounds the button that triggers the modal. Your button is triggering the form action, which is why it suddenly changes. Working example here: http://www.bootply.com/zYGnsEkuF2 <!-- <form class="form-horizontal" role="form"> REMOVE THIS LINE --> <!--Button trigger modal--> <button class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Read & Accept Lorem Ipsum </button> <!-- </form> REMOVE THIS LINE -->
doc_23538640
See the query below: { "find": "users", "filter": { "role": "USER", "$text": { "$search": "[email protected]" } }, "sort": { "score": { "$meta": "textScore" } }, "projection": { "score": { "$meta": "textScore" } }, "limit": 20, ... } Is there a way to fix this high ratio? I have an index for role already and obviously it's using my text index. Thanks! Alex
doc_23538641
For example: The Page: protected void Page_Load(...) { Items[KeyValueFromConfigurationFile] = new DataContext(); var repo = new Repository(); var rootEntity = repo.GetById(1); } The Repository: public virtual TEntity GetById(int id) { var ctx = HttpContext.Current.Items[KeyValueFromConfigurationFile] as DataContext; return ctx.TEntities.SingleOrDefault(p => p.Id == id); } Of course, I would check for nulls and perform the steps needed to get a DataContext if it wasn't available in the HttpContext.Current.Items collection. So, back to my original question given the above code: Will the HttpContext.Current be disposed along with any of the objects contained in its Items collection even if an exception is thrown? A: I didn't think there was an issue with the last post providing a solution because the underlying collection isn't being modified, which cannot be done while it's being enumerated, but I did recently run into sporadic errors with this code. We were seeing the error 'Collection was modified; enumeration operation may not execute' when OnEndRequest fired and executed the for loop below: foreach (var item in HttpContext.Current.Items.Values) { var disposableItem = item as IDisposable; if (disposableItem != null) { disposableItem.Dispose(); } } So apparently disposing the current HttpContext items while iterating the collection with a foreach loop can also pose a problem. There's a couple ways around this, but I chose to do it this way: int size = HttpContext.Current.Items.Count; if (size > 0) { var keys = new object[size]; HttpContext.Current.Items.Keys.CopyTo(keys, 0); for (int i = 0; i < size; i++) { var obj = HttpContext.Current.Items[keys[i]] as IDisposable; if (obj != null) obj.Dispose(); } } A: Objects in HttpContext.Current.Items will not automatically be disposed. You would need to handle this yourself. You can do it in the global.asax Application_EndRequest: foreach (var item in HttpContext.Current.Items.Values) { var disposableItem = item as IDisposable; if (disposableItem != null) { disposableItem.Dispose(); } }
doc_23538642
Similarity is transitive. Example: Result of computations: A (similar to A) B (similar to C) C D In this case, only A or D and B or C would be presented to the user - but not two similar Puzzles. Two similar puzzles are equally valid. It is only important that they are not both shown to the user. To accomplish this, I wanted to use an ADT that prohibits duplicates. However, I don't want to change the equals() and hashCode() methods to return a value about similarity instead. Is there some Equalator, like Comparator, that I can use in this case? Or is there another way I should be doing this? The class I'm working on is a Puzzle that maintains a grid of letters. (Like Scrabble.) If a Puzzle contains the same words, but is in a different orientation, it is considered to be similar. So the following to puzzle: (2, 2): A (2, 1): C (2, 0): T Would be similar to: (1, 2): A (1, 1): C (1, 0): T A: I'd use a wrapper class that overrides equals and hashCode accordingly. private static class Wrapper { public static final Puzzle puzzle; public Wrapper(Puzzle puzzle) { this.puzzle = puzzle; } @Override public boolean equals(Object object) { // ... } @Override public int hashCode() { // ... } } and then you wrap all your puzzles, put them in a map, and get them out again… public Collection<Collection<Puzzle>> method(Collection<Puzzles> puzzles) { Map<Wrapper,<Collection<Puzzle>> map = new HashMap<Wrapper,<Collection<Puzzle>>(); for (Puzzle each: puzzles) { Wrapper wrapper = new Wrapper(each); Collection<Puzzle> coll = map.get(wrapper); if (coll == null) map.put(wrapper, coll = new ArrayList<Puzzle>()); coll.add(puzzle); } return map.values(); } A: Okay you have a way of measuring similarity between objects. That means they form a Metric Space. The question is, is your space also a Euclidean space like normal three dimensional space, or integers or something like that? If it is, then you could use a binary space partition in however many dimensions you've got. (The question is, basically: is there a homomorphism between your objects and an n-dimensional real number vector? If so, then you can use techniques for measuring closeness of points in n-dimensional space.) Now, if it's not a euclidean space then you've got a bigger problem. An example of a non-euclidean space that programers might be most familiar with would be the Levenshtein Distance between to strings. If your problem is similar to seeing how similar a string is to a list of already existing strings then I don't know of any algorithms that would do that without O(n2) time. Maybe there are some out there. But another important question is: how much time do you have? How many objects? If you have time or if your data set is small enough that an O(n2) algorithm is practical, then you just have to iterate through your list of objects to see if it's below a certain threshold. If so, reject it. Just overload AbstractCollection and replace the Add function. Use an ArrayList or whatever. Your code would look kind of like this class SimilarityRejector<T> extends AbstractCollection<T>{ ArrayList<T> base; double threshold; public SimilarityRejector(double threshold){ base = new ArrayList<T>(); this.threshold = threshold; } public void add(T t){ boolean failed = false; for(T compare : base){ if(similarityComparison(t,compare) < threshold) faled = true; } if(!failed) base.add(t); } public Iterator<T> iterator() { return base.iterator(); } public int size() { return base.size(); } } etc. Obviously T would need to be a subclass of some class that you can perform a comparison on. If you have a euclidean metric, then you can use a space partition, rather then going through every other item. A: * *Create a TreeSet using your Comparator *Adds all elements into the set *All duplicates are stripped out A: Normally "similarity" is not a transitive relationship. So the first step would be to think of this in terms of equivalence rather than similarity. Equivalence is reflexive, symmetric and transitive. Easy approach here is to define a puzzle wrapper whose equals() and hashCode() methods are implemented according to the equivalence relation in question. Once you have that, drop the wrapped objects into a java.util.Set and that filters out duplicates. A: IMHO, most elegant way was described by Gili (TreeSet with custom Comparator). But if you like to make it by yourself, seems this easiest and clearest solution: /** * Distinct input list values (cuts duplications) * @param items items to process * @param comparator comparator to recognize equal items * @return new collection with unique values */ public static <T> Collection<T> distinctItems(List<T> items, Comparator<T> comparator) { List<T> result = new ArrayList<>(); for (int i = 0; i < items.size(); i++) { T item = items.get(i); boolean exists = false; for (int j = 0; j < result.size(); j++) { if (comparator.compare(result.get(j), item) == 0) { exists = true; break; } } if (!exists) { result.add(item); } } return result; }
doc_23538643
id sensorValue timeStamp delta 1 586 08-11-16 23:39 0 2 595 08-11-16 23:44 9 3 586 08-11-16 23:49 -9 4 586 08-11-16 23:55 0 5 586 08-11-16 23:59 0 6 576 09-11-16 00:04 -10 7 595 09-11-16 00:09 19 8 586 09-11-16 00:14 -9 9 586 09-11-16 00:19 0 with rows all the way for 2 months. Now, if i smooth (considering the gas expansion as 2% of the tank capacity, 960 liters) and ggplot the sensorValues in the time span it gives me a graph like this: The problem is when i try to count the decrements and increments in the graph, each row pointing down have to count one decrement and each arrow pointing upwards have to count as an increment, but if you notice each row represents a 5 minute register in my dataframe, and each increment or decrement consists of more than one row, i wonder if there is a way to count the times when the tank was filled, and when the gas in the tank is being used, ignoring the normal expansion of the volume due to termal contraction or expansion. Here is the output of dput(df[1:50,]): structure(list(sensorValue = c(586, 595, 586, 586, 586, 576, 595, 586, 586, 576, 586, 576, 576, 586, 586, 586, 586, 586, 595, 586, 586, 586, 586, 576, 586, 586, 586, 595, 586, 576, 576, 586, 586, 586, 595, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 595, 586, 586, 586), TimeStamp = structure(c(1478669973, 1478670292, 1478670583, 1478670901, 1478671193, 1478671482, 1478671773, 1478672092, 1478672383, 1478672673, 1478672993, 1478673283, 1478673575, 1478673894, 1478674185, 1478674474, 1478674794, 1478675084, 1478675375, 1478675694, 1478675985, 1478676274, 1478676594, 1478676884, 1478677175, 1478677494, 1478677785, 1478678075, 1478678395, 1478678684, 1478678977, 1478679295, 1478679587, 1478679876, 1478680196, 1478680486, 1478680777, 1478681095, 1478681386, 1478681676, 1478681996, 1478682286, 1478682577, 1478682895, 1478683186, 1478683476, 1478683796, 1478684086, 1478684377, 1478684695), class = c("POSIXct", "POSIXt"), tzone = ""), capacidad = c(961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961), delta = c(0, 9, -9, 0, 0, -10, 19, -9, 0, -10, 10, -10, 0, 10, 0, 0, 0, 0, 9, -9, 0, 0, 0, -10, 10, 0, 0, 9, -9, -10, 0, 10, 0, 0, 9, -9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, -9, 0, 0), smoothValue = c(586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 576, 576, 576, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586)), .Names = c("sensorValue", "TimeStamp", "capacidad", "delta", "smoothValue"), row.names = c(NA, 50L), class = "data.frame") And the output of dput(df[660:720,]): structure(list(sensorValue = c(586, 595, 586, 586, 586, 576, 595, 586, 586, 576, 586, 576, 576, 586, 586, 586, 586, 586, 595, 586, 586, 586, 586, 576, 586, 586, 586, 595, 586, 576, 576, 586, 586, 586, 595, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 595, 586, 586, 586), TimeStamp = structure(c(1478669973, 1478670292, 1478670583, 1478670901, 1478671193, 1478671482, 1478671773, 1478672092, 1478672383, 1478672673, 1478672993, 1478673283, 1478673575, 1478673894, 1478674185, 1478674474, 1478674794, 1478675084, 1478675375, 1478675694, 1478675985, 1478676274, 1478676594, 1478676884, 1478677175, 1478677494, 1478677785, 1478678075, 1478678395, 1478678684, 1478678977, 1478679295, 1478679587, 1478679876, 1478680196, 1478680486, 1478680777, 1478681095, 1478681386, 1478681676, 1478681996, 1478682286, 1478682577, 1478682895, 1478683186, 1478683476, 1478683796, 1478684086, 1478684377, 1478684695), class = c("POSIXct", "POSIXt"), tzone = ""), capacidad = c(961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961), delta = c(0, 9, -9, 0, 0, -10, 19, -9, 0, -10, 10, -10, 0, 10, 0, 0, 0, 0, 9, -9, 0, 0, 0, -10, 10, 0, 0, 9, -9, -10, 0, 10, 0, 0, 9, -9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, -9, 0, 0), smoothValue = c(586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 576, 576, 576, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586, 586)), .Names = c("sensorValue", "TimeStamp", "capacidad", "delta", "smoothValue"), row.names = c(NA, 50L), class = "data.frame") > dput(df[660:720,]) structure(list(sensorValue = c(432, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 432, 442, 490, 922, 912, 922, 922, 932, 912, 922, 922, 922, 922, 922, 922, 922, 922, 922, 932, 912, 912, 922, 922, 912, 922, 912, 922, 912, 922, 912, 922, 922, 922, 912, 912, 912, 922, 912, 922, 922, 922, 922, 903, 912, 912), TimeStamp = structure(c(1478867679, 1478868000, 1478868291, 1478868582, 1478868874, 1478869195, 1478869485, 1478869777, 1478870097, 1478870389, 1478870679, 1478871000, 1478871291, 1478871582, 1478871874, 1478872195, 1478872485, 1478872777, 1478873097, 1478873389, 1478873679, 1478874000, 1478874291, 1478874583, 1478874874, 1478875195, 1478875485, 1478875777, 1478876097, 1478876389, 1478876679, 1478877000, 1478877291, 1478877583, 1478877874, 1478878195, 1478878485, 1478878777, 1478879097, 1478879389, 1478879680, 1478880000, 1478880291, 1478880583, 1478880874, 1478881195, 1478881485, 1478881777, 1478882097, 1478882389, 1478882680, 1478883001, 1478883291, 1478883583, 1478883874, 1478884195, 1478884485, 1478884777, 1478885097, 1478885389, 1478885680), class = c("POSIXct", "POSIXt"), tzone = ""), capacidad = c(961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961, 961), delta = c(-10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -10, 10, 48, 432, -10, 10, 0, 10, -20, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, -20, 0, 10, 0, -10, 10, -10, 10, -10, 10, -10, 10, 0, 0, -10, 0, 0, 10, -10, 10, 0, 0, 0, -19, 9, 0), smoothValue = c(442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 442, 490, 912, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 922, 912, 912, 912, 912, 922, 922, 922, 922, 922, 912, 912, 912)), .Names = c("sensorValue", "TimeStamp", "capacidad", "delta", "smoothValue"), row.names = 660:720, class = "data.frame") A: Based on your question, it looks like you want to count the number of runs when the level is falling or rising. We can use diff and sign to get a vector equal to -1 when the level is falling and 1 when the level is rising. Then we recode that to Falling and Rising, respectively. Finally, to count the number of periods with Falling or Rising level, we create a separate group for each run of Falling or Rising values. library(dplyr) # Fake data set.seed(113) dat = data.frame(sensorValue=cumsum(sample(c(-1,10),100,replace=TRUE,prob=c(10,1))) + 500, timeStamp=seq(0,495,5)) Here's what the fake data look like: library(ggplot2) theme_set(theme_classic()) ggplot(dat, aes(timeStamp, sensorValue)) + geom_line() runs = with(dat, sign(diff(sensorValue))) slope = recode(runs, "-1"="Falling", "1"="Rising") groups = c(0, cumsum(diff(runs) != 0)) run.data = data.frame(runs, slope, groups) run.data %>% group_by(groups) %>% slice(1) %>% group_by(slope) %>% tally slope n 1 Falling 11 2 Rising 10 UPDATE: Based on your comment, it looks like we need to do some filtering to get rid of small ups and downs in the data. You can get fancy and use a low pass filter to get rid of high frequency noise. But in this case, maybe a simpler approach will work. In the code below, we calculate the difference between each successive measurement, just as before, but if the difference is less than 25, we set the difference to zero. You can adjust this cutoff value to whatever seems optimal for getting rid of the small noise jumps without eliminating the larger movements that you're interested in. First, I've combined the two data samples you posted and added a new time2 column that removes the time gap between the two samples, just for this illustration. dat = rbind(dat, dat2) # Put both data samples on a continuous 5-second time scale dat$time2 = seq(0,nrow(dat)*5 - 5, 5) Now we run the same code as before, but with the cutoff value of 25, below which we set the delta to zero. runs = with(dat, sign(ifelse(abs(diff(sensorValue)) < 25, 0, diff(sensorValue)))) slope = recode(runs, "-1"="Falling", "0"="Stable", "1"="Rising") groups = c(0, cumsum(diff(runs) != 0)) run.data = data.frame(runs, slope, groups) run.data %>% group_by(groups) %>% slice(1) %>% group_by(slope) %>% tally slope n <fctr> <int> 1 Falling 1 2 Rising 1 3 Stable 3 One large fall and one large rise seems to be consistent with the data sample: ggplot(dat, aes(time2, sensorValue)) + geom_line(size=1)
doc_23538644
This question will actually answer $resource update method behaving strangely which has become so bloated I felt it might be worth opening a new question since the solution may come in useful outside of the scope of the original question. UPDATE: To clarify, I have the following object as output from console.log: Resource {$get: function, $save: function, $query: function, $remove: function, $delete: function…} id: 1 name: "tits" __proto__: Resource $delete: function (a1, a2, a3) { $get: function (a1, a2, a3) { $query: function (a1, a2, a3) { $remove: function (a1, a2, a3) { $save: function (a1, a2, a3) { $update: function (a1, a2, a3) { So when I pass it through $.param(), all the methods on the object are triggered as part of the serialization process. Instead, I would only like to serialize the properties of the object which do not trigger any other methods.
doc_23538645
A: In each column i, the first non empty cell is set first_ne = cells(2,i) if isempty(first_ne.value) then set first_ne = first_ne.end(xldown) end if A: Note: Their is a difference between blank and empty. For First Non-Blank (as in question title) Try: With Columns("B") .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate End With For First Non-Empty (as in question body) Try: Unlike above this will also find non-empty cells where a formula equates to blank ie =IF(A1=1,A1,"") With Columns("B") .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlFormulas).Activate End With A: Using the IsEmpty function can check if a cell is blank or not: Sub GetFirstNonEmptyCell() Dim startCell as range, firstNonEmptyCell as range Set startCell = Range("B2") 'change this depending on which column you are looking at If VBA.IsEmpty(startCell.Value) Then MsgBox "No data in this column" Else Set firstNonEmptyCell = startCell.End(xlDown) MsgBox "First non empty cell is " & firstNonEmptyCell.Address End If End Sub
doc_23538646
i have been sitting on this problem for days and have tried all sorts of methods but i just cant seem to crack it. Sourcecode: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import {HttpClientModule} from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; import { FrontpageComponent } from './frontpage/frontpage.component'; import { AdministratorComponent } from './administrator/administrator.component'; import { AdminCustomerComponent } from './admin-customer/admin-customer.component'; import { Ng2SearchPipeModule } from 'ng2-search-filter'; import { DatePipe } from '@angular/common'; import { CategoryComponent } from './category/category.component'; import { BookComponent } from './book/book.component'; import { LoginComponent } from './login/login.component'; import { ContactComponent } from './contact/contact.component'; import { CategoryDetailsComponent } from './category-details/category-details.component'; import { BookDetailsComponent } from './book-details/book-details.component'; import { LoanComponent } from './loan/loan.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatDatepickerModule} from '@angular/material/input';//error happens here imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, Ng2SearchPipeModule, BrowserAnimationsModule, MatDatepickerModule,//and here ], providers: [DatePipe], bootstrap: [AppComponent] }) export class AppModule { }
doc_23538647
onTap: function(e) { var nombre = scope.data.nombre; var telefono = scope.data.telefono; if (nombre.length > 0 && telefono.toString().length > 0) { scope.data.nombre = nombre; scope.data.telefono = telefono; return scope.data; } else { ionicToast.show('Debe completar todos los campos.', 'bottom', true, 2500); e.preventDefault(); } } The toast works perfect. But I wanna differentiate when the toast is an error or a success message. The question is: ¿How can I change the style of the toast programmatically? Because Sometimes I need the background red (for error message) and sometimes i need it green (for success message). Also I don't have this toast in my .HTML file, so I can't set a specific style This is my style that I defined: .toast-container-error{ background-color: red; } .toast-container-success{ background-color: green; } Thanks for helping me! //EDIT// Using toastr for my custom toast, it not showing on Android devices index.html <link href="bower_components/toastr/toastr.css" rel="stylesheet"> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" ></script> <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" /> Agenda.service (where I wanna use it) agendaService.$inject = ['remoteDataService','$q', '$ionicPopup', '$rootScope', 'ionicDatePicker']; /* @ngInject */ function agendaService(remoteDataService,$q, $ionicPopup, $rootScope, ionicDatePicker){ var agendaComplejo = []; var service = { obtenerAgenda: obtenerAgenda, cargarNuevoTurno: cargarNuevoTurno, abrirAgenda: abrirAgenda }; toastr.options = { "closeButton": true, "debug": true, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-full-width", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } return service; function cargarNuevoTurnoPopup() { var scope = $rootScope.$new(); scope.data = { nombre: '', telefono: '' }; return { templateUrl: 'scripts/complejo/agenda/nuevo-turno.html', title: "Nuevo Turno", scope: scope, buttons: [{ text: 'Cancelar', onTap: function(e) { scope.data.canceled = true; return scope.data; } }, { text: '<b>Guardar</b>', type: 'button-positive', onTap: function(e) { var nombre = scope.data.nombre; var telefono = scope.data.telefono; if (nombre.length > 0 && telefono.toString().length > 0) { scope.data.nombre = nombre; scope.data.telefono = telefono; return scope.data; } else { toastr["error"]("Debe completar todos los campos.") e.preventDefault(); } } }] }; } Also, I generate the apk with the following command: ionic build android --debug A: It is possible but you have to overide the native style of the component to do this. In our project we use Toastr that give you standard method to display an error or an info and that can be overide more easily. To include it in your project only include the js and the css <script src="toastr.js"></script> <link href="toastr.css" rel="stylesheet"/> Then the api allow you to raise an info or an error toastr.info('yourmessage') toastr.error('your message') toastr.success('your message') You can found a demo here: http://codeseven.github.io/toastr/demo.html
doc_23538648
Thanks Greg A: $data = array('one' => array('sub1' => 42, 'sub2' => 90310), 'two' => array('sub1' => 321, 'sub2' => 10122)); Same thing with "short syntax" $data = [ 'one' => ['sub1' => 42, 'sub2' => 90310], 'two' => ['sub1' => 321, 'sub2' => 10122] ]; A: There are two types of array * *Array like @DFriend answer *Array objects use print_r($arrayName); so that you can see the array structure. For an example, let's say you getting result from the database. and if you use $result = $query->result(); you will get an array object and if you use $result = $query->result_array(); you will get 2D array. those two array will be like below, (@DFriend example) 2D Array $data = array('one' => array('sub1' => 42, 'sub2' => 90310), 'two' => array('sub1' => 321, 'sub2' => 10122)); Array Object link Array ( [0] => stdClass Object ( [id] => 25 [time] => 2014-01-16 16:35:17 [fname] => 4 [text] => 5 [url] => 6 ), [1] => stdClass Object ( [id] => 25 [time] => 2014-01-17 16:35:17 [fname] => 45 [text] => 55 [url] => 66 ) )
doc_23538649
Possible Duplicate: Javascript file uploads I am using jQuery post to Post data to a PHP file. It's working fine for the input text,textarea. But I want it to work with input type file as well. Here's my code, how can I adapt it? <input type="file" name="image"> $.ajax({ type : "post" , url : LIB_PATH + "sharefund/sharefund.php" , data : $("form[name=sharefunds]").serialize() , dataType : "json", success : function(retData){ alert(retData); if(retData != null && retData.hasOwnProperty("response")) { if(retData.response.code == '400') { $("span.error").html("Unable to update address, please try again later .").show(); } if(retData.response.code == '200') { $("span.error").html("Your address has been updated successfully.").css('color' , 'green').show(); } } __removeOverlay(); setTimeout(function(){ $("span.error").slideUp(); }, 5000); } }); A: You can not get the input type file in the jquery form serialization . you have to use the plugins for the ajax file upload.
doc_23538650
A: The problem is that cloned objects will have the same attributes as the original, so it's rather hard to distinguish them, however, you could try this: (function() { //or indeed: querySelector('.combo') which returns a single DOM ref var original = document.querySelectorAll('.combo')[0];//reference to the original //clone and add function removeClones() { var i,all = document.querySelectorAll('.combo'); for(i=0;i<all.length;i++) { if (all[i] !== original) {//this is a clone all[i].parentNode.removeChild(all[i]); } } } }()); That should do it. An alternative method would be to add a class to the clones, prior to appending them to the DOM: var clone = original.cloneNode(true); clone.className += ' combo-clone'; //then, to remove: var clones = document.querySelectorAll('combo-clone');//selects all clones A: Keep a reference to the cloned elements somewhere (such as an array). Loop over that array and call foo.parentNode.removeChild(foo) on each value. A: var fn = function(originalEl){ var els = document.querySelectorAll('.combo'); for(var i=0; i<els.length; i++){ if( els[i] !== originalEl ){ els[i].parentNode.removeChild(els[i]); } } }
doc_23538651
http://imgur.com/a/VkCrJ When my terrain size if 400 x 400 i get clipping, yet at 40x40 or anything less, i don't get any clipping. This is my code to fill the position and indices: void Terrain::fillPosition() { //start from the top right and work your way down to 1,1 double x = -1, y = 1, z = 1; float rowValue = static_cast<float>((1.0f / _rows) * 2.0); // .05 if 40 float colValue = static_cast<float>((1.0f / _columns) * 2.0); // .05 if 40 for (y; y > -1; y -= colValue) { for (x; x < 1; x += rowValue) { _vertexPosition.emplace_back(glm::vec3(x, y, z)); } x = -1; } } This properly sets my position, I've tested it with GL_POINTS. It works fine at 400x400 and 40x40 and other values in between. Index code: void Terrain::fillIndices() { glm::ivec3 triangle1, triangle2; for (int y = 0; y < _columns - 1; y++) { for (int x = 0; x < _rows - 1; x++) { // Triangle 1 triangle1.x = x + y * _rows; triangle1.y = x + (y + 1) * _rows; triangle1.z =(x + 1) + y * _rows; // Triangle 2 triangle2.x = triangle1.y; triangle2.y = (x + 1) + (y + 1) * _rows; triangle2.z = triangle1.z; // add our data to the vector _indices.emplace_back(triangle1.x); _indices.emplace_back(triangle1.y); _indices.emplace_back(triangle1.z); _indices.emplace_back(triangle2.x); _indices.emplace_back(triangle2.y); _indices.emplace_back(triangle2.z); } } } _indices is std::vector.I'm not sure what's causing this, But I'm pretty sure it's the way I'm filling the indices for the mesh. I've re-written my algorhithm and it ends up with the same result, small values work perfectly fine, and large values over ~144 get clipped. I fill my buffers like this: void Terrain::loadBuffers() { // generate the buffers and vertex arrays glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); glGenBuffers(1, &_ebo); // bind the vertex array glBindVertexArray(_vao); // bind the buffer to the vao glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, _vertexPosition.size() * sizeof(_vertexPosition[0]), _vertexPosition.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size() * sizeof(_indices[0]), _indices.data(), GL_STATIC_DRAW); // enable the shader locations glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // unbind our data glBindVertexArray(0); } and my draw call: void Terrain::renderTerrain(ResourceManager& manager, ResourceIdTextures id) { // set the active texture glActiveTexture(GL_TEXTURE0); // bind our texture glBindTexture(GL_TEXTURE_2D, manager.getTexture(id).getTexture()); _shaders.use(); // send data the our uniforms glUniformMatrix4fv(_modelLoc, 1, GL_FALSE, glm::value_ptr(_model)); glUniformMatrix4fv(_viewLoc, 1, GL_FALSE, glm::value_ptr(_view)); glUniformMatrix4fv(_projectionLoc, 1, GL_FALSE, glm::value_ptr(_projection)); glUniform1i(_textureLoc, 0); glBindVertexArray(_vao); // Draw our terrain; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBindVertexArray(0); _shaders.unuse(); } I thought it was because of my transformations to the model, so i removed all transformations and it's the same result. I tried debugging by casting the glm::vec3 to_string but the data looks fine, My projectionMatrix is: glm::perspective(glm::radians(_fov), _aspRatio, 0.1f, 1000.0f); So i doubt it's my perspective doing the clipping. _aspRatio is 16/9. It's really strange that it works fine with small rowsxcolumns and not large ones, I'm really not sure what the problem is. A: I would check the length of _vertexPosition; I suspect the problem is that you are (depending on the number of _rows) generating an extra point at the end of your inner loop (and your outer loop too, depending on _columns). The reason is that the termination condition of your vertex loops depends on the exact behavior of your floating point math. Specifically, you divide up the range [-1,1] into _rows segments, then add them together and use them as a termination test. It is unclear whether you expect a final point (yielding _rows+1 points per inner loop) or not (yielding a rectangle which doesn't cover the entire [-1,1] range). Unfortunately, floating point is not exact, so this is a recipe for unreliable behavior: depending on the direction of your floating point error, you might get one or the other. For a larger number of _rows, you are adding more (and significantly smaller) numbers to the same initial value; this will aggravate your floating point error. At any rate, in order to get reliable behavior, you should use integer loop variables to determine loop termination. Accumulate your floating point coordinates separately, so that exact accuracy is not required.
doc_23538652
https://doc.oroinc.com/backend/setup/dev-environment/docker-and-symfony/ https://doc.oroinc.com/backend/setup/dev-environment/docker-and-symfony/windows/ Requirements etc. are fine. but on Step 5: symfony console oro:install -vvv --sample-data=y --application-url=https://127.0.0.1:8000 --user-name=admin [email protected] --user-firstname=John --user-lastname=Doe --user-password=admin --organization-name=Oro --timeout=0 --symlink --env=prod -n Filling the database etc works fine, but when it comes to translation the installation fails and this error occurs: In Filesystem.php line 190: FilesystemIterator::__construct(/mnt/c/DPI_Projects/OroPlattform/orocommerce-application/var/cache/dev/..Ux0): Failed to open directory: No such file or directory oro:translation:load [-l|--languages [LANGUAGES]] [--rebuild-cache] This is almost all the information I can provide, since I did everything according to the documentation. I have never worked with WSL and Docker before. It would be great if someone with more experience could help me handle this problem. Thanks Alex A: The Oro team recently extended the instruction with much more detail. Please start over to make it work. From what I see, the main issue is that you've installed the application in the Windows filesystem, which is way slower than the Linux filesystem. It may lead to many unexpected issues.
doc_23538653
I created a firefox profile named "eAgency-Client1", following directions similar to these: https://seleniumbycharan.wordpress.com/2015/07/12/how-to-create-custom-firefox-profile-in-selenium-webdriver/ I have a certificate named "client1.p12" that I use to authenticate with a server. I set up the aforementioned profile to use that certificate. After step 7 in the profile creation process, I went to the newly opened firefox browser and went to Options->Privacy & Security->Certificates->View Certificates, selected the "Your Certificates" tab, clicked "Import", browsed to the "client1.p12" file and entered the password. I am using this profile ("eAgency-Client1") with Selenium. I access the site I am working with by using Selenium code like the following: ProfilesIni profile = new ProfilesIni(); FirefoxProfile ffProfile = profile.getProfile("eAgency-Client1"); ffProfile.setPreference("security.default_personal_cert", "Select Automatically"); . . . FirefoxOptions firefoxOptions = new FirefoxOptions(); . . . firefoxOptions.setProfile(ffProfile); . . . driver = new FirefoxDriver(firefoxOptions); . . . driver.get(<URL>); Unfortunately, this code functions differently on my local machine and on the Jenkins server. I checked this by printing out the page source. When I run it locally, the resultant source is what I expect it to be (too long to copy here.) When I run it in Jenkins, I get the following: <html><head><title>400 No required SSL certificate was sent</title></head> <body bgcolor="white"> <center><h1>400 Bad Request</h1></center> <center>No required SSL certificate was sent</center> <hr><center>nginx/1.10.2</center> </body></html> This is what I would get locally before I started using that profile. It indicates that the "client1.p12" was not getting sent. Once I started using the profile, the profile would allow firefox to send the certificate. I know, however, that the profile was successfully copied to Jenkins and is being used, because if it was not the following line FirefoxProfile ffProfile = profile.getProfile("eAgency-Client1"); would return a null. It does not, so the profile it returns is legitimate. This profile is identical to what I have locally and it should have the information to provide the certificate. It does not, however, appear to be sending the certificate. Does anyone have any idea how this could be happening? The evidence suggests that the profile allows the user to send the certificate. The evidence also suggests that the Jenkins project is using the profile. However, it also looks like the certificate is not getting sent. Any idea what the weak link could be? A: The problem appears to have been the fact that I was attempting to copy the profile from windows to linux. Despite what some information I have read (http://forum.notebookreview.com/threads/migrate-firefox-profile-from-windows-to-linux.444601/ ) appears to say, it looks like the profile needs to be set up on a CentOS machine. I simply acquired a CentOS instance with a desktop, set up the profile there and copied it to the firefox instance on the GUIless machine I was using. That simple.
doc_23538654
about HTTPservice.send() HTTPservice.send() didn't work when request object has Object in the Array.(my coworker reported PHP's server side log show that POST query is wrong, thus I suspected transformation mistake from Object to POST Parameter) sample code saveService = new HTTPService(); var action_url:String = "save_score.json"; saveService.url =api_url; saveService.method = "POST"; saveService.resultFormat = mx.rpc.http.HTTPService.RESULT_FORMAT_TEXT; saveService.addEventListener(ResultEvent.RESULT, saveResult); saveService.addEventListener(FaultEvent.FAULT, saveFault); var params:Object = new Object();; params.score_id = SCORE_ID; params.boxes = new Array(); var boxArray:Array = [ { "column" : 1, "row" : 1, "symbol" : "GUItest", "explanation" : "GUItest", "pronunciation" : "GUItest", "subsymbols" : [ { "division" : 1, "subsymbol_id" : 1 } ] }] params.boxes = boxArray; saveService.send(); I evade this issue by using URLRequest, URLVariables, URLLoader, but I hope your advice. A: In general, when POSTing an object or building an object from HTTP reply data, have a look at HTTPService's serializationFilter. You provide an adapter, which should be able to do the actual object/flat and flat/object conversions.
doc_23538655
I have a Qt IFW installer with an online repository, from which users fetch data to install and update the software. My installer has a "root script" defined in config.xml: <Installer> <!-- ... --> <ControlScript>controllerscript.qs</ControlScript> </Installer> Now I want to change the content of controllerscript.qs and deploy it on the online repository. * *when a new user installs the software for the first time, it works as expected *when a user updates its software from a previous version using MaintenanceTool.exe, it does not get the update Possible solution I realized that when you create the installer, it generates a file named MaintenanceTool.dat which seems to contain controllerscript.qs (+ other things). I managed to manually copy that file and push it to the online repository (inside a package). That way, the maintenance tool is able to see the package update, and correctly gets the new MaintenanceTool.dat. After that, the maintenance tool is indeed using the new code from controllerscript.qs. Question * *Is there another (cleaner) way to achieve that? *If not, is it really safe to provide a manual update to MaintenanceTool.dat? That file contains many other things, so is there a risk to interfere with the rest? Thanks,
doc_23538656
Each table contains an "id_employees" column, and then a number of bit columns to define access to certain areas of different apps. There are a varying number of bit columns in each table, each with different names, and new tables will be added as new sections are developed. I am using Kendo and MVC, and what I would like to do is have one view with a dropdown of all tables, and load a partial view underneath with a grid of the bits from the selected table. These would both be dynamically generated from the database, meaning we'd only have to add another table to the database, without having to modify the controlling program too. I currently have a stored procedure which returns all access_ tables, and the columns in each. These are then put into classes similar to: Public Class access_parent { public access_parent() { AccessParams = new List<access_params>(); } public string TableName { get; set; } public virtual List<access_params> AccessParams { get; set; } } Public Class access_params { public string ParamName { get; set; } public string ParamValue { get; set; } public virtual access_parent AccessParent {get; set; } } but I'm not sure this is the correct approach. I should be able to handle the Kendo and MVC code, if I could just figure out the correct way to handle the situation, but to be honest I'm lost. Is there a way to do this or am I making work for myself by trying to be too clever and ending up dumb?
doc_23538657
My array looks like: "data" => array:2 [▼ 0 => array:5 [▶] 1 => array:5 [▶] I want to show div if topic from link is the same topic from array. But I do not know how to search and compare that words. So it will be like that: v-if="$topic == this.topic" But now I can only use v-if="$data[]['0']['topic']" and then I have the same topic on all my views. My link looks like: /user/{topic}/post How to do it correctly guys? A: I did it using foreach, the easiest way :)
doc_23538658
Thanks and regards Rithesh A: you can read any key/value from Web.Config. Try these lines of code: NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("YOUR_SECTION_NAME_HERE"); string data = section["YOUR_KEY"]; Hope it helps.
doc_23538659
I want to know: * *What methods should repositories contain? *What should repositories definitely (or closer that) return? Thanks. A: For each aggregate root (AR) you should have a repository. As a minimum the repository would probably have a void Save(Aggregate aggregate) and a Aggregate Get(Guid id) method. The returned aggregate would always be fully constituted. I sometimes add methods for specific use cases in order to update only certain bits of data. For instance, something like void Activate(Guid id) or some such. This is simply to avoid manipulating more data than is necessary. Querying on a repository is usually problematic since you should typically avoid querying your domain. For such scenarios my recommendation is to use a query mechanism that is closer to the data and in a more raw format than a domain object or object graph. The query mechanism would more-then-likely return primitives, such as int Count(Query.Specification specification) or perhaps return a list of read model instances. A: You are right, a repository has different meanings in different contexts - and many authors have their own interpretation. The way I understand them is from multiple perspectives: * *They abstract away underline storage type *They can introduce interface closer to the domain model *They represent a collection of objects and thus serve as aggregate in-memory storage(collection of related objects) *They represent a transaction boundary for related objects. *They can't contain duplicates - like sets. *It is valid for the repository to contain only one object, without complex relations internally So to answer your questions, repositories should contain collection related methods like add, remove, addAll, findByCriteria - instead of save, update, delete. They can return whole aggregate or parts of aggregates or some internal aggregate relation - it is dependent on your domain model and the way you want to represent objects A: Eric Evans coined "domain driven design" in 2003; so the right starting point for any definitions in that context is his book. He defines the repository pattern in chapter 6 ("Lifecycle of a Domain Object"). A REPOSITORY represents all objects of a type as a conceptual set (usually emulated). It acts like a collection, except with more elaborate querying ability. Objects of the appropriate type are added and removed, and the machinery behind the repository inserts them or deletes them from the database. ... For each type of object that requires global access, create an object that can provide the illusion of an in-memory collection of all objects of that type. The primary use case of a repository: given a key, return the correct root entity. The repository implementation acts as a module, which hides your choice of persistence strategy (see: Parnas 1971).
doc_23538660
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y] It is in the context of a tik tac toe program, and if you want to see it, here it is: starting_message = 'Greetings, X Shall Go First And O Shall Go Second. ' prompt = 'Shall We Begin?(Y Or N) ' instructions = 'Pick A Number(1-9)' box = ["1", "2", "3", "4", "5", "6", "7", "8" ,"9"] print(starting_message) get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y] player_begin = raw_input(prompt) if player_begin == 'Y': print(instructions) else: if player_begin == 'N': quit() player = 'X' def is_winner(boxes): if 6 in boxes and 7 in boxes and 8 in boxes: return True elif 5 in boxes and 4 in boxes and 3 in boxes: return True elif 2 in boxes and 1 in boxes and 0 in boxes: return True elif 0 in boxes and 4 in boxes and 8 in boxes: return True elif 1 in boxes and 4 in boxes and 7 in boxes: return True elif 0 in boxes and 3 in boxes and 6 in boxes: return True elif 2 in boxes and 5 in boxes and 8 in boxes: return True elif 2 in boxes and 4 in boxes and 6 in boxes: return True else: return False def is_tie(boxes): if all boxes == 'X' or 'O' and is_winner(boxes) is false: return True else return False def is_occupied(index,boxes): return boxes[index - 1] == 'X' or boxes[index - 1] == 'O' while True: if player == 'X': print('Your Turn X') else: print('Your Turn O') board = ''' ___________________ | | | | | '''+box[0]+''' | '''+box[1]+''' | '''+box[2]+''' | | | | | |-----------------| | | | | | '''+box[3]+''' | '''+box[4]+''' | '''+box[5]+''' | | | | | |-----------------| | | | | | '''+box[6]+''' | '''+box[7]+''' | '''+box[8]+''' | | | | | ___________________ ''' player_board = raw_input(board) if is_occupied(int(player_board), box): print('This Box Is Not Avaliable') else: if player == 'X': box[int(player_board) - 1] = "X" player = 'O' #False else: box[int(player_board) - 1] = "O" player = 'X' #True if is_winnerX(get_indexes('X', box)): print('X WINS!!') quit() elif is_winnerX(get_indexes('O', box)): print('O WINS!!') quit() elif is_tie(boxes): print() quit() else: 'return' A: It finds the indexes where there are is a X or an O, depending on how you call it. Lets say that box = ['1', '2', 'X', 'O', '5', 'X', '7', '8', 'O']. Now, you call get_indexes, passing 'X', meaning that you want to find the indexes of all the X's, and passing in box, like so: get_indexes('X', box). The first thing that happens is the zip. To see what is happening, let's print it out: print([i for i in zip(box, range(len(box)))]) # and we get: [('1', 0), ('2', 1), ('X', 2), ('O', 3), ('5', 4), ('X', 5), ('7', 6), ('8', 7), ('O', 8)] Let's look at the first tuple, ('1', 0). Well, where did the '1' come from? Well, if you look at box you will see that it is the first index. That means that the 0 must be the index of '1'! The next part is here : lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y] # this part ---> (y, i) <--- this part What's happening here is y and i are beging set to ('1', 0). So y is being set to '1', and i to 0. Now we come to if x == y. If you remember from the beginning, x = 'X'. Well, y is equal '1' not 'X', so i, or the index of '1', is not appended to the list. Skip to the third tuple ('X', 2). y is set to 'X'. if x == y will return True, and the index of y (i) will be appended to the list. So after looping through all the tuples, get_indexes will return [2, 5]. You could also accomplish the same thing with enumerate(xs) instead of using zip(xs, range(len(xs))). Like this: get_indexes = lambda x, xs: [idx for idx, ele in enumerate(xs) if ele == x] # idx is the index, and ele is current item/element
doc_23538661
A: As long as you have an Internet connection you can use http://jsfiddle.net for testing snippets of code. You can also select a js framework to work with on the left navigator.
doc_23538662
Seems the button (by clicking the 'Choose file') opens a native file picker, which cypress Webdriver doesn't seem to support interacting with, so probably trigger an event to simulate file selection can be an option in this case. But the input(type=file) can't be located by Cypress because it is not a part of DOM, which means cy.get('input[type=file]') returns null. Could you please give me some thoughts how to do it? this button opens a native file picker I've tried with this - const testfile = new File(['test data to upload'], 'upload.csv') cy.get('input[type=file]').trigger('change', { force: true, data: testfile, }); this brings no luck,because of CypressError: Timed out retrying: Expected to find element: 'input[type=file]', but never found it. The source code of the page: import React, { Component } from 'react' interface Props { text?: string type?: string | undefined fileID?: string onFileSelected: (file: any) => void } interface State { name: string } export default class FileUpload extends Component<Props, State> { fileSelector = document.createElement('input') state: State = { name: '', } componentDidMount() { this.fileSelector = this.buildFileSelector() } buildFileSelector = () => { const { fileID, type } = this.props this.fileSelector.setAttribute('type', 'file') this.fileSelector.setAttribute('id', fileID || 'file') this.fileSelector.setAttribute('multiple', 'multiple') this.setAcceptType(type) this.fileSelector.onchange = this.handleFileChange return this.fileSelector } setAcceptType = (type: string | undefined) => { if (type) { type = type[0] === '.' ? type : type.replace(/^/, '.') this.fileSelector.setAttribute('accept', type) } } handleFileChange = (event: any) => { const file = event.target.files[0] if (file) { this.setState({ name: file.name }) this.props.onFileSelected(file) } } render() { const { name } = this.state return ( <div> <button onClick={(event: React.ChangeEvent<any>) => { event.preventDefault() this.fileSelector.click() }} style={{ marginRight: 10 }} > {this.props.text || 'Choose file'} </button> <label>{name || 'No file chosen'}</label> </div> ) } } I look forward to receiving suggestions how to automate this 'choose file' action in Cypress. Thanks in advance. A: I sorted out this issue by putting an input(type=file) element into the DOM, so that cypress can locate the element and manipulate it. But regarding the issue I had before I still would like to hear some insights from you if this is still possible to be handled in cypress.
doc_23538663
Notice how when you scroll down, and hover near the edge, white imprints are left outside the canvas on neighbouring divs. Why does this happen, and how do I fix it? var canvas = document.querySelector('canvas'); canvas.width = document.body.clientWidth; canvas.height = document.body.clientHeight; var context = canvas.getContext('2d'); var mouse = { x: undefined, y: undefined } window.addEventListener('mousemove', function(event){ mouse.x = event.x; mouse.y = event.y; }); function Circle(x, y, dx, dy, radius, bg){ this.x = x; this.y = y; this.dx = dx; this.dy = dy; this.radius = radius; this.defaultRadius = radius; this.bg = bg; this.draw = function(){ context.beginPath(); context.arc(this.x, this.y, this.radius, 0, Math.PI*2, false); context.fillStyle = this.bg; context.fill(); } this.update = function(){ if (this.x + this.radius > innerWidth || this.x - this.radius < 0) { this.dx = -this.dx; } if (this.y + this.radius > innerHeight || this.y - this.radius < 0) { this.dy = -this.dy; } if (this.x - mouse.x < 50 && this.x - mouse.x > -50 && this.y - mouse.y < 50 && this.y - mouse.y > -50) { if (this.radius < 30) { this.radius += 5; } } else { if (this.radius > this.defaultRadius) { this.radius -= 1; } } this.x += this.dx; this.y += this.dy; this.draw(); } } var circlesArray = []; for(var i = 0; i < 300; i++){ addNewCircle(); } function addNewCircle(){ var radius = (Math.random() * 2) + 1; var x = (Math.random() * (innerWidth - (radius*2))) + radius; var y = (Math.random() * (innerHeight - (radius*2))) + radius; var dx = Math.random() - 0.5; var dy = Math.random() - 0.5; var bg = 'rgba(255, 255, 255, 0.1)'; circlesArray.push(new Circle(x, y, dx, dy, radius, bg)); } function animate(){ requestAnimationFrame(animate); context.clearRect(0, 0, innerWidth, innerHeight); for(var i = 0; i < circlesArray.length; i++){ circlesArray[i].update(); } } animate(); *{ box-sizing: border-box; font-family: 'Roboto', sans-serif; font-weight: 400; margin: 0; padding: 0; color: rgba(0,0,0, 0.8); } #page{ width: 100%; height: 100vh; background: rgba(0, 0, 0, 0.7); } #page canvas{ position: absolute; top: 0; left: 0; } #top-bar{ width: 100%; height: 200px; background: black; } <!DOCTYPE html> <html> <body> <div id="page"> <canvas></canvas> </div> <div id="top-bar"> </div> </body> </html> A: Your canvas is setting height based on body, but your #top-bar div is taking up some of that space. So that extra space is where you #top-bar div is You could set the canvas size to be (body - #top-bar height).
doc_23538664
After creating the .ipa file and use the URL to download, it only works with my device (iPhone ios 12.3.1). In other devices, it just stopped downloading at the end. Steps used to create the .ipa file and the URL: * *using flutter command to build a release ios (flutter build ios --release) *archive it using XCode 10.2.1 *export .ipa file using Adhoc (I am using individual apple developer membership) *using this site (https://www.diawi.com/) to create the URL The libraries used is: * *flutter_bloc: ^0.17.0 *firebase_auth: ^0.11.1+6 *cloud_firestore: ^0.12.5 *firebase_storage: ^3.0.1 *firebase_messaging: ^5.0.3 *intl: ^0.15.8 *cached_network_image: ^1.0.0
doc_23538665
While running the test on Django, the test fails with the below error, Migration went fine. django.db.utils.ProgrammingError: relation "table_name_GeoLocation_id" already exists If I comment out below line on models, it gets passed. test_db seems to be trying to create an index twice. Can I get some help on that? indexes = [GinIndex(fields=["GeoLocation"])] A: I got an answer for this, Creating geometry field in geodjango automatically created index for us. Unless we specifically pass spatial_index=False to the PointField(), the index is already available. Removing an explicit index indexes = [GinIndex(fields=["GeoLocation"])] from the above ques has actually solved the problem. Thanks!
doc_23538666
along with express, ejs, socket.io Below is a working repo I cloned from https://github.com/ngrt/simpleChatApp Folder Structure for simplechatApp app.js views public views index.js public chat.js style.js This is the app.js file in which I rendered the index.js file and used public .. Now the Problem is in the second pic ...in the index.ejs file Here when I am linking it with the external css file (style.css) which is in another folder (namely the public folder).....How can I be writing href=style.css I think this shouldn't work for files in different folder ..... but it seems to work Similarly here when including the external chat.js which is a different folder again writing src ="chat.js" works , but again I think it shouldn;t be working for a file in a different folder Can Someone please explain how is this working ....this is my first project so I am not much used to all this A: Take a look at middleware: Middleware middlewares You can find this below statement in app.js file app.use(express.static('public')) the above line means : Serving static files in Express. To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The function signature is: express. static(root, [options]) The root argument specifies the root directory from which to serve static assets. By using middleware we can access style.css and chat.js file in index.ejs file
doc_23538667
class MyComponent extends React.Component { render(){ setTimeout(function(){ myCoolGraphLibrary.createChart({ container : "myChartContainer", series : [...], ... }); },1000); return (<div id="myChartContainer"></div>); } } Without setTimeout, the container is not yet available in the DOM so the call to createChart fails. Is there a better design pattern for achieving this ? A: Use the lifecycle methods. https://facebook.github.io/react/docs/component-specs.html In particular, you'll want to use componentDidMount to run any code that depends on the DOM elements existing. If you're adding event listeners, be sure to remove them in componentWillUnmount EDIT: In response to your comment, your code would look like this: class MyComponent extends React.Component { componentDidMount() { myCoolGraphLibrary.createChart({ container : "myChartContainer", series : [...], ... }); } render() { return (<div id="myChartContainer"></div>); } }
doc_23538668
Given my requirements, I believe I need a global variable in my library that stores the "connected" boolean value and a continual loop that constantly checks for internet connection, comparing the result of that check with my global boolean. Should I do an async loop method with locking around my global boolean? Is there any set design pattern that I could use? Please point me in the right direction as I'm relatively new to asynchronous patterns and design principles, examples would be helpful. Note: I'm also potentially restricted to .NET 4.0, so useful things like Task.Delay might not be available. A: Such an event handler already exists, for physical network connectivity. See Event to Detect Network Change (stackoverflow.com) However, if you would like to do it yourself, or want to check for other conditions (like internet access) you could implement it thus: public static bool IsConnected { get; protected set; } protected readonly static object _sync = new object(); protected static Task NetworkTask; public static void Start(int period = 1000) { NetworkTask = Task.Run(() => { lock (_sync) { IsConnected = MyNetworkManager.IsConnected(); System.Threading.Thread.Sleep(period); } }); } Please note you cannot lock a boolean directly, since it is a value type, but you can create a readonly object to act as a proxy for the lock.
doc_23538669
<html> <script src="https://www.gstatic.com/firebasejs/3.8.0/firebase.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script> var config = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "" }; firebase.initializeApp(config); var database = firebase.database().ref(); //get a reference to firebase database service var textboxRef = database.child('textbox'); //Get a reference to the "textbox" child var $textbox = $('#textbox'); //Saves a reference to the textarea element using jQuery //When anything changes (added, removed, updated) in the "textbox" child in the database textboxRef.on('value', function(snapshot) { console.log("From Firebase:", snapshot.val()); $textbox.val(snapshot.val().text); //Set the value of the textarea to the value returned by Firebase (specifically the "text" property of the "textbox" child) }); //When any key is released while the textarea is in focus $textbox.keyup(function() { //Updates the properties and values in the database child called "textbox" with the object provided. The "set" function is used instead of the "update" function so that if the database child "textbox" of its properties are removed, this will create it as well as update it textboxRef.set({ text: $textbox.val() }); }); </script> <link rel="stylesheet" href="style.css"> <textarea name="textbox" id="textbox" placeholder="Type here"></textarea> </html> I am very new to Firebase Realtime Database, too.
doc_23538670
My problem is that as soon as I include jquery the tabs all break and all the information from each tab is jut rendered on the current tab. For instance, you can download the demo that easytabs uses here: http://jspkg.com/packages/easytabs If you open demo.html and include the following line: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> The tabs break and render all the content on one page. What gives?
doc_23538671
Can anyone help me add the segue for UITabBarController? If I add a push segue on the login button, it will go to UITabBarController directly irrespective of the validation status. A: you can tie your button from your storyboard to an IBAction in your initial view controller. then you can create a push segue (named "pushToTabBarController" for reference in this answer) from that same view controller to the UITabBarController finally, in the IBAction code for your login button, you can validate, and if happy with the validation, then call - (IBAction) validateThenPush:(id)sender { if ([self loginValidated]) [self performSegueWithIdentifier:@"pushToTabBarController" sender:self]; } (sender:self can be nil or the button passed to the action or whatever you want for context in prepareForSegue:sender:)
doc_23538672
Right now I'm using an options.html file to save user preferences to localstorage, as you can see here: <html> <head><title>Options</title></head> <script type="text/javascript"> function save_options() { var select = document.getElementById("width"); var width = select.children[select.selectedIndex].value; localStorage["site_width"] = width; } function restore_options() { var fwidth = localStorage["site_width"]; if (!fwidth) { return; } var select = document.getElementById("width"); for (var i = 0; i < select.children.length; i++) { var child = select.children[i]; if (child.value == fwidth) { child.selected = "true"; break; } } } </script> <body onload="restore_options()"> Width: <select id="width"> <option value="100%">100%</option> <option value="90%">90%</option> <option value="80%">80%</option> <option value="70%">70%</option> </select> <br> <button onclick="save_options()">Save</button> </body> </html> I also have a background.html file to handle the communication between the content script and the localstorage: <html> <script type="text/javascript"> chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method == "siteWidth") sendResponse({status: localStorage["site_width"]}); else sendResponse({}); }); </script> </html> Then there's the actual content script that looks like this: var Width; chrome.extension.sendRequest({method: "siteWidth"}, function(response) { width = response.status; }); None of that code actually works. It looks solid enough to me but I'm not a very experienced programmer so I might be wrong. Could someone explain localstorage to me in layman's terms? A: The window.localStorage has getters and setters that need to be used in order to access the internal object map. So, to set: localStorage.setItem(key, value); To get: localStorage.getItem(key); To clear map: localStorage.clear(); To remove item: localStorage.removeItem(key); To get length: localStorage.length To key based on index in internal map: localStorage.key(index); To read more: http://dev.w3.org/html5/webstorage/#the-storage-interface The window.localStorage implements the Storage interface: interface Storage { readonly attribute unsigned long length; DOMString key(in unsigned long index); getter any getItem(in DOMString key); setter creator void setItem(in DOMString key, in any value); deleter void removeItem(in DOMString key); void clear(); }; A: To learn how localStorage works and in detail Complete details about LocalStorage is a good source for you to begin with. Just to add I will give you an example which might help you. This is the options.html <html> <head> <script type='text/javscript'> function save_options() { if(document.getElementById("x").checked == true){localStorage['x_en'] = 1;} if(document.getElementById("x").checked == false){localStorage['x_en'] = 0;} } function restore_options() { var x_opt = localStorage['x_en']; if (x_opt == 0) {document.getElementById('x').checked = false;}else{ var select = document.getElementById('x');select.checked = true; localStorage['x_en'] = 1;} } </script> </head> <body onload="restore_options()"> <table border="0" cellspacing="5" cellpadding="5" align="center"> <tr class='odd'><td><input type='checkbox' id='x' onclick="save_options()"/></td><td>X</td></tr> </table> To access this you need to have a background.html page which can be as shown below. alert(localStorage['x_en']); //Will alert the localStorage value. If you want to access the localStorage from the Content Script you can't directly access it by the above method. You need to use the concept called Message Passing (http://code.google.com/chrome/extensions/messaging.html) which can pass the values from the background to content scripts. Just as Sergey said this might be an issue with the typo. A: Using accessors isn’t mandatory, feel free to use [] operator to get and set values, and “in” operator to test if key exists. However, it looks like there’s a typo in your content script: var Width; chrome.extension.sendRequest({method: "siteWidth"}, function(response) { width = response.status; }); Since JavaScript is case-sensitive, these two are different variables. A: try using window.localStorage.getItem/setItem instead of localStorage["site_width"]
doc_23538673
SwipeTouchListener.java public class SwipeTouchListener implements View.OnTouchListener { private final GestureDetector gestureDetector; public SwipeTouchListener(Context context) { gestureDetector = new GestureDetector(context, new GestureListener()); } @Override public boolean onTouch(View view, MotionEvent motionEvent) { gestureDetector.onTouchEvent(motionEvent); return true; } public void onSwipeLeft() { } public void onSwipeRight() { } private class GestureListener extends GestureDetector.SimpleOnGestureListener{ private static final int SWIPE_DISTANCE_THRESHOLD = 100; private static final int SWIPE_VELOCITY_THRESHOLD = 100; @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float distanceX = e2.getX() - e1.getX(); float distanceY = e2.getY() - e1.getY(); if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (distanceX > 0) onSwipeRight(); else onSwipeLeft(); return true; } return false; } } } And in my Activity, I call the following method and override the onSwipeLeft() and onSwipeRight() and show a Toast message on both. chartFlipper.setOnTouchListener(new SwipeTouchListener(this){ @Override public void onSwipeLeft() { Toast.makeText(DashboardActivity.this, "Swipe Left", Toast.LENGTH_SHORT).show(); } @Override public void onSwipeRight() { Toast.makeText(DashboardActivity.this, "Swipe Right", Toast.LENGTH_SHORT).show(); } }); But the problem is, I only see the toast messages on very few occasions. I put a breakpoint in onDown method and found out, it only gets called a few times (like once in 20 maybe). EDIT : I called this method on a ViewFlipper. EDIT 2 : I am showing a pie chart and a bar chart in the ViewFlipper as 2 views. I just found out that swiping over the charts doesn't register as a touch. Is there a way to get around this? A: in your method @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float distanceX = e2.getX() - e1.getX(); float distanceY = e2.getY() - e1.getY(); if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (distanceX > 0) onSwipeRight(); else onSwipeLeft(); return true; } return false; } you have AND condition for distance covered by user should be greater than the SWIPE_DISTANCE_THRESHOLD distance which might not true in every case and you have another AND condition for SWIPE_VELOCITY_THRESHOLD in many cases this could be lower than the threshold value.So you are seeing results only in the cases distance is more than the threshold and velocity is also more than the threshold velocity try to lower these values and you will see results more often
doc_23538674
A: You have two options: * *Create your own package and load it on the start-up, you will have all the function available. A tutorial *Customize R start-up loading automatically your R files containing your functions. A tutorial and an example A: We can create a package in R * *Bundle the functions and create a package -yourpackage and then load the package library(yourpackage) *One example is here *Another resource is here *Yet another is here A: If you don't wish to take the package approach (which I agree is the best approach), you could stack all your functions on top of one another in an R script and source it on startup. One step instead of 6. End up with all the functions in your .GlobalEnv Put this in an R script: ###Put in a script eeee <- function(){ cat("yay I'm a function") } ffff <- function(){ cat("Aaaaaah a talking function") } If you use RStudio, the code would be as below. Otherwise change the source location. Do this in console (or in a script): ###Do this source('~/.active-rstudio-document') Then you can do: eeee() yay I'm a function ffff() Aaaaaah a talking function A: You can run the below script before starting your work: source_code_dir <- "./R/" #The directory where all source code files are saved. file_path_vec <- list.files(source_code_dir, full.names = T) for(f_path in file_path_vec){source(f_path)}
doc_23538675
I have stored all IP connections from an IDPS into a data frame and trying to identify unique connections The connection is defined as IP1:IP2 is same as IP2:IP1. import pandas as pd import re data = {'IP1': ['168.125.x.1', '10.10.x.1', '10.10.x.1.', '168.125.x.2',10.10.x.2], 'IP2': [10.10.x.1, 168.125.x.1, 168.125.x.1, 10.10.x.2,168.12.5.x.2]} Based on this data, The answer should have been: 168.12.5.x.1 <-> 10.10.x.1 168.12.5.x.2 <-> 10.10.x.2 but I am not getting above answer at all. I appreciate any help you can provide on how to get this implemented in a data frame. df = pd.DataFrame(data) df = df.drop_duplicates(inplace=False) temp1 = df.loc[df['IP1'].isin(df['IP2']) & df['IP2'].isin(df['IP1'])] cleanconnection = df[~df.isin(temp1)].dropna() Thanks
doc_23538676
urls.py path('change-password/', views.change_password, name='change-password'), path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name='reset-password'), path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), I was hoping to customise the django email template and put it as a template_name or similar in one of the correct paths above? Any help would be appreciated. Thanks A: In order to change the email default template, you'll need to: * *Point the template dirs' search directive to your application first, then to Django's default templates if you haven't done: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, ... }, ] * *Make sure that you're editing the right template. It's the password_reset_email.html, you should create a template directory within your application called "registration", and then customize it the way for your likes. But don't forget to use the required fields such as URL token for validation in password reset. So the directory and the structure should be app_dir/templates/registration/password_reset_email.html.
doc_23538677
<a href="/main/list.nhn?mode=LS2D&amp;mid=shm&amp;sid1=100&amp;sid2=264" class="snb_s11 nclicks(lmn_pol.mnl,,1)">BlueHouse <span class="blind">selected</span></a> and then below is my source code to get only Blue House middle_category = soup.find('a',{'class':'snb_s11 nclicks(lmn_pol.mnl,,1)'}) when i run that code to get only Blue House, it's gave me result with selected. but i wanna only Blue House. so How can i do for it? bellow is my full code def crwaling_data_bluehouse(self): # setting web driver to get object chrome_driver = webdriver.Chrome('D:/바탕 화면/인턴/python/crawling_software/crwaler/news_crwaling/chromedriver.exe') url = 'https://news.naver.com/main/list.nhn?mode=LS2D&mid=shm&sid1=100&sid2=264' chrome_driver.get(url) html = chrome_driver.page_source soup = BeautifulSoup(html, 'html.parser') #get main category main_category = soup.find('a',{'class':'nclicks(LNB.pol)'}).find('span',{'class':'tx'}).get_text() self.set_main_category(main_category) #get middle category middle_category = soup.find('a',{'class':'snb_s11 nclicks(lmn_pol.mnl,,1)'}).get_text() middle_category = middle_category.find_next(text = True) self.set_middle_category(middle_category) #get title title = soup.find('ul',{'class':'type06_headline'}).find('a')['href'] self.set_title(title) A: You can use find_next() which will only return the first match: from bs4 import BeautifulSoup txt = """<a href="/main/list.nhn?mode=LS2D&amp;mid=shm&amp;sid1=100&amp;sid2=264" class="snb_s11 nclicks(lmn_pol.mnl,,1)">BlueHouse <span class="blind">selected</span></a>""" soup = BeautifulSoup(txt, 'html.parser') middle_category = soup.find('a', {'class': 'snb_s11 nclicks(lmn_pol.mnl,,1)'}) print(middle_category.find_next(text=True)) Output: BlueHouse Edit don't call get_text(). Instead of middle_category = soup.find('a',{'class':'snb_s11 nclicks(lmn_pol.mnl,,1)'}).get_text() Use middle_category = soup.find('a', {'class': 'snb_s11 nclicks(lmn_pol.mnl,,1)'}).find_next(text=True)
doc_23538678
#economy123{ position:absolute; top:67%; left:53%; } <div class="result-temp" > <img id="economy123" src="{{ asset('assets/images/economy123.png') }}" > </div> A: If you want your image to stay on the same spot even after you resize your browser you need to use pixels instead of percentages. For example: .result-temp{ width: 400px; height: 400px; } #economy123{ position:relative; top: 100px; left: 100px; width: 200px; height: 200px; } <div class="result-temp"> <img id="economy123" src="{{ asset('assets/images/economy123.png') }}" > </div> This will keep the image centered even after the browser is resized.
doc_23538679
//f9 to open action editor //in scene 1: import mx.controls.Button; var b:Button = new Button(); b.label = "My button"; b.width = 100; b.height = 30; b.visible = true; stage.addChild(b); A: The [mx.controls] package contains controls for use in Flex / FlashBuilder. The fl.controls package contains similar, but not necessarily equivalent, controls for use in the Flash IDE. If you just want to use a button, you should do what @Moorthy says and drag the button from the components library, then reference fl.controls.Button. If you absolutely have to use Flex components in Flash, it is possible, you can do it like this: * *Load the Flex swf into your flash *Wait until the loaded Flex component reaches frames 2 (all Flex swf's have 2 frames indeed) *Add the eventlistener (for the event defined in the flex) on the application property of the loaded object. This property is actually a property of the SystemManager class. Remeber the SystemManager class does not exist in Flash. It's a Flex thing. * *this procedure is taken from a nice blog on the subject, here: http://seeing-is-believing.blogspot.co.uk/2007/11/flex-components-in-flash-example-with.html It's worth saying that this makes sense for advanced Flex components, where you don't want to recode a lot of complex behaviour, but it is hard to imagine why you would need mx.controls.Buttton instead of fl.controls.Button, or your own MovieClip, as the behaviour is really quite common and straightforward.
doc_23538680
<div class='btn-group'> <button class='btn btn-inverse playstop' rel='tooltip' data-original-title='Run><i class='icon-play'></i></button> </div> In the script for one condition i have $(".icon-stop", $this.element).attr("data-original-title", "Run"); $(".icon-stop", $this.element).removeClass("icon-stop").addClass("icon-play"); and for other condition i have $(".icon-play", $this.element).attr("title", "Stop"); $(".icon-play", $this.element).removeClass("icon-play").addClass("icon-stop"); A: I have edited to show a full html of a button which changes its text when clicked from Stopped to Running. The tooltip displayed is also changed on click <html> <head> <meta charset="ISO-8859-1"> <title>TestingStuff</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> </head> <script> $(document).ready(function(){ $("#aBtn").click(function(){ if($("#aBtn").html() == "Stopped"){ $("#aBtn").html("Running"); $("#aBtn").attr("title","Running"); } else{ $("#aBtn").html("Stopped"); $("#aBtn").attr("title","Stopped"); } }); }); </script> <body> <div> <button id="aBtn" title="Stopped">Stopped</button> </div> </body> </html> A: I'm not really sure why you need a tooltip that displays the text on a button, but, here's an inelegant, brute force FIDDLE for you to consider. You can play around with the text anyway you want. JS $('.playbutton').html('STOP'); $('.tooltip').html('STOP'); $('.playbutton').on('click', function(){ if ( $('.playbutton').html() == "PLAY" ) { $('.playbutton').html('STOP'); $('.tooltip').html('STOP'); } else { $('.playbutton').html('PLAY'); $('.tooltip').html('PLAY'); } }); $('.playbutton').hover( function(){ $('.tooltip').css('display', 'block'); }, function(){ $('.tooltip').css('display', 'none'); } );
doc_23538681
This is what I've got but it seems to be allowing anything to be returned. int numpad(int min, int max) { int input; do { input=getch() - 48; } while(input<=min && input>=max); return input; } Anyone know what's going wrong here? A: I guess you wrote a wrong token: while(input<=min && input>=max); ^^ Which should have been while(input< min || input> max); ^ ^^ ^
doc_23538682
So there are two keys here: * *Adding to the main preferences screen *Starting an activityForResult when an item is pressed. This activity will show another preferences view (sliders, checkboxes, etc) where the user can manipulate these and then return the new values to be stored in a data structure. Image: A: I would suggest heading down the road of Fragments - specifically PreferenceFragment: http://developer.android.com/reference/android/preference/PreferenceFragment.html Why I think this will work well for you: Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this fragment (as a superclass) to deal with preferences in applications. A: Your question is a little bit vague, but probably this is best solved by storing the user's data in a database (and using standard CursorAdapter and CursorLoader instances to show this data to the user) rather than trying to force everything into the Preferences framework. The CursorAdapter is optimized for dealing with arbitrarily large result sets, while PreferenceActivity and friends really work better with a fixed set of data. The Preferences stuff is designed to be easy to implement for its specific use case, but if your use case falls out of that scope — and it sounds like it does — it's going to be a hassle to squeeze your data into a preferences model. If you just like the Preferences UI, you can of course peek at the Android source code to see how it is implemented while still letting your own logic drive a variant of that UI. A: Actually creating the preference screens dynamically is easy. You can do it in code (search the API Demos sample app for PreferenceFromCode.java) or by expanding an XML file that you can write (PreferencesFromXml.java). What's going to be hard is coming up with a sensible UI and storage back-end for the user to compose and store these dynamic preference collections.
doc_23538683
def inorder(self): if self.__root == None: return '[ ]' else: return '[ ' + self.__inorder(self.__root) + ']' def __inorder(self, root): rep = '' if root != None: rep = self.__inorder(root.leftC) + str(root.value) + ', ' + self.__inorder(root.rightC) return rep A: Use Slicing >>> a = "[1,2,3,]" >>> a[0:len(a)-2]+a[len(a)-1] '[1,2,3]'
doc_23538684
In my module directed_graph there is function algorithm_dijkstra(vertex_name) that I want to execute on the server. Client: from xmlrpc.client import ServerProxy ... if __name__ == '__main__': proxy = ServerProxy('http://127.0.0.1:8080') # filling the graph with data ... test = proxy.algorithm_dijkstra(vertex) # I expect the correct data (dictionary) in test after the function is executed on the server ... Server: from xmlrpc.server import SimpleXMLRPCServer from directed_graph import algorithm_dijkstra def main(): server = SimpleXMLRPCServer(("127.0.0.1", 8080)) print('Server is listening on port 8080...') server.register_function(algorithm_dijkstra) server.serve_forever() if __name__ == '__main__': main() Small clarification: In my module "directed_graph", basically the functions that the client uses, but there is one that I want to perform on the server. I found that if all the functions are performed on the server, then the program works correctly. But how do I delegate only 1 function to the server and not all? A: I solved the problem as follows. On the client, I set and store data for the graph, and on the server I perform only one function algorithm_dijkstra. And for everything to work correctly, need to make the second parameter for function algorithm_dijkstra, namely transfer the graph itself to this function, and not take the graph from somewhere like me tried to do before. And then everything works correctly and as expected.
doc_23538685
But I'm unable to find any information on how to do this from an array of pixels with 4 bytes per color (rgba, bgra, rgb would be ok to since jpeg doesn't support alpha etc.) Not interested in an external library or gdi+. gdi32 should have the ability, but I can't seem to find enough information on how to implement it. A: Plain GDI does not have any support for JPEG. If you won't countenance using a library other than GDI, then you will have to write your own JPEG library. Allow me to recommend that you reconsider your requirements. A: I am going to ignore your refusal to use anything outside of gdi32.dll, because that kind of requirement is not likely to help anyone, and as @David Heffernan said, there is no JPEG support in gdi32.dll. There are a number of ways to load/save JPEG pictures built into winapi, and supported all the way back to Windows 2000 (and earlier...). * *OleLoadPicture / OleSavePicture - though I am not sure if it's very easy to save your own JPEG files this way. *Gdiplus::Image allows loading & saving JPEG files. A: The GDI is the Graphical Device Interface. It's responsibility includes rendering primitives to the screen or offscreen device contexts. Encoders and decoders are not included. The standard Windows encoders and decoders are provided through the Windows Imaging Component. This component is available starting with Windows XP SP2. It is also available for Windows Store apps.
doc_23538686
My naive way to do this in the simplest/fastest manner was to save each string as a file and simply open the file and load the bytes. This won't work since the cluster size is 8k. Can you create a 'zip' of all 100,000 files without compression and would that be a simple and fast way to access the data? Do I have to learn how to do a database? By simple I mean least code and fast I mean this is data is looked up often so must execute quickly. I really liked the file.open(str) idea. EDIT - I don't have control of the strings except they will be unique. It looks like Tokyo Cabinet has a restrictive license, but I'm googling key-value store. Since yep I have no queries I just need to do a lookup and sqllite seems overkill. NSDictionary - I didn't think of this, but I'm not sure I can load the whole thing into memory and keep it there since I don't control the total size. A: Use simple fast nosql database like Tokyo Cabinet. It's very easy to setup/use and will be faster than core data for your needs (you have no complex queries) and much faster than files. A: Sounds like you want to use core data. This would be infinitely faster than having Ks of files. My guess is that this is the fastest and most robust solution. A: This sounds a lot like you just have a simple mapping of string -> data. Something like this in some generic map notation: data = { 'string1' => 0x00000001, 'string2' => 0x00000002, 'string3' => 0x00000003, } It also seems like you don't need to 'query' per-se, but instead you know the key precisely and just need to get its associated value. If this is the case, you could try a simple property list and see if it is performant enough. You can load that file and get back an NSDictionary object to use as you please. If it's not performant (I wouldn't be surprised), a sqlite database or some small embedded key-value store should do the trick.
doc_23538687
I've come across a few examples on the web, however they all are using the 1st date of March and the 1st date of November and thats not technically correct. Daylight savings time begins at 2AM on the 2nd Sunday of March and ends on at 2AM in the first Sunday in November. I've started with the below code but I'm sure its wrong. Any assistance is appreciated! :) DECLARE @DSTSTART DATETIME SELECT @DSTSTART = CASE WHEN DATEPART(MONTH, SYSDATETIME()) = 3 AND DATEPART(weekday, SYSDATETIME()) = 1 AND DATEDIFF(week,dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, SYSDATETIME()), 0)), 0), SYSDATETIME() - 1) = 2 AND DATEPART(HOUR, SYSDATETIME()) = 2 THEN SYSDATETIME() END RETURN (@DSTSTART) END GO A: Personally, I think it's easier to find the first Sunday in November than it is to find the second Sunday in March. Luckily, if you find one, you can find the other because there's always 238 days between them. So here's a handy function to find the end of Dst: create function GetDstEnd ( @Year int ) returns datetime as begin declare @DstEnd datetime; ;with FirstWeekOfNovember as ( select top(7) cast(@Year as char(4)) + '-11-0' + cast(row_number() over(order by object_id) as char(1)) + ' 02:00:00' 'DST_Stops' from sys.columns ) select @DstEnd = DST_Stops from FirstWeekOfNovember where datepart(weekday,DST_Stops) = 1 return @DstEnd; end; Now the Start of Dst is the same function, only 238 days earlier. create function GetDstStart ( @Year int ) returns datetime as begin; declare @DstStart datetime; ;with FirstWeekOfNovember as ( select top(7) cast(@Year as char(4)) + '-11-0' + cast(row_number() over(order by object_id) as char(1)) + ' 02:00:00' 'DST_Stops' from sys.columns ) select @DstStart = dateadd(day,-238,DST_Stops) from FirstWeekOfNovember where datepart(weekday,DST_Stops) = 1 return @DstStart; end; go A: SQL Server version 2016 will solve this issue once and for all. For earlier versions a CLR solution is probably easiest. Or for a specific DST rule (like US only), a T-SQL function can be relatively simple. However, I think a generic T-SQL solution might be possible. As long as xp_regread works, try this: CREATE TABLE #tztable (Value varchar(50), Data binary(56)); DECLARE @tzname varchar(150) = 'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE', @tzname, 'TimeZoneKeyName', @tzname OUT; SELECT @tzname = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\' + @tzname INSERT INTO #tztable EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE', @tzname, 'TZI'; SELECT -- See http://msdn.microsoft.com/ms725481 CAST(CAST(REVERSE(SUBSTRING(Data, 1, 4)) AS binary(4)) AS int) AS BiasMinutes, -- UTC = local + bias: > 0 in US, < 0 in Europe! CAST(CAST(REVERSE(SUBSTRING(Data, 5, 4)) AS binary(4)) AS int) AS ExtraBias_Std, -- 0 for most timezones CAST(CAST(REVERSE(SUBSTRING(Data, 9, 4)) AS binary(4)) AS int) AS ExtraBias_DST, -- -60 for most timezones: DST makes UTC 1 hour earlier -- When DST ends: CAST(CAST(REVERSE(SUBSTRING(Data, 13, 2)) AS binary(2)) AS smallint) AS StdYear, -- 0 = yearly (else once) CAST(CAST(REVERSE(SUBSTRING(Data, 15, 2)) AS binary(2)) AS smallint) AS StdMonth, -- 0 = no DST CAST(CAST(REVERSE(SUBSTRING(Data, 17, 2)) AS binary(2)) AS smallint) AS StdDayOfWeek, -- 0 = Sunday to 6 = Saturday CAST(CAST(REVERSE(SUBSTRING(Data, 19, 2)) AS binary(2)) AS smallint) AS StdWeek, -- 1 to 4, or 5 = last <DayOfWeek> of <Month> CAST(CAST(REVERSE(SUBSTRING(Data, 21, 2)) AS binary(2)) AS smallint) AS StdHour, -- Local time CAST(CAST(REVERSE(SUBSTRING(Data, 23, 2)) AS binary(2)) AS smallint) AS StdMinute, CAST(CAST(REVERSE(SUBSTRING(Data, 25, 2)) AS binary(2)) AS smallint) AS StdSecond, CAST(CAST(REVERSE(SUBSTRING(Data, 27, 2)) AS binary(2)) AS smallint) AS StdMillisec, -- When DST starts: CAST(CAST(REVERSE(SUBSTRING(Data, 29, 2)) AS binary(2)) AS smallint) AS DSTYear, -- See above CAST(CAST(REVERSE(SUBSTRING(Data, 31, 2)) AS binary(2)) AS smallint) AS DSTMonth, CAST(CAST(REVERSE(SUBSTRING(Data, 33, 2)) AS binary(2)) AS smallint) AS DSTDayOfWeek, CAST(CAST(REVERSE(SUBSTRING(Data, 35, 2)) AS binary(2)) AS smallint) AS DSTWeek, CAST(CAST(REVERSE(SUBSTRING(Data, 37, 2)) AS binary(2)) AS smallint) AS DSTHour, CAST(CAST(REVERSE(SUBSTRING(Data, 39, 2)) AS binary(2)) AS smallint) AS DSTMinute, CAST(CAST(REVERSE(SUBSTRING(Data, 41, 2)) AS binary(2)) AS smallint) AS DSTSecond, CAST(CAST(REVERSE(SUBSTRING(Data, 43, 2)) AS binary(2)) AS smallint) AS DSTMillisec FROM #tztable; DROP TABLE #tztable A (complex) T-SQL function could use this data to determine the exact offset for all dates during the current DST rule. A: FWIW, there is much easier option starting with SQL Server 2016. System table 'sys.time_zone_info' has the offsets and DST flag to determine how to convert to the desired timezone. For more information about this table, please see the MS Doc. You can identify the version of your SQL Server by this simple query: SELECT @@VERSION; You can identify the timezone your SQL Server is in by this simple query: SELECT CURRENT_TIMEZONE(); You should be able to put together these resources to convert datetime values to approp. timezone while respecting the DST rules. A: As pointed out in comments, right now (March 2022) this calculation looks likely to change next year: US may not switch off of DST in the fall. Don't forget that daylight saving time schedules change depending on country, and also are subject to change over the years: the current (as of 2013 through 2022) US system took effect in 2007, for example. Assuming you want the current system for the US, here's one form of an answer for any given year. SET DATEFIRST 7 DECLARE @year INT = 2013 DECLARE @StartOfMarch DATETIME , @StartOfNovember DATETIME , @DstStart DATETIME , @DstEnd DATETIME SET @StartOfMarch = DATEADD(MONTH, 2, DATEADD(YEAR, @year - 1900, 0)) SET @StartOfNovember = DATEADD(MONTH, 10, DATEADD(YEAR, @year - 1900, 0)); SET @DstStart = DATEADD(HOUR, 2, DATEADD(day, ( ( 15 - DATEPART(dw, @StartOfMarch) ) % 7 ) + 7, @StartOfMarch)) SET @DstEnd = DATEADD(HOUR, 2, DATEADD(day, ( ( 8 - DATEPART(dw, @StartOfNovember) ) % 7 ), @StartOfNovember)) SELECT @DstStart AS DstStartInUS , @DstEnd AS DstEndInUS or as functions, but you have to know that DateFirst is set to 7, otherwise the math will be off. CREATE FUNCTION GetDstStart ( @Year AS INT ) RETURNS DATETIME AS BEGIN DECLARE @StartOfMarch DATETIME , @DstStart DATETIME SET @StartOfMarch = DATEADD(MONTH, 2, DATEADD(YEAR, @year - 1900, 0)) SET @DstStart = DATEADD(HOUR, 2, DATEADD(day, ( ( 15 - DATEPART(dw, @StartOfMarch) ) % 7 ) + 7, @StartOfMarch)) RETURN @DstStart END GO; CREATE FUNCTION GetDstEnd ( @Year AS INT ) RETURNS DATETIME AS BEGIN DECLARE @StartOfNovember DATETIME , @DstEnd DATETIME SET @StartOfNovember = DATEADD(MONTH, 10, DATEADD(YEAR, @year - 1900, 0)) SET @DstEnd = DATEADD(HOUR, 2, DATEADD(day, ( ( 8 - DATEPART(dw, @StartOfNovember) ) % 7 ), @StartOfNovember)) RETURN @DstEnd END A: I wasn't really satisfied with any of the solutions I found online to convert UTC to local time, so I came up with this function. Have a look at my SO answer here There is some logic in there that calculates whether daylight savings is active based on the standard date range DST uses (Second Sunday in March at 2am, clocks move forward; 1st Sunday in November revert to standard time)
doc_23538688
-1603112 -2785117 -1602727 -2785305 -1600754 -2780565 -1600754 -2786134 -1600752 -2786134 -1600752 -2780560 -1600154 -2779123 -1600356 -2779472 -1600752 -2780283 -1600752 -2780159 -1600754 -2780162 -1600754 -2780287 A: It's likely you have coordinate pairs within the text file you were mentioning (not just a list of negative values as it looks like in the paragraph above). The pairings would look something like this: [ (-1603112, -2785117), (-1602727, -2785305), (-1600754, -2780565), ...etc.. ] With these pairings, you'd construct the polygons you'd like to test for (not sure about the shape/size here since you can connect as many pairs as you want to above) and then test for "similarity" (whether that's in shape/angles/volume etc. -- you'll probably need to be more specific). If you could confirm the coordinate pairing assumptions above and what tests for similarity you'd like to perform, I can help answer the question further.
doc_23538689
File ".../mixin.py", line 10, in <module> QuerySet.__bases__ += (QuerySetExplainMixin,) TypeError: Cannot create a consistent method resolution order (MRO) for bases QuerySetExplainMixin, object the mixin and code I add it with: from django.db import connections from django.db.models.query import QuerySet class QuerySetExplainMixin: def explain(self): cursor = connections[self.db].cursor() query, params = self.query.sql_with_params() cursor.execute('explain %s' % query, params) return '\n'.join(r[0] for r in cursor.fetchall()) QuerySet.__bases__ += (QuerySetExplainMixin,) (credits of the mixin: https://stackoverflow.com/a/39168237/3385534 ) A: This code was written for Python 2, that's why you get a conflict in Python 3, i cannot see another way than below to set the new method on the QuerySet object : from django.db import connections from django.db.models.query import QuerySet def explain(self): cursor = connections[self.db].cursor() query, params = self.query.sql_with_params() cursor.execute('explain %s' % query, params) return '\n'.join(r[0] for r in cursor.fetchall()) type.__setattr__(QuerySet, 'explain', explain) I hope this can help you.
doc_23538690
type (optional, default String): type of the field on the resulting JSON message. Possible values are: String, int, float and boolean. But I can't make it work. This is the snippet of my logback.xml file: <appender name="ELASTIC" class="com.internetitem.logback.elasticsearch.ElasticsearchAppender"> ... <property> <name>elapsed time (ms)</name> <value>%X{elapsedTime}</value> <type>int</type> </property> ... </appender> and I'm configuring logback using JoranConfigurator: String logConfigurationPath = "logback.xml"; if (logConfigurationPath != null) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator config = new JoranConfigurator(); config.setContext(context); context.reset(); config.doConfigure(logConfigurationPath); } catch (JoranException je) { } StatusPrinter.printInCaseOfErrorsOrWarnings(context); } Logback configures OK, but when it tries to process that type tag I get an error: testingdocker | 09:46:13,134 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@68:23 - no applicable action for [type], current ElementPath is [[configuration][appender][properties][property][type]] And Elastic set that tag in the resulting JSON as a String, as I can check in Kibana. How can I use that tag properly so I get number types in Kibana from Logback? A: It seems to be a bug in the appender. If you see Property.java, you will see: public void setType(String type) { try { this.type = Enum.valueOf(Type.class, type.toUpperCase()); } catch (IllegalArgumentException e) { this.type = Type.STRING; } } So, if you set something that is not in Enum, it will use String. This is fine. So we can see about Type: public enum Type { STRING, INT, FLOAT, BOOLEAN } And I think here you are problem! ElasticSearch do not accept the type "int", but "integer". More information about data types: * *Elasticsearch 2.3 *Elasticsearch 6.X
doc_23538691
For Example:- * *Input: 5000 to 6000 Output: 5678 5679 5689 5789 *Input: 90 to 124 Output: 123 124 Brute force approach can make it count to all numbers and check of digits for each one of them. But I want approaches that can skip some numbers and can bring complexity lesser than O(n). Do any such solution(s) exists that can give better approach for this problem? A: I offer a solution in Python. It is efficient as it considers only the relevant numbers. The basic idea is to count upwards, but handle overflow somewhat differently. While we normally set overflowing digits to 0, here we set them to the previous digit +1. Please check the inline comments for further details. You can play with it here: http://ideone.com/ePvVsQ def ascending( na, nb ): assert nb>=na # split each number into a list of digits a = list( int(x) for x in str(na)) b = list( int(x) for x in str(nb)) d = len(b) - len(a) # if both numbers have different length add leading zeros if d>0: a = [0]*d + a # add leading zeros assert len(a) == len(b) n = len(a) # check if the initial value has increasing digits as required, # and fix if necessary for x in range(d+1, n): if a[x] <= a[x-1]: for y in range(x, n): a[y] = a[y-1] + 1 break res = [] # result set while a<=b: # if we found a value and add it to the result list # turn the list of digits back into an integer if max(a) < 10: res.append( int( ''.join( str(k) for k in a ) ) ) # in order to increase the number we look for the # least significant digit that can be increased for x in range( n-1, -1, -1): # count down from n-1 to 0 if a[x] < 10+x-n: break # digit x is to be increased a[x] += 1 # all subsequent digits must be increased accordingly for y in range( x+1, n ): a[y] = a[y-1] + 1 return res print( ascending( 5000, 9000 ) ) A: Sounds like task from Project Euler. Here is the solution in C++. It is not short, but it is straightforward and effective. Oh, and hey, it uses backtracking. // Higher order digits at the back typedef std::vector<int> Digits; // Extract decimal digits of a number Digits ExtractDigits(int n) { Digits digits; while (n > 0) { digits.push_back(n % 10); n /= 10; } if (digits.empty()) { digits.push_back(0); } return digits; } // Main function void PrintNumsRec( const Digits& minDigits, // digits of the min value const Digits& maxDigits, // digits of the max value Digits& digits, // digits of current value int pos, // current digits with index greater than pos are already filled bool minEq, // currently filled digits are the same as of min value bool maxEq) // currently filled digits are the same as of max value { if (pos < 0) { // Print current value. Handle leading zeros by yourself, if need for (auto pDigit = digits.rbegin(); pDigit != digits.rend(); ++pDigit) { if (*pDigit >= 0) { std::cout << *pDigit; } } std::cout << std::endl; return; } // Compute iteration boundaries for current position int first = minEq ? minDigits[pos] : 0; int last = maxEq ? maxDigits[pos] : 9; // The last filled digit int prev = digits[pos + 1]; // Make sure generated number has increasing digits int firstInc = std::max(first, prev + 1); // Iterate through possible cases for current digit for (int d = firstInc; d <= last; ++d) { digits[pos] = d; if (d == 0 && prev == -1) { // Mark leading zeros with -1 digits[pos] = -1; } PrintNumsRec(minDigits, maxDigits, digits, pos - 1, minEq && (d == first), maxEq && (d == last)); } } // High-level function void PrintNums(int min, int max) { auto minDigits = ExtractDigits(min); auto maxDigits = ExtractDigits(max); // Make digits array of the same size while (minDigits.size() < maxDigits.size()) { minDigits.push_back(0); } Digits digits(minDigits.size()); int pos = digits.size() - 1; // Placeholder for leading zero digits.push_back(-1); PrintNumsRec(minDigits, maxDigits, digits, pos, true, true); } void main() { PrintNums(53, 297); } It uses recursion to handle arbitrary amount of digits, but it is essentially the same as the nested loops approach. Here is the output for (53, 297): 056 057 058 059 067 068 069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 Much more interesting problem would be to count all these numbers without explicitly computing it. One would use dynamic programming for that. A: There is only a very limited number of numbers which can match your definition (with 9 digits max) and these can be generated very fast. But if you really need speed, just cache the tree or the generated list and do a lookup when you need your result. using System; using System.Collections.Generic; namespace so_ascending_digits { class Program { class Node { int digit; int value; List<Node> children; public Node(int val = 0, int dig = 0) { digit = dig; value = (val * 10) + digit; children = new List<Node>(); for (int i = digit + 1; i < 10; i++) { children.Add(new Node(value, i)); } } public void Collect(ref List<int> collection, int min = 0, int max = Int16.MaxValue) { if ((value >= min) && (value <= max)) collection.Add(value); foreach (Node n in children) if (value * 10 < max) n.Collect(ref collection, min, max); } } static void Main(string[] args) { Node root = new Node(); List<int> numbers = new List<int>(); root.Collect(ref numbers, 5000, 6000); numbers.Sort(); Console.WriteLine(String.Join("\n", numbers)); } } } A: Why the brute force algorithm may be very inefficient. One efficient way of encoding the input is to provide two numbers: the lower end of the range, a, and the number of values in the range, b-a-1. This can be encoded in O(lg a + lg (b - a)) bits, since the number of bits needed to represent a number in base-2 is roughly equal to the base-2 logarithm of the number. We can simplify this to O(lg b), because intuitively if b - a is small, then a = O(b), and if b - a is large, then b - a = O(b). Either way, the total input size is O(2 lg b) = O(lg b). Now the brute force algorithm just checks each number from a to b, and outputs the numbers whose digits in base 10 are in increasing order. There are b - a + 1 possible numbers in that range. However, when you represent this in terms of the input size, you find that b - a + 1 = 2lg (b - a + 1) = 2O(lg b) for a large enough interval. This means that for an input size n = O(lg b), you may need to check in the worst case O(2 n) values. A better algorithm Instead of checking every possible number in the interval, you can simply generate the valid numbers directly. Here's a rough overview of how. A number n can be thought of as a sequence of digits n1 ... nk, where k is again roughly log10 n. For a and a four-digit number b, the iteration would look something like for w in a1 .. 9: for x in w+1 .. 9: for y in x+1 .. 9: for x in y+1 .. 9: m = 1000 * w + 100 * x + 10 * y + w if m < a: next if m > b: exit output w ++ x ++ y ++ z (++ is just string concatenation) where a1 can be considered 0 if a has fewer digits than b. For larger numbers, you can imagine just adding more nested for loops. In general, if b has d digits, you need d = O(lg b) loops, each of which iterates at most 10 times. The running time is thus O(10 lg b) = O(lg b) , which is a far better than the O(2lg b) running time you get by checking if every number is sorted or not. One other detail that I have glossed over, which actually does affect the running time. As written, the algorithm needs to consider the time it takes to generate m. Without going into the details, you could assume that this adds at worst a factor of O(lg b) to the running time, resulting in an O(lg2 b) algorithm. However, using a little extra space at the top of each for loop to store partial products would save lots of redundant multiplication, allowing us to preserve the originally stated O(lg b) running time. A: One way (pseudo-code): for (digit3 = '5'; digit3 <= '6'; digit3++) for (digit2 = digit3+1; digit2 <= '9'; digit2++) for (digit1 = digit2+1; digit1 <= '9'; digit1++) for (digit0 = digit1+1; digit0 <= '9'; digit0++) output = digit3 + digit2 + digit1 + digit0; // concatenation
doc_23538692
<select name="" id="" class="select"> <option value="">Select</option> <option value="1">Value 1</option> <option value="2">Value 2</option> </select> <select name="" id="" class="select"> <option value="">Select</option> <option value="1">Value 1</option> <option value="2">Value 2</option> </select> $(function () { var select = $('select.select'); select.change(function () { select.not(this).val(this.value); }); }); A: This should work (synchronizing lists by data attributes): <select name="" id="" class="select"> <option data-id='1' value="">Select</option> <option data-id='2' value="1">Value 1</option> <option data-id='3' value="2">Value 2</option> </select> <select name="" id="" class="select"> <option data-id='1' value="5">Select</option> <option data-id='2' value="3">Value 1</option> <option data-id='3' value="4">Value 2</option> </select> (function () { var select = $('select.select'), opt, dataAttr; select.change(function () { dataAttr = $(this).find(':selected').data('id'); select.not($(this)).each(function(){ if (opt = $(this).find('[data-id='+ dataAttr +']')){ $(opt).prop('selected', true); } }); }); })();
doc_23538693
I've tried code like shell.get("1.7", '"') but I get an error saying _tkinter.TclError: bad text index """ Here is a snippet of my current code: from tkinter import * import datetime def run(): print("File run " + str(datetime.datetime.now())) line = shell.get("1.0", END) #dont worry about ^ line for now (line 2 in run()) if 'print "' in line: print (shell.get('1.7', '"')) shell = ScrolledText(root, width=167, height=42) shell.grid(column=0, row=1) Heres what is in the shell print "Hello World" I just want something like: print (shell.get(1.7, "<nearest quotation mark>") A: The tkinter Text widget has a search method which you can use to find the first occurrence of a pattern starting at an index. In your case you would want to find the first " after the 1.7 index. To do this you can run: shell.search('"', '1.7') Integrated in your code that would be: from tkinter import * from tkinter.scrolledtext import ScrolledText import datetime def run(event=None): print('File run ' + str(datetime.datetime.now())) line = shell.get("1.0", END) if 'print "' in line: print (shell.get('1.7', shell.search('"', '1.7'))) root = Tk() shell = ScrolledText(root, width=167, height=42) shell.insert('1.0', 'print "print this" do not print this') shell.grid(column=0, row=1) shell.bind('<Button-1>', run) root.mainloop() Notice that I bound the run function to the left mouse button for demonstrative purposes.
doc_23538694
* *mvnw *mvnw.bat Should these files be ignored when committing to a git repo? A: A mvnw Maven wrapper script allows you to run a Maven command without having Maven installed and present on your PATH. It does by looking for Maven on your PATH and, if not found, it downloads and installs Maven in a default location (your user home directory, IIRC). They are a convenience but they are not necessarily part of your project, not in the same way as your project code and configuration is. In other words: * *Any given mnvw file could be used for multiple, unrelated projects *A mnvw file will almost certainly not be different from one version of your project to another On this basis you could make a case for not committing mvnw to your code repository. However, including a mvnw script in your repo does have these benefits: * *Allows anyone who clones / checks-out your repo to build your project without having to install Maven first. *Ensures that the version of Maven in use is the version with which your project is compatible. On this basis you could make a case for committing mvnw to your code repository. So, there are pros and cons on both sides. Just choose the side which best fits the needs of those who will use your repo. Either: * *Include something in your readme which makes clear that (a) Maven is a prerequisite and (b) which version of Maven is required. ... or: * *Include a mvnw script. A: It depends, if you want to use the Maven wrapper or not. If not, then you can delete those files. If you want to use it, then you have to commit the files in the repository, otherwise it doesn't make sense to use it.
doc_23538695
<div> <a href="#"></a> » <a href="#"></a> » <a href="#"></a> » <a href="#"></a> » <a href="#"></a> </div> How i can disable or delete this simbol - "»" ? I use this code text = $('div').html(); text = text.replace('»',''); $('div').html(text); but hi does not wokr correctly. The last symbol is displaing. Another way? A: You just need to add the global flag (g) to your replace code like it was a regex: text = $('div').html(); text = text.replace(/»/g,''); $('div').html(text); jsFiddle example A: replace when passed a string only replaces the first instance. You must use a regular expression instead. http://jsfiddle.net/zkvss6uf/ text = $('div').html(); text = text.replace(/»/g,''); $('div').html(text);
doc_23538696
fooled around with a folder - c:/documents/class/lab1part1, typed git init for that folder. Couldn't upload, made some mistakes. Changed folder to c:/documents/class/lab2part3 and ran git init. made mistakes. Went back to c:/documents/class/, was able to successfully upload (git init, git add, etc). Went to github.com and all folders and files were there... except for folders (with files in it) lab1part1 and lab2part3. So, I deleted that repository and started all over again... Googled, one site said to use the command "rm -rf $HOME/.git" to undo the git init on my folder. I typed that in git bash... and things went to hell. This was done on a macbook pro that dual boots OSX and Windows 10 (clearly this occurred on the windows partition). Right now - I'm unable to access the start menu, my programs that were in the task bar are gone, I'm unable to access connect to a network or any of my files. What happened, and how to I fix this - i cannot afford to lose my labs!!!! A: Putting aside the rm -rf step: * *your lab1part1 and lab2part3 were not on GitHub because you create a git repo in their parent folder c:/documents/class/: when you pushed that repo, the two subfolders were recorded as nested git repo gitlinks (a special entry in the index) *as long as those folders are on your local machine, you will be able to add, commit and push once again (but you will need to push to two separate GitHub repos) So save your folders elsewhere (backup), re-install Windows, and try agian.
doc_23538697
Well this makes it so whatever I put in between these tags gets lowered. Everything is working fine I just don't want my image to be lowered because of div. Help would be appreciated. A: To prevent line wrapping, try using a span element, which is inline. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span You could also set a div to display inline or inline-block (which allows CSS sizing, for example) using CSS: #cartpopup {display: inline-block;}
doc_23538698
Spark installed locally and was launched by means of start_pyspark.sh #!/bin/bash export PYSPARK_PYTHON=/opt/anaconda3/bin/python export PYSPARK_DRIVER_PYTHON=/opt/anaconda3/bin/jupyter export PYSPARK_DRIVER_PYTHON_OPTS="notebook --NotebookApp.open_browser=False --NotebookApp.ip='*' --NotebookApp.port=8880 --notebook-dir=~/" pyspark "$@" Neo4j connector for Spark was downloaded and put into /opt/spark/jars before starting PySpark. Neo4j database was started at neo4j://localhost:7687 I tried to apply vendor recommendations (https://neo4j.com/docs/spark/current/python/) but I failed. Spark.version - 3.3.0 My python code import pyspark from pyspark.sql import SparkSession spark = SparkSession.Builder().getOrCreate() df = spark.read.format("org.neo4j.spark.DataSource") \ .option("url", "neo4j://localhost:7687") \ .option("labels", "Department") \ .option("authentication.type", "basic")\ .option("authentication.basic.username", "*****")\ .option("authentication.basic.password", "******")\ .load() After starting the following error arise: Py4JJavaError Traceback (most recent call last) Input In [2], in <cell line: 1>() ----> 1 df = spark.read.format("org.neo4j.spark.DataSource") \ 2 .option("url", "neo4j://localhost:7687") \ 3 .option("labels", "Department") \ 4 .option("authentication.type", "basic")\ 5 .option("authentication.basic.username", "*****")\ 6 .option("authentication.basic.password", "******")\ 7 .load() File /opt/spark/python/pyspark/sql/readwriter.py:184, in DataFrameReader.load(self, path, format, schema, **options) 182 return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path))) 183 else: --> 184 return self._df(self._jreader.load()) File /opt/spark/python/lib/py4j-0.10.9.5-src.zip/py4j/java_gateway.py:1321, in JavaMember.__call__(self, *args) 1315 command = proto.CALL_COMMAND_NAME +\ 1316 self.command_header +\ 1317 args_command +\ 1318 proto.END_COMMAND_PART 1320 answer = self.gateway_client.send_command(command) -> 1321 return_value = get_return_value( 1322 answer, self.gateway_client, self.target_id, self.name) 1324 for temp_arg in temp_args: 1325 temp_arg._detach() File /opt/spark/python/pyspark/sql/utils.py:190, in capture_sql_exception.<locals>.deco(*a, **kw) 188 def deco(*a: Any, **kw: Any) -> Any: 189 try: --> 190 return f(*a, **kw) 191 except Py4JJavaError as e: 192 converted = convert_exception(e.java_exception) File /opt/spark/python/lib/py4j-0.10.9.5-src.zip/py4j/protocol.py:326, in get_return_value(answer, gateway_client, target_id, name) 324 value = OUTPUT_CONVERTER[type](answer[2:], gateway_client) 325 if answer[1] == REFERENCE_TYPE: --> 326 raise Py4JJavaError( 327 "An error occurred while calling {0}{1}{2}.\n". 328 format(target_id, ".", name), value) 329 else: 330 raise Py4JError( 331 "An error occurred while calling {0}{1}{2}. Trace:\n{3}\n". 332 format(target_id, ".", name, value)) Py4JJavaError: An error occurred while calling o51.load. : java.lang.NoSuchMethodError: 'scala.collection.immutable.ArraySeq scala.runtime.ScalaRunTime$.wrapRefArray(java.lang.Object[])' at org.neo4j.spark.DataSource.<init>(DataSource.scala:15) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at java.base/java.lang.Class.newInstance(Class.java:584) at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:726) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:207) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:171) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182) at py4j.ClientServerConnection.run(ClientServerConnection.java:106) at java.base/java.lang.Thread.run(Thread.java:829) Has any faced this issue? Thanks in advance. ​ A: Hi I just tried by myself with the last release (4.1.5) and the connector works with Spark 3.3.0. You can try by yourself with this notebook that I used during my workshop at Graph Connect 2022. https://github.com/conker84/gc-2k22-spark I think that your problem is that you're using the connector compiled with the wrong Scala version for your project.
doc_23538699
import AsyncStorage from "@react-native-async-storage/async-storage"; import EventEmitter from "eventemitter3"; import { useEffect, useState } from "react"; const eventEmitter = new EventEmitter(); /** * Acts as a react hook for AsyncStorage * @param id - ID of the element * @param defaultValue - Default value of the element * @returns A react hook of the element */ export default function useStorage<Type>(id: string, defaultValue: Type): [Type, (value: Type) => Promise<void>] { const [version, setVersion] = useState(0); const [data, setData] = useState(defaultValue); // Grab Data const getData = async () => { const jsonData = await AsyncStorage.getItem(id); if (jsonData) setData(JSON.parse(jsonData) as Type); }; useEffect(() => { getData(); }, [version]); // Save Data const saveData = async (value: Type) => { const jsonData = JSON.stringify(value); await AsyncStorage.setItem(id, jsonData); setData(value); eventEmitter.emit(id); } useEffect(() => { let isMounted = true; const handleDataChange = () => { if (isMounted) { setVersion(v => v + 1); } } const unmount = () => { isMounted = false; eventEmitter.removeListener(id, handleDataChange); } eventEmitter.addListener(id, handleDataChange); return unmount; }, [id]); return [data, saveData]; } However, whenever I utilize it, I get very strange results including... * *Data not properly loading when the same key is on parent and child screen simultaneously *Data not properly updating *Hook not cleaning up properly Am I missing something? What is causing all of these issues? Is there a better way of implementing this? Note: I am aware React Redux exists, but I would prefer to avoid it if possible. A: Calling multiple setStates() in a single function can cause unintended side effects. By adjusting the code to only use 1 setState() per function, these issues can be avoided.