id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_2500
*asfaa@asadaf:~/test$ git review -R Could not connect to gerrit. Enter your gerrit username: remote0 Trying again with ssh://<username>@<ip>:29418/test Creating a git remote called "gerrit" that maps to: ssh://<username>@<ip>:29418/test This repository is now set up for use with git-review. You can set the default username for future repositories with: git config --global --add gitreview.username "remote0" Your change was committed before the commit hook was installed. Amending the commit to add a gerrit change id. remote: Processing changes: refs: 1, done To ssh://<username>@<ip>:29418/test ! [remote rejected] HEAD -> refs/publish/master (no common ancestry) error: failed to push some refs to 'ssh://<username>@<ip>:29418/test'* I get this error after the steps below; * *I create a gerrit folder with the command "ssh -p 29418 user@localhost gerrit create-project project_name" *Then, i create a folder with the same same in my home directory and convert it to a git repo with "git init" command. *Then, i copy all the content of the project that i want to push to the gerrit repository in this folder and add all the changes as new changes using "git add --all" command *I create a .gitreview file and put the host and project attributes in it. *Commit my changes. *And lastly, i use "git review -R" command to send my changes to gerrit repository to be reviewed. Here, in the last step, if i use this command git push ssh://[username]@[ip]:29418/project_name, it works. But in this case there is no point in using gerrit repository because i push them directly to git without any review made. Moreover, i assume i will have to deal with this error later when i clone this project to another computer and send my changes to the gerrit repository, so it is better if i learn what am i doing wrong in the above. Thanks in advance A: Instead of doing git init in a new directory and adding your code I would recommend you clone your new, empty, gerrit repository and make the changes there. So to amend your steps: * *Create a gerrit folder with the command "ssh -p 29418 user@localhost gerrit create-project project_name" *Clone project_name : clone ssh://user@localhost:29418/project_name *Copy all the content of the project you want and "git add --all" *Create a .gitreview file and put the host and project attributes in it *Commit changes *git review A: The reason for HEAD -> refs/publish/master (no common ancestry) is probably because that master (local) has not been hooked onto master (remote, usually: origion/master). To ensure this, you can run git config --list and look for: branch.master.remote=origin branch.master.merge=refs/heads/master If this is missing you may set it manually and directly (better not): git config --local branch.master.remote=origin git config --local branch.master.merge=refs/heads/master or better using: git branch --set-upstream-to=origin/master master the branch name is got from: git branch --all mine is: $ git branch --all * master remotes/gerrit/master remotes/origin/master
doc_2501
d = {'state': ['United States', 'IT', 'Spain', 'JP', 'FR'], 'continent': ['North America', 'Europe', 'Europe', 'Asia', 'Europe']} df = pd.DataFrame(data=d) with two columns, df['state'] and df['continent']: United States North America IT Europe Spain Europe JP Asia FR Europe I want to create a new column that is composed in this way: for state in df['state']: if(len(state) <= 2): # df['newCol'] = df['continent'] + ' - ' + df['state'] So that the result would be: United States Europe - IT Spain Asia - JP Europe - FR But I have some problems with the iteration of the dataset... A: Use np.where: df['new'] = np.where(df['state'].str.len() <= 2, df['continent'] + ' - ' + df['state'], df['state']) Output: >>> df state continent new 0 United States North America United States 1 IT Europe Europe - IT 2 Spain Europe Spain 3 JP Asia Asia - JP 4 FR Europe Europe - FR
doc_2502
java.io.IOException: Error inserting: bucket: *****, object: ***** at com.google.cloud.hadoop.gcsio.GoogleCloudStorageImpl.wrapException(GoogleCloudStorageImpl.java:1600) at com.google.cloud.hadoop.gcsio.GoogleCloudStorageImpl$3.run(GoogleCloudStorageImpl.java:475) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 429 Too Many Requests { "code" : 429, "errors" : [ { "domain" : "usageLimits", "message" : "The total number of changes to the object ***** exceeds the rate limit. Please reduce the rate of create, update, and delete requests.", "reason" : "rateLimitExceeded" } ], "message" : "The total number of changes to the object ***** exceeds the rate limit. Please reduce the rate of create, update, and delete requests." } at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469) at com.google.cloud.hadoop.gcsio.GoogleCloudStorageImpl$3.run(GoogleCloudStorageImpl.java:472) ... 3 more * *Anyone knows any solution for that? *Is there a way to control the read/write rate of Spark? *Is there a way to increase the rate limit for my Google Project? *Is there a way to use local Hard-Disk for temp files that don't have to be shared with other slaves? Thanks! A: Unfortunately, the usage of GCS when set as the DEFAULT_FS can pop up with high rates of directory-object creation whether using it for just intermediate directories or for final input/output directories. Especially for using GCS as the final output directory, it's difficult to apply any Spark-side workaround to reduce the rate of redundant directory-creation requests. The good news is that most of these directory requests are indeed redundant, just because the system is used to being able to essentially "mkdir -p", and cheaply return true if the directory already exists. In our case, it's possible to fix it on the GCS-connector side by catching these errors and then just checking whether the directory indeed got created by some other worker in a race condition. This should be fixed now with https://github.com/GoogleCloudPlatform/bigdata-interop/commit/141b1efab9ef23b6b5f5910d8206fcbc228d2ed7 To test, just run: git clone https://github.com/GoogleCloudPlatform/bigdata-interop.git cd bigdata-interop mvn -P hadoop1 package # Or or Hadoop 2 mvn -P hadoop2 package And you should find the files "gcs/target/gcs-connector-*-shaded.jar" available for use. To plug it into bdutil, simply gsutil cp gcs/target/gcs-connector-*shaded.jar gs://<your-bucket>/some-path/ and then edit bdutil/bdutil_env.sh for Hadoop 1 or bdutil/hadoop2_env.sh to change: GCS_CONNECTOR_JAR='https://storage.googleapis.com/hadoop-lib/gcs/gcs-connector-1.4.1-hadoop2.jar' To instead point at your gs://<your-bucket>/some-path/ path; bdutil automatically detects that you're using a gs:// prefixed URI and will do the right thing during deployment. Please let us know if it fixes the issue for you! A: Have you tried to set the spark.local.dir config parameter and attach a disk (preferable SSD) for that tmp space to your Google Compute Engine instances? https://spark.apache.org/docs/1.2.0/configuration.html You can not change the rate limiting for your project, what you would have to use is a back-off algorithm once the limit is reached. Since you mentioned most of the reads/writes are for tmp files, try to configure Spark to use local disks for that.
doc_2503
PHP $sum = 0; for($i = 0; $i <= 1000000000 ; $i++) { $sum += $i; } printf("%s", number_format($sum, 0, "", "")); // 500000000067108992 Node.js var sum = 0; for (i = 0; i <= 1000000000; i++) { sum += i ; } console.log(sum); // 500000000067109000 The correct answer can be calculated using 1 + 2 + ... + n = n(n+1)/2 Correct answer = 500000000500000000, so I decided to try another language. GO var sum , i int64 for i = 0 ; i <= 1000000000; i++ { sum += i } fmt.Println(sum) // 500000000500000000 But it works fine! So what is wrong with my PHP and Node.js code? Perhaps this a problem of interpreted languages, and that's why it works in a compiled language like Go? If so, would other interpreted languages such as Python and Perl have the same problem? A: The reason is that the value of your integer variable sum exceeds the maximum value. And the sum you get is result of float-point arithmetic which involves rounding off. Since other answers did not mention the exact limits, I decided to post it. The max integer value for PHP for: * *32-bit version is 2147483647 *64-bit version is 9223372036854775807 So it means either you are using 32 bit CPU or 32 bit OS or 32 bit compiled version of PHP. It can be found using PHP_INT_MAX. The sum would be calculated correctly if you do it on a 64 bit machine. The max integer value in JavaScript is 9007199254740992. The largest exact integral value you can work with is 253 (taken from this question). The sum exceeds this limit. If the integer value does not exceed these limits, then you are good. Otherwise you will have to look for arbitrary precision integer libraries. A: took ages in ruby, but gives the correct answer: (1..1000000000).reduce(:+) => 500000000500000000 A: To get the correct result in php I think you'd need to use the BC math operators: http://php.net/manual/en/ref.bc.php Here is the correct answer in Scala. You have to use Longs otherwise you overflow the number: println((1L to 1000000000L).reduce(_ + _)) // prints 500000000500000000 A: There's actually a cool trick to this problem. Assume it was 1-100 instead. 1 + 2 + 3 + 4 + ... + 50 + 100 + 99 + 98 + 97 + ... + 51 = (101 + 101 + 101 + 101 + ... + 101) = 101*50 Formula: For N= 100: Output = N/2*(N+1) For N = 1e9: Output = N/2*(N+1) This is much faster than looping through all of that data. Your processor will thank you for it. And here is an interesting story regarding this very problem: http://www.jimloy.com/algebra/gauss.htm A: This gives the proper result in PHP by forcing the integer cast. $sum = (int) $sum + $i; A: Common Lisp is one of the fastest interpreted* languages and handles arbitrarily large integers correctly by default. This takes about 3 second with SBCL: * (time (let ((sum 0)) (loop :for x :from 1 :to 1000000000 :do (incf sum x)) sum)) Evaluation took: 3.068 seconds of real time 3.064000 seconds of total run time (3.044000 user, 0.020000 system) 99.87% CPU 8,572,036,182 processor cycles 0 bytes consed 500000000500000000 * *By interpreted, I mean, I ran this code from the REPL, SBCL may have done some JITing internally to make it run fast, but the dynamic experience of running code immediately is the same. A: Racket v 5.3.4 (MBP; time in ms): > (time (for/sum ([x (in-range 1000000001)]) x)) cpu time: 2943 real time: 2954 gc time: 0 500000000500000000 A: I don't have enough reputation to comment on @postfuturist's Common Lisp answer, but it can be optimized to complete in ~500ms with SBCL 1.1.8 on my machine: CL-USER> (compile nil '(lambda () (declare (optimize (speed 3) (space 0) (safety 0) (debug 0) (compilation-speed 0))) (let ((sum 0)) (declare (type fixnum sum)) (loop for i from 1 to 1000000000 do (incf sum i)) sum))) #<FUNCTION (LAMBDA ()) {1004B93CCB}> NIL NIL CL-USER> (time (funcall *)) Evaluation took: 0.531 seconds of real time 0.531250 seconds of total run time (0.531250 user, 0.000000 system) 100.00% CPU 1,912,655,483 processor cycles 0 bytes consed 500000000500000000 A: Works fine in Rebol: >> sum: 0 == 0 >> repeat i 1000000000 [sum: sum + i] == 500000000500000000 >> type? sum == integer! This was using Rebol 3 which despite being 32 bit compiled it uses 64-bit integers (unlike Rebol 2 which used 32 bit integers) A: I wanted to see what happened in CF Script <cfscript> ttl = 0; for (i=0;i LTE 1000000000 ;i=i+1) { ttl += i; } writeDump(ttl); abort; </cfscript> I got 5.00000000067E+017 This was a pretty neat experiment. I'm fairly sure I could have coded this a bit better with more effort. A: For the sake of completeness, in Clojure (beautiful but not very efficient): (reduce + (take 1000000000 (iterate inc 1))) ; => 500000000500000000 A: ActivePerl v5.10.1 on 32bit windows, intel core2duo 2.6: $sum = 0; for ($i = 0; $i <= 1000000000 ; $i++) { $sum += $i; } print $sum."\n"; result: 5.00000000067109e+017 in 5 minutes. With "use bigint" script worked for two hours, and would worked more, but I stopped it. Too slow. A: AWK: BEGIN { s = 0; for (i = 1; i <= 1000000000; i++) s += i; print s } produces the same wrong result as PHP: 500000000067108992 It seems AWK uses floating point when the numbers are really big, so at least the answer is the right order-of-magnitude. Test runs: $ awk 'BEGIN { s = 0; for (i = 1; i <= 100000000; i++) s += i; print s }' 5000000050000000 $ awk 'BEGIN { s = 0; for (i = 1; i <= 1000000000; i++) s += i; print s }' 500000000067108992 A: Here is the answer in C, for completeness: #include <stdio.h> int main(void) { unsigned long long sum = 0, i; for (i = 0; i <= 1000000000; i++) //one billion sum += i; printf("%llu\n", sum); //500000000500000000 return 0; } The key in this case is using C99's long long data type. It provides the biggest primitive storage C can manage and it runs really, really fast. The long long type will also work on most any 32 or 64-bit machine. There is one caveat: compilers provided by Microsoft explicitly do not support the 14 year-old C99 standard, so getting this to run in Visual Studio is a crapshot. A: My guess is that when the sum exceeds the capacity of a native int (231-1 = 2,147,483,647), Node.js and PHP switch to a floating point representation and you start getting round-off errors. A language like Go will probably try to stick with an integer form (e.g., 64-bit integers) as long as possible (if, indeed, it didn't start with that). Since the answer fits in a 64-bit integer, the computation is exact. A: Category other interpreted language: Tcl: If using Tcl 8.4 or older it depends if it was compiled with 32 or 64 bit. (8.4 is end of life). If using Tcl 8.5 or newer which has arbitrary big integers, it will display the correct result. proc test limit { for {set i 0} {$i < $limit} {incr i} { incr result $i } return $result } test 1000000000 I put the test inside a proc to get it byte-compiled. A: For the PHP code, the answer is here: The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5. A: Harbour: proc Main() local sum := 0, i for i := 0 to 1000000000 sum += i next ? sum return Results in 500000000500000000. (on both windows/mingw/x86 and osx/clang/x64) A: Erlang works: from_sum(From,Max) -> from_sum(From,Max,Max). from_sum(From,Max,Sum) when From =:= Max -> Sum; from_sum(From,Max,Sum) when From =/= Max -> from_sum(From+1,Max,Sum+From). Results: 41> useless:from_sum(1,1000000000). 500000000500000000 A: Funny thing, PHP 5.5.1 gives 499999999500000000 (in ~ 30s), while Dart2Js gives 500000000067109000 (which is to be expected, since it's JS that gets executed). CLI Dart gives the right answer ... instantly. A: Erlang gives the expected result too. sum.erl: -module(sum). -export([iter_sum/2]). iter_sum(Begin, End) -> iter_sum(Begin,End,0). iter_sum(Current, End, Sum) when Current > End -> Sum; iter_sum(Current, End, Sum) -> iter_sum(Current+1,End,Sum+Current). And using it: 1> c(sum). {ok,sum} 2> sum:iter_sum(1,1000000000). 500000000500000000 A: Smalltalk: (1 to: 1000000000) inject: 0 into: [:subTotal :next | subTotal + next ]. "500000000500000000" A: For completeness only. In MATLAB there is no problem with automatic type selection: tic; ii = 1:1000000; sum(ii); toc; ans Elapsed time is 0.004471 seconds. ans = 5.000005000000000e+11 And in F# interactive, automatic unit types give an overflow error. Assigning type int64 gives the correct answer: seq {int64 1.. int64 1000000} |> Seq.sum val it : int64 = 500000500000L Notes: Could use Seq.reduce (+) instead of Seq.sum without a noticeable change in efficiency. However, using Seq.reduce (+) with automatic unit type will give a wrong answer rather than an overflow error. Computation time is <.5 seconds, but I am currently lazy and so I am not importing the .NET stopwatch class to get a more exact time. A: A few answers have already explained why your PHP and Node.js code don't work as expected, so I won't repeat that here. I just want to point out that this has nothing to do with "interpreted vs compiled languages". Perhaps this a problem of interpreted languages, and that's why it works in a compiled language like Go? A "language" is merely a set of well-defined rules; an implementation of a language is what's either interpreted or compiled. I could take a language whose principal implementation is compiled (like Go) and write an interpreter for it (and vice-versa), but every program processed by the interpreter should produce identical output as running the program via the compiled implementation, and this output should be in accordance with the language's specification. The PHP and Node.js results are in fact in accordance with the languages' specifications (as some other answers point out), and this has nothing to do with the fact that the principal implementations of these languages are interpreted; compiled implementations of the languages by definition must also produce the same results. A tangible example of all this is Python, which has both widely-used compiled and interpreted implementations. Running a translated version of your program in the interpreted implementation: >>> total = 0 >>> for i in xrange(1000000001): ... total += i ... >>> print total 500000000500000000 must not, by the definition of Python, result in a different output than running it in the compiled implementation: total = 0 for i in xrange(1000000001): total += i print total 500000000500000000 A: Perl script give us the expected result: use warnings; use strict; my $sum = 0; for(my $i = 0; $i <= 1_000_000_000; $i++) { $sum += $i; } print $sum, "\n"; #<-- prints: 500000000500000000 A: The Answer to this is "surprisingly" simple: First - as most of you might know - a 32-bit integer ranges from −2,147,483,648 to 2,147,483,647. So, what happens if PHP gets a result, that is LARGER than this? Usually, one would expect a immediate "Overflow", causing 2,147,483,647 + 1 to turn into −2,147,483,648. However, that is NOT the case. IF PHP Encounters a larger number, it Returns FLOAT instead of INT. If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead. http://php.net/manual/en/language.types.integer.php This said, and knowing that PHP FLOAT implementation is following the IEEE 754 double precision Format, means, that PHP is able to deal with numbers upto 52 bit, without loosing precision. (On a 32-bit System) So, at the Point, where your Sum hits 9,007,199,254,740,992 (which is 2^53) The Float value returned by the PHP Maths will no longer be precise enough. E:\PHP>php -r "$x=bindec(\"100000000000000000000000000000000000000000000000000000\"); echo number_format($x,0);" 9,007,199,254,740,992 E:\PHP>php -r "$x=bindec(\"100000000000000000000000000000000000000000000000000001\"); echo number_format($x,0);" 9,007,199,254,740,992 E:\PHP>php -r "$x=bindec(\"100000000000000000000000000000000000000000000000000010\"); echo number_format($x,0);" 9,007,199,254,740,994 This example Shows the Point, where PHP is loosing precision. First, the last significatn bit will be dropped, causing the first 2 expressions to result in an equal number - which they aren't. From NOW ON, the whole math will go wrong, when working with default data-types. •Is it the same problem for other interpreted language such as Python or Perl? I don't think so. I think this is a problem of languages that have no type-safety. While a Integer Overflow as mentioned above WILL happen in every language that uses fixed data types, the languages without type-safety might try to catch this with other datatypes. However, once they hit their "natural" (System-given) Border - they might return anything, but the right result. However, each language may have different threadings for such a Scenario. A: Python works: >>> sum(x for x in xrange(1000000000 + 1)) 500000000500000000 Or: >>> sum(xrange(1000000000+1)) 500000000500000000 Python's int auto promotes to a Python long which supports arbitrary precision. It will produce the correct answer on 32 or 64 bit platforms. This can be seen by raising 2 to a power far greater than the bit width of the platform: >>> 2**99 633825300114114700748351602688L You can demonstrate (with Python) that the erroneous values you are getting in PHP is because PHP is promoting to a float when the values are greater than 2**32-1: >>> int(sum(float(x) for x in xrange(1000000000+1))) 500000000067108992 A: The other answers already explained what is happening here (floating point precision as usual). One solution is to use an integer type big enough, or to hope the language will chose one if needed. The other solution is to use a summation algorithm that knows about the precision problem and works around it. Below you find the same summation, first with with 64 bit integer, then with 64 bit floating point and then using floating point again, but with the Kahan summation algorithm. Written in C#, but the same holds for other languages, too. long sum1 = 0; for (int i = 0; i <= 1000000000; i++) { sum1 += i ; } Console.WriteLine(sum1.ToString("N0")); // 500.000.000.500.000.000 double sum2 = 0; for (int i = 0; i <= 1000000000; i++) { sum2 += i ; } Console.WriteLine(sum2.ToString("N0")); // 500.000.000.067.109.000 double sum3 = 0; double error = 0; for (int i = 0; i <= 1000000000; i++) { double corrected = i - error; double temp = sum3 + corrected; error = (temp - sum3) - corrected; sum3 = temp; } Console.WriteLine(sum3.ToString("N0")); //500.000.000.500.000.000 The Kahan summation gives a beautiful result. It does of course take a lot longer to compute. Whether you want to use it depends a) on your performance vs. precision needs, and b) how your language handles integer vs. floating point data types. A: If you have 32-Bit PHP, you can calculate it with bc: <?php $value = 1000000000; echo bcdiv( bcmul( $value, $value + 1 ), 2 ); //500000000500000000 In Javascript you have to use arbitrary number library, for example BigInteger: var value = new BigInteger(1000000000); console.log( value.multiply(value.add(1)).divide(2).toString()); //500000000500000000 Even with languages like Go and Java you will eventually have to use arbitrary number library, your number just happened to be small enough for 64-bit but too high for 32-bit. A: In Ruby: sum = 0 1.upto(1000000000).each{|i| sum += i } puts sum Prints 500000000500000000, but takes a good 4 minutes on my 2.6 GHz Intel i7. Magnuss and Jaunty have a much more Ruby solution: 1.upto(1000000000).inject(:+) To run a benchmark: $ time ruby -e "puts 1.upto(1000000000).inject(:+)" ruby -e "1.upto(1000000000).inject(:+)" 128.75s user 0.07s system 99% cpu 2:08.84 total A: I use node-bigint for big integer stuff: https://github.com/substack/node-bigint var bigint = require('bigint'); var sum = bigint(0); for(var i = 0; i <= 1000000000; i++) { sum = sum.add(i); } console.log(sum); It's not as quick as something that can use native 64-bit stuff for this exact test, but if you get into bigger numbers than 64-bit, it uses libgmp under the hood, which is one of the faster arbitrary precision libraries out there. A: Your Go code uses integer arithmetic with enough bits to give an exact answer. Never touched PHP or Node.js, but from the results I suspect the math is done using floating point numbers and should be thus expected not to be exact for numbers of this magnitude. A: In ruby, these to functionally similar solutions (that return the correct answer) take significantly different amounts of time to complete: $ time ruby -e "(1..1000000000).inject{|sum, n| sum + n}" real 1m26.005s user 1m26.010s sys 0m0.076s $ time ruby -e "1.upto(1000000000).inject(:+)" real 0m48.957s user 0m48.957s sys 0m0.045s $ ruby -v ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.8.0] A: Javascript (and possibly PHP) represent all numbers as double, and round them for integer values. This means that they only have 53 bits of precision (instead of the 64 bits provided by int64 and a Java long), and will result in rounding errors on large values. A: As other people have pointed out, the fastest way to do this calculation (regardless of the language) is with a simple math function (instead of a CPU intensive loop): number = 1000000000; result = (number/2) * (number+1); You would still need to solve any 32/64 bit integer/float issues, depending on the language, though. A: And the ruby one's: [15] pry(main)> (1..1000000000).inject(0) { |sum,e| sum + e } => 500000000500000000 Seems to get the right number.
doc_2504
Has anyone successfully gotten this working? Thanks! reproduction: https://gist.github.com/toraora/a9d4eb8679383fe659da04d3be5c2d6e (I'll put up the actual solution when I finish setting up SSH keys on this machine) A: Ah, so the solution was to have: CSharpSyntaxTree.ParseText(File.ReadAllText(srcfile), path: srcfile, encoding: System.Text.Encoding.UTF8) Thanks @hvd!
doc_2505
Applied to a ToggleButton, the Outline is missing, and in some occasions, the Unchecked-state will be rendered as Checked. Moreover, the style references an Element named "BackgroundCheckedGlyph" which is not defined and leads to debug-errors when used in an AppBar. Has someone already found or built a working Style for Buttons and ToggleButtons? A: There are clearly some issues with StandardStyles.xaml and ToggleButtons in RTM. While HCL's attempt to fix this is a good start, there are still some issues, by HCL's own admission. Until this is fixed by MS, I think it's best to use an entirely separate style for ToggleButtons. There is a working Style at this MS forum page which I've reproduced below - so far, it seems to function perfectly. <Style x:Key="ToggleAppBarButtonStyle" TargetType="ToggleButton"> <Setter Property="Foreground" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> <Setter Property="VerticalAlignment" Value="Stretch"/> <Setter Property="FontFamily" Value="Segoe UI Symbol"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="FontSize" Value="20"/> <Setter Property="AutomationProperties.ItemType" Value="App Bar ToggleButton"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <Grid x:Name="RootGrid" Width="100" Background="Transparent"> <StackPanel VerticalAlignment="Top" Margin="0,12,0,11"> <Grid Width="40" Height="40" Margin="0,0,0,5" HorizontalAlignment="Center"> <TextBlock x:Name="BackgroundGlyph" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemBackgroundThemeBrush}"/> <TextBlock x:Name="OutlineGlyph" Text="&#xE0A7;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0"/> <ContentPresenter x:Name="Content" HorizontalAlignment="Center" Margin="-1,-1,0,0" VerticalAlignment="Center"/> </Grid> <TextBlock x:Name="TextLabel" Text="{TemplateBinding AutomationProperties.Name}" Foreground="{StaticResource AppBarItemForegroundThemeBrush}" Margin="0,0,2,0" FontSize="12" TextAlignment="Center" Width="88" MaxHeight="32" TextTrimming="WordEllipsis" Style="{StaticResource BasicTextStyle}"/> </StackPanel> <Rectangle x:Name="FocusVisualWhite" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="1.5"/> <Rectangle x:Name="FocusVisualBlack" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="0.5"/> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="PointerOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverBackgroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed"/> <VisualState x:Name="Disabled"/> <VisualState x:Name="Checked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="CheckedPointerOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="CheckedPressed"/> <VisualState x:Name="CheckedDisabled"/> <VisualState x:Name="Indeterminate"/> <VisualState x:Name="IndeterminatePointerOver"/> <VisualState x:Name="IndeterminatePressed"/> <VisualState x:Name="IndeterminateDisabled"/> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <DoubleAnimation Storyboard.TargetName="FocusVisualWhite" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/> <DoubleAnimation Storyboard.TargetName="FocusVisualBlack" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/> </Storyboard> </VisualState> <VisualState x:Name="Unfocused" /> <VisualState x:Name="PointerFocused" /> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> A: I've found that if I set the VisualState of the ToggleButton manually then the style works just fine (after adding the missing TextBlock). Not sure why this works (or why it's not working to begin with...) See this post for more information. A: Here the result of my own trials to fix the Style. It seems to work (I have looked at it in the "Light"-theme and in the "HighContrast"- Theme. I have found some minor drawbacks, but it seems to me better than the original. If I invest more time in this, I will post the improved Version. If you use this Style and improve it yourself, feel free to Change my Version. <Style x:Key="AppBarButtonStyle" TargetType="ButtonBase"> <Setter Property="Foreground" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> <Setter Property="VerticalAlignment" Value="Stretch"/> <Setter Property="FontFamily" Value="Segoe UI Symbol"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="FontSize" Value="20"/> <Setter Property="AutomationProperties.ItemType" Value="App Bar Button"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ButtonBase"> <Grid x:Name="RootGrid" Width="100" Background="Transparent"> <StackPanel VerticalAlignment="Top" Margin="0,12,0,11"> <Grid Width="40" Height="40" Margin="0,0,0,5" HorizontalAlignment="Center"> <TextBlock x:Name="BackgroundGlyph" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemBackgroundThemeBrush}"/> <!-- The following TextBlock seemed to be missing in the original template --> <TextBlock x:Name="BackgroundCheckedGlyph" Visibility="Collapsed" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemForegroundThemeBrush}"/> <TextBlock x:Name="OutlineGlyph" Text="&#xE0A7;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0"/> <ContentPresenter x:Name="Content" HorizontalAlignment="Center" Margin="-1,-1,0,0" VerticalAlignment="Center"/> </Grid> <TextBlock x:Name="TextLabel" Text="{TemplateBinding AutomationProperties.Name}" Foreground="{StaticResource AppBarItemForegroundThemeBrush}" Margin="0,0,2,0" FontSize="12" TextAlignment="Center" Width="88" MaxHeight="32" TextTrimming="WordEllipsis" Style="{StaticResource BasicTextStyle}"/> </StackPanel> <Rectangle x:Name="FocusVisualWhite" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="1.5"/> <Rectangle x:Name="FocusVisualBlack" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="0.5"/> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ApplicationViewStates"> <VisualState x:Name="FullScreenLandscape"/> <VisualState x:Name="Filled"/> <VisualState x:Name="FullScreenPortrait"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextLabel" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Width"> <DiscreteObjectKeyFrame KeyTime="0" Value="60"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Snapped"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextLabel" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Width"> <DiscreteObjectKeyFrame KeyTime="0" Value="60"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <!-- The following animations are here, because I was not able to reset the Glyphs states in the Unchecked state. I hope that this does not produces any sideeffects --> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundCheckedGlyph" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="PointerOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverBackgroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundCheckedGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverBackgroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundCheckedGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextLabel" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <DoubleAnimation Storyboard.TargetName="FocusVisualWhite" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/> <DoubleAnimation Storyboard.TargetName="FocusVisualBlack" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/> </Storyboard> </VisualState> <VisualState x:Name="Unfocused" /> <VisualState x:Name="PointerFocused" /> </VisualStateGroup> <VisualStateGroup x:Name="CheckStates"> <VisualState x:Name="Checked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundCheckedGlyph" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundThemeBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unchecked"><!-- This state seems to me as not working. Am I right? --> </VisualState> <VisualState x:Name="Indeterminate"> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
doc_2506
response = requests.get(url) artists=re.findall(re.escape('<name>')+'(.*?)'+re.escape('</name>'),str(response.content)) print(artists) This returns a list of strings. The problem is, some strings have unwanted characters in them. For example, one of the strings in the list is "Somethin\\' \\'Bout A Truck" and I'd like it to be 'Somethin' 'Bout A Truck'. Thanks in advance. A: I think the beautiful soup(bs4) will solve this problem and it will also support for higher version of python 3.4 A: Those escapes (single backslashes, each displayed as \\) may be "unwanted" from your viewpoint but they're no doubt "present" in the response you received. So if characters are present but unwanted, you can remove them, e.g using in lieu of str(response.content) str(response.content).replace('\\'. '') if what you actually want to do is remove all such escapes (if you want to do something different than that you'd better explain what it is:-). BeautifulSoup4 as recommended in the accepted answer, though a nice package indeed, does not wantonly remove characters present in the input -- it can't read your mind, so it can't know what's "unwanted" to you. E.g: >>> import bs4 >>> s = '<name>Somethin\\\' \\\'Bout A Truck</name>' >>> soup = bs4.BeautifulSoup(s) >>> print(soup) <name>Somethin\' \'Bout A Truck</name> >>> As you see, the escapes (backslashes) are still there before the single-quotes.
doc_2507
I tried the solutions of several similar questions from here, but sadly none of them worked in my case. The Application worked like a charm before I decided to turn it into a cloud application by adding Eureka Server. My stacktrace: *************************** APPLICATION FAILED TO START *************************** Description: An attempt was made to call a method that does not exist. The attempt was made from the following location: org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:161) The following method did not exist: 'void org.springframework.boot.builder.SpringApplicationBuilder.<init>(java.lang.Object[])' The calling method's class, org.springframework.cloud.bootstrap.BootstrapApplicationListener, was loaded from the following location: jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/cloud/spring-cloud-context/1.3.6.RELEASE/spring-cloud-context-1.3.6.RELEASE.jar!/org/springframework/cloud/bootstrap/BootstrapApplicationListener.class The called method's class, org.springframework.boot.builder.SpringApplicationBuilder, is available from the following locations: jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar!/org/springframework/boot/builder/SpringApplicationBuilder.class The called method's class hierarchy was loaded from the following locations: org.springframework.boot.builder.SpringApplicationBuilder: file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar Action: Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.cloud.bootstrap.BootstrapApplicationListener and org.springframework.boot.builder.SpringApplicationBuilder My Application.properties: spring.datasource.url=jdbc:mariadb://localhost:3306/woerdl spring.datasource.username=root spring.datasource.password=[redacted] spring.datasource.driver-class-name=org.mariadb.jdbc.Driver spring.jpa.hibernate.ddl-auto=none spring.sql.init.mode=always server.port=8010 spring.application.name=woerdl_db eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false eureka.server.enable-self-preservation=true eureka.server.waitTimeInMsWhenSyncEmpty=0 eureka.instance.lease-expiration-duration-in-seconds= 15 eureka.instance.lease-renewal-interval-in-seconds= 5 eureka.instance.hostname=localhost My Main class: package de.derandy.woerdl_db; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; import de.derandy.woerdl_db.config.Config; @EnableEurekaServer @SpringBootApplication public class Woerdl_dbApplication { public static void main(final String[] args) { Config.config(args); } } My Config class: package de.derandy.woerdl_db.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import de.derandy.woerdl_db.Woerdl_dbApplication; import de.derandy.woerdl_db.wort.service.impl.WortServiceImpl; @Configuration public class Config { public static ApplicationContext context; public static Environment environment; public static String[] args; public static String random; @Autowired private static WortServiceImpl wortService; public static void config(final String[] args) { Config.args = args; Config.context = new SpringApplicationBuilder(Woerdl_dbApplication.class).registerShutdownHook(true) .run(Config.args); environment = Config.context.getEnvironment(); wortService = (WortServiceImpl) Config.context.getBean("wortServiceImpl"); random = wortService.findRandom(); } } My pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>de.derandy</groupId> <artifactId>woerdl_db</artifactId> <version>1.0</version> <name>woerdl_db</name> <description>Ein Wortspiel</description> <properties> <java.version>17</java.version> <org.mapstruct.version>1.4.2.Final</org.mapstruct.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-apache-client4</artifactId> <version>1.19.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.7.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>17</source> <!-- depending on your project --> <target>17</target> <!-- depending on your project --> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </path> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build> </project> A: I resolved the issue by editing the Pom. I added jaxb-runtime and spring-cloud-dependencies <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>de.derandy</groupId> <artifactId>woerdl_db</artifactId> <version>1.0</version> <name>woerdl_db</name> <description>Ein Wortspiel</description> <properties> <java.version>17</java.version> <org.mapstruct.version>1.4.2.Final</org.mapstruct.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-apache-client4</artifactId> <version>1.19.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.7.RELEASE</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>17</source> <!-- depending on your project --> <target>17</target> <!-- depending on your project --> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </path> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build> </project>
doc_2508
https://github.com/jamierumbelow/codeigniter-base-model How do you validate the data in put method. I have tried as like below. config/form_validation.php $config = array( 'create_put' => array( array( 'field' => 'emailid', 'label' => 'email_address', 'rules' => 'trim|required|valid_email' ), array( 'field' => 'lastname', 'label' => 'lastname', 'rules' => 'trim|required|min_length[8]|max_length[16]' ), array( 'field' => 'leadname', 'label' => 'first_name', 'rules' => 'trim|required|max_length[50]' ), array( 'field' => 'website', 'label' => 'last_name', 'rules' => 'trim|required|max_length[50]' ), array( 'field' => 'mobilenumber', 'label' => 'phone_number', 'rules' => 'trim|required|alpha_dash' ) ) And in lead controller method function create_put() { //$this->load_model(); //var_dump($this->put()) ; $this->load->library('form_validation'); $lead = remove_unknown_fields($this->put(),$this->form_validation->get_field_names('create_put')); //print_r($data ); die; $this->form_validation->set_data($lead) ; if ($this->form_validation->run('create_put') != false){ $this->load->model('Model_lead'); $lead_id = $this->Model_lead->insert($lead); if (!$lead_id) { $this->response(array('status'=>'failure','message'=>'An un-expected error occured while trying to insert student details'),REST_Controller::HTTP_INTERNAL_SERVER_ERROR); } else { $this->response(array('status'=> 'success','message'=>'Student data successfully inserted')); } }else { $this->response(array('status'=> 'failure','message'=>$this->form_validation->get_errors_as_array()), REST_Controller::HTTP_BAD_REQUEST); } } Validation always throws error. check below response. { "status": "valid failure", "message": [] } I don't know why validation is not performed. A: the problem was I have chosen form-data in postman instead of x-www-form-urlencoded option in header. I found that there was an issue created in someone's repo in below link. https://github.com/alexmarton/RControl/issues/1 This might be the problem there too. Everything is working fine now after selecting x-www-form-urlencoded in header.
doc_2509
1., S → 0S1 | 01 2., S → + SS | * SS A: Are these grammars left recursive No. and why? In both cases you can never reach S (which is the only non-terminal) without consuming a terminal first. In the first grammar the only occurrence of S is preceded by the terminal 0 and in the second each occurrence is either preceded by + or *.
doc_2510
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"my web service "]]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; I create my user interface according to this JSON string and I need to add a progress bar to my code. I have tried many examples but I cannot get the progress bar to display properly. Can anybody tell me how to use a progress bar to till my view did load. It will be a great help, thank you. A: If you haven't decided on what kind of progress dialog to use yet, I recommend MBProgressHUD: https://github.com/jdg/MBProgressHUD It's fairly easy to use, and seems to be what you would need for this case. If you're set on making the request synchronous, at the desired point in your view lifecycle e.g. viewDidLoad: you could have something like the following: [MBProgressHUD showHUDAddedTo:self.view animated:YES]; // synchronously pull down the necessary JSON NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"my web service "]]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; // perform the necessary view configuration you need to do based on this data // . // . // . [MBProgressHUD hideHUDForView:self.view animated:YES]; This will display a blocking spinner while your configuration is occurring and then clear it when the process is complete.
doc_2511
First and foremost, this is an app for teacher to make attendance, the attendance will update back to my server. My TableViewCell is customised as below. @interface TvcStudentClassSession : UITableViewCell @property (strong, nonatomic) IBOutlet UILabel *lblStudentInfo; @property (strong, nonatomic) IBOutlet UISegmentedControl *smgStatus; @property NSInteger studentId; @end I have created a IBAction for the SegmentedControl within the TableViewCell. When it is selected, it should call my webservice and update the value immediately in the server. There is no problem on this. The problem right now is, my UITableViewCell was populated in my parent View. The code is as below. The objStudentClassSessions is a NSMutableArray that stored values loaded from the server. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"tvcStudentClassSession"; TvcStudentClassSession *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... ObjStudentClassSession *objStudentClassSession = [objStudentClassSessions objectAtIndex:indexPath.row]; cell.classSessionId = selectedObjClassSession.classSessionId; cell.studentId = objStudentClassSession.studentId; cell.lblStudentInfo.text = [NSString stringWithFormat:@"%@ (%@)", objStudentClassSession.studentName, objStudentClassSession.studentCode]; if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_NONE]) { [cell.smgStatus setSelectedSegmentIndex:0]; } else if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_PRESENT]) { [cell.smgStatus setSelectedSegmentIndex:1]; } else if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_ABSENT]) { [cell.smgStatus setSelectedSegmentIndex:2]; } return cell; } Every time when user changes the SegmentedControl, the IBAction called successfully within the UiTableViewCell class and updated to server successfully. But once I scroll down the screen and then back up, the SegmentedControl return to the original state, I know this is how iOS is working, it load the cell value every time is become visible. So for my case, may I know how can I update my objStudentClassSessions in the UITableView so that it is correctly reload when the cell become visible again? A: You also need to update the local data when segment changes. So something like this in the code handling segment change: ObjStudentClassSession *objStudentClassSession = [objStudentClassSessions objectAtIndex:indexOfStudentFromSegmentedControl]; objStudentClassSession.attendanceStatus == segentedControl.selectedSegmentIndex == 0 ? ...
doc_2512
<li id="coz"><a onclick="doRequest('zemberek.jsp','YAZI_COZUMLE');">Cozumle</a></li> by Jsoup?.How can I do? here is original site : http://zemberek-web.appspot.com/ <html> <head> <script> function doRequest(url, islem) { var ajaxRequest = new AjaxRequest(url); var hiddenField = document.getElementById("islem"); hiddenField.value = islem; ajaxRequest.addNamedFormElements("giris", "islem"); ajaxRequest.sendRequest(); } </script> </head> <body> <big>Zemberek Demo</big> <small>(<a href="http://code.google.com/p/zemberek">Zemberek Proje Sitesi</a>)</small> <div id="menu"> <ul id="nav"> <li id="denetle"><a onclick="doRequest('zemberek.jsp', 'YAZI_DENETLE');">Denetle</a></li> <li id="coz"><a onclick="doRequest('zemberek.jsp','YAZI_COZUMLE');">Cozumle</a></li> <li id="oner"><a onclick="doRequest('zemberek.jsp','ONER');">Oner</a></li> <li id="ascii2tr"><a onclick="doRequest('zemberek.jsp','ASCII_TURKCE');">Ascii->Tr</a></li> <li id="tr2ascii"><a onclick="doRequest('zemberek.jsp','TURKCE_ASCII');">Tr->ascii</a></li> <li id="hecele"><a onclick="doRequest('zemberek.jsp','HECELE');">Hecele</a></li> <li id="ayristir"><a onclick="doRequest('zemberek.jsp','SACMALA');">Sacmala</a></li> </ul> </div> <br> <br> <br> <br> <br> <form id="form" action="#"> <P align=center><b>Islem yapilacak yaziyi asagidaki alana giriniz.</b><br> <textarea name="giris" rows="10" cols="60"></textarea> <input type="hidden" name="islem" id="islem" /></P> </form> <br> <div id="div"></div> </body> </html> A: Simple and working solution with Jsoup: Code String url = "http://zemberek-web.appspot.com/zemberek.jsp?ts=1367326940830&giris=%s&islem=YAZI_COZUMLE"; String query = "MyParamĄĘÓŚŁ"; String formattedUrl = String.format(url, URLEncoder.encode(query, "UTF-8")); Document document = Jsoup.connect(formattedUrl).get(); String result = document.select("taconite-root > taconite-replace-children > div").text(); System.out.println(result); Result MyParam :cozulemedi A: I think the anserw is the following if you look the request in Google Chrome developper tools you will see that when you click the generated url is the following for example : http://zemberek-web.appspot.com/zemberek.jsp?ts=1367076182039&giris=bnfhjfttgfhffgfg&islem=ASCII_TURKCE giris=bnfhjfttgfhffgfg => is your string sent to the server. So you can do in every programming language this following http://zemberek-web.appspot.com/zemberek.jsp?ts=1367076182039&giris=MY_STRING&islem=ASCII_TURKCE Don't forget to UTF-8 encode your string for the query string UPDATE Here is an example that I've made public class MyRequester { /** * @param args */ public static void main(String[] args) { HttpURLConnection conn = null; InputStream in = null; try { String textToSend = "Java is cool :)"; String urlRequest = "http://zemberek-web.appspot.com/zemberek.jsp?ts=1367076182039&giris="+URLEncoder.encode(textToSend, "UTF-8")+"&islem=ASCII_TURKCE"; System.out.println(urlRequest+"\n"); conn = (HttpURLConnection) new URL(urlRequest).openConnection(); in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String data = null; while ((data = reader.readLine()) != null) { sb.append(data); } System.out.println(sb.toString()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(conn != null){ conn.disconnect(); } if(in != null){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } Output in the console : http://zemberek-web.appspot.com/zemberek.jsp?ts=1367076182039&giris=Java+is+cool+%3A%29&islem=ASCII_TURKCE <taconite-root> <taconite-replace-children contextNodeID="div" parseInBrowser="true"><div> Java <font color="#33AA33">iÅŸ</font> <font color="#FF0033">cool</font> :) </div> </taconite-replace-children> </taconite-root> The result from the request is a XML document. According to my experience I would use SAX instead of Java XML native implementation.
doc_2513
Runas /user:domain\user "cmd /C echo Test > C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config" The problem ist, this is only working if the path of the file has no blank spaces. And I can not put the path in quotation marks as usually because the whole CMD-command has to be in quotation marks. Runas /user:domain\user "cmd /C echo Test > "C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config"" Even escaping the double quotation marks is not working. Runas /user:domain\user "cmd /C echo Test > ""C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config""" Does anybody have an idea how to deal with that problem? Thanks! A: Escape inner double quotes using \ Reverse Solidus (backslash) as follows: Runas /user:domain\user "cmd /C echo Test>\"C:\Program Files\Install2AgentService\Install2AgentWinService.exe.config\"" Resources (equivalent): * *runas /? from an open command prompt *RUNAS at ss64.com Example use case: d:\bat> runas /noprofile /user:user "cmd /V:ON /C whoami&echo \"!CD!\"&echo !CD! Test runas>>\"%CD%\test runas.txt\"&pause" Enter the password for user: Attempting to start cmd /V:ON /C whoami&echo "!CD!"&echo !CD! Test runas>>"d:\bat\test runas.txt"&pause as user "MY-PC\user" ... d:\bat> type "test runas.txt" C:\WINDOWS\system32 Test runas C:\WINDOWS\system32 Test runas
doc_2514
I don't want to use the default id as a parameter because it would be way too simple to 'parse' other estimations if the url looks ends with /3 or /4. You'd just have to try a few URLs and if it's your lucky day, you'd get to "hack" an estimation that isn't yours. I'm planning to use a cron job to delete these estimations after a while, but I don't want to take any risk. To avoid that, I decided to use the visitor's session_id as a parameter, on which I removed every alphabetic characters, but still saved as a string in my MySQL 5.7 database so that ActiveRecord would be ok with that. I also changed my routes accordingly, and the result is supposed to be something like localhost:3000/devis/4724565224204064191099 # Devis means 'quotation' in french However, when I try to get to this route, I get the following error: ActiveRecord::RecordNotFound (Couldn't find Devi with an out of range value for 'id') Here is the relevant part of my controller: devis_controller.rb # ... def create @devi = Devi.new(devi_params) respond_to do |format| @devi.status = 'created' @devi.session_id = session.id.gsub(/[^\d]/, '').to_s # How I store my parameter # Latest record returns '4724565224204064191099' if @devi.save format.html { redirect_to @devi, notice: 'Devi was successfully created.' } format.json { render :show, status: :created, location: @devi } else format.html { render :new } format.json { render json: @devi.errors, status: :unprocessable_entity } end end end # ... private def set_devi @devi = Devi.find(params[:session_id].to_s) # Tried '.to_s', didn't work end And here are my routes: # 'index' and 'destroy' don't exist resources :devis, only: %i(create update) get '/devis/nouveau', to: 'devis#new', as: :devis_new get '/devis/:session_id', to: 'devis#show', as: :devis_show get '/devis/editer/:session_id', to: 'devis#edit', as: :devis_edit My question is the following: is there a way to present the :session_id as a string to my controller's params? Or do I have a better option? Thank you A: I think session_id is a int at database, and then is where you should do the change. change the type of session_id to string and ActiveRecord map session_id as string from then on
doc_2515
Ex: {(0,0):2, (1,1):3} would output to the following numpy array ([[2,0], [0,3]]) What would be the simplest way to convert this dense dictionary into a sparse array? A: This should work, the only thing you need, you should know the dimensions for your output. import numpy as np d = {(0,0):2, (1,1):3} S = 2 table = np.zeros((S,S)) for k,v in d.items(): if d[k]: table[ k[0],k[1] ] = v print(table)
doc_2516
However, as soon as one part of the input matches, the submit button activates and a user can submit the form even if I put a number or capital letter. I want to disable this and not let a user click submit unless it matches perfectly as opposed to just finding one match and activating the button. I want the regex to only allow lowercase letters that match one of the 6 above and are separated by commas. Input text field: <input type="text" name="input" ng-model="keysToPlay.text" ng-pattern="format" required ng-trim="false" class="form-control" placeholder="c, d, e, etc..."> My regex is: $scope.format = /^[cdefgab]{1}(, [cdefgab]{1})*/; A: Try this and see if it works properly: placeholder="((?:[ac-g], ?)+[ac-g])" If not let me know and I'll see if I can fix it
doc_2517
json Object we receive is : { "1": { "serverName": "abc" } } we want to read the above response using $.ajax in jsp page. when we try to read it, getting the error "Uncaught SyntaxError: missing ) after argument list" in browser console, code snippet where we getting the error $.ajax({ type : 'POST', contentType : "application/json; charset=utf-8", url : 'MyServices1.do', success : function(datas) { alert(datas); var graphData = JSON.parse(datas); alert(graphData.1.serverName); } }); A: The line alert(graphData.1.serverName); throws the error since you can't access the property 1 directly. Instead use alert(graphData[1].serverName);
doc_2518
How can I solve this error? #include<iostream> #include<sstream> using namespace std; void separate(string product) { std::istringstream is(product); double n; int i = 0; while(is >> n) { cout << i << ": " << n << " "; i++; } } int main() { string product1, product2; cin >> product1; separate(product1); } Input: 12 1 5.30 Output: 0: 12 I need the output to be: 0: 12 1: 1 2: 5.30
doc_2519
<?php error_reporting(0); /* function: returns files from dir */ function get_files($images_dir,$exts = array('jpeg','gif','png','jpg')) { $files = array(); if($handle = opendir($images_dir)) { while(false !== ($file = readdir($handle))) { $extension = strtolower(get_file_extension($file)); if($extension && in_array($extension,$exts)) { $files[] = $file; } } closedir($handle); } return $files; } /* function: returns a file's extension */ function get_file_extension($file_name) { return substr(strrchr($file_name,'.'),1); } $images_dir = 'hftpnyc/thumbs/'; $thumbs_dir = 'hftpnyc/thumbs/thumbnails/'; $thumbs_width = 100; $images_per_row = 11; $string = ""; /** generate photo gallery **/ $image_files = get_files($images_dir); if(count($image_files)) { $index = 0; foreach($image_files as $index=>$file) { $index++; $thumbnail_image = $thumbs_dir.$file; //if(!file_exists($thumbnail_image)) { //$extension = get_file_extension($thumbnail_image); //if($extension) { //make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width); //} //} error_reporting(0); echo '<div class="smllpic" style=" padding: 0px; margin: 0px; border: 1px solid black; display: block; width: 100px; height:100px; float: left; "><a href="'.$images_dir.$file.'" rel="lrgimg" class="lightbox"> <img id="thumbs" src="',$thumbnail_image,'" width="100px"/></a></div>'; if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; } } } else { echo '<p>There are no images in this gallery.</p>'; } ?> A: Did you try a Google search for "jQuery image preload"? Yeah, almost 500,000 results chock full of useful plugins and tutorials. Here is a sampling: jQuery Image Preload Plugin jQuery Smart Preloader Plugin jQuery Preload Images - Tutorial and Example
doc_2520
final MultiUserChat muc = new MultiUserChat(connection, chatName+"@conference.123"); try { muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); muc.create(chatName); } catch (XMPPException e) { Log.e("Exception", e.getMessage()); } This gives an exception (not-authorized(401)). Following are the two packets received from server: <iq id="J1O5y-5" to="akshay@123/Smack" from="[email protected]" type="error"><error code="401" type="AUTH"><not-authorized xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq> and <message to="akshay@123/Smack" from="[email protected]" type="groupchat"><body>This room is locked from entry until configuration is confirmed.</body></message> So are there any changes in server configuration that I need to make or is there any problem in code ? A: How about changing the order as below: muc.create(nickName); muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); Hope this will help :) A: It worked for me. Please try this. public void createRoom(String r,String n) throws XMPPException { // TODO Auto-generated method stub String t = r + "@conference.localhost"; MultiUserChat muc = new MultiUserChat(connection, t); muc.create(n); muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); }
doc_2521
I want to scale the the plot area to fit the plot in view. I tried using [plotspace scaleToFitPlots: [NSArray arrayWithObject:mainPlot]]; which worked, except that the axes were scaled independently: The X axis is stretched relative to the Y axis. So that the slope of the line is shown accurately, it is important that both axes be scaled together. How can I scale a plot area to fit a plot while maintaining an equal relationship between axes? To be clear, the range of the axes can vary, but the physical amount of onscreen space between 0 and 1 needs to be the same on both axes. A: After calling -scaleToFitPlots:, inspect the resulting plot ranges and adjust them as needed to achieve the effect you want. Compare the length of each range to the corresponding dimension of the plot area bounds (compute the ratio between the length and bounds size), determine if one ratio is larger than the other, and adjust the ranges as needed so the ratios match.
doc_2522
Specific example. I have a class that accepts a CalculationMethod (interface) to do the calculation. There are several implementations of CalculationMethod. The GUI developer wants to only use data binding to present the choices to the user. I have taken a few approaches. Easiest is to create a class that returns a list(of CalcuationMethod) for all the implementations and add a Name property to CalculationMethod for display purposes. Expanding on that I will sometimes create a class that uses reflection to do the same thing (finds all the classes that implement CalculationMethod). This way I don't have to remember to add new implementations but it can be bad in web applications (it is expensive) or environments that don't allow reflection. At times I have added an enumeration with each enum representing an implementation. There is a factory method that accepts the enumeration and returns the proper implementation. This way the GUI developer can bind to the enumeration. I often do this if the user selection must be persisted in some way. All the above have advantages and disadvantages. Are there other and/or better ways to do this? Example below. The GUI developer would bind the dropdown (or whatever) to the CalculationOptions.Calculations allowing the user to select. I won't write the other examples because you should get the idea. (I would use reflection to get all the classes that inherit CalculatoinTemplate or I would have an enum that represents all the classes that inherit.) Public Class CalculationTemplate Public MustOverride Readonly Property Name() as string Public MustOverride Sub Calculate() End Class Public Class CalculationImp1 Public Overrides Sub Calculate() End Sub Public Overrides Readonly Property Name() as String Get Return "Imp1" End Get End Property End Class Public Class CalculationImp2 Public Overrides Sub Calculate() End Sub Public Overrides Readonly Property Name() as String Get Return "Imp2" End Get End Property End Class Public Class CalculationOptions Public Shared Function Calculations() as List(Of CalculationTemplate) Dim lst as New List(Of CalculationTemplate) lst.add(new CalculationImp1) lst.add(new CalculationImp2) Return lst End Function End Class A: Add a new function named AddCalculationOption() in CalculationOptions class, which adds calculation options to list. Call AddCalculationOption function in constructor of CalculationTemplate with current Object and return value from name() as arguments. So when an object is created it is automatically added to the list. You can use the name to have map for name and object. which can be used by factory to return appropriate object. I hope I understood your question properly.
doc_2523
Is Quote the best way? A: You can use DBI placeholders. Here is an example (from this link): #! /usr/bin/perl use DBI; print "Enter the city you live in: "; chomp( $city = <STDIN> ); print "Enter the state you live in: "; chomp( $state = <STDIN> ); $dbh = DBI->connect(your db info here); $sth = $dbh->prepare( "SELECT name WHERE city = ? AND state = ?" ); $sth->execute( $city, $state );
doc_2524
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at SQLite.Vm.step(Native Method) at SQLite.Database.get_table(Database.java:314) at SQLite.JDBC2z.JDBCStatement.executeQuery(JDBCStatement.java:120) at SQLite.JDBC2z.JDBCStatement.executeQuery(JDBCStatement.java:168) at TestData.readData(TestData.java:21) at TestData.main(TestData.java:41) A: By using the -Xmx command line parameter when you invoke java. See http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html A: Following are few options available to change Heap Size. -Xms<size> set initial Java heap size -Xmx<size> set maximum Java heap size -Xss<size> set java thread stack size java -Xmx256m TestData.java A: Use -Xms1024m -Xmx1024m to control your heap size (1024m is only for demonstration, the exact number depends your system memory). Setting minimum and maximum heap size to the same is usually a best practice since JVM doesn't have to increase heap size at runtime. A: -XmxSIZE For example: -Xmx1024M A: Java command line parameters -Xms: initial heap size -Xmx: Maximum heap size if you are using Tomcat. Update CATALINA_OPTS environment variable export CATALINA_OPTS=-Xms16m -Xmx256m; A: Start the program with -Xms=[size] -Xmx -XX:MaxPermSize=[size] -XX:MaxNewSize=[size] For example - -Xms512m -Xmx1152m -XX:MaxPermSize=256m -XX:MaxNewSize=256m
doc_2525
table emp eid ename age salary 1000 Lakmal 33 90000 1001 Nadeeka 24 28000 table works eid did percentage 1000 Admin 40 1000 ITSD 50 1001 Admin 100 1002 Academic 100 1003 Academic 30 I want to Display the employees’ name and the total percentage he/she has worked in total. And this is what I tried select sum(w.pct_time) as 'Total' ,e.ename from emp e, works w where w.eid = e.eid group by w.eid and this is not working, i get this error Column 'emp.ename' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. can anyone explain how to obtain above output? A: This can be used for percentage calculation Select (Sum(pct_time)* 100 / (Select Sum(pct_time) From works)) as 'Total', e.ename, e.eid From emp e Join works w On e.eid = w.eid Group By e.ename, e.eid using inner join is enough, if all people worked included in the emp table. You seem to have all employees, but some work records for some identification numbers are missing. A: Correct your group by clause as below. select sum(w.pct_time) as 'Total' ,e.ename from emp e, works w where w.eid = e.eid group by e.ename Note: Here, I am assuming that names are unique since you only need to display ename and pct_time. If not, this will not give correct results as it will combine the results of all employees with same name. If names are not unique, you can add e.eid as well in group by clause. select sum(w.pct_time) as 'Total' ,e.ename from emp e, works w where w.eid = e.eid group by e.eid, e.ename A: Here's a full working SQL Server sample, with tables converted to common table expressions: with [emp] (eid, ename, age, salary) as ( select eid, ename, age, salary from ( values (1000 , ' Lakmal', 33, 90000), (1001 , 'Nadeeka', 24, 28000) ) as result (eid, ename, age, salary) ), [works] (eid, did, pct_time) as ( select eid, did, percentage from ( values (1000, 'Admin', 40), (1000, 'ITSD', 50), (1001, 'Admin', 100), (1002, 'Academic', 100), (1003, 'Academic', 30) ) as result(eid, did, percentage) ), [grouped] (eid, pct) as ( ' Do the grouping here. select e.eid, sum(w.pct_time) from emp e inner join works w on w.eid = e.eid group by e.eid ) ' And now you can join the grouped results with the employees to display the names select [w].pct as 'Total', e.ename from [emp] e inner join [grouped] w on w.eid = e.eid;
doc_2526
Am I correctly understand that AddExtension method do what I expect? public class MyUnityContainer : UnityContainer { public MyUnityContainer(MyUnityContainer containerParent) { if ( containerParent!=null ) this.AddExtention(containerParent); } public static void Test() { MyUnityContainer cont1 = new MyUnityContainer(); cont1.RegisterType<IA,A>(); MyUnityContainer cont2 = new MyUnityContainer(cont1); IA a = cont2.Resolve<IA>(); } Should this work? If not, what is a way to achieve such functionality? I could make MyUnityContainer not inherited from UnityContainer, but containing it ("has a" instead of "is a"), but I don't want to implement IUnityContainer interface in my MyUnityContainer class. A: No, that's not what extensions do. Extensions add new features or registrations to the container, not set up inheritance relationships. What you want is a child container. You call parent.CreateChildContainer, and that should do what you want - except that the child will be a UnityContainer, not MyUnityContainer. What does MyUnityContainer do? Perhaps there's a way to make it work without the subclass?
doc_2527
So I want to do calculations like leading = screen_width/3 and trailing = screen_width/3 It is possible and it is a good solution ? How to do this or here is an better way ? A: If the leading will be w / 3 and trailing is the same. So the image width itself is w / 3 as well. So set Width constraint to be width = superview.width / 3. Then add another constraint to center it horizontally A: When there is such requirement that you want to show View A in centre of View B, I recommend the following constraints: - View A : Equal Width to superview (i.e. View B), with multiplier. (In your case 1/3 = 0.33). - View B : Equal Height to superview (i.e. View A), with multiplier. (In your case 1/3 = 0.33). - View A Center Vertically to superview (i.e. View B). - View A Center Horizontally to superview (i.e. View B). A: If you want to centralize your image, you can do it through auto layout and that should work for all the devices. This is the approach I would take- First take an image view inside your table view cell and with cursor centralize it. Now- Step 1: control drag from the image view to you table view's content view. and select "Center horizontally" and "Center vertically option". At this point, you may see some red or yellow line but avoid that. We are going to deal with that now. Step 2: Pin the top and botton to the content view. Here I assumed your image height is same as your cell height but that can change according to your requirement. So, pin to the content view like - Now you are just left with your image's width. In my case I assumed it is going to be same as the height , so I just had to control drag to itself and select "Aspect Ration" like- This is you final constrains That should work fine. If your image view's width is not same as your its height then you can you "Equal Width" property with respect to the cell's content view and tell it how you like your width to be. You DO NOT use trailing or leading space constraints when you are centralize an object inside another.
doc_2528
Test class: @Tag("foo") class SomeIT { @Test public void testSomeStuff() { ... } } Suite class: @RunWith(JUnitPlatform.class) @IncludeTags({"foo"}) //@SelectPackages("org.foo") public class SomeITSuite { } My pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.foo</groupId> <artifactId>bar</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.slf4j>1.7.30</version.slf4j> <version.junit>5.7.0</version.junit> <version.junit.platform.runner>1.7.0</version.junit.platform.runner> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> </plugin> </plugins> </build> <dependencies> <!-- for testing --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>${version.junit}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-runner</artifactId> <version>${version.junit.platform.runner}</version> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>integration-tests</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>3.0.0-M5</version> <configuration> <includes> <include>**/*ITSuite.java</include> </includes> </configuration> <executions> <execution> <id>integration-test</id> <phase>integration-test</phase> <goals> <goal>integration-test</goal> </goals> </execution> <execution> <id>verify</id> <phase>verify</phase> <goals> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> This executes the suite with 0 tests in both Idea and a console (using mvn clean install -Pintegration-tests). If I restore the commented out @SelectPackages("org.foo"), it will run all the tests, regardless of whether they're tagged, or not. What am I missing here? Is this a bug? A: Apparently, when JUnit scans the classes, it doesn't identify such that end with IT as integration tests. I had to rename them to *ITTest and things started working. If anyone's interested in more details, you can have a look at this pull request.
doc_2529
from flask import Flask, request, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World! I am running on port ' + str(port) @app.route('/health') def health(): return 'OK' @app.route('/es', defaults={'path': ''}) @app.route('/es/<path:path>') def es_status(path): resp = Response( response='{"version":{"number":"6.0.0"}}', status=200, content_type='application/json; charset=utf-8') return resp Any help is appreciated. A: You can take a look on Gorilla Mux which is a popular URL router and dispatcher for golang. A sample catch all route could be configured using Mux as: r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) A: Use a path ending with "/" to match an entire subtree with http.ServeMux. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // The "/" matches anything not handled elsewhere. If it's not the root // then report not found. if r.URL.Path != "/" { http.NotFound(w, r) return } io.WriteString(w, "Hello World!") }) http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "OK") }) http.HandleFunc("/es/", func(w http.ResponseWRiter, r *http.Request) { // The path "/es/" matches the tree with prefix "/es/". log.Printf("es called with path %s", strings.TrimPrefix(r.URL.Path, "/es/")) w.Header().Set("Content-Type", "application/json; charset=utf-8") io.WriteString(w, `{"version":{"number":"6.0.0"}}`) } If the pattern "/es" is not registered, then the mux redirects "/es" to "/es/".
doc_2530
// Inside webapp const host = document.querySelector('#sdk-launcher'); if (host) { const shadowRoot = host.attachShadow({ mode: 'open' }); const script = document.createElement('script'); if (script) { script.type = 'text/javascript'; script.src = 'cdn.com/sdk-link.js'; script.onload = () => { // @ts-ignore _mylib = Mylib; // @ts-ignore Mylib.init({ userId: 'john', appKey: 'asndkj-asdn-aksnd-aklsdn', }); }; script.id = 'sdk-loader'; shadowRoot.appendChild(script); } } This script is basically another webapp exported as a library that attaches some styles to the document. // Inside SDK (Mylib library) document.documentElement.style.setProperty('--color-base-white', colorInversePrimary); Now instead of attaching to the root document, I want to attach these styles to only the shadowDOM from within the SDK code so that it does not impact the root document. Any ideas how can I do so?
doc_2531
A: Slight variation of Gerald's answer using keyword args create pickleable object image = {'data': im.tostring(), 'size':im.size, 'mode':im.mode} or image = dict(data=im.tostring(), size=im.size, mode=im.mode) unpickle back to image im = Image.fromstring(**image) A: You can convert the Image object into data then you can pickle it: image = { 'pixels': im.tostring(), 'size': im.size, 'mode': im.mode, } And back to an Image: im = Image.fromstring(image['mode'], image['size'], image['pixels']) NOTE: As astex mentioned, if you're using Pillow (which is recommended instead of PIL), the tostring() method is deprecated for tobytes(). Likewise with fromstring() for frombytes().
doc_2532
Date.valueOfYearMonthDay(int year, int month, int day); But then I found that the resultant code using the API was not very readable. So I added: Date.yearMonthDay(int year, int month, int day) Date.ymd(int year, int month, int day) Date.date(int year, int month, int day) Then I started getting fluent: Date.january().the(int day).in(int year); (I find that the fluent version is really useful for making readable tests). All these methods do identical things and have accurate JavaDoc. I think I've read that a strength of perl is that each programmer can choose exactly which method he/she prefers to solve something. And a strength of Java is that there is usually only one way of doing things :-) What are people's opinions? A: I've been doing academic research for the past 10 years on different issues that have to do with API usability in Java. I can tell you that the statement about having one way to do things in Java is fairly incorrect. There are often many ways to do the same thing in Java. And unfortunately, they are often not consistent or documented. One problem with bloating the interface of a class with convenience methods is that you are making it more difficult to understand the class and how to use it. The more choices you have, things become more complex. In an analysis of some open-source libraries, I've found instances of redundant functionality, added by different individuals using different terms. Clearly a bad idea. A greater problem is that the information carried by a name is no longer meaningful. For example, things like putLayer vs. setLayer in swing, where one just updates the layer and the other also refreshes (guess which one?) are a problem. Similarly, getComponentAt and findComponentAt. In other ways, the more ways to do something, the more you obfuscate everything else and reduce the "entropy" of your existing functionality. Here is a good example. Suppose you want in Java to replace a substring inside a string with another string. You can use String.replace(CharSequence, CharSequence) which works perfectly as you'd expect, literal for literal. Now suppose you wanted to do a regular expression replacement. You could use Java's Matcher and do a regular expression based replacement, and any maintainer would understand what you did. However, you could just write String.replaceAll(String, String), which calls the Matcher version. However, many of your maintainers might not be familiar with this, and not realize the consequences, including the fact that the replacement string cannot contains "$"s. So, the replacement of "USD" with "$" signs would work well with replace(), but would cause crazy things with replaceAll(). Perhaps the greatest problem, however, is that "doing the same thing" is rarely an issue of using the same method. In many places in Java APIs (and I am sure that also in other languages) you would find ways of doing "almost the same thing", but with differences in performance, synchronization, state changes, exception handling, etc. For instance, one call would work straight, while another would establish locks, and another will change the exception type, etc. This is a recipe for trouble. So bottom line: Multiple ways to do the same thing are not a good idea, unless they are unambiguous and very simple and you take a lot of care to ensure consistency. A: I'd echo what some others said in that convenience methods are great, but will take it a step further - all "convenience" methods should eventually call the same underlying method. The only thing that the convenience methods should do other than proxy the request is to take or return variables differently. No calculations or processing allowed in the convenience methods. If you need to add additional functionality in one of them, go the extra mile and make it happen in the "main" / "real" one. A: Its fine to provide convenience methods, the real problem is if each entry point begins to do behave in subtly different ways. Thats when the api isn't convenient anymore. Its just a pain to remember which way is "right," and documentation starts saying "the recommended way is..." If Date.yearMonthDay() began to validate the date while Date.ymd() didn't, that'd be a problem. The same goes for if each begins supporting different "features" - Date.yearMonthDay() could take non-gregorian dates, and Date.date() could take a non-gregorian dates so long as a 4th object is given that tells the calendar type. A: First, please don't invent your own date library. It's too hard to get right. If you absolutely have nothing better to do, be sure to read -- and understand -- Calendrical Calculations. Without understanding Calendrical Calculations you run a big risk of doing things wrong in obscure corner and edge cases. Second, multiple access to a common underlying method is typical. Lots of Java library API methods state that they are simply a "wrapper" around some other method of class. Also, because of the Java language limitations, you often have overloaded method names as a way to provide "optional" arguments to a method. Multiple access methods is a fine design. A: If these do the exact same thing: Date.yearMonthDay(int year, int month, int day) Date.ymd(int year, int month, int day) Date.date(int year, int month, int day) I think that is bad form. When I am reading your code, I have no clue which one to use. Things like canvas.setClipRegion (int left, int top, int right, int bottom); canvas.setClipRegion (Rect r); are different in that it allows the caller to access the functionality without having to figure out how to format the data. A: My personal opinion is that you should stick with one method to do something. It all 4 methods ultimatly call the same method then you only need on of them. If however they do something in addition to calling them method then they should exist. so: // This method should not exist Data yearMonthDay(final int year, final int month, final int day) { return (valueOfYearMonthDay(year, month, day)); } The first methid in addition to the fluent version would make more sense. But the yearMonthDay, ymd, and date methods should go. Also, differnt langauges have different goals. Just because it makse "sense" in Perl doesn't mean it makes sense in Java (or C#, or C++, or C, or Basic, or...) A: I find that the fluent version is really useful for making readable tests. This is a little bit troublesome because I worry that you might only be testing the fluent version. If the only reason methodX() exists is so you can have a readable test for methodY() then there is no reason for one of methodX() or methodY() to exist. You still need to test them in isolation. You're repeating yourself needlessly. One of the guiding principles of TDD is that you force yourself into thinking about your API while you're writing your code. Decide which method you want clients of your API to use and get rid of the redundant ones. Users won't thank you providing convenience methods, they'll curse you for cluttering your API with seemingly useless redundant methods.
doc_2533
* *A table test.domain(int id, text value) that stores possible values for a field. This data is dynamic. *A table test.table(id int, domainn text) which domainn field references to the test.domain table. *A view test.view_domain which is a view of test.domain. I have defined a INSTEAD of trigger with the security definer option on the view. This trigger updates the table test.domain. The problem is that despite this trigger is being executed as the user "system", the reference update on the table test.table is executed by the invoker user. Here is an example where, if executed as postgres, I expect to get "user system" as error instead of "user postgres" drop schema IF EXISTS test cascade; create schema test; create function test.modified() returns trigger as $$ BEGIN raise exception 'user %', ' '||current_user; END $$ language plpgsql; set role system; create function test.insert_with_system() returns trigger as $$ DECLARE valor text; BEGIN --raise exception 'user %', ' '||current_user; update test.domain set value = ''||new.value where id = new.id; END $$ language plpgsql security definer; reset role; CREATE table test.domain( id int primary key, value text unique ); create view test.domain_view as select * from test.domain; create table test.table( id int primary key, domainn text ); alter table test.table add foreign key (domainn) references test.domain(value) on delete restrict on update cascade; create trigger test_trigger before insert or update or delete on test.table for each row execute procedure test.modified(); create trigger instead_ins INSTEAD OF update or delete on test.domain_view for each row execute procedure test.insert_with_system(); insert into test.domain(id, value) values(1,'one'); alter table test.table DISABLE TRIGGER all; insert into test.table(id, domainn) values (0,'one'); alter table test.table enable TRIGGER all; update test.domain_view set value = 'two'; select * from test.table; A: A cascading update is always run in the security context of the owner of the referencing table (test.table in your example). See ri_PerformCheck in src/backend/utils/adt/ri_triggers.c: /* * Use the query type code to determine whether the query is run against * the PK or FK table; we'll do the check as that table's owner */ if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK) query_rel = pk_rel; else query_rel = fk_rel; ... /* Switch to proper UID to perform check as */ GetUserIdAndSecContext(&save_userid, &save_sec_context); SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner, save_sec_context | SECURITY_LOCAL_USERID_CHANGE | SECURITY_NOFORCE_RLS); I tried to follow the code to its origin, and the behavior seems to originate in commit 465cf168eb6151275016486fe2d2c629fed967ca. Searching the hackers archives for relevant discussions, I found this. So, as far as I can say, the behavior tries to avoid the following: * *User A owns atable and grants REFERENCES on that table to user B. *User B owns btable and adds a foreign key to atable with ON UPDATE OR DELETE CASCADE. User A has no permissions on btable. *User A tries to update or delete a row in atable that would cascade to btable and fails with a “permission denied” error. I personally am not certain if the present behavior is good or not, but I can see the point that it would be surprising for A' not to be able to modify a table she owns.
doc_2534
I've been working on this for awhile and i'm stuck. Can someone help me! I've created a text file and tried to insert it in the the project but it still does not detect it. I don't know what else to do. Thanks in advance!! #include <stdio.h> #include "stdlib.h" #include "string.h" void Ouccpy_Routing_Table(); typedef struct RTE { unsigned long Dest; int port; unsigned long Route; }; Route[120]; struct IP { unsigned char Ipverison; unsigned char TOS; unsigned short ID; unsigned short Fragoffset; unsigned char TTL; unsigned char Protcl; unsigned char dcheksum; unsigned char Data[1]; }; int main() { int count; FILE *ptr_testfile; struct IP my_testfile; ptr_testfile = fopen_s("c:\\testroute\\TEST.txt", "rb"); if (!ptr_testfile) { printf("Cannot Open File!"); return 1; } while (count = 2) count <= (sizeof(struct IP)); count++; { fread(&my_testfile, sizeof(struct IP), 2, ptr_testfile); } fclose(ptr_testfile); return 0; } void Ouccpy_Routing_Table() { } A: Put the text file in the corresponsing location. * *c:\testroute\TEST.txt Verify it before compiling. If the problem persists, please post the error code? A: Regarding the way the code tries to open the file ptr_testfile = fopen_s("c:\\testroute\\TEST.txt", "rb"); The compiler should at least warn you not providing enough parameters. If you would have read the documentation to fread_s() you would have learned that it should have been called: errno_t en = fopen_s(&ptr_testfile, "c:\\testroute\\TEST.txt", "rb"); if (0 != en) { issue some error message here } As an alternative you could use the standard fopen() instead the Microsoft specific fopen_s(). fopen() would be called as your original code does. This while (count = 2) count <= (sizeof(struct IP)); count++; { fread(...); } is the same as while (count = 2) count <= (sizeof(struct IP)); count++; { fread(...); } which in turn is the same as while (count = 2) /* This repeatly assigns 2 to count. Resulting in an infinite loop.*/ { count <= sizeof(struct IP); /* This does nothing. */ } /* Because of the infinite loop above the code never arrives here. */ count++; fread(...); Please have a second look.
doc_2535
Let's say I have a table called [student], with 4 columns: [name], [gender], [age], [country]. How to do a 'SELECT *' query that returns the rows that meet this requirements: * *student must be male *only one student from each country *if there are more than one students from a country, choose the oldest one I tried using GROUP BY on [country] but keep getting error "Column '...' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" A: One possible approach: SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Country ORDER BY Age DESC) RN FROM students WHERE gender = 'male') T WHERE RN = 1; The subquery selects only male students, and assigns them a row number based on their age, partitioned by country.
doc_2536
I saw this question before. But the option from rbokeh produces a low quality graphic. I tried to use the second option, but it seems that there is an error in the code, because the function throws object 'vl' not found. As that question is from three years ago, I think that there may be a better solution so far. Example graphic that I want to save: --- title: "Untitled" author: "Guilherme" date: "12/5/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, fig.path = "graph/") ``` ```{r} library(networkD3) URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/', 'master/JSONdata/energy.json') energy <- jsonlite::fromJSON(URL) # Plot sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', units = 'TWh', fontSize = 12, nodeWidth = 30) ``` A: What about something like this: -- title: "sankey as image" author: "..." date: "12/5/2020" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, fig.path = "graph/") ``` ```{r, fig.align='center'} library(networkD3) URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/', 'master/JSONdata/energy.json') energy <- jsonlite::fromJSON(URL) # Plot sn <- sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', units = 'TWh', fontSize = 12, nodeWidth = 30) # you save it as an html saveNetwork(sn, "sn.html") library(webshot) # you convert it as png webshot("sn.html","sn.png", vwidth = 1000, vheight = 900) ```
doc_2537
Example: Common tables: Client_ClientDepartment (Id, Value) Client_ClientDesignation (Id, Value) Client_ClientCompany (Id, Value) What I want to do is to pass table name and Id to get the value. I have created a common method as public string GetClientValue(string id, string tableName) { DatabaseContext dbContext = new DatabaseContext(); //Query the database and get value based on table and id. string value = dbContent. ("query here") return value ; } Can I do it in entity framework? Is it possible? A: using ( DatabaseContext dbContext = new DatabaseContext()) { var blogs = dbContext.Database.SqlQuery<>("query here").ToList(); } A: I believe you can run a custom query like this using (var context = new BloggingContext()) { var blogNames = context.Database.SqlQuery<string>( "SELECT Name FROM dbo.Blogs").ToList(); } Source: https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx Sorry I had to answer instead of comment, but don't got the badge yet. A: Actually, you normally don't pass table and column names in EF. You have classes and properties, which become tables and columns in the resulting database. Your context should look something like this: public class DatabaseContext : DbContext { public DatabaseContext(): base(YourWebConfigConnectionStringName){} public DbSet<Client_ClientDepartment> ClientDepartment { get; set; } public DbSet<Client_ClientDesignation> ClientDesignation { get; set; } With this you are basically registering your "table" classes. You then address them in code like this: using (var context=new DatabaseContext()) { var department = context.ClientDepartment.First(d => d.Id == someIdVariable); Which is the analogy to a SQL query SELECT TOP 1 department WHERE ID=someId You can also pass SQL statements as described in the other answers, but that too will only work if you properly registered your classes as DBSets in your DatabaseContext class. P.S: I left out the Database initializer in the DBContext class, which is something you also need in code first.
doc_2538
So basically when I do the PUT I want to provide the versionid of the document I started with, and get 409 conflict error if that version is no longer the current version. I'm really hoping s3 supports this, but I've not been able to find an example yet. A: There is no mechanism for this sort of conditional PUT in S3. Overwrite PUTs are only eventually consistent, so the notion of what was the current version when a PUT occurred is not something that has a strict meaning in S3. You could come close by sending a HEAD request immediately before the PUT to verify that the version you're working on still appears to be the current version, and in doing so, avoid an obvious condition where the object has been overwritten an become consistent between when you fetched it and when you are about to overwrite it, but there's an inevitable window of time, however short it may be, when the object still could be or could have extremely recently been changed. You could also maybe mitigate the potential harm by adding metadata to the replacement copy, such as x-amz-meta-replaces-version-id and the former versionId, auditing it later or in near real time with an S3 event notification, and catching cases where an intermediate version was uploaded... but there's no conditional update capability or object locking built-in.
doc_2539
import numpy as np from sklearn.tree import DecisionTreeClassifier train_data = np.array([[0, 0, 1, 0], [1, 0, 1, 1], [0, 1, 1, 1]], dtype=bool) train_targets = np.array([0, 1, 2]) c = DecisionTreeClassifier() c.fit(train_data, train_targets) p = c.predict(np.array([1, 1, 1, 1], dtype=bool)) print(p) # -> [1] That works fine. However, suppose now that I know a priori that the presence of feature 0 excludes class 1. Can additional information of this kind be easily included in the classification process? Currently, I'm just doing some (problem-specific and heuristic) postprocessing to adjust the resulting class. I could perhaps also manually preprocess and split the dataset into two according to the feature, and train two classifiers separately (but with K such features, this ends up in 2^K splitting). A: Can additional information of this kind be easily included in the classification process? Domain-specific hacks are left to the user. The easiest way to do this is to predict probabilities... >>> prob = c.predict_proba(X) and then rig the probabilities to get the right class out. >>> invalid = (prob[:, 1] == 1) & (X[:, 0] == 1) >>> prob[invalid, 1] = -np.inf >>> pred = c.classes_[np.argmax(prob, axis=1)] That's -np.inf instead of 0 so the 1 label doesn't come up as a result of tie-breaking vs. other zero-probability classes.
doc_2540
But when I try to do a stored procedure call dbo.GET_ALL_USERS", it fails because SQLite doesn't support stored procedures... So, how do you test an app that uses stored procedures? Can I convert the stored procedure to multiple queries? Can I mock the result of the stored procedure? A: I use tSQLt for unit testing my stored procedures in SQL Server https://tsqlt.org/ For MySQL, I use http://utmysql.sourceforge.net/
doc_2541
I made this code but by this only one radio button is working. $(document).ready(function() { $('#radio1').change(function() { $("#lhr1").prop("checked", true) }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <h2 align="center"><b><i>Form Validation Assignment</i></b></h2> <form id="vald" class="form-horizontal" action=""> </div> <div class="form-check form-check-inline" id="radio1"> <label class="control-label col-sm-2" for="name">Gender</label> <div class="container"> <label class="radio-inline"> <input type="radio" name="optradio" id="male">Male </label> <label class="radio-inline"> <input type="radio" name="optradio" id="female">Female </label> </div> </div> <input type="checkbox" name="lhr" value="lhr" id="lhr1"> You can go Lahore<br> <input type="checkbox" name="mtn" value="mtn" id="mtn1">You can go Multan<br> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" id="add">Submit</button> </div> </div> </form> </div> If i select Male (radio button) then checkbox (" You can go Multan") should be select and if I select Female (radio button) then (" You can go Lahore") should be select. A: This should do the job $(document).ready(function(){ $('#male').click(function(){ $('#mtn1').prop("checked", $(this).is(':checked')); }); $('#female').click(function(){ $('#lhr1').prop("checked", $(this).is(':checked')); }); }); A: To just (slightly) modify your code, this should also work. $(document).ready(function() { $('#radio1').change(function() { // Get the currently selected gender let gender = $("input[name=optradio]:checked").attr("id"); // Check checkboxes based on gender $("#lhr1").prop("checked", gender === "male") $("#mtn1").prop("checked", gender === "female") }); }); A: It'll be easier to use data attribute for male and female inputs like this .. <input type="radio" name="optradio" id="female" data-check-id="mtn1"> $(document).ready(function() { $('[name="optradio"]').change(function() { $('#lhr1 , #mtn1').prop('checked' , false); $('#'+$(this).attr('data-check-id')).prop('checked' , true); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <h2 align="center"><b><i>Form Validation Assignment</i></b></h2> <form id="vald" class="form-horizontal" action=""> </div> <div class="form-check form-check-inline" id="radio1"> <label class="control-label col-sm-2" for="name">Gender</label> <div class="container"> <label class="radio-inline"> <input type="radio" name="optradio" id="male" data-check-id="lhr1">Male </label> <label class="radio-inline"> <input type="radio" name="optradio" id="female" data-check-id="mtn1">Female </label> </div> </div> <input type="checkbox" name="lhr" value="lhr" id="lhr1"> You can go Lahore<br> <input type="checkbox" name="mtn" value="mtn" id="mtn1">You can go Multan<br> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" id="add">Submit</button> </div> </div> </form> </div>
doc_2542
function timesTable() { var values = document.getElementById('value1'); var showTables = ''; for (var i=1; i<9; i++) { showTables += values + " x " + i +" = "+ values*i + "\n"; } var p_tables = document.getElementById('tables').innerHTML = showTables; } <label>Enter an integer from 1 to 9 : </label> <input type="text" size=20 id=value1 name="value"> <button onclick="timesTable()">Generate times table</button><br> <br> <p id="tables"></p> Expected result: A: You have to take the value of the element not the element itself var values = document.getElementById('value1').value; function timesTable() { var values = document.getElementById('value1').value; var showTables = ''; for (var i=1; i<9; i++) { showTables += values + " x " + i +" = "+ values*i + "<br>"; } var p_tables = document.getElementById('tables').innerHTML = showTables; } <label>Enter an integer from 1 to 9 : </label> <input type="text" size=20 id=value1 name="value"> <button onclick="timesTable()">Generate times table</button><br> <br> <p id="tables"></p> A: You are trying to multiply the element itself. What you actually want is the value. function timesTable() { var values = document.getElementById('value1').value; var showTables = ''; for (var i=1; i<9; i++) { showTables += values + " x " + i +" = "+ values*i + "\n"; } var p_tables = document.getElementById('tables').innerHTML = showTables; } <label>Enter an integer from 1 to 9 : </label> <input type="text" size=20 id=value1 name="value"> <button onclick="timesTable()">Generate times table</button><br> <br> <p id="tables"></p> A: the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property. You just have to find it's value, replace you line var values = document.getElementById('value1'); with var values = document.getElementById('value1').value; A: This does what you want. Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.) const userValue = document.getElementById("value1").value; const p_tables = document.getElementById("tables"); let outputHtml = ""; for(let i = 1; i < 10; i++){ outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>"; } p_tables.innerHTML = outputHtml; A: you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use <\br>(please ignore '\'). function timesTable() { var values = document.getElementById('value1').value; var showTables = ''; for (var i=1; i<=9; i++) { showTables += values + " x " + i +" = "+ values*i + "<br>"; } document.getElementById('tables').innerHTML = showTables; } <label>Enter an integer from 1 to 9 : </label> <input type="Number" size=20 id=value1 name="value"> <button onclick="timesTable()">Generate times table</button><br> <br> <p id="tables"></p>
doc_2543
This is my code: #include<Windows.h> //to use windows API #include<iostream> int main() { TCHAR a[] = TEXT("This is not ANSI anymore! Olé!"); //8bits each char wchar_t b[] = L"This is the Unicode Olé!"; //16 bits each char std::cout << a << "\n"; std::wcout << b << "\n"; return 0; } So I thought, after defining TCHAR, I could make use of: #ifdef UNICODE #define std::cout std::wcout #else #define std::cout std::cout #endif But still, my output is in hex for TCHAR a[], but why? It should use wcout automatically, right? A: std::cout does not support wchar_t strings, and std::wcout does not support char strings. So you will have to pick one or the other based on which character type TCHAR is using. You were right to try to use #define to work around that, but you used the wrong syntax for it. Try this instead: #include <Windows.h> //to use windows API #include <iostream> #ifdef UNICODE #define t_cout std::wcout #else #define t_cout std::cout #endif int main() { TCHAR a[] = TEXT("Olé!"); t_cout << a << TEXT("\n"); // or: t_cout << a << std::endl; return 0; } A: But still, my output is in hex for TCHAR a[], but why? You'll need to use _setmode with stdout for a correct console output. You'll need to do it to stdin also if you want to read console input. It should use wcout automatically, right? The macros are not correct, but if you define them correctly and assuming you enabled unicode, yes, TCHAR should expand t wchar_t, and the used output macro will be the one enabled by your #ifdef condition: #include <Windows.h> //to use windows API #include <iostream> #include <fcntl.h> #include <io.h> #ifdef UNICODE #define tcout std::wcout //unicode enabled #else #define tcout std::cout #endif int main() { _setmode(_fileno(stdout), _O_WTEXT); // enable wide char output TCHAR a[] = TEXT("This is not ANSI anymore! Olé!"); tcout << a << TEXT("\n"); } With _setmode: Without _setmode: A: In Windows with UNICODE set, TCHAR comes out to wchar_t. You can't use std::cout with wide characters. It only ever uses char. windows.h doesn't redefine cout in the way you think. So it's as if you were outputting an array of (signed or unsigned) short to the stream. The array decays to a pointer and that's probably why you see hex. However std::wcout << a << "\n"; should work. A: It's only possible for functions that are part of the Windows API, because the windows.h header file defines two functions, one each for ASCII and Unicode forms. TCHAR would change only for those present there. cout and wcout are not part of the Windows API. Rather, they are part of the standard C++ iostream header, so they do not change based on the definition of TCHAR.
doc_2544
while (currLine != null) { // Check if current line holds the query ID String regexp="\\.\\I\\s\\d"; Pattern pattern=Pattern.compile(regexp); Matcher matcher; if (pattern.matcher(currLine).matches()) { queryBuffer.append(currLine); currLine = buffR.readLine(); queryBuffer.append(".").append(" ").append(currLine); QueryListModel.add(iterator, queryBuffer.toString()); queryBuffer.delete(0, queryBuffer.length()); iterator++; } currLine = buffR.readLine(); } I took the regexp shown above, from regexplanet.com where i tested it and it validated. I checked other sites and validated as well. However, in Eclipse console i get the following error: Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 3 \.\I\s\d ^ Any help appreciated. A: String regexp="\\.I\\s\\d"); This will match everything that starts with a .I and it's fallowed by a number and has exactly 1 white space between them ".I 12132" or ".I 123213213"
doc_2545
We found that every time that Java updates itself, we have to once again re-install the Access Bridge components. Is there a way to use an environment variable to point to either the Java Access Bridge or Java JRE to a folder that I can protect from getting updated? A: When you update Java it installs it in a new folder and %JAVAHOME% changes. JAVAHOME on my systems is set to C:\Program Files\Java\jdk1.7.0_13 and when I update that 13 is going to change to a 14. Now the problem is that when you install Java Access Bridge files get copied into varies folders including %JAVAHOME%. So when you update Java the new Java home folder doesn't have the Java Access Bridge components. There is really nothing you can do except reinstall Java Access Bridge. See the installation doco at http://docs.oracle.com/javase/accessbridge/2.0.2/setup.htm#installing-jab-64-bit. A: This is the batch file we went with: @echo on cd /d %~dp0 rem case sensitive jre - finds juice Java folder and puts to temp.txt into temp folder :CHKFLEX set temp1=%LOCALAPPDATA%\Juice\Flex dir /AD /b %temp1% | find "jre" > %temp%\temp.txt rem didnt find the jre folder in juice if %errorlevel% NEQ 0 goto notfound rem create environment variable to path found and written to temp.txt for /f "delims=" %%x in (%temp%\temp.txt) do set temp2=%%x rem path to juice subfolder created set temp1 set temp2 set "_prog=%temp1%\%temp2%" rem copy if files aren't there already :x86 Set JAVAHOME32=%_prog% @echo on if exist "%JAVAHOME32%\bin\JavaAccessBridge-32.dll" goto theend copy WindowsAccessBridge-32.dll %WINDIR%\SYSTEM32 copy JavaAccessBridge-32.dll %JAVAHOME32%\bin copy JAWTAccessBridge-32.dll %JAVAHOME32%\bin copy accessibility.properties %JAVAHOME32%\lib copy access-bridge-32.jar %JAVAHOME32%\lib\ext copy jaccess.jar %JAVAHOME32%\lib\ext goto theend rem Juice JRE folder not found :notfound echo "Alternate JRE folder not found..." :theend pause Although we did have a more advanced batch file that can copy to both the Juice folder and to the Java folder by checking the registry for the java home path. Here is that one: @echo on cd /d %~dp0 :REGVAL FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment" /v CurrentVersion') DO set CurVer=%%B FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment\% CurVer%" /v JavaHome') DO set JAVA_HOME=%%B Set JAVA_HOME :CHKFLEX set temp1=%LOCALAPPDATA%\Juice\Flex dir /AD /b %temp1% | find "JRE" > %temp%\temp.txt if %errorlevel% NEQ 0 goto notfound for /f "delims=" %%x in (%temp%\temp.txt) do set temp2=%%x set temp1 set temp2 set "_prog=%temp1%\%temp2%" pause if not exist "%systemdrive%\Program Files (x86)" ( goto x86 ) else ( goto x64 ) :x86 Set JAVAHOME32=%_prog% @echo on if exist "%JAVAHOME32%\bin\JavaAccessBridge-32.dll" goto x86_next copy WindowsAccessBridge-32.dll %WINDIR%\SYSTEM32 copy JavaAccessBridge-32.dll %JAVAHOME32%\bin copy JAWTAccessBridge-32.dll %JAVAHOME32%\bin copy accessibility.properties %JAVAHOME32%\lib copy access-bridge-32.jar %JAVAHOME32%\lib\ext copy jaccess.jar %JAVAHOME32%\lib\ext :x86_next if exist "%JAVA_HOME%\bin\JavaAccessBridge-32.dll" goto theend copy JavaAccessBridge-32.dll %JAVA_HOME%\bin copy JAWTAccessBridge-32.dll %JAVA_HOME%\bin copy accessibility.properties %JAVA_HOME%\lib copy access-bridge-32.jar %JAVA_HOME%\lib\ext copy jaccess.jar %JAVA_HOME%\lib\ext goto theend :x64 Set JAVAHOME32=%_prog% Set JAVAHOME64=%_prog% @echo on if exist "%JAVAHOME64%\bin\JavaAccessBridge-64.dll" goto x64_next copy WindowsAccessBridge-32.dll %WINDIR%\SYSWOW64 copy WindowsAccessBridge-64.dll %WINDIR%\SYSTEM32 copy JavaAccessBridge-64.dll %JAVAHOME64%\bin copy JAWTAccessBridge-64.dll %JAVAHOME64%\bin copy accessibility.properties %JAVAHOME32%\lib copy access-bridge-64.jar %JAVAHOME64%\lib\ext copy jaccess.jar %JAVAHOME64%\lib\ext :x64_next if exist "%JAVA_HOME%\bin\JavaAccessBridge-64.dll" goto theend copy JavaAccessBridge-64.dll %JAVA_HOME%\bin copy JAWTAccessBridge-64.dll %JAVA_HOME%\bin copy accessibility.properties %JAVA_HOME%\lib copy access-bridge-64.jar %JAVA_HOME%\lib\ext copy jaccess.jar %JAVA_HOME%\lib\ext goto theend :notfound echo "not found..." FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment" /v CurrentVersion') DO set CurVer=%%B FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment\%CurVer%" /v JavaHome') DO set JAVA_HOME=%%B set CurVer Set _prog=%JAVA_HOME% set _prog if not exist "%systemdrive%\Program Files (x86)" ( goto x86 ) else ( goto x64 ) :theend
doc_2546
Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. here is my server log error: 127.0.0.1:45292] /var/www/tvvarzesh.dev/public_html/.htaccess: Invalid command 'BEGIN', perhaps misspelled or defined by a module not included in the server configuration what should I do? thanx A: Please follow the below steps: * *Go to Dashboard > Settings > Permalinks *Select a suitable permalink structure and click Save. *WordPress will generate a new .htaccess file code, copy the code. *Create a file named .htaccess in the WordPress root directory and paste the code into it and save.
doc_2547
I need to test to see what color(if any) is under a defined area. Then determine if the font color should be Black or White. I found a great routine Here (on StackOverflow). to help determine what color to use based on a color you send it. I was hoping to see if there was anyway to find that information out using ITextSharp. any help would be great! A: The short answer is no. The color that a human eye would perceive at any specific x,y coordinate falls under the realm of a PDF renderer which iText is not. If I were you I would use Ghostscript to convert the PDF to an image such as a PNG or JPEG and then load that into a System.Drawing.Bitmap object and call GetPixel
doc_2548
Here's an example of my problem: var dialog = { open: function(x){ console.log(JSON.stringify(x)) }, type: { settings: { controller: '', click: false, clas: '' }, foo: function(){ this.settings.controller = 'Foo controller' this.settings.clas = 'Foo class' dialog.open(this.settings) }, bar: function(){ this.settings.click = true dialog.open(this.settings) } } } This is my issue: //A dialog.type.foo(); //B dialog.type.bar(); //C dialog.type.foo(); Why is it that when I run //C, dialog.type.settings is still retaining the value from foo? How can I default back to dialog.type.settings? A: You only have one object to work with, so anything you changed in previous steps are "carried along" until you explicitly change them. To work with a new dialog object each time I would recommend using a function that returns a new instance each time and hide the settings and open properties: function dialog() { var settings = { controller: '', click: false, clas: '' }, open = function(x) { console.log(JSON.stringify(x)); }; return { type: { foo: function() { settings.controller = 'Foo controller'; settings.clas = 'Foo class'; open(settings); }, bar: function() { settings.click = true; open(settings); } } }; } And then: var a = dialog(); a.type.foo(); var b = dialog(); b.type.bar(); var c = dialog(); c.type.foo(); Demo It avoids the issues you would otherwise face with using this in all kinds of contexts, because settings and open are always within the scope of the API that you return from the dialog() function. A: Your "foo" function is explicitly and deliberately changing the values of those "settings" properties. There's just one "settings" object, after all. If you want to revert the values, you'll have to write a function to do that.
doc_2549
I was wondering if it would be possible to launch the main game once the user selects the "Start game" section of the menu. Currently I have two different .py files, one for my game menu and one for the game itself, is there a specific way I can get the menu.py to run the game.py once the "Start game" option is selected? A: First of all, you won't be able to import it unless: A: both programs are in the same directory, or B: the program you are trying to import is in a directory that is part of the PYTHONPATH variable. However, either way, this is not the best way to run an external py file. It sounds like you want it to run ideally as an independent program, not as part of your current one. A program you import really shouldn't run anything upon importing, but should really just define some functions and variables for the main program's use. What you should use to run the program instead is subprocess, which launches a new program as if you had typed it into the command line. Here is an example of code to run an external file. The other advantage of this way method is that the file does not have to be in the programs current working directory, it just has to have the file path of the program. Here is an example of the code: import subprocess filepath = "Documents/game" subprocess.call("python "+filepath) This will execute a new python process. The other thing you could do is put the files in the same directory, and make the code that runs in game contained within a function, so that you can import it and than just call the function when you need it.
doc_2550
and also in just your opinion what is the future of 3d/2d/etc on web. I know for the fact that websites will become like apps. I know that the technology that is eventually going to win is has to be open source otherwise a company could just take on a direction of its own. I also think that gap between 3d graphics and 2d as is used in websites will narrow down. And for this matter flash has the answer(meaning to make something appear you use language A and to just make it 3d you use language B, which is not correct way, as both are graphics.) but it belongs to one company. But all other stuff like webgl, opengl,and unity is too complicated and works on very few places. Mobiles and desktops will have same kind of graphical power, except size...which i am not sure given googles 3d glasses. I so wanna learn flash...but not. It doesnt need to be this way to make a button you use css and html, but to make it 3d without hacking you go learn 1 tons of libraries and whole javascript.
doc_2551
Developer mode and USB debug have been opened in my phone.
doc_2552
but I intend to add the COALESCE statement in the commented out portion to this Script. Would anyone know how to write the Script properly. When I combined them, there was an error. CREATE VIEW [dbo].[VW_Bzo_D] AS WITH today AS (SELECT * FROM [dbo].[Bz_DAYS] WHERE [DATE] = CAST(GETDATE() AS DATE) ), pd AS (SELECT [DATE] AS REPORTING_PERIOD FROM dbo.Bz_DAYS WHERE DAY([DATE]) = 1 ) SELECT sp.*, rp.REPORTING_PERIOD, ac.DATE_ORDINAL AS CUSTOMER_ACCEPTANCE_ORDINAL, mv.DATE_ORDINAL AS CUSTOMER_MOVE_ORDINAL, today.DATE_ORDINAL TODAY_ORDINAL /*sp.[CUSTOMER_MOVE], sp.[CUSTOMER_REQUESTED], sp.[LEASE_SIGNED_BY_GSA], sp.[SUBMITTED_TO_GSA], sp.[CUSTOMER_ACCEPTANCE], COALESCE(sp.[CUSTOMER_MOVE], sp.[CUSTOMER_REQUESTED], sp.[LEASE_SIGNED_BY_GSA], sp.[SUBMITTED_TO_GSA], sp.[CUSTOMER_ACCEPTANCE] ) AS REPORT_MONTH */ FROM dbo.Bzo_Den sp The error is : Column names in each view or function must be unique. Column name 'CUSTOMER_MOVE' in view or function 'VW_Bzo_D' is specified more than once. A: I dont know if this will help but did you try aliasing the column names which is giving you trouble? One of the other users had a similar problem and he tried aliasing. Please look at the link below Create view in sql server "names in each view or function must be unique" Hope it helps.
doc_2553
// Include standard headers #include <stdio.h> #include <stdlib.h> // Include glfw for window handling #include <GLFW/glfw3.h> int SCREEN_WIDTH = 1280; int SCREEN_HEIGHT = 720; GLFWwindow* window; int main() { if(!glfwInit()) { fprintf( stderr, "Failed to initialize GLFW!\n" ); return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Title", NULL, NULL); if( !window ) { fprintf( stderr, "Failed to create window!\n" ); glfwTerminate(); return -1; } glClearColor(0.0f, 0.0f, 1.0f, 0.0f); do { glfwSwapBuffers(window); } while(!glfwGetKey(window, GLFW_KEY_ESCAPE)); glfwTerminate(); return 0; } It compiles fine, but when I run the application it just "freezes", not showing the correct clear color or anything. It just thinks like crazy (that "thinking"-cursor icon in Windows 7 spins and never stops). I'm wondering why it freezes like such, does anyone have an idea? EDIT: Found the solution to my problem. I was learning from a GLFW2 example, but having the newest version (GLFW3) required me to redo the code some; the thing I didn't realize was that the glSwapBuffers(window) call doens't call glfwPollEvents() by itself, giving me the problem I had. A: * *You're not clearing the buffers, hence the clear colour is not showing through. *You're not adding any kind of delay, so you're swapping empty buffers flat out ("thinking like crazy").
doc_2554
ALTER TABLE `table_name` ADD COLUMN `column_name` varchar(128) NULL DEFAULT NULL; This is being run using the mysql command line application. Every time i try to run this it takes hours and then i get the error ERROR 2013 (HY000): Lost connection to MySQL server during query The database is running in a RDS instance on AWS and checking the monitoring statistics neither the memory or disk space is being exhausted. Is there anything else i can try to add this column to the table? A: Check your memory usage or, more probably, your disk usage (is there enough free space during the process?). Altering a table may require either a large amount of memory or a copy on disk of your table. Changing the alter algorithm from INPLACE to COPY can be even faster in your particular case. You may also be hitting the innodb_online_alter_log_max_size limit, although in that case, only the query should fail, not the entire server. It is possible that the crash may be happening due to the ROLLBACK, and not the operation itself, though. Finally, some application configurations or hosting servers cancels a query/http request that is taking too long, I recommend you to execute the same query on the command line client for testing purposes.
doc_2555
I've lost my archives that had that dSYM particularly. Can I do that? I need the dSYM to upload to Crittercism. Thanks in advance. A: Assuming you still have access to the app in iTunes Connect, it's now possible to download the dSYM from iTunes Connect, too. Login, go to My Apps, select your app, then tap on the Activity tab at the top. Tap on the relevant build, and, assuming the app was submitted with symbols in the first place, you should see the option to "Download dSYM." The file you get is called dSYMs (without an extension) but it is in fact a zip file. Add the .zip extension, unzip, and you'll find your dSYM(s) inside. (I needed to do this this week since Crashlytics was complaining about a missing dSYM: https://stackoverflow.com/a/35374388/2397068.) A: Unfortunately, the dSYM is included within the app archive but not within the .ipa file, so it is not possible to get it from downloading the app from the App Store. This is for security reasons too- having the dSYM within the .ipa file would mean anyone could download it, potentially making it easier to hack/crack/reverse engineer your app.
doc_2556
My following Code gives me all current students in alphabetical order, but I only want the first one. for (char letter = 'A'; letter <= 'Z'; letter++) { Console.WriteLine(letter); foreach (var studentName in _students) { if (studentName) { Console.WriteLine(studentName.Lastname + " " + studentName.Firstname); } } } A: You can use Linq to create a sorted enumerable: var sortedStudents = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase); This will sort the students A-Z ignoring diacritics. Then you can simply iterate through it to print all: foreach (var student in sortedStudents) { Console.WriteLine(student.LastName + " " + student.FirstName); } Or just take the first one: var firstStudent = sortedStudents.FirstOrDefault(); // returns the first student or null. And finally, all in one statement: var firstStudent = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase).FirstOrDefault(); A: If you _students is a List<String>, this will return the first one in the sorted list. student1 = _students.sort()[0] If you want to sort by property List<Student> (Sort by FirstName): List<Student> sortedList = _students.OrderBy(s=>s.FirstName).ToList(); Now ypu can get the first one by _sortedList[0]. You don´t need alphabetical loop anymore. This snippet will print all students in alphabetical order: _students = _students.OrderBy(s=>s.FirstName).ToList(); // sorting and saving _students.ForEach(s => Console.WriteLine(s.FirstName + " " + s.LastName)); // printing each element If you want the first Student for each letter you can filter like this: _students.Where(s => searchList.Any(s=>s.StartsWith(letter)))[0]; Write this into your letter-loop and every first one gets returned. Be careful null or Exception can be thrown if there is no result for [0].
doc_2557
My code: while (!file.EndOfStream) { line = file.ReadLine(); bool isComment = (line[0] == '/') && (line[1] == '/'); bool isPoint = (line[0] == '(') && (line[line.Length - 1] == ')'); bool isWhiteSpace = string.IsNullOrEmpty(line); Debug.Log("Comment: " + isComment + ", Point: " + isPoint + ", WhiteSpace: " + isWhiteSpace + "Value: '" + line + "'"); if (!isComment && !isPoint && !isWhiteSpace) { Application.Quit(); } else if (isPoint) { //Strip parenthesis line = line.Remove(line.Length - 1, 1).Remove(0, 1); //break into float array string[] arr = line.Split(','); float xVal = float.Parse(arr[0]); float yVal = float.Parse(arr[1]); float zVal = float.Parse(arr[2]); Vector3 currentVector = new Vector3(xVal, yVal, zVal); results.Add(currentVector); } } You can see that i happen to be doing things with Vector3. If the line is a comment line or a whitespace line, i want it to do nothing. If it notices parentheses, i want it to assume it is a Vector3 and parse it. Finally, if it is a line that is none of these, i want it to stop entirely. Here is a sample text file that i have created just with Notepad: //This is a comment // ... and so is this! (0, -1.5, 3) (1, 4, 1.23) (3, 5, 2) Notice that there is a gap between the second and third Vector3. In this particular case, the line is completely empty, it does not contain spaces or anything, i simply pressed [Enter][Enter] in Notepad. When my script reaches this line, it seems to trigger the file.EndOfStream boolean.... but its NOT the end of the file! How can i fix this? Is there a more appropriate condition for my while loop? I have also tried reading the line in and checking if it is null as the while condition, which is a more popular way to approach this, but this way of doing things also does not work for my case. ** Note: "file" is a variable of type StreamReader ** A: This is more of a style note than an answer, although this also will prevent the issues you were seeing. First, with a StreamReader when you call ReadLine you will only receive a null result when you reach the end of the file. You also don't care about whitespace at the start and end of your lines, and presumably don't care about lines that are entirely whitespace either. So you can use that to test for end of file and empty lines this way: string line; while ((line = file.ReadLine()) != null) { line = line.Trim(); if (line == "") continue; } Next you have some tests for start/end characters that is still going to cause problems in some situations. Specifically, reading the second character in a line that has only one character is going to cause an exception. Instead of using indexing on a string of untested length you can use the StartsWith and EndsWith methods to do your tests: bool isComment = line.StartsWith("//"); bool isPoint = line.StartsWith("(") && line.EndsWith(")"); Finally, in your code that parses the point value you assume that any line that starts with ( and ends with ) will have at least 2 commas in it, and that the text will correctly parse. This is a bad assumption. The better way to handle all of this is to detect and deal with each case as you go, with the parse functionality broken out to a method you can reuse Here's my version: public class Program { public static void Main() { List<Vector3> results = new List<Vector3>(); using (var file = System.IO.File.OpenText(@"C:\temp\test.txt")) { string line; while ((line = file.ReadLine()?.Trim()) != null) { // skip empty lines and comments if (line == string.Empty || line.StartsWith("//")) continue; // parse all other lines as vectors, exit program on error try { Vector3 vector = ParseVector(line); results.Add(vector); } catch (FormatException e) { Console.WriteLine("Parse error on line: {0}", line); throw; } } } foreach (var v in results) Console.WriteLine("({0},{1},{2})", v.X, v.Y, v.Z); } // parse string in format '(x,y,z)', all as floats // throws FormatException on any error public static Vector3 ParseVector(string text) { if (!text.StartsWith("(") || !text.EndsWith(")")) throw new FormatException(); string[] parts = text.Substring(1, text.Length - 1).Split(','); if (parts.Length != 3) throw new FormatException(); float x = float.Parse(parts[0]); float y = float.Parse(parts[1]); float z = float.Parse(parts[2]); return new Vector3(x, y, z); } } If you prefer not to use exceptions you could return null or use the pattern used by the TryParse methods, returning a boolean success/failure indicator and using an out parameter to write the results to. I prefer exceptions in this case. A: David was correct. I was reaching an index out of bounds exception. Below is my corrected and working code: while (!file.EndOfStream) { line = file.ReadLine(); bool isWhiteSpace = false; bool isComment = false; bool isPoint = false; isWhiteSpace = string.IsNullOrEmpty(line); if (!isWhiteSpace) { isComment = (line[0] == '/') && (line[1] == '/'); isPoint = (line[0] == '(') && (line[line.Length - 1] == ')'); } Debug.Log("Comment: " + isComment + ", Point: " + isPoint + ", WhiteSpace: " + isWhiteSpace + "Value: '" + line + "'"); if (!isComment && !isPoint && !isWhiteSpace) { Application.Quit(); } else if (isPoint) { //Strip parenthesis line = line.Remove(line.Length - 1, 1).Remove(0, 1); //break into float array string[] arr = line.Split(','); float xVal = float.Parse(arr[0]); float yVal = float.Parse(arr[1]); float zVal = float.Parse(arr[2]); Vector3 currentVector = new Vector3(xVal, yVal, zVal); results.Add(currentVector); } }
doc_2558
Issue Resolved: Both Webview are different but when I logged in with user 'A' in WKFBView then the same user is automatically logged in WKFBView1.(This issue is resolved using cookies) New Issue: I am facing new issues when I move from WKFBView1 to WKFBView, WKFBView1 cookies are used in WKFBView and user logged in WKFBView1 is automatically logged in WKFBView. So basically last saved cookies are used, but I want to save different cookies for different WKFBView. What I want to achieve: Multiple Webview with different user logged in. Single user means my url link ("https://www.facebook.com/"). @IBOutlet var WKFBView: WKWebView! @IBOutlet var WKFBView1: WKWebView! @IBAction func WebViewUserBtn1(_ sender: Any) { let myBlog = "https://www.facebook.com/login/" let processPool = WKProcessPool() let configuration1 = WKWebViewConfiguration() configuration1.processPool = processPool configuration1.websiteDataStore = WKWebsiteDataStore.nonPersistent() self.WKFBView= WKWebView(frame: self.view.frame, configuration: configuration1) let url = NSURL(string: myBlog) let request = URLRequest(url: url! as URL) WKFBView.navigationDelegate = self WKFBView.customUserAgent = "Safari/603.3.8" WKFBView.load(request) self.fbview.addSubview(WKFBView) } @IBAction func WebViewUserBtn2(_ sender: Any) { let myBlog = "https://www.facebook.com/login/" let processPool = WKProcessPool() let configuration1 = WKWebViewConfiguration() configuration1.processPool = processPool configuration1.websiteDataStore = WKWebsiteDataStore.nonPersistent() self.WKFBView1 = WKWebView(frame: self.view.frame, configuration: configuration1) let url = NSURL(string: myBlog) let request = URLRequest(url: url! as URL) WKFBView1.navigationDelegate = self WKFBView1.customUserAgent = "Safari/603.3.8" WKFBView1.load(request) self.fbview.addSubview(WKFBView1) }
doc_2559
However, in the skeleton code given, it is as such ; PACS initial, set the parallel port start from 00H MOV DX, PACS MOV AX, 0003H ; Peripheral starting address 00H no READY, No Waits OUT DX, AX They have set the PACS register start address to 0 based on the manual. I am not sure why they have done this as this would mean it is connected to PCS0..
doc_2560
A: There is not a template or file that will allow you to change the value of %%GLOBAL_ViewOrderStatusMsg%%. It is something that has been set within the BigCommerce core application and can only be changed by engineers. You can change the variable to a static string/sentence as a workaround.
doc_2561
They are based on the activated route where they fetch the changes in URL and sends the call to the server and get the latest "filterMap " from it. Component_A.html <section class="abc"> <filter [filterMap]=[filterMap]></filter> <div *ngFor="let item of courses"> <!-- code --> </div> </section> Component_A.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'component-a', templateUrl: '../template/component-a.html' }) export class ComponentAComponent implements OnInit, OnDestroy { constructor(private _activatedRoute: ActivatedRoute, private _router: Router) { } ngOnInit() { this._querySubscription = this._activatedRoute.queryParams .subscribe(params => { this.setQueryParams(params); this._courseService.getData() .subscribe(res => { if (res.data) { this.courses = res.data.courseDTOList; this.filterMap = res.data.filterMap; } }); }); } } Component_B.html <div class="xyz"> <span> Filter Result </span> <section class="filter-section" *ngFor='let filter of filterData> <!-- Code --> </section> </div> Component_B.ts import { Component, Input, Output, EventEmitter, OnInit, AfterViewInit } from "@angular/core"; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'filter', templateUrl: '../template/course-filter.html' }) export class FilterComponent implements OnInit{ @Input() filterMap: any; ngOnInit() { if (this.filterMap[0]) this.filterData = this.filterMap[0]; } } Problem: Once the page is reloaded, both the components get initialized and provide the desired output. If URL gets changed, the call to the server is sent and filterMap comes from service but Component_B doesn't get initialized again and the filter screen remains with the old data every time. A: This is the expected behavior, by default, angular reuse components if the parameters of the route change but the route in itself does not. For example with a route like route/:id, if the user navigates from route/1 to route/2, angular will reuse the same component. This is a default behavior that can be overriden by implementing your own RouteReuseStrategy. You can check this to get more informations about this approach. In your case, defining your filterMap inside Component B during change detection instead of on init should be sufficient : @Component({ selector: 'filter', templateUrl: '../template/course-filter.html' }) export class FilterComponent implements OnChanges { @Input() filterMap: any; ngOnChanges() { if (this.filterMap && this.filterMap[0]) this.filterData = this.filterMap[0]; } }
doc_2562
Is there a way to fix Matplotlib default settings to plt.axis("equal") (as what is proposed by matplotlib.rcParams for most of the Matplolib paramaters) ? Thanks, Patrick A: I have created an issue / feature request (8088) for this. As it was pointed out there this rcParams doesn't work for pyplot.plot() yet. Hopefully it will be implemented soon. However, the following works already and is the solution in case of images: import matplotlib.pyplot as plt plt.rcParams['image.aspect'] = 'equal' a=[[1],[2]] plt.imshow(a)
doc_2563
* *20 uppercase alphabetical chars or digits before the space, the number of digits is 6 strictly *6 digits after the space Here is what I've done so far: public static boolean validateCode(String input) { String[] words = input.split("\\s+"); ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(words)); Stream<Character> left = wordList.get(0).chars().mapToObj(ch -> (char)ch); Stream<Character> right = wordList.get(1).chars().mapToObj(ch -> (char)ch); boolean leftIs20 = left .collect(Collectors.counting()).equals(20L); boolean leftisAlfaDigit = left .allMatch(x -> (Character.isDigit(x) || Character.isUpperCase(x))); boolean leftis6Digits = left.filter(x -> Character.isDigit(x)).equals(6L); boolean rightAreDigits = right.allMatch(x ->Character.isDigit(x)); boolean rightAre6Digits = right.collect(Collectors.counting()).equals(6L); return leftIs20 && leftisAlfaDigit && leftis6Digits && rightAreDigits && rightAre6Digits; } But as a stream cannot be reused, it is wrong, but I have no idea how to overcome the issue. A: As others have pointed out it's not necessary to use streams for this but it can be done. If I understood the requirements correctly then this should satisfy what you're after with streams. private static boolean validateCode(String in) { //The task is to check using Stream if such type of string "AZ6BYW59UO6CR8BNT7NM 284130" satisfies these conditions: //20 uppercase alphabetical chars or digits before the space, the number of digits is 6 strictly //6 digits after the space final var input = in.split("\\s"); final var a = input[0]; final var b = input[1]; return a.chars().filter(c -> Character.isDigit(c) || (Character.isAlphabetic(c) && Character.isUpperCase(c))).count() == 20 && b.chars().filter(Character::isDigit).count() == 6; } To test it: System.err.println(validateCode("AZ6BYW59UO6CR8BNT7NM 284130")); //valid System.err.println(validateCode("Z6BYW59UO6CR8BNT7NM 284130")); //less than 20 System.err.println(validateCode("A$6BYW59UO6CR8BNT7NM 284130")); //non alpha numeric System.err.println(validateCode("AZ6BYW59UO6CR8BNT7NM 284k30")); //non-digit in end System.err.println(validateCode("AZ6BYW59UO6CR8BNT7NM 28413")); //less than 6 System.err.println(validateCode("AZ6BYW59UO6CR8BNT7NM 2841302")); //more than 6 EDIT - I missed the fact the first part must have 6 digits private static boolean validateCode(String in) { final var input = in.split("\\s"); final var a = input[0]; final var b = input[1]; final var prefixCounts = a.chars() .mapToObj(c -> Map.entry(Character.isDigit(c) ? 1 : 0, Character.isAlphabetic(c) && Character.isUpperCase(c) ? 1 : 0)) .reduce(Map.entry(0, 0), (lhs, rhs) -> Map.entry(lhs.getKey() + rhs.getKey(), lhs.getValue() + rhs.getValue())); return prefixCounts.getKey() == 6 && prefixCounts.getValue() == 14 && //6 digits and 14 upper case letters = 20 total b.chars().filter(Character::isDigit).count() == 6; } I will caution that using this will work but the stream API is probably overkill. This solution also creates temporary objects during the map-reduce that could be avoided with other solutions. It's not a big deal for many cases but in a performance critical situation this could show up in profiling. You'd have to see how it compares to a regex or other solution in your own tests. This just answers the question using the approach requested. A: All you need is to match patterns so streams is not necessary or really appropriate. But, you can do it with a single stream using a filter String[] data = { "AZ6BYW59UO6CR8BNT7NM 284130", // valid "AZ6BYW59UO6&C8BNT7NM 2841S0", // non letter or digit (&) "MMMMMMMMMMMMMMMMMMMM 823820", // not enough digits "111111MMMMMMMMMMMMMM 228130", // valid "11111111111111111111 228130", // too may digits "AZ6BYW59UO6CR8BT7NM 284130", // first word too short "AZ6BYW59UO6CR8BNT7NM 2824130", // seven digits "AZ6BYW59UO6CRs8BNT7NM 284130", // first word too long "AZ6BYW59UO6CR8BNT7NM 282230" // too many spaces "AZ6BYW59UO6CR8BNT7NM 28230" }; // five digits for (String text : data) { System.out.printf("%30s -> %s%n", text, validateCode(text) ? "Valid" : "Invalid"); } Prints AZ6BYW59UO6CR8BNT7NM 284130 -> Valid AZ6BYW59UO6&C8BNT7NM 2841S0 -> Invalid MMMMMMMMMMMMMMMMMMMM 823820 -> Invalid 111111MMMMMMMMMMMMMM 228130 -> Valid 11111111111111111111 228130 -> Invalid AZ6BYW59UO6CR8BT7NM 284130 -> Invalid AZ6BYW59UO6CR8BNT7NM 2824130 -> Invalid AZ6BYW59UO6CRs8BNT7NM 284130 -> Invalid AZ6BYW59UO6CR8BNT7NM 282230 -> Invalid AZ6BYW59UO6CR8BNT7NM 28230 -> Invalid This splits on a single space and and the tries to match the required contents. If it gets thru, the count will be 1 and true will be returned. Otherwise, 0 and false. * *\\w{20} will match a word of 20 letters and digits. *\\d{6} will match a number of 6 digits. public static boolean validateCode(String text) { return Stream.<String[]>of(text.split("\\s")) .filter(s -> s.length == 2 && s[0].matches("\\w{20}") && s[0].chars() .filter(Character::isDigit) .count() == 6 && s[1].matches("\\d{6}")) .count() == 1; } A: * *Make sure you check the size of the resulting array (i.e. the array obtained by splitting the given string) to avoid ArrayIndexOutOfBoundsException. *Since you have to perform three independent operations on the left side of the substring, you will have to create a stream-supplier to construct a new stream with all intermediate operations already set up. Check this article to learn more about it. Demo: import java.util.function.Supplier; import java.util.stream.Stream; public class Main { public static void main(String[] args) { // Test String[] testStrs = { "AZ6BYW59UO6CR8BNT7NM 284130", "AZ6BYW59UOXCR8BNT7NM 284130", "AZ6BYW59UO6CR8BNT7NM 7284130", "AbZ6BYW59UO6CR8BNT7NM 284130", "AZ6BYW59UO6CR8BNT7NM284130" }; for (String s : testStrs) { System.out.println(s + " => " + validateCode(s)); } } public static boolean validateCode(String input) { int leftAllCount = 20, leftDigCount = 6, rightDigCount = 6; String[] words = input.split("\\s+"); if (words.length >= 2) { Supplier<Stream<Character>> streamSupplierLeft = () -> words[0].chars().mapToObj(ch -> (char) ch); Stream<Character> right = words[1].chars().mapToObj(ch -> (char) ch); return streamSupplierLeft.get().count() == leftAllCount && streamSupplierLeft.get().filter(Character::isDigit).count() == leftDigCount && streamSupplierLeft.get().filter(Character::isUpperCase).count() == (leftAllCount - leftDigCount) && right.filter(Character::isDigit).count() == rightDigCount; } return false; } } Output: AZ6BYW59UO6CR8BNT7NM 284130 => true AZ6BYW59UOXCR8BNT7NM 284130 => false AZ6BYW59UO6CR8BNT7NM 7284130 => false AbZ6BYW59UO6CR8BNT7NM 284130 => false AZ6BYW59UO6CR8BNT7NM284130 => false
doc_2564
<a4j:outputPanel id="listValues"> <a4j:repeat value="#{listBean.values}" var="aValue"> <a4j:outputPanel rendered="#{not empty aValue.value}"> <h:selectBooleanCheckbox id="selectRecordCheck" value="#{listBean.aValueSelectedMap[aValue.value]}"> <a4j:ajax event="valueChange" execute="@this" render="tagsValues, listValues" listener="#{listBean.listenerValueChange}" /> <a4j:param name="id" value="#{aValue.value}" /> <a4j:param name="value" value="#{listBean.aValueSelectedMap[aValue.value]}" /> </h:selectBooleanCheckbox> <h:outputLabel value="#{aValue.label}" /> <br /> </a4j:outputPanel> </a4j:repeat> </a4j:outputPanel> <a4j:outputPanel id="tagsValues"> <table> <a4j:repeat value="#{listBean.listaVirtualEstadoSeleccionados}" var="tag"> <tr> <td><h:outputText styleClass="tags" value="#{tag}" /></td> </tr> </a4j:repeat> </table> </a4j:outputPanel> The problem is that clicking on a checkBox reload the lists of the other groups of checkBoxes (other managedBean properties are called). How can avoid this behavior? Running on a JBoss AS6.1.0, Mojarra 2.0.3, RichFaces 4.3.7 Thx A: Ok, We had the Mojarra 2.0.3-b05 version. I've upgraded to 2.0.11 (i've found something about a bug on the 2.1 in 2011 that could be relationated) and added to the a4j:ajax element the following code immediate="true" limitRender="true" bypassUpdates="true" Maybe adding the attributes would be enough, but i think that upgrading the jsf version is a good idea anyway. PD: I suppose that there is a bug, because I think that it has not sense that behavior.
doc_2565
=INDEX(C:C,AGGREGATE(15,6,ROW($C$1:INDEX(C:C,MATCH("zzz",C:C)))/(ISNUMBER(SEARCH(" " & $C$1:INDEX(C:C,MATCH("zzz",C:C)) & " "," " & A1 & " "))),1)) I'm thinking that I'm getting the error because there are "." in the string. Any help would be appreciated. A: The formula you have doesn't work in that case because of what Scott pointed out in his answer: "The SEARCH will search for matches. The " " & and & " " make sure we are looking for the entire word, So we do not get false positives on things like eric and erica.." You could remove those spaces from his formula, i.e. =INDEX(C:C,AGGREGATE(15,6,ROW($C$1:INDEX(C:C,MATCH("zzz",C:C)))/(ISNUMBER(SEARCH($C$1:INDEX(C:C,MATCH("zzz",C:C)),A1))),1)) to make B5 return what you want - which is not a whole "word" but a part of A5, but as a caveat that might allow for false positives. Row 5 is not the same scenario as 1-4. So take this answer with a grain of salt, depending on your data.
doc_2566
Here's the code that got me worried: window.onload = function(){ var description = document.getElementsByClassName('description'), buttons = document.getElementsByClassName('button'); var currD = 0; // this var stands for the current description that should be shown var show = function(){ for( var i = 0; i < description.length; i++ ){ if( i !== currD ){ description[i].style.display='none'; } else if( i === currD ){ description[i].style.display='block'; } } }; for (var i = 0; i < buttons.length; i++){ buttons[i].addEventListener('click', function(){ currD = i; console.log(i); }); } window.setInterval(show,300); }; Every time I click the button the for loop return the last element. Since I didn't have many buttons on this page I went for the unproficient old way which is: window.onload = function(){ var description = document.getElementsByClassName('description'), buttons = document.getElementsByClassName('button'); var currD = 0; // this var stands for the current description that should be shown var show = function(){ for( var i = 0; i < description.length; i++ ){ if( i !== currD ){ description[i].style.display='none'; } else if( i === currD ){ description[i].style.display='block'; } } }; buttons[0].addEventListener('click', function(){ currD = 0; }); buttons[1].addEventListener('click', function(){ currD = 1; }); buttons[2].addEventListener('click', function(){ currD = 2; }); window.setInterval(show,300); }; This works but if I want to add more buttons it'd be a loss of time setting all the event listeners. A: This is a common CLOSURE issue. This should work: for (var i = 0; i < buttons.length; i++){ (function (_i) { buttons[_i].addEventListener('click', function(){ currD = _i; console.log(_i); }); })(i); } Another solution: for (var i = 0; i < buttons.length; i++){ buttons[i].addEventListener('click', function(){ return function() { currD = i; console.log(i); } }); } You can read more about closure even here: http://www.w3schools.com/js/js_function_closures.asp but there are a lot of other interesting articles. Just google javascript closure For your specific example, maybe even something like this can work: for (var i = 0; i < buttons.length; i++){ buttons[i].addEventListener('click', function(e){ currD = buttons.indexOf( e.currentTarget ); console.log(currD); }); }
doc_2567
Unhandled Exception: System.AggregateException: One or more errors occurred. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: The server name or address could not be resolved However when running locally this does not happen and instead it is able to get the secret without issue. A: Is it Windows container? There is a known issue that it requires a couple seconds to have outbound network for ACI Windows container. The recommendation is to add some retry logic for any outbound requests.
doc_2568
A: Well, it's pretty simple to animate avatar: you'll need a dance animation (those are pretty easy to find, or you could create your own), put it in a prim (which is basic building object in SL), and then create a simple script which first requests permission to animate desired avatar: llRequestPermissions(agent_key, PERMISSION_TRIGGER_ANIMATION); You receive response in run_time_permissions event and trigger your animation by name: run_time_permissions(integer param) { llStartAnimation("my animation"); } Those are the essentials; you'll probably want to request permissions when an avatar touches your object, and stop animation on second touch... or you could request for permissions for each avatar which is in certain range. As for the "bot" part, Second Life viewer code is open source; if you don't want to build it yourself, there are several customizable bots available. Or you could simply run an official SL viewer and leave it on; there is a way to run several instances of SL viewer at the same time. It all depends on what exactly you need it for. Official LSL portal can be found here, though I prefer slightly outdated LSL wiki. A: Slight language mismatch: To make an object perform a dance is currently known as "puppetry" in a SecondLife context. The term "bot" currently means control of an avatar by an external script api. Anyway in one instance, it took me about two hours to write, when I did one for a teddy bear a few weeks back, but that was after learning alot from taking apart some old ones, and i never did finish making the dance, it just waggles the legs or hugs with the arms, but the script is capable for however many steps and parts you can cram in memory. Puppetry of objects has not improved much in the past decade. It is highly restricted by movement update rates and script limitations. Movement is often delayed under server load and the client doesn't always get updates, which produces pauses and skips in varying measure. Scripts have a maximum size of 64k which should be plenty but in actuality runs out fast with the convolutions necessary in lsl. Moving each linked prim in an object seperately used to need a script in each prim, until new fuctions were introduced to apply attributes by linknumber, still many objects use old scripts which may never be updated. Laggy puppets make for a pitiful show, but most users would not know how to identify a good puppetry script. The popular way to start making a puppet script is to find an older open source puppet script online, and update it to work from one script. Some archane versions are given as 'master' and 'slave' scripts which need to be merged placing the slave actions as a function into the master, changing llMessageLinked( ) for the function name. Others use an identical script for each prim. I said popular, not the simplest or easiest, and it will never be the best. Scripting from scratch, the active flow needs to go in a timer event with nothing else in it. Use a different state for animating if a timer is needed when waiting because it's a heavy activity and you don't need any more ifs or buts. The most crucial task is create a loop to build parameters from a list of linknumbers, positions, and rotations into a parameter list before the llSetLinkPrimitiveParamsFast( ). Yes, that's what they called it because it's a heavy list based function, you may just call it SLPPF inworld but not in the script. Because SLPPF requires the call to have certain constants for each parameter, the parameter list for each step will need to include PRIM_LINK_TARGET, linknumber, PRIM_POS, position, PRIM_ROT, rotation for each linked part in the animation step. Here's an example of putting a list of a single puppetry step into SLPPF. list parameters; integer index; while ( index < total ) { // total number of elements in each list parameters += [ PRIM_LINK_TARGET, llList2Integer( currentstep, index ), PRIM_POS, llList2Vector( currentstep, index+1 ), PRIM_ROT, llList2Rotation( currentstep, index+2 ) ]; index += 3; } llSetLinkPrimitiveParamsFast( 0, parameters ); How you create your currentstep list is another matter but the smoothest movement over many linked parts will only be possible if the script isn't moving lists around. So if running the timer at 0.2 seconds isn't any improvement over 0.3, it's because you've told lsl to shovel too many lists. This loop with three list calls may handle about 20 links at 0.1 seconds if the weather's good. That's actually the worst of it over, just be careful of memory if cramming too many step lists into memory at once. Oh and if your object just vanishes completely, it's going to be hanging around near <0,0,0> because a 1 landed in the PRIM_LINK_TARGET hole.
doc_2569
Is there any way to calculate or pull the full height of an ItemsControl element with all Items generated/rendered? Currently if my window renders at 1920x1080 and I've got a ton of items in my ItemsControl - the ItemsControl actualHeight always matches the windows height; I need to be able to determine the full length of all my items and how it compares to the window size. Thanks really appreciate your time and assistance! A: ItemsControls are complicated entities, you see, there is progressive/incremental loading built in to those controls, it is part of a system called Virtualization, and it an extremely widespread across all UI systems, when you scroll down on BinGooglGo image results you get progressive loading for example. Not all items inside the ItemSource are rendered at the same time, instead only what the user sees have a 'physical' form. It is often for example that, A typical UWP ListView will only render the exact amount of items that fit into the current ViewPort (visible area) plus about 10-20 more items south and north of of the viewport in preparation of a scrolling action. Edit: But because i dont like leaving my answers not being solutions, i will showcase the following albeit Anti-Pattern : Wrap your ItemsControl with a Scrollviewer, it will cause an immediate load of all of its contents.
doc_2570
One extension is a WebP decoder. The goal is to decode a WebP image in an IAsyncOperation from C++/Native code directly to an ImageData's data buffer. I believe I'm having some problem with the lambda capture of a handle to an object of type WriteOnlyArray. The C++ part: Windows::Foundation::IAsyncOperation<bool>^ WebPDecoder::DecodeRgbaAsyncInto(const Platform::Array<byte>^ input, Platform::WriteOnlyArray<uint8>^ output, int stride) { return create_async([input, output, stride]() -> bool { auto data = WebPDecodeRGBAInto(input->Data, input->Length, output->Data, output->Length, stride); if (data == nullptr) { return false; } return true; }); } Javascript part: // _this.decoder = Universal.WebP.WebPDecoder(); // function decode(data, height, width, canvas) { return new Promise(function (resolve, reject) { canvas.height = height; canvas.width = width; var context = canvas.getContext('2d'); var imageData = context.createImageData(width, height); var stride = imageData.data.length / height; _this.decoder.decodeRgbaAsyncInto(data, imageData.data, stride).then(function (success) { if (success == false) { reject(Error("Failed to decode WebP Image")); return; } context.putImageData(imageData, 0, 0); context.drawImage(canvas, 0, 0); resolve(); }); }); } With this code I get a crash after the lambda function has been called and is being destroyed. The crash is in __abi_winrt_ptr_dtor(). I am not sure why. If I change to use a reference capture of the WriteOnlyArray as below the decoding works most of the time, but occasionally I get a crash because output seems to change to an invalid pointer. return create_async([input, &output, stride]() -> bool { For this case I'm suspecting it is because the lambda capture does not increase the reference count of the WriteOnlArray object and it is released before/during lambda execution. How can I force the object to be available until the lambda is finished?
doc_2571
We are not even able to add any key-value inside this node.
doc_2572
doc_2573
System Overview: 1) Customer Place new order (Client wait until order being processed by admin client). 2) The order is saved to the DB with ‘status=unknown ‘. 3) Admin is notified through hub about new order. (on a dashboard) 4) Admin accepts or decline new order then Order status is updated in database. 5) Customer is notified about the order, if is accepted or declined through SignalR Problem scenario The business rule that we have to implement is that the order should be automatically declined after 2 minutes if the Admin does not respond. In this case the server should automatically decline the order and the customer should be notified. Solution 1: We thought of adding a timer on the Customer and Admin side, but we prefer the Timer to be somewhere on the server so we don't have to implement the timers on the customer and admin side. Base Hub Controller public abstract class ApiHubController<T> : Controller where T : Hub { private readonly IHubContext _hub; public IHubConnectionContext<dynamic> Clients { get; private set; } public IGroupManager Groups { get; private set; } protected ApiHubController(IConnectionManager signalRConnectionManager) { var _hub = signalRConnectionManager.GetHubContext<T>(); Clients = _hub.Clients; Groups = _hub.Groups; } } public class BaseHubController : ApiHubController<Broadcaster> { public BaseHubController(IConnectionManager signalRConnectionManager) : base(signalRConnectionManager) { } } Server side code (Place Order) public class OrderController : BaseHubController { public async Task SendNotification([FromBody]NotificationDTO notify) { await Clients.Group(notify.AdminId.ToString()).SendNotificationToDashboard(notify); //notifing to admin for about //new order } public async Task NotifyDashboard(NotificationDTO model) { var sendNotification = SendNotification(model);//sending notification to admin dashboard } [HttpPost] [Route("PlaceOrder")] public IActionResult PlaceOrder([FromBody]OrderDTO order)//Coustomer place order { if (!ModelState.IsValid) { return new BadRequestObjectResult(ModelState); } var orderCode = _orderProvider.PlaceOrder(order, ValidationContainer);//save new order in database var notify = order.GetNotificationModel(); notify.OrderId = orderCode; NotifyDashboard(notify); //Other code return new OkObjectResult(new { OrderCode = orderCodeString, OrderId = orderCode }); } }
doc_2574
public class Member { // varibales declaration private String email; private int membershipNumber; private boolean loggedInStatus; /** * Constructor for objects of class Member */ public Member(String memberEmail, int newMembershipNumber ) { // initialise instance variables email = memberEmail; membershipNumber = newMembershipNumber; } //loggedInStatus method public void setloggedInStatus() { if ( email == email && membershipNumber == membershipNumber ) { System.out.println("you are logged in "); } else { System.out.println("you are not logged in"); } } } A: If there hasn't been any input, both variables will contain default values (null for a String, 0 for an integer. You could check that: public void setloggedInStatus() { if (email != null && membershipNumber != 0) { System.out.println("you are logged in "); } else { System.out.println("you are not logged in"); } } But in your case it's not possible to call the constructor without an argument for email and membershipNumber. Both will always have a value, their values just might be null and 0. You have to decide if that makes sense in your case and if an expression like if (email != null && membershipNumber != 0) is enough to check both values for validation.
doc_2575
http_listener listener(U("http://localhost:10000/restdemo")); listener.support(methods::GET, handle_get); listener.support(methods::POST, handle_post); listener.support(methods::PUT, handle_put); listener.support(methods::DEL, handle_del); This works fine when handle_get, handle_post, etc. are simply functions. But as soon as I try to implement this inside a Controller class with handle_get, handle_post, etc. being methods I get errors like: error: no matching function for call to ‘Controller::handle_get()’ error: invalid use of non-static member function ‘void Controller::handle_get(web::http::http_request) I don't see anything in the documentation for why methods wouldn't work. I also perused through the issues and didn't see anything relating to my problem. Is there any obvious reason why listener.support would struggle to find the methods? A: I think you need to bind the methods listener.support(methods::GET, std::bind(&Controller::handle_get, this, std::placeholders::_1)); A: http_listener::support accepts a parameter of type const std::function< void(http_request)> &handler, that means that you can pass any Callable type, so, in order to use a member function, you can use the following: listener.support(methods::GET, [this](web::http::http_request http_request) { // call your member function here or handle your request here }); or listener.support(methods::GET, std::bind(&MyClass::my_handler, this, std::placeholders::_1)); The first example uses a lambda with this captured, the second creates a call wrapper over function MyClasss::my_handler
doc_2576
<div id="buttonpanel" style="display:None; float:left"> <apex:commandButton action="{!selectQuarter}" value="Go!" status="actStatusId2" reRender="pgBlckId,panelrender,panelrender1,panelrender14,panelrender15,panelrender24,panelrender23,panelrender12,panelrender13,panelrender2,panelrender21,panelrender22" id="button2"/> <apex:actionStatus id="actStatusId2" title="This is the status for loading image"> <apex:facet name="start" > <img src="/img/loading.gif" width="25" height="25" align="bottom" title="Loading"/> <h3> Loading..</h3> </apex:facet> </apex:actionStatus> </div> I want to display these two div tags side by side. Please let me know how can I achieve this? A: I do not see two divs....But changing your h3 elements inside the div to have inline display should work as inline elements do not start on a new line. #buttonpanel h3{ display:inline; }
doc_2577
\d+%[^\.][^0-9]*?((?!original).)percentage* And I want it to match from a percentage (i.e. 10%) until the word percentage * *10% "whatever" percentage except if it contains the word "original": * *10% original percentage So, "whatever" can be anything until the word "percentage" except if he word "original" is in it. I've been able to get my regex but it only works correctly if "percentage" is at the beggining of the new line In some cases, 10% of the sales starts with the original percentage --> my regex match with this string but I don't want to because it contains the word "original" The 10% of the sales starts with a certain percentage --> my regex match with this string, it's okay because it doesn't containt the word "original" The 10% of the original percentage of the sale is higher--> my regex doesn't match with this string, and it's okay because it containts the word "original" (maybe because the new line starts with percentage?) The 10% of the original sale is the percentage of that --> my regex match with this string but I don't want to because it contains the word "original" I'm sorry if my explanation is a little weird, English is not my first language. Thanks!!! A: You have to repeat this part ((?!original).) and omit the * after percentage* as it optionally repeats the e char. Then if you don't want to match digits in between, you can match any char except a newline or a digit using [^\d\r\n] instead of the . \d+%[^.](?:(?!original\b)[^\d\r\n])*\bpercentage\b The pattern matches: * *\d+% Match 1+ digits and % *[^.] Match any char except a dot (Note that this is a broad match, you might also use a space instead) *(?: Non capture group * *(?!original\b)[^\d\r\n] Match any char except a digit or newline when wat is directly to the right is not original *)* Close the group and repeat it 0+ times *\bpercentage\b Match percentage Regex demo
doc_2578
$(document).attr('key', 'value'); So far I've looked into * *document - it's not an element so you cannot call setAttribute on it *document.documentElement - returns the html tag. This is not the same "element" that jquery is targeting *$(document)[0] seems to return a shadow element in Chrome Inspector *$(document).attr('key', 'somethingUnique') doesn't exist in the Chrome Inspector Is jQuery creating it's own shadow element mock of the document so it can treat it like a real element? What element is jQuery actually referencing when you do $(document)? A: A jQuery results set is an array like object that in general holds DOMElement, but jQuery does not really care about what type the objects in the result set have. Neither the DOMElements nor any other element that is stored within the jQuery result set is somehow mocked/wrapped, they are directly stored in the result set. jQuery tries to figure out what it has to do to those objects by looking at their available functions. When you call .attr, jQuery checks for each object in the set if it has the function getAttribute if this is the case it assumes that it also has a function setAttribute. If it does not have a function getAttribute, then it will forward the function call to the .prop() function, and prop will internally just do: elem[name] = value So if you pass a plain object to jQuery, then it will just set its property. var a = { } $(a).attr('test', 'hello world'); console.dir(a) // for `a` the property `test` is set <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> If you add a getAttribute and setAttribute function to that object then jQuery will call those: var a = { getAttribute() { }, setAttribute() { console.log('setAttribute was called') } } $(a).attr('test', 'hello world'); console.dir(a); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> However, you should always assume, that the way and order how jQuery does these tests might change. Moreover, only rely on it if it is mentioned explicitly in the documentation. A: I believe you're incorrect about $(document) not referring to document, thus, the answer is (quite simply): document['key'] = 'value' E.g. In Chrome: > $(document)[0] === document true > $(document).attr('blarg', 'narf') n.fn.init [document, context: document] > document.blarg "narf" > document.foo = 'bar' "bar" > document.foo "bar" A: jQuery is just assigning the value to document directly. $(document).attr('test', 'hello world'); console.log(document['test']); // prints "hello world" A: I really thought jQuery would have wrapped DOM elements, since for some reason, I never write var x = $('#x') to reuse it later but recall $. That´s why I wrote: Yes it is wrapped But after reading @t.niese answer here I tried var x = $('#x') var y = $('#y') var ref = x[0] x[0] = y[0] // hack jQuery Object reference to DOM element setTimeout(() => x.html('1'), 1000) // actually writes in #y setTimeout(() => x.html('2'), 2000) // actually writes in #y setTimeout(() => { x.push(ref) }, 2500) // hack jQuery Object reference to DOM element setTimeout(() => x.html('3'), 3000) // actually writes in both #x and #y And understood I don't write var x = $('#x') not because it is a wrapped object, but exactly because it is not a wrapped object. I thought the entry point of the API was $, but I may see the API like var api = $(), and the entry point as (el) => api.push(el) or (sel) => api.push(document.querySelector(sel)) I can $().push but I can not $().forEach nor shift nor unshift but yes delete an index, also In the example setTimeout(() => { x.map((item) => {console.log(item)}) }, 3500) logs 0 and 1, not the elements. Tested using jQuery version 3.3.1
doc_2579
runs smoothly when I run the program manually but when it runs with crontab, the program can't find the astrometry.net path and doesn't work. i do that in terminal: export PATH=$PATH:"/home/desktop/astrometry.net/bin" but didn't work. Does anyone have any suggestions? (Ubuntu)
doc_2580
New in macOS Big Sur 11.0.1, the system ships with a built-in dynamic linker cache of all system-provided libraries. As part of this change, copies of dynamic libraries are no longer present on the filesystem. Code that attempts to check for dynamic library presence by looking for a file at a path or enumerating a directory will fail. Instead, check for library presence by attempting to dlopen() the path, which will correctly check for the library in the cache. I am on M1 macOS Big Sur 11.1, and there is no file at /usr/lib/libssl.dylib : $ ls /usr/lib/libssl.dylib ls: /usr/lib/libssl.dylib: No such file or directory So I assume libssl.dylib is in the linker cache, however this simple program: #include <dlfcn.h> #include <stdio.h> int main() { printf("Calling dlopen()..\n"); void* handle = dlopen("/usr/lib/libssl.dylib", RTLD_NOW ); if (handle == NULL) { fprintf(stderr, "Could not open libssl.dylib: %s\n", dlerror()); return 1; } if (dlclose(handle) != 0) { fprintf(stderr, "Could not close libssl.dylib: %s\n", dlerror()); return 1; } printf("Success!\n"); return 0; } compiled with cc -g -o test_load load.c -ldl crashes: $ ./test_load Calling dlopen().. WARNING: /Users/hakonhaegland/test/test_load is loading libcrypto in an unsafe way [1] 9364 abort ./test_load A: You cannot load the system's libssl because it does not have a stable ABI. If you go in your Console > Crash Reports you'll see an abort log. Invalid dylib load. Clients should not load the unversioned libssl dylib as it does not have a stable ABI.
doc_2581
PROGRAM GENERATES_EIKM IMPLICIT NONE INTEGER I, M, N PARAMETER (M=65, N=3) REAL EIKM(1:M) REAL ALFA, EPSILON, NU, PI REAL U2RMS, KE, KEFISIENSI, KALI, KALE REAL KM(1:M), LS REAL KMLOW, KMHIGH, DELTAKM KMLOW=100 KMHIGH = 10000 DELTAKM = (KMHIGH-KMLOW)/(M-1) PI = 3.14 ALFA = 1.453 EPSILON = 10 NU = 7 LS = 23 KE = ALFA*9*PI/(55*LS) KEFISIENSI = (EPSILON**(1/4))/(NU**(-3/4)) CALL CALLING_THE_VALUE_OF_KM (M) WRITE (*,*) 'CHECKING THE VALUE OF KM AT DATA NUMBER 2 : ', KM(2) DO I=1,M U2RMS = (2/3*KM(I))**2 KALI = KM(I)/KE KALE = KM(I)/KEFISIENSI EIKM(I) = ALFA*(U2RMS/KE)*((KALI**4)/((1+KALI**2)**(17/6)))* & EXP(-2*(KALE**2)) WRITE (*,*) 'THE VALUE OF EIKM AT (I) ', I, EIKM(I) END DO PAUSE END SUBROUTINE CALLING_THE_VALUE_OF_KM (M) REAL KM(1:M) INTEGER I REAL KMLOW, KMHIGH, DELTAKM KMLOW=100 KMHIGH = 10000 DELTAKM = (KMHIGH-KMLOW)/(M-1) WRITE(*,*) 'START OF CALLING_THE_VALUE_OF_KM' DO I=1,M KM(I) = KMLOW + DELTAKM*(I-1) WRITE(*,*) I, KM(I) END DO WRITE(*,*) 'END OF CALLING_THE_VALUE_OF_KM' WRITE(*,*) '--------------------' RETURN END A: I would put IMPLICIT NONE in your subroutine. If M is defined as an integer or not then that would help. You could also put INTENT(IN) on M and see if the compiler also does fortran90. If the subroutine is supposed to output something then you will need that inside the (). You proby want...: F90: Subroutine Callingthevalue_of_KM(M, KM) IMPLICIT NONE INTEGER , INTENT(IN ) :: M REAL, DIMENSION (M), INTENT(INOUT) :: kM If that compiles then it must be force 2.0.9+ And then you probably do not need M Subroutine Callingthevalue_of_KM(KM) IMPLICIT NONE REAL, DIMENSION (:), INTENT(INOUT) :: kM INTEGER :: M M = Size(kM) ... Or do the loops a DO I = 1, SIZE(kM) F77: Subroutine Callingthevalue_of_KM(M, KM) IMPLICIT NONE INTEGER M REAL kM(M) In all those cases km will be "returned" via the reference for km, with updates values on km then known by the main. The other way for kM to be known inside and outside is a COMMON, but I believe it is conceptually easier to shy away from them at this point.
doc_2582
import scala.collection.immutable.Queue import scala.collection.mutable.ListBuffer abstract class Exp[+T:Manifest] { // constants/symbols (atomic) def tp: Manifest[T @uncheckedVariance] = manifest[T] //invariant position! but hey... } case class Sym[+T:Manifest](val id: Int) extends Exp[T] { } abstract class Def[+T] { // operations (composite) override final lazy val hashCode = scala.runtime.ScalaRunTime._hashCode(this.asInstanceOf[Product]) } abstract class Stm case class TP[+T](sym: Sym[T], rhs: Def[T]) extends Stm abstract class Trial{ } class M1() extends Trial{} class M2() extends Trial{} class N1() extends Def[M1]{} class N2() extends Def[M2]{} TP(Sym[M1]{4},new N1()) This gives the following error: scala> TP(Sym[M1]{4},new N1()) java.lang.ClassCastException: class N1 cannot be cast to class scala.Product (N1 is in unnamed module of loader scala.tools.nsc.interpreter.IMain$TranslatingClassLoader @2098d37d; scala.Product is in unnamed module of loader 'bootstrap') at Def.hashCode$lzycompute(:13) at Def.hashCode(:13) at java.base/java.lang.Object.toString(Object.java:246) at java.base/java.lang.String.valueOf(String.java:2951) at java.base/java.lang.StringBuilder.append(StringBuilder.java:168) at scala.collection.IterableOnceOps.addString(IterableOnce.scala:1194) at scala.collection.IterableOnceOps.addString$(IterableOnce.scala:1186) at scala.collection.AbstractIterator.addString(Iterator.scala:1279) at scala.collection.IterableOnceOps.mkString(IterableOnce.scala:1136) at scala.collection.IterableOnceOps.mkString$(IterableOnce.scala:1134) at scala.collection.AbstractIterator.mkString(Iterator.scala:1279) at scala.runtime.ScalaRunTime$._toString(ScalaRunTime.scala:159) at TP.toString(:18) at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:261) at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:266) at scala.runtime.ScalaRunTime$.replStringOf(ScalaRunTime.scala:274) at .lzycompute(:8) ... 28 elided I was expecting an object of type TP[Trial], what happened? Since Sym and Def are covariant types. Am I missing something? Thanks A: At Scastie it isn't reprodusible as https://scastie.scala-lang.org/tCD4HahgTqO4WTnlGcfWqQ but is reprodusible as https://scastie.scala-lang.org/L46PWLF2S5i4d1IGoT6UuQ Locally I can reproduce ClassCastException only if I remove lazy for Def#hashCode. Covariance is irrelevant. In this.asInstanceOf[Product] you're trying to cast Def's this to Product. When you create new N1() it is current Def's this. new N1() as a value of class N1 cannot be cast to Product because N1 doesn't extend Product. In Scala by default classes do not extend Product, case classes do. To fix ClassCastException it's enough to make N1 a case class.
doc_2583
class Blog(models.Model): title = models.CharField(max_length=80, blank=True, null=True) content = models.TextField(blank=True, null=True) pricing_tier = models.ManyToManyField(Pricing, related_name='paid_blogs', verbose_name='Visibility', blank=True) I want to create a notification with post save signal if pricing tier has free-trial slug exists, so I tried as follows def blog_notify_receiver(sender, instance, created, *args, **kwargs): if created and instance.pricing_tier.filter(slug='free-trial').exists(): try: BlogNotification.objects.create() except: pass post_save.connect(blog_notify_receiver, sender=Blog) this doesn't work as it always gives none, the following print shows empty queryset, eventhough the data exists in the pricing tier field if created: print(instance.pricing_tier.all()) How I can check if data exixts in the pricing tier field which is a many to many field of a parent class
doc_2584
What is the best way to do this ? 1) By using BCC ?: $from_addr = '[email protected]'; $mailing_list = '[email protected]', '[email protected]', '[email protected]; $message_subject = 'this is a test'; `$headers = array ("From" => $from_addr, "Bcc" => $mailing_list, "Subject" => $message_subject); $smtp = Mail::factory("smtp", array ('host' => "smtp.example.com", 'auth' => true, 'username' => "xxx", 'password' => "xxx")); $mail = $smtp->send($email, $headers, $message_body);` . 2) by using PEAR mail queue ? A: I haven't used PEAR mail_queue yet, but using a queue is definitively the way to go! BCC shouldn't be used because your mails would easily get flagged as Spam by big email providers like gmail/hotmail. Also having thousands of addresses in an email header seems to be crazy. There may even be a limit. Also some mail servers could refuse your mail because of the over-sized header. On top of that the mail server that is supposed to send your email wouldn't be to happy about it. A: Using built-in mail function is not the best way in the first place for that. I would suggest you to go for SwiftMailer which has HTML support, support for different mime types and SMTP authentication which is less likely to mark your mail as spam. Also, you can check out this pear package: http://pear.php.net/package/Mail_Queue
doc_2585
/filter/ - is my route defined in my extension. Thank you in advance.
doc_2586
My Dockerfile FROM python:3.10-alpine AS python ENV PYTHONUNBUFFERED=true WORKDIR /app FROM python as poetry ENV POETRY_HOME=/opt/poetry ENV POETRY_VIRTUALENVS_IN_PROJECT=true ENV PATH="$POETRY_HOME/bin:$PATH" RUN python -c 'from urllib.request import urlopen; print(urlopen("https://install.python-poetry.org").read().decode())' | python - COPY pyproject.toml poetry.lock ./ RUN poetry install --no-interaction --no-ansi -vvv A: Using your Dockerfile with my project I added a line before the last one as follows: RUN poetry config installer.max-workers 10 RUN poetry install --no-interaction --no-ansi -vvv It worked for me!
doc_2587
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Initialize COM for this thread... CoInitialize(NULL); << Create Excel application >> << Create Workbooks collection >> << Create Workbook >> << Create worksheet >> ... // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } << Release pointers >> CoUninitialize(); return (int) msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { ... switch (message) { << Process message >> } } The problem When the user closes Excel before closing the program, I get an error when I close the program because now the pointers are referencing non-existing app. Is it possible to get a message, indicating that the program is closed. And how should I release the pointers in this case?
doc_2588
The Databrick Workspace URL is not the same in all my environments so I need to parameterize it and include the parameter in the ARM template. I added a global parameter to the Data Factory and ticked "Include in ARM template" but when that was deployed, it removed the ADF's binding to the Git repo. I have also tried it using the ARM Parameter Configuration: I added this section under Microsoft.DataFactory/factories/linkedServices to the ARM template instead of using a global parameter: "AzureDatabricks": { "properties": { "typeProperties": { "domain": "=" } } }, Again it removed the ADF's Git binding when it was deployed. Does anyone know a way to parameterize a field without removing the Git binding? A: After changing the ARM template as described in the question, I deployed and it did remove my Git binding. I added the binding back in and deployed again. Now I have both the Git binding and the parameter I needed.
doc_2589
I've the following mysql statement $username and $password could be anything whatever $query = mysql_query ("SELECT * FROM `settings` WHERE user='$username' AND pass='$password'") i want to say SELECT * FROM `settings` WHERE user='$username' AND pass='$password' or sos=$username and sos=$password so my question is how to use or within select statement like i wanna say user='$username' pass='$password' or sos = both $username and $password Thanks for helping A: You need to use some brackets to make sure you are correctly matching on related username/password pairs: SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') or (sos='$username' and sos='$password') However, you really need to use parameterized queries as the above is subject to SQL injection attack. See here for some examples on how to do this: How can I prevent SQL injection in PHP? A: You could do SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') or (sos='$username' and sos='$password') A: You just need some parenthetical groups. I added single quotes in the second group, where you were initially missing them. SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') OR (sos='$username' AND sos='$password') A: Use parentheses: SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') OR (sos='$username' AND sos='$password') A: I think you need parenthesis SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') or (sos=$username and sos=$password) A: Does it not work exactly like that? I would write WHERE (user = '$username' AND pass = '$password') OR ('$username' = '$password' AND sos = '$username');
doc_2590
gridView.setChoiceMode(ExpandableGridview.CHOICE_MODE_MULTIPLE_MODAL); gridView.setMultiChoiceModeListener(new ExpandableGridview.MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if(checked) { checkedItems.add(position); } else { checkedItems.remove(checkedItems.indexOf(position)); } int checkedCount = gridView.getCheckedItemCount(); mode.setTitle(checkedCount + " selected"); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { Log.i("test", "onCreateActionMode"); MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); menu.findItem(R.id.done).setVisible(false); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { menu.findItem(R.id.done).setVisible(true); return true; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.done: Toast.makeText(MainActivity.this, "sent", Toast.LENGTH_LONG).show(); mode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { checkedItems.removeAll(checkedItems); } }); gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { gridView.setItemChecked(position,!checkedItems.contains(position)); return true; } }); I am trying to pick multiple images to store in some other place. I tried with GridView and ExpandableGridView but onCreateActionMode never called. its callback methods onItemCLick and onItemLongClick are also not working. working fine if i am handling onClick through Adapter class. Please help if i am missing something. A: GridView starts ActionMode by long clicking on one of it's items by default. So, try to remove your custom OnItemLongClickListener and see, if that works.
doc_2591
function weight(w) { Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' small = 'abcdefghijklmnopqrstuvwxyz' spcl = "~!@#$%^&*()_+[]\{}|;':,./<>?" num = '0123456789' var p = [] for(i=0;i<w.length;i++) { if(Cap.contains(w[i])==true) p[i] = Cap.indexOf(w[i]) + 2 else if(small.contains(w[i])==true) p[i] = small.indexOf(w[i]) + 1 else if(num.contains(w[i])) p[i] = num.indexOf(w[i]) else if(spcl.contains(w[i])) p[i] = 1 } return _.reduce(p,function(memo, num){ return memo + num; }, 0); } where w is a string. this properly calculates weight of the string. But whn i try to to calculate weight of strings given in a an array, it jst calculates the weight of the first element, ie. it does not run the full for loop. can anyone explain to me why is that so?? the for loop is as given below function weightList(l) { weigh = [] for(i=0;i<l.length;i++) weigh.push(weight(l[i])); return weigh; } input and output: >>> q = ['abad','rewfd'] ["abad", "rewfd"] >>> weightList(q) [8] whereas the output array should have had 2 entries. [8,56] i do not want to use Jquery. i want to use Vanilla only. A: Because i is a global variable. So when it goes into the function weight it sets the value of i greater than the lenght of l. Use var, it is not optional. for(var i=0;i<l.length;i++) and for(var i=0;i<w.length;i++) You should be using var with the other variables in the function and you should be using semicolons. A: I think your issue is just malformed JavaScript. Keep in mind that JavaScript sucks, and is not as forgiving as some other languages are. Just by adding a few "var" and semicolons, I was able to get it to work with what you had. http://jsfiddle.net/3D5Br/ function weight(w) { var Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', small = 'abcdefghijklmnopqrstuvwxyz', spcl = "~!@#$%^&*()_+[]\{}|;':,./<>?", num = '0123456789', p = []; for(var i=0;i<w.length;i++){ if(Cap.contains(w[i])==true) p[i] = Cap.indexOf(w[i]) + 2 else if(small.contains(w[i])==true) p[i] = small.indexOf(w[i]) + 1 else if(num.contains(w[i])) p[i] = num.indexOf(w[i]) else if(spcl.contains(w[i])) p[i] = 1 } return _.reduce(p,function(memo, num){ return memo + num; }, 0); } function weightList(l) { var weigh = []; for(var i=0;i<l.length;i++) weigh.push(weight(l[i])); return weigh; } q = ['abad','rewfd']; results = weightList(q); Hope that helps
doc_2592
I tries using JTextArea, JTextField and many more, but they always seems to be disabled. I cannot change this behaviour. Do you have any ideas how can I change that?
doc_2593
Is there a way to fix this so that stops happening? add_filter('pre_get_posts', 'query_post_type'); function query_post_type($query) { if( is_category() ) { $post_type = get_query_var('post_type'); if($post_type) $post_type = $post_type; else $post_type = array('nav_menu_item', 'post', 'conditions', 'product-reviews', 'conversations', 'experts', 'custom_fields'); $query->set('post_type', $post_type); return $query; } } A: Was able to fix this by amending my code to the following: function custom_post_type_cat_filter($query) { if ( !is_admin() && $query->is_main_query() ) { if ($query->is_category()) { $query->set( 'post_type', array( 'post', 'conditions', 'product-reviews', 'conversations' ) ); } } } add_action('pre_get_posts','custom_post_type_cat_filter');
doc_2594
The displayed directions all work fine except the b point (end). The b marker displays 781-815 county road 555 but it should display 4011 Kings highway. in the following code, directionsDisplay.setPanel(document.getElementById('directions-panel')); Is there any way to do a replace on 781-815 county road 555 and display the kings highway address. I have Googled everything I can think of but all I can alert is Object Object. Thanks for any help. A: I figured it out. create, directions2Display = new google.maps.DirectionsRenderer(); Then added a Json lib file var string = JSON.stringify(response); var newString = string.replace("Turn", "Drive"); // replace what you need here myDirections = JSON.parse(newString); directions2Display.setDirections(myDirections); directions2Display.setPanel(document.getElementById('directions-panel')); No errors and works a treat. –
doc_2595
Result GUI I am trying to add one string from main class to another gui when you hit the submit button. When the second gui comes up however, it comes up null on my firstname. class 1 main public class SubmitButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e) { first_name = firstText.getText(); last_name = lastText.getText(); firstText.setText(first_name); lastText.setText(last_name); frame.setVisible(false); resultGui gui1 = new resultGui(); gui1.setName(first_name); } } class 2 second gui public JFrame resultFrame; public JLabel first_name_label , last_name_label; private String first_name; public String getName() { return first_name; } public void setName(String name) { this.first_name = name; } A: In your class 1 you use gui1.setName(first_name);, which will invoke public void setName(String name) { this.first_name = name; } in class 2. But the value is not passed to the Label. That method probably should look like public void setName(String name) { this.first_name = name; first_name_label.setText(name); } A: All you need to do is add the second GUI (let's call it a popup) as a component of the first. In the example below, I chose to make the popup an internal frame. Then, all the action listener of the "show popup" button needs to do is grab the text from the text field and set it on the label in the popup. import javax.swing.*; import java.awt.*; public class MyApp { public static void main (String[] args) { SwingUtilities.invokeLater(() -> createAndShowGUI()); } private static void createAndShowGUI () { JFrame frame = new JFrame(); Form form = new Form(); Container pane = frame.getContentPane(); pane.add(form, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); frame.setVisible(true); } private static class Form extends JPanel { private JTextField field = new JTextField(); private Popup popup = new Popup(); JButton btn = new JButton("Show popup"); public Form() { field.setColumns(20); add(field); add(btn); add(popup); btn.addActionListener(e -> { popup.setLabel(field.getText()); popup.setVisible(true); }); } } private static class Popup extends JInternalFrame { private static final String TEXT_PREFIX = "You entered: "; private JLabel label = new JLabel(TEXT_PREFIX); public Popup () { super("Popup", false, true, false, false); add(label); label.setVisible(true); setLocation(0,0); setPreferredSize(new Dimension(200, 100)); } public void setLabel (String text) { label.setText(TEXT_PREFIX + text); } } } I added this code to Replit. You can run it from there. Replit JInternalFrameDemo See the results below:
doc_2596
$imghtml=CHtml::image('images/imageSlider/397498913','Test'); echo CHtml::link($imghtml, $this->createAbsoluteUrl('https://www.facebook.com/')); This does display an image on the website but the link is wrong, when i click on this i go to the following link. http://localhost:63342/France2014/index.php?r=https://www.facebook.com. How do i make it link to just facebook? A: Just use echo CHtml::link($imghtml, 'https://www.facebook.com/'); The method createUrl() always creates an internal Yii link inside your application. A: Try following - $imghtml=CHtml::image('images/imageSlider/397498913','Test'); echo CHtml::link($imghtml, CHtml::normalizeUrl('https://www.facebook.com/')); Hope it will help you.
doc_2597
This is something I know should be fairly simple, but I am having a mind blank today. For example, my table is something like this: CustName: Acct #: FavColor: Mr Johnson 12345 Red Barry Johnson 86749 Dark Red Mike Johnson 90462 Blue Ms Smith 85693 Light Blue The table has multiple variations of the color "Red" in the "FavColor" column. That could be "Light Red", "Dark Red", "Red" etc etc.. I just need to know the total count of Customers who like any shade of "Red". No matter how I write this simple query, the counts are still separating each record into a separate row with a count of '1' each. So if I run the below query: Select CustName, CustAcct, FavColor, count(case when FavColor like '%Red%' then 1 end) AS [Total_Red], count(case when FavColor like '%Blue%' then 1 end) AS [Total_Blue] From CustTable Group by CustName, CustAcct, FavColor I get the following results: CustName: Acct #: | FavColor: [Total_Red] [Total_Blue] Mr Johnson 12345 Red 1 Barry Johnson 86749 Dark Red 1 Mike Johnson 90462 Blue 1 Ms Smith 85693 Light Blue 1 I need the results to show the [Total_Red] column value as '2' since there are two customers who like red. Thank you in advance! Using SQL Server 2012 A: Your issue is the groupings. It is breaking it out by customer. If you want just a total for the color then you can run something like the below query. This will return the total customers who like each color. SELECT SUM(CASE WHEN FavColor LIKE '%Red%' THEN 1 ELSE 0 END) AS 'Total_Red', SUM(CASE WHEN FavColor LIKE '%Blue%' THEN 1 ELSE 0 END) AS 'Total_Blue' FROM CustTable A: ;With cte as ( select sum(case when FavColor like '%Red%' then 1 end) AS [Total_Red], sum(case when FavColor like '%Blue%' then 1 end) AS [Total_Blue], CustName, CustAcct from table t2 group by CustName, CustAcct ) select c.total_red,c.total_blue, t1.CustName, t1.CustAcct, t1.FavColor from cte t1 join table t2 on t1.CustName=t2.CustName t2.CustAcct=t1.CustAcct
doc_2598
The input format json is as follows: [ { "part_number": "12312311", "part_description": "HELIUM FILLING AND GAS CALIBRATION KIT", "quantity": "3", "available_quantity": "0", "ordered_tool_id": "28", "tool_id": "15", "wh_data": [ { "wh_name": "TI02 - (DHL)", "wh_id": "3", "wh_code": "TI02", "wh_qty": 2 }, { "wh_name": "TI03 - (Secunderabad WH)", "wh_id": "4", "wh_code": "TI03", "wh_qty": 1 } ], "tool_order_id": "22" }, { "part_number": "90FG34", "part_description": "LINEARITY PHANTOM KIT", "quantity": "2", "available_quantity": "0", "ordered_tool_id": "29", "tool_id": "17", "wh_data": [ { "wh_name": "TI02 - (DHL)", "wh_id": "3", "wh_code": "TI02", "wh_qty": 1 }, { "wh_name": "TI03 - (Secunderabad WH)", "wh_id": "4", "wh_code": "TI03", "wh_qty": 1 }, { "wh_name": "TI06 - (Bangladesh)", "wh_id": "7", "wh_code": "TI06", "wh_qty": 1 } ], "tool_order_id": "22" } ] I have to convert it into this format: { "sso_id": "123", "tool_order_id": "22", "od_req_qty": { "28": "3", "29": "2" }, "post_od_tool": { "28": "15", "29": "17" }, "post_qty": { "3": { "28": "2", "29": "1" }, "4": { "28": "1", "29": "1" } }, "submit_fe": "1" } I had written code for the conversion as follows: convertLogic(data, ssoid) { var toolOrderId = data[0].tool_order_id; console.log(toolOrderId); var values = '{"sso_id":"' + ssoid + '","tool_order_id":"' + toolOrderId + '","od_req_qty":{},"post_od_tool":{},"post_qty":{},"submit_fe":"1"}'; var jsObj = JSON.parse(values); console.log(jsObj); var warehouseIds = []; data.forEach(element => { var orderToolID = element.ordered_tool_id; var quantity = element.quantity; var toolId = element.tool_id; jsObj.od_req_qty[orderToolID] = quantity; jsObj.post_od_tool[orderToolID] = toolId; var warehouses = element.wh_data; warehouses.forEach(warehouse => { jsObj.post_qty[warehouse.wh_id] = {}; warehouses.forEach(warehouse => { jsObj.post_qty[warehouse.wh_id][orderToolID] = warehouse.wh_qty; }); }); }); } But it is giving this error : core.es5.js:1020 ERROR TypeError: Cannot set property '28' of undefined Can anyone help me and tell me how to do the format conversion. I had wasted my whole day and completely exhausted but able to do the conversion. A: Wherever you are using code like object[propertyName] = someValue, you need to make sure that the object is "defined" before. Otherwise it will consider it as undefined and hence the error. Eg: for this line in your code - jsObj.od_req_qty[orderToolID] = quantity; You need to do something like - jsObj.od_req_qty = jsObj.od_req_qty || {}; jsObj.od_req_qty[orderToolID] = quantity; Similarly for others as well. Check the fiddle here. The error disappears in the console.
doc_2599
Write a PHP class that inherits from PHP's ArrayObject class. Give your new class a public function called displayAsTable() that outputs all the set keys and values as an HTML table. Instantiate an instance of this class, set some keys for the object, and call the object's displayAsTable() function to display your data as an HTML table. my answer is: <?php class View { //definition private $id; private $name; private $email; /* * Constructor */ public function __construct($id, $name, $email) { $this->id = $id; $this->name = $name; $this->email = $email; } /* * get ID */ public function getId() { return $this->id; } /* * get Name */ public function getName() { return $this->name; } /* * get Email */ public function getEmail() { return $this->email; } } // New View List Class which extends arrayObject in PHP class ViewList extends ArrayObject { /* * a public function to return data */ public function displayAsTable() // or you could even override the __toString if you want. { $sOutput = '<table border="1"><tbody>'; foreach ($this AS $user) { $sOutput .= sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>', $user->getId(), $user->getName(), $user->getEmail() ); } $sOutput .= print '</tbody></table>'; return $sOutput; } /* * return data to string */ public function __toString() { return $this->displayAsTable(); } } /* * data(s) */ $data = new ViewList(); $data[] = new View(1, 'Selim Reza', '[email protected]'); $data[] = new View(2, 'Half Way', '[email protected]'); /* * final output */ print $data; BUT I think I am missing something in 2D and 3D array(s) for print. Please help me out how can I print 2D and 3D in html format (in table). Thanks in Advance. A: Here is the simplest solution - <?php class InheritArrayObject extends ArrayObject { // inherits function from parent class public function __set($name, $val) { $this[$name] = $val; } public function displayAsTable() { $table = '<table>'; $table .= '<tbody>'; $all_data = (array) $this; foreach ($all_data as $key => $value) { $table .= '<tr>'; $table .= '<td>' . $key . '</td>'; $table .= '<th>' . $value . '</th>'; $table .= '</tr>'; } $table .= '</tbody>'; $table .= '</table>'; return $table; } } $obj = new InheritArrayObject(); $obj->Name = 'John Doe'; $obj->Gender = 'Male'; $obj->Religion = 'Islam'; $obj->Prepared_For = 'ABC Org'; echo $obj->displayAsTable(); ?>