id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23538100
First of all, is the output from the kafka-consumer-group.sh script. I am getting weird output that doesn't really tell me where a particular consumer is at though they seem to be connected to a particular group/topic/partition: TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG STANDARD_DATA 9 11 11 0 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-1-consumer-4fd9dc15-d8a7-4598-85a9-3761ae6a747b/1.1.1.1 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-1-consumer STANDARD_DATA 0 4 11 7 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-5-consumer-28e1c7bf-860d-44d6-bf58-5e0ff875587c/1.1.1.1 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-5-consumer STANDARD_DATA 4 - 10 - myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-4-consumer-a3023af6-eafb-4633-85f1-048c20c4dfb3/1.1.1.1 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-4-consumer STANDARD_DATA 5 - 10 - myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-3-consumer-a81f1399-1fc4-4579-b24f-fa8fee01fabf/1.1.1.1 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-3-consumer STANDARD_DATA 3 - 12 - myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-2-consumer-6a83bfcc-2c6e-4e9d-a819-029ac8c6ae17/1.1.1.1 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-2-consumer STANDARD_DATA 8 12 12 0 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-4-consumer-6d46bed3-70c4-4c7f-8e53-f9591192bc3f/1.1.1.1 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-4-consumer STANDARD_DATA 7 - 11 - myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-3-consumer-5313315b-ded9-4fe7-ac9d-d8d5b20dd5b9/1.1.1.1 myConsumer-13b61e5a-6289-45db-844b-3ef8c5a26782-StreamThread-3-consumer STANDARD_DATA 2 10 10 0 myConsumer-b9402faf-4b37-479f-82be-a17eaa180c62-StreamThread-1-consumer-c08a648f-548e-47a8-8bc5-7b6fa3bc1fb5/1.1.1.1 myConsumer-b9402faf-4b37-479f-82be-a17eaa180c62-StreamThread-1-consumer STANDARD_DATA 1 2 10 8 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-2-consumer-08d99679-d430-4e9f-a3b9-11e558ca34a4/1.1.1.1 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-2-consumer STANDARD_DATA 6 - 12 - myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-5-consumer-666040f8-d4d0-49e9-9db6-c6efee49ebe1/1.1.1.1 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-5-consumer * *Why is it that some CURRENT-OFFSETS (3rd column) and LAG (4th column) are showing up as '-' when I can query the API of Kafka directly to distinguish that they are in fact caught up? (queried through golang API) 4 myConsumer-7fc71848-465b-4817-93b3-42b9ba290dcd-StreamThread-4-consumer-a3023af6-eafb-4633-85f1-048c20c4dfb3 OFFSET: 10 LOG-END: 10 LAG: 0 *Also, why on would that offset not being showing up as represented in the logs (aka, it should be caught up) in general? My second high level question is that of streams. We have a stream process working that is, at random times (mostly during a restart), resetting to the earliest offset available in particular topics. Throughout the code there is no 'reset', and the OFFSET_RESET isn't touched. I also can confirm that we are not using the 'exactly-once', so I am not sure where exactly these offset resets are coming into play. Once again, its basically: stream process is churning through the data, something ~happens~ and then our offsets are back to ground 0, processing again. This can be going on for days to weeks before it decides to reset too, so the committing of offsets IS happening. A: About the output of kafka-consumer-groups.sh: A - in CURRENT-OFFSET indicates that there is no committed offset for this partition. This implies, that the lag can also not be computed (thus, you get a - there, too). If I read your statement correctly, if you query the offsets with golang, it shows that partition 4 is at offset 10, in contrast to what kafka-consumer-groups.sh showns -- not sure why this is the case... About the reseted offsets: You might need to increase broker config offsets.retention.minutes -- default is 24h (cf. https://docs.confluent.io/current/streams/faq.html#why-is-my-application-re-processing-data-from-the-beginning). Also note that Streams API uses default reset policy "earliest" (in contrast to Consumer API that use "latest" as default). You can change the reset policy in Streams API via StreamsConfig: https://docs.confluent.io/current/streams/developer-guide.html#non-streams-configuration-parameters
doc_23538101
boolean isActive; boolean isEnable; boolean isNew; every property is related to an enum (e.g. ACTIVE,ENABLE,NEW). I want to have 2 lists of enum. One which has only the enums related to true property value and one for the false one. just to be clear. using if-else statement I could have Set<FlagEnum> flagSet = new HashSet<>(); Set<FlagEnum> falseFlagSet = new HashSet<>(); if (object.isActive()) { flagSet.add(ACTIVE); } else { falseFlagSet.add(ACTIVE); } if (object.isEnable()) { flagSet.add(ENABLE); } else { falseFlagSet.add(ENABLE); } if (object.isNew()) { flagSet.add(NEW); } else { falseFlagSet.add(NEW); } is there a way to avoid all these if-else? I tried with something like Map<boolean, List<Pair<boolean, FlagEnum>>> res = Stream.of( new Pair<>(object.isActive(), ACTIVE), new Pair<>(object.isNew(), NEW), new Pair<>(object.isEnable(), ENABLE)) .collect(Collectors.partitioningBy(Pair::getKey)); but the resulted structure is an additional complexity which I would like to avoid. In my real case, I have more than 15 boolean properties... A: You can simplify this in various ways. Which of them make sense, depends on your exact requirements. * *You can derive the falseFlagSet trivially from the flagSet using EnumSet.complementOf after populating the flagSet: EnumSet<FlagEnum> falseFlagSet = EnumSet.complementOf(flagSet); This assumes that all FlagEnum values have corresponding flags. If that's not the case then you need to construct a EnumSet with all enums that have flags and subtract flagSet from that using removeAll. *#1 already removes the need for the else in your cascade, simplifying the code to if (object.isActive()) { flagSet.add(ACTIVE); } if (object.isEnable()) { flagSet.add(ENABLE); } if (object.isNew()) { flagSet.add(NEW); } *If you have enough different flags, then you can create a mapping from getter method to FlagEnum value like this: Map<Function<YourClass,Boolean>,FlagEnum> GETTERS = Map.of( YourClass::isActive, FlagEnum.ACTIVE, YourClass::isNew, FlagEnum.NEW, YourClass::isEnable, FlagEnum.ENABLE); Then you can use this to make the whole process data-driven: EnumSet<FlagEnum> getFlagSet(YourClass yourObject) { EnumSet<FlagEnum> result = EnumSet.noneOf(FlagEnum.class); for (Map.Entry<Function<YourClass,Boolean>, FlagEnum> getter : GETTERS.entrySet()) { if (getter.getKey().apply(yourObject)) { result.add(getter.getValue()); } } return result; } *If the number of flags is very big, then you could switch entirely to reflection and detect the flags and matching getters dynamically using string comparison, but I would not suggest that approach. If you need something like that then you probably should switch to a framework that supports that kind of feature and not implement it yourself. That last two obviously only makes sense when the number of flags is big. If it's actually just 3 flags, then I wouldn't mind and just have 3 simple if statements. As a slight tangent: GETTERS above should definitely be an immutable map (wrap it in Collections.unmodifiableMap or use something like Guava ImmutableMap) and it could be argued that the same applies to the return value of the getFlagSet method. I've left those out for succinctness. A: You can use a private helper method for this. private void addFlagSet(boolean condition, FlagEnum flagEnum, Set<FlagEnum> flagSet, Set<FlagEnum> falseFlagSet) { Set<FlagEnum> chosenFlagSet = condition ? flagSet: falseFlagSet; chosenFlagSet.add(flagEnum); } Call it as: addFlagSet(object.isActive(), FlagEnum.ACIVE, flagSet, falseFlagSet); addFlagSet(object.isNew(), FlagEnum.NEW, flagSet, falseFlagSet); addFlagSet(object.isEnable(), FlagEnum.ENABLE, flagSet, falseFlagSet); A: You could probably use Reflection to get all methods, then check if a getReturnType() == boolean.class. Problem is the connection between the method's name and the enum. If every single one is named like the method without the 'is', you could use FlagEnum.valueOf() to retrieve the enum value from the method name and use it. A: I think this could be the easiest and clearest way to do what I need Map<Boolean, Set<FlagEnum>> flagMap = new HashMap<>(); flagMap.computeIfAbsent(object.isActive(), h -> new HashSet()).add(ACTIVE); flagMap.computeIfAbsent(object.isEnabled(), h -> new HashSet()).add(ENABLE); flagMap.computeIfAbsent(object.isNew(), h -> new HashSet()).add(NEW); //to get TRUE set simply : flagMap.get(true); what do you think?
doc_23538102
mat <- rep(cbind(c(1,3,0,1,4),c(0,4,1,2,1), c(2,3,0,4,0), c(1,0,4,2,0), c(0,2,3,0,1)),2) arr <- array(mat, dim=c(5,5,2)) nul <- c(1,3,5,8,4) I have tried many different things, but the closest I have come is: x1 <- apply(arr,c(1,3), function(x)myfun(x[x!=(nul)])) However, this results in the exclusion of row elements in arr which match corresponding row elements in nul for each row in nul. "myfun" is a summation for sake of simplicity, though in reality this will be something more complicated: > nul [1] 1 3 5 8 4 > arr , , 1 [,1] [,2] [,3] [,4] [,5] [1,] 1 0 2 1 0 [2,] 3 4 3 0 2 [3,] 0 1 0 4 3 [4,] 1 2 4 2 0 [5,] 4 1 0 0 1 , , 2 [,1] [,2] [,3] [,4] [,5] [1,] 1 0 2 1 0 [2,] 3 4 3 0 2 [3,] 0 1 0 4 3 [4,] 1 2 4 2 0 [5,] 4 1 0 0 1 > x1 [,1] [,2] [1,] 3 3 [2,] 12 12 [3,] 8 8 [4,] 8 8 [5,] 6 6 As you can see, only the "1" at position [1,1,1] is excluded, instead of each matching value in that row. In addition, the function excludes "1" in each row, instead of just the first. The desired output is: [1,] 2 2 [2,] 6 6 [3,] 8 8 [4,] 8 8 [5,] 2 2 A: try to use the which function instead res <- cbind(rep(0,5), rep(0,5)) #is the result matrix count <- 1 #is the dimension count of the array while (count <= dim(arr)[3]){ for (i in 1:nrow(arr[,,count])){ res[i,count] <- sum(arr[i,c(which(arr[i,,count] != nul[i])), count]) } count <- count + 1 } However i don't understand the ultimate output part.
doc_23538103
SAMLResponse=urlencode(base64.encode(deflate(data)))&signature=signdata&sigAlg=sha256 I can able to decrypt data and read claims but I can't verify signature Can someone explain me the steps how to verify signature against the saml response? If it is python it would be great SAMLResponse=nVdZk6NIDv4rjtq39VRzG3BUdQQGjMH44D5eNrgvc5jk9K9fqqqrp3t6YqJ3H6VIfZI+paTMF+CVt2arRqCpKxCtRO716T8wHcQoFhHPMOGTz3iwgZ8pAl5EzyNwMsZQAt08rcyoBVldvT6hX+CnlQhAH4kV6LyqW1Qwijwj6DNM6Qi5xfAtDH/ZwLD7tOIi0GWV171bpl3XgC0EgS55LoMiir6UWRXe6iQLvnhNA3l9l0JvYvW0Yt/ie8Pu22pbeyAD28orI7Dtgq3GnOTtEsY2+Di07SvQREEWZ1G4hFZ9pqfXr0/ljQx9IoqfA4SInnEcwZ7pYIkWx0nfoyOKCijsaTWVtwps38n5Z49NW3d1UN+evr68U9B+mP6zkQdA1L5R8PT1jYKFgTIGXz4YCOoS8sIYQMuRIQsiAHVtD7oX6AP+68tHxbTO63rws8TWYbQyvVsf/bN78H56q/XBAg+eVtDXF+hnVL4K2rnpopD5jPR/TOtliqpg+x2G8zpvpc9N9FHzJeFxHL+M2Je6TSAUhhEIxqHFw2L0L/4WlUsNP2vwBvQbVn9xuQRxirq0DlfMLanbrEvL3wDxIoASm+fAD95JOUazWMX1Z+p/aw5DMP1mHoIseQsi+jPpxfxbDr+T9o+2/1/0LfCeay9qnsskRpoFj8uSpdt+E+mnREDqIR/34teYvvPy9SUEW5uA6ffqfmQa/i5P30w/LrUWtZl3+4vyvNyvr+z59d8/D4U/Vhfjb3Svp0UhvylW4pn9YyW/OnXreyt5UXt/rLRXlvljxb4a2gv0q5dPxx9xnPvSXxoNoVAKoTEapWmEJGl6QyM4vFnmBY1ucIykMZLaYMuc22A0jcEk8R34J5S/uPvMFPqBukX6zmi0ZbMmjdoP/af03tNfD0SRGrXgKIqxLor5NECNax54A0pYDsVmkBVhf9qIdJ4U196p1RASzaCF4FN6ajkRMUPr2nA5Le7j9U6CyOyUJANeRTDhIL1wtW5amML9DT+0dkY5jTtBWoBvNn2WwrZ6Zi1Tc8D00IUutG4YHqBqF7GIeOnDdBJRu/RdiUkQJJfhoEVtWC9Cz0DuDtFxoJMxNQFWbvjHq6DKpyF1+Qge9wo5xpiu2LhYcI289yp5g4lKljDZ/pbvN3mDcX6WNZWBBDgr7mW2xB5td4yj1B+8c3TcF2B9Kk7KKBGCwxFlHORjfSr1/FKGWlo2kTQns1xGDDa1HtwJ6qQQGHa57usWM9V079QSz7y+vl3yH3n+U/5WnZ97+sdyvY+cH8/+oPgAu98ot8pbH6v4YAjqc++ziWrthm7WUPwAJJ267OjwlmXKTERc6KIcNh5j5LEmrObsQ+S6kEdawTnztLnvUHQ+1vuFNYlN4xbm7hwwlmso9jf6lF0idOgyU5DL3Fbu9KkCPITDd06QdH7g9DuqtT1P9kI6mBuo6qWhGzYLoemo77jwLseo0GHYrgx3elKuOdXV5+4UtMlxeHDyWqccpXi0J4U6JaT0AIFuBmx/yPe7AxwyNhNUhzp8iOeLTwqZR6i17ln4la1BSBMuJbCFROq0vS7z8K45dMM4kodAyCkUgD1E3SFaG0YbzhiFwWlAjrsOGrl1gF7wu7AGIUlp0TXPM/m6awnqbLdQnlXFgzWPuc1NPAeZ1hW/PyLLEKqAYnon87LysNbJ+HAbZM/GRn0GpVS6VMcafMTEpDddgdgau10wjEIybMQRpxz0oJ4EKCn4FhlZTo509gQ3s09xLS4ncnI/onsST1mmNrumMwllXQ0PaA9UokUHk6oeoq3AB1T0oH4WNOAM/Np/eIGqcQczAqnIX62rOV1SShMPJ02FCsl/qK5Lei5QCApS7nLNzXzJ2Nopv6ni1CS3O12tXeR+WVolzUoUOu8NUud1/pHoO6G9Hk9lUPKsCu+NA2nRk8hjNt6Mh6zMrYOPSgdBPVvimuUtf1Yi3Z+0mc7jxDck3t24xaXK3aMBsAhBZMI8CEQz9SJybuBguCh8vYE4UmYtRQeWcAxKyiDXNwbM+QRZg01b6yhBnGPmctCAInEy3Bl8cpmix4pCOWDUyCBHayMcIVWd2tmuUzXSJoPLD5xMTH0crR3riE16jRjuYKGJvex8fXanbgONpeAlQuJAtjyLDcldiuRi+oTAxAisWYfqPpetLAVtrLqsBIVtkOhWfqVU57BjpBg50NJGepCNQDfEpcAcx/eNHo8sJGmXunKYdM3ArtLJJddOKfszuS/rPGcND5k0bCwtsXXOOF/VOUkJVOrucwD5WShreJebfM1grJmOJBgeSpsPg7WGRKMqhTu8Xl63V1sWk1v+KGKTqNOevIGbEKrQfmZ6Uk3LdV0RM4bW1E1Tz4EBZ7O9ltiAJtYQY/pK65/r+bi+hUbIIfdCDCiWrAXE4mzQOzYlW4+87BJvGdSSY1cBf7yaaeI4eRjvVE9JbhdbwLGHvREM6szursGVAbbmImolbvrRVxXggLtGWIVIrPWI04I8QqXOFKZT3Z2z4lDIBnvGshHkuIn6jV1pczyfAWzEWUey5DoiJ3hObuqDO1uKyQvgPHLhfkPm5FBqPl6LSHVPTzlYWCD6x30f2kQ083lF+KljILhGXwyqPx7NmdjzddMHNOP5PSn3OzwyOioe5ApvAUsfEMhptH3ZjcUUnq+RYmvTUbalnc9e4aw3iKGItWXNDeys348HaCPgRyTcgCuJbCjlNB+HCAeFjnkWcJi9R57qwXTHeM93ySALAYKeMjkTb4rhULcUIzUnb80buc9qPT3YEuZ7HXSBsbiQQLnXlrWUJwvXRuHnw91Kamd2HtakQZguC1m8pqW4uqhu4LctKCLfQrJu0gdu2i+dLGOYDe+nFj+UFieliY5SNj1gFMTcryYpj9WBnW0BJg82qIyILaNJ6YoHj5CK5xLmST32RdJafIqv90m8jL2p2WEIAWmy74kKOp6uZyWx8CH0kBSBN3NaUkpphQ+01YbNsbSpwz2Cy3KCJuXez0zG4+rDvUj8YNK8LBil2HCaj/mqmYuUHN7Vercker3z6JjJiYZSUq5V9Eh6rcfpmEvsO75Rz93Z13b9YO5zZxfS55lnivPyFeCateswE36J/eTUuY+xwqid6ME5cewrnWW8DSe52XV5PuwGbz+P9vvS/WVV/qT6tnp//UYsyl9/J98/MJ8/va//BQ== SigAlg = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 Signature = gwTQM9St1EnHg0CC0aEuKTHWf8tJvyHcMTHchpymMmPJuV2l/hkmS57phozphajxHZzOW4ynx/dlJWXLvIEqziRLtCoiWRH1/pzpcJsBC2Mm9RH/WrWHhITIedjS4SMiVdi9Ud6ibHO+5n7eB05cBlhhMMvtMrUPrDo2C4itF2/TBSz8YGNWOTrAGu/6WEwBPzPxpu+P1yyUL4lDcFtWN1O4PL357xgSVo5q8vV8cQoOc6UeKRzznQEQOoU9kchKI8DhDwxu/VPZRrDXLiRe07yDO+XMIiDNluBZ9UThJHGsAEcTWaiJBzxUiXtzutIOj+0UNr8aD65Yzk0eQ3PIIQ== SAMLResponse=pVJNb8IwDP0rVe5pmrQUiEqlCS5I22UgDrtMIXVGtDbp6nTaz18/xqRx4LJbnu1nv2enQNXUrXwGbL1DiPa7DXnV+mwWaX6mKhcpzfJc0VWeZ3TFU7OEM+RZdibRCTq03m2IiBMS7RF72DsMyoUhlAhOkzUV66NIpMhkmsQZX76QaAcYrFNhYl5CaFEy1uh3gLixrqr9m9Wxalum+nBhI3Qk2o7axr5956RXaFE61QDKoOXh4elRDhKknotk77AFbY2FapDlrtaOfkOammtuTEp5rgXl3GjKjVhQvhScVzzjXACJvpraoZwWc39i2/ngta9JWUz2u5l6n6QQoRvtk3K0P7o3WlUGrQvx8Iy179p43oj2DRtTbKB8Wg3IQtdjKNg8rizm6x2CCj3+RVtfQXRSdQ/35eBU/fMBKujIP9t89MOBd+Cm7bOyYLfdbkK/8Hqn8hs=&Signature =kJvFbnKgsY+qCGvG/WI0S0vmNJoRtaKWllzMDuXiD+0qlWM4V/ZETRPlBrpm6NWmvdrr4PsxavHv7H6PmQkZDyeGYw9MxrwnJI0dCVtLWsZENQxU8BX2hpPxTv4DGi7Ax4Gz0J+sZiEwbXi8r0OWp36JbK+U0WPklm02CQXxvKQ7AzsdfSHQIRdq8dVrVAkL6ZzGVICpx9xd5Vfsu3ZsjsfTE/8JJ1ON47P94UVndQODI/t+HCSEDD67zWgQRIh2Brk5WWMFG4sEyIR/tirq8JKqZ2RvJIHzvQkWQTjX8eH3oxI3AHviohOrQc1sYIuUhEh1nY01X/cAOgeL1JXSaA==&SigAlg=http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 A: The easiest answer is to use https://github.com/onelogin/python-saml and simply call the appropriate function. That being said the basic steps are: * *concatenate: SAMLResponse= RelayState= (only if it was in the URI) SigAlg= These should be the original un-decoded URI (exactly as it was sent) seperated by &. For example: signed = SAMLResponse=babkabdabd&RelayState=/main&SigAlg=http...rsa-sha1 *you need to then extract the signature from the URI and assign it to a variable: sig = base64decode(Sugnature) Then depending on the SigAlg you need to verify the Signature against the signed data for the algorithim (rsa-sha1 for instance): This Perl function is reasonably easy to read to see the steps: https://github.com/perl-net-saml2/perl-Net-SAML2/blob/26c53c1241caf86afc15d33d506c0ab573704fee/lib/Net/SAML2/Binding/Redirect.pm#L170 I could not quickly find the same for the Python library. You should know however tat while you can use HTTP-Redirect in practice the assertion is normally to large to fit in the URI so it is often done via a HTTP-POST Tim
doc_23538104
Ctrl-Alt-L can format code one-time, but is there a way to format code as you're writing it? If not, is there a Python IDE where you can? A: You can use black with PyCharm and force it to format on each file save, see the official docs https://black.readthedocs.io/en/stable/editor_integration.html
doc_23538105
var imageBitmap = GetImageBitmapFromUrl(mydata["newsimage1"].ToString()); imageView1.SetImageBitmap(imageBitmap); from a website like blogger it works and the application view it without any problems. For example this image url: http://4.bp.blogspot.com/-_PdNK07R8wQ/VzdAiJtOdqI/AAAAAAAABLE/AzxlzGVbL_Y5HCKH3ckGtEr7pwkKvhaJQCK4B/s1600/2.png It works fine, but when I put an image that uploaded into my php webhost it does not work! For example this url: www.ihled.eb2a.com/gcmt/NewsImages/170108022726.jpg Anyone have any idea about that ?
doc_23538106
Is there any tutorial that can help me with this? BTW, very newbie developing for android and using APIs. Aditional info: I'm planning to do an internal map of a mall (including parking lot, coffee place, etc). But I want the app work only if the user is inside the mall. Comments about this: Someone told me something about we can use shapes while working with Google Maps API. Can't resolve how to. Thanks a lot.
doc_23538107
I'm using the odfpy library for manipulating .odt files, but all the examples and documentations I can find are more concerned with adding things to the document, getting the style in a given element, replaing something etc etc. I can't find any documention or examples about how to simply get the text in a doc. Edit: Thank you karatekraft, your answear was just what I needed. Your code seems to get the total nr of characters rather than words, but that at least was within my abilities to do! New def count_words_in_file(file_list) looks like this! (Currently, it only checks the document added in the file_path var, but its to late at night to fix now.) def count_words_in_file(file_list): # This function will open all found .odt files, count the words, and then sum the total # ADJUST SO IT DOES THE SEARCH FOR ALL FILES file_path = "test.odt" from odf import text # Read document document_text = load(file_path) # Get all paragraphs in document all_paragraphs = document_text.getElementsByType(text.P) final_word_count = 0 # For each paragraph, extract text and count number words. for paragraph in all_paragraphs: text = teletype.extractText(paragraph) words = text.split(" ") while '' in words: words.remove('') print(words) final_word_count = final_word_count + len(words) print(f"Final word count: {final_word_count}") # This program will count the number of words and .odt docs # in a folder and all its sub-folders. For ease of use it will check the folders above its # current directory. # Import the needed libraries import os from odf.opendocument import OpenDocumentText from odf import text # Make relly fucking sure the ODFPY module is installed, was pain in asshole. fuck programing def main(): # This variable is the current location of the script, attained with the os.path current_dir = os.path.dirname(os.path.abspath(__file__)) # This variable changes the current_dir into the dir above the current one. above_dir = current_dir + "\.." # Call the function to scan for .odt files file_list = scan_for_files(above_dir) # Call the function to open and count the .odt files count_words_in_file(file_list) def scan_for_files(above_dir): # This list will store the path to all files found. file_list = [] # This for-loop will go through all the folders that can be found for folder, subfolder, files in os.walk(above_dir): for file in files: complete_path = os.path.join(folder, file) file_list.append(complete_path) return(file_list) def count_words_in_file(file_list): # This function will open all found .odt files, count the words, and then sum the total for file in file_list: if file.endswith(".odt"): textdoc = OpenDocumentText() for paragraph in textdoc.body.childNodes: print(paragraph) main() A: You can try this. It identifies all paragraphs, extracts the text from each paragraph, and gets total word count. from odf import text, teletype from odf.opendocument import load file_path = "my_file.odt" # Read document document_text = load(file_path) # Get all paragraphs in document all_paragraphs = document_text.getElementsByType(text.P) final_word_count = 0 # For each paragraph, extract text and count number words. for paragraph in all_paragraphs: text = teletype.extractText(paragraph) final_word_count = final_word_count + len(text) print(f"Final word count: {final_word_count}")
doc_23538108
A: You can find different cellular networks in emulator settings, such as Full, LTE, EDGE, etc. The signal strength can also be changed. Changing that would give you an idea of how your app behaves. You may also change some emulator GPU or RAM settings (-gpu <value>, -no-accel, -lowram, etc.) and use ARM images instead of x86 to force slower emulation but their help understanding how you app experience would be on a slower device might be limited. Finally, you can also pass options to qemu (see the list running emulator -qemu -h).
doc_23538109
When I execute the code in CMD, it returns no response except for: echo "test 1"; echo "test 2"; My Code: <?php // Author: Labrador // Date: 19-07-2020 // Purpose: To modify the contents of a binary checkBin(); // This function checks the input file to see if it is compatible with the program function checkBin() { //Open file in current directory $file = file_get_contents(dirname(__FILE__). './file.bin'); echo "test 1"; //Convert file to hexadecimal $ori = strtoupper(bin2hex($file)); $ori_hex = str_split($ori, 2); $ori_hex_length = count($ori_hex); $string_loc = 0; echo "test 2"; // Search for identification tag for ($i = 0; $i < ($ori_hex_length - 1); $i++) { if (hexdec($ori_hex[$i]) == hexdec("36")) { if (hexdec($ori_hex[$i + 1]) == hexdec("30")) { if (hexdec($ori_hex[$i + 2]) == hexdec("36")) { if (hexdec($ori_hex[$i + 3]) == hexdec("59")) { if (hexdec($ori_hex[$i + 4]) == hexdec("30")) { { $string_loc = 0x00000000 + $i; echo "Binary Identified as compatible Software <strong>0x".$string_loc."</strong> \n"; } } } } } } } // Return false if not found if ($string_loc==0) { return false; echo "Not Found!"; } echo "test 3"; } ?>
doc_23538110
I do it with knex and the fronted is done with vue js. Everthing works but the post not and when i put something in the form it comes Duplicate entry '1' for key 'PRIMARY' how can i fix that? exports.up = function(knex) { return knex.schema.createTable('series', function(table) { table.increments('id').unsigned().primary() table.string('text').notNullable() table.enum('rating', ['good', 'not bad', 'bad']).defaultTo('not bad') table.string('comment').notNullable() }) }; exports.down = function(knex) { return knex.schema.dropTableIfExists('series') }; The frontend template> <div class="Series"> <h2>Table</h2> <table id="tabelle" border="1"> <!-- Header --> <tr> <th>text</th> <th>rating</th> <th>comment</th> <th>action</th> </tr> <!-- series List --> <tr v-for="series in series" :key="series.id"> <td> {{series.text}}</td> <td>{{series.rating}}</td> <td>{{series.comment}}</td> <td><button @click="removeData(series.id)">Löschen</button></td> </tr> </table> <input type="text" name="text" v-model="series.text"> <br> <select name="rating" v-model="series.rating"> <option>good</option> <option>not bad</option> <option>bad</option> </select><br> <input type="text" name="comment" v-model="series.comment"> <br> <button @click="postData" >Post</button> </div> </template> <script> import axios from 'axios'; export default { name: 'Series', data() { return { series: {}, } }, methods: { getData(){ axios.get('/api/series').then((response) =>{ console.log(response.data); this.series = response.data; }) .catch((error) => { console.log(error); }); }, postData(){ axios.post('/api/serie/create', this.series) .then((result) => { console.warn(result) }).catch((error) => { console.log(error); }); }, removeData(id){ axios.delete('/api/serie/delete/'+id).then(()=>{ this.getData(); }) } }, mounted() { this.getData() }, } </script> endpoints app.post('/api/serie/create', (req,res)=> { console.log("create"); console.log(req.body); let serie = req.body knex('series').insert(serie) .then(results => res.json(results)) .catch(err => { console.error(err.sqlMessage) res.status(500) res.json(err.sqlMessage) }) }) enter image description here A: This error tells you like what each time you want to save in your database, the primary key is duplicated because your "primary key column" doesn't increment. Check that your "primary key column " is auto-incrementing. If not, or modify to auto-increment or increment it manually.
doc_23538111
template<typename MyExplicitelyLongTemplateParameter> class C { public: typedef MyExplicitelyLongTemplateParameter P; // Use "P" and keep your sanity. }; My question is, can one do the same with template template parameter? template<template<typename> typename MyExplicitelyLongTemplateParameter> class C { public: typedef /* ??? */ P; // Use "P" and keep your sanity. }; A: You can't create a typedef, no, but you can shorten the name: template <template <typename> typename MyExplicitlyLongTemplateParameter> class C { public: template <typename T> struct P { typedef MyExplicitlyLongTemplateParameter<T> Type; }; // Use "P<T>::Type" and keep your sanity. }; A: In the current standard, you can't typedef a template. In the new, upcoming standard, you will be able to....
doc_23538112
I have the master branch, where all the main code resides, and the design branch, where the layout of the rails application is built by the design team. They have added a folder called "photoshop" to the public folder to keep their sources for the images also under version control. But I don't want this folder to be copied on merge to the master branch because, well, it is not needed. Apparently, the way to do this is through a merge driver. So, I've created the "ignore" driver: [merge "ignore"] name = always ignore during merge driver = ignore.sh %0 %A %B And created the ignore.sh file on my $PATH: exit 0 I've created the .gitattributes file inside public/, because the photoshop folder should be ignored in whole and it is going to appear under public/: photoshop merge=ignore photoshop/ merge=ignore photoshop/* merge=ignore photoshop/**/* merge=ignore As you can see, I've tried several different patterns to ignoring the whole folder, but it does not work. I believe this is because there is no folder on the master branch, so there's no conflict and so git doesn't use the ignore driver. Is there a way to achieve this without having to create a public/photoshop folder on master? Thanks! A: As suggested by my other answer, here goes the extended, generalized, industrial-strength version of the solution. (yes, I was bored at home and had nothing else better to do :P) This script will add a new, detached commit based on your local design branch, so it won't affect neither the design repository or your design branch. The commit will have all desired files removed. Then it performs the merge. For those too lazy to read the full code, the "core" of these steps can be simplified as: original=$(gitbranch HEAD) # current branch name, or sha1 if not in a branch branchsha=$(gitsha "$branch") # sha1 of a ref, to force detached commit git checkout "$branchsha" && git rm -rf "${files[@]}" && git commit -m "$msgcommit" && newsha=$(gitsha HEAD) && git checkout "$original" && git merge -m "$msgmerge" "${mergeopts[@]}" "$newsha" And here is the full script: (a bit modified to cope with the weak and limited SO's syntax coloring, so it's better to get the pristine source from the link below) git-strip-merge #!/bin/bash # # git-strip-merge - a git-merge that delete files on branch before merging # # Copyright (C) 2012 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not see <http://www.gnu.org/licenses/gpl.html> # # Answer for "How to setup a git driver to ignore a folder on merge?" # See http://stackoverflow.com/questions/3111515 #Defaults: msgcommit="remove files from '<branch>' before merge" msgmerge="Merge stripped branch '<branch>'" verbose=0 quiet=(--quiet) usage() { cat <<- USAGE Usage: $myname [git-merge options] [-M <commitmsg>] <branch> FILE... USAGE if [[ "$1" ]] ; then cat >&2 <<- USAGE Try '$myname --help' for more information. USAGE exit 1 fi cat <<-USAGE "git-merge that delete files on "foreign" <branch> before merging Useful for ignoring a folder in <branch> before merging it with current branch. Works by deleting FILE(S) in a detached commit based on <branch>, and then performing the merge of this new commit in the current branch. Note that <branch> is not changed by this procedure. Also note that <branch> may actually be any reference, like a tag, or a remote branch, or even a commit SHA. For more information, see <http://stackoverflow.com/questions/3111515> Options: -h, --help show this page. -v, --verbose do not use -q to supress normal output of internal steps from git checkout, rm, commit. By default, only git merge output is shown. Errors, however, are never supressed -M <message>, --msgcommit=<message> message for the removal commit in <branch>. Not to be confused with the message of the merge commit, which is set by -m. Default message is: "$msgcommit" -m <message>, --message=<message> message for the merge commit. Since we are not merging <branch> directly, but rather a detached commit based on it, we forge a message similar to git's default for a branch merge. Otherwise git would use in message the full and ugly SHA1 of our commit. Default message is: "$msgmerge" For both commit messages, the token "<branch>" is replaced for the actual <branch> name. Additional options are passed unchecked to git merge. All options must precede <branch> and FILE(s), except -h and --help that may appear anywhere on the command line. Example: $myname design "photoshop/*" Copyright (C) 2012 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> License: GPLv3 or later. See <http://www.gnu.org/licenses/gpl.html>" USAGE exit 0 } # Helper functions myname="${0##*/}" argerr() { printf "%s: %s\n" "${0##*/}" "${1:-error}" >&2 ; usage 1 ; } invalid() { argerr "invalid option: $1" ; } missing() { argerr "missing ${2:+$2 }operand${1:+ from $1}." ; } # Option handling files=() mergeopts=() for arg in "$@"; do case "$arg" in -h|--help) usage ;; esac; done while (( $# )); do case "$1" in -v|--verbose ) verbose=1 ;; -M ) shift ; msgcommit=$1 ;; -m ) shift ; msgmerge=$1 ;; --msgcommit=* ) msgcommit=${1#*=} ;; --message=* ) msgmerge=${1#*=} ;; -* ) mergeopts+=( "$1" ) ;; * ) branch="$1" shift ; break ;; esac shift done files+=( "$@" ) # Argument handling msgcommit=${msgcommit//<branch>/$branch} msgmerge=${msgmerge//<branch>/$branch} [[ "$msgcommit" ]] || missing "msgcommit" "MSG" [[ "$branch" ]] || missing "" "<branch>" (( ${#files[@]} )) || missing "" "FILE" ((verbose)) && quiet=() # Here the fun begins... gitsha() { git rev-parse "$1" ; } gitbranch() { git symbolic-ref "$1" 2> /dev/null | sed 's/refs\/heads\///' || gitsha "$1" } original=$(gitbranch HEAD) branchsha=$(gitsha "$branch") trap 'git checkout --quiet "$original"' EXIT git checkout "$branchsha" "${quiet[@]}" && git rm -rf "${files[@]}" "${quiet[@]}" && git commit -m "$msgcommit" "${quiet[@]}" && newsha=$(gitsha HEAD) && git checkout "$original" "${quiet[@]}" && git merge -m "$msgmerge" "${mergeopts[@]}" "$newsha" Enjoy! An image is worth more than a thousand words... Before merge: After merge: Note that "design" branch tip wasn't affected at all, even being a local branch, thanks to the detached commit trick. Other than that, both commits (the removal and the merge) are regular commits, with suitable commit messages and parents. And "master" branch is clean of any undesired files. A: Not an answer per se, but a few notes about .gitignore: it will not help you in your scenario. .gitignore is for ignoring files from the working tree to be added to index (staging area). So it is only effective when you use git add <files>, and it can still be overridden using git add --force <files>. It is meant just as a convenience to prevent unwanted files from being added, but it has no effect on files inside the repository In your scenario, .gitignore is not needed, since you don't have any local ./photoshop folder, so you will never have any photoshop files to add to your master branch. It wouldn't hurt, however, to create one just in case. And for the design team .gitignore is not welcome, since they want photoshop files to be added to their branch. So, since merge deals with committed data, and ./photoshop files are already inside the repository, your approach of using a a merge driver was correct. The problem is... by default a merge driver is only triggered in case of conflicts. And, since master branch does not have any ./photoshop folder or files, there are no conflicts at all, they are cleanly merged. So your merge driver also had no effect, regardless of your path patterns (by the way, your 2nd one, photoshop/, was the correct one). I don't know if git merge can be configured to trigger a merge driver even for non-conflicting files, but it's worth googling for. As I've said before, my answer is not a true solution to your problem. I just hoped to shed some light on the subject, explaining why your attempts using merge driver and .gitignore have failed. I suggest reading more about (configuring) merge drivers. Also submodules is worth investigating. Hope this helps! UPDATE Maybe my other answer will help you: Usage: git-strip-merge [git-merge options] [-M <commitmsg>] <branch> FILE... git-strip-merge Enjoy! A: Did you try adding a .gitignore file in your master branch, to ignore any photopshop directory content ? Then a merge from design to master shouldn't add that new directory in master. If this works, you still needs a merge driver, but this time to manage the content of the .gitignore file.
doc_23538113
{ "array": [1, 2, 3, 4], "test1": "testing123", "test2": "testing_another" } { "array": [4, 3, 2, 1], "test1": "testing123", "test2": "testing_another" } And with an aggregation I'd like to get a result that contained { "array": [5, 5, 5, 5] } The only way I've thought to do this would be to store the arrays as a hash whose values could then be summed in the aggregation: { "array": {"0": 4, "1": 3, "2": 2, "3": 1} } { "array": {"0": 1, "1": 2, "2": 3, "3": 4} } So that the aggregated result looks like (using sum on "0", "1", "2", "3" fields) { "array": {"0": 5, "1": 5, "2": 5, "3": 5} } But it seems that as the hash size increases elasticsearch slows down on writes, probably due to that fact that is indexing these fields thinking that I might query on them. This is not necessary, I only need to be able to get the merged (summed) result on the way out. Is this a reasonable assessment of the situation? If so, is there a way in elasticsearch to specify that a given field will not need to be queried on? A: @cmwright it sounds a bit weird to ask for something that was built mainly for search to do not allow a field to be searchable :) nevertheless, what you can certainly do is to define a field in your index to do not be analyzed through a mapping. More info here Elastic Search Mapping Core Types. I dont give you a direct answer to your question but I hope that at least you can get some clues to figure out a possible solution. A: You can specify your array to be not analyzed for search with the help of mapping { "array": { "type": "string", "index": "not_analyzed" } } where array being your field name. You can read more on elasticsearch refrence for mappings at Mappings A: I’m not sure if the size of the hash is what caused the issue, but I found two field mapping parameters in the elasticsearch 6.2 docs that allow you to specify that a field should not be queried on. * *Use index=False to disable indexing for that specific field. Fields that are not indexed are not queryable. *Use enabled=False to disable indexing (and ALL processing) for that field and all of its children (Only applicable to object fields) Sources: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/mapping-index.html https://www.elastic.co/guide/en/elasticsearch/reference/6.2/enabled.html
doc_23538114
I know that old spring-seurity-core plugin is not compatible with Grails 3.0 version. Thus I've tried to follow this tutorial: http://spiesdavid.blogspot.fi/2015/03/grails-3-app-with-security-part-1.html I've added the compile line in build.gradle file in dependencies. I've also added the logger line in logback.groovy file. Problems start after that. There is no such file as SecurityConfiguration.groovy and there is no org.springframework.security package so I can't import them and it gives an error. So I can't create the file either. A: So I am assuming that your question is: «How do I get this to work?» * *spring security plugin 3.0.0 (for grails 3.x) was released just a few days ago. Documentation is quite good. Start here: https://grails-plugins.github.io/grails-spring-security-core/ *There are some problems with Intellij. I tried to add spring security to a slightly older grails project (started with intellij 15.0.1 and grails 3.0.9). Adding the dependencies was successful and rebuilding it made the plugin available, also in the grails console. But when I launched a debug instance of the application directly from the IDE, it would not show spring security among the loaded/installed plugins. I made a pristine project with IntelliJ 15.02, grails 3.0.10 and just copied my code over to the new project. Now it works. A: Note there are some issue with IntelliJ not major. do the following it will work: * *on your build.gradle add compile 'org.grails.plugins:spring-security-core:3.0.0.M2' *run command compile *run comand s2-quickstart yourAppName User Role *now you should see "application.groovy" file under conf folder *as usual use @Secured annotation in your controller
doc_23538115
Initially it is in the head section, which is the default for Rails 5.2 I assume. The problem with this was that it wouldn't load the JS files in my assets/javascripts folder. I was advised to move the tag to somewhere that was after the <%= yield %> part but still within the body. This worked fine and the JS from that folder loaded ok. The problem now is that I am using the leaflet-rails gem and the map will not load when the javascript_include_tag is in the body... Is there anything I can do so that both these things work? My assets/javascripts/locations.js var currentLocation = document.getElementById('coordinatesStore'); document.querySelector('.add-button').addEventListener('click', () => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => { currentLocation.value = latitude + ", " + longitude; }); } else { currentLocation.value = "Geolocation is not supported by this browser."; } }); A: The problem here is you're trying to attach event handlers to elements that do not yet exist. Solution is standard: load the code in the head, but postpone running it until page loads. // wrap your code in a function, so that it can be executed later function attachLocationClickHandlers() { Array.prototype.forEach.call( document.querySelectorAll('.add-button'), (button, i) => { // do something on click } ); } document.addEventListener("turbolinks:load", function() { attachLocationClickHandlers() }) (or something similar to that. I don't know javascript)
doc_23538116
https://github.com/rainmanwy/robotframework-SikuliLibrary 'Set Ocr Text Read' & 'Get Text' keywords are not working in RobotFramework.Error msg is gives as picture below. Similar error msg for 'Set Ocr Text Read'. Please click here to see error msg for 'Get Text' keyword But in keyword documentation of Sikuli these 2 keywords are mentioned. Sikuli Library is imported properly. Others Sikuli keywords are working fine except these 2. Need your kind help. Thanks in advance. A: I just had a look at SikuliLibrary In fact the Keyword "Get Text" was only added at September 12th this year. Since the latest version 0.1.5 on pypi is from May 16th, "Get Text" is not included in the package you get with pip. You have to follow the steps mentioned on GitHub under Build With Maven to get the latest version containing the changes made after May 16th.
doc_23538117
AndroidManifest.xml <uses-permission android:name="android.permission.SEND_SMS"/> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.WRITE_SMS"/> MainActivity.java (onCreate) CheckAndGetPermission(Manifest.permission.SEND_SMS, 10); CheckAndGetPermission(Manifest.permission.RECEIVE_SMS, 13); CheckAndGetPermission(Manifest.permission.MODIFY_PHONE_STATE, 11); CheckAndGetPermission(Manifest.permission.READ_PHONE_STATE, 12); private boolean CheckAndGetPermission(String permission, int requestCode) { if(ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, "Permission already granted " + permission , Toast.LENGTH_LONG).show(); } return true; } MainActivity.java (onResume) protected void onResume() { super.onResume(); smsSentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("SENT", "In Broadcast Receiver"); } }; smsDeliveredReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("DELIVERY", "In Broadcast Receiver"); } }; registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT")); registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED")); } Update: @mike-m asked to see pending Indent. Here is the code sending SMS. private void SendSampleSms(String uuid) { SmsManager smsManager = SmsManager.getDefault(); // Intent sendIntent = new Intent(); Intent sendIntent = new Intent("SMS_SENT"); sendIntent.putExtra("type", "SMS_SENT"); sendIntent.putExtra("uuid", uuid); PendingIntent piSent = PendingIntent.getBroadcast(MainActivity.this, 100, sendIntent,0); // Intent deliveryIntent = new Intent(); Intent deliveryIntent = new Intent("SMS_DELIVERED"); deliveryIntent.putExtra("type", "SMS_DELIVERED"); deliveryIntent.putExtra("uuid", uuid); PendingIntent piDelivered = PendingIntent.getBroadcast(MainActivity.this, 100, deliveryIntent,0); smsManager.sendTextMessage("*1111",null,"Sample Message",piSent,piDelivered); } I was able to fix the problem. I was not setting action while creating Intent for PendingIntent, as seen in the lines commented in above method. After setting action, the broadcast receivers started receiving messages.
doc_23538118
And the console says this: SEVERE: Class [ Lorg/slf4j/Logger; ] not found. Error while loading [ class managedbeans.UploadController ] WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: Lorg/slf4j/Logger; SEVERE: Exception while invoking class org.glassfish.ejb.startup.EjbDeployer load method java.lang.RuntimeException: Unable to load EJB module. DeploymentContext does not contain any EJB Check archive to ensure correct packaging for C:\jeeAplicationServer\glassfishv3\glassfish\domains\domain1\eclipseApps\GarbageTheWeb at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:133) at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:63) at org.glassfish.internal.data.ModuleInfo.load(ModuleInfo.java:175) at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:216) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:662) SEVERE: Exception while loading the app java.lang.RuntimeException: Unable to load EJB module. DeploymentContext does not contain any EJB Check archive to ensure correct packaging for C:\jeeAplicationServer\glassfishv3\glassfish\domains\domain1\eclipseApps\GarbageTheWeb at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:133) at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:63) at org.glassfish.internal.data.ModuleInfo.load(ModuleInfo.java:175) at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:216) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:662) The component that i am tiying is the simple file upload from prime faces, it looks exacty as in this link: http://www.primefaces.org/showcase/ui/fileUploadSingle.jsf Am i ussing the correct impor statement? import org.slf4j.Logger; import org.slf4j.LoggerFactory; A: I found the answer here: http://seam-framework.2283336.n4.nabble.com/glassfish-and-Seam-Faces-error-td3272490.html For some reason it needs this 2 jar files in the classpath: slf4j-api-1.6.1.jar slf4j-simple-1.6.1.jar Sorry :)
doc_23538119
My first impression is to create a python script to traverse each directory, compute a hash of each file, and if the hash has changed, copy the file over to the new subset of files. Is this a proper approach? Am I neglecting any tools out there which may do this already? I've never used it, but maybe use something like rsync could be used? Thanks Edit: The important part is that I am able to compile a subset of only those files were changed-- so if a only 3 files have changed between versions, I only need those three files copied to a new directory... A: It seems to me that you need something as simple as that: from os.path import getmtime from os import sep,listdir rep1 = 'I:\\dada' rep2 = 'I:\\didi' R1 = listdir(rep1) R2 = listdir(rep2) vanished = [ filename for filename in R1 if filename not in R2] appeared = [ filename for filename in R2 if filename not in R1] modified = [ filename for filename in ( f for f in R2 if f in R1) if getmtime(rep1+sep+filename)!=getmtime(rep2+sep+filename)] print 'vanished==',vanished print 'appeared==',appeared print 'modified==',modified A: That is one completely reasonable approach, but you are essentially reinventing rsync. So yes, use rsync. edit: There's a way to create "difference-only" folders using rsync A: I like diffmerge, it works great for this purpose. A: I have modified @eyquem answer a bit! Arguments can be given as python file.py dir1 dir2 NOTE : sorts on basis of modification time ! #!/usr/bin/python import os, sys,time from os.path import getmtime from os import sep,listdir ORIG_DIR = sys.argv[1]#orig:-->/root/backup.FPSS/bin/httpd MODIFIED_DIR = sys.argv[2]#modified-->/FPSS/httpd/bin/httpd LIST_OF_FILES_IN_ORIG_DIR = listdir(ORIG_DIR) LIST_OF_FILES_IN_MODIFIED_DIR = listdir(MODIFIED_DIR) vanished = [ filename for filename in LIST_OF_FILES_IN_ORIG_DIR if filename not in LIST_OF_FILES_IN_MODIFIED_DIR] appeared = [ filename for filename in LIST_OF_FILES_IN_MODIFIED_DIR if filename not in LIST_OF_FILES_IN_ORIG_DIR] modified = [ filename for filename in ( f for f in LIST_OF_FILES_IN_MODIFIED_DIR if f in LIST_OF_FILES_IN_ORIG_DIR) if getmtime(ORIG_DIR+sep+filename)<getmtime(MODIFIED_DIR+sep+filename)] same = [ filename for filename in ( f for f in LIST_OF_FILES_IN_MODIFIED_DIR if f in LIST_OF_FILES_IN_ORIG_DIR) if getmtime(ORIG_DIR+sep+filename)>=getmtime(MODIFIED_DIR+sep+filename)] def print_list(arg): for f in arg: print '----->',f print 'Total :: ',len(arg) print '###################################################################################################' print 'Files which have Vanished from MOD: ',MODIFIED_DIR,' but still present ',ORIG_DIR,' ==>\n',print_list(vanished) print '-----------------------------------------------------------------------------------------------------' print 'Files which are Appearing in MOD: ',MODIFIED_DIR,' but not present ',ORIG_DIR,' ==>\n',print_list(appeared) print '-----------------------------------------------------------------------------------------------------' print 'Files in MOD: ',MODIFIED_DIR,' which are MODIFIED if compared to ORIG: ',ORIG_DIR,' ==>\n',print_list(modified) print '-----------------------------------------------------------------------------------------------------' print 'Files in MOD: ',MODIFIED_DIR,' which are NOT modified if compared to ORIG: ',ORIG_DIR,' ==>\n',print_list(same) print '###################################################################################################' A: Including Subfolders and comparing hashes of the files (>Python 3.11 required) from os.path import isdir,normpath from os import sep,walk import hashlib rep1=normpath(input('Folder 1: ')) rep2=normpath(input('Folder 2: ')) def hashcheck(fileloc1,fileloc2): # only works from python 3.11 on if isdir(fileloc1) or isdir(fileloc2): return False if fileloc1[fileloc1.rfind(sep):]==fileloc2[fileloc2.rfind(sep):] else True with open(fileloc1,'rb') as f1: f1hash=hashlib.file_digest(f1,"sha256").hexdigest() with open(fileloc2,'rb') as f2: f2hash=hashlib.file_digest(f2,"sha256").hexdigest() return (f1hash!=f2hash) R1=[] R2=[] for wfolder in list(walk(rep1)): R1+=(wfolder[0].replace(rep1,'')+sep+item for item in wfolder[2]) for wfolder in list(walk(rep2)): R2+=(wfolder[0].replace(rep2,'')+sep+item for item in wfolder[2]) vanished = [ pathname for pathname in R1 if pathname not in R2] appeared = [ pathname for pathname in R2 if pathname not in R1] modified = [ pathname for pathname in ( f for f in R2 if f in R1) if hashcheck(rep1+sep+pathname,rep2+sep+pathname)] print ('vanished==',vanished,'\n') print ('appeared==',appeared,'\n') print ('modified==',modified,'\n') input()
doc_23538120
The following question http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/260d8536-c39f-41ec-b181-4d452cf054b3/ shows how to change SQL membership provider at runtime. However if I do it with System.Web.Providers.DefaultMembershipProvider then it doesn't work as it doesn't seem to have have _sqlConnectionString field to set. Any ideas? A: I used the code from the following blog post http://fabriccontroller.net/blog/posts/asp-net-universal-providers-and-the-windows-azure-service-configuration/ Basically I inherited defaultmembershipprovider override its Initialize method accessed its connectionstringname and then used the ConfigurationManager http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx to update the web.config
doc_23538121
This is our code, we received the above error when compiling. The error comes from the !newList parameter we send to the recursive function. newList is defined as a reference so we sent !newList in order to pass its value. When removing the ! we received an error that we sent a ref for inst list instead of an inst list (eventually we want to send an inst list!). A: OK, I think the problem is that the compiler thinks createInstList returns unit. This is due to precedence of ;, I think. It looks to me like the !newlist at the end is supposed to be the result of the whole createInstList function. But I suspect that it's being treated as part of the inner match. You might try this: let rec createInstList instList expr currentReg = let newList = ref instList in (match ... done); !newList
doc_23538122
var song; function preLoad() { song = loadSound('pathToAudio') } function setup() { createCanvas(windowWidth, windowHeight); } function draw() { background(0) } function mouseClicked() { if (song.isPlaying()) { //error initiate here song.pause() } else { song.play() } } <!--CDN for p5js library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js" integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
doc_23538123
list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca'] list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de'] There letters after the last digit represent an area; I can already find this using regex regex = re.compile(r"[^[0-9]+$") reg_list = [] for i in list_one: reg_list.append(regex.findall(i)) Which would give reg_list = [u'a', u'ba', u'ba', u'ca'] I want to search list_two to check if any of its items match anything from my reg_list, and if so remove it from that list. So I would end up with list_two = ['qqq55de'] as 'de' is the only location not in list_one. My current code is for i in list_one: for j in list_two: find_location = regex.findall(j) if a == find_location: list_two.pop(j) But I get the error TypeError: expected string or buffer Is there a better way of performing this? A: Assuming you already got reg_list, you can now use filter: filter(lambda x: re.findall(regex, x)[0] not in reg_list, list_two) I don't like one-lining everything when it becomes unreadable. Just consider the most readable (and of course most efficient) solution. A: You can use a list comprehension as a shorter, more concise alternative: import re list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca'] list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de'] new_list_two = [i for i in list_two if any(re.sub('[a-zA-Z]+$', '', i) == re.sub('[a-zA-Z]+$', '', b) for b in list_one)] Output: ['qqq55de'] A: You can not modify a list while iterating on it. But you can create a new one import re list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca'] list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de'] regex = re.compile(r"[^0-9]+$") reg_list = [] for i in list_one: reg_list.append(regex.findall(i)[0]) list_two = [j for j in list_two if regex.findall(j)[0] not in reg_list] print(list_two) Result: ['qqq55de']
doc_23538124
Below is the message. Can someone help so i can publish it on my server? Sequence contains more than one element Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Sequence contains more than one element Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOp`enter code here`erationException: Sequence contains more than one element System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +5876344 System.Linq.Queryable.SingleOrDefault(IQueryable`1 source, Expression`1 predicate) +490 Sinai.Ors.Domain.Repositories.UserRepository.GetUser(String mnemonic) in \\mdpointfs\md\moupar\Public Desktop\ORSUPDATE\Sinai (2)12.22.2014 VS2010\Sinai\Sinai.Ors.Domain\Repositories\UserRepository.cs:19 SinaiMasterPage.OnInit(EventArgs e) +42 System.Web.UI.Control.InitRecursive(Control namingContai`enter code here`ner) +186 System.Web.UI.Control.InitRecursive(Control namingContainer) +291 System.Web.UI.Page.ProcessRequestMain(Boolean includeS`enter code here`tagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2098 ________________________________________ Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212 A: The stack trace tells you exactly where the error is. In the GetUser() method there is a call to SingleOrDefault() on a collection. The collection has more than one element, so the exception is thrown. The code is assuming that there will never be more than one element in the collection, and that assumption is false for that data. You have a few options: * *The data is bad, correct it. If the data shouldn't be in this state then somewhere there is a missing data integrity check. A unique constraint on a column or set of columns, a foreign key relationship, etc. It's possible that the schema might not be able to maintain this particular measure of data integrity, in which case the application code should enforce it. *If there should be only one record, enforce that. Check the Count() of the collection and if it's greater than 1 then handle that error condition. Show a message to the user? Notify somebody? That's up to you. *If it's ok that there is more than one record and you only want the first one, use FirstOrDefault() instead of SingleOrDefault(). Either way, the stack trace is telling you where the problem is. A: Do you expect that an GetUser() can have multiple values? If not, SingleOrDefault might have shown you an inconsistency. Then you should fix your bug that caused it and stay with it SingleOrDefault instead of FirstOrDefault. SingleOrDefault throws an exception if more than one element exists. Here you can see exactly what the single or default method does: http://msdn.microsoft.com/en-us/library/system.linq.enumerable.singleordefault(v=vs.100).aspx
doc_23538125
(CLOSED)
doc_23538126
This is the only way I have figured out how it would work: from graphics import * def main(): win = GraphWin('Star', 600, 600) win.setCoords(0.0, 0.0, 600.0, 600.0) win.setBackground('White') p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) p4 = win.getMouse() p4.draw(win) p5 = win.getMouse() p5.draw(win) p6 = win.getMouse() p6.draw(win) p7 = win.getMouse() p7.draw(win) p8 = win.getMouse() p8.draw(win) p9 = win.getMouse() p9.draw(win) p10 = win.getMouse() p10.draw(win) vertices = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10] print(vertices.getPoints()) # Use Polygon object to draw the star star = Polygon(vertices) star.setFill('darkgreen') star.setOutline('darkgreen') star.setWidth(4) # width of boundary line star.draw(win) main() This works but not too well as I can't get a perfect star and I always have to guess where I am clicking. A: Below is a mathematical approach to solving this problem based on code for drawing a star in C#: import math from graphics import * POINTS = 5 WIDTH, HEIGHT = 600, 600 def main(): win = GraphWin('Star', WIDTH, HEIGHT) win.setCoords(-WIDTH/2, -HEIGHT/2, WIDTH/2, HEIGHT/2) win.setBackground('White') vertices = [] length = min(WIDTH, HEIGHT) / 2 theta = -math.pi / 2 delta = 4 / POINTS * math.pi for _ in range(POINTS): vertices.append(Point(length * math.cos(theta), length * math.sin(theta))) theta += delta # Use Polygon object to draw the star star = Polygon(vertices) star.setFill('darkgreen') star.setOutline('lightgreen') star.setWidth(4) # width of boundary line star.draw(win) win.getMouse() win.close() main() Note that I changed the coordinate system to simplify the solution. Also, the fill may look strange on some systems like Unix (unfilled in the center) but look completely filled other systems, like Windows. This is an artifact of the way fill is implemented in the Tkinter library that underpins Zelle graphics: You can probably make it fill completely in both by calculating the points along the outer perimeter rather than just the (crossing) points of the star.
doc_23538127
When I set a breakpoint on a line javasscript code and start debugging , I doesn't get hit anymore. This worked well when I had IE7 installed. The code hasn't changed. There were no other system changes performed at the same time. How can I solve this problem (permanently if possible)? A: In Internet Explorer, go to: Tools (Menu) -> Internet Options -> Advanced (Tab) Under the Browsing Section uncheck both: 'Disable Script Debugging (Internet Explorer)' and 'Disable Script Debugging (Other)' A: Now whit ie 8 you can debug javascript directly in dev tools bar. Open dev tools bar, go to tab script and click button start debugging. On the rigth pane you got other tab to get watch, breakpoints and other fonctionnality.
doc_23538128
void PvSbProUISampleDlg::OnBnClickedSave() { // TODO: Add your control notification handler code here CString StringValue; mMovieSave.GetWindowTextW(StringValue); if (StringValue == L"Save") { CString codecValue; mMovieCodecSelected.GetWindowTextW(codecValue); if (codecValue.IsEmpty()){ MessageBox( L"Please select a codec before saving to file", L"Select Codec!", MB_OK | MB_ICONEXCLAMATION ); return; } CString fileNameValue; mFileName.GetWindowTextW(fileNameValue); if (fileNameValue.IsEmpty()){ MessageBox( L"Please select a file location", L"Select File!", MB_OK | MB_ICONEXCLAMATION ); return; } if (!StartMovie()) return; mSavingMovie = true; mMovieSave.SetWindowTextW(L"Saving"); } else { mVideoMutex.Lock(); PvResult aResult = mVideoCompressor->Stop(); mSavingMovie = false; mVideoMutex.Unlock(); if (!aResult.IsOK()) { MessageBox( mLocation, L"Can't Stop Video Compressor!", MB_OK | MB_ICONEXCLAMATION ); return; } mMovieSave.SetWindowTextW(L"Save"); } } I set up the video stream and select uncompressed AVI for my codec. I click "save" button which then calls the function below bool PvSbProUISampleDlg::StartMovie() { if ( !mDevice.IsConnected() ) { MessageBox( L"Need to connect to device", L"Cannot start Video Compressor!", MB_OK | MB_ICONEXCLAMATION ); return false; } if (!mPipeline.IsStarted() ) { return false; } if (mSavingMovie) return false; PvInt64 width; PvInt64 height; PvInt64 bitCount; if (!GetImageWidth(width).IsOK()) return false; if (!GetImageHeight(height).IsOK()) return false; if (!GetPixelBitCount(bitCount).IsOK()) return false; // Start the movie compressor if ( !mVideoCompressor->Start( mLocation, width, height, bitCount/8, 59).IsOK()) { MessageBox( mLocation, L"Cannot start Video Compressor!", MB_OK | MB_ICONEXCLAMATION ); return false; } return true; } the function gets the video size info and then calls the actually compression to start PvResult VideoCompressor::Start(const CString& aFileName, unsigned short aSizeX, unsigned short aSizeY, unsigned short aBPP, double aFPS) { IAVIFile *lAVIFile = NULL; IAVIStream *lAVIStream = NULL; IAVIStream *lAVICompressedStream = NULL; AVISTREAMINFO lAVISTREAMINFO; AVICOMPRESSOPTIONS lAVICOMPRESSOPTIONS; // Try to match the image format with the Video Compressor capabilities BITMAPINFO lTempBI; lTempBI.bmiHeader.biSize = sizeof( BITMAPINFO ); lTempBI.bmiHeader.biWidth = aSizeX; lTempBI.bmiHeader.biHeight = aSizeY; lTempBI.bmiHeader.biPlanes = 1; lTempBI.bmiHeader.biBitCount = aBPP * 8; lTempBI.bmiHeader.biCompression = BI_RGB; lTempBI.bmiHeader.biSizeImage = aSizeX * aSizeY * aBPP; lTempBI.bmiHeader.biXPelsPerMeter = 1280; lTempBI.bmiHeader.biYPelsPerMeter = 720; lTempBI.bmiHeader.biClrUsed = 0; lTempBI.bmiHeader.biClrImportant = 0; //lTempBI.bmiHeader. if( ( mCOMPVARS.hic != NULL ) && // if not the "Full Frames (uncompressed)" ( ICCompressQuery( mCOMPVARS.hic, &lTempBI, NULL ) != ICERR_OK ) ) { mLastVideoError = "Image format not accepted by compressor!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } // Try to open the stream for writing if( mTempBuffer ) delete [] mTempBuffer; mTempBuffer = new unsigned char[ aSizeX * aSizeY * aBPP ]; if( mTempBuffer == NULL ) { mLastVideoError = "Cannot allocate memory for a temporary buffer!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } if( AVIFileOpen( &lAVIFile, aFileName, OF_CREATE | OF_WRITE, NULL ) != 0 ) { mLastVideoError = "Cannot open movie file for writing!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } // Fill out AVIStream information memset( &lAVISTREAMINFO, 0, sizeof( AVISTREAMINFO ) ); lAVISTREAMINFO.fccType = streamtypeVIDEO; lAVISTREAMINFO.fccHandler = mCOMPVARS.fccHandler; lAVISTREAMINFO.dwFlags = 0; lAVISTREAMINFO.dwCaps = 0; lAVISTREAMINFO.wPriority = 0; lAVISTREAMINFO.wLanguage = 0; lAVISTREAMINFO.dwScale = 100; lAVISTREAMINFO.dwRate = (unsigned long)( aFPS * 100.0 ); lAVISTREAMINFO.dwStart = 0; lAVISTREAMINFO.dwLength = 0; lAVISTREAMINFO.dwInitialFrames = 0; lAVISTREAMINFO.dwQuality = mCOMPVARS.lQ; lAVISTREAMINFO.dwSuggestedBufferSize = aSizeX * aSizeY * aBPP; lAVISTREAMINFO.dwSampleSize = aSizeX * aSizeY * aBPP; SetRect(&lAVISTREAMINFO.rcFrame, 0, aSizeY, aSizeX, 0); // Convert to a wchar_t* char *orig = "Video Stream"; size_t origsize = strlen(orig) + 1; const size_t newsize = 64; size_t convertedChars = 0; mbstowcs_s(&convertedChars, lAVISTREAMINFO.szName, origsize, orig, _TRUNCATE); if( AVIFileCreateStream( lAVIFile, &lAVIStream, &lAVISTREAMINFO ) != 0 ) { mLastVideoError = "Cannot create video stream!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } BITMAPINFOHEADER lBIH; lBIH.biSize = sizeof( BITMAPINFOHEADER ); lBIH.biWidth = aSizeX; lBIH.biHeight = aSizeY; lBIH.biPlanes = 1; lBIH.biBitCount = aBPP * 8; lBIH.biCompression = BI_RGB; lBIH.biSizeImage = aSizeX * aSizeY * aBPP; lBIH.biXPelsPerMeter = 1280; lBIH.biYPelsPerMeter = 720; lBIH.biClrUsed = 0; lBIH.biClrImportant = 0; memset( &lAVICOMPRESSOPTIONS, 0, sizeof( AVICOMPRESSOPTIONS ) ); lAVICOMPRESSOPTIONS.fccType = streamtypeVIDEO; lAVICOMPRESSOPTIONS.fccHandler = mCOMPVARS.fccHandler; lAVICOMPRESSOPTIONS.dwKeyFrameEvery = 15; lAVICOMPRESSOPTIONS.dwQuality = mCOMPVARS.lQ; lAVICOMPRESSOPTIONS.dwBytesPerSecond = 0; lAVICOMPRESSOPTIONS.dwFlags = AVICOMPRESSF_KEYFRAMES; //| AVICOMPRESSF_VALID;//|AVICOMPRESSF_DATARATE; lAVICOMPRESSOPTIONS.lpFormat = &lBIH; lAVICOMPRESSOPTIONS.cbFormat = sizeof( lBIH ); lAVICOMPRESSOPTIONS.lpParms = 0; lAVICOMPRESSOPTIONS.cbParms = 0; lAVICOMPRESSOPTIONS.dwInterleaveEvery = 0; HRESULT lR = AVIMakeCompressedStream( &lAVICompressedStream, lAVIStream, &lAVICOMPRESSOPTIONS, NULL); if( lR == AVIERR_NOCOMPRESSOR ) { mLastVideoError = "Cannot find a suitable compressor!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } else if( lR == AVIERR_MEMORY ) { mLastVideoError = "Not enough memory to start the compressor!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } else if( lR == AVIERR_UNSUPPORTED ) { mLastVideoError = "Compression is not supported for this image buffer!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } if( AVIStreamSetFormat( lAVICompressedStream, 0, &lBIH, sizeof( lBIH ) ) != 0 ) { mLastVideoError = "Cannot set stream format. It probably isn't supported by the Codec!"; CleanUp(lAVIFile, lAVIStream ,lAVICompressedStream); return PvResult::Code::GENERIC_ERROR; } /////////////////// HRESULT hr; //IBaseFilter mux = Null; //IFileSinkFilter sink = null; // Guid x = new Guid( 0xe436eb88, 0x524f, 0x11ce, 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); //ICaptureGraphBuilder2::SetOutputFileName( ////////////////// // finishing up mAVIFile = lAVIFile; mAVIStream = lAVIStream; mAVICompressedStream = lAVICompressedStream; mSizeX = aSizeX; mSizeY = aSizeY; mBPP = aBPP; mImageSize = aSizeX * aSizeY * aBPP; mLastSample = 0; mCompressing = true; return PvResult::Code::OK; } this compresses the stream PvResult VideoCompressor::Compress(PvBuffer *aPvBuffer) { if (!mCompressing) return PvResult::Code::GENERIC_ERROR; ASSERT( mTempBuffer != NULL ); long lSamplesWritten, lBytesWritten; int numberOfLines = 0; PvUInt8 * aBuffer = aPvBuffer->GetDataPointer(); for( unsigned short lLine = 0; lLine < mSizeY; lLine++ ) { numberOfLines = lLine; unsigned char *lCurLine = (unsigned char *)aBuffer + (lLine ) * mSizeX * mBPP; unsigned char *lCurLineInv = mTempBuffer + (mSizeY - lLine - 1) * mSizeX * mBPP; ::memcpy( lCurLineInv, lCurLine, mSizeX * mBPP ); } if( AVIStreamWrite( mAVICompressedStream, mLastSample, 1, mTempBuffer, mImageSize, 0, &lSamplesWritten, &lBytesWritten ) != 0 || lSamplesWritten < 1 || lBytesWritten < 1 ) { mLastVideoError = "Cannot compress image!"; return PvResult::Code::GENERIC_ERROR; } mLastSample ++; return PvResult::Code::OK; } this is what it should look like: http://i13.photobucket.com/albums/a269/Masterg_/Untitled-16.png this is what it saves as ( minus the guy): http://i13.photobucket.com/albums/a269/Masterg_/vlcsnap-2011-06-07-13h11m34s97.png A: From MSDN we have: Syntax DWORD ICCompressQuery( hic, lpbiInput, lpbiOutput ); Parameters hic : Handle to a compressor. lpbiInput : Pointer to a BITMAPINFO structure containing the input format. lpbiOutput : Pointer to a BITMAPINFO structure containing the output format. You can specify zero for this parameter to indicate any output format is acceptable. I might be wrong, but it seems to me that you are trying to "force" this input format whitout taking into account the actual format you are passing as input. If your input format does not match the "forced" one, weird result must be expected. If your actual input format is not compatible with your compressor, you could try usign a ColorSpace converter filter before your compressor.
doc_23538129
Here's the problem: import java.util.ArrayList; import java.util.Collections; import java.util.List; public class testMain { public static void main(String[] args) { myClass myObject = new myClass("haha1"); ArrayList a = new ArrayList(); a.add(myObject); a.add(new myClass("haha2")); a.add(new myClass("haha3")); List b; b = Collections.nCopies(5, myObject); System.out.println(a.containsAll(b)); //prints true } static private class myClass { String a; myClass(String a) { this.a = a; } } } Problem 1: List b has a greater size than list a - should be false Problem 2: List b has more than one myObject objects (as opposed to Lista - should be false This doesn't work due to the way containsAll works, since I want to see if the object myObject is contained (in this case) 3 times in List a. I know I can write my own method that would do exactly what I want, but I was wondering if there is an out of the box solution for this case or what would be the most "elegant" way of handling it. EDIT: Removed clarification for my use of myClass as it was conflicting with given example. A: Use Collections.frequency(a,myObject) == 5 (or Collections.frequency(a,myObject) >= 5 if you don't mind if your Collection has more than 5 instances pf myObject). int java.util.Collections.frequency(Collection c, Object o) Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).
doc_23538130
C:\TeamCity\buildAgent\work\cbd612042b438c8c\web\LobApp\CatBallBusinessWeb\Scripts\PurchaseOrderModule.ts(2, 15): error TS1148: Build: Cannot compile modules unless the '--module' flag is provided. Apparently, the TeamCity build isn't picking up the right typescript.targets file. The line below from "C:\Program Files (x86)\msbuild\Microsoft\VisualStudio\v14.0\TypeScrip\Microsoft.TypeScript.targetst" is where the --module compiler flag should be applied. <TypeScriptBuildConfigurations Condition="'$(TypeScriptModuleKind)' != '' and '$(TypeScriptModuleKind)' != 'none'">$(TypeScriptBuildConfigurations) --module $(TypeScriptModuleKind)</TypeScriptBuildConfigurations> In the relevant project settlings, under "TypeScript Build", I have the "AMD" Module system selected.. which shouldd trigger the line above. The TeamCity build log differs from the build log I see when I compile with MSBuild from the command line here: TeamCity: [18:15:07] : [web\LobApp\CatBallBusinessWeb\CatBallBusinessWeb.csproj] PreComputeCompileTypeScript [18:15:07] : [PreComputeCompileTypeScript] Using "VsTsc" task from assembly "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\TypeScript.tasks.dll". [18:15:07] : [PreComputeCompileTypeScript] VsTsc [18:15:07] : [VsTsc] Task Parameter:ToolPath=C:\Program Files (x86)\Microsoft SDKs\TypeScript [18:15:07] : [VsTsc] Task Parameter:ToolExe=tsc.exe [18:15:07] : [VsTsc] Task Parameter:Configurations= --sourcemap --target ES5 --noEmitOnError COMPUTE_PATHS_ONLY [18:15:07] : [VsTsc] Task Parameter: FullPathsToFiles= Areas\Manage\Scripts\PurchaseOrderModule.ts Scripts\App\Purchase\PurchaseOrderEdit.ts Scripts\PurchaseOrderModule.ts Scripts\PurchaseOrderIndex.ts Scripts\typings\jquery\jquery.d.ts Scripts\typings\knockout.mapping\knockout.mapping.d.ts Scripts\typings\knockout.validation\knockout.validation.d.ts Scripts\typings\knockout\knockout.d.ts Scripts\typings\moment\moment-node.d.ts Scripts\typings\moment\moment.d.ts Vs. MSBuild command line: Target "PreComputeCompileTypeScript" in file "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\Microsoft.TypeScript.targets" from project "D:\dev\web\lobapp\CatBallBusinessWeb\CatBallBusinessWeb.csproj" (target "CompileTypeScript" depends on it): Using "VsTsc" task from assembly "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\TypeScript.tasks.dll". Task "VsTsc" Task Parameter:ToolPath=C:\Program Files (x86)\Microsoft SDKs\TypeScript Task Parameter:ToolExe=tsc.exe Task Parameter:Configurations= --module AMD --sourcemap --target ES5 --noEmitOnError COMPUTE_PATHS_ONLY Task Parameter: FullPathsToFiles= Areas\Manage\Scripts\PurchaseOrderModule.ts Scripts\App\Purchase\PurchaseOrderEdit.ts Scripts\PurchaseOrderModule.ts Scripts\PurchaseOrderIndex.ts Scripts\typings\jquery\jquery.d.ts Scripts\typings\knockout.mapping\knockout.mapping.d.ts Scripts\typings\knockout.validation\knockout.validation.d.ts Scripts\typings\knockout\knockout.d.ts Scripts\typings\moment\moment-node.d.ts Scripts\typings\moment\moment.d.ts The highlighted part is missing from the TeamCity log. In TeamCity, I'm building the solution directly.. the same one that builds fine everywhere else. I have Visual Studio 2015 tools selected. I should also mention that this solution builds from the command line from the TeamCity work directory. I'm not a build, teamcity, or typescript expert. So I'm not sure how to investigate this further. How can I figure out why the right targets file isn't being run? Given that this builds fine everywhere else, I feel like it's a TeamCity bug. On the other hand, I can't imagine how TeamCity is running MSBuild wrong. Any help appreciated.
doc_23538131
I wrote a test.js app to demonstrate this. var koa = require('koa'); var app = new koa(); var Router = require('koa-router'); var router = new Router(); router.get('/', function *(next){ this.body = "hello world"; console.log("success") }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000); console.log("listening on 3000"); I run the server with node v4.6.1 No errors occur, but when I send the get request, I get Not Found and no console log. This code works though: var koa = require('koa'); var app = new koa(); var Router = require('koa-router'); var router = new Router(); router.get('/', function (ctx){ ctx.body = "hello world"; console.log("success") }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000); console.log("listening on 3000"); Any idea why the generators don't run? A: If you're using the @next version of koa and koa-router, you should be using async functions for your middleware instead of generator functions which were meant for Koa v1. Example: var koa = require('koa'); var app = new koa(); var Router = require('koa-router'); var router = new Router(); router.get('/', async function (ctx){ // You can use `await` in here ctx.body = "hello world"; console.log("success") }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000); console.log("listening on 3000"); Of course, async/await isn't supported right now unless you're using Node v7 and use the --harmony-async-await flag. If you want to use it with Node v4, you will have to use something like babel in order to transpile your code. If you don't want to have a build step for your server-side code, I would recommend just using Koa v1 and stick with generator functions. A: var koa = require('koa'); var app = new koa(); var router = require('koa-router'); var route = router(); // These three lines will help you app.use(route.routes()); // to route to your given path and route.get("/user/", functionname); // will call the generator function. function *functionname(next){ console.log('in side the function'); this.body="hi this is my new page"; yield next; };
doc_23538132
I see from here that you can install the mono control panel and restart applications there. That's fine, but I don't really want that enabled on a production system. Is there a way to do it from the command line? A: Unless you disabled file change notifications a simple "touch web.config" (make sure to use the actual casing of your file) should do it. Otherwise a more hardcore approach would be to kill the mod-mono processes (they'll be restarted automatically).
doc_23538133
Now for the second and third steps I don't need a gradle docker image. If I add I can see on the build logs the image already exists. How can steps: # This step show the version of Gradle - name: gradle:7.4.2-jdk17-alpine entrypoint: gradle args: ['--version'] # This step build the gradle application - name: 'Build' entrypoint: gradle args: [ 'build' ] # This step run test - name: 'Test' entrypoint: gradle args: [ 'test' ]
doc_23538134
LNK1104: cannot open file 'opencv_core246d.lib' C:\Users\Public\Documents\imgSwitchingFiles Please can somebody shed light on this issue? A: It looks like your project options state this library should be linked to your binaries. Did you reuse this project from elsewhere? If you really don't need OpenCV, simply remove its libraries from the project linking options. A: In project properties: VC++ Directories>Library files>C:\OpenCV2.4.3\build\x86\vc9\lib & Linker>Input>Additional Dependencies> Add the following under edit (each on a new line) opencv_core243d.lib; opencv_imgproc243d.lib; opencv_highgui243d.lib; opencv_ml243d.lib; opencv_video243d.lib; opencv_features2d243d.lib; opencv_calib3d243d.lib; opencv_objdetect243d.lib; opencv_contrib243d.lib; opencv_legacy243d.lib; opencv_flann243d.lib; Your file paths may be different i.e. vc10 instead of vc9 or u may have x64 instead of x86. Also u will have 246 in every .lib instead of 243.
doc_23538135
* *Create a Java Agent within the mailbox and schedule it. It will process the mails and take actions.\ *Write separate Java code with used Notes API and call dominos server to fetch mails and process them. What is difference in both? Capabilities or something else? A: Write a Java Agent to run inside the email server Pros * *Lets you leverage all of the resiliency of the email server itself *Can be reasonably guaranteed to start and stop with the email server *Less code to manage *Easier to keep error logging with email server Cons * *Vendor specific so it will be less portable Reason for personal opinion I wrote a client that used IMAP to read emails inside an inbox periodically and I set up a James Mail Server with something like the agent you are talking about to programmatically respond to emails that were received by an email address. I tend to like your option 1 (a Java agent running inside the email server) because it lets you leverage all of the resiliency of the email server itself. The code can be reasonably guaranteed to start and stop with the email server and it's logging is connected to the logging of the server. Making a stand alone agent has the benefit of working with servers other than your initial configuration (especially if you leverage standard protocols). But you have to do more to make sure it is operational and you have to work harder to debug (in my own experience). Also, the Java Agent approach tends to be smaller so there is less code to manage. A: If you are monitoring just one mailbox, then a Java agent has an obvious advantage because it does not need any configuration data. You just put the agent in the actual mailbox database and it calls AgentContext.getCurrentDatabase when it runs. If you are monitoring just a few maiboxes, you can just duplicate the agent, and again each instance just reads AgentContext.getCurrentDatabase. But if you have many mailboxes, then you probably don't want to duplicate it all over the place. You probably want just a single agent, or a stand-alone program -- and in both cases you will need some configuration data to control it. This is the case where I might consider running it stand-alone instead of as an agent. But that would raise the question: How do you want to manage the configuration data? And another question comes from that: Who will manage the configuration data? If the answer is that the administrator of the Domino server will also manage the configuration of the process that is reading the mailbox data, then I would suggest that you should use a configuration tool that you know is familiar to all Domino administrators. That might be a group in the Domino Directory listing the names of the mailboxes, or it might be a Notes database containing a configuration document for each mailbox you are monitoring. And if you decide to go this way, then my preference would still be to use a Domino agent that reads the configuration information on the Domino server and reads the data from the configured mailboxes. But here the advantage isn't as strong. You could configure it in Domino but still run standalone. The stand-alone code would just need to be configured so that it knows where to look for its configuration data and that could just be a command line, like 'java myprog dominoServerName configDatabaseName'.
doc_23538136
doc_23538137
Traceback (most recent call last): File "/usr/lib/python2.6/site-packages/flup- 1.0.3.dev_20110405- py2.6.egg/flup/server/fcgi_base.py", line 574, in run protocolStatus, appStatus = self.server.handler(self) File "/usr/lib/python2.6/site-packages/flup-1.0.3.dev_20110405-py2.6.egg/flup/server/fcgi_base.py", line 1159, in handler result = self.application(environ, start_response) File "/home/mcgillme/lib/python2.6.6/site-packages/Django-1.4.10-py2.6.egg/django/core/handlers/wsgi.py", line 219, in __call__ self.load_middleware() File "/home/mcgillme/lib/python2.6.6/site-packages/Django-1.4.10-py2.6.egg/django/core/handlers/base.py", line 47, in load_middleware raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) ImproperlyConfigured: Error importing middleware django.middleware.page: "No module named page" Status: 500 Internal Server Error Content-Type: text/html I looked through other solutions, so I checked my cms installation - the folder middleware exists and contains an _init.py file. $PATH and $PYTHONPATH seem to include the cms as well, because, for example this works: Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cms >>> import django.middleware >>> import django.middleware.page Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named page >>> What else can it be besides a missing path? How can django.middleware work, but django.middleware.page is not found? A: I look into every django version from 1.2 to 1.7 and there is no django.middleware.page, but it is in django-cms. Use cms.middleware.page A: Did you add cms to your INSTALLED_APPS environment variable in settings.py? INSTALLED_APPS = { 'cms', } After checking, maybe u can run this command again to make sure it's installed: python manage.py syncdb A: * *CHECK THIS:Removed the MultilingualMiddleware *IT SAYS THE SOLUTION COULD BE: Remove cms.middleware.multilingual.MultilingualURLMiddleware from your settings. Be sure django.middleware.locale.LocaleMiddleware is in your settings, and that it comes after the SessionMiddleware.
doc_23538138
Anyway, I am running into a roadblock here and I am not certain if this is just the IDE I am using (PhpStorm), or if it is something else. Here is what I am seeing in PhpStorm: When I use Kint, it shows that the namespace is defined as shown in the screenshot above (namespace SavvyPro\Sandbox): Here is the complete code: namespace SavvyPro\Sandbox; add_action('loop_start', __NAMESPACE__ . '\process_the_string'); function process_the_string() { $current_user = wp_get_current_user(); render_user_message($current_user->user_firstname, get_the_ID()); } function render_user_message($first_name, $post_id) { d("My name is {$first_name}."); ddd("The post ID is {$post_id}."); } Here is the version of PhpStorm I am currently running: I am certain it is something quite simple for you PHP gurus out there, but since I am such a noob, it's a bit of a brain twister for me. Any help on this is of course greatly appreciated. Thank you all! A: I emailed JetBrains support and they got back to me with the fix and it is exactly what @LazyOne mentioned in the comments section above. I simply deleted the following folder on my Mac and it resolved the issue: ~Library/Caches/JetBrains/PhpStorm2020.2 A: This is still an issue with later versions of PHPStorm. I just had to delete this folder to fix this very same issue with 2022.3.1 - ~Library/Caches/JetBrains/PhpStorm2022.3
doc_23538139
Footer section is overlaying the body content. Why overlaying? Because I have used .body_wrapper{height:100%;} to display the background image. If I remove the height:100% then not getting the overlay issue but my header image not displaying. Why .body_wrapper{height:100%;} ? because I have two parent div. Would you help me out in this? body, html { margin: 0; padding: 0; height: 100%; } .main_wrapper { display: inline; } .body_wrapper { height: 100%; min-height: 100%; width: 100%; margin-top: 90px; } .bg_contact { background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url('https://wallpaper-house.com/data/out/6/wallpaper2you_106757.jpg'); } .banner_bg { background-repeat: no-repeat; background-size: cover; width: 100%; height: auto; min-height: 100%; } .contact_header_content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); text-align: center; } .contact_header_content h2 { font-size: 38px; color: #fff; } .contact_header_content p { font-size: 22px; color: #fff; padding: 25px 0; } .contact_header { position: relative; } #footer { background-color: #222; width: 100%; } <div class="main_wrapper"> <div class="body_wrapper"> <div class="bg_contact banner_bg contact_header"> <div class="contact_header_content"> <h2>We sould love to hear back from you.</h2> <p>Whether you have question about features, pricing, need a demo or anything e s Our team is ready to answer all your questions. </p> <div class="btn_slider"> <a href="#" class="i_btn i_btn_bg text_cap">Contact Us</a> </div> </div> </div> <section> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> </div> <div id="footer"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> A: i think you have put your footer div outside of your body_wrapper div i have modified your code snipet, please check and let me know body, html { margin: 0; padding: 0; height: 100%; } .main_wrapper { display: inline; } .body_wrapper { height: 100%; min-height: 100%; width: 100%; margin-top: 90px; } .bg_contact { background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url('https://wallpaper-house.com/data/out/6/wallpaper2you_106757.jpg'); } .banner_bg { background-repeat: no-repeat; background-size: cover; width: 100%; height: auto; min-height: 100%; } .contact_header_content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); text-align: center; } .contact_header_content h2 { font-size: 38px; color: #fff; } .contact_header_content p { font-size: 22px; color: #fff; padding: 25px 0; } .contact_header { position: relative; } #footer { background-color: #222; width: 100%; } <div class="main_wrapper"> <div class="body_wrapper"> <div class="bg_contact banner_bg contact_header"> <div class="contact_header_content"> <h2>We sould love to hear back from you.</h2> <p>Whether you have question about features, pricing, need a demo or anything e s Our team is ready to answer all your questions. </p> <div class="btn_slider"> <a href="#" class="i_btn i_btn_bg text_cap">Contact Us</a> </div> </div> </div> <section> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> <div id="footer"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> </div>
doc_23538140
std::vector<std::string> array = { {"A", "a"}, {"B", "b"}, {"C", "c"} }; for (std::string& a : array) { if (letter == a[1] || letter == a[0]) { std::cout << a[0] << ": " << a[1] << std::endl; break; } } I am new to C++ and cannot figure out why it gives me errors about this. Edit: Error: error: invalid operands to binary expression ('std::string' (aka 'basic_string<char>') and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char')) A: The problem is in how you initialize your strings. The following fails as well: std::string s {"A", "a"}; "A" and "a" are of type const char* and represent two characters each (the letter, and a null terminator '\0'). What you probably want is to initialize your strings with char elements instead: std::vector<std::string> array = { {'A', 'a'}, {'B', 'b'}, {'C', 'c'} }; Note the single quotes '. You can also just do this: std::vector<std::string> array = { "Aa", "Bb", "Cc" }; A: I think {"A", "a"} is already a verctor, and this array varable type should be vector<vector<string>>.
doc_23538141
Thanks in advance.
doc_23538142
<mat-form-field appearance="outline" class="date-picker" style="margin-right: auto;"> <mat-label>یک بازه زمانی انتخاب کنید</mat-label> <mat-date-range-input [rangePicker]="rangePicker"> <input matInput #dateRangeStart matStartDate placeholder="تاریخ شروع" formControlName="fromDate"> <input matInput #dateRangeEnd matEndDate placeholder="تاریخ پایان" formControlName="toDate"> </mat-date-range-input> <mat-datepicker-toggle matSuffix [for]="rangePicker"></mat-datepicker-toggle> <mat-date-range-picker #rangePicker> <mat-date-range-picker-actions> <button mat-button matDateRangePickerCancel>کنسل</button> <button mat-raised-button color="primary" matDateRangePickerApply (click)="onFormSubmit()">تایید</button> </mat-date-range-picker-actions> </mat-date-range-picker> </mat-form-field> </form> I define form like this initForm() { this.form = this.formBuilder.group({ fromDate: new FormControl(), toDate: new FormControl() }); } and want to set value from ts file like this if (filterModel.fromCreateDate && filterModel.toCreateDate) { this.form.get('fromDate')?.setValue(this.convertToMiladi(filterModel.fromCreateDate)); this.form.get('toDate')?.setValue(this.convertToMiladi(filterModel.toCreateDate)); } How do I convert to miladi is like this convertToMiladi(date: string) { let convertableDate = moment(date).locale('en').format('YYYY-MM-DD'); var m = moment(convertableDate, 'jYYYY-jMM-jDM'); m = m.locale('en') return m.format('YYYY-MM-DD'); } and I have an adapter for calendar import { Inject, Optional } from '@angular/core'; import { DateAdapter, MAT_DATE_LOCALE } from '@angular/material/core'; import * as jMoment from 'moment-jalaali'; const minmin: any = jMoment; export const PERSIAN_DATE_FORMATS = { parse: { dateInput: "jYYYY/jMM/jDD" }, display: { dateInput: "jYYYY/jMM/jDD", monthYearLabel: "jYYYY jMMMM", dateA11yLabel: "jYYYY/jMM/jDD", monthYearA11yLabel: "jYYYY jMMMM" } }; export class JalaliMomentDateAdapter extends DateAdapter<jMoment.Moment> { constructor(@Optional() @Inject(MAT_DATE_LOCALE) matDateLocale: string) { super(); this.setLocale(matDateLocale || minmin.locale('fa')); minmin.loadPersian(); } invalid() { return 'hi' as any; } toIso8601(date) { return 'hi'; } /** * returns year in jalali calendar system. */ getYear(date: jMoment.Moment): number { return this.clone(date).jYear(); } /** * returns month in jalali calendar system. */ getMonth(date: jMoment.Moment): number { return this.clone(date).jMonth(); } /** * returns day in jalali calendar system. */ getDate(date: jMoment.Moment): number { return this.clone(date).jDate(); } /** * returns Day Of Week in jalali calendar system. */ getDayOfWeek(date: jMoment.Moment): number { return this.clone(date).day(); } /** * returns Month Names in jalali calendar system. * most of the time we use long format. short or narrow format for month names is a little odd. */ getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { const r: string[] = []; minmin.loadPersian({ dialect: 'persian-modern', usePersianDigits: true }); const l = minmin().localeData(); if (style === 'long' || style === 'short') { Object.keys(l).forEach(key => { if (key === '_jMonths') { const values = l[key]; for (let index = 0; index < values.length; index++) { r.push(values[index]); } } }); } else { Object.keys(l).forEach(key => { if (key === '_jMonthsShort') { const values = l[key]; for (let index = 0; index < values.length; index++) { r.push(values[index]); } } }); } return r; // switch (style) { // case 'long': // const mlong = (minmin().localeData() as any)._jMonths.slice(0); // console.log(mlong); // return mlong; // case 'short': // const mshort = (minmin().localeData() as any)._jMonthsShort.slice(0); // console.log('mshort: ', mshort); // return mshort; // case 'narrow': // return (minmin().localeData() as any)._jMonthsShort.slice(0); // } } /** * borrowed from angular material code. */ getDateNames(): string[] { return this.range(31, i => String(i + 1)); } /** * returns Day Of Week names in jalali calendar system. */ getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { switch (style) { case 'long': return minmin().localeData().weekdays().slice(0); case 'short': return minmin().localeData().weekdaysShort().slice(0); case 'narrow': return minmin().localeData().weekdaysMin().slice(0); } } /** * returns year in jalali calendar system. */ getYearName(date: jMoment.Moment): string { return this.clone(date).jYear().toString(); } /** * returns first day of week in jalali calendar system. * first day of week is saturday, شنبه */ getFirstDayOfWeek(): number { return 6; } /** * returns Number of Days In Month in jalali calendar system. */ getNumDaysInMonth(date: jMoment.Moment, fa?): number { if (date['_d']) { return minmin.jDaysInMonth(this.getYear(date['_d']), this.getMonth(date['_d'])); } return minmin.jDaysInMonth(this.getYear(date), this.getMonth(date)); } clone(date: jMoment.Moment): jMoment.Moment { // return date.clone().locale(this.locale); return minmin(date); } createDate(year: number, month: number, date: number): jMoment.Moment { return minmin().jYear(year).jMonth(month).jDate(date); } today(): jMoment.Moment { return minmin(); } parse(value: any, parseFormat: string | string[]): jMoment.Moment | null { if (value && typeof value === 'string') { return minmin(value, parseFormat, this.locale); } return value ? minmin(value).locale(this.locale) : null; } format(date: jMoment.Moment, displayFormat: any): string { return this.clone(date).format(displayFormat); } addCalendarYears(date: jMoment.Moment, years: number): jMoment.Moment { return this.clone(date).add(years, 'jYear'); } addCalendarMonths(date: jMoment.Moment, months: number): jMoment.Moment { return this.clone(date).add(months as any, 'jmonth'); } addCalendarDays(date: jMoment.Moment, days: number): jMoment.Moment { return this.clone(date).add(days, 'day'); } getISODateString(date: jMoment.Moment): string { return this.clone(date).format('jYYYY-jMM-jDD'); } isDateInstance(obj: any): boolean { return minmin.isMoment(obj); } isValid(date: jMoment.Moment): boolean { return this.clone(date).isValid(); } range<T>(length: number, valueFunction: (index: number) => T): T[] { const valuesArray = Array(length); for (let i = 0; i < length; i++) { valuesArray[i] = valueFunction(i); } return valuesArray; } } I try to set value but my date range picker is empty after patchValue or setValue in Angular reactive forms. Can someone help me set the value for the mat date range picker from the .ts file? A: As your JalaliMomentDateAdapter extends DateAdapter<T> with T is jMoment.Moment. Hence, you need to set the value with jMoment.Moment type to FormControl. convertToMiladi(date: string) { // Match the date format with the format of parsed date return moment(date, 'YYYY/MM/DD'); } Sample demo on StackBlitz
doc_23538143
I've already achieved some result on the following case: 1.Paste some text into textarea 2.Double click on the word from textarea 3.See how this word appears in a div with ul inside. The word adds as a li. See the code of the case: //html block <textarea name="" id="text" cols="30" rows="10" ondblclick="copyPaste()" >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur minus iure suscipit quam expedita? Sed minus laboriosam natus quaerat autem enim accusantium, architecto officiis aliquam pariatur. Adipisci provident tenetur velit!</textarea> <div id="wordList" class="wordListclass"> <ul id="myList"> <li></li> </ul> </div> </body> //js block for copy-pasting words after doubleclick on the text from the texarea with id ='text' "use strict"; function copyPaste(){ var selection = window.getSelection(); console.log(selection.toString()); var node = document.createElement("LI"); var selectionWithButton = selection; var textnode = document.createTextNode(selectionWithButton); node.appendChild(textnode); document.getElementById("myList").appendChild(node); } Now I need to get rid of and add the second textarea. I want to see how words after doublclicking on the text from the first textarea appear in the second textarea. Important note - they should have the following structure: word1 word2 word3 without html tags, because after I see the list of these words in the second textarea I want to insert them into a database, so html tags (as in the code I provided) would be undesirable. Replacing div element with textarea just didn't work, unfortunately. Thanks everyone for reading and help! A: const myList = document.querySelector("div#wordList ul#myList") // Get the list function copyPaste(){ let textAreaValue = document.querySelector("textarea#text").value //get the written text in textarea myList.innerHTML += `<li> ${textAreaValue} </li>` //put the "textAreaValue" in the list } Something like this? A: If i understand correctly, you just want to paste the selected word in the second textarea instead of the list. For that, you can simply append the text using the property value of the textarea. In order for the text to apear on different lines, you can use \n which is a character that insert a new line. You can find more info here about the escape sequence. Your function could look like this: function copyPaste(){ // trim() is used here to remove the whitespace at the end of the word when you dblClick on a word const selection = window.getSelection().toString().trim(); const textarea2 = document.getElementById("pasteTextarea"); if(!textarea2.value) { // Don't add a new line when the textarea is empty textarea2.value = selection; } else { textarea2.value += `\n${selection}`; } } <textarea name="" id="text" cols="30" rows="10" ondblclick="copyPaste()" >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur minus iure suscipit quam expedita? Sed minus laboriosam natus quaerat autem enim accusantium, architecto officiis aliquam pariatur. Adipisci provident tenetur velit!</textarea> <textarea name="" id="pasteTextarea" cols="30" rows="10"></textarea>
doc_23538144
CGFloat breed = 768; CGFloat hoogte = 975; CGSize afmeting = CGSizeMake(breed, hoogte); UIGraphicsBeginImageContext(afmeting); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)]; There are some layers (buttons and textlabels) that I don't want in the image. Is there a way to remove some layers from renderincontext? Now I use textLabel.hidden = YES before making the screenshot and set hidden to NO when finished. Also for the buttons and other labels. A: All the buttons and labels have their own layers. All these layers can be rendered to some graphical context. Now you are generating your self.view.layer as image, you could try to make another view that would consist only of items you do want to render (keeping your labels and buttons separate in another view that would overlap your "picture view") or you can in fact render all components one by one not including your buttons (though that would probably be more work than you do now). If you will consider making one view on top of another, bear in mind that all the inputs (touches and events) in the top view must be sent to bottom view if you want it to react accordingly.
doc_23538145
HTTP Status 404 - /ESA/protected/admin/list description The requested resource is not available. this is my struts.xml file : <action name="login" class="ir.imrasta.esa.ui.action.UserAction" method="login"> <result name="success">protected/admin/list</result> <result name="failed">/login.jsp?login=failed</result> </action> <action name="/protected/admin/list" class="ir.imrasta.esa.ui.action.ManagerAction" method="list"> <result name="success">/protected/admin/list.jsp</result> </action> see <result name="success">/protected/admin/list</result> in above code. if i change it with a jsp page it work fine. update 2013/07/20: web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Educational System Application</display-name> <filter> <filter-name>loginFilter</filter-name> <filter-class>ir.imrasta.esa.ui.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/protected/*</url-pattern> </filter-mapping> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> struts.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="languages" /> <package name="default" namespace="/" extends="struts-default"> <default-action-ref name="index" /> <global-results> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="error" exception="java.lang.Exception"/> <exception-mapping result="error" exception="ir.imrasta.esa.bll.exceptions.DataSourceException"/> <exception-mapping result="error" exception="ir.imrasta.esa.bll.exceptions.DecryptionException"/> </global-exception-mappings> <action name="index"> <result>/index.jsp</result> </action> <action name="login" class="ir.imrasta.esa.ui.action.UserAction" method="login"> <result name="success">protected/admin/list</result> <result name="failed">/login.jsp?login=failed</result> </action> <action name="/protected/admin/list" class="ir.imrasta.esa.ui.action.ManagerAction" method="list"> <result name="success">/protected/admin/home.jsp</result> </action> </package> <!-- Add packages here --> </struts> loginFilter : public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{ HttpServletRequest req=(HttpServletRequest) request; HttpSession session=req.getSession(); User user=(User)session.getAttribute(Constants.SESSION_USER); if (user!=null){ chain.doFilter(request, response); }else{ RequestDispatcher dispatcher=req.getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); } } A: See even the action class which you are referring too also needed to be mapped in struts.xml, the reason you are getting 404 is that the action class which you are finding is not having any mapping found in struts A: In order to redirect to another action you need to use redirectAction result type. <action name="login" class="ir.imrasta.esa.ui.action.UserAction" method="login"> <result name="success" type="redirectAction">protected/admin/list</result> <result name="failed">/login.jsp?login=failed</result> </action> And slashes in action names are not allowed by default. To allow slashes in action names you need to set struts.enable.SlashesInActionNames constant to true in struts.xml file. <constant name="struts.enable.SlashesInActionNames" value="true" />
doc_23538146
I feel I should be able to put a JDBC connection string into tnsnames on the server and have it "just work". I've looked around a little for this functionality but it doesn't seem to be there. In this way I could connect to pretty much any database just using a database link. Have I missed something? It looks like the two options are Generic Connectivity and Oracle Gateways but I'm surprised that's all there is. Generic Connectivity comes with the database license and Oracle Gateways is an add-on. For Generic Connectivity, if you're running on Linux (like me) you need to get hold of an ODBC driver as it isn't bundled with the database. However... with Oracle being such keen Java fans, and with a JVM built-in to the database I'd have thought a JDBC-based linking technology would have been a no-brainer. It seems a natural extension to have a JDBC connection string in TNSNAMES and everything would "just work". Anyone any ideas why this isn't available? A: Generic Connectivity is what you are after, it will let you setup a remote database link against MS SQL Server, so you can do queries like select * from mytable@my_ms_sql_server; I've only used it in Oracle 9i against mysql, and found, that in our cases, it didn't work very well, as it ended up using up MASSIVE amounts of ram, we still use it, but now just use it for syncing to a local table rather than doing 'live' queries against it. BUT, it might be completely different against MS SQL Server, and in 10g/11g A: Another product to look at is Oracle Gateways. Have a look at: http://www.oracle.com/technology/documentation/gateways10g.html
doc_23538147
Is DropToFrame is available only in Ultimate Edition? Any other plugin add this to intellij community edition Thanks A: The Drop Frame was renamed to Reset Frame and now is located to the left of the frame name in Frames view (curved arrow icon on the screenshot) You may add it manually in Settings/Preferences | Appearance & Behavior | Menus and Toolbars - Debug Tool Window Top Toolbar:
doc_23538148
I built my navbar with php in the unordered list of the navbar to retrieve the menu elements from an SQL table called "menu" from a database called "shop", with no avail. I even have a print_r in place, only to show me that my resource is working, but for some reason the whole code isn't creating the menu items as written. This is the code: <?php $menu = []; mysql_connect('localhost', 'root', ''); mysql_select_db('shop'); $result= mysql_query("SELECT * FROM menu"); if ($result && mysql_num_rows($result)>0){ while($row = mysql_fetch_assoc($result)){ $menu[] = $row; } } echo '<pre>'; $error= print_r($menu); $error = '' ; echo '</pre>'; ?> <!DOCTYPE html> <html> <head> <link href="_CSS/style.css" rel="stylesheet" type="text/css"/> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="site-wrapper"> <div class="header"> <div class="navbar"> <ul> <li><a href="./">Home</a></li> <?php if(count($menu) >0) : ?> <?php foreach ($menu as $row) : ?> <li><a href="#"><?php $row = ['link']; ?></a></li> <?php endforeach; ?> <?php endif; ?> </ul> </div> <div class="member"> <ul> <li><a href="../login.php"></a>Login</li> <li><a href="../Register.php"></a>Register</li> </ul> </div> </div> </div> The result unfortunately looks like this: A: Your problem is this: <?php $row = ['link']; ?> It should probably be this: <?php echo $row['link']; ?> Maybe you got confused trying to do this: <?= $row['link']?> A: Mistake 1 : You have used $row = ['link']; Where you will get this error Notice: Array to string conversion in .. So you need to have $row['link']; Mistake 2 : You need to output the content using echo <li><a href="#"><?php echo $row['link']; ?></a></li> Warning : Don't use mysql_* functions as it is depreciated instead use mysqli or PDO for safer Operations !
doc_23538149
sample_method_or_Class() { /* I'd like to fold this * comment block */ } /* The same way I can fold this one * outside the code block. */ Does Eclipse support functionality like Visual Studio does like (How do I fold code for comment blocks inside method blocks?) ? A: There is no such support in Eclipse, unfortunately. There is a request for this though, reported in 2008 with only 10 votes, so I would not expect it implemented any time soon. Mentions of an Eclipse folding plugin called Coffee Bytes can be found, but most links are broken. Looks like latest Eclipse versions are not supported and the project looks discontinued. Update: As indicated by howlger in the comment below, EclipseFolding plugin is alive and well. I've tested it now, installed it via Help / Install new software... / Add... using its update site: * *https://github.com/stefaneidelloth/EclipseFolding/raw/master/com.cb.platsupp.site After Eclipse restart I got little red squares indicating folding capability for both comment scenarios from the question:
doc_23538150
global $mdb2; $mdb2=MDB2::connect($dsn); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } I do this to connect to my DB, I put this in a separate php file called Connect.php and require it on all my pages. However, when I have to query inside a function, I will have to pass $mdb2 to the function as an argument? Is this the right way to do it. Further, I am writing a class which will query my DB. And I have no idea what to do (I don't wanna pass it as an argument) Do I have to re-establish the connect everytime (ie. write a function for connection) Can't you make the connection persistent and global? A: You can require your file Connect.php on all of your pages, and every function that needs to use the connection can refer to the global variable $mdb2. For example: # In file Connect.php <?php $dsn="mysql://$db_username:$db_password@$db_hostname/$db_database"; $mdb2=MDB2::connect($dsn); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } #In any other file <?php require_once "Connect.php"; getUser($id) { global $mdb2; $mdb2->query("SELECT ...."); } Other solution is using a Singleton Class to access the database, so that there is a function that always returns the reference to your $mdb2 variable. Surely, the discussion Global or Singleton for database connection? is something worth reading.
doc_23538151
The @@DbName contains the name of the database the user gave in, the fact that it is creating a database says the DbName is correct. When executed the database is created but empty, all tables are inserted in another database. I believe the error lies in the USE [@@DbName] What am I doing wrong? My SQL statements: CREATE DATABASE [@@DbName] ON PRIMARY ( NAME = [@@DbName], FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\@@DbName.mdf', SIZE = 5 MB, MAXSIZE = UNLIMITED, FILEGROWTH = 1 MB ) LOG ON ( NAME = [@@DbName_log], FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\@@DbName_log.ldf', SIZE = 1 MB, MAXSIZE = 2097152 MB, FILEGROWTH = 10 % ) COLLATE Latin1_General_CI_AS GO CREATE LOGIN [@@DbLogin] WITH PASSWORD=N'@@DbPassword', DEFAULT_DATABASE=[@@DbName], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF GO USE [@@DbName] GO CREATE TABLE [dbo].[Customers] ( [ID] int IDENTITY(1, 1) NOT NULL, [CustomerName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Address] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Picture] image NOT NULL, [Balance] decimal(18, 2) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO CREATE TABLE [dbo].[Employee] ( [ID] int IDENTITY(1, 1) NOT NULL, [EmployeeName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Address] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Email] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Phone] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Registers] ( [ID] int IDENTITY(1, 1) NOT NULL, [RegisterName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Device] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Errorlog] ( [RegisterID] int NOT NULL, [Timestamp] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Message] varchar(255) COLLATE Latin1_General_CI_AS NOT NULL, [StackTrace] ntext COLLATE Latin1_General_CI_AS NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO CREATE TABLE [dbo].[Products] ( [ID] int IDENTITY(1, 1) NOT NULL, [ProductName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL, [Price] decimal(18, 2) NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Register_Employee] ( [RegisterID] int NOT NULL, [EmployeeID] int NOT NULL, [From] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL, [Until] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Sales] ( [ID] int NOT NULL, [Timestamp] timestamp NOT NULL, [CustomerID] int NOT NULL, [RegisterID] int NOT NULL, [ProductID] int NOT NULL, [Amount] int NOT NULL, [TotalPrice] decimal(18, 2) NOT NULL ) ON [PRIMARY] GO
doc_23538152
When the first-step is correctly completed and the "Continue" button is clicked, some elements from the first-step form still remain visible even though the div that contains them has the styles set to display:none. I have no idea why this is happening, can any of you take a look ? You need to try and order something and go to the checkout process and try to get by the first step. The problem appears only on IE 8 & 9, cause I restricted older versions on this website. All the best! A: First check your tags. I think the li tag is not closed properly. It's showing </li/> for the <li id="opc-billing" class="allow"> opening tag. Which is obviously wrong. If checking that doesn't work, then try giving the style overflow:hidden to the <li> or the DIV inside it. I think that will work.
doc_23538153
I have following logs: root@dev1:~/launch# ./sh/local-iam-maintenance Creating volume "launch_fa_config" with default driver Creating volume "launch_web-root" with local driver Creating fusionauthdb ... done Creating fusionauth ... done Creating webserver ... done Attaching to fusionauthdb, fusionauth, webserver fusionauth | NOTE: Picked up JDK_JAVA_OPTIONS: --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED fusionauthdb | fusionauthdb | PostgreSQL Database directory appears to contain a database; Skipping initialization fusionauthdb | fusionauthdb | 2021-01-19 12:17:34.854 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 fusionauthdb | 2021-01-19 12:17:34.854 UTC [1] LOG: listening on IPv6 address "::", port 5432 fusionauthdb | 2021-01-19 12:17:34.858 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" fusionauthdb | 2021-01-19 12:17:34.881 UTC [20] LOG: database system was shut down at 2021-01-19 12:16:47 UTC fusionauthdb | 2021-01-19 12:17:34.892 UTC [1] LOG: database system is ready to accept connections webserver | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration webserver | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ webserver | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh webserver | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf webserver | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf webserver | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh webserver | /docker-entrypoint.sh: Configuration complete; ready for start up fusionauth | 19-Jan-2021 12:17:36.900 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib] fusionauth | 19-Jan-2021 12:17:37.280 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-9011"] fusionauth | 19-Jan-2021 12:17:37.305 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 19-Jan-2021 12:17:37.359 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-9013"] fusionauth | 19-Jan-2021 12:17:37.750 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 19-Jan-2021 12:17:37.754 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-127.0.0.1-9019"] fusionauth | 19-Jan-2021 12:17:37.758 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 19-Jan-2021 12:17:37.761 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1373 ms fusionauth | 19-Jan-2021 12:17:37.771 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina] fusionauth | 19-Jan-2021 12:17:37.773 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.57 fusionauth | Jan 19, 2021 12:17:39 PM org.apache.jasper.servlet.TldScanner scanJars fusionauth | INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. fusionauth | 2021-01-19 12:17:40.331 PM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Loading FusionAuth configuration file [/usr/local/fusionauth/config/fusionauth.properties] fusionauth | 2021-01-19 12:17:40.336 PM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Set property [fusionauth-app.url] set to [http://fusionauth:9011] using configured value. fusionauth | 2021-01-19 12:17:40.343 PM ERROR org.primeframework.mvc.guice.GuiceBootstrap - fusionauth | fusionauth | =================================================================================================== fusionauth | fusionauth | Unable to start the server. Here's why: fusionauth | fusionauth | fusionauth | [Error injecting constructor, java.lang.UnsupportedOperationException] fusionauth | -> [class java.lang.UnsupportedOperationException] null fusionauth | fusionauth | =================================================================================================== fusionauth | fusionauth | fusionauth | 2021-01-19 12:17:40.352 PM ERROR org.primeframework.mvc.guice.GuiceBootstrap - Unable to start the server. Exception: fusionauth | fusionauth | com.google.inject.CreationException: Unable to create injector, see the following errors: fusionauth | fusionauth | 1) Error injecting constructor, java.lang.UnsupportedOperationException fusionauth | at io.fusionauth.api.configuration.DefaultFusionAuthConfiguration.<init>(DefaultFusionAuthConfiguration.java:58) fusionauth | at io.fusionauth.api.configuration.DefaultFusionAuthConfiguration.class(DefaultFusionAuthConfiguration.java:23) fusionauth | while locating io.fusionauth.api.configuration.DefaultFusionAuthConfiguration fusionauth | at io.fusionauth.app.maintenance.guice.FusionAuthInitialMaintenanceModeModule.configure(FusionAuthInitialMaintenanceModeModule.java:19) fusionauth | while locating io.fusionauth.api.configuration.FusionAuthConfiguration fusionauth | fusionauth | 1 error fusionauth | at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:554) fusionauth | at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:188) fusionauth | at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:111) fusionauth | at com.google.inject.Guice.createInjector(Guice.java:87) fusionauth | at com.google.inject.Guice.createInjector(Guice.java:69) fusionauth | at com.google.inject.Guice.createInjector(Guice.java:59) fusionauth | at org.primeframework.mvc.guice.GuiceBootstrap.initialize(GuiceBootstrap.java:58) fusionauth | at com.inversoft.maintenance.servlet.MaintenanceModePrimeServletContextListener.contextInitialized(MaintenanceModePrimeServletContextListener.java:39) fusionauth | at io.fusionauth.app.primeframework.FusionAuthAppPrimeServletContextListener.contextInitialized(FusionAuthAppPrimeServletContextListener.java:26) fusionauth | at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4689) fusionauth | at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5155) fusionauth | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402) fusionauth | at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) fusionauth | at java.base/java.lang.Thread.run(Thread.java:832) fusionauth | Caused by: java.lang.UnsupportedOperationException: null fusionauth | at io.fusionauth.api.domain.RuntimeMode.fromConfiguration(RuntimeMode.java:21) fusionauth | at io.fusionauth.api.configuration.DefaultFusionAuthConfiguration.initialize(DefaultFusionAuthConfiguration.java:181) fusionauth | at com.inversoft.configuration.BasePropertiesFileInversoftConfiguration.initializeAndLogWarningsAndErrors(BasePropertiesFileInversoftConfiguration.java:514) fusionauth | at com.inversoft.configuration.BasePropertiesFileInversoftConfiguration.<init>(BasePropertiesFileInversoftConfiguration.java:88) fusionauth | at io.fusionauth.api.configuration.DefaultFusionAuthConfiguration.<init>(DefaultFusionAuthConfiguration.java:58) fusionauth | at io.fusionauth.api.configuration.DefaultFusionAuthConfiguration$$FastClassByGuice$$b82219af.newInstance(<generated>) fusionauth | at com.google.inject.internal.DefaultConstructionProxyFactory$FastClassProxy.newInstance(DefaultConstructionProxyFactory.java:89) fusionauth | at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:114) fusionauth | at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:91) fusionauth | at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:306) fusionauth | at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40) fusionauth | at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:168) fusionauth | at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:39) fusionauth | at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:62) fusionauth | at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40) fusionauth | at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:168) fusionauth | at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:39) fusionauth | at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:213) fusionauth | at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184) fusionauth | ... 16 common frames omitted fusionauth | Jan 19, 2021 12:17:40 PM org.apache.catalina.core.StandardContext listenerStart fusionauth | SEVERE: Exception sending context initialized event to listener instance of class [io.fusionauth.app.primeframework.FusionAuthAppPrimeServletContextListener] fusionauth | org.primeframework.mvc.PrimeException fusionauth | at org.primeframework.mvc.guice.GuiceBootstrap.initialize(GuiceBootstrap.java:77) fusionauth | at com.inversoft.maintenance.servlet.MaintenanceModePrimeServletContextListener.contextInitialized(MaintenanceModePrimeServletContextListener.java:39) fusionauth | at io.fusionauth.app.primeframework.FusionAuthAppPrimeServletContextListener.contextInitialized(FusionAuthAppPrimeServletContextListener.java:26) fusionauth | at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4689) fusionauth | at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5155) fusionauth | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402) fusionauth | at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) fusionauth | at java.base/java.lang.Thread.run(Thread.java:832) fusionauth | fusionauth | 19-Jan-2021 12:17:40.355 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file fusionauth | 19-Jan-2021 12:17:40.376 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors fusionauth | Jan 19, 2021 12:17:40 PM org.apache.catalina.core.StandardContext listenerStop fusionauth | SEVERE: Exception sending context destroyed event to listener instance of class [io.fusionauth.app.primeframework.FusionAuthAppPrimeServletContextListener] fusionauth | java.lang.NullPointerException fusionauth | at org.primeframework.mvc.guice.GuiceBootstrap.shutdown(GuiceBootstrap.java:88) fusionauth | at org.primeframework.mvc.servlet.PrimeServletContextListener.contextDestroyed(PrimeServletContextListener.java:47) fusionauth | at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4735) fusionauth | at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5399) fusionauth | at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257) fusionauth | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:187) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412) fusionauth | at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402) fusionauth | at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) fusionauth | at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) fusionauth | at java.base/java.lang.Thread.run(Thread.java:832) fusionauth | fusionauth | 19-Jan-2021 12:17:40.434 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-9011"] fusionauth | 19-Jan-2021 12:17:40.447 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["https-jsse-nio-9013"] fusionauth | 19-Jan-2021 12:17:40.451 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-127.0.0.1-9019"] fusionauth | 19-Jan-2021 12:17:40.454 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 2692 ms using following docker-compose file: version: '3.7' services: fusionauthdb: container_name: fusionauthdb image: postgres:11.9-alpine environment: PGDATA: /var/lib/postgresql/data/pgdata POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres networks: - app-network restart: unless-stopped volumes: - /var/lib/postgresql:/var/lib/postgresql/data fusionauth: container_name: fusionauth image: fusionauth/fusionauth-app:1.22.2 depends_on: - fusionauthdb environment: DATABASE_URL: jdbc:postgresql://fusionauthdb:5432/fusionauth DATABASE_ROOT_USERNAME: postgres DATABASE_ROOT_PASSWORD: postgres DATABASE_USERNAME: fusionauth DATABASE_PASSWORD: hkaLBM3RVnyYeYeqE3WI1w2e4Avpy0Wd5O3s3 FUSIONAUTH_APP_MEMORY: '512M' #FUSIONAUTH_APP_RUNTIME_MODE: development FUSIONAUTH_APP_RUNTIME_MODE: productive FUSIONAUTH_APP_URL: http://fusionauth:9011 SEARCH_TYPE: database networks: - app-network restart: unless-stopped ports: - 9011:9011 volumes: - fa_config:/usr/local/fusionauth/config volumes: fa_config: networks: app-network: driver: bridge and following nginx config: server { listen 80; listen [::]:80; #for certbot challenges (renewal process) location ~ /.well-known/acme-challenge { allow all; root /var/www/html; } location / { rewrite ^ https://$host$request_uri? permanent; } } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name ***(domain)***; server_tokens off; # ssl on; <-- Deprecated ssl_buffer_size 8k; ssl_dhparam /etc/ssl/certs/dhparam-2048.pem; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_prefer_server_ciphers on; ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5; ssl_ecdh_curve secp384r1; ssl_session_tickets off; # OCSP stapling ssl_stapling on; ssl_stapling_verify on; resolver 127.0.0.11 valid=30s; # (127.0.0.11) is the internal Docker DNS, cache only for 30s ssl_certificate /etc/letsencrypt/live/***(domain)***/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/***(domain)***/privkey.pem; client_max_body_size 20M; underscores_in_headers on; location / { try_files $uri @iam; } # Reroute to the iam app location @iam { set $upstream http://fusionauth:9011; proxy_pass $upstream; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Port "443"; proxy_set_header X-Forwarded-Proto "https"; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # enable strict transport security only if you understand the implications } } I cannot really make sense out of the error message and what is going wrong. Thank you for your help! EDIT: This is the log when starting in development mode: fusionauthdb | fusionauthdb | PostgreSQL Database directory appears to contain a database; Skipping initialization fusionauthdb | fusionauthdb | 2021-01-30 11:19:35.409 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 fusionauthdb | 2021-01-30 11:19:35.409 UTC [1] LOG: listening on IPv6 address "::", port 5432 fusionauthdb | 2021-01-30 11:19:35.411 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" fusionauthdb | 2021-01-30 11:19:35.425 UTC [20] LOG: database system was shut down at 2021-01-30 11:10:14 UTC fusionauthdb | 2021-01-30 11:19:35.430 UTC [1] LOG: database system is ready to accept connections fusionauth | NOTE: Picked up JDK_JAVA_OPTIONS: --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED fusionauth | 30-Jan-2021 11:19:37.277 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib] webserver | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration webserver | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ webserver | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh webserver | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf webserver | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf webserver | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh webserver | /docker-entrypoint.sh: Configuration complete; ready for start up fusionauth | 30-Jan-2021 11:19:37.987 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-9011"] fusionauth | 30-Jan-2021 11:19:38.017 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 30-Jan-2021 11:19:38.063 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-9013"] fusionauth | 30-Jan-2021 11:19:38.406 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 30-Jan-2021 11:19:38.410 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-127.0.0.1-9019"] fusionauth | 30-Jan-2021 11:19:38.412 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read fusionauth | 30-Jan-2021 11:19:38.413 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1492 ms fusionauth | 30-Jan-2021 11:19:38.420 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina] fusionauth | 30-Jan-2021 11:19:38.420 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.57 fusionauth | Jan 30, 2021 11:19:40 AM org.apache.jasper.servlet.TldScanner scanJars fusionauth | INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. fusionauth | 2021-01-30 11:19:41.146 AM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Loading FusionAuth configuration file [/usr/local/fusionauth/config/fusionauth.properties] fusionauth | 2021-01-30 11:19:41.151 AM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Set property [fusionauth-app.url] set to [http://fusionauth:9011] using configured value. fusionauth | 2021-01-30 11:19:41.152 AM INFO com.inversoft.configuration.BasePropertiesFileInversoftConfiguration - fusionauth | - Overriding default value of property [database.mysql.enforce-utf8mb4] with value [true] fusionauth | - Overriding default value of property [database.mysql.connector-version] with value [8.0.21] fusionauth | - Overriding default value of property [FUSIONAUTH_APP_RUNTIME_MODE] with value [development] fusionauth | - Overriding default value of property [SEARCH_TYPE] with value [database] fusionauth | fusionauth | 2021-01-30 11:19:41.260 AM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Loading FusionAuth configuration file [/usr/local/fusionauth/config/fusionauth.properties] fusionauth | 2021-01-30 11:19:41.261 AM INFO io.fusionauth.api.configuration.DefaultFusionAuthConfiguration - Set property [fusionauth-app.url] set to [http://fusionauth:9011] using configured value. fusionauth | 2021-01-30 11:19:41.264 AM INFO com.inversoft.configuration.BasePropertiesFileInversoftConfiguration - fusionauth | - Overriding default value of property [database.mysql.enforce-utf8mb4] with value [true] fusionauth | - Overriding default value of property [database.mysql.connector-version] with value [8.0.21] fusionauth | - Overriding default value of property [FUSIONAUTH_APP_RUNTIME_MODE] with value [development] fusionauth | - Overriding default value of property [SEARCH_TYPE] with value [database] fusionauth | fusionauth | 2021-01-30 11:19:41.443 AM INFO com.inversoft.maintenance.DefaultMaintenanceModeWorkflow - fusionauth | fusionauth | --------------------------------------------------------------------------------------------------------- fusionauth | ---------------------------------- Entering Silent Configuration Mode ----------------------------------- fusionauth | --------------------------------------------------------------------------------------------------------- fusionauth | fusionauth | 2021-01-30 11:19:41.539 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Attempting to lock database to prevent multi-node issues fusionauth | 2021-01-30 11:19:41.552 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Obtained a database lock fusionauthdb | 2021-01-30 11:19:41.556 UTC [28] LOG: incomplete startup packet fusionauth | 2021-01-30 11:19:41.590 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Database Version [1.22.2] fusionauth | 2021-01-30 11:19:41.591 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Latest Migration Version [1.22.0] fusionauth | 2021-01-30 11:19:41.593 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Attempting to unlock database to prevent multi-node issues fusionauth | 2021-01-30 11:19:41.594 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Unlock completed fusionauthdb | 2021-01-30 11:19:41.596 UTC [32] LOG: incomplete startup packet fusionauth | 2021-01-30 11:19:41.602 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Database Version [1.22.2] fusionauth | 2021-01-30 11:19:41.602 AM INFO com.inversoft.maintenance.db.JDBCMaintenanceModeDatabaseService - [jZpYqg] Latest Migration Version [1.22.0] fusionauth | 2021-01-30 11:19:41.605 AM INFO org.primeframework.mvc.servlet.PrimeServletContextListener - Initializing Prime fusionauth | 2021-01-30 11:19:41.606 AM INFO io.fusionauth.app.guice.FusionAuthModule - fusionauth | fusionauth | --------------------------------------------------------------------------------------------------------- fusionauth | --------------------------------- Starting FusionAuth version [1.22.2] ---------------------------------- fusionauth | --------------------------------------------------------------------------------------------------------- … A: You have an invalid runtime mode configured which causes the exception. FUSIONAUTH_APP_RUNTIME_MODE: productive Caused by: java.lang.UnsupportedOperationException: null at io.fusionauth.api.domain.RuntimeMode.fromConfiguration(RuntimeMode.java:21) See available options for this parameter in the FusionAuth configuration. Available options are: * *development *production
doc_23538154
When running the build i'm getting an error because it's trying to execute java but from a directory where it doesn't exist. While Java home is set as C:\Program Files (x86)\Java\jdk1.8.0_51\ it's trying to locate it in C:\Program Files\Java\jdk1.8.0_51\bin\java. Why is that? Everything in IntelliJ settings looks correct. Must add that I'm new to these applications. A: Please check and compare the Java setting in intellij with the one in your operating system. You can run this in a terminal > java -version That should show you your systems java version. Gradle also uses a gradle.properties file in your project root which can contain further Gradle specific settings. A: Found it ! It was under External Libraries the java directory there was the old one.
doc_23538155
public static void Statistics(int[] array, int els, out int high, out int low, out int sum, out double avg) { //set statistic values via the arguments els = count; high = array.Max(); low = array.Min(); sum = array.Sum(); avg = array.Average(); //output the statistics WriteLine("The array has {0} values", els); WriteLine("The highest value is {0}", high); WriteLine("The lowest value is {0}", low); WriteLine("The sum of the values is {0}", sum); WriteLine("The average is {0}", avg); } The problem I'm finding is that even if the user does not enter 10 total values, the minimum is always set to 0. Per my professors advice I have tried using a for loop that iterates the value of count, which is what I use to assign the amount of values entered. When doing this the low variable counts as not being assigned (since it is an out and needs an assigned value). I gather that is due to it being considered a local variable when it is in the for loop. Everything else checks out other than the minimum value being properly assigned so that is my main question and concern is how would I assign it a proper minimum value if the user does not enter in 10 values. If the user does enter 10 values the minimum is correct. As a side note the way I got count to work was by setting it to public and outside of the main() method to allow it to be assigned when inside the for loop and nested if statement for determining if the sentinel value has been entered. I mainly think the Statistics method is where my trouble is but here is the code for the other method in case improvements can be made, or perhaps that's where the problem lies. { int x; string inputString; WriteLine("Enter an integer: "); for (x = 0; x < array.Length; ++x) { inputString = ReadLine(); //Will break the loop to continue to next method or line if (int.Parse(inputString) == 999) { // count how many times we entered in data count = x; break; } // will add input to array and continue until sentinel value is entered array[x] = int.Parse(inputString); WriteLine("Enter another integer: "); } count = x; return x; } I only added the int = x because the method needed to return an int and I wasn't sure how else to make it work. A: you haven't shown the code, but where you create your array, of size 10 probablly, will be initizializing that array to 10 things all equal to 0. If you track the count of how many things you put in that array, you can do array.Take(count).Min(); or you can dynamically grow the array ( or ideally, just use a generic list ) as you get each input. However, depending on your professor, there may be different requirements about what you are allowed to use
doc_23538156
I can't get GMP to work on my computer, so I can't run any tests. If I could, just general math like addition and maybe some trig functions. I'll figure out GMP later. A: numpy and GMPY2 have different purposes. numpy has fast numerical libraries but to achieve high performance, numpy is effectively restricted to working with vectors or arrays of low-level types - 16, 32, or 64 bit integers, or 32 or 64 bit floating point values. For example, numpy access highly optimized routines written in C (or Fortran) for performing matrix multiplication. GMPY2 uses the GMP, MPFR, and MPC libraries for multiple-precision calculations. It isn't targeted towards vector or matrix operations. The Python interpreter adds overhead to each call to an external library. Whether or not the slowdown is significant depends on the how much time is spend by the external library. If the running time of the external library is very short, say 10e-8 seconds, then Python's overhead is significant. If the running time of the external library is relatively long, several seconds or longer, then Python's overhead is probably insignificant. Since you haven't said what you are trying to accomplish, I can't give a better answer. Disclaimer: I maintain GMPY2.
doc_23538157
* *All the dependencies in a separate lib folder *The main project jar with a manifest that includes the lib folder on it's classpath A: In your pom.xml file ... 1) Add this code to your project->properties node. This will define your main class in a central place for use in many plugins. <properties> <mainClass>project.Main.class</mainClass> </properties> 2) Add this code to your project->build->plugins node. It will collect all your jar dependencies into a lib folder AND compile your main class jar with the proper classpath reference: <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>${mainClass}</mainClass> </manifest> </archive> </configuration> </plugin>
doc_23538158
i have deployed a war file, when i run localy through tomcat it works fine but when i run on another system by giveing my system ip and then project folder e.g http:\192.168.0.145\DllTest it loads the applet but when i click on a button to load the functionality it is throwing an exception Exception in thread "AWT-EventQueue-3" java.lang.UnsatisfiedLinkError: Expecting an absolute path of the library: http:\192.168.0.145:8080\DllTest\lib\jinvoke.dll while it is working fine localy but not in another system. Please tell me what is the problem. Is it a rights issue or something else. A: You cannot load a DLL on an external host. It has to be an absolute disk file system -as the exception message already hints. Your best bet is to download it manually, create a temp file and load it instead. File dllFile = File.createTempFile("jinvoke", ".dll"); InputStream input = new URL(getCodeBase(), "lib/jinvoke.dll").openStream(); OuptutStream output = new FileOutputStream(dllFile); // Write input to output and close streams the usual Java IO way. // Then load it using absolute disk file system path. System.loadLibrary(dllFile.getAbsolutePath()); dllFile.deleteOnExit();
doc_23538159
So i went back to basics downloaded a fresh copy of orchard...and ran the first time set up and tried to deploy that... I am using visual studio 2012 i right clicked published chose to publish to file system then ftp across to server... copied app data folder in binary mode changed the settings.txt to point to my prod database. Tried to open the website and just get a 404 error.. when I look in the app logs this is what i see.. 2013-05-02 11:40:52,439 [15] Orchard.FileSystems.AppData.AppDataFolder - Could not delete recipe execution folder C:\Websites\OrchardTestDeploy\src\Orchard.Web\App_Data\RecipeQueue\25fc7ed3855649e68c0435a7dcf412b3 under "App_Data" folder 2013-05-02 11:44:45,702 [6] Orchard.Environment.DefaultOrchardHost - A tenant could not be started: Default Autofac.Core.DependencyResolutionException: None of the constructors found with 'Orchard.Environment.AutofacUtil.DynamicProxy2.ConstructorFinderWrapper' on type 'Orchard.Settings.CurrentSiteWorkContext' can be invoked with the available services and parameters: Cannot resolve parameter 'Orchard.Settings.ISiteService siteService' of constructor 'Void .ctor(Orchard.Settings.ISiteService)'. at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.b__0() at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) Which is worse than my daisy website with new modules and lots of errors... am i doing something wrong... there must be a simple approach other than the installation guide on this site that says zip up the whole project and deploy it. A: You might have to set read/write permissions for the account that is configured as the identity for the IIS application pool on the following folders: * *Modules *Themes *App_Data *Media Taken from Orchard documentation - Manually installing Orchard.
doc_23538160
Tabs.html <ion-tabs> <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab> </ion-tabs> Tabs.ts import { Component } from '@angular/core'; import { SigninPage } from '../Auth/Signin/Signin'; @Component({ templateUrl: 'Tabs.html' }) export class TabsPage { tab1Root: any = SigninPage; constructor() { } } app.components.ts import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar } from 'ionic-native'; import { TabsPage } from '../pages/Tabs/Tabs'; @Component({ template: `<ion-nav [root]="rootPage"></ion-nav>` }) export class MyApp { rootPage = TabsPage; constructor(platform: Platform) { platform.ready().then(() => { StatusBar.styleDefault(); }); } } Is there any way to show a different tab with an if condition? For example, I want to show Tabs.App.html or Tabs.Auth.html depending on an if block. What is the best way to do it with Ionic 2? A: In ionic2 every page is accompanied by it's .ts file. So if you want 2 tabs, app.html and auth.html you would need to create both these pages and their .ts file. In that way you can write an if-statement saying: if(1 > 2){ this.rootpage = AuthTab; }else{ this.rootpage = AppTab; } ps don't forget to import your components
doc_23538161
Combox Box Example http://aalto.tv/test/combobox-image.png As you can hopefully see, this ComboBox only shows 8 items and I would like to show more if there are more to be seen. Having searched around the popular solution is to call "setMaximumRowCount" on the JComboBox, however this is having no effect. Can any one point me in the right direction? Many thanks for any and all help! Cheers, Alex A: JComboBox#setMaximumRowCount works for JTable / TableHeader and AutoComplete JComboBox in the JTable too A: try the revalidate() (or repaint()) method after setting the rowcount; if a setXX method does not generate an event to the component, then you have to manually reset it. failing that, look at the source code of the setMaximumRowCount() method
doc_23538162
var str = "To be, or not to be, that is the question."; alert(str.endsWith("question.")); The above simple JS code doesn't work at all? A: As said in this post http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/ var str = "To be, or not to be, that is the question."; function strEndsWith(str, suffix) { return str.match(suffix+"$")==suffix; } alert(strEndsWith(str,"question.")); this will return true if it ends with provided suffix. JSFIDDLE EDIT There is a similar question asked before check it here the answer says var str = "To be, or not to be, that is the question$"; String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; alert(str.endsWith("$")); A: ES5 has no endsWith function (or, for that matter, startsWith). You can roll your own, like this version from MDN: if (!String.prototype.endsWith) { Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: false, writable: false, value: function (searchString, position) { position = position || this.length; position = position - searchString.length; var lastIndex = this.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; } }); } A: I have never seen an endsWith function in JS. You can rather do an String.length and then check the last words by manually referencing each character you want to check against. Even better would be to do a regex to find the last word in the string and then use that (Regular expression to find last word in sentence). A: I found the endsWith() function available in Chrome console, but oddly, not defined when debugging in VS Code (with Chrome). You can try editing the snippet below by deleting the polyfill to see if your browser supports it. This is a quote from MDN Developer Docs for String.prototype.endsWith(): String.prototype.endsWith() This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.endsWith() with the following snippet: // If string.endsWith() isn't defined, Polyfill it. if (!String.prototype.endsWith) { String.prototype.endsWith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; } // Use it. const myString = "Mayberry"; const result = myString.endsWith("berry") ? 'Yes' : 'Nope'; document.body.append('A. ' + result); Q. Does Mayberry end with "berry"?<br>
doc_23538163
function closetip(a) { //alert($(a).attr('id')); var cls = $(a).attr('id'); $("#" + cls).parent().parent().parent().hide(); }
doc_23538164
Now I have : * *a view *one button I want to use the button to export the excel. The following is I already tried the code: In the button(Client-side) : var viewPanel1Id = "view:_id1:viewPanel1" var htmltable = document.getElementById(viewPanel1Id); var html = htmltable.outerHTML; window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html)); But the button was no response... How can I export to excel????? The following is the code of XPages <?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> <xp:button value="Export5" id="button5"> <xp:eventHandler event="onclick" submit="true" refreshMode="complete"> <xp:this.action><![CDATA[#{javascript: var viewPanel = document.getElementById("#{id:viewPanel1}"); var html = viewPanel.outerHTML; window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));}]]> </xp:this.action> </xp:eventHandler> </xp:button> <xp:viewPanel rows="30" id="viewPanel1" viewStyle="width:100%"> <xp:this.facets> <xp:pager partialRefresh="true" layout="Previous Group Next" xp:key="headerPager" id="pager1"> </xp:pager> </xp:this.facets> <xp:this.data> <xp:dominoView var="view1" viewName="VEMPM03"></xp:dominoView> </xp:this.data> <xp:viewColumn columnName="LOCAL_PR_NO" id="viewColumn1" showCheckbox="true"> <xp:viewColumnHeader value="prno" id="viewColumnHeader1" showCheckbox="true"> </xp:viewColumnHeader> </xp:viewColumn> <xp:viewColumn columnName="PUR_DEPT_S01" id="viewColumn2"> <xp:viewColumnHeader value="pur" id="viewColumnHeader2"> </xp:viewColumnHeader> </xp:viewColumn> <xp:viewColumn columnName="ITEM_NAME" id="viewColumn3"> <xp:viewColumnHeader value="name" id="viewColumnHeader3"> </xp:viewColumnHeader> </xp:viewColumn> </xp:viewPanel> </xp:view> A: Your Button executes ServerSide Script. When using <xp:this.script> it worked for me. <xp:button value="Export5" id="button5"> <xp:eventHandler event="onclick" submit="false"> <xp:this.script><![CDATA[ var viewPanel = document.getElementById("#{id:viewPanel1}"); var html = viewPanel.outerHTML; window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));]]> </xp:this.script> </xp:eventHandler> </xp:button> A: This may not fix your problem, but the line below is a better way to reference an element by its id in csjs: var viewPanel1Id = document.getElementById("#{id:viewPanel1}")
doc_23538165
var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112]; How to find if AT LEAST 3 elements of this array fall within range 50 to 99? If AT LEAST 3 elements within this array are within this range 50 to 99 to return true, and if less than 3 elements of this particular array a are within range 50 to 99 to return false! A: You can use .filter: const atLeastThreeBetweenXAndYInArr = (x=0, y=0, arr=[]) => arr.filter(e => e >= x && e <= y).length >= 3; console.log( atLeastThreeBetweenXAndYInArr(50, 99, [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112]) ); console.log( atLeastThreeBetweenXAndYInArr(50, 99, [2, 5, 8, 16, 35, 67, 89, 102, 108, 112]) ); A: just filter them a.filter(e => e >= 50 && e <= 99).length >= 3 A: You can make use of some and take closure over count: const isMin3=arr=>arr.some((count=>o=>(o>=50 && o<=99) && ++count===3)(0)); console.log(isMin3([2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112])); console.log(isMin3([1,2,65,90])); console.log(isMin3([50,49,65,100])); The advantage of some is, it will exit from the loop once it found its minimum match.
doc_23538166
#include <SoftwareSerial.h> //#define PIN_TX 1 //#define PIN_RX 0 //SoftwareSerial mySerial(PIN_TX,PIN_RX); //DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR, //make sure that the baud rate of SIM900 is 9600! //you can use the AT Command(AT+IPR=9600) to set it through SerialDebug DFRobot_SIM808 sim808(&Serial); char buffer[512]; int i = 0; void setup(){ //mySerial.begin(9600); Serial.begin(9600); //******** Initialize sim808 module ************* while(!sim808.init()) { delay(1000); Serial.print("Sim808 init error\r\n"); } delay(3000); //*********** Attempt DHCP ******************* while(!sim808.join(F("mobitel3g"))) { Serial.println("Sim808 join network error"); delay(2000); } //************ Successful DHCP **************** Serial.print("IP Address is "); Serial.println(sim808.getIPAddress()); //************* Turn on the GPS power************ while(!sim808.attachGPS()) { delay(1000); Serial.print("Open the GPS power failure\r\n"); } delay(3000); Serial.println("Open the GPS power success"); for(int i = 0; i<=40;i++) { for(int y = 0;y<=i;y++) { Serial.print("."); delay(60); } Serial.println(""); } } void loop(){ tcp(); delay(2000); //Calls the function every 2 seconds } void tcp() { // Update the GPS data float lati, longi; if (sim808.getGPS()) { Serial.print(sim808.GPSdata.year); Serial.print("/"); Serial.print(sim808.GPSdata.month); Serial.print("/"); Serial.print(sim808.GPSdata.day); Serial.print(" "); Serial.print(sim808.GPSdata.hour); Serial.print(":"); Serial.print(sim808.GPSdata.minute); Serial.print(":"); Serial.print(sim808.GPSdata.second); Serial.print(":"); Serial.println(sim808.GPSdata.centisecond); lati = sim808.GPSdata.lat,6; longi = sim808.GPSdata.lon,6; //print the variables Serial.print("LAT ="); Serial.println(lati); Serial.print("LON ="); Serial.println(longi); sim808.detachGPS(); } else { // No gps, abort Serial.println("No GPS"); return; } //*********** Establish a TCP connection ************ if (!sim808.connect(TCP,"http://syntiq.lk", 80)) { Serial.println("Connect error"); return; } else { Serial.println("Connect mbed.org success"); } //*********** Send a GET request ***************** char http_cmd[100]; sprintf(http_cmd, "GET /GPS/Addtoserver.php?data2=%f&data1=%f HTTP/1.0\r\n\r\n\0", lati, longi); sim808.send(http_cmd, strlen(http_cmd)); /* int ret = sim808.recv(buffer, sizeof(buffer) - 1); if (ret <= 0){ Serial.println("error receiving"); } else { buffer[ret] = '\0'; Serial.print(buffer); } */ //************* Close TCP or UDP connections ********** sim808.close(); //*** Disconnect wireless connection, Close Moving Scene ******* sim808.disconnect(); } This is the code I have used to retrieve GPS data and I send these data to a MySQL server. But I'm not receiving any data from the GPS module. I'm sure that the module is working because I tried both GPS and TCP codes individually and they worked well. Can someone please tell me where I went wrong. A: It will be better if you use two serial ports (By port I mean a set of serial pins), one for the computer (Serial) and one for the GPS module (Say Serial 1), that is assuming the microcontroller is an Arduino Mega. But if it is an Arduino Uno or any other Arduino with one serial port, then you need to use Software Serial. Software Serial comes with examples in the Arduino IDE by default or you can just go here. I wish you all the best in your project.
doc_23538167
This creates the Image: function createMOImage( objId ) { var img = document.createElement('img'); var leftOffset = document.getElementById( objId ).offsetLeft; img.src = 'images/pre-butt-mo.png'; img.style.position = 'absolute'; img.style.left = leftOffset + "px"; img.style.opacity = '0.2'; img.style.zindex = '9'; img.id = 'temp'; img.onmouseout = function () { moff( objId ); }; return img; } As you can see, the image created is given a mouse out event calling this function: function moff( objId ) { var container = document.getElementById( 'container' ); var temp = document.getElementById( 'temp' ); removeMOImage( ); changeButt( objId ); return; } The change function works perfectly fine but it's not getting called because the JavaScript is being terminated in the removeMOImage() function: function removeMOImage( ) { if ( img = document.getElementById('temp') ) { img.parentNode.removeChild( temp ); } else { return; } } The removeChild function is returning the not found despite the fact the element was successfully recreated in the create function. I tested in IE Chrome Opera and Firefox and the only one having issues is Firefox. There were a few other FF specific issues I had to overcome, most of which were solved from other stack overflow threads; however, I could not find a solution to this issue. This is the full JavaScript c&p from the source: function mon( objId ) { var container = document.getElementById( 'container' ); var img = createMOImage( objId ); container.appendChild( img ); changeButt( objId ); return; } function moff( objId ) { var container = document.getElementById( 'container' ); var temp = document.getElementById( 'temp' ); removeMOImage( ); changeButt( objId ); return; } function createMOImage( objId ) { var img = document.createElement('img'); var leftOffset = document.getElementById( objId ).offsetLeft; img.src = 'images/pre-butt-mo.png'; // change image names to match button ID's img.style.position = 'absolute'; img.style.left = leftOffset + "px"; img.style.opacity = '0.2'; img.style.zindex = '9'; img.id = 'temp'; img.onmouseout = function () { moff( objId ); }; return img; } function removeMOImage( ) { // find cross browser approach. General consensus is to use remove child from the parent div reference but there are alot of issues. // Also have issue with mouse moving over the element causing the element to be deleted even though the mouse never actually leaves the element. // Best Hypothesized solution - move the mouseout event to the MO image // Confirmed solution for Chrome and IE but FF will only delete the image after the first MOut, after recreating the element it stays perminantly if ( img = document.getElementById('temp') ) { img.parentNode.removeChild( temp ); } else { return; } } function changeButt( objId ) { var img = document.getElementById( objId ); var imginv = document.getElementById( objId + "inv" ); var temp = document.getElementById( 'temp' ); if ( temp != null ) { img.src = "images/blank-butt.png"; imginv.src = "images/blank-butt-inv.png"; return; } else { img.src = "images/" + objId + ".png"; imginv.src = "images/" + objId + "inv.png"; return; } } The purpose is to create an image over another image and to delete the image when the mouse is removed from the newly created image ( which is larger than the original image ). It would be VERY much appreciated if this can be solved. I really don't want to use flash. Another issue is that the opacity attribute doesn't seem to work in IE. Ill work on that solution solo unless anyone here has any ideas. And if possible, would some one mind testing on safari? don't have access to a Mac. *I apologize for the stupid notes, they were meant to help me keep track when I walked away from computer. [edit] I fixed the opacity issue. [edit] Resolved the issue by creating an extra variable. A: This is a scoping issue. You define the temp variable in one function and try to refer to it in another function. function moff( objId ) { var container = document.getElementById( 'container' ); removeMOImage( ); changeButt( objId ); } function removeMOImage( ) { var temp = document.getElementById( 'temp' ); if ( temp ) { temp.parentNode.removeChild( temp ); } } You also don't need the return statements at the end. If you don't quit early or return a value, you are imitating what the interpreter does for you anyway.
doc_23538168
Here is my code softwareFolder = "X:\Software\app\2.0" shortcutFolder = "X:\Software\app\SKYNet" pcName = "\\\\" & pcName & "\\c$\\scripts\\2.0" Dim FSO Set FSO = CreateObject("Scripting.FileSystemObject") FSO.CopyFolder softwareFolder , pcName I am trying to copy a folder to \\PCNAME\c$\scripts\2.0 I am getting Path not found
doc_23538169
extension Array where Element == String { func foo(){ } } And consider the following string that I want to split so I can use the extension... let string = "This|is|a|test" let words = string.split(separator: "|") The problem is words is a [Substring] and not [String] so I can't call foo() on it. So in Swift 4, how do I split a string to return a [String] and not a [Substring]? A: As Leo said above, you can use components(separatedBy:) let string = "This|is|a|test" let words = string.components(separatedBy: "|") words.foo() instead, that returns a [String]. If you want to stick with split() (e.g. because it has more options, such as to omit empty subsequences), then you'll have to create a new array by converting each Substring to a String: let string = "This|is|a|test" let words = string.split(separator: "|").map(String.init) words.foo() Alternatively – if possible – make the array extension method more general to take arguments conforming to the StringProtocol protocol, that covers both String and Substring: extension Array where Element: StringProtocol { func foo(){ } }
doc_23538170
Here creditor_group is constructed in both objects.. How to duplicate the Delegate function!? http://jsfiddle.net/q2nxuhyc/2/ code var App = {}; App.module_group = function(main, location, table){ this.init = function(){ console.log('init: '+table+' args: '+main+', '+location); }; this.test = function(){ console.log('test: '+table); }; }; function Delegate(main, location){ this.table; this.module_name; var module; this.init = function(){ module = new App[this.module_name](main, location, this.table); module.init(); return module; }; this.test = function(){ module.test(); }; } var module_1 = Delegate; module_1.prototype.table = 'debtor_group'; module_1.prototype.module_name = 'module_group'; var module_2 = Delegate; module_2.prototype.table = 'creditor_group'; module_2.prototype.module_name = 'module_group'; // This part where the objects are constructed is done in another scope var m_1 = new module_1('main', 'location'); m_1.init(); m_1.test(); var m_2 = new module_2('main', 'location'); m_2.init(); m_2.test(); console init: creditor_group args: main, location test: creditor_group init: creditor_group args: main, location test: creditor_group A: Sounds like you want to use inheritance with two extra constructors module_1 and module_2 that both call the Delegate: function Delegate(main, location) { this.module = null; this.init = function() { // you should do initialisation stuff directly in the // constructor, not an `init` method this.module = new App[this.module_name](main, location, this.table); this.module.init(); }; } Delegate.prototype.test = function(){ this.module.test(); }; function Module_1(main, location) { Delegate.call(this, main, location); } Module_1.prototype = Object.create(Delegate.prototype); Module_1.prototype.table = 'debtor_group'; Module_1.prototype.module_name = 'module_group'; function Module_2(main, location) { Delegate.call(this, main, location); } Module_2.prototype = Object.create(Delegate.prototype); Module_2.prototype.table = 'creditor_group'; Module_2.prototype.module_name = 'module_group';
doc_23538171
https://github.com/se22as/vue-3-with-router-basic-sample When I run the sample application with SSR, I get the following Vue Router Warnings when I go to the home or about page. Can't find documentation for the warnings. Any help would be appreciated. [Vue Router warn]: Path "/" was passed with params but they will be ignored. Use a named route alongside params instead. [Vue Router warn]: Path "/about" was passed with params but they will be ignored. Use a named route alongside params instead. A: The warning is basically letting you know that you need to use a named route instead of a path if you want to pass parameters. So instead of this.$router.push({path:'/', params: { param: someValue } }) and: routes: [ { path: '/', component: Home } You would do something like this.$router.push({name:'Home', params: { param: someValue } }) and: routes: [ { path: '/', name: 'Home', component: Home } Some more info: * *how to use vue-router params *https://router.vuejs.org/guide/essentials/passing-props.html
doc_23538172
My files are that: 1) Controller: package controllers import play.api._ import play.api.mvc._ import play.api.i18n.{I18nSupport,MessagesApi,Messages,Lang} import play.api.i18n.Messages.Implicits._ import play.api.Play.current import javax.inject.Inject class Application @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport { def index = Action { implicit request => Ok(views.html.index("Your new application is ready.")) } } 2) Message resource file: application.name = Orthoclinic welcome = Welcome to play! 3) Main template: @(title: String)(content: Html)(implicit messages: Messages) <!DOCTYPE html> <html lang="en"> <head> <title>@title</title> <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("/assets/stylesheets/main.css")"> <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("/assets/images/favicon.png")"> <script src="@routes.Assets.versioned("/assets/javascripts/hello.js")" type="text/javascript"></script> </head> <body> @Messages("application.name") @content </body> </html> 4) Index template: @(message: String) @main("Welcome to Play") { @play20.welcome(message) } 5) routes file: # Home page GET / controllers.Application.index # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) 6) Application conf file: play.crypto.secret = "k1mIneaPlay_pRoJ" play.i18n.langs = [ "en", "en-us", "pt-br", "es" ] Calling ./activator reload compile run my result is that: [error] /home/josenildo/scala-ide/workspace/orthoclinic-app/app/views/main.scala.html:13: could not find implicit value for para meter messages: play.api.i18n.Messages [error] @Messages("application.name") I have followed the documentation for i18n last version on Play Documentation here. What's the problem on that implementation? A: You just need to add the implicit messages argument to your index.scala.html template: @(message: String)(implicit messages: Messages) @main("Welcome to Play") { @play20.welcome(message) } An implicit Messages instance needs to be in-scope whenever you use i18n via @Messages("my.key"), which has a corresponding implicit messages argument that will be supplied by the compiler (see the signature here). Also, you may want to get rid of import play.api.i18n.Messages.Implicits._, since it shouldn't be required if your controller extends I18NSupport, and indeed may cause an error concerning ambiguous implicit values.
doc_23538173
Created certificate : C:\OpenSSL-Win..\bin>openssl genrsa -aes256 -out private.key 2048 C:\OpenSSL-Win..\bin>openssl rsa -in private.key -out private.key C:\OpenSSL-Win..\bin>openssl req -new -x509 -sha1 -key private.key -out certificate.crt -days 36500 -config C:\OpenSSL-Win..\bin\openssl.cfg What is wrong? Why getting ERR_CERT_COMMON_NAME_INVALID? A: it WORKS. Step 1 A) # openssl genrsa -out server_rootCA.key 2048 # openssl req -x509 -new -nodes -key server_rootCA.key -sha256 -days 3650 -out server_rootCA.pem B) # cat server_rootCA.csr.cnf [req] default_bits = 2048 prompt = no default_md = sha256 distinguished_name = dn [dn] C=BE ST=oost-vlaanderen L=Stackoverflow O=Stackoverflow OU=local_RootCA emailAddress=helpdesk@Stackoverflow.com CN = localhost # cat v3.ext authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alt_names [alt_names] DNS.1 = localhost C) # openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server_rootCA.csr.cnf ) # openssl x509 -req -in server.csr -CA server_rootCA.pem -CAkey server_rootCA.key -CAcreateserial -out server.crt -days 3650 -sha256 -extfile v3.ext Step 2 Use in Apache SSLCertificateFile /etc/apache2/ssl/server.crt SSLCertificateKeyFile /etc/apache2/ssl/server.key Step 3: * *Add PEM to the browser *Chromium -> Setting -> (Advanced) Manage Certificates -> Import -> 'server_rootCA.pem'
doc_23538174
Now i have code that shows me images from device into popover (using UIImagePickerController). How can i (if i can) show those images into UITableViewController or something like it? Thanks. A: UIImagePickerControllers can only be presented in popovers on iPad, trying to present one otherwise will result in an assertion failure stating just that. To get at user photos and display them in a custom way you should look into the Assets Library Framework.
doc_23538175
My application: The user is prompt with a login screen and I create the db, move to another activity to perform a query. From this activity the user cannot go back to login, and will be only able to go to the phone home screen. When I will go to the home screen and re open the application I want to wipe out the db and start like it is my first time the user uses the application. I know that this is not actually practical for an application, but this is just for learning. I tried to do db.close() and context.deleteDatabase(db.getPath()); in onResume and onRestart, but this always crushes my application. I also tried to check that 'db.getPath()!=null' , but this did not help either. thank you A: Since you are aware that is not the most practical way to use databases I guess I won't bug you for that. What you want to do is not to call the method to delete the database content during on Resume() or on Restart(), you actually want to call that via on Stop(). The method you want to use is db.delete(String table, string whereClause, String [] whereArgs); Passing the name of the table you want to delete, i.e "user_food_database", a whereclause which would be null in your case since you want to delete ALL rows, and null for whereArgs. Here's the official doc: "Convenience method for deleting rows in the database. Parameters table the table to delete from whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows. Returns the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. " You can also call: deleteDatabase(File pathToDatabase) in case you have more than one table in your database, but recreating the database itself everytime is expensive, and deleting only the content may result better. A: I suggest that you simply wipe the database, i.e., delete all data (or even drop the tables). This is not a direct answer to your question, but has the same effect. A: Just drop all tables in the open() method of your SQLiteDatabaseHelper and recreate the tables by calling onCreate(db). Works of course only when you are opening the db only once per app start.
doc_23538176
Below is a screenshot of the table The table name is called heating I am trying to get the data from column called 'garage' and row id = 3 I have tried many ways but keep failing. The following is what I have so far but only returns the column name garage for some reason. I am using the following which gives me the name garage $room = 'garage'; require_once "connect.php"; $sql = 'SELECT :name FROM heating WHERE id = 3'; $stmt = $pdo->prepare($sql); $stmt->bindParam(':name', $room); $stmt->execute(); $sw = $stmt->fetch(); echo $sw[0]; If I do the following I gives me the correct outcome but I would like to replace garage with a variable $sql = 'SELECT garage FROM heating WHERE id = 3'; $stmt = $pdo->prepare($sql); $stmt->execute(); $sw = $stmt->fetch(); echo $sw[0]; A: You can create a white list of your column names and use it to select the right column. You can check the column against a white list with the help of in_array. The third parameter is very important as it checks that string is a string. You can only then safely concatenate the SQL with your PHP variables using PHP concatenation operator. For the good measure, the column names should be enclosed in backticks `, in case any of your column names is a reserved word or contains special characters. $whiteListOfHeating = [ 'keyName', 'den', 'WC1', 'hallway', 'garage' ]; $room = 'garage'; if (in_array($room, $whiteListOfHeating, true)) { $sql = 'SELECT `'.$room.'` FROM heating WHERE id = 3'; $stmt = $pdo->prepare($sql); // ... } else { echo 'Invalid column name specified!'; } A: Sometimes simplest solutions are best. require_once "connect.php"; $room = 'garage'; $sql = 'SELECT * FROM heating WHERE id = ?'; $stmt = $pdo->prepare($sql); $stmt->execute([3]); $sw = $stmt->fetch(); echo $sw[$room]; Besides, every time you need such a functionality, in means that most likely your database structure is wrong. A room should be a row, not column require_once "connect.php"; $room = 'garage'; $sql = 'SELECT value FROM heating_room WHERE heating_id=3 and room = ?'; $stmt = $pdo->prepare($sql); $stmt->execute([$room]); $sw = $stmt->fetchColumn(); echo $sw; will make it straight
doc_23538177
* *I would like to keep the information of the checkmark, the way I was trying to do it is by controlling if a checkmark is true or false at the beginning. I've tried putting all of them true by using setItemChecked(i,true) but it's not working... ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_single_choice, getResources().getStringArray(R.array.Stigmate_P)); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setItemChecked(0,true); listView.setItemChecked(1,true); listView.setItemChecked(2,true); *When I'm using setOnItemClickListener, I would like to not change the state of my check mark. I've found a way to do so but I'm positive this isn't the best way. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { if (Var[i] == 2){ listView.setItemChecked(i,true); } else if (Var[i] == 1){ listView.setItemChecked(i,false); } } Here is most of the java code for my listview public class Main2Activity extends AppCompatActivity { public static int POSITION; public static int Var[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; private Toolbar mActionBarToolbar; ListView listView; ImageView ImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (POSITION == 0){ setContentView(R.layout.activity_main4); mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); setSupportActionBar(mActionBarToolbar); setSupportActionBar(mActionBarToolbar); getSupportActionBar().setTitle(" ");} if (POSITION == 1){ setContentView(R.layout.activity_main2); mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mActionBarToolbar); getSupportActionBar().setTitle("Stigmate"); ImageView = (ImageView)findViewById(R.id.imageView2); ImageView.setImageResource(R.drawable.r_stigmate); listView = (ListView)findViewById(R.id.mainMenu2); ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_single_choice, getResources().getStringArray(R.array.Stigmate_P)); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setItemChecked(0,true); listView.setItemChecked(1,true); listView.setItemChecked(2,true); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { if (Var[i] == 2){ listView.setItemChecked(i,true); } else if (Var[i] == 1){ listView.setItemChecked(i,false); } Intent intent = new Intent(Main2Activity.this, Main3Activity.class); intent.putExtra("CountryName",listView.getItemAtPosition(i).toString()); startActivity(intent); int n = 0; for (n= 0; n < 20 ; n++) { if(i==n){ Main3Activity.POSITION3 = n; }} } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) { if (Var[pos] == 1){ listView.setItemChecked(pos,true); Var[pos] = 2; } else if (Var[pos] == 2){ listView.setItemChecked(pos,false); Var[pos] = 1; } return true; } }); listView.setAdapter(mAdapter); } ... Thanks in advance. A: well, first you need set the adapter, then set check able items as checked. please check the note layout should be android.R.layout.simple_list_item_multiple_choice not android.R.layout.simple_list_item_single_choice try below code public class Main2Activity extends AppCompatActivity { public static int POSITION; public static int Var[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; private Toolbar mActionBarToolbar; ListView listView; ImageView ImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (POSITION == 0){ setContentView(R.layout.activity_main4); mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); setSupportActionBar(mActionBarToolbar); setSupportActionBar(mActionBarToolbar); getSupportActionBar().setTitle(" ");} if (POSITION == 1){ setContentView(R.layout.activity_main2); mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mActionBarToolbar); getSupportActionBar().setTitle("Stigmate"); ImageView = (ImageView)findViewById(R.id.imageView2); ImageView.setImageResource(R.drawable.r_stigmate); listView = (ListView)findViewById(R.id.mainMenu2); // make note : android.R.layout.simple_list_item_multiple_choice not android.R.layout.simple_list_item_single_choice ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.Stigmate_P)); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // add this lines after you set the adapter /*listView.setItemChecked(0,true); listView.setItemChecked(1,true); listView.setItemChecked(2,true);*/ listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { if (Var[i] == 2){ listView.setItemChecked(i,true); } else if (Var[i] == 1){ listView.setItemChecked(i,false); } Intent intent = new Intent(Main2Activity.this, Main3Activity.class); intent.putExtra("CountryName",listView.getItemAtPosition(i).toString()); startActivity(intent); int n = 0; for (n= 0; n < 20 ; n++) { if(i==n){ Main3Activity.POSITION3 = n; }} } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) { if (Var[pos] == 1){ listView.setItemChecked(pos,true); Var[pos] = 2; } else if (Var[pos] == 2){ listView.setItemChecked(pos,false); Var[pos] = 1; } return true; } }); listView.setAdapter(mAdapter); // here you should set checked items listView.setItemChecked(0,true); listView.setItemChecked(1,true); listView.setItemChecked(2,true); }
doc_23538178
I have proved that the sent and received timeframes equal to the streamed video (by exporting out the sent and received time frames). my suspicion is that the HTTP Server doesn't automatically refresh or write the received timeframe every new messages are received. KafkaProducer import cv2 import io from PIL import Image from kafka import KafkaProducer def recordedVid(video_file): producer = KafkaProducer( bootstrap_servers='localhost:9092' ) cap = cv2.VideoCapture(video_file) while(cap.isOpened()): ret, frame = cap.read() ret, buffer = cv2.imencode('.jpg', frame) toStream = buffer.tobytes() producer.send('Video', toStream) print('sent') time.sleep(0.1) cap.release() print('done') recordedVid('sample.mp4') KafkaConsumer import cv2 import socket from http.server import HTTPServer, BaseHTTPRequestHandler from kafka import KafkaConsumer from PIL import Image import numpy as np import io from ensurepip import bootstrap def extract_IP(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) HOST = s.getsockname()[0] return HOST def msg_process(msg) : frame_bytes = msg.value frame_arr = np.frombuffer(frame_bytes, np.uint8) frame = cv2.imdecode(frame_arr, cv2.IMREAD_COLOR) img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) toLoad = io.BytesIO() img.save(toLoad, format='JPEG') return toLoad.getvalue() consumer = KafkaConsumer( "Video", bootstrap_servers = 'localhost:9092' ) class Display(BaseHTTPRequestHandler): def do_GET(self): for msg in consumer: frame = msg_process(msg) self.send_response(200) self.send_header("Content-type", "image/jpeg") self.end_headers() self.wfile.write(frame) HOST = extract_IP() PORT = 9999 server = HTTPServer((HOST, PORT), Display) print("server is now running in ", HOST," and Port ", PORT) server.serve_forever() server.server_close() Did I miss something or is there any workaround for my problem?
doc_23538179
I am trying to do it whit the next query: SELECT UPPER(conname) AS restriccion, UPPER(relname) AS tabla, UPPER(pg_catalog.pg_attribute.attname) AS columna FROM pg_catalog.pg_constraint, pg_catalog.pg_class, pg_catalog.pg_attribute WHERE contype = 'u' AND conrelid = pg_catalog.pg_class.oid AND conrelid = pg_catalog.pg_attribute.attrelid AND pg_catalog.pg_attribute.attnum = pg_catalog.pg_constraint.conkey[1] ORDER BY UPPER(conname), UPPER(relname), UPPER(pg_catalog.pg_attribute.attname); I am doing it changing the letter 'u' with 'c' to see the check constraints but it is a bit difficult... Is there another way to see all the constraint in only one query? Thanks! A: For just looking for check and unique constraints, does the following get you started? SELECT nr.nspname AS table_schema, r.relname AS table_name, c.conname AS constraint_name, CASE WHEN c.contype = 'c' THEN c.consrc END AS search_condition, CASE WHEN c.contype = 'u' THEN split_part ( split_part ( pg_get_constraintdef ( c.oid ), '(', 2 ), ')', 1 ) END AS column_names, d.description AS comments FROM pg_class r INNER JOIN pg_namespace nr ON ( nr.oid = r.relnamespace ) INNER JOIN pg_constraint c ON ( c.conrelid = r.oid ) INNER JOIN pg_namespace nc ON ( nc.oid = c.connamespace ) LEFT OUTER JOIN pg_description d ON ( d.objoid = c.oid ) WHERE r.relkind = 'r' AND c.contype IN ( 'c', 'u' ) ORDER BY r.relname, c.conname ; Update 2016-04-14: Not null constraints are not to be found in the pg_constraint table. The pg_attribute table has that information: SELECT nr.nspname AS table_schema, r.relname AS table_name, null::text AS constraint_name, 'Not Null'::text AS null_condition, a.attname AS column_name, pg_catalog.col_description ( a.attrelid, a.attnum ) AS comments FROM pg_catalog.pg_class r LEFT OUTER JOIN pg_catalog.pg_namespace nr ON ( nr.oid = r.relnamespace ) LEFT OUTER JOIN pg_catalog.pg_attribute a ON ( c.oid = a.attrelid AND a.attnum > 0 AND NOT a.attisdropped ) WHERE r.relkind IN ( 'r', 'f', 'm' ) -- tables(r), foreign tables(f), and materialized views(m) AND a.attnotnull ORDER BY nr.nspname, r.relname, a.attname ;
doc_23538180
I have this function: double readableDouble( double input ) { return (int)(input*100+0.5)/100.0; } As you can see, nothing special. Now I call the function from another function (in the same class): cout << readableDouble(4434.21121131234323243) <<endl; // result: 4434.22 all okay cout << readableDouble(tempTrack.getLenght()/1000.0); // result: 30.56 all okay string lenght = boost::lexical_cast<string>(readableDouble((tempTrack.getLenght()/1000.0))); // result 30.55999999999982. expected: 30.56 getLenght() returns a double. (same double for both calls) I am not quite sure how this is happening? . A: From another post (Credit to Mic): From the documentation for boost lexical_cast: For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast. Example: #include <sstream> #include <iomanip> int main() { std::ostringstream ss; double x = 5; ss << std::fixed << std::setprecision(2); ss << x; std::string s = ss.str(); return 0; }
doc_23538181
Now, in the catch() block of my promise chain in case of an error an error object is passed which on console.error(err) prints: [ReferenceError: number is not defined] What kind of object is this? console.error(JSON.stringify(err)); prints: {} console.log(err instanceof Array); prints: false console.log(Object.keys(err)); prints: [] console.log(typeof err); prints: object Also, how do I differentiate it from an empty {}?
doc_23538182
i,j = 3,3 for i in range(10): j = i print(i,j) to print me "3 9", but in reality it prints me "9 9". I'm coming from lua, and this is possible to do since a local variable "i" is automatically created for the cycle, so that there's an "i" that reaches 9 inside the loop, but there's still an "i" outside the loop that's still at 3. Is this possible? Or do i must use a variable that has not previously been used? A: You are itself iterating with i where it is already declared before with j as 3 and in loop, values of both variables increase. So use a different variable. If you add a print(i,j) you will see both increase by 1 in each iteration, because i is the variable which is used to iterate over the range, so the old i value gets overwritten. Perhaps use a different variable like k to iterate instead of i. Or instead variables have scope, global and local, then use the global keyword. List comprehension could be considered.
doc_23538183
var Class = function(){ var klass = function(){ this.init.apply(this, arguments); console.log("here"); }; klass.prototype.init = function(){ console.log("another"); }; return klass; }; window.Person = new Class; executing Person() will log "here" to the console. I tried accessing the prototype by using Person.klass.init() with no success. Can someone supplement another way of explaining this? The book says "we could return a function that would set up a new class, the first step in building our own class emulation library:" A: How would i access the klass.prototype.init function By window.Person.prototype.init. klass is what is returned from Class(), and is assigned to window.Person. Btw you shouldn't use new with Class here.
doc_23538184
The path I am using is @"C:\Test\Test.txt". When I change to relative addressing (i.e., @".\Test.txt") and have the file in the exe folder, it will work. What I need to know is relative addressing the only option to upload a file to Azure File Storage from a .NET client? Is there a way to reference a file with a full path and upload to File Storage? Update: Based on the comments and answer below, I realized my mistake: I was supplying the incoming file path to the GetFileReference method, where this should be the name of the new file in Azure, hence it contained the ':' which was invalid. Comments are right, I should have provided code, may have been diagnosed easier. public static async Task WriteFileToStorage(string filePath) { CloudFileShare fileShare = GetCloudFileShare(); CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference(); CloudFile cloudFile = fileDirectory.GetFileReference(filePath); await cloudFile.UploadFromFileAsync(filePath); } A: .Net client does support the full path when upload to azure file storage. You'd better provide the complete code you're using including the file name / path in local and azure file storage. Here is the code I test with, and it works.(and I'm using the package WindowsAzure.Storage, version 9.3.3 ): static void Main(string[] args) { CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("account_name", "account_key"), true); CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); CloudFileShare fileShare = fileClient.GetShareReference("test"); CloudFileDirectory rootDir = fileShare.GetRootDirectoryReference(); CloudFile myfile = rootDir.GetFileReference("mytest.txt"); //the full file path on local myfile.UploadFromFile(@"C:\Test\Test.txt"); }
doc_23538185
The table columns are identical other than the destination table (tab@db2) has a few more columns which causes a simple INSERT to fail. I'd like to use a simple PL/SQL statement to build a list of the columns in tab@db2 dynamically instead of typing out the names of col1, col2, etc in the INSERT and SELECT clause. Example declare a variable as var_col_list set col_list = output of select * from tab (omitting rows) INSERT INTO TAB *var_col_list* SELECT *var_cols_list* FROM TABLE TAB@db2 I've researched using %rowtype but cannot find a suitable example that would take less time than simply writing out the names of the columns! Any advice is greatly appreciated A: If you use e.g. TOAD, you can right-click the table and let it Generate statement - in your case, that would be INSERT. You'd slightly modify it (remove columns you don't need) and that's all. Otherwise, this is how you might do it semi-manually. This is my source table: SQL> SELECT * FROM dept; DEPTNO DNAME LOC ---------- -------------------- -------------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Target table doesn't contain all columns: SQL> CREATE TABLE target 2 ( 3 deptno NUMBER, 4 dname VARCHAR2 (20) 5 ); Table created. Code which loops through all TARGET table columns (i.e. a table which has less columns) and composes the INSERT INTO statement: SQL> DECLARE 2 l_str VARCHAR2 (1000); 3 BEGIN 4 FOR cur_r IN (SELECT column_name 5 FROM user_tab_columns 6 WHERE table_name = 'TARGET') 7 LOOP 8 l_str := l_str || ', ' || cur_r.column_name; 9 END LOOP; 10 11 l_str := 12 'insert into target select ' || LTRIM (l_str, ', ') || ' from dept'; 13 DBMS_OUTPUT.put_line (l_str); 14 15 EXECUTE IMMEDIATE l_str; 16 END; 17 / insert into target select DEPTNO, DNAME from dept --> this is the L_STR contents PL/SQL procedure successfully completed. SQL> SELECT * FROM target; DEPTNO DNAME ---------- -------------------- 10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS Seems to be OK. A: Using the solution provided by Littefoot, I made some minor tweaks to fit my requirement perfectly: SQL> create table taba (col1 number,col2 number); SQL> insert into taba values (1,2); SQL> select * from taba; COL1 COL2 ---------- ---------- 1 2 SQL> create table tabb (col1 number,col2 number, col3 number); SQL> DECLARE l_str VARCHAR2 (32767); BEGIN FOR cur_r IN (SELECT column_name FROM user_tab_columns WHERE table_name = 'TABA' order by column_id asc) LOOP l_str := l_str || ', ' || cur_r.column_name; END LOOP; l_str := 'insert into tabb (' || LTRIM (l_str, ', ') || ') ' ||' select ' || LTRIM (l_str, ', ') || ' from taba'; DBMS_OUTPUT.put_line (l_str); EXECUTE IMMEDIATE l_str; END; / Output of l_str (SQL INSERT): insert into tabb (COL1, COL2) select COL1, COL2 from taba Result: SQL> select * from tabb; COL1 COL2 COL3 ---------- ---------- ---------- 1 2
doc_23538186
I am using PHP here, and I don't know how to create a query for this. This is the data in my table. tblaccess_event_logs USERID | User_FirstName | User_LastName | EVENTID | LOCAL_TIMESTAMP(Y-m-d) | 2222 | Zack | Hewit | IN | 2014-10-09 08:30:00 2222 | Zack | Hewit | OUT | 2014-10-09 17:30:00 This is the output I want: USERID | User_FirstName | User_LastName | IN | OUT | 2222 | Zack | Hewit | 09 08:30:00 | 17:30:00 | A: This should work.. select USERID,User_FirstName,User_LastName, time(min(LOCAL_TIMESTAMP(Y-m-d))) as In, # get the time part time(Max(LOCAL_TIMESTAMP(Y-m-d))) as out # get the time part from tblaccess_event_logs group by USERID,User_FirstName,User_LastName A: try this..... SELECT USERID, User_FirstName, User_LastName, MIN(LOCAL_TIMESTAMP(Y-m-d)) AS IN, MAX(LOCAL_TIMESTAMP(Y-m-d)) AS OUT FROM tblaccess_event_logs GROUP BY USERID this will work if zack is having 1 in and 1 out only, but what if zach have 2 log in and 2 log out? having log_id field in yout table will be a great help in the near future.
doc_23538187
I made FTP Accounts as below; FTP Username: ****@*********.org FTP server: ****.****.org FTP & explicit FTPS port: 21 I need suggestion on how to connect to public_html/ folder from JetBrains PhpStorm and then synch files. A: Follow those steps: * *Go to: File -> New Project from Existing Files... *Select: Web server is on remote host, files are accessible via FTP/SFTP/FTPS *Give a name and a path for the local copy of the project *Select: Add new remote server *Fill all the fields *Select as root folder the public_html folder A: There is no reference in the previous answer on how to connect to cpanel instance, I had this issue too. In PHPStorm's deployment menu there is a field to add the Host, now PHPStorm's connections have a prefixed ftp:// (or sftp, depends what you choose). Cpanel also has it's own stipulated connection method, it defaults to create your entry host as ftp.yoursite.com PHPStorm interprets this as ftp://ftp.yoursite.com, thus you get an error. This is what you should do to connect successfully: * *use SFTP *write your host name as a top level domain (TLD) yoursite.com *use port 22 *write root path with your user name: home/user-name *fill in your user name and then password That worked for me.
doc_23538188
EF Core POCOS: public class Farmer { [Key] public int FarmerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } //changed entities public virtual ICollection<Chicken> ChangedChickens { get; set; } public virtual ICollection<Cow> ChangedCows { get; set; } } public class Chicken { [Key] public int ChickenId { get; set; } public bool IsRooster { get; set; } //common change props public int LastChangeByFarmerId { get; set; } public DateTime LastChangeTimestamp { get; set; } [ForeignKey("LastChangeBy")] public virtual Farmer LastChangeFarmer { get; set; } } public class Cow { [Key] public int CowId { get; set; } public string Name { get; set; } //common change props public int LastChangeByFarmerId { get; set; } public DateTime LastChangeTimestamp { get; set; } [ForeignKey("LastChangeBy")] public virtual Farmer LastChangeFarmer { get; set; } } I would like to use a base class for the change properties in my data transfer classes: DTOs public abstract class FarmerChangeDtoBase { public int LastChangeBy { get; set; } public DateTime LastChangeTime { get; set; } public string ChangingFarmerFirstName { get; set; } public string ChangingFarmerLastName { get; set; } public string ChangingFarmerFullName => $"{ChangingFarmerFirstName} {ChangingFarmerLastName}"; } public class ChickenDto : FarmerChangeDtoBase { public int ChickenId { get; set; } public bool IsRooster { get; set; } } public class CowDto : FarmerChangeDtoBase { public int CowId { get; set; } public string Name { get; set; } } I wrote an extension method to get LastChangeBy and LastChangeTime values using reflection, which may not be ideal, but I cannot figure out how to get the nested properties for the farmer name. Here's the extension method: public static IMappingExpression<TSource, TDest> MapChangeFarmer<TSource, TDest>( this IMappingExpression<TSource, TDest> mappingExpression) where TDest : FarmerChangeDtoBase { return mappingExpression.ForMember(d => d.LastChangeBy, opt => opt.MapFrom(s => (int) s.GetType().GetProperty("LastChangeByFarmerId").GetValue(s))) .ForMember(d => d.LastChangeTime, opt => opt.MapFrom(s => (DateTime) s.GetType().GetProperty("LastChangeTimestamp").GetValue(s))); //what/how can I map the name properties??? } Is there any way I can map the nested properties LastChangeFarmer.FirstName and LastChangeFarmer.LastName in the extension method, rather than having to write it out for every single DTO inheriting from FarmerChangeDtoBase? A: Rather than trying to map destination inheritance without source inheritance, let solve the origin of the issue - the lack of source inheritance. EF (Core) inheritance is a concept of modeling an entity inheritance around a single polymorphic abstract entity set and mapping it to a single table (TPH) or multiple tables (TPT or TPC). However EF (Core) does not prohibit using POCO class inheritance without using EF inheritance - there is absolutely no problem of using base classes containing a common entity properties like in your case. For instance, the sample model produces the following tables for Chicken and Cow entities: migrationBuilder.CreateTable( name: "Chicken", columns: table => new { ChickenId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), IsRooster = table.Column<bool>(nullable: false), LastChangeByFarmerId = table.Column<int>(nullable: false), LastChangeTimestamp = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Chicken", x => x.ChickenId); table.ForeignKey( name: "FK_Chicken_Farmer_LastChangeByFarmerId", column: x => x.LastChangeByFarmerId, principalTable: "Farmer", principalColumn: "FarmerId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Cow", columns: table => new { CowId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), LastChangeByFarmerId = table.Column<int>(nullable: false), LastChangeTimestamp = table.Column<DateTime>(nullable: false), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Cow", x => x.CowId); table.ForeignKey( name: "FK_Cow_Farmer_LastChangeByFarmerId", column: x => x.LastChangeByFarmerId, principalTable: "Farmer", principalColumn: "FarmerId", onDelete: ReferentialAction.Cascade); }); If we extract a base class with the common properties and let the Chicken and Cow inherit from it: public abstract class FarmerChangeBase { public int LastChangeByFarmerId { get; set; } public DateTime LastChangeTimestamp { get; set; } [ForeignKey("LastChangeByFarmerId")] public virtual Farmer LastChangeFarmer { get; set; } } public class Chicken : FarmerChangeBase { [Key] public int ChickenId { get; set; } public bool IsRooster { get; set; } } public class Cow : FarmerChangeBase { [Key] public int CowId { get; set; } public string Name { get; set; } } the resulting migration (hence the mapping) is exactly the same as the previous one without using inheritance. Once you do that, the mapping method is simple due to the appropriate generic type constraints: public static IMappingExpression<TSource, TDest> MapChangeFarmer<TSource, TDest>( this IMappingExpression<TSource, TDest> mappingExpression) where TSource : FarmerChangeBase where TDest : FarmerChangeDtoBase { return mappingExpression .ForMember(d => d.LastChangeBy, opt => opt.MapFrom(s => s.LastChangeByFarmerId)) .ForMember(d => d.ChangingFarmerFirstName, opt => opt.MapFrom(s => s.LastChangeFarmer.FirstName)) .ForMember(d => d.ChangingFarmerLastName, opt => opt.MapFrom(s => s.LastChangeFarmer.LastName)) .ForMember(d => d.LastChangeTime, opt => opt.MapFrom(s => s.LastChangeTimestamp)); } P.S. To answer the original question, in case by some reason you can't use source inheritance, the following custom extension method builds dynamically the required expression from a string containing a property path: public static void MapFromPath<TSource, TDestination, TMember>(this IMemberConfigurationExpression<TSource, TDestination, TMember> opt, string memberPath) { var source = Expression.Parameter(typeof(TSource), "s"); var member = memberPath.Split('.').Aggregate( (Expression)source, Expression.PropertyOrField); var selector = Expression.Lambda<Func<TSource, TMember>>(member, source); opt.MapFrom(selector); } It can be used this way: public static IMappingExpression<TSource, TDest> MapChangeFarmer<TSource, TDest>( this IMappingExpression<TSource, TDest> mappingExpression) where TDest : FarmerChangeDtoBase { return mappingExpression .ForMember(d => d.LastChangeBy, opt => opt.MapFromPath("LastChangeByFarmerId")) .ForMember(d => d.ChangingFarmerFirstName, opt => opt.MapFromPath("LastChangeFarmer.FirstName")) .ForMember(d => d.ChangingFarmerLastName, opt => opt.MapFromPath("LastChangeFarmer.LastName")) .ForMember(d => d.LastChangeTime, opt => opt.MapFromPath("LastChangeTimestamp")); }
doc_23538189
Result of calling the function .CSS files are not going thro, ie. text/css.
doc_23538190
try { } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { } catch (NullPointerException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } A: http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html Any sub-class of Exception you can see there is going to be catched by the try catch Exception. NumberFormatException and NullpointerException are also Exception, but they're neither a sub-class of each other. That is, the first try-catch you stated won't catch a NullPointerException and vice-versa. A: your syntax doesn't make sense, you can catch multiple exceptions, the most specific/narrow class of exception higher on the list: try { ..code here... } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NullPointerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
doc_23538191
>>> bytes = ['0xa6', '0x7b'] If I modify these string bytes: >>> big5_str = '' >>> for hexVal in bytes: >>> newHexVal = '\\' + hexVal[1:] >>> big5_str += newHexVal so they appear as: >>> print big5_str >>> '\xa6\x7b' but big5_str actually has the escape '\' still in the string: >>> big5_str >>> '\\xa6\\x7b' and if i decode using big5, I only get the same string back (due to the double-backslash): >>> print byte_string.decode('big5') >>> '\xa6\x7b' If I explicitly code the the byte sequence as the hex values: >>> bytes2 = '\xa6\x7b' >>> print bytes2.decode('big5') >>> 州 My question is, how can I read these bytes, format them in '\x**' format them so that they are recognized as bytes, not strings, using a non-escaped backslash?
doc_23538192
i have increased my max upload to 500m and i included enctype but it still does the same thing html <form action="apps/course/uploadvideo.php" method="post" enctype="multipart/form-data"> <input style="display: none" type="file" name="videos[]" id='video1' multiple="multiple" accept=".mov,.mp4" /> <input style="display: none" type="file" name="videos[]" id='video2' multiple="multiple" accept=".mov,.mp4" /> <input style="display: none" type="file" name="videos[]" id='video3' multiple="multiple" accept=".mov,.mp4" /> <input type="submit" value="Submit Videos" class="btn btn-primary btn-user btn-block"> </form> php code if(isset($_FILES['videos'])){ $name_array = $_FILES['videos']['name']; $tmp_name_array = $_FILES['videos']['tmp_name']; $type_array = $_FILES['videos']['type']; $size_array = $_FILES['videos']['size']; $error_array = $_FILES['videos']['error']; for($i = 0; $i < count($tmp_name_array); $i++){ if(move_uploaded_file($tmp_name_array[$i], "../../../../upload/".$name_array[$i])){ echo $name_array[$i]." upload is complete<br>"; } else { echo "move_uploaded_file function failed for ".$name_array[$i]."<br>"; } } } after var dumping it outputs this array (size=0) empty I expect it to move to the required folder
doc_23538193
I am using cv2.imshow but it only displays the image for the user that runs the code. Thanks A: I was able to display the images on another user/host by setting the DISPLAY environment variable of the X server to match the desired user's DISPLAY.
doc_23538194
I'm just testing Java multi-threading stuff, this is not real code. I wonder how to make two member variables update at the same time in Java, in case we want them both in sync. As an example: public class Testing { private Map<String, Boolean> itemToStatus = new ConcurrentHashMap<>(); private Set<String> items = ConcurrentHashMap.newKeySet(); public static void main(String[] args) { (new Testing()).start("ABC"); } public void start(String name) { if (name.equals("ABC")) { itemToStatus.put(name, true); items.add(name); } } } In that scenario (imagine multi-threaded, of course) I want to be able to guarantee that any reads of items and itemToStatus always return the same. So, if the code is in the line itemToStatus.put(name, true), and other thread asks items.contains(name), it will return false. On the other hand, if that other thread asks itemToStatus.containsKey(name); it will return true. And I don't want that, I want them both to give the same value, if that makes sense? How can I make those two changes atomic? Would this work? if (name.equals("ABC")) { synchronised(this) { itemToStatus.put(name, true); items.add(name); } } Still, I don't see why that would work. I think that's the case where you need a lock or something? Cheers! A: Just synchronizing the writes won't work. You would also need to synchronize (on the same object) the read access to items and itemToStatus collections. That way, no thread could be reading anything if another thread were in the process of updating the two collections. Note that synchronizing in this way means you don't need ConcurrentHashMap or ConcurrentHashSet; plain old HashMap and HashSet will work because you're providing your own synchronization. For example: public void start(String name) { if (name.equals("ABC")) { synchronized (this) { itemToStatus.put(name, true); items.add(name); } } } public synchronized boolean containsItem(String name) { return items.contains(name); } public synchronized boolean containsStatus(String name) { return itemToStatus.containsKey(name); } That will guarantee that the value returned by containsItem would also have been returned by containsStatus if that call had been made instead. Of course, if you want the return values to be consistent over time (as in first calling containsItem() and then containsStatus()), you would need higher-level synchronization. A: The short answer is yes: by synchronizing the code block, as you did in your last code snippet, you made the class thread-safe because that code block is the only one that reads or modifies the status of the class (represented by the two instance variables). The meaning of synchronised(this) is that you use the instance of the object (this) as a lock: when a thread enters that code block it gets the lock, preventing other threads to enter the same code block until the thread releases it when it exits from the code block.
doc_23538195
Using Webclient I am able to download file but the webclient only gives me access to its dwonloaded bytearray when the file download is complete. Is there a way to download the file and make modifications to the file's byte array on the fly in Silverlight. I can not use Sockets, I can only download files from a Webserver. Any help from you Gurus are appreciated A: I can't see what is the problem with the Webclient. You should copy the results of the WebClients in byte arrays. Once every file has been downloaded, you can merge those byte arrays. byte[] bytes; public void DownloadFile() { WebClient webClient = new WebClient(); webClient.OpenReadCompleted += (s, e) => { Stream stream = e.Result; MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); bytes = ms.ToArray(); }; webClient.OpenReadAsync(new Uri("http://myurl.com/file.zip"), UriKind.Absolute); }
doc_23538196
<select id="country"> <option value="">Any</option> <option value="ENGLAND">England</option> <option value="IRELAND">Ireland</option> <option value="SCOTLAND">Scotland</option> <option value="WALES">Wales</option> </select> <select id="county"> <option value="">Select a country first...</option> </select> <div style="clear:both">&nbsp;</div> <select id="country"> <option value="">Any</option> <option value="ENGLAND">England</option> <option value="IRELAND">Ireland</option> <option value="SCOTLAND">Scotland</option> <option value="WALES">Wales</option> </select> <select id="county"> <option value="">Select a country first...</option> </select> Not sure how to I change the JavaScript code so the second county drop down list functions same as the first one. The existing javascript and how it functions can be seen here: http://jsfiddle.net/pfYEb/10/ A: You'll probably want to use class="country" instead of id="country" so that your selector will match both. (same for your id="county") In your jsfiddle, you'll also need to distinguish which county to change within your country change event. One easy way to do this is to use the index of the current element. I've forked your jsfiddle here. HTML <select class="country"> <option value="">Any</option> <option value="ENGLAND">England</option> <option value="IRELAND">Ireland</option> <option value="SCOTLAND">Scotland</option> <option value="WALES">Wales</option> </select> <select class="county"> <option value="">Select a country first...</option> </select> <div style="clear:both">&nbsp;</div> <select class="country"> <option value="">Any</option> <option value="ENGLAND">England</option> <option value="IRELAND">Ireland</option> <option value="SCOTLAND">Scotland</option> <option value="WALES">Wales</option> </select> <select class="county"> <option value="">Select a country first...</option> </select> ​ Relevant Javascript: $('.country').change(function() { var country = $(this).val(), county = $('.county').eq($(".country").index(this)); // This matches the county // Empty county dropdown county.empty(); // Update dropdown with appropriate contents if (country === '') { county.append('<option value="">Select a country first...</option>'); } else { $.each(counties[country], function(i, v) { county.append('<option value="' + i + '">' + v + '</option>'); }); } }); A: You can't really solve this querying by id. Element ID's have to be unique within a document by specification by the way. Your best shot, use classes instead.
doc_23538197
These are the resize method. Thank you in advance func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } NSLayoutConstraint.activate([ textView.topAnchor.constraint(equalTo: self.topAnchor, constant: 10), textView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10), textView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10), textView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10) ]) NSLayoutConstraint.activate([ button.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 50), button.bottomAnchor.constraint(equalTo: self.bottomAnchor), button.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20), button.widthAnchor.constraint(equalToConstant: 20), button.heightAnchor.constraint(equalToConstant: 10) ]) A: Default behaviour of UITableView will handle it on its own. Make sure that you didn't set anything custom for table view. Second thing is UITableViewCell where you need to specify height for each UI component - this will allow UITableView to resize cell properly. Edit.1 If you are creating your view controller from xib/storyboard, then you would need just do this for your tableView (notice that cell is loaded from nib and view controller conforms UITableViewDataSource) override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.register(UINib(nibName: "YourCellNibName", bundle: nil), forCellReuseIdentifier: "reuseIdentifier") } A: You have a height conflict because of these 3 constraints textView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10), button.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 50), button.bottomAnchor.constraint(equalTo: self.bottomAnchor), You need to also add the textView & button to contentView and set the constraints with it NSLayoutConstraint.activate([ textView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10), textView.leadingAnchor.constraint(equalTo:self.contentView.leadingAnchor, constant: 10), textView.trailingAnchor.constraint(equalTo:self.contentView.trailingAnchor, constant: -10), textView.heightAnchor.constraint(equalToConstant:50), button.topAnchor.constraint(equalTo: self.textView.bottomAnchor, constant: 50), button.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), button.leftAnchor.constraint(equalTo:self.contentView.leftAnchor, constant: 20), button.widthAnchor.constraint(equalToConstant: 20), button.heightAnchor.constraint(equalToConstant: 10) ]) A: You can do something like this. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { // First table cell if firstLoad { return 200 // Fixed height } else { return UITableView.automaticDimension } } } Also you might need to re-trigger the heightForRowAt method by doing self.tableView.beginUpdates() self.tableView.endUpdates() Hope it helps! A: set the bottom constraint of the button to the bottom constraint of the cell contentView. The autolayout will automatically manage the cell height.
doc_23538198
var option_tinymce = { script_url : '/ui/js/tinymce/tinymce.min.js', plugins: "code autosave insertdatetime textcolor print", toolbar1: "print code | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | undo redo | removeformat | forecolor backcolor | formatselect | restoredraft", menubar: false, toolbar_items_size: 'small', language: 'fr_FR', setup: function(editor) { editor.on('change', function(e) { $(editor.formElement).find('[name="modification_form"]').val("Yes"); }); }, skin: 'pvx_light', content_css: "/ui/css/style.css, /ui/css/style_tiny.css", schema: "html5", autosave_restore_when_empty: false, resize : 'both' }
doc_23538199
[ServiceContract] public interface IHealthProducts { [OperationContract()] ResponseClass OrderSelfSignedHealthCertificate(); } Which returns the following type [MessageContract] public class ResponseClass { [MessageBodyMember] public string AnimalSpeciesCode { get; set; } [MessageBodyMember] public int VBN { get; set; } } I expected that the generated client code would expose the OrderSelfSignedHealthCertificate method in the following way: HealthProductsClient client = new HealthProductsClient(); ResponseClass response = client.OrderSelfSignedHealthCertificate(); Instead, the properties of ResponseClass aren't wrapped in the ResponseClass, but exposed like so: string OrderSelfSignedHealthCertificate(out int VBN) When I exchange the MessageContract for a DataContract attribute and the MessageBodyMember for a DataMember attribute, I get the expected behaviour (ResponseClass response type). I need the MessageContract however, because I need to put some of the properties in the SOAP header. Am I doing something wrong? Is this normal behaviour? How do I get a ResponseClass return type, when using a MessageContract? Any help greatly appreciated. A: When your [MessageContract] contains more than one [MessageBodyMember], then WCF will return the first one as return value from the service call (AnimalSpeciesCode in your case), and all others are returned as out or ref paraemters. You can solve this by having only a single [MessageBodyMember] in your message contract that encapsulates all items you need to have return, something like this: [DataContract] class CompoundData { public string AnimalSpeciesCode { get; set; } public int VBN { get; set; } } [MessageContract] public class ResponseClass { [MessageBodyMember] public CompoundData Payload { get; set; } } In this case, the CompoundData should be the return value from your service call - containing both elements you need. A: Thanks Marc, that did it. I made a generic ResponseWrapper class to encapsulate the return types: [MessageContract(WrapperNamespace = "http://mynamespace.com")] public class ResponseWrapper<T> { [MessageBodyMember(Namespace = "http://mynamespace.com")] public T Response { get; set; } } I have defined the returntype of OrderSelfSignedHealthCertificate to be ResponseWrapper<ResponseClass> OrderSelfSignedHealthCertificate(); In my client code this translate to ResponseClass OrderSelfSignedHealthCertificate(); Which is what I wanted. Thanks!