id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23528400
Option Compare Database Option Explicit Dim strTaxR As String Dim strYTDG As String Public Function fncTRate(ByVal PEnd As Date) As Double strTaxR = "SELECT TOP 1 [Tax Rate] As TRate FROM tblTax WHERE [Effective Date] <= #" & PEnd & "#" ORDER BY [Effective Date] DESC;" With CurrentDb.OpenRecordset(strTaxR) If Not (.BOF And .EOF) Then fncTRate = .Fields("TRate") End If End With End Function Public Function fncYTDG(EmpN As Integer, PEnd As Date) As Double strYTDG = "SELECT Sum([SGROSS]) As YTDG FROM qryYTD2 WHERE [PE] Between #" & DateSerial(Year(PEnd ), 1, "1") & "# And #" & PEnd & "# And [EID]=" & EmpN With CurrentDb.OpenRecordset(strYTDG) If Not (.BOF And .EOF) Then fncYTDG = .Fields("YTDG") End If End With End Function Will compacting it make a difference or should I leave it as is? A: You could do this: Public Function fncGrossRate( _ ByVal GrossOrRate As Integer, _ ByVal PEnd As Date, _ Optional ByVal EmpN As Integer) _ As Currency Dim SQL As String Dim Result As Currency Select Case GrossOrRate Case 0 SQL = "SELECT TOP 1 [Tax Rate] As TRate FROM tblTax " & _ "WHERE [Effective Date] <= #" & Format(PEnd, "yyyy\/mm\/dd") & "# ORDER BY [Effective Date] DESC;" Case 1 SQL = "SELECT Sum([SGROSS]) As YTDG FROM qryYTD2 " & _ "WHERE [PE] Between #" & Format(DateSerial(Year(PEnd), 1, 1), "yyyy\/mm\/dd") & "# And #" & Format(PEnd, "yyyy\/mm\/dd") & "# And [EID]=" & EmpN & "" End Select If SQL <> "" Then With CurrentDb.OpenRecordset(SQL) If Not (.BOF And .EOF) Then Result = .Fields(0).Value End If End With End If fncGrossRate = Result End Function But, as already stated by June, the direct answer to your question is No.
doc_23528401
for i in range(number_dense_layers): model.add(layers.Dense(units=units, input_dim=input_dim, kernel_initializer='normal', activation='relu')) however, in the case of Tensorflow, I have the following: class generic_vns_function(tf.keras.Model): def __init__(self, num_layers, num_class=10): super().__init__() # Convolutional layers and MaxPools self.conv1 = tf.keras.layers.Conv2D(64, 3, activation="relu") self.conv2 = tf.keras.layers.Conv2D(64, 3, activation="relu") where I would want to do something like: for i in range(num_layers): self.add(tf.keras.layers.Conv2D(64, 3, activation="relu")) but I am unsure how to dynamically create this layer since the add function does not work in this context as it did in Keras. A: It looks like the following is what is needed: for i in range(num_layers): self.layers.append(tf.keras.layers.Conv2D(64, 3, activation="relu")) where we append in a specific layer to the models layers attribute. A: You can append first and stack them later. Here is a rough example: import tensorflow as tf class generic_vns_function(tf.keras.Model): def __init__(self, num_layers, num_class=10): super().__init__() self.convolutions = [] ... for i in range(num_layers): self.convolutions.append(tf.keras.layers.Conv2D(64, 3, activation="relu")) def call(self, inputs): ... for layer in self.convolutions: x = layer(x) ... return x A: Inspired by Frightera, If you want dynamic number of layers with different function, try dict. Dict is ordered after python 3.6. A: Instead of using for-loops to define multiple layers I prefere list comprehension: import tensorflow as tf class generic_vns_function(tf.keras.Model): def __init__(self, num_layers, num_class=10): super().__init__() ... self.convolutions = [tf.keras.layers.Conv2D(64, 3, activation="relu") for _ in range(num_layers)] def call(self, inputs): ... for layer in self.convolutions: x = layer(x) ... return x
doc_23528402
magick mogrify titli.gif -crop 2x4@ +repage -reverse -append -path converted titli.gif my problem is "-append" creates tall image (400x1600) & "+append" creates wide image (3200x200) How can I get a large image of original size 800x800 but with cropped and swapped (reversed) parts set in "mosaic or tiled" style... A: If I understand the question, you shouldn't need "mogrify" to do that. Just "magick" should accomplish that task. It looks like you'll have to crop the image into 8 pieces, reverse them, and "-append" them vertically as you've done. Then after that, and in the same command, you'll need to crop that result in half vertically and "+append" those two pieces horizontally to get the 800x800 output. This example command shows how it works... magick in.png -crop 2x4@ -reverse -append -crop 1x2@ +append out.png If you're doing any more operations within the same command you'll probably want to use "+repage" after the "+append" to reset the image geometry back to WxH+0+0.
doc_23528403
I'm done with the preprocessing: binarization local&global w/o api/libs and i use tesseract tessbase api for page segmentation and recognition. the results are almost fine it can recognize about 70% accuracy. Can i use edge detection( so that it can help to highlight the edges) for preprocess or should i used it for segmentation? how could I enhance the accuracy..
doc_23528404
This is the the target document. <div class="parent"> <a href="http://www.example1.com" class="child">name1</a> </div> <div class="parent"> <a href="http://www.example2.com" class="child">name2</a> </div> <div class="parent"> <a href="http://www.example3.com" class="child">name3</a> </div> <div class="parent"> <a href="http://www.example4.com" class="child">name4</a> </div> <div class="parent"> <a href="http://www.example5.com" class="child">name5</a> </div> I want the result to be like this. <div class="parent"> <a href="http://www.example1.com" class="child">name1</a> <a href="preview.php?link=http://www.example1.com" class="child_two">preview</a> </div> <div class="parent"> <a href="http://www.example2.com" class="child">name2</a> <a href="preview.php?link=http://www.example2.com" class="child_two">preview</a> </div> <div class="parent"> <a href="http://www.example3.com" class="child">name3</a> <a href="preview.php?link=http://www.example3.com" class="child_two">preview</a> </div> <div class="parent"> <a href="http://www.example4.com" class="child">name4</a> <a href="preview.php?link=http://www.example4.com" class="child_two">preview</a> </div> <div class="parent"> <a href="http://www.example5.com" class="child">name5</a> <a href="preview.php?link=http://www.example5.com" class="child_two">preview</a> </div> thank you so much. A: $("a.child").each(function (index, elem) { $(elem).clone() .attr("href", "preview.php?link=" + $(elem).attr("href")).attr("class", "child_two").text("preview").appendTo($(elem).parent()); });​ A: You can do it using after()'s function $('.parent a.child').after(function() { var $el = $(this); return $el.clone().attr({ 'href': 'preview.php?link=' + $el.attr('href'), 'class': 'child_two' }).text('preview'); });​ http://jsfiddle.net/3MFEu/ A: $("a.child").each(function(){ var newLink = $(this).clone(); $(newLink).attr("href", "preview.php?link=" + $(this).attr("href")); $(newLink).attr("class", "child_two"); $(newLink).text("Preview"); $(newLink).insertAfter(this); }); http://jsfiddle.net/bkU4r/2/ Updated - I failed to notice you want the second link to read "preview"
doc_23528405
when I try to customed the Tab-Navigation , I found this line that I couldn't hidden it(that white line!). pic I tried to set borderColor:'00000000',but it didn't work Please help me. =============================================================================== this is my code import React from 'react'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import Home from '../screens/Home'; import Me from '../screens/Me'; import { View, Image, Text } from 'react-native'; const Tab = createBottomTabNavigator(); export default () => { return ( <Tab.Navigator initialRouteName="Home" screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconSrc; if (route.name === 'Home') { iconSrc = require('../assets/img/影院.png'); } else if (route.name === 'Me') { iconSrc = require('../assets/img/我的.png'); } // You can return any component that you like here! return ( <Image source={iconSrc} resizeMode="contain" style={{ width: 25, height: 25, tintColor: focused ? '#FFCF64' : '#6D6D72' }} /> ); }, tabBarActiveTintColor: '#FFCF64', tabBarInactiveTintColor: '#6D6D72', tabBarStyle: { position: 'absolute', borderRadius: 25, height: 65, borderColor: '#333', backgroundColor: '#1a1a1a', bottom: 30, left: 10, right: 10 }, tabBarItemStyle: { height: 65 } })} > <Tab.Screen name="Home" component={Home} options={{ headerShown: false, tabBarShowLabel: false }} /> <Tab.Screen name="Me" component={Me} options={{ headerShown: false, tabBarShowLabel: false }} /> </Tab.Navigator> ); }; A: sorry,I'm fixed it up. add this code in tabBarStyle:'#00000000'
doc_23528406
Firstly I'm asking the user to give his name, Secondly, I'm asking the user to choose one of the spaceships, Thirdly, I want the user to add 2 modification, to improve the stats... Here is the problem, I want to change some values of the spaceship. The problem is that I don't know how to determine the chosen spaceship and how to change its values. Example: The Heavy-type Armour is 90 right now​ if I add the Advanced Hull Armour modification, i want it to increase to 100 public class Game { static void playerName() { System.out.println("What's your name?:"); String name = Keyboard.readString(); System.out.println("Okay,"+name+" it is!\n"); } static class StarShip { String name; String armour; String attack; String mobility; } public static void main (String args[]) { System.out.println("Hello Rookie! \n"); playerName(); System.out.println("Let's pick your first ship!\n"); System.out.println("Choose one of these:"); //insert ships here: StarShip ship1 = new StarShip(); ship1.name = "Heavy-type"; ship1.armour = "Armour=90"; ship1.attack = "Firepower=50"; ship1.mobility = "Mobility=40"; StarShip ship2 = new StarShip(); ship2.name = "Medium-type"; ship2.armour = "Armour=60"; ship2.attack = "Firepower=60"; ship2.mobility = "Mobility=60"; StarShip ship3 = new StarShip(); ship3.name = "Light-type"; ship3.armour = "Armour=20"; ship3.attack = "Firepower=60"; ship3.mobility = "Mobility=90"; System.out.println("1 -"+ship1.name+"- "+ship1.armour+" "+ship1.attack+" "+ship1.mobility); System.out.println("2 -"+ship2.name+"- "+ship2.armour+" "+ship2.attack+" "+ship2.mobility); System.out.println("3 -"+ship3.name+"- "+ship3.armour+" "+ship3.attack+" "+ship3.mobility); int chosen = Keyboard.readInt(); switch (chosen) { case 1: System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n"); break; case 2: System.out.println("Medium-type! An all-rounder, a mix of everything! \n"); break; case 3: System.out.println("Light-type! Fast and mobile, but has little armour! \n"); break; } System.out.println("Lets pimp out your ship! \n"); String advancedHull = "1 - Advanced Hull Armour - Armour +10"; String betterAmmo = "2 - Better Ammo \t - Firepower +10"; String booster = "3 - Booster \t\t - Mobility +10"; System.out.println(advancedHull+"\n"+betterAmmo+"\n"+booster); } } A: Currently you the fields of the StarShip are all Strings, when you add two strings they are concatenated, eg "abc"+"def" = "abcdef" regardless of what they say. You want to use ints these are "java numbers" and add as you would expect eg 10 + 20 = 30 class StarShip { String name; int armour; int attack; int mobility; } ... StarShip ship1 = new StarShip(); ship1.name = "Heavy-type"; ship1.armour = 90; ship1.attack = 50; ship1.mobility = 40; ... When the user selects the ship we want to save this chose into a variable, like so: Starship chosenShip; // must be declared outside the switch statement switch (shipChoice ) { case 1: System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n"); chosenShip = ship1; Break; ... Assuming advancedHull is selected and you include logic similar to how ships are selected if (modificationChoice = 1){ chosenShip.armour = chosenShip.armour + 10; } ... You may want to declare a toSting() methods in StarShip like so @Override public String toString() { return name +" Armour=" + armour +", Firepower=" + attack +", Mobility=" + mobility; } This way you can call System.out.println(ship1.toString()) to print the ship info. Example: System.out.println(ship1.toString()); // outputs: Heavy-type Armour=90, Firepower=50, Mobility=40 ship1.armour += 10; // java shorthand for `ship1.armour + ship1.armour + 10` System.out.println(ship1.toString()); // outputs: Heavy-type Armour=100, Firepower=50, Mobility=40
doc_23528407
I have some release pipeline's variables. I want to read those variables as they will be required by my script in above two tasks. I used powershell core in Azure cli task I tried to read them in the inline script directly as $(variableName) or $env:variableName but none of the above worked. I tried to set read the variable in Environment variables option in the task and then use in the inline scripts using $env:variableName but it also didn't work. On printing the variableName in the script using Write-Host, the value I got is $(valueName) instead of the correct value. How to read those variables inside these scripts? A: The pipeline variables can be reference in the Azure CLI inline script by using the syntax $(variableName). I tested by adding the following in a script write-host "The variable value: $(variableName)"
doc_23528408
I have created my S3 bucket. I have also created my user with AWSS3FullAccessRights. By default my s3 bucket has public access turned off. When I upload a files I am getting a 403 forbidden error. The request URL is: https://[bucket_name].s3.ap-southeast-2.amazonaws.com/livewire-tmp/HeFkgK7BTeFv2voaPzMPJdwqX69KQ4-metac2FtcGxlLW1wNC1maWxlLm1wNA%3D%3D-.mp4?x-amz-acl=private&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAS3BSKYVMYVLYCB44%2F20201025%2Fap-southeast-2%2Fs3%2Faws4_request&X-Amz-Date=20201025T041359Z&X-Amz-SignedHeaders=host%3Bx-amz-acl&X-Amz-Expires=300&X-Amz-Signature=9e87a654cbeab84772c18a950741027e7eeea1ad41b28e7b1c84a60cf2266147. The file is not getting uploaded to S3 at all. My livewire settings file is set to s3. I have entered my key, secret, region and bucket name into my .env file. Are there any other permissions I need to setup on AWS for this to work. All the tutorials I have looked at don't work and not sure why. Any heklp would be appreciated Thanks Danny A: The issue here was with allowing cross-origin requests. I had to insert the following code into the CORS configurations in the S3 bucket <CORSConfiguration> <CORSRule> <AllowedOrigin>http://www.example1.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>http://www.example2.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> </CORSRule> </CORSConfiguration>
doc_23528409
Here I am taking the average of the neighboring pixels and iterating the loop until I get an approximate result: n = 500; Mat_new = rand(n); error = 1; while error > 0.000001 Mat_Old = Mat_new; for i = 2:n-1 for j = 2:n-1 Mat_new(i,j) =abs((2+((Mat_Old(i+1,j)+Mat_Old(i-1,j)+Mat_Old(i,j+1)+Mat_Old(i,j-1))))/(4)); end end error =max(max(abs(Mat_Old-Mat_new))); end A: What you are doing is essentially a convolution of a 2D matrix. You just have to specify the input filter that you want. In your case, you want find a weighted sum of the base cardinal directions: North, East, South, West, given a particular location in the matrix as the output. As such, create a 3 x 3 filter that encompasses these directions, then use imfilter, or conv2 to create your output matrix. Seeing as how you want to create an image that has 1 element border surrounding the result, we should use conv2 instead. Though you have a lot of parentheses (yuck), what (I believe) you are doing is adding up all of the values in the cardinal directions, add this sum with 2, take the absolute value, then divide by 4. As such, do this: n = 500; Mat_new = rand(n); error = 1; h = [0 1 0; 1 0 1; 0 1 0]; % // Define filter here while error > 0.000001 Mat_Old = Mat_new; Mat_new = conv2(Mat_Old, h, 'valid'); Mat_new = abs(Mat_new + 2) / 4; %//Take the output, add 2, absolute then divide by 4 %// Pad border with zeroes Mat_new = padarray(Mat_new, [1 1]); error = max(abs(Mat_Old(:) - Mat_new(:))); %// Calculate maximum error end What the above code is doing is basically what you're doing with the double for loop. Except now, we are doing it with conv2. The first line of Mat_new computes the sum of the four cardinal directions for each location in your matrix, ignoring the border as you have shown in your for loop. Once we do this, we take the absolute value of each entry in the matrix through abs after we add 2 to each entry, then divide by 4. After, we pad the border of the output matrix with all zeroes using padarray. By the way, I've restructured your error statement so that it doesn't use a nested call to max. I never liked the way that looked. Unfortunately, the while loop (I don't think...) can be vectorized. You are computing a new output at each iteration, and want to calculate the error between the previous iteration and the current one. In this case, there is no way to vectorize something like this with a strong recurrence relation.... so you're stuck with the while loop for now. However, you can definitely vectorize the double for loop, and that's what we have just accomplished. This should hopefully achieve what you want!
doc_23528410
1st method Code - resnet = InceptionResnetV1(pretrained='vggface2').eval() mtcnn = MTCNN(image_size=96) img = Image.open(image_path) image_prep = mtcnn(img) plt.figure() plt.axis('off') plt.imshow(image_prep.permute(1, 2, 0)) if image_prep is not None: image_embedding = resnet(image_prep.unsqueeze(0)) In this code, I extract the face from the given images, and get the 512 encodings for recognizing faces. In this example, I used two different faces, and plot the distance between the faces a.jpg b.jpg a.jpg 0.000000 1.142466 b.jpg 1.142466 0.000000 It works well... 2nd method Code- img = Image.open(image) boxes, probs = mtcnn.detect(img) # Gives the coordinates of the face in the given image face = img.crop((boxes[0][0], boxes[0][1], boxes[0][2], boxes[0][3])) # Cropping the face plt.figure() plt.imshow(face) pil_to_tensor = transforms.ToTensor()(face).unsqueeze_(0) # Converting to tensor type image_embedding = resnet(pil_to_tensor) In this code, I used to get the coordinates of the face, first and then the embeddings. The distance between the two faces - a.jpg b.jpg a.jpg 0.000000 0.631094 b.jpg 0.631094 0.000000 In 1st method, I directly feed the image to the mtcnn and gets better result, the distance between the two faces are more than 1.0. In, 2nd method, I gets the coordinates of the faces using mtcnn.detect(), cropped the face from the given image, and feed to resnet. This method gives less distance between the two different faces. Then, I find the reason for why the 1st method performs well than the 2nd method by plotting the result(face) before feeding to resnet. In 2nd method, I feed the faces same as given in the input image(clear image) by cropping the faces using mtcnn.detect(). But, In 1st method, I directly gives the input to mtcnn(img) which returns the tensor of the faces in dark than in input image. This darker image is not a clear image(area around eyes are darker, I tested with many photos), Can't able to see the eyes clearly. This is the reason, the 1st method shows higher distance between two faces. My doubt is, Why mtcnn returns the tensor in dark, How to solve it, Help me in this issue, Thanks A: Maybe besause tensor returns in [-1:1] range? And you have to convert it back to uint8 [0-255].
doc_23528411
Thanks. A: It's simple. Just keep it on your PC and don't put it on the web. ALL can be decompiled, reverse engineered and hacked, even programs written in c++/c/asm. If you want to make this task of decompiling a bit harder use some obfuscators for flash A: While there is no full-proof way to secure code from decompilers there are some tricks to reduce the chances of this happening. * *host the .swf on a https server then it doesnt get cached *You can obfuscate the code to make it impossible to understand even if it is decompiled. *Change the file extension of the .swf file to something like a .jpg file or a .png file, the browser should still detect that it is a .swf and display it correctly, but it will be stored in the cache as an image file A: There is a product that encrypts the code inside the swf. It's not bullet proof but does protect. A: There are many tools to "encrypt" SWF even though I don't think we can actually discuss encryption here. Encryption is not obfuscation. I've reviewed one such obfuscation tool just recently, see Protect your ActionScript code with SWF Protector. Although it does pretty well for an obfuscator, you need to realise that: * *obfuscation increases file size; *most obfuscation algorithms in use today are still pretty easy to reverse engineer, so it's certainly not a bullet-proof solution. It's just obfuscation and is likely to keep off amateurs and pros who find it easier to rewrite from scratch rather than mess with reversing the obfuscation. A: you can protect them by setting a password while compiling. can this solve your security issue?
doc_23528412
{block:Photo} <div class="PhotoPost"> <div class="PhotoWrapper"> <div class="Button">-</div> <div class="box"> <script type="text/javascript"> $(".Button").click(function(){ if($(this).html() == "-"){ $(this).html("+"); } else{ $(this).html("-"); } $(".box").slideToggle(); }); </script> <img class="PhotoPostImage" src="{PhotoURL-HighRes}" alt="{PhotoAlt}"/> <!-- Some more code --> </div> </div> </div> </div> When I click the minimise button it minimises and maximises every single photo post as many times as there are photo posts instead of minimising the photo post where the button is. Thanks in advance! A: change $(".box").slideToggle(); to $(this).siblings(".box").slideToggle(); Hope this will help you A: change $(".box").slideToggle(); to $(this).next('.box').slideToggle(); .next('.box') .closest('box') .siblings('.box') all should work notice that the icon html was only changing for the clicked div because you used $(this) , but then you called slideToggle() on everything with box class A: Your code uses $('.box') which matches every element of class box anywhere in the page. Instead, select only the one in the same PhotoWrapper as the button that was clicked: $(this).closest('.PhotoWrapper').find('.box').slideToggle(); By the way, I suggest using a proper minus sign (−, &#x2212; in HTML, \u2212 in JavaScript) as this will visually match the plus sign it replaces: the - hyphen often displays smaller and lower. $(this).html('\u2212');
doc_23528413
functions.logger.log("Hello from info. Here's an object:", someObj); So when I run functions.logger.log this is the error I get: TypeError: Cannot read property 'log' of undefined Why is logger undefined and how do I fix this? A: Check your version of the firebase-functions module. The logger requires version 3.7.0 or later. The latest at the time of this writing is 3.13.0.
doc_23528414
* *The use case is we are having a lms_status model & in the model having after_create callback with if condition. *I found that when if conditions is true then the code inside the after_create executed properly but in the lms_statuses table no entry created. *It seems that after created it also deleted from table. class LmsStatus after_create :enqueue_order_item, if: ->{ status == 6 } def enqueue_order_item //code working fine end end *It is happening for some of the lms_status object/entry not always. *Is it possible that after_create callback after executing the code inside callback can rollback ? If Yes then for those lms_statuses, it is reverting I do not want to execute the callback code. How can I prevent ?
doc_23528415
I use the following link, it opens up Maps fine, but I don't know the value for the "saddr"-key: <a href="maps:daddr=MyStreet 1, My City&saddr=">Navigate me</a> I could use Phonegap's Geolocation-API to find out the user's current position, but I don't want to make iOS ask the user, if he wants to let my app access the GPS-sensor. A: I'm not sure how you are handling the url, but the destination should also be url encoded (e.g. escape spaces with %20). Final url: <a href="maps:daddr=MyStreet%201,%20My%20City&saddr=Current%20Location">Navigate me</a>
doc_23528416
Followed the below approach : final ObjectName mapMBeanName = new ObjectName( "java.lang:type=OperatingSystem" ); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); cpu =100.0 * Float.parseFloat( server.getAttribute( mapMBeanName, "SystemCpuLoad" ).toString() ); Can anyone help me how can I get correct System CPU usage irrespective of whether the JVM process does the heavy task or lighter task?
doc_23528417
//Database.SetInitializer(new KjokkenSeedInitializer()); -- not working Database.SetInitializer(new DropCreateDatabaseAlways<KjokkenContext>()); // - not working var context = new KjokkenContext(); context.Database.Initialize(true); var x = context.Persons.ToList(); Any idea what might be wrong? I've seen some other similar questions ( EF Code First not initializing database ) but I'm not getting any initializer to run. Thanks for any help Larsi
doc_23528418
I created a simple WinForms Project and I added a menuStrip. Then I changed the Visible property to true/false. I am decompiling with ildasm.exe but I cannot spot the difference that specifies if the menuStrip is visible or not, the instructions are identical.
doc_23528419
if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView { view.addSubview(alertView) alertView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 20)) view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20)) alertView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin] self.view.layoutIfNeeded() } I call this code in viewDidAppear. The center thing seems to work, but it seems that the trailing and leading don't have any effect. I want them with a distance of 20, my alertView should have a fixed height and appear in center. The xib has always the same size (see screenshots) My originally targeted was to get a xib that I can implement in every view for every device. So what is the best way to get this? my xib file simulator iphone 7 simulator iphone 4 A: You are mixing up auto layout and fixed placement (with autoresizing mask). What you want to do is completely use auto layout so that the view will adjust its layout automatically. You say you want a horizontal distance of 20, a fixed height and to be centred so I would do this: if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView { view.addSubview(alertView) // Start using auto layout alertView.translatesAutoresizingMaskIntoConstraints = false // Set the leading and trailing constraints for horizontal placement view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -20)) view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20)) // Centre it vertically view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)) // Set the fixed height constraint let fixedHeight: CGFloat = 100 view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: fixedHeight)) } That will get you what you want no matter how the device, superview, orientation, etc changes.
doc_23528420
* *task A >> task B >> task C *task D I want to backfill task A and it's downstream tasks. (in this case: only task A,B,C) with cli command: backfill dag_id -s 2019-07-01 -e 2019-07-07 -t taskA Only task A was backfilled. There is no argument like '--downstream'. Can I backfill task A and it's downstream tasks with 1 command? A: As per Airflow CLI docs -t, --task_regex The regex to filter specific task_ids to backfill (optional) so i recon you ought to omit that -t taskA from your Airflow CLI command and backfill the entire DAG (instead of backfilling individual tasks)
doc_23528421
That iframe has a contact form in it with an uploader. I want to close the modal when the form is submitted. How do you do that? I tried to use success:function(){ $('#modal .close', parent.document).trigger('click'); } But that obviously is blocked for cross domain access. The modal: <div class="modal fade" id="modal" 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-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">{{ 'Vraag uw beregeningsplan aan' | t }}</h4> </div> <div class="modal-body"> <iframe></iframe> </div> </div> </div> </div> <script> $(document).ready(function() { $('#modal').on('shown.bs.modal',function(){ $(this).find('iframe').attr('src','//link-to-form/') }); }); </script> Any help appreciated! A: Well Not sure from the description if the Form inside the iframe is your own form or some external web form. In case its your own form then write this jquery code in the inside form $(document).ready(function () { $(document).on('submit', '#myForm', function () { window.parent.$('#modal').modal('hide'); }); }); where myForm is the ID for the inside form
doc_23528422
I'm expecting this to show the same popup request to access the Media Library that we get at app startup, but nothing happens. It is simply returning with the MPMediaLibraryAuthorizationStatusDenied status from before. The docs for requestAuthorization are incomplete at this time, so I can't tell if I'm just using this incorrectly, or there is something else wrong. if ( MPMediaLibrary.authorizationStatus == MPMediaLibraryAuthorizationStatusAuthorized) { // we already have access to the Media Library - use it here... } else { // We expect this to show a popup so the user can grant access, but does not work [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus authorizationStatus) { if ( authorizationStatus == MPMediaLibraryAuthorizationStatusAuthorized ) { // success: the user authorized - use it here... } else { // user did not authorize - tell user why here... } }]; } Update Apparently there is no way to cause the original dialog to reappear (see comments below). I'm now using this code to at least take me to the right place in settings so the user can make the change. (for iOS8 and beyond) NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; [[UIApplication sharedApplication] openURL:url]; A: The MPMediaLibrary will only automatically prompt the user once. The state is MPMediaLibraryAuthorizationStatusNotDetermined if you ask for it before it has been granted or denied by the user. If they have denied access previously, you need to send the user to the System Settings so they can manually turn it on for your app. The following code is how we are doing it. + (void) validateMediaLibraryForMinimumIosAndAboveWithViewController:(UIViewController *)viewController ifAuthorized:(void(^)())authorizedBlock ifNotAuthorized:(void(^)())notAuthorizedBlock { MPMediaLibraryAuthorizationStatus authorizationStatus = MPMediaLibrary.authorizationStatus; switch (authorizationStatus) { case MPMediaLibraryAuthorizationStatusAuthorized: { // We are already authorized - proceed if( authorizedBlock ) { authorizedBlock(); } break; } case MPMediaLibraryAuthorizationStatusNotDetermined: { // Not yet authorized - request it from the system [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus authorizationStatus) { if ( authorizationStatus == MPMediaLibraryAuthorizationStatusAuthorized ) { if( authorizedBlock ) { authorizedBlock(); } } else { PLog(@"The Media Library was not authorized by the user"); if( notAuthorizedBlock ) { notAuthorizedBlock(); } } }]; break; } case MPMediaLibraryAuthorizationStatusRestricted: case MPMediaLibraryAuthorizationStatusDenied: { // user has previously denied access. Ask again with our own alert that is similar to the system alert // then take them to the System Settings so they can turn it on for the app NSString *titleString = NSLocalizedStringWithDefaultValue(@"Media Library Privacy Alert Title", @"Localizable", [NSBundle mainBundle], @"Would Like to Access Apple Music And Your Media Library", @"Title for dialog requesting media library access"); [self displayPermissionAlertFromViewController:viewController withTitle:titleString]; if( notAuthorizedBlock ) { notAuthorizedBlock(); } break; } } } + (void)displayPermissionAlertFromViewController:(UIViewController *)viewController withTitle:(NSString *)title { NSString* appName = [[NSProcessInfo processInfo] processName]; NSString *titleString = [NSString stringWithFormat:@"\"%@\" %@",appName, title]; NSString *cancelString = NSLocalizedStringWithDefaultValue(@"Don't Allow", @"Localizable", [NSBundle mainBundle], @"Don't Allow", @"Don't allow button"); NSString *settingsString = NSLocalizedStringWithDefaultValue( @"Settings", @"Localizable", [NSBundle mainBundle], @"Settings", @"Settings button label"); UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleString message:nil preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:cancelString style:UIAlertActionStyleDefault handler:nil]]; [alertController addAction:[UIAlertAction actionWithTitle:settingsString style:UIAlertActionStyleDefault handler: ^(UIAlertAction * _Nonnull action) { NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; [[UIApplication sharedApplication] openURL:url]; }]]; [viewController presentViewController:alertController animated:true completion:nil]; }
doc_23528423
I'm not looking for a complete solution (naturally), I'm asking for help with regard to the orbits of complex numbers. Say I have a given Complex number derived from a point on the complex plane. I now need to iterate over its orbit sequence and plot points according to whether the orbits increase by orders of magnitude or not. How do I gather the orbits of a complex number? Any guidance is much appreciated (links etc). Any pointers on Math functions needed to test the orbit sequence e.g. Math.pow() I'm using Java but that's not particularly relevant here. Thanks again, Alex A: When you display the Mandelbrot set, you simply translate the real and imaginaty planes into x and y coordinates, respectively. So, for example the complex number 4.5 + 0.27i translates into x = 4.5, y = 0.27. The Mandelbrot set is all points where the equation Z = Z² + C never reaches a value where |Z| >= 2, but in practice you include all points where the value doesn't exceed 2 within a specific number of iterations, for example 1000. To get the colorful renderings that you usually see of the set, you assign different colors to points outside the set depending on how fast they reach the limit. As it's complex numbers, the equation is actually Zr + Zi = (Zr + Zi)² + Cr + Ci. You would divide that into two equations, one for the real plane and one for the imaginary plane, and then it's just plain algebra. C is the coordinate of the point that you want to test, and the initial value of Z is zero. Here's an image from my multi-threaded Mandelbrot generator :) A: Actually the Mandelbrot set is the set of complex numbers for which the iteration converges. So the only points in the Mandelbrot set are that big boring colour in the middle. and all of the pretty colours you see are doing nothing more than representing the rate at which points near the boundary (but the wrong side) spin off to infinity. In mathspeak, M = {c in C : lim (k -> inf) z_k = 0 } where z_0 = c, z_(k+1) = z_k^2 + c ie pick any complex number c. Now to determine whether it is in the set, repeatedly iterate it z_0 = c, z_(k+1) = z_k^2 + c, and z_k will approach either zero or infinity. If its limit (as k tends to infinity) is zero, then it is in. Otherwise not. It is possible to prove that once |z_k| > 2, it is not going to converge. This is a good exercise in optimisation: IIRC |Z_k|^2 > 2 is sufficient... either way, squaring up will save you the expensive sqrt() function. A: Wolfram Mathworld has a nice site talking about the Mandelbrot set. A Complex class will be most helpful. Maybe an example like this will stimulate some thought. I wouldn't recommend using an Applet. You have to know how to do add, subtract, multiply, divide, and power operations with complex numbers, in addition to functions like sine, cosine, exponential, etc. If you don't know those, I'd start there. The book that I was taught from was Ruel V. Churchill "Complex Variables". A: /d{def}def/u{dup}d[0 -185 u 0 300 u]concat/q 5e-3 d/m{mul}d/z{A u m B u m}d/r{rlineto}d/X -2 q 1{d/Y -2 q 2{d/A 0 d/B 0 d 64 -1 1{/f exch d/B A/A z sub X add d B 2 m m Y add d z add 4 gt{exit}if/f 64 d}for f 64 div setgray X Y moveto 0 q neg u 0 0 q u 0 r r r r fill/Y}for/X}for showpage
doc_23528424
here is MyClient part... import java.net.Socket; import java.net.ServerSocket; import java.io.*; class MyClient implements Runnable { static Socket s; static DataInputStream cdis; static DataOutputStream cdos; static MyClient clientObj; public static void main(String... hj) { clientObj= new MyClient(); try { s=new Socket("192.168.1.4",10); cdis=new DataInputStream(s.getInputStream()); cdos=new DataOutputStream(s.getOutputStream()); clientObj.clientChat(); } catch(IOException e) {System.out.println(e);} } /* This meathod will handle working of Client Chat. Internally,another thread "receiver" is started which will handle receiving of message from Server.*/ public void clientChat()throws IOException { String send; Thread receiver=new Thread(clientObj); receiver.start(); BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); do { send=input.readLine(); cdos.writeUTF(send); }while(!send.equals("stop")); System.out.println("\t\t\t\t Connection Terminated"); } /* This meathod will be used to recieve mesage from Client .*/ public void run() { String received; try{ do { received=cdis.readUTF(); System.out.println("Server : "+received); }while(!received.equals("stop")); System.out.println("\t\t\t Connection Terminated by Server"); System.exit(0); } catch(IOException e){} } } Here is MyServer part... import java.net.Socket; import java.net.ServerSocket; import java.io.*; class MyServer implements Runnable { static ServerSocket ss; static Socket s; static DataInputStream sdis; static DataOutputStream sdos; static MyServer serverObj; public static void main(String... g)throws IOException { serverObj=new MyServer(); try{ ss=new ServerSocket(10); System.out.println("\t\t\t\t Connection Establishing....."); s=ss.accept(); System.out.println(s); System.out.println("\t\t\t\t Connection Established"); sdis=new DataInputStream(s.getInputStream()); sdos=new DataOutputStream(s.getOutputStream()); serverObj.serverChat(); } catch(IOException e) {System.out.println(e);} } /* This meathod will handle working of Server Chat. Internally,another thread "receiver" is started which will handle receiving of message from client.*/ public void serverChat()throws IOException { String send; Thread receiver=new Thread(serverObj); receiver.start(); BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); do { send=input.readLine(); sdos.writeUTF(send); }while(!send.equals("stop")); System.out.println("\t\t\t\t Connection Terminated"); } /* This meathod will be used to receive mesage from Client .*/ public void run() { String received; try{ do { received=sdis.readUTF(); System.out.println("Shadab : "+received); }while(!received.equals("stop")); System.out.println("\t\t\t Connection Terminated by Shadab"); System.exit(0); } catch(IOException e){} } }
doc_23528425
$statement = db::getInstance()->prepare('INSERT INTO `Training_Log` ( `Trainees_Name`, `Date`, `Time`, `Bus_Number`, `Trainer`, `Training_Shift_Number`, `Number_of_Hours`, `Total_Number_of_Hours`, `Static_Comments`, `PreTrip_Comments`, `Road_Driving_Comments`, `RailRoad_Comments`, `Bus_Stop_Comments`, `Route_Comments`, ) VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); $statement->bind_param('sssiiiissssss', $_SERVER['HTTP_CAS_USER'], $_POST['sec1_trainee'], $_POST['sec1_trainer'], $_POST['sec1_datetime'], $_POST['sec1_bus'], $_POST['sec1_shiftnum'], $_POST['sec1_numhour'], $_POST['sec1_totnumhour'], $_POST['static'], $_POST['pretrip'], $_POST['roaddriving'], $_POST['railroad'], $_POST['busstop'], $_POST['routes']); $statement->execute(); $statement->close(); A: Removing the trailing comma in your insert columns list. `Route_Comments`, ) Should be `Route_Comments`) (There are probably other issues too. Like the fact that you're inserting a DATE into a field called *_name?) You don't see any errors because you're not checking for any errors. http://us3.php.net/manual/en/pdo.errorinfo.php
doc_23528426
I've tried margin:0px auto. Am I overlooking something? Thanks. CSS: .full { width: 100%; height: auto; float: left; clear: none; position: relative; display: block; } .logo { width: 230px; height: 117px; float: left; clear: none; position: relative; display: block; margin: 10px auto 15px auto; padding: 0; } HTML: <div class="full"> <figure class="logo"></figure> <figure class="x-button"></figure> </div> A: Remove the following: .logo { float: left; } You cannot directly center a floated element via margin:0px auto;. If you want an element to be floated and center, you can always apply the margin to the parent while the child itself keeps the float. An example of this can be seen here. Keep in mind, if it is just text you are trying to center, you can always just use: text-align:center; A: Remove float: left; for .logo. float: left makes it align to the left. Click here for a demo fiddle. A: At least in this case, you can not center a floated element horizontally. Here is a minimal example: http://jsfiddle.net/tJ5N3/ You can remove the floating, as others said above. Also, as a workaround, you can wrap your element with a div that is horizontally centered. In this case, your can keep your floating, if it is necessary.
doc_23528427
A: You could use recursion. public void doSomethingToAll(List list) { // Begin the recursion. doSomethingToAll(list, 0); } private void doSomethingToAll(List list, int index) { // Break the recursion when we have processed the entire list. if (index >= list.size()) return; // Do whatever you want with the list. process(list.get(index)); // Recursive step. Process the next element. doSomethingToAll(list, index + 1); } A: Not saying what I offer is the only and the best solution, but it's generic enough to be reused easily, type-safe, and allows you to break early in the course of your traversal. You can easily extend it and make it generic to any type of collection. A Simple Traversal Implementation The implementation is composed of: * *a reusable type-safe Actor class to define actions (if any), *a reusable type-safe Traversal class, *and an exception class used to break out early of a traversal. By reusable I mean that once used on a collection you can reuse it without needing to reinstantiate it, so that you only need one instance per target behavior. Actor interface Actor<T> { void act(final T element) throws TraversalInterruptionException; } Traversal class Traversal<T> { int index = 0; Actor<T> actor = null; public Traversal(final Actor<T> a) { actor = a; } void traverse(final List<T> col) { if (index < col.size()) { final T element = col.get(index++); try { if (actor != null) { actor.act(element); } traverse(col); } catch (final TraversalInterruptionException e) { /* let's get out of there early */ index = 0; // reset } } else { index = 0; // reset } } } TraversalInterruptionException class TraversalInterruptionException extends Exception { } Test It @Test public void test() { final List<String> list = new ArrayList<String>(); final Traversal<String> strTraversal = new Traversal<String>(new Actor<String>() { @Override public void act(final String element) throws TraversalInterruptionException { if ("exit".equals(element)) { throw new TraversalInterruptionException(); } System.out.println(element); } }); list.add("test1"); list.add("test2"); list.add("test3"); list.add("exit"); list.add("test4"); strTraversal.traverse(list); strTraversal.traverse(list); // and again to test the reset } Output test1 test2 test3 test1 test2 test3 A: You can do something dumb like this: void traverse(ArrayList list) { traverseHelper(list, 0); } void traverseHelper(ArrayList list, int index) { if (index == list.size()) return; "visit" list.get(index); traverseHelper(list, index+1); } It uses recursion instead of iteration, but why would you want to do this? A: You can try with recursion: void traverse(ArrayList<Whatever> list, int cur) { if (cur == list.size()) return; else { Whatever elem = list.getAt(cur); System.out.println(elem); traverse(list, ++cur); } } void traverse(ArrayList<Whatever> list) { traverse(list, 0); }
doc_23528428
I have : @Override public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text){ Rectangle rectangle = new Rectangle(rect); //something like that : rectangle.setWidth(400f); } A: You can (and should) not use a method called setWidth(). Whatever that method would do would be very ambiguous. Suppose that you would have a rectangle with lower-left x coordinate equal to 36 and with upper-right x coordinate equal to 559. (I didn't choose these numbers at random: those are the default margins inside the default A4 page when using iText.) Now when you change the width of such a rectangle: do you mean to extend the rectangle to the left, to the right, or both? I hope this example shows that having a setWidth() method doesn't make sense. Instead, you should use setLeft() or setRight() when you change the x value of the left or right coordinate of the rectangle, you automatically change the width and there can be no confusion about the direction in which you're changing the width.
doc_23528429
I figure the modal segue class is inappropriate for this situation since ideally the transition to the home screen would be permanent, not temporary. But Push didn't make any sense either, since the login screen isn't a Navigation controller, and that isn't the functionality I'm looking for anyway. What would be the best way approach this specific case? Thanks! A: I think you can present it as modal viewController and then set it as rootviewController of appDelegate. There are different transition styles: modelViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; modelViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; modelViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; modelViewController.modalTransitionStyle = UIModalTransitionStylePartialCurl; A: Since its a login screen (for profiles or custom settings or something) perhaps just a simple view on the same view controller might be enough? Unless you want to create a really complex log in proceadure I dont think you have to create another view controller for this. (just my opinion tho)
doc_23528430
paramGrid = HyperparamBuilder().addHyperparam(gbt,gbt.maxBin, DiscreteHyperParam([200, 255,300])) searchSpace= paramGrid.build() print(searchSpace) type(searchSpace) GridSpace(searchSpace) This gives me the following error P Py4JError: An error occurred while calling None.com.microsoft.azure.synapse.ml.automl.GridSpace. Trace: py4j.Py4JException: Constructor com.microsoft.azure.synapse.ml.automl.GridSpace([class [Lscala.Tuple2;]) does not exist When I ran the code to instantiate a RandomSpace object it worked properly. I checked the api docs of the 2 constructors here https://mmlspark.blob.core.windows.net/docs/0.10.1/pyspark/_modules/synapse/ml/automl/HyperparamBuilder.html#DiscreteHyperParam For GridSpace: def __init__(self, paramValues): And for RandomSpace: def __init__(self, paramDistributions): I saw both the params are unpacked in the same way , so I am not able to figure out the mistake. A: Import the necessary modules and try below code: >from synapse.ml.automl import HyperparamBuilder, DiscreteHyperParam, GridSpace #Define your hyperparameter gbt = <your gradient boosting tree estimator> paramGrid = HyperparamBuilder().addHyperparam(gbt, gbt.maxBin, DiscreteHyperParam([200, 255, 300])) Convert your HyperparamBuilder object into a format that the GridSpace constructor >pa_val = {param.name: values for param, values in paramGrid.paramDict.items()} ser_sp = GridSpace(list(pa_val.items())) print(ser_sp)
doc_23528431
alter table IAM_Software_Licence_Master alter column SoftwareLicId int identity(1,1) primary key How can I achieve this.. A: Its difficult to say what the issues are with changing this on your end as I do not know the table structure or whether or not this is used as a foreign Key. But the below link should give you everything you need: http://social.msdn.microsoft.com/Forums/sqlserver/en-US/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032/how-to-alter-column-to-identity11
doc_23528432
I have the following two Custom tasks, Get that produces a Hashtable and Set that should consume it. Get.cs public class Get : Task { [Output] public Hashtable Output { get; set; } public override bool Execute() { Output = new Hashtable(); return true; } } Set.cs public class Set : Task { [Required] public Hashtable Output { get; set; } public override bool Execute() { var items = Output.Cast<DictionaryEntry>().ToDictionary(d => d.Key.ToString(), d => d.Value.ToString()); foreach(var item in items) { //Do Something } return true; } } The above classes build fine into Assembly.dll I then use that Assembly.dll in the following build target script to call the Get and Set custom tasks: MyTarget.targets <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="Get" AssemblyFile=".\Assembly.dll"/> <UsingTask TaskName="Set" AssemblyFile=".\Assembly.dll"/> <Target Name="Get"> <Get> <Output TaskParameter="Output" ItemName="Output" /> </Get> <Set Output=@(Output) /> </Target> </Project> When I build the project with the above target MSBuild shows the following error: The "System.Collections.Hashtable" type of the "Output" parameter of the "Get" task is not supported by MSBuild How can I use an Hashtable or Dictionary in a property for a custom MSBuild task? A: The Parameters that can go in or out a Task are limited to either ITaskItem or an array of ITaskItem's. So your properties should change from public Hashtable Output { get; set; } to public ITaskItem[] Output { get; set; } to match that requirement. Next you need an implementation class that implements ITaskItem. That allow you to handle your hashset or dictionary. I left that for you that add but a minimal KeyValue class could look like this: public class KeyValue: ITaskItem { string _spec = String.Empty; public KeyValue(string key, string value) { _spec = key; metadata.Add("value", value); } Dictionary<string,string> metadata = new Dictionary<string,string>(); public string ItemSpec { get {return _spec;} set {} } public ICollection MetadataNames { get {return metadata.Keys;} } public int MetadataCount { get {return metadata.Keys.Count;} } public string GetMetadata(string metadataName) { return metadata[metadataName]; } public void SetMetadata(string metadataName, string metadataValue) { metadata[metadataName] = metadataValue; } public void RemoveMetadata(string metadataName) { } public void CopyMetadataTo(ITaskItem destinationItem) { } public IDictionary CloneCustomMetadata() { return metadata; } } This class will produce and Item that will look look this if it was done in plane MSBuild script: <Item Include="key"> <value>some value</value> </Item> Next you can adapt the Set and Get Task to use this new class KeyValue: public class Set : Task { TaskLoggingHelper log; public Set() { log = new TaskLoggingHelper(this); } [Required] public ITaskItem[] Output { get; set; } public override bool Execute() { log.LogMessage("start set"); foreach(var item in Output) { log.LogMessage(String.Format("Set sees key {0} with value {1}.",item.ItemSpec, item.GetMetadata("value"))); } log.LogMessage("end set"); return true; } } public class Get : Task { // notice this property no longer is called Output // as that gave me errors as the property is reserved [Output] public ITaskItem[] Result { get; set; } public override bool Execute() { // convert a Dictionary or Hashset to an array of ITaskItems // by creating instances of the class KeyValue. // I use a simple list here, I leave it as an exercise to do the other colletions Result = new List<ITaskItem> { new KeyValue("bar", "bar-val"), new KeyValue("foo","foo val") }.ToArray(); return true; } } The build file I used to test above code: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="Get" AssemblyFile=".\cb.dll"/> <UsingTask TaskName="Set" AssemblyFile=".\cb.dll"/> <Target Name="Get"> <Get> <Output TaskParameter="Result" ItemName="GetResult" /> </Get> <!-- lets see what we've got --> <Message Importance="high" Text="key: @(GetResult) :: value: %(value)" /> <Set Output="@(GetResult)"> </Set> </Target> </Project> When run the result will be: Build started 24-12-2017 21:26:17. Project "C:\Prj\bld\test.build" on node 1 (default targets). Get: key: bar :: value: bar-val key: foo :: value: foo val start set Set sees key bar with value bar-val. Set sees key foo with value foo val. end set Done Building Project "C:\Prj\bld\test.build" (default targets). Build succeeded. 0 Warning(s) 0 Error(s) A: You can use the TaskItem(String, IDictionary) constructor, which would look something like this. public class Get : Task { [Output] public ITaskItem Result { get; set; } public override bool Execute() { var values = new Dictionary<string, string>(); values["Foo"] = "Bar"; Result = new TaskItem("Result", values); return true; } } <UsingTask TaskName="Get" AssemblyFile=".\cb.dll"/> <Target Name="Get"> <Get> <Output TaskParameter="Result" ItemName="ResultItem" /> </Get> <Message Text="%(ResultItem.Foo)" /> </Target>
doc_23528433
I can find that the ripple on Raised Buttons is defined in drawable/v21/abc_btn_colored_material.xml. But the only flat button drawable is defined in the base drawables/abc_btn_borderless_material.xml which doesn't have ripple (obviously). So where is the ripple getting set on flat buttons? I'm looking in appcompat-v7:23:4.0 EDIT: I did follow the path described by Alexander Mironov but my btn_borderless_material looks like: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/abc_btn_default_mtrl_shape"/> <item android:state_pressed="true" android:drawable="@drawable/abc_btn_default_mtrl_shape"/> <item android:drawable="@android:color/transparent"/> </selector> A: Let's start our journey with AppCompat values.xml: <style name="Widget.AppCompat.Button.Borderless" parent="Base.Widget.AppCompat.Button.Borderless"/> When we go to parent we have specialization with v21 qualifier values-v21.xml. Here we see: <style name="Base.Widget.AppCompat.Button.Borderless" parent="android:Widget.Material.Button.Borderless"/> Ok, that's mean that when API is 21 or higher we use Android's built-in theme. Let's go to styles_material.xml: <!-- Borderless ink button --> <style name="Widget.Material.Button.Borderless"> <item name="background">@drawable/btn_borderless_material</item> <item name="stateListAnimator">@null</item> </style> Then go to btn_borderless_material. And finally we have our ripple: <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?attr/colorControlHighlight"> <item android:id="@id/mask" android:drawable="@drawable/btn_default_mtrl_shape" /> </ripple>
doc_23528434
As you can see, one of the 1x5 rectangular cuboids has been rotated by 90º. This was achieved by setting the y attribute of the Euler Angles property to 90 in the Node Inspector. But notice that the Bounding Box doesn't account for the cuboids rotation. This is also the case when I iterate through the SCNNodes in the scene. Both cuboids have the same Bounding Volumne for wall:SCNNode in walls.childNodes { var v1 = SCNVector3Zero var v2 = SCNVector3Zero wall.getBoundingBoxMin(&v1, max:&v2) print(v1, v2) } // Prints // SCNVector3(x: -0.5, y: 0.0, z: -2.5) SCNVector3(x: 0.5, y: 0.5, z: 2.5) // SCNVector3(x: -0.5, y: 0.0, z: -2.5) SCNVector3(x: 0.5, y: 0.5, z: 2.5) So it seems the Bounding Volume is calculated using the child node's own coordinate system, not node parent's (or scene's) coordinate system. Which leaves me wondering; How do I calculate the SCNNodes bounding volume in the scene? Looking through the documentation for SCNNode, it seems all the information is there. I can read the eulerAngles which gives me the correct rotation around the y axis. I can read the transform property. I thought I might be able to multiply the vectors by the nodes transform matrix, but the transform matrix (4x4) and bounding box vectors (1x3) don't appear to be compatible. Nor does SceneKit appear to provide any methods for applying a transformation matrix to a vector. However, I'm not great with Geometry so I could be missing something obvious. A: A few ideas: * *In Interface Builder, as shown on your screenshot, there's an Editing space property that you can set to World (instead of Local) *In code, you can use a temporary node to compute the bounding box. Make sure that only has one child node (the node whose bounding box you want to compute), apply any transform on that child node, and they ask the parent node for its bounding box. From the documentation: The bounding volume of a node containing child nodes is the minimal volume that encloses the bounding volumes of the node’s children. *Get the node's bounding box and then use utils such as -convertPosition:toNode: to compute the bounding box in another's coordinate system
doc_23528435
What I basically have is a list of all animals in my current world with information about animal type and location. This list can grow very large - probably close to millions. So, in order to implement some simple AI, I need to make this operation as fast as possible: Given a point on the map and a radius, give me a list of all animals within the radius sorted by the distance from center point. The world would be 2d so we are limited to planar coordinates. Some of the operations I also need to support: * *Changing location of animals *Creating new animals *Removing animals I read about kd trees and their ability to calculate nearest neighbour fast. Questions: do you think it will work in my case? If not, what data structure should I use to meet the requirements? EDIT: Here are some more details as requested in comments. The world wouldn't be too big - something that can fit a screen with animals being little circles. I should also support the scenario where the world could become fairly dense. Finally, I expect not more than a few dozens returned per query but as I will have a great number of those queries (one per each animal althrough this should be cached somehow probably but let's forget about that for simplicity for now) this to be as fast and efficient as possible. A: Given your constraints (a large number of moving objects and a small world of presumably fixed size), a simple grid may be a better fit than a kd-tree. See: Trees or Grids? Indexing Moving Objects in Main Memory A: kd-trees should work fine if there are many queries before the positions change (e.g., one per animal). Incremental updates probably would be fine as well, but an immutable kd-tree that is completely rebuilt when necessary has the advantage that the tree structure can be represented succinctly with an array. To find all points within a search disk, traverse the tree while pruning nodes whose half-plane completely excludes the search disk. You'll have to sort the results by distance at the end.
doc_23528436
* *I added item editing features to my code, unfortunately when I accept changes my item doesn't change. The add (almost), remove option works as it should. The update option, however, does not send a request. *The second problem is that after a slight change of code to add the function of editing the element, my code for adding the element broke a bit. After completing the form and sending it, the element is added, BUT is added without an ID code and I get the error: Warning: Each child in a list should have a unique "key" prop. After refreshing the page, the problem disappears, the previously added item already has an ID and is displayed correctly. PROBLEM NUMBER 1 TaskDetail.js component import React, { Component } from "react"; import { connect } from "react-redux"; import { getTask, updateTask } from "../../actions/tasks"; import { Redirect } from "react-router-dom"; class TaskDetail extends Component { constructor(props) { super(props); this.state = { title: "", description: "", date: "", hours: null, }; } componentDidMount() { this.props.getTask(this.props.match.params.id); setTimeout(() => this.update(), 50); } update = () => { console.log("STATE UPDATE"); const { title, description, date, hours } = this.props.task[0]; this.setState({ title: title, description: description, date: date, hours: hours, }); }; onChange = (e) => { this.setState({ [e.target.name]: e.target.value, }); }; onSubmit = (e) => { console.log("UPDATE REQUEST"); const task = { title: this.state.title, description: this.state.description, date: this.state.date, hours: this.state.hour, }; this.props.updateTask(this.props.task.id, task); }; render() { const { title, description, date, hours } = this.state; return ( <div className="card mt-5"> <div className="card-header"> <span>ID: {this.props.match.params.id}</span> </div> <form className="card-body" onSubmit={this.props.updateTask.bind( this.props.match.params.id, this.state )} > <div className="form-group"> <label>Title</label> <input type="text" className="form-control" name="title" onChange={this.onChange} value={title || ""} /> </div> <div className="form-group"> <label>Description</label> <textarea type="text" className="form-control" name="description" onChange={this.onChange} value={description || ""} /> </div> <div className="date-hours-form"> <div className="form-group"> <label>Date</label> <input type="date" className="form-control" name="date" onChange={this.onChange} value={date || ""} /> </div> <div className="form-group"> <label>Hours</label> <input type="number" className="form-control" name="hours" onChange={this.onChange} value={hours || ""} /> </div> </div> <div className="form-group"> <button type="submit" className="btn btn-block btn-suc"> EDIT TASK </button> </div> </form> </div> ); } } const mapStateToProps = (state) => ({ task: state.tasks.task, isLoading: state.tasks.isLoading, }); export default connect(mapStateToProps, { getTask, updateTask })(TaskDetail); tasksAction.js // UPDATE TASK export const updateTask = (id, task) => (dispatch) => { console.log(`ID: ${id} TASK: ${task}`); axios .put(`/api/tasks/${id}/`, task) .then((response) => { dispatch({ type: UPDATE_TASK, payload: task, }); }) .catch((err) => console.log(err.response)); }; tasksReducser.js import { GET_TASKS, DELETE_TASK, CREATE_TASK, GET_TASK_REQUEST, GET_TASK_SUCCESS, UPDATE_TASK, } from "../actions/types.js"; const initialState = { tasks: [], task: {}, isLoading: false, }; export default function (state = initialState, action) { switch (action.type) { case GET_TASKS: return { ...state, tasks: action.payload, }; case DELETE_TASK: return { ...state, tasks: state.tasks.filter((task) => task.id !== action.payload), }; case CREATE_TASK: return { ...state, tasks: [...state.tasks, action.payload], }; case GET_TASK_REQUEST: console.log("TASK GET PENDING"); return { ...state, isLoading: action.payload.loading, }; case GET_TASK_SUCCESS: console.log("TASK GET SUCCESS"); return { ...state, task: state.tasks.filter((task) => task.id === action.payload.data.id), isLoading: action.payload.loading, }; case UPDATE_TASK: console.log("TASK UPDATED"); return { ...state, task: {}, }; default: return state; } } PROBLEM NUMBER 2 TasksList.js import React, { Component, Fragment } from "react"; import { connect } from "react-redux"; import { getTasks, deleteTask, getTask } from "../../actions/tasks"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; export class Tasks extends Component { static propTypes = { tasks: PropTypes.array.isRequired, getTasks: PropTypes.func.isRequired, deleteTask: PropTypes.func.isRequired, }; render() { return ( <div className="card card-tasks card-body mt-3"> <table className="table table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Title</th> <th scope="col">Date</th> <th scope="col">Hours</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {this.props.tasks.map((task) => ( <Fragment key={task.id}> <tr> <th>{task.id}</th> <td>{task.title}</td> <td>{task.date}</td> <td>{task.hours}</td> <td> <Link to={{ pathname: `/edit/${task.id}`, state: { id: task.id }, }} className="btn btn-primary" > DETAIL </Link> </td> <td> <button onClick={this.props.deleteTask.bind(this, task.id)} className="btn btn-danger" > DELETE </button> </td> </tr> </Fragment> ))} </tbody> </table> </div> ); } } const mapStateToProps = (state) => ({ tasks: state.tasks.tasks, }); export default connect(mapStateToProps, { getTasks, deleteTask, getTask })( Tasks );
doc_23528437
Class P has an instance for every mapped doc entity, which uses the single Parser instance to parse a doc. class P (object): def __init__(self, parser, ...): self.parser = parser .... def get_content(...) .... # using methods from P and self.parser def other methods ... .... # using methods from P and self.parser class Parser(object): def __init__(args) .... def some parser methods() .... def callback(entity): # Is now a method of Parser, but .... p = P(self, ...) .... content = p.get_content(...) .... parser = Parser(...) # initialize Parser (instance, closure) query = Docs.query() multi_future = query.map_async(parser.callback) .... # process results This works fine, but does not feel well structured. I look for a solution where P inherits from Parser: (The callback can / should be part of P) query = Docs.query() multi_future = query.map_async(????? P ??????) .... # process results A: I figured it out, using a lambda. query = Docs.query() multi_future = query.map_async(lambda entity: P(...).callback(entity))
doc_23528438
table name: companies country | name canada a usa b china c france d table name: orders id| importer | exporter | value 23 canada usa 10 24 usa china 50 25 canada china 10 26 france usa 40 I can produce the sum of imports and sum of exports tables seperately using a join for example: sum of importers select name, sum(value) from orders full outer join companies on orders.importer = companies.country I would like to see one table combining both sum of imports and sum of exports grouped by the name. The sum of imports and sum of exports is a sum on the value column in the orders table. I'm confused as to if i have to use a subquery here. Example table Name | sum of importer | sum of exporter a 20 0 b 50 50 c 0 60 d 40 0 A: You need to use, two full outer join separately and join them based on name column for this purpose. The working query is: select g1.name, g1.sumofimporter, g2.sumofexporter from ( select c.name ,COALESCE(sum(o1.value), 0) as sumofimporter from companies c full outer join orders o1 on o1.importer = c.country group by c.name ) g1 join ( select c.name ,COALESCE(sum(o2.value), 0) as sumofexporter from companies c full outer join orders o2 on o2.exporter = c.country group by c.name ) g2 on g2.name = g1.name order by g1.name Note: Since the post is about postgresql, but I created a working demo on SQL Server for testing purpose. Please find the demo on db<>fiddle A: '''It's actually very simple.. use the following - select c.name, IFNULL(sum(i.value),0) as sum_of_imports, IFNULL(sum(e.value),0) as sum_of_exports from companies c Left join orders i on c.country = i.importer Left join orders e on c.country = e.exporter group by c.name order by c.name asc; A: Check this- SELECT A.name,A.sum_of_importer,COALESCE(SUM(O2.value),0) sum_of_exporter FROM ( SELECT C.name,C.country,COALESCE(SUM(Value),0) AS sum_of_importer FROM Companies C LEFT JOIN orders O ON C.country = O.importer GROUP BY C.name,C.country )A LEFT JOIN orders O2 ON A.country = O2.exporter GROUP BY A.name,A.sum_of_importer ORDER BY 1 A: I'd solve it like this: WITH importer AS (SELECT orders.importer, SUM(orders.value) AS t_import FROM orders GROUP BY 1), exporter AS (SELECT orders.exporter, SUM(orders.value) AS t_export FROM orders GROUP BY 1) SELECT c.name, COALESCE(i.t_import, 0) sum_of_import, COALESCE(e.t_export, 0) sum_of_export FROM company c LEFT JOIN importer i ON c.country = i.importer LEFT JOIN exporter e ON c.country = e.exporter Which gave me: name | sum_of_import | sum_of_export a 20 0 b 50 50 c 0 60 d 40 0 Planning Time: 0.157 ms Execution Time: 0.120 ms My thinking: I decided to split it into two different CTEs because it is easier to then join. You get the value for each country for when it's an importer or exporter. Then using a left join (to not lose any country that is not showing as an importer or exporter).
doc_23528439
I have a working piece of code that adds a fee and updates the cart on click of a checkbox, but I want it to add a product instead of a surcharge fee: function cart_custom_fee( $cart ) { if( !$_POST || ( is_admin() && ! is_ajax() ) ) { return; } if( isset( $_POST['post_data'] ) ) { parse_str( $_POST['post_data'], $post_data ); } else { $post_data = $_POST; } if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name WC()->cart->add_fee('Test Item', 35); } } add_action( 'woocommerce_cart_calculate_fees', 'cart_custom_fee' ); This is the code for the checkbox <script> jQuery(document).ready(function(){ jQuery('#cp-checkbox').click(function() { jQuery('body').trigger('update_checkout'); }); }); </script> And the code works… Now, I tried changing the code to add a product instead: function add_item_checkout( $cart ) { if( !$_POST || ( is_admin() && ! is_ajax() ) ) { return; } if( isset( $_POST['post_data'] ) ) { parse_str( $_POST['post_data'], $post_data ); } else { $post_data = $_POST; } if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name WC()->cart->add_to_cart( 123 ); // 123 is the product ID } } add_action( 'woocommerce_calculate_totals', 'add_item_checkout' ); But it didn't work. Any help will be appreciated. A: Update (related to your comment). This can only be done with Javascript (jQuery) and Ajax as it's a client side event and nothing is submitted when making an action on a checkout field. When this checkbox will be checked, a specific product will be added to cart refreshing the checkout order review data. If the checkbox is unchecked by the customer, it will remove the specific product, refreshing the checkout order review data. Update changes: I have changed the checkbox under payment options and lightly changed the jQuery code, to handle the checkbox value, as it's now Ajax refreshed too. The code: // Display a custom checkout field add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' ); function custom_checkbox_checkout_field() { $value = WC()->session->get('add_a_product'); woocommerce_form_field( 'cb_add_product', array( 'type' => 'checkbox', 'label' => '&nbsp;&nbsp;' . __('Add a demo product to your order'), 'class' => array('form-row-wide'), ), $value == 'yes' ? true : false ); } // The jQuery Ajax request add_action( 'wp_footer', 'checkout_custom_jquery_script' ); function checkout_custom_jquery_script() { // Only checkout page if( is_checkout() && ! is_wc_endpoint_url() ): // Remove custom WC session variables on load if( WC()->session->get('add_a_product') ){ WC()->session->__unset('add_a_product'); } if( WC()->session->get('product_added_key') ){ WC()->session->__unset('product_added_key'); } // jQuery Ajax code ?> <script type="text/javascript"> jQuery( function($){ if (typeof wc_checkout_params === 'undefined') return false; $('form.checkout').on( 'change', '#cb_add_product', function(){ var value = $(this).prop('checked') === true ? 'yes' : 'no'; $.ajax({ type: 'POST', url: wc_checkout_params.ajax_url, data: { 'action': 'add_a_product', 'add_a_product': value, }, success: function (result) { $('body').trigger('update_checkout'); console.log(result); } }); }); }); </script> <?php endif; } // The Wordpress Ajax PHP receiver add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' ); add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' ); function checkout_ajax_add_a_product() { if ( isset($_POST['add_a_product']) ){ WC()->session->set('add_a_product', esc_attr($_POST['add_a_product'])); echo $_POST['add_a_product']; } die(); } // Add remove free product add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' ); function adding_removing_specific_product( $cart ) { if (is_admin() && !defined('DOING_AJAX')) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // HERE the specific Product ID $product_id = 53; if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') ) { $cart_item_key = $cart->add_to_cart( $product_id ); WC()->session->set('product_added_key', $cart_item_key); } elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') ) { $cart_item_key = WC()->session->get('product_added_key'); $cart->remove_cart_item( $cart_item_key ); WC()->session->__unset('product_added_key'); } } Code goes in function.php file of your active child theme (or active theme). Tested and work. * *The order items and the checkbox custom field under payment methods *When enabling the checkbox, the product is added and appear in order items:
doc_23528440
I have try to delete the button and re-post it . but still have the same problem. I used node js and I followed FaceBook's documentation: facebook get started button documentation Anyone has a solution? Is it a bug? Thanks a lot in advance for your answers. A: There are certain conditions to seeing the Welcome Screen and the Get Started button: * *They are only rendered the first time the user interacts with the Page on Messenger *Only admins/developers/testers of the app can see it when the app is in development mode *Your app must be subscribed to postbacks on your webhook These are the conditions mentioned in the documentation. Make sure they are satisfied. There are two ways you can try to see the get started button: * *Try using the bot with a new user *Clear all existing conversation with the bot, force close messenger app and relaunch it and start a conversation with bot
doc_23528441
doc_23528442
from collections import namedtuple from typing import List TestCase = namedtuple("TestCase", ["number_of_purchased_items", "prices"]) def prepare_tests() -> List[TestCase]: tests = [] cases_amount = int(input()) for _ in range(cases_amount): number_of_purchased_items = int(input()) prices = [int(price) for price in input().split(maxsplit=number_of_purchased_items + 1)] test_case = TestCase(number_of_purchased_items, prices) tests.append(test_case) return tests Input( where 2 - test_cases amount, then 6 - numOfPurchasedItems, 2 2 2 3 3 3 - list 2 6 2 2 2 3 3 3 7 1 1 2 2 3 3 5 Output [TestCase(number_of_purchased_items=6, prices=[2, 2, 2, 3, 3, 3]), TestCase(number_of_purchased_items=7, prices=[1, 1, 2, 2, 3, 3, 5])] I tried to write the same in Go: package main import ( "bufio" "fmt" "os" "strconv" "strings" ) type testCase struct { numberOfPurchasedItems int prices []int } func prepareTests() []testCase { var tests []testCase scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanWords) scanner.Scan() casesAmount, err := strconv.Atoi(scanner.Text()) if err != nil { fmt.Println("Error:", err) return tests } for i := 0; i < casesAmount; i++ { scanner.Scan() numberOfPurchasedItems, err := strconv.Atoi(scanner.Text()) if err != nil { fmt.Println("Error:", err) return tests } scanner.Scan() pricesStr := scanner.Text() var prices []int for _, priceStr := range strings.Split(pricesStr, " ") { price, err := strconv.Atoi(priceStr) if err != nil { fmt.Println("Error:", err) return tests } prices = append(prices, price) } tests = append(tests, testCase{numberOfPurchasedItems, prices}) } return tests } Output in Go: [{6 [2]} {2 [2]}] A: you don`t need scanner.Split(bufio.ScanWords) so just delete that code type testCase struct { numberOfPurchasedItems int prices []int } func prepareTests() []testCase { var tests []testCase scanner := bufio.NewScanner(os.Stdin) //scanner.Split(bufio.ScanWords) scanner.Scan() casesAmount, err := strconv.Atoi(scanner.Text()) if err != nil { fmt.Println("Error:", err) return tests } for i := 0; i < casesAmount; i++ { scanner.Scan() numberOfPurchasedItems, err := strconv.Atoi(scanner.Text()) if err != nil { fmt.Println("Error:", err) return tests } scanner.Scan() pricesStr := scanner.Text() var prices []int for _, priceStr := range strings.Split(pricesStr, " ") { price, err := strconv.Atoi(priceStr) if err != nil { fmt.Println("Error:", err) return tests } prices = append(prices, price) } tests = append(tests, testCase{numberOfPurchasedItems, prices}) } return tests }
doc_23528443
But if the window is closed (as it will be) and the user clicks for a second time the button on the page that opens the popup, the popup opens but no report content appears. Here is the client code: $(document).ready(function () { $('#printButton').click(function () { var printPopup = $.telerik.window.create({ title: "Resident Account Report", contentUrl: '/myApp/ReportPages/ReportPage.aspx' + '?rpt=myReport&ID=' + @Model.id, actions: ["Refresh", "Maximize", "Close"], height: 600, width: 1100, modal: true, resizable: true, draggable: true, scrollable: false, onRefresh: function () { var myWindow = $(this).data('tWindow'); myWindow.center().open(); } }); }); }); Is the problem because the first popup instance still exists in the DOM and needs to be disposed? A: I am sure the problem you explained above is exactly the cause. Closing MVC popup windows does not dispose the object loaded into MVC Popup Window. So either you dispose and reload the report module for each popup or just use the export the report content from the original page to your popup, this way your content will always be in parent window and popup will just be used to view exported report data. A: I know this question is almost 1.5 years old, but I faced same issue and I have a solution for it, so sharing solution for my brothers who will face this issue in future. In my case I was returning entire view from Action in response to ajaxRequest(). and in that case it was also returning all JS files, CSS files etc. which are conflicting with existing files. When i changed my action to return partial view everything works like charm. Thank you, Sandesh Daddi
doc_23528444
The whole javascript file is codepen.io/smarty_tech/pen/gWpKjE (function($) { jQuery.fn.lightTabs = function(options) { var createTabs = function() { tabs = this; i = 0; showPage = function(i) { $(tabs).children("div").children("div").hide(); $(tabs).children("div").children("div").eq(i).show(); $(tabs).children("select").children("option").removeClass("current"); $(tabs).children("select").children("option").eq(i).addClass("current"); } showPage2 = function(i) { $(tabs).children("div").children("div").hide(); $(tabs).children("div").children("div").eq(i).show(); clasw = '.re-compare-wrap-' + i; $(clasw).css("display", "block"); $(clasw).css("display", "block"); } showPage(0); datap = $('#re-compare-bar-tabs').children("select").children("option:selected").attr("data-page"); <!-- $(tabs).children("select").children("option").removeClass("current"); --> $('.re-compare-wrap').css("display", "none"); clas = '.re-compare-wrap-' + datap; $(clas).css("display", "block"); function ret(dt) { return dt.attr('data-comparing'); } function abc() { var dt = $("#re-compare-bar-tabs select option:first"); va1 = ret(dt); alert(va1); if (typeof va1 !== typeof undefined && va1 !== false) { alert('hi'); words1 = va1.split(","); text1 = $(this).html(); pos11 = text1.indexOf("("); pos21 = text1.indexOf(")"); $(this).text(text1.substring(0, pos11 + 1) + words1.length + text1.substring(pos21)); } $("#re-compare-bar-tabs select > option").each(function() { va = ret($(this)); alert(va); if (typeof va !== typeof undefined && va !== false) { words = va.split(","); alert(words.length); text = $(this).html(); pos1 = text.indexOf("("); pos2 = text.indexOf(")"); $(this).text(text.substring(0, pos1 + 1) + words.length + text.substring(pos2)); } }); } abc(); $(tabs).children("select").children("option").each(function(index, element) { $(element).attr("data-id", i); i++; }); $(tabs).children("select").change(function() { var element = $(this).find('option:selected'); showPage(parseInt(element.attr("data-id"))); }); }; return this.each(createTabs); }; })(jQuery); From function ret onward code doesn't work without alerts. I tried https://www.sitepoint.com/community/t/script-works-only-when-alert-is-called/2803/7 but no luck. A: You can use setTimeout for create delay instead alert. setTimeout(function(){ your code here }, 1000);
doc_23528445
What I want is, if it exists, the @Entity Note for a given messagId and group, but I don't understand the syntax. How do I specify the messageId and group for the below query? public void persist(Msg message) { LOG.info("\t" + message); LOG.info("isOpen?" + em.isOpen()); em.getTransaction().begin(); int id = message.getId(); Query q = em.createQuery("SELECT n " + "FROM Notes n WHERE n.messageId = :messageId " + "AND n.group = :group"); List results = q.getResultList(); em.getTransaction().commit(); for (Object o : results) { LOG.info("object is \n\n" + o); } } } A: You need to set the parameters on the query using setParameter(). See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Parameters A: Use setParameter(String name, Object value) q.setParameter("messageId", id).setParameter("group", group); To make it better, use TypedQuery public void persist(Msg message) { LOG.info("\t" + message); LOG.info("isOpen?" + em.isOpen()); em.getTransaction().begin(); int id = message.getId(); TypedQuery<Note> q = em.createQuery("SELECT n " + "FROM Notes n WHERE n.messageId = :messageId " + "AND n.group = :group", Note.class); q.setParameter("messageId", id).setParameter("group", group); List<Note> results = q.getResultList(); em.getTransaction().commit(); for (Note o : results) { LOG.info("object is \n\n" + o); } }
doc_23528446
* *| Name | Surname | Age | *| Robert | Red | 25 and I want to use the name Robert in the code like a variable but to export it from the CSV file. (so something like csv.name[1]) I've been studying for 2/3 months now so I'm totally a beginner. I've been searching online or in forums but couldn't find anything. Let me know if there's something confusing. Have a wonderful day all. Edit* and then you can do like * *var name = csv.name[1] *console.log(name) And by editing the name automatically will change the output. A: Since this post is tagged with node.js, I'm going to assume that you are actually using it. Javascript doesn't have any built-in ways to directly access rows and columns from a csv file. You have to firstly parse the csv file into a type which Javascript can understand. That being said, your best bet might be installing the following npm package (or just the csv-parse subpackage). If you don't want to install additional npm packages, take a look at this answer. It's a simple Javascript function that allows you to parse a csv file into an array which you can access like you mentioned in your question (array[row][column]). A: You might look at d3-dsv (delimiter seperated values) part of the d3 library. const csvInput = "Name,Surname,Age\nRobert,Red,25\nJudith,Gray,29" const parsed = d3.csvParse(csvInput); console.log(parsed[0].Name); console.log(parsed); <script src="https://cdn.jsdelivr.net/npm/d3-dsv@3"></script>
doc_23528447
This works perfectly for Android. But for iOS, the image[] is created also contains some data but it is entirely different from android. And for uri null value only present. Please help me to solve this issue.! (Note: Android should not get affected by change.) Thanks in advance.! Images Array: (For Android) [ { 'file': 'content://media/external/images/media/30993', 'size': 125434, 'uri': 'content://media/external/images/media/30993', 'isDirectory': false, 'md5': '041550fe959f36d1b247bb6b2eaa3272', 'exists': true }, { 'file': 'content://media/external/images/media/30988', 'size': 541148, 'uri': 'content://media/external/images/media/30988', 'isDirectory': false, 'md5': '39bf35dfcf0852c5412205195a395b29', 'exists': true } ] Images Array: (For iOS) [ { 'file': 'assets-library://asset/asset.JPG?id=C2FBB68D-2012-4696-8648-D8990F72BF77&ext=JPG', 'size': 125434, 'modificationTime': 1552019118.1320686, 'uri': null, 'isDirectory': 0, 'md5': '041550fe959f36d1b247bb6b2eaa3272', 'exists': 1 }, { 'file': 'assets-library://asset/asset.JPG?id=98EBA95A-254E-40F4-8E1D-C355D8795777&ext=JPG', 'size': 541148, 'modificationTime': 1552019117.7241733, 'uri': null, 'isDirectory': 0, 'md5': '39bf35dfcf0852c5412205195a395b29', 'exists': 1 } ] [Updated] I need to get the absolute file path from this url 'assets-library://asset/asset.JPG?id=98EBA95A-254E-40F4-8E1D-C355D8795777&ext=JPG' , which is similar to 'content://media/external/images/media/30988'. Please help me to resolve this issue.! Thanks in advance.! A: I had this exact same issue. The solution is to set the uri to the 'file' attribute. This is how you can append the image into formData correctly for both iOS and Android: let uri = image.file; // extract the filetype let fileType = uri.substring(uri.lastIndexOf(".") + 1); formData.append('uploads[]', { uri, name: `photo.${fileType}`, type: `image/${fileType}`, }); You can't remove the additional data on the iOS filename "?id=98EBA95A-254E-40F4-8E1D-C355D8795777&ext=JPG'" at this point, otherwise it won't upload. You can remove it at the server side though.
doc_23528448
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String database = "jdbc:odbc:Driver={MS Access Database (*.accdb)};DBQ=obn.accdb;"; c= DriverManager.getConnection(database, "", ""); s=c.createStatement(); string = "IN TRY"; s.close(); // Close the statement c.close(); // Close the database. Its no more required JOptionPane.showMessageDialog( null, string ); } catch(Exception e) { string = "IN exception"; JOptionPane.showMessageDialog( null, string ); } I have tried accessing a MS Access Database using Java using the above code always have an Exception. I have tried a few things c= DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=obn.mdb"); s=c.createStatement(); In the first one and the second i get exception - [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. ... Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); c= DriverManager.getConnection("jdbc:odbc:obn"); s=c.createStatement(); Tried doing this like this, adding OBN in ODBC Datasources(32-bit) in windows , selecting the path to the database. But it didnt work either. It gave the error The specified DSN contains an architecture mismatch between the Driver and Application I Normally dont use MS Access but i have to for a University Project A: Verify that you are using the correct ODBC driver name for your environment. You need to specify either... {Microsoft Access Driver (*.mdb)} ...or... {Microsoft Access Driver (*.mdb, *.accdb)} ...depending on whether you want to use the older "Jet" driver (only for .mdb files, available to 32-bit applications only) or the newer "ACE" driver (.mdb or .accdb files, can be used by 32- or 64-bit applications, may need to be installed separately if the machine does not already have Access on it). A: I found a solution. connecting using this is correct. c= DriverManager.getConnection("jdbc:odbc:obn"); The database has to be added under odbc in windows administrative tools. Since there is no 64 bit driver, 32 bit driver has to be used. Since 32 bit odbc driver is being used we cant use 64 bit JVM, so changing the JVM from 64 bit to 32 bit from the project manager does the trick , and now it works fine
doc_23528449
As I have search the code and found this may be possible by using following callback but I don't know how to use this in my code typedef void (*SCNetworkReachabilityCallBack) ( SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void * __nullable info ); can any one please help me to get network change callback with sample code ? A: This post may help you. As he said, Whenever there is a network change/network break or whenever network will flicker, the Reachability class will fire a ReachabilityChangedNotification which will ultimately call this user defined method checkForReachability. So, you can handle anything here. A: If you are using this Reachability files then its easy. Add an Observer inside the viewWillAppear [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityDidChange:) name:kReachabilityChangedNotification object:nil]; And implement the observer method - (void)reachabilityDidChange:(NSNotification *)notification { Reachability *reachability = (Reachability *)[notification object]; if ([reachability isReachable] && [reachability isReachableViaWiFi]) { NSLog(@"Reachable via Wifi"); } } Updated Add the following code inside the Network change completion block of your Reachability handler. By Sending the SCNetworkReachabilityFlag as a parameter to the method. -(BOOL)isReachableViaWiFi :(SCNetworkReachabilityFlags)flags { // Check we're reachable if((flags & kSCNetworkReachabilityFlagsReachable)) { // Check we're NOT on WWAN if((flags & kSCNetworkReachabilityFlagsIsWWAN)) { return NO; } return YES; } return NO; } A: Add observer :- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; -(void) checkNetworkStatus:(NSNotification *)notice { // called after network status changes NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; if(internetStatus == NotReachable) { } else if([internetReachable connectionRequired]) { } }
doc_23528450
How would I do it? A: Your best bet is to use an external library. libcurl is popular and fairly easy to use. Here's a simple example, you need to add error checking though: string data; CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url_.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWrite); curl_easy_perform(curl); Your callback would look something like this: size_t curlWrite(void *ptr, size_t size, size_t nmemb, void *usrPtr) { size_t bytes = size * nmemb; string *data = static_cast<string *>(usrPtr); data->append(static_cast<const char *>(ptr), bytes); return bytes; } You can add your GET parameters on the end of the URL.
doc_23528451
So I figure myself that I have to update Products.ResouceRegistries to 2.1.2. I have modified the versions.cfg and run buildout, but with no effect (no download of the new version). How could I update the version ? A: Why not just upgrade to Plone 4.2? A: The problem was there is a kgv in the buildout that pinned Products.ResouceRegistries to 2.0.6 : http://good-py.appspot.com/release/dexterity/1.2.1?plone=4.1.4 Removing the ?plone=4.1.4 and pin Products.ResouceRegistries to 2.1.2 make it works.
doc_23528452
I wanted to give the finished official app a test drive before continuing to better understand where I'm heading to, however I'm not sure how to do this (given the fact that I'm just beginning the book). I forked the "learn-rails" repo from the RailsApps GitHub account and cloned it into my Mac with the name "learn-rails-guide" (as "learn-rails" was already taken for following along). When tried to start the server, I got an error saying that I should run 'bundle install'. I did so, hoping that the gemset created during the following along won't get messed up; however 'bundle' wasn't able to install the 'pg' gem. And I hit a road block... Is this problem related to changing the name of the app? Does this have something to do with the finished app being set up for production? Am I taking the wrong approach for trying the finished app locally? Will an app with a .ruby-gemset and a .ruby-version files mess up my current gemsets if a run bundle install? Thanks! A: Use $ bundle install --without production (see the book's deploy chapter). Otherwise, you'll need to install PostgreSQL locally (which can be difficult). The repo version of the app is the final version that includes gems for deploying to Heroku. There will be no problem with changing the name of the folder that contains the app.
doc_23528453
Make sure that the following folders are writable by the server: * *_cache — this one’s a must *_logs — if you want to enable message logging *_content & _config/users — if you want to use the Control Panel I know this should is really basic, but I don't know anything about how to check the server's write permissions. I'm a front-end guy. Can anyone drill this down for me? Step one... do I need to use Terminal? A: I am not sure what OS you use, but I will assume it's a *nix based OS. First make sure the owner and group of the folders are the web servers user or a group the web server is part of. In some systems the Apache user is setup as www-data (Can be found in httpd.conf as User and Group). Something like this would do what you want: chown <user>.<group> <your folders> chmod 744 <your folder> Your really don't need the group in chown if you do not want to and using the example with www-data it would be: chmod www-data _logs Hope this helps. A: Contact your hosting provider if you don't know about server permissions. I use InMotion Hosting and they're freaking awesome, all the time. Live chat is the best. For me it was as simple as looking at the folders in my cPanel's File Manager. If I needed to change the permissions, I simply right-clicked it and checked / unchecked the appropriate boxes. http://www.inmotionhosting.com/support/website/how-to/change-file-permissions
doc_23528454
I'm getting an XML DateTime exception on my C# web app client when I call a web service that was auto-generated using Visual Studio web references. The error occurs at the web service client endpoint as the web reference proxy is formatting the XML response. Because of the type of error, I'm wondering if there is a .NET bug or incompatibility with converting certain Text formats to DateTimes formats. What's a good way to trace the cause of this error and to look at the XML response- I couldn't find a way in Visual Studio 2010 to examine the XML response from the Web Service. I appreciate the help I can get. message: at System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style) at System.DateTime.ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style) at System.Xml.Serialization.XmlSerializationReader.ToDate(String value) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderCONSULTA_CLIENTEBindingQSService.Read97_address(Boolean isNullable, Boolean checkType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderCONSULTA_CLIENTEBindingQSService.Read98_customerAddressList(Boolean isNullable, Boolean checkType) at i´m using SoapUI for tests and work´s for show xml response, but in visualstudio 2010 theres an error. examplo for two dates response in xml using SoapUI >>> 1985-04-18T00:00:00 27/02/2009 16:07:02 Note: i consuming webservice from client.Just consuming.. Thank´s
doc_23528455
(defmacro defendpoint [msg-type url-key schema] `(defrecord ~msg-type [] Create (create [entity#] (s/validate ~schema entity#) (create-entity (~url-key urls) entity#)))) and I'm using it like so (defendpoint Location :locations {... my schema ...}}) (defendpoint LocationHierarchy :location-hierarchies {... my schema ...}}) The first time I use the macro, it works (create (map->Location {... data ...})) => { ... json response ...} But the second time, it fails: (create (map->LocationHierarchy {... data ...})) => 1. Unhandled java.lang.IllegalArgumentException No implementation of method: :spec of protocol: #'schema.core/Schema found for class: ohds.client$fn__32303 I'm not sure why this is happening. I expect that the second call will work in the same way as the first, but it seems like there is an error in the validation step. In fact, if I remove (s/validate...) from the macro, it works as expected. So I'm not sure exactly what's going on here. I've created a gist that shows the entire file I'm working with A: I'm going to go through how I solved my problem in hopes that the method helps somebody else. tl;dr ;; Wrong: (def date-schema (s/both s/Str #(re-matches #"my-regex" %))) ;; Right: (def date-schema (s/both s/Str (s/pred #(re-matches #"my-regex" %)))) The Method I started with the error: No implementation of method: :spec of protocol: #'schema.core/Schema found for class: ohds.client$fn__32303 I wasn't sure what this meant at first. :spec of protocol: threw me off. But I did see it was mentioning schema.core/Schema, so I read the source code. I discovered Schema was a protocol with a method spec, just like the error says :/ The next part that was confusing was for class: ohds.client$fn__32303. I was wondering why my namespace needed to implement the protocol. That didn't make any sense. Then I noticed $fn_32303. This told me there was a lambda somewhere where the mistake was! At this point, it was my hypothesis that my schema had a problem. So I removed all the special validation from my schema and used s/Str everywhere to see if it worked. It did, so I was in the right spot! I added the special validation back, one at a time, until the test failed again. The problem was in my date-schema. I looked at the schema I defined just above it to see what was different. There I noticed I'd failed to to wrap my lambda in s/pred. The Moral Clojure is well designed, so the error message is telling you exactly what's wrong. You just need to understand it. A: Just had this happen to me. Turned out i had a defschema that was referencing itself: (s/defschema Templates {:templates [Templates] :error s/Bool}) instead of the correct reference: (s/defschema Templates {:templates [Template] :error s/Bool})
doc_23528456
(define context-interface<%> (interface () [entity-list (->m (listof (is-a?/c entity-interface<%>)))] ) ) (define entity-interface<%> (interface () [on-add (->m (is-a?/c context-interface<%>) void?)] ) what should I do to avoid cannot reference an identifier before its definition error? I haven't found anything like forward declaration in C++ meaning in Racket docs. From the answer for my previous question I know that it is possible to somehow solve issue using lazy-require, but what if I want to keep both definitions in same source file? A: You can fix this kind of "value not initialized" error in recursive contracts by adding recursive-contract around a part of the contract, to delay that part's evaluation until it's needed. In this case, you can add recursive-contract around (is-a?/c entity-interface<%>). (define context-interface<%> (interface () [entity-list (->m (listof (recursive-contract (is-a?/c entity-interface<%>))))] )) (define entity-interface<%> (interface () [on-add (->m (is-a?/c context-interface<%>) void?)] )) Note that it can be around (is-a?/c entity-interface<%>) because that's a contract value, but it cannot be around just entity-interface<%> because that's a racket/class interface value and not a contract.
doc_23528457
I'm getting lost in this expression, any help is appreciated. =SWITCH ( (InStr(Fields!Info.Value, CHR(13)&CHR(10) > 0, REPLACE(Fields!Info.Value, CHR(13)&CHR(10)), "\x0D\x0A")), (InStr(Fields!Info.Value, CHR(13) > 0, REPLACE(Fields!Info.Value, CHR(13)), "\x0D")), (InStr(Fields!Info.Value, CHR(10) > 0, REPLACE(Fields!Info.Value, CHR(10)), "\x0A")) ) Error is: System.Web.Services.Protocols.SoapException: The Value expression for the textrun ‘Info.Paragraphs[0].TextRuns[0]’ contains an error: [BC30455] Argument not specified for parameter 'Replacement' of 'Public Function Replace(Expression As String, Find As String, Replacement As String, [Start As Integer = 1], [Count As Integer = -1], [Compare As Microsoft.VisualBasic.CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary]) As String'. at Microsoft.ReportingServices.Library.ReportingService2005Impl.SetReportDefinition(String Report, Byte[] Definition, Guid batchId, Warning[]& Warnings) at Microsoft.ReportingServices.Library.ReportingService2010Impl.SetItemDefinition(String ItemPath, Byte[] Definition, String expectedItemTypeName, Property[] Properties, Warning[]& Warnings) at Microsoft.ReportingServices.WebServer.ReportingService2010.SetItemDefinition(String ItemPath, Byte[] Definition, Property[] Properties, Warning[]& Warnings) A: Try this: =SWITCH( InStr(Fields!Info.Value, CHR(13) & CHR(10)) > 0, REPLACE(Fields!Info.Value,CHR(13) & CHR(10), "\x0D\x0A"), InStr(Fields!Info.Value,CHR(13)) > 0, REPLACE(Fields!Info.Value, CHR(13), "\x0D"), InStr(Fields!Info.Value, CHR(10)) > 0, REPLACE(Fields!Info.Value, CHR(10), "\x0A") ) Note if you use Switch function it will execute only the first case that is true, so if the first condition is true the second and the third will not be evaluated therefore not executed. If you want to replace every char you should just use multiple REPLACE nested functions. =Replace( Replace( REPLACE(Fields!Info.Value,CHR(13) & CHR(10), "\x0D\x0A"), CHR(13),"\x0D"), CHR(10),"\x0A")
doc_23528458
A: That means a hyperlink (a) or link that was dynamically created and inserted into the page by JavaScript, as opposed to a link that was in the original HTML. A: I imagine it's like this: <a id="linkId" href="here" display="none"> <script> document.getElementById("linkId").href = "there"; document.getElementById("linkId").display= "block"; </script> Or, actually creating the node in the DOM later, like Jacob said, like this: function insertcode() { var code ="<a id="new_link" href="there">link text</a>" var myText = document.createTextNode(code); document.getElementById("content").appendChild(myText); } I hope this helps.
doc_23528459
My question is simply, what am I looking at here? Should I be concerned about modifying it. Is there a resource that covers this that my google-fu has missed? <?php namespace App; use Illuminate\Database\Eloquent\Model; /** * App\FitOption * * @property int $id * @property string $option_type * @property string $option_name * @property float $option_price * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption newQuery() * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption query() * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereOptionName($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereOptionPrice($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereOptionType($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\FitOption whereUpdatedAt($value) * @mixin \Eloquent */ class FitOption extends Model { // } A: Turns out I was looking at PhpDoc comments and I need not have worried about them.
doc_23528460
@Component("assembler") public class DefaultAssemblerStrategy implements AssemblerStrategy//, ServletContextAware { @Autowired//(required=false) private ServletContext servletCtxt; public void setServletContext(ServletContext servletContext) { System.out.println("~~~~~~~~~~~~setServletContext"); servletCtxt = servletContext; } Note this is on the actual web server not during a JUnit test case run. If I try the Autowired I get this error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assembler': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.servlet.ServletContext com.ibm.retail.xc.maestro.web.theme.impl.DefaultAssemblerStrategy.servletCtxt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1073) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455) And if I implement the ServletContextAware it is just null... A: It sounds like you're not using ContextLoaderListener. ServletContextAware relies on a BeanFactoryPostProcessor that is set up by AbstractRefreshableWebApplicationContext inside refresh(). The context relies on ContextLoader to inject the ServletContext into it. Therefore you can resolve this issue by using ContextLoaderListener in your application, or (probably more simply) calling AbstractRefreshableWebApplicationContext#setServletContext() before the context is refreshed. Defining a ServletContext bean might also work, but conceptually the servlet context is "outside" the Spring context--really it's the servlet context that is managing the Spring context, not vice versa. Happily this approach is completely unnecessary. A: madth3 has indicated a possible reason: namely that a bean is defined with the name applicationContext. This makes sense e.g. for testing with a MockApplicationContext, but not in the application itself.
doc_23528461
Before the upgrade the Podfile on my library contained pod 'Crashlytics' and the Podspec spec.dependency "Crashlytics" After the upgrade the line in the Podfile was replaced with pod 'Firebase/Crashlytics' and in the Podspec with spec.dependency "Firebase/Crashlytics" Compiling the library project itself works, however when using it as a Cocoapods library from another project I get No such module 'Firebase' on import Firebase in the library code. Looking at what Cocoapods creates in the project importing my library I see that the library has Firebase-CoreOnly-Crashlytics as a dependency which in turns has FirebaseCore and FirebaseCrashlytics as dependencies. This is in line with what I would expect yet it doesn't compile. A: Found this workaround: s.xcconfig = { 'SWIFT_INCLUDE_PATHS' => '$(PODS_ROOT)/Firebase/CoreOnly/Sources' } A: this is my App settings hope help you to solve this issue 1- the first thing i did is to update the podfile from pod 'Firebase/Crash' to pod 'Firebase/Crashlytics' 2 update the debug symbolopen click here add the code run crashlytics run code click here 3 - clean your build 4 - rerun your code
doc_23528462
for i=0 to #columns for j=0 to #rows sum=sum+matrix[i,j] for j=0to #rows matrix[i,j]=matrix[i,j]/sum All of the iterators I've seen in examples iterate over the entire matrix at once instead of doing it per column. Is there a way to do what I'm trying to do? A: Scipy sparse matrices have their own sum method you can use for this. For example: A=sp.lil_matrix((5,5)) b=1+np.arange(0,5) A.setdiag(b[:-1],k=1) A.setdiag(b) print(A) (0, 0) 1.0 (0, 1) 1.0 (1, 1) 2.0 (1, 2) 2.0 (2, 2) 3.0 (2, 3) 3.0 (3, 3) 4.0 (3, 4) 4.0 (4, 4) 5.0 f=A.sum(axis=0) print(f) [[1. 3. 5. 7. 9.]] The returned sum is a dense numpy.matrix which you can convert into scaling factors: print(A/f) [[1. 0.33333333 0. 0. 0. ] [0. 0.66666667 0.4 0. 0. ] [0. 0. 0.6 0.42857143 0. ] [0. 0. 0. 0.57142857 0.44444444] [0. 0. 0. 0. 0.55555556]]
doc_23528463
Task :app:compileReleaseJavaWithJavac FAILED /Users/runner/work/1/s/android/app/src/main/java/com/app/MainActivity.java:24: error: class, interface, or enum expected protected ReactActivityDelegate createReactActivityDelegate() { ^ /Users/runner/work/1/s/android/app/src/main/java/com/app/MainActivity.java:26: error: class, interface, or enum expected } ^ /Users/runner/work/1/s/android/app/src/main/java/com/app/MainActivity.java:48: error: class, interface, or enum expected } ^ 3 errors This is my MainActivity.java file content. package com.app; import com.bugsnag.android.Bugsnag; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.soloader.SoLoader; import com.facilt.newarchitecture.MainApplicationReactNativeHost; import com.microsoft.codepush.react.CodePush; import com.facebook.react.bridge.JSIModulePackage; // <- add import com.swmansion.reanimated.ReanimatedJSIModulePackage; // <- add import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } @Override protected JSIModulePackage getJSIModulePackage() { return new ReanimatedJSIModulePackage(); // <- add } } private final ReactNativeHost mNewArchitectureNativeHost = new MainApplicationReactNativeHost(this); @Override public ReactNativeHost getReactNativeHost() { if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { return mNewArchitectureNativeHost; } else { return mReactNativeHost; } } @Override public void onCreate() { super.onCreate(); // If you opted-in for the New Architecture, we enable the TurboModule system ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; Bugsnag.start(this); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class<?> aClass = Class.forName("com.facilt.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
doc_23528464
but when I run brew doctor and brew install libmpc, it's always saying Error: Cannot write to /usr/local/Cellar. I thought I have no write permission, and I've run sudo chown -R $USER /usr/local but it does not work. How can I install libmpc? A: My personal recommendation is to run the Pebble SDK on a Virtual Machine running Ubuntu. I tried getting it installed on Mac OS, and all steps appeared to go as they should, but things were never working right, even after a fair amount of troubleshooting (and I am an experienced Unix/Linux admin). Plus, it did some funny things to some of the custom Unix stuff I had in Mac OS. I installed a VM with Ubuntu and had it up and running quickly and without any complications. VirtualBox (http://virtualbox.org) is free and works well. You can use Eclipse (and many others) for editing code. And most importantly, you don't run any risk of messing anything up on your Mac OS system while fudging around with the Unix system on your Mac OS install. Ubuntu is probably the easiest of the *nixes for non-*nix users, so you shouldn't fear the requirement of having to learn how to use Linux. Ubuntu and VirtualBox will take care of most of the difficult stuff for you, and what you can't figure out by virtue of the fact that you are knowledgeable enough about computers to be programming, you will learn from Pebble's instructions and quick Google searches. There are some additional advantages, such as having your development machine be able to act as the web server from which your test app builds are installed, but you'll figure those out as you go along. A: I installed the SDK by using Pebble's guide from their site. https://developer.getpebble.com/2/getting-started/. A: I also had issues when installing on OSX Mavericks. I posted my solution here.
doc_23528465
We have a .net application that sends a json formatter string message into a bus. The message is retrieved successfully in this format "2014-04-07T15:20:40.7439627Z", as you can see the length of millisecond segment is 7 characters (normally we have 3). The problem is using ObjectMapper from jackson library, the parsing / conversion failed. The example above generated: Mon Apr 07 19:24:39 CEST 2014. Also we are sure that it's not a timezone issue because when we use a millisecond value with only 3 characters, it worked. Unfortunately, I cannot change the format from the source so I'm stuck. Any suggestions? Thanks. A: I was able to get around this problem by first transforming XmlGregorianCalendar to a Date object using a jaxb binding and by using a custom serializer for the objectMapper module from jackson library. I've explained my solution here: http://czetsuya-tech.blogspot.fr/2014/04/create-custom-json-string-deserializer.html
doc_23528466
if it's not a success response, jest will throw an error that I don't want. I wanna first check if the properties are already there. I know, I can acquire this by lodash (_.get). But I wanna know is it possible with jest without using other libs. A: The expectation you need is .toHaveProperty(): expect(res).toHaveProperty('body.result.verificationToken'); Alternatively you can pass the names of the properties as an array: expect(res).toHaveProperty(['body', 'result', 'verificationToken']); The second format is more intuitive when arrays are involved in the path but the first format can be used as well, using numbers (the indices) as properties. A: It's possible to avoid this error with null-coalescing (elvis) operator: res.body.result?.verificationToken But the assertion will still fail because the result is undefined. This addresses the wrong problem. Expectations in tests should preferably be as precise as possible. If it's unknown that a response is successful, there are problems with testing conditions. Instead, it can be: // in a test where failed response is expected expect(res.body.result).not.toBeDefined() // in a test where success response is expected expect(res.body.result.verificationToken).toBeDefined()
doc_23528467
$line = mysql_fetch_array($result, MYSQL_ASSOC); When I do this, I can see the results of the query printed: foreach ($line as $data) { echo ($data . ", "); } But if I do this instead: echo ($line[0] . " " . $line[1] . " " . $line[2]); I don't see anything. Also I can't assign a value from $line: $values[] = $line[0]; // fails - doesn't assign anything Why? And what should I be doing instead? A: You've nominated to retrieve records as associative entries only (MYSQL_ASSOC). This means your $line array will not contain numeric indices. If you only want numeric arrays, use mysql_fetch_row(). Associative only, mysql_fetch_assoc() You can also retrieve a mixed numeric and associative array using mysql_fetch_array($result, MYSQL_BOTH) however this will give you duplicate entries in your foreach loop. A: You told MySQL that you want to fetch the row as an array, which means $line is not a 0-index array, it's an associative array, which means the keys of the array are the column names of the table(s) you selected from. var_dump($line); // Will display the keys A: try: echo ($line["id"] . " " . $line["id"] . " " . $line["id"]); so instead of using a index number like [0] you use the corresponding column-name
doc_23528468
Since we must communicate via serialUSB with an external device, it became a little fuzzy after we noticed that leaving the tablet powering the bus (Host Mode) drains it`s battery till death. Moreover, we still must supply enough energy to power the tablet. After a lot of attempted fails, such as using a OTG-Y cable, modifying Kernel Battery Config and using a USB Hub, I need to discover a way to perform the communication and keep the tablet charging. Thought about using the HDMI or even the audio/serial. Is there any solution I can look forward to solve this? At this point, I'm getting out of ideas. A: You can use an arduino, but not a normal one, you'll need a mega, i say this because the ardiono mega is the only arduino i know of with more than one serial UART. The Uno for example shares the RX/TX serial pins with the same UART as the USB interface. If you DO have a mega, you can get a cheap USB to Serial module such as this: http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=arduino+usb+to+serial&_sop=15 Now, you plug your PC into the mega's normal USB This will power the Mega from your PC. Then you connect your tablet to the serial module. All that's left to do is create a simple ino script for your mega to transfer data from serial (pc-USB) to serial2 (Tablet), and vice versa.. Example: void setup() { // put your setup code here, to run once: Serial.begin(115200); // PC <--> USB Serial1.begin(115200); // Serial <--> Tablet } void loop() { // put your main code here, to run repeatedly: serialComs(); // Tells loop to execute the serialComs() function } // Serial Comunication function void serialComs() { // read from port 1 (Tablet), send to port 0 (PC): if (Serial1.available()) { int inByte = Serial1.read(); Serial.write(inByte); } // read from port 0 (PC), send to port 1 (Tablet): if (Serial.available()) { int inByte = Serial.read(); Serial1.write(inByte); } } NOTE: You may need to add #DEFINE entries before void setup to define which pins are which on your serial to USB module. A: I think your way througt the HDMI will not work. And you have only one other option: You could also load your battery directly. You could open the case and power your tabled instead your battery. This should also work. I think ther is no other way. Also you could try a OTG hub: http://www.miniinthebox.com/de/3-in-1-micro-usb-otg-host-adapter-kabel-hub-fuer-samsung-smartphone-tablet-n9000_p1996674.html?currency=EUR&litb_from=paid_adwords_shopping&litb_from=&adword_mt=&adword_ct=73333307802&adword_kw=&adword_pos=1o1&adword_pl=&adword_net=g&adword_tar=&adw_src_id=4196617767_313342362_22461529362_kwd-140182704282&gclid=CJqW-Na8zMcCFc8aGwodznEIZA But not all tables allow charging and using USB at the same time.
doc_23528469
function getRoster(con){ var roster = new JSJaCIQ(); roster.setIQ(null, 'get', 'roster_1'); roster.setQuery(NS_ROSTER); con.send(roster); } A: Instead of con.send, try: con.sendIQ(roster, {result_handler: function(aIq, arg) { var node = aIq.getQuery() // do something with roster }); You need to have a callback that fires when the roster is returned. To be complete, set a error_handler as well, in case an IQ error is returned or you time out. A: sorry for commenting on such old question, hoewever this pops as #1 result in google on 'JSJAC roster' and the above answers didn't worked for me. i don't know whether something changed in the JSJaC API, however i was receiving iq errors 'service-unavaliable'. i had to use this code instead: var rosterRequest = new JSJaCIQ(); rosterRequest.setType('get'); rosterRequest.setQuery(NS_ROSTER); connection.send(rosterRequest); (so no domain setting and no id setting - just the type, and namespace).
doc_23528470
Here as sample of my code fname = input('Enter filename...') fileObject = open(fname, 'r') print(fname) A: Yes, you need to read the data from the file and then print it out, or do everything at once: fname = input("What's the file name? ") # this assumes it's on the same directory with open(fname, 'r') as file: print(file.read()) A: You can try this: (read the official Python doc. too) with open(filename) as f: content = f.read() # you may also want to remove whitespace characters like `\n` at the end of each line print(content)
doc_23528471
choice = input("enter v for validate, or enter g for generate").lower() try: choice == "v" and "g" except TypeError: print("Not a valid choice! Try again") restartCode() *#pre-defined function, d/w about this* So I would like my program to output that print statement and do that defined function when the user inputs something other than "v" or "g" (not including when they enter capitalised versions of those characters). There is something wrong with my try and except function, but whenever the user inputs something other than those 2 characters the code just ends. A: Try. choice = input("enter v for validate, or enter g for generate").lower() if (choice == "v") or (choice == "g"): #do something else : print("Not a valid choice! Try again") restartCode() #pre-defined function, d/w about this* However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError. choice = input("enter v for validate, or enter g for generate").lower() valid_choices = {'v':1, 'g':1} try: valid_choices[choice] #do something except: KeyError print("Not a valid choice! Try again") restartCode() #pre-defined function, d/w about this A: You are confused about what try/except does. try/except is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to be. You, however, want an error to be shown if the user does not enter a valid choice. You need to use an if/else logic instead, and print the error out yourself. And as a side note, the line choice == "v" and "g" does not test if choice is equal to 'v' or 'g'. It test if choice i equal to v and if the string 'g' is "truthy". Your estenially saying if variable = value and True I'm pretty sure that is not what you want. Here is how I would re-write your code. if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g' # do stuff else: # otherwise print("Not a valid choice! Try again") # print a custom error message. A: The problem is not in your try and except but in the fact that you are using try and except at all. The code in your try block won't give you an error so except will never be triggered. You want to use an if statement. Also, your condition only checks for choice == "v" because it is evaluated as (choice == "v") and "g", and "g" is a string not of length 0, so is always "truthy" (taken as true in a Boolean context). Anything and True is unchanged, so only the first test has any meaning. The best way to do this test is with in. Finally, you can and should use a while loop to repeat the prompt until the user enters a valid entry. Putting it all together, you want something like this: prompt = "Enter v for validate, or g for generate >" choice = input(prompt).strip().lower()[:1] # take at most 1 character while choice not in ("v", "g"): print("Not a valid choice! Try again.") choice = input(prompt).strip().lower()[:1] If you think of how you might generalize the code to use it again (as you probably will in the rest of your script), it's easy and useful to do so. First, you can break out the input stuff into a separate function, since it's called twice: def input1char(prompt): return input(prompt + " >").strip().lower()[:1] And then break out the while loop into its own function too: def validinput(prompt, options): letters = tuple(options) choice = input1char(prompt) while choice not in options: print("'%s' is not a valid choice! Try again." % choice) choice = input1char(prompt) return choice And then you just write: choice = validinput("Enter v for validate, or g for generate", "vg")
doc_23528472
These variations generally are not speling erors. The most common errors are missing punctuation or citation elements. Question: is there some effective table driven method to do close matches? A possible variation on LEX? Or maybe a LEX programming technique (like error in YACC). A: Resurrecting this question because I see no one answered you. With usual regex engine: no As you've probably found out, with most engines, regex is not the best tool for doing close matches or arbitrary words or phrases. Sure, at the most basic level, something like \bs?he\b will find either he or she... But to find all close matches in a word such as interactive, you'd have to generate a regex that introduces a number of permutations in the word... Neither efficient nor effective. One exception The one exception I know of is Matthew Burnett's [regex][1] module for Python. To start with, it's a terrific engine, one of the only two that I know (with .NET) that supports infinite-width lookbehinds. (JGSoft supports it too, but it's not tied to a language.) This engine has a fuzzymatch mode that might just do what you want. You can provide a "cost equation" (max number of substitutions and so on). You'd have to hook up Python to your data... There might be a module available for that. Here's an excerpt from the doc. Regex usually attempts an exact match, but sometimes an approximate, or "fuzzy", match is needed, for those cases where the text being searched may contain errors in the form of inserted, deleted or substituted characters. A fuzzy regex specifies which types of errors are permitted, and, optionally, either the minimum and maximum or only the maximum permitted number of each type. (You cannot specify only a minimum.) The 3 types of error are: Insertion, indicated by "i" Deletion, indicated by "d" Substitution, indicated by "s" In addition, "e" indicates any type of error. The fuzziness of a regex item is specified between "{" and "}" after the item. Examples: foo match "foo" exactly (?:foo){i} match "foo", permitting insertions (?:foo){d} match "foo", permitting deletions (?:foo){s} match "foo", permitting substitutions (?:foo){i,s} match "foo", permitting insertions and substitutions (?:foo){e} match "foo", permitting errors If a certain type of error is specified, then any type not specified will not be permitted. In the following examples I'll omit the item and write only the fuzziness. {i<=3} permit at most 3 insertions, but no other types {d<=3} permit at most 3 deletions, but no other types {s<=3} permit at most 3 substitutions, but no other types {i<=1,s<=2} permit at most 1 insertion and at most 2 substitutions, but no deletions {e<=3} permit at most 3 errors {1<=e<=3} permit at least 1 and at most 3 errors {i<=2,d<=2,e<=3} permit at most 2 insertions, at most 2 deletions, at most 3 errors in total, but no substitutions It's also possible to state the costs of each type of error and the maximum permitted total cost. Examples: {2i+2d+1s<=4} each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 {i<=1,d<=1,s<=1,2i+2d+1s<=4} at most 1 insertion, at most 1 deletion, at most 1 substitution; each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 You can also use "<" instead of "<=" if you want an exclusive minimum or maximum: {e<=3} permit up to 3 errors {e<4} permit fewer than 4 errors {0 By default, fuzzy matching searches for the first match that meets the given constraints. The ENHANCEMATCH flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found. The BESTMATCH flag will make it search for the best match instead. Further examples to note: regex.search("(dog){e}", "cat and dog")1 returns "cat" because that matches "dog" with 3 errors, which is within the limit (an unlimited number of errors is permitted). regex.search("(dog){e<=1}", "cat and dog")1 returns " dog" (with a leading space) because that matches "dog" with 1 error, which is within the limit (1 error is permitted). regex.search("(?e)(dog){e<=1}", "cat and dog")1 returns "dog" (without a leading space) because the fuzzy search matches " dog" with 1 error, which is within the limit (1 error is permitted), and the (?e) then makes it attempt a better fit. In the first two examples there are perfect matches later in the string, but in neither case is it the first possible match. The match object has an attribute fuzzy_counts which gives the total number of substitutions, insertions and deletions. A 'raw' fuzzy match: regex.fullmatch(r"(?:cats|cat){e<=1}", "cat").fuzzy_counts (0, 0, 1) 0 substitutions, 0 insertions, 1 deletion. A better match might be possible if the ENHANCEMATCH flag used: regex.fullmatch(r"(?e)(?:cats|cat){e<=1}", "cat").fuzzy_counts (0, 0, 0) 0 substitutions, 0 insertions, 0 deletions.
doc_23528473
.here my api const createPatient = (req, res, next) => { const patient = new Patient(); name = req.body.name; email = req.body.email; hashed_password = req.body.hashed_password; ID = req.body.ID; address = req.body.address; KK_number = req.body.KK_number; occupation = req.body.occupation; photo = req.body.photo; patient.save( (err, result) => { if (err) { return res.status(400).json({ error: err, }); } console.log(patient); res.status(200).json({ message: 'Successfully signed up!', }); console.log(result); }); }; anyone know whats wrong with my code? A: The problem with your code is that you are not creating the patient object. While you are creating variables to hold the patient details, you are not adding them to the patient object. This should work. const createPatient = (req, res, next) => { const patient = new Patient({ name : req.body.name; email : req.body.email; hashed_password : req.body.hashed_password; ID : req.body.ID; address : req.body.address; KK_number : req.body.KK_number; occupation : req.body.occupation; photo : req.body.photo; }); patient.save( (err, result) => { if (err) { return res.status(400).json({ error: err, }); } console.log(patient); res.status(200).json({ message: 'Successfully signed up!', }); console.log(result); }); };
doc_23528474
<?xml version="1.0" encoding="UTF-8"?> <root> <issue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <comment text="&lt;div class=&quot;wiki text&quot;&gt;&lt;h4&gt;Tom Fenech&lt;/h4&gt;Here is a comment&lt;/div&gt;&#10;"/> </issue> </root> As you can see, the text attribute in the comment node contains escaped HTML. I would like to get the contents of the attribute as XHTML, which I currently do this inside a template using: <xsl:value-of select="@text" disable-output-escaping="yes" /> That gets me the HTML in the final output: <div class="wiki text"><h4>Tom Fenech</h4>Here is a comment</div> But I want to be able to extract the contents of the <h4> tag to use elsewhere. In general, it would be nice to be able to manipulate the contents of this once it has been escaped. How do I apply further templates to the output of the <xsl:value-of />? I am currently using the PHP built-in XSLT processor, which supports XSLT version 1.0, although I would be willing to consider using an alternative processor if features from newer versions make this possible. A: You cannot apply templates to unparsed (escaped or CDATA) text. See some previous answers that may be relevant to you: Parsing html with xslt XSLT: Reading a param that's an xml document passed as a string how to parse the xml inside CDATA of another xml using xslt? A: Here's one way you could do it, by calling into a PHP function from XSLT: function parseHTMLString($html) { $doc = new DOMDocument(); $doc->loadHTML($html); return $doc; } $xml = <<<EOB <root> <issue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <comment text="&lt;div class=&quot;wiki text&quot;&gt;&lt;h4&gt;Tom Fenech&lt;/h4&gt;Here is a comment&lt;/div&gt;&#10;"/> </issue> </root> EOB; $xsl = <<<EOB <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xsl:extension-element-prefixes="php"> <xsl:output method="html" encoding="utf-8" indent="yes"/> <xsl:template match="comment"> <xsl:apply-templates select="php:functionString('parseHTMLString', @text)//div/h4"/> </xsl:template> <xsl:template match="div/h4"> <h2><xsl:apply-templates/></h2> </xsl:template> </xsl:stylesheet> EOB; $xmldoc = new DOMDocument(); $xmldoc->loadXML($xml); $xsldoc = new DOMDocument(); $xsldoc->loadXML($xsl); $proc = new XSLTProcessor(); $proc->registerPHPFunctions('parseHTMLString'); $proc->importStyleSheet($xsldoc); echo $proc->transformToXML($xmldoc);
doc_23528475
The logic is I have a column in DB with numeric values called 'time', I want to sum all of them together, and output the result next to /10000 in my view. I believe I need to use row() but I am not sure how. Controller: $this->load->library(array('form_validation', 'session')); $this->db->select_sum('time'); $data['num'] = $this->db->get('posts'); $this->db->order_by('id', 'DESC'); $data['query'] = $this->db->get('posts'); $this->load->view('templates/header'); $this->load->view('templates/navigation'); $this->load->view('home_page', $data); $this->load->view('templates/footer'); View: <?php foreach ($num->result() as $row): ?> <?php if (empty($row->time)): echo "0"?> <?php else: echo $row->time ?> <?php endif ?>/10000</p> <?php endforeach;?> A: You can combine row() with the variable. $sql = $this->db->select_sum('time'); $sql = $this->db->get('posts'); $data['num'] = $sql->row(); And you can call in your view $num->time; hope this solve your problem.
doc_23528476
I'm aware that I can encode a vector with vector() if the size field is directly in front of the vector data. But here the field encoding the vector size is not adjacent. case class Item( address: Int, size: Int, ) case class Header { // lots of other fields before numOfItems: Int, // lots of other fields after } case class Outer( hdr: Header, items: Vector[] ) Decoding of Outer is OK: Header.numOfItems is read from the bit vector and items is created with vectorOfN(provide(hdr.numOfItems, Item.codec)) Encoding of Outer is the problem: When encoding I would like to have numOfItem be taken from the items.length. I'm aware that I could set numOfItems with additional code when the items Vector is updated or with something like a "before encoding callback". The question is if there is a more elegant solution. To me Header.numOfItems is redundant with Outer.items.length, so ideally only the Encoder should know about numOfItems. A: You could try building a Codec using consume() and start without building the Outer object: case class OuterExpanded( fieldBefore: Int, // Field before number of items in the binary encoding fieldAdter: Int, // Field after number of items in the binary encoding items: Vector[Item] // Encoded items ) // Single Item codec def itemC: Codec[Item] = (int32 :: int32).as[Item] def outerExpandedC: Codec[OuterExpanded] = ( int32 :: // Field before count int32.consume( c => // Item count int32 :: // Field after count vectorOfN(provide(c), itemC)) // 'consume' (use and forget) the count (_.tail.head.length) // provide the length when encoding ).as[OuterExpanded] As defined above, you get the following when encoding: outerExpandedC.encode(OuterExpanded(-1, -1, Vector(Item(1,2), Item(3,4)))) returns Successful(BitVector(224 bits, 0xffffffff00000002fffffffe00000001000000020000000300000004)) ^ ^ ^ ^-------^-> First Item |-1 | |-2 |Vector length inserted between the two header fields Afterwards, you can xmap() the Codec[OuterExpanded] to pack the other header fields together into their own object. Ie (adding two conversion methods to Outer and OuterExpanded): def outerC: Codec[Outer] = outerExpandedC.xmap(_.toOuter,_.expand) case class OuterExpanded(fieldBefore: Int, fieldAfter: Int, items: Vector[Item]) { def toOuter = Outer(Hdr(fieldBefore,fieldAfter), items) } case class Outer(header: Hdr, items: Vector[Item]) { def expand = OuterExpanded(header.beforeField1, header.beforeField1, items) } This can probably be adapted to more complex cases, though I'm not entirely familar with shapeless' heterogeneous lists – or HList – and there might be nicer ways to get to the length of the vector rather than calling _.tail.head.length in the example above, especially if you end up with more than one field after the number of encoded values. Also, the Codec scaladoc is a nice place to discover useful operators A: Based on the previous answer I came up with something like the code below. I used the consume trick form above and an AtomicInteger to hold the size of the vector. import java.util.concurrent.atomic.AtomicInteger import scala.Vector import org.scalatest._ import scodec._ import scodec.Attempt._ import scodec.codecs._ import scodec.bits._ object SomeStructure { case class Item( address: Int, size: Int) def itemC: Codec[Item] = (int32 :: int32).as[Item] case class Hdr( beforeField1: Int, // vectorSize would be here afterField1: Int) // vectorSize is an "in" param when encoding and an "out" param when decoding def hdrC(vectorSize: AtomicInteger): Codec[Hdr] = (int32 :: int32.consume(c => { vectorSize.set(c); int32 })((i) => vectorSize.get)).as[Hdr] case class Outer( hdr: Hdr, var items: Vector[Item]) def outerC() = { // when decoding the length is in this atomic integer // when encoding it is set before val c = new AtomicInteger(-1) (hdrC(c) :: lazily(vectorOfN(provide(c.get), itemC))) .xmapc(identity)((g) => { c.set(g.tail.head.length); g }) }.as[Outer] } import SomeStructure._ class SomeStructureSpec extends FlatSpec with Matchers { val bv = hex"ffffffff00000002ffffffff00000001000000020000000300000004".bits val v = Vector(Item(1, 2), Item(3, 4)) val bv2 = hex"ffffffff00000003ffffffff000000010000000200000003000000040000000500000006".bits val v2 = Vector(Item(1, 2), Item(3, 4), Item(5, 6)) val o = Outer(Hdr(-1, -1), v) "outerC" should "encode" in { o.items = v outerC.encode(o) shouldBe Successful(bv) o.items = v2 outerC.encode(o) shouldBe Successful(bv2) } it should "decode" in { o.items = v outerC.decode(bv) shouldBe Successful(DecodeResult(o, BitVector.empty)) o.items = v2 outerC.decode(bv2) shouldBe Successful(DecodeResult(o, BitVector.empty)) } }
doc_23528477
A trivial programmatic example, to supplement that description: #include <stdio.h> int adder(int *a, int *b) { return *a + *b; } int main() { auto int a = 5; // `auto' is redundant; included for clarity auto int b = 3; // adder() gets the addresses of two auto variables! is this an issue? int result = adder(&a, &b); printf("5 + 3 = %d\n", result); return 0; } This program works as expected, printing 5 + 3 = 8. Usually, when I have questions about C, I turn to the standard, and this was no exception. Specifically, I checked ISO/IEC 9899, §6.2.4. It says there, in part: 4 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration. 5 For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached. Reading this, I reason the following points: * *Variables a and b have storage duration auto, which I've made explicit using the auto keyword. *Calling the adder() function corresponds to the parenthetical in clause 5, in the partial quote above. That is, entering the adder() function "suspends, but does not end," the execution of the current block (which is main()). *Since the main() block is not "end[ed] in any way," storage for a and b is guaranteed. Thus, accessing them using the addresses &a and &b, even inside adder(), should be safe. My question, then, is: am I correct in this? Or am I just getting "lucky," and accessing memory locations that, by happenstance, have not been overwritten? P.S. I was unable to find an exact answer to this question through either Google or SO's search. If you can, mark this as a duplicate and I'll delete it. A: Yes, it is safe and basically your assumptions are correct. The lifetime of an automatic object is from the entry in the block where it has been declared until the block terminates. (C99, 6.2.4p5) "For such an object [...] its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. A: Your reasoning is correct for your particular function call chain, and you have read and quoted the relevant portions of the standard. This is a perfectly valid use of pointers to local variables. Where you have to be wary is if the function stores the pointer values in a structure that has a lifetime longer than its own call. Consider two functions, foo(), and bar(): int *g_ptr; void bar (int *p) { g_ptr = p; } void foo () { int x = 10; bar(&x); } int main () { foo (); /* ...do something with g_ptr? */ return 0; } In this case, the variable xs lifetime ends with foo() returns. However, the pointer to x has been stored in g_ptr by bar(). In this case, it was an error for foo() to pass a pointer to its local variable x to bar(). What this means is that in order to know whether or not it is valid to pass a pointer to a local variable to a function, you have to know what that function will do with it. A: Those variables are allocated in the stack. As long as you do not return from the function that declared them, they remain valid. A: As I'm not yet allowed to comment, I'd rather write another answer as amendment to jxh's answer above: Please see my elaborate answer here for a similar question. This contains a real world example where the aliasing in the called function makes your code break even though it follows all the c-language rules. Even though it is legal in the C-language I consider it as harmful to pass pointers to automatic variables in a function call. You never know (and often you don't want to know) what exactly the called function does with the passed values. When the called function establishes an alias, you get in big trouble.
doc_23528478
"scripts": { "webdriver-update": "./node_modules/.bin/webdriver-manager update", "webdriver-start": "./node_modules/.bin/webdriver-manager start --versions.chrome=84.0.4147.30", "protractor": "./node_modules/.bin/protractor configuration.js", "start": "npm run webdriver-update &&npm run webdriver-start" } If I open 2 command prompts & run npm run start & npm run protractor, my tests run fine. In the tutorial I am following, they are able to just run npm run protractor & the tests also run. However, when I try that then I get this error message: protractor configuration.js [21:01:19] I/launcher - Running 1 instances of WebDriver [21:01:19] I/hosted - Using the selenium server at http://localhost:4444/wd/hub [21:01:21] E/launcher - Error code: 135 [21:01:21] E/launcher - Error message: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:4444 [21:01:21] E/launcher - Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:4444 Can someone please tell me why this isn't working for me? A: Your webdriver-manager must run in a separate terminal and then you must start the test. Run npm run webdriver-start in one terminal and let it run. Later run npm run protractor in another terminal to start the tests.
doc_23528479
double A::a(double(b::*bb)()) { b.init(); return (b->*bb)(); } void A::run(); { cout<< a(b.b1); cout<< a(b.b2); } class A { B b; void run(); double a(double(b::*bb)()); }; class B { void init(); double b1(); double b2(); }; A: It doesn't make sense. This makes sense though: class B // <- class B definition comes first { void init(); double b1(); double b2(); }; class A { B b; void run(); double a(double(B::*bb)()); // <- B instead of b }; double A::a(double(B::*bb)()) // <- B instead of b { b.init(); return (b->*bb)(); } void A::run() // <- you can't put semicolon here { cout<< a(&B::b1); // <- you want to pass the address of a member. cout<< a(&B::b2); // <- you want to pass the address of a member. } Now it makes more sense to me. A: This: double a(double(b::*bb)()); Should be: double a(double(B::*bb)()); That is, bb is to be declared as a pointer to member function in the class B, not in the object b (which is an instance, not a type itself, therefore cannot be part of a type).
doc_23528480
D/CartActivity-onCreate(18171): onCreate D/CartActivity-TOTAL-InsideFORLOOP:(18171): 0.0 D/CartActivity-onResume(18171): onResume D/CartAdapter-TOTAL:(18171): 12.95 As you can see in above Log for loop is executed first in CartActivity and after the execution of onResume() method of CartActivity, CartAdapter is executing this line, therefore for i am getting 0.0 as value of Total in CartActivity inside For loop The reason is not where i am adding to data ArrayList, issue is CartActivity executes (where i am getting value for Total) before CartAdapter execution (where i am setting value for Total) So what I have to do, If I would like to call below line before execution of onCreate() method of CartActivity CartArrayList.cartArraylist.get(position).setTotal(totalPrice); CartActivity.java: public class CartActivity extends Activity { ..... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("CartActivity-onCreate", "onCreate"); setContentView(R.layout.activity_cart); ....... adapter = new CartAdapter(getApplicationContext(), R.layout.adapter_cart, CartArrayList.cartArraylist); for (int d = 0; d < CartArrayList.cartArraylist.size(); d++) { subTotal = subTotal + CartArrayList.cartArraylist.get(d).getTotal(); Log.d("CartActivity-TOTAL-InsideFORLOOP:", String.valueOf(CartArrayList.cartArraylist.get(d).getTotal())); } listview.setAdapter(adapter); adapter.notifyDataSetChanged(); textSubTotal.setText(decimalFormat.format(subTotal)); } @Override public void onResume() { super.onResume(); Log.d("CartActivity-onResume", "onResume"); } } CartAdapter.java: public class CartAdapter extends BaseAdapter { ..... @Override public View getView(final int position, View convertView, ViewGroup parent) { ...... totalPrice = cart.getQuantity() * cart.getPrice(); CartArrayList.cartArraylist.get(position).setTotal(totalPrice); Log.d("CartAdapter-TOTAL:", String.valueOf(CartArrayList.cartArraylist.get(position).getTotal())); ..... return convertView; } } A: You have to calculate Total value in entity only before setting the array list in Adapter, rather than calculating it in getView. Code snippet : for (int d=0; d<CartArrayList.cartArraylist.size(); d++) { // calculate total value Double totalPrice = CartArrayList.cartArraylist.get(d).getQuantity() * CartArrayList.cartArraylist.get(d).getPrice(); CartArrayList.cartArraylist.get(d).setTotal(totalPrice); // set it for subTotal subTotal = subTotal + totalPrice; } adapter = new CartAdapter(getApplicationContext(), R.layout.adapter_cart, CartArrayList.cartArraylist); listview.setAdapter(adapter); Hope it helps ツ A: You're going to want to move your list population to onResume() and it's a good idea to store your list in the outstate bundle of onSaveInstanceState() then check for it's existence to repopulate your list in onCreate()'s savedInstanceState bundle. That's indirectly related to your question ;) I know, but if you're moving the population and display of your list to onResume() you're going to want to also do those things so you're not repeating work you've potentially already done. Also, move your notifyDataSetChanged() to after the spot where you update the data. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cart); listview = (ListView)findViewById(R.id.listCart); if (adapter == null) { adapter = new CartAdapter(getApplicationContext(), R.layout.adapter_cart, CartArrayList.cartArraylist); } listview.setAdapter(adapter); if (savedInstanceState != null) { CartArrayList.cartArrayList = savedInstanceState.getParcelableArrayList(KEY_BUNDLE_CART_LIST); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelableArrayList(KEY_BUNDLE_CART_LIST, CartArrayList.cartArrayList); super.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); if (CartArrayList.cartArrayList.isEmpty()) { // Update your cartArrayList here if necessary } adapter.notifyDataSetChanged(); for(int d=0; d<CartArrayList.cartArraylist.size(); d++) { subTotal = subTotal + CartArrayList.cartArraylist.get(d).getTotal(); Log.d("NAME:", CartArrayList.cartArraylist.get(d).getName().toString()); Log.d("QUANTITY:", String.valueOf(CartArrayList.cartArraylist.get(d).getQuantity())); Log.d("PRICE:", String.valueOf(CartArrayList.cartArraylist.get(d).getPrice())); Log.d("TOTAL:", String.valueOf(CartArrayList.cartArraylist.get(d).getTotal())); Log.d("SUM:", String.valueOf(subTotal)); } } A: Use the following code _ListAdapter.notifyDataSetChanged(); A: I am unsure based on your first sentence, because you said there that you add an item before you go to the CartActivity. I kind of doubt that, or you have a concurrency issue there. If your first sentence is true, your onClick which adds the cart entry is probably called after your onCreate method runs, that means you only see it if you open the CartActivity the second time. The biggest question is the timing of your add call. A: The value won't reflect automatically. You have to call adapter.notifyDataSetChanged(); after updating your dataset.
doc_23528481
I was running this snippet of code under Ubuntu 20.04 LTS with NASM 2.14.02, but it results in a SIGSEGV segmentation fault on the load, not SIGBUS. global _start section .text _start: mov rax, [qword 0x11223344557788] mov rax, 60 xor rdi, rdi syscall Corresponding X86-64 assembly code after compiling: Disassembly of section .text: 0000000000401000 <_start>: 401000: 48 a1 88 77 55 44 33 movabs 0x11223344557788,%rax 401007: 22 11 00 40100a: b8 3c 00 00 00 mov $0x3c,%eax 40100f: 48 31 ff xor %rdi,%rdi 401012: 0f 05 syscall A: If you review the Instruction Set Architecture manual for the MOV instruction you would find that accessing a non-canonical address yields a #GP(0) General Protection Fault: Linux maps all #GP exceptions to SIGSEGV signal (Segmentation Fault). However, in Linux there is a way for a non-canonical address to cause a Bus Error and that is by getting the processor to raise an #SS (Stack Segment) exception. Linux maps #SS exceptions to the SIGBUS signal. Setting the stack pointer to a non-canonical address and then performing a stack related operation will produce such an exception. This code should produce a Bus Error: global _start section .text _start: mov rsp, 0x8000000000000000 ; Set RSP to a non-canonical address push rax ; Pushing value on stack should produce BUS ERROR One other way of producing a Bus Error on Linux is to raise an #AC (Alignment Check) exception. If you write ring 3 (user) code that enables the Alignment Check bit (bit 18) in RFLAGS and do an unaligned memory access you should also receive a SIGBUS signal. This code should produce a Bus Error: global _start section .text _start: pushf ; Put current RFLAGS on the stack or dword [rsp], 1<<18 ; Enable bit 18 (Alignment Check) of the ; RFLAGS value saved on stack popf ; Pop new RFLAGS flags value into the RFLAGS register mov eax, [rsp + 1] ; Move a DWORD value from unaligned address ; Should produce a BUS ERROR
doc_23528482
I try to describe only the essential: * *I have a vector (I know, not a good idea, but I only use it briefly) *I want to store it in a file (I'm using Linux) *I want to retrieve it from said file and recreate the vector Since C++ doesn't allow the storing of single bits, I had to group all the bits in char and save the char as a "text". To do so I used this http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101 If the number of bits is multiple of 8, everything works fine. If this is not the case, I don't know how to handle the problem. I'll explain better. I have: 010011000110111101110010011001010110110101 I save the chars as: 01001100 -> L 01101111 -> o 01110010 -> r 01100101 -> e 01101101 -> m 01 That last "01"... I don't know how to store it. Of course I could create a byte with a 1 and some 0 padding... but I don't know the number of "extra bits" when I retrieve them! What is padding and what is info? I simply don't know how to do this... any idea? Some code for the file writer (Not my actual code... its too long... I wrote only the important parts...): void Compressor::compress(std::istream &is, std::ostream &os) { queue<bool> bit_buffer; char c; while (is.get(c)) { new_letter = c; const std::vector<bool> bit_c = char2bits(new_letter); for(bool bit : bit_c) bit_buffer.push(bit); } //Here my code adds a certain number of bits, I simulate this with: bit_buffer.push(false); bit_buffer.push(true); // Write the bit buffer into a file while (bit_buffer.size() >= 8) { // Group vector<bool> in char char output = 0; for (int i=0; i<8; i++) { int bit = bit_buffer.front(); bit_buffer.pop(); if (bit) bit_set(output, BIT(i)); else bit_clear(output, BIT(i)); } // Individually write chars in file os.write(&output,sizeof(char)); } //???????? //Last bits??? //???????? } vector<bool> char2bits (char c) { bitset<8> bit_c (c); vector<bool> bool_c; for (int i=7; i>=0; i--) { bool_c.push_back(bit_c[i]); } return bool_c; } A: One way to do bit padding is to pad with 10...0. So 01 gets padded to 01100000. When decoding, just ignore everything behind the last 1. If you have a full byte in the end, pad with 10000000. A: I would use header too, but for a group of payload bytes. I mean : HH PP PP PP PP PP PP .. HH PP PP * *If HH == 256, ok, you've got 32 bits of Payload and then you'll find another chunk *If HH < 256, you've have to read next int(HH/8) bytes and within the last one, HH % 8 bits. In addition, it's meaning the file is over. For large bit fields, you may increase the header to 16 or 32 bits.
doc_23528483
class LinkedListNode { public: friend class LinkedList; friend class LinkedListIterator; LinkedListNode(const T p_data) : data(p_data), next(nullptr) {} ~LinkedListNode() { std::cout << "~LinkedListNode()\n"; } private: T data; LinkedListNode<T>* next; }; template <typename T> class LinkedList { /* Redefinition of 'LinkedList' as different kind of symbol */ ... } I made own linked-list data structure, but an error message is appeared to LinkedList class. If I try to compile the code, another error is occured. error: template argument required for ‘class LinkedList’ class LinkedListNode { ^ error: template placeholder type ‘LinkedListNode’ must be followed by a simple declarator-id LinkedListNode* pre_remove; ^~~~~~~~~~~~~~ I've added template <typename T> above LinkedList class so I can't understand why these error messages come out. int main() { LinkedList li; ... } ---------------------------------------------------- error: class template argument deduction failed: LinkedList li; ^~ Full source code of Linked List A: As already hinted by dorKKnight, class LinkedList is actually a template. Hence, you have to use it as such – even in friend declarations. template <typename T> class LinkedListNode { friend class LinkedList<T>; The other part of the story is that LinkedList and LinkedListNode have a circular dependency. To break this, a template forward declaration is needed. // forward declaration template <typename T> class LinkedList; A complete sample: // forward declaration template <typename T> class LinkedList; template <typename T> class LinkedListNode { friend class LinkedList<T>; public: const T value; private: LinkedListNode *pNext; public: LinkedListNode(const T value): value(value), pNext(nullptr) { } ~LinkedListNode() = default; }; template <typename T> class LinkedList { LinkedListNode<T> *pFirst, *pLast; public: LinkedList(): pFirst(nullptr), pLast(nullptr) { } void push(const T value) { if (!pFirst) pFirst = pLast = new LinkedListNode<T>(value); else { pLast->pNext = new LinkedListNode<T>(value); pLast = pLast->pNext; } } void print(const char *sep = " ") { std::cout << "{"; for (LinkedListNode<T> *pNode = pFirst; pNode; pNode = pNode->pNext) { std::cout << sep << pNode->value; } std::cout << sep << "}"; } }; int main() { LinkedList<int> list; list.push(1); list.push(2); list.push(3); list.print(); } Output: { 1 2 3 } Live Demo on coliru A matter of design: It is usual to embed the class for a single node into the template class for the list because the node class is a list detail which need not to be “seen” anywhere else. Redesigning the above sample: #include <iostream> template <typename T> class LinkedList { private: struct Node { const T value; Node *pNext; Node(const T value): value(value), pNext(nullptr) { } }; Node *pFirst, *pLast; public: LinkedList(): pFirst(nullptr), pLast(nullptr) { } void push(const T value) { if (!pFirst) pFirst = pLast = new Node(value); else { pLast->pNext = new Node(value); pLast = pLast->pNext; } } void print(const char *sep = " ") { std::cout << "{"; for (Node *pNode = pFirst; pNode; pNode = pNode->pNext) { std::cout << sep << pNode->value; } std::cout << sep << "}"; } }; int main() { LinkedList<int> list; list.push(1); list.push(2); list.push(3); list.print(); } Output: { 1 2 3 } Live Demo on coliru As a bonus, the forward issue has been vanished.
doc_23528484
I am currently building a „Data-Logger“ - App using R Shiny. I do have an REST - API, which returns a value, that changes over time. My goal is to create an Shiny App, in which an user can click on an actionbutton to start writing the values fetched from the api periodically (e.g. every 60 seconds) to a dataframe. The logging of the data also should be stopped, when the user clicks on another actionbutton. Problem My problem is writing a function that starts executing when a button is pressed, executes periodically after that and stops executing when another button is pressed. Previous Ideas I previously tried using invalidateLater(), but i could not achieve what i desire. Can you guys help me out with a clever thought or idea? Thanks in advance! A: This should show how it works. invalidateLater() is the right choice. The start/stop buttons change a reactive expression that determines whether polling is on or off. That way, the reactive RestPoll expression gets notified every time it gets switched on/off and, of course, after 500 ms as long as Running() == TRUE. library(shiny) ui <- fluidPage( actionButton("btnStart", "Start"), actionButton("btnStop", "Stop"), textOutput("outTime") ) server <- function(input, output, session) { Running <- reactiveVal(FALSE) observeEvent(input$btnStart, { Running(TRUE) }) observeEvent(input$btnStop, { Running(FALSE) }) RestPoll <- reactive({ if (Running()) # IS called every time `Running` changes invalidateLater(500, session) # Add any REST calls here, process the results return(Sys.time()) # deliver results }) output$outTime <- renderText({ req(RestPoll()) }) } shinyApp(ui, server) You could also do it with a reactiveTimer but that would also poll and use resources when polling is not required.
doc_23528485
@IBOutlet var Map: MKMapView! override func viewDidLoad() { super.viewDidLoad() Map.delegate = self let location = CLLocationCoordinate2DMake(lat!, lon!) let span = MKCoordinateSpanMake(0.1, 0.1) let region = MKCoordinateRegion(center: location, span: span) Map.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Title" Map.addAnnotation(annotation) } I try use UITapGestureRecognizer and mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) but it doesn't work. Maybe someone have any ideas A: Implement the delegate methods. func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let reuseId = "Pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView?.canShowCallout = true let rightButton: AnyObject! = UIButton(type: UIButtonType.detailDisclosure) pinView?.rightCalloutAccessoryView = rightButton as? UIView } else { pinView?.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { print(#function) if control == view.rightCalloutAccessoryView { // Do something } }
doc_23528486
So essentially in the example below - I'd want IDs 1,4 and 5 to have 'True' because those values appear in the ParentID column, and for the others to have False because they don't - So I don't want to exclude those rows or hide them, just mark them differently in my new column. ID ParentID 1 null 2 null 3 1 4 1 5 null 6 4 7 5 8 null 9 null 10 1 This is something that's really easy to do in Excel with a vlookup formula, and it might be easy to add a column in PowerQuery that can display this but I'm stumped, and don't know where to go with it. I've tried merging the table with itself but all that seems to achieve is identifying the rows that are true OR the rows that are false rather than indicating in a new column what the result is. There's got to be a way for this... hasn't there?? A: You can use List.Contains and reference the parent column from the previous step. List.Contains(#"Previous Step Name"[ParentID], [ID])) In full context: let Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUcorzclRitWJVjJC5hgDOYZglgmcZYqswAzIMQGzzIEsUzDLAlmBJTLH0ABiSiwA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, ParentID = _t]), #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"ParentID", Int64.Type}}), #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each List.Contains(#"Changed Type"[ParentID], [ID]), type logical) in #"Added Custom"
doc_23528487
//this could be C++ MyVectorType position = ...; MyVectorType velocity = ...; float dt; //Here's the expression I want to calculate: position += dt*velocity; Now let's say you want to do this in Java. There's no operator overloading - ok, I can live without. //this still could be C++ MyVectorType position = ...; MyVectorType velocity = ...; float dt; //Here's the expression I want to calculate: position.add(velocity.times(dt)); I would say it's less readable, but still ok. How should I write the code above in Java? I thought I'd use javax.vecmath: //my attempt in Java Vector3f velocity = new Vector3f(...); Vector3f position = new Vector3f(...); float dt; //Here's the expression I want to calculate - three lines. Vector3f deltaPosition = new Vector3f(velocity); deltaPosition.scale(dt); position.add(deltaPosition); Does it really require these three lines to perform such a simple operation? For people being used to reading mathematical expressions I think this is a pain, especially as the operations become more complex. Also, writing such expressions is not really a pleasure. Am I missing something? Or is there another vector math package that leads to more readable code? A: The javax.vecmath package is, unfortunately, kind of clunky. You might want to take a look at JAMA from NIST. It's a matrix package, not a vector package (doesn't have cross product, for example), but at least with that package, you can chain operations together on a single line: double[][] array = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}}; Matrix A = new Matrix(array); Matrix b = Matrix.random(3,1); Matrix x = A.solve(b); Matrix Residual = A.times(x).minus(b); You can do a lot of vector arithmetic by treating vectors as 1xN matrices. NIST has also posted a page of links to other Java numerics packages where you might find something that's a closer match to your needs if JAMA isn't quite right.
doc_23528488
class Rule: def __init__ (self,number, callout): self.number=number self.callout=callout def shout(self): print(self.callout) I then create a list of these objects to iterate over, calling shout() for each of them: Fizz = Rule(3,"Fizz") Buzz = Rule(5,"Buzz") Rules = [Fizz,Buzz] #example 1 for x in range(0, 2): Rules[x].shout() #example 2 for item in Rules: print (item.shout()) The output of example 1 is: Fizz Buzz as expected. But the output of example 2 is: Fizz None Buzz None Why do they perform differently? Thank you in advance :) A: item.shout() returns a value of None Therefore, when you print it, you'll get the print statement from the function as well as the return value which by default, is None
doc_23528489
I can hackishly set the page zoom by sending the ctrl+0 keystroke to the IE window, but there's not really any easy way that I can see to set the text size. I could go through the menu with keystrokes: alt+z -> x -> m but this is just getting silly. I have no way of knowing whether the menu has shown and whether it's safe to send the next key. I've looked at the IE command line arguments, but they're really limited. Any ideas? A: Take a look at HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Zoom. You can set a DWORD that corresponds to the zoom level of the page.
doc_23528490
If I try, I get the following error: Uncaught SyntaxError: Unexpected identifier That is the example code: //index.html ... <script src="script1.js" type="module"></script> ... //script1.js import Class1 from './script2.js'; const class1 = new Class1(); //script2.js class Class1 { constructor() { //doStuff import Class2 from './script3.js'; const class2 = new Class2(); } } export default Class1; //script3.js class Class2 { constructor() { //doStuff console.log("Class2"); } } export default Class2; A: Thanks a lot Anurag! To make the solution more prominent, I post the solution here again: The import statement has to be on top level of the file and not inside the class. Read this question and the answer for details about the reasons: Why must export/import declarations be on top level in es2015?
doc_23528491
net = resnet18() phi = math.pow(math.sqrt(2), 7) # net.conv1 = nn.Conv2d(math.ceil(phi*3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) net.conv1 = nn.Conv2d(math.ceil(3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) net.bn1 = nn.BatchNorm2d(math.ceil(phi*64), eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) net.relu = nn.ReLU(inplace=True) net.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) net.layer1[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*64), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) . . net.layer2[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*128), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) . . net.layer3[0].conv1 = nn.Conv2d(math.ceil(phi*128), math.ceil(phi*256), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) . . net.layer4[0].conv1 = nn.Conv2d(math.ceil(phi*256), math.ceil(phi*512), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) . . # net.avgpool = Identity() net.avgpool = nn.AdaptiveAvgPool2d(output_size=(1, 1)) nn.fc = nn.Linear(in_features=math.ceil(phi*512), out_features=1000, bias=True) The edited model works when I use model.named_parameters(). I am thinking that I messed up by directly assigning layers with new values (I am not sure of the order of parameters for the layers, printing my model seems to be fine, but for the love of god not a single input passes throught the model). Want to know where I messed up in the syntax, because of which my inputs are not passing through the model. ip = torch.rand(1,3,224,224).to(dev) count_ops(net, ip) # Count the number of FLOPs
doc_23528492
I'm coding in c++. What I need is to create a button (in the dialog box) that, when I click on it, gives me the possibility to choose a file from my pc. After that, I only need to charge in memory (like in a string variable nameFile) the name of this file. Do anyone know how to do this operation? And second problem, do you guys know any youtube guide or similar to customize the interface?? Like to put one picture on the background of the application, or change button style etc. I used Eclipse before, coding in Java and It was totally different. Thank you all!! A: Here is an MFC tutorial for adding a button to a dialog and what has to be done to "wire it up" so that clicking the button invokes an event handler for the BN_CLICKED event. Inside the BN_CLICKED event handler (that is, the function that is called when you click the button), you'll want to launch the dialog that lets you selecte the file. @Jongware suggested this link, which has a couple of approaches. Once the file has been selected and the dialog disappears, you'll have access to the string containing the selected file. How you do this will depend on which approach you take in the preceding step. Once you have the string, you can use the appropriate File Management functions to slice-and-dice the file name as necessary. That's far short of the actual code you'll need to write, I know, but it should give you enough of a start to get going. HTH.
doc_23528493
I would like to achieve this only with the .NET API without using third party libraries. I am researching the ability to use the SignedCms class from System.Security.Cryptography.Pkcs namespace. The SignedCms class has signedCms.SignerInfos collection from a SignerInfo object, which should hold the encrypted digest data. However, I can't find a way to access it. Can anyone help me with this?
doc_23528494
import requests import json from json2table import convert from flask import Flask, render_template, abort, url_for, json, jsonify, request ... html1 = convert(table1, build_direction=build_direction, table_attributes=table_attributes) return render_template('index.html', table = html1) I put {{ table }} in templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST"> <input name="text"> <input type="submit"> </form> <div> {{ table }} </div> </body> </html> But when I start the app it show me a raw html without formatting How can I fix it? What should be done? A: Use the safe filter to tell Jinja that the generated HTML is safe to render without escaping. <div> {{ table | safe }} </div>
doc_23528495
export const courseIndustry: any = { getById: (id: string) => { return {}; } }; And I thought I specified that the argument id is of type string, but the mocha test claims: mocha -r ts-node/register -r espower-typescript/guess test/**/*.test.ts Unable to compile TypeScript: courseIndustry.ts(4, 15): error TS7006: Parameter 'id' implicitly has an 'any' type. Where am I wrong? A: The error seems thrown by espower-typescript/guess. So I checked its document and find the following switch can work around the errors: 'TS_NODE_TRANSPILE_ONLY=1'. So the final version of the shell command make it work: TS_NODE_TRANSPILE_ONLY=1 mocha -r ts-node/register --require espower-typescript/guess test/**/*.test.ts --exit A: Try to use a another transpiler like typescript-compiler or any other and try to complie. enter link description here
doc_23528496
And while talking about libraries to work with OpenGL (at 3:00) he mentions GLFW, freeGLUT and GLUT to use to create the window. But can they handle input and sound as well like SDL? And if so should I be using SDL? Or is GLFW more tuned for making games specifically in OpenGL? A: No, GLUT and GLFW are frameworks that manage OpenGL context creation and windowing (which includes input) mostly. GLUT has a few components that are actually designed to draw things, but by in large it is there to setup GL only. SDL, on the other hand, includes sound which neither GLFW nor GLUT do but also includes utilities to load resources such as image files. It is a much more end-to-end solution, whereas GLFW and GLUT are only designed to facilitate rendering/windowing. To do the same thing using GLFW, you would need to throw in some libraries such as SOIL (or work directly with libpng, libjpeg, etc.) and also find an audio library. You do not need any of these things to make a game in truth. I interact directly with OpenGL (WGL/GLX/CGL) on Windows, Linux and OS X in my work but the extra time necessary to debug and maintain each of these platforms at such a direct level can be a real nuisance. If writing extra code specific to each platform you run on is unappealing then you should definitely consider GLFW, etc.
doc_23528497
Each participant had been asked to specify the age of all of their children. Child number was shown along the top of the grid (e.g. 'Child 1', 'Child 2' etc.) and age bracket in a column down the left-hand side (e.g. 10-13, 14-18, etc.). Multiple responses could be selected from the grid and it's this that's giving me a headache. When it comes to the CSV output, results for the problem question have been separated so that they occur across multiple columns. Age brackets are displayed as separate columns and multiple responses can occur within a cell (see a very small example below). The real dataset contains several hundred participants and the results have been subsetted according to multiple criteria. x10a.6.9 x10a.10.13 x10a.14.18 x10a.19.23 child 2;child 3 child 1 child 1 child 3;child 4 child 2 child 1 child 1; child 2 Edit: Reproducible version of the ugly table (thanks for the link Mojoesque): structure(list(x10a.6.9 = c("child 2;child 3", NA, "child 3;child 4", NA), x10a.10.13 = c(NA, "child 1", "child 2", "child 1;child 2" ), x10a.14.18 = c("child 1", NA, NA, NA), x10a.19.23 = c(NA, NA, "child 1", NA)), row.names = c(NA, -4L), class = "data.frame") I would like to know how I would go about reshaping this data so that it can be presented in simple bar charts. I don't know how to arrange this data in order to get it to cooperate with ggplot2. I would, if at all possible, like it to look like the summary image produced in Google Forms. As it stands, I have no idea how to use data like this to plot age along the x-axis and count along the y-axis. I want to show this separately for each child number as in the attached image, but do not know where to begin. Any and all help would be greatly appreciated. I apologise profusely if the question is worded poorly and apologise too for my incredible naivity. Edit: Resolution I played around with this a little and figured out how to plot what I wanted. I'll post the steps used below in case they are useful to anyone else. In the code below, data_to_split corresponds to the small snippet of a table that was shown above. library(tidyr) library(dplyr) library(ggplot2) data_split <- data_to_split %>% separate_rows(x10a.6.9:x10a.19.23, sep = ";") %>% select(x10a.6.9:x10a.19.23) %>% na_if(., "") %>% mutate_all(funs(as.factor)) It was necessary to use the separate_rows function from tidyr as multiple responses could occur within a cell (e.g. a cell could read 'child 1;child 2') The separator ";" was used to split these cells into multiple rows. na_if was used to convert empty spaces that were reading as factors into NA values. In the code below, new columns were added. These columns simply provided new names for the columns that had been read into R. The old ones were ugly and harder to work with. data_split$`6-9` <- data_split$x10a.6.9 data_split$`10-13` <- data_split$x10a.10.13 data_split$`14-18` <- data_split$x10a.14.18 data_split$`19-23` <- data_split$x10a.19.23 In the first two lines of code below, all relevant columns containing age brackets were selected. The data was then converted from wide to long format. In the third line, na values were dropped as I did not wish to display them. Tally() was used to obtain an n value that could be used to display count along the y-axis. In the fourth line, it was necessary to re-order the age-brackets, so that they were shown along the x-axis in chronological order. The rest of the lines helped develop a basic barplot. age_plot <- data_split %>% select(`6-9`:`19-23`) %>% pivot_longer(., cols = c(`6-9`:`19-23`), names_to = "Var", values_to = "Val") %>% drop_na() %>% group_by(Var, Val) %>% tally() %>% ggplot(aes(x = factor(Var, level = c("6-9", "10-13", "14-18", "19-23")), y = n, fill = factor(Val, level = c("child 1", "child 2", "child 3", "child 4")))) + geom_bar(stat = "identity", position = position_dodge(width = 0.9)) + theme_classic() + labs(fill = "Child", x = "Age", y = "Number") age_plot The result looked like this. (Obviously this graph looks a little odd with so few data points, but the real things looked good!) A: Updated: "position_dodge" changed to "position_dodge2" and "preserve = 'single'" in "geom_bar" so that each individual bar is now the same width. Answer is within the question body, but pasting here, too in case it is useful. In the code below, data_to_split corresponds to the small snippet of a table that was shown in the question. Reproducible version: structure(list(x10a.6.9 = c("child 2;child 3", NA, "child 3;child 4", NA), x10a.10.13 = c(NA, "child 1", "child 2", "child 1;child 2" ), x10a.14.18 = c("child 1", NA, NA, NA), x10a.19.23 = c(NA, NA, "child 1", NA)), row.names = c(NA, -4L), class = "data.frame") library(tidyr) library(dplyr) library(ggplot2) data_split <- data_to_split %>% separate_rows(x10a.6.9:x10a.19.23, sep = ";") %>% select(x10a.6.9:x10a.19.23) %>% na_if(., "") %>% mutate_all(funs(as.factor)) It was necessary to use the separate_rows function from tidyr as multiple responses could occur within a cell (e.g. a cell could read 'child 1;child 2') The separator ";" was used to split these cells into multiple rows. na_if was used to convert empty spaces that were reading as factors into NA values. In the code below, new columns were added. These columns simply provided new names for the columns that had been read into R. The old ones were ugly and harder to work with. data_split$`6-9` <- data_split$x10a.6.9 data_split$`10-13` <- data_split$x10a.10.13 data_split$`14-18` <- data_split$x10a.14.18 data_split$`19-23` <- data_split$x10a.19.23 In the first two lines of code below, all relevant columns containing age brackets were selected. The data was then converted from wide to long format. In the third line, na values were dropped as I did not wish to display them. Tally() was used to obtain an n value that could be used to display count along the y-axis. In the fourth line, it was necessary to re-order the age-brackets, so that they were shown along the x-axis in chronological order. The rest of the lines helped develop a basic barplot. age_plot <- data_split %>% select(`6-9`:`19-23`) %>% pivot_longer(., cols = c(`6-9`:`19-23`), names_to = "Var", values_to = "Val") %>% drop_na() %>% group_by(Var, Val) %>% tally() %>% ggplot(aes(x = factor(Var, level = c("6-9", "10-13", "14-18", "19-23")), y = n, fill = factor(Val, level = c("child 1", "child 2", "child 3", "child 4")))) + geom_bar(stat = "identity", position = position_dodge2(width = 0.9, preserve = "single")) + theme_classic() + labs(fill = "Child", x = "Age", y = "Number") age_plot The result looked like this. (Obviously this graph looks a little odd with so few data points, but the real things looked good!)
doc_23528498
<!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #111; } li a:active { background-color: #51014d; } </style> </head> <body> <ul> <li><a class="active" href="#home">Home</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> <div id="home"> <h1>Welcome!</h1></div> <div id="contact" style="visibility: hidden"> <h2>you can reach me at:</h2></div> <style> #home { background-color: honeydew; } </style> <style> #contact { background-color: lightblue; } </style> </body> </html> I am trying to make the navigation menu link to different pages of my website (for example, they can go to "contact", and view information regarding that topic). However, the links with this code aren't working. When I click on the different tabs, it does not show the corresponding page. How do I fix this? Thank you! A: try below code: <!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #111; } li a:active { background-color: #51014d; } #home { background-color: honeydew; } #contact { background-color: lightblue; } #about { background-color: darkblue; } </style> </head> <body> <ul> <li><a onclick="showDiv('home');" class="active" href="#home">Home</a></li> <li><a onclick="showDiv('contact');" href="#contact">Contact</a></li> <li><a onclick="showDiv('about');" href="#about">About</a></li> </ul> <div id="home"> <h1>Welcome!</h1> </div> <div id="contact"> <h2>you can reach me at:</h2> </div> <div id="about"> <h2>about us at:</h2> </div> <script> function showDiv(id) { document.getElementById("home").style.display = "none"; document.getElementById("about").style.display = "none"; document.getElementById("contact").style.display = "none"; document.getElementById(id).style.display = "block"; } showDiv('home'); </script> </body> </html>
doc_23528499
A: Say you have the following: * *deck, a randomized deck containing all the cards (including those the players have seen). *seen_card_id_by_player, a lookup table that give you the guid of the card a player has seen. Then the solution is simply local card_ids = {} for i, card_data in ipairs(deck.getObjects()) do table.insert(card_ids, card_data.guid) end for player, seen_card_id in pairs(seen_card_id_by_player) do local card_id = table.remove(card_ids) if card_id == seen_card_id then local i = math.random(1, #card_ids) card_ids[i], card_id = card_id, card_ids[i] end -- Deal the specific card. deck.takeObject({ guid = card_ids[i], position = player.getHandTransform().position, flip = true, }) end When we pick the card the player has already seen, it is placed back at a random location among the remaining cards. This ensures that every card has an equal chance of being drawn by the next player. This is the underlying principle of the Fisher-Yates shuffle. Full demonstration function broadcast_error(msg) broadcastToAll(msg, { r=1, g=0, b=0 }) end function get_cards_seen_by_players() local player_ids = Player.getAvailableColors() local error = false local seen_card_by_player = {} for i, player_id in ipairs(player_ids) do local player = Player[player_id] local hand_objs = player.getHandObjects() local player_error = false if #hand_objs > 1 then player_error = true elseif #hand_objs == 1 then local card = hand_objs[1] if card.tag ~= "Card" then player_error = true else seen_card_by_player[player] = card end end if player_error then broadcast_error(player_id .. " doesn't have a valid hand.") error = true end end if error then return nil end return seen_card_by_player end function run() local deck = getObjectFromGUID("...") local seen_card_by_player = get_cards_seen_by_players() if seen_card_by_player == nil or next(seen_card_by_player) == nil then return end local seen_card_id_by_player = {} for player, card in pairs(seen_card_by_player) do local card_id = card.guid seen_card_id_by_player[player] = card_id card.putObject(deck) end deck.randomize() local card_ids = {} for i, card_data in ipairs(deck.getObjects()) do table.insert(card_ids, card_data.guid) end for player, seen_card_id in pairs(seen_card_id_by_player) do local card_id = table.remove(card_ids) if card_id == seen_card_id then local i = math.random(1, #card_ids) card_ids[i], card_id = card_id, card_ids[i] end deck.takeObject({ guid = card_ids[i], position = player.getHandTransform().position, flip = true, }) end end Create a game with a deck of cards. Place the above code in Global, replacing ... with the deck's GUID. To run the demonstration, deal one card to any number of players, then use /execute Global.call("run") in the chat window.