text
stringlengths
70
452k
dataset
stringclasses
2 values
Error in using tidyverse function pivot_wider [enter image description here][1]Dear all, I have a very large file (14,566,680 records) with 2 variables (ID and A). The first variable (ID) is the individual (n=258) and each individual has 56,460 records (A) I would like to write out a "transpose" file (i.e. 258 lines & 54460 columns). When I execute the following code: system.time(snp1 %>% #filter(`Sample ID`=='8362974') %>% select(`Sample ID`,A) %>% mutate(id = row_number()) %>% #head(n=nsnp) %>% pivot_wider(names_from=id, values_from = A)->T) I got the following error: Error in rep_len(NA_integer_, n) : invalid 'length.out' value In addition: Warning message: In nrow * ncol : NAs produced by integer overflow Timing stopped at: 28.73 0.62 29.36 If I use only 1 ID it works correctly Best Stefano Looks like the output is too long. Weird You inserted a tag for an image but forgot the url for it Took another look, Your function call is wrong, You will have a column in the output for each id meaning you get a huge matrix, makes sense it doesn't work Can you make this reproducible? Without any data we can't run your code, and it's unclear what's going wrong since we can't see either what you're starting with or what you're trying to get Does it work if you group the records by individual before calculating the row_number (record ID)? # made up sample df <- tibble(`Sample ID` = rep(1:258, each = 56460)) %>% mutate(A = rnorm(nrow(.))) df %>% group_by(`Sample ID`) %>% mutate(id = row_number()) %>% pivot_wider(names_from=id, values_from = A) # A tibble: 258 x 56,461 # Groups: Sample ID [258] `Sample ID` `1` `2` `3` `4` `5` `6` `7` <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 1.49 0.546 0.0517 -0.480 -0.500 0.266 -1.52 2 2 -0.391 -0.855 -1.28 -0.0277 -0.999 0.617 -0.415 3 3 0.200 0.484 1.08 -0.568 1.16 1.75 -0.143 4 4 0.212 0.371 0.674 0.0481 -1.09 -1.07 0.160 5 5 0.409 1.54 0.931 -0.280 1.27 0.0447 0.426 6 6 -0.936 0.903 -0.0408 0.590 -1.52 -1.14 -0.600 7 7 -1.97 0.336 -0.233 0.488 0.995 -0.933 -1.90 8 8 -0.396 2.12 1.10 0.304 0.290 0.595 -1.32 9 9 -1.31 -0.124 -0.804 -0.447 1.12 -0.721 0.378 10 10 0.977 0.818 1.51 -0.258 -0.00794 0.0386 2.03 # ... with 248 more rows, and 56,453 more variables: ...
common-pile/stackexchange_filtered
Django uploaded file permissions How to add permissions to uploaded file? E.g class Car(models.Model): name = models.CharField(max_length=255) photo = models.ImageField(upload_to='cars') owner = models.ForeigKey(AuthUser) And each logged user can add te images. E.g. User1 added image a.jpg. And can access it by adresserver.com/cars/a.jpg but anyone can access it too. How add permissions to only owner can see the image? I think no need to add permission as the loged user records saves with uploading image.So that you can filter your or loged user images with their current user object from request (request.user). You can instruct the view that serves the image to only show the image if the logged in user is the owner: photo_to_show = get_object_or_404(Car, owner=request.user, photo=photo)
common-pile/stackexchange_filtered
How to uglify only changed file with Grunt.js watch task if dynamic expansion in Uglify has been enabled? I have following config in my Gruntfile.js: Problem is, that when some file is changed, 'uglify' task is performing as usual for all files. What I am doing wrong? module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON('package.json'), watch: { scripts: { files: ['js/**/*.js'], tasks: ['uglify'] } }, uglify : { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n', sourceMapRoot: 'www/js/sourcemap/' }, build: { files: [ { expand: true, cwd: 'js/', src: ['**/*.js', '!**/unused/**'], dest: 'www/js/', ext: '.js' } ] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.event.on('watch', function(action, filepath) { grunt.config(['uglify', 'build', 'src'], filepath); }); grunt.registerTask('default', ['uglify', 'watch']); }; By default the watch task will spawn task runs. Thus they are in a different process context so setting the config on the watch event wont work. You'll need to enable nospawn to not spawn task runs and stay within the same context: watch: { options: { nospawn: true }, scripts: { files: ['js/**/*.js'], tasks: ['uglify'] } }, You were almost there. Your "onWatch" function should look something like this : grunt.event.on('watch', function(action, filepath, target) { grunt.config('uglify.build.files.src', new Array(filepath) ); // eventually you might want to change your destination file name var destFilePath = filepath.replace(/(.+)\.js$/, 'js-min/$1.js'); grunt.config('uglify.build.files.dest', destFilePath); }); Note nospawn:true in your wacth task options is mandatory too.
common-pile/stackexchange_filtered
Problems with multiples private sites in Liferay 6.2 I need to create 2 private sites in Liferay 6.2. I have already created one of them, that has been built as the private side of the portal (site 1). I have created the another private site (site 2). The problem I am facing is that I cannot log in and go straight to the new site (site 2). Instead of that I always get logged in in the private side (site 1), as well as the new private site (site 2). In other words, when I log in I can see both private sites, and I cannot not remove the first private site (private side of the portal). This woudl be the site structure: Liferay Portal |- Private site 1 (private side of the portal, strikethrough eye icon) |- Private site 2 I guess I am not working properly with private sites. Maybe site 1 needs to be something different from the "private side" of the portal? Do I need to move content from site 1 to another site and leave site 1 empty? Thanks!!! In Liferay you cant log in only to one site, you are being logged to the portal instance that contains sites. You have to create new instance in control panel in order to achieve two independent sites. Maybe my mistake is to use the private pages of the portal as a site?. So when you log in in the portal, you will see the private pages and sites you can see. What I need is to loging in the portal and see the sites you can see and hide the private pages of the portal. Is it possible or should I move the private pages content to a new site? Maybe solution to your problem would be site membership. You can create sites and restric access to them to certain users.
common-pile/stackexchange_filtered
Battery suddenly not charging anymore I have a relatively new ASUS F451MA. I had already updated the BIOS to the latest version before the problem appeared. I have opened up my laptop and tried to reset the battery by taking it out and putting it back again, to no avail. Then I removed 14.04 and did a fully new install of 15.04, but the stats are still the same: native-path: BAT0 vendor: ASUSTeK power supply: yes updated: za 25 jul 2015 14:27:06 CEST (96 seconds ago) has history: yes has statistics: yes battery present: yes rechargeable: yes state: charging warning-level: none energy: 0 Wh energy-empty: 0 Wh energy-full: 18,236 Wh energy-full-design: 32,625 Wh energy-rate: 0 W voltage: 11,25 V percentage: 0% capacity: 55,8958% technology: lithium-ion icon-name: 'battery-caution-charging-symbolic' Before trying to reset the battery and reinstalling Ubuntu I had tried lots of different possible solutions that I had found on this forum, but nothing worked, hence this post. Can you verify that your problem is not caused by a hardware fault? I guess not, although my gut feeling is that it's not a hardware problem, because it happened so suddenly. I also don't have a way of checking; I don't know anyone with a laptop with the same type of battery. Or is there another way? also because it is very similar to this case: https://askubuntu.com/questions/409603/battery-issue-in-asus-with-ubuntu-12-04?rq=1 Just a thought: the battery charge settings usually are stored in the BIOS, and since you updated your BIOS it is possible that the settings maybe got overwritten (BIOS chips aren't the smartest things). Sadly currently there doesn't seem to exist any Linux/Ubuntu tool that can manipulate that sort of information (unlike on Windows), which is kinda disappointing. Still, could you go poking around in your BIOS? You should look for something named "Power Management" or "Battery Optimizer" or "Battery Saver" or something similar as the exact location and name changes from BIOS to BIOS and I'm unable to find a manual for your BIOS. There should be a setting that controls the maximum allowed battery charge as a percentage - maybe it somehow got set to a horrible default 0% when you updated. I wanted to post this as a comment, but ran out of space. :/
common-pile/stackexchange_filtered
bash_profile function to git grep and replace I wanted to create a function in my ~/.bash_profile that would git grep and list the files that contains a string and then replace all occurrences of that string with another function git-replace() { eval git grep -l ${1} | xargs sed -i '' -e 's/${1}/${2}/g' ; } However, if I run the function git-replace "Type1" "Type2" , nothing happens. What am I doing wrong here ? There's 2 issues: don't use the evil eval if you want to expand a variable, don't use single quotes but double quotes, so: git-replace() { git grep -l "$1" | xargs sed -i '' -e "s/$1/$2/g" } And no need the function statement in modern shell. Learn how to quote properly in shell, it's very important : "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes http://mywiki.wooledge.org/Arguments http://wiki.bash-hackers.org/syntax/words
common-pile/stackexchange_filtered
Trying to run template multiple times depending on dynamic variable array in the pipeline I am trying to find the git difference from the previous commit in one of folders in my repo and trying to loop different folder names. At the end I need to call template . To simplify the question, I have not mentioned that here. When I try to split the array at the each statement , it is NOT working as expected . can some one help me over this Below is the pipeline . jobs: - job: 'First_Job_Name' continueOnError: false steps: - checkout: self fetchDepth: 0 - task: PowerShell@2 name : myvar inputs: targetType: 'inline' script: | $gitDiff=git diff-tree -r --no-commit-id --name-only HEAD | Select-String -Pattern "pro" $specificContent = $gitDiff -split '\r?\n' $secondElements = @() foreach ($filePath in $specificContent) { $splitPath = $filePath -split '/' if ($splitPath.Length -gt 1) { $secondElement = $splitPath[1] $secondElements += $secondElement Write-Host "Second Element: $secondElement" } } Write-Host "Second Elements: $($secondElements -join ',')" echo "##vso[task.setvariable variable=MY_VAR;isOutput=true]$($secondElements -join ',')" - job: 'Second_Job_Name' dependsOn: 'First_Job_Name' variables: # Define MY_VAR to be get its value from the first job's variable MY_VAR: $[ dependencies.First_Job_Name.outputs['myvar.MY_VAR'] ] continueOnError: false steps: - task: Bash@3 displayName: Using var passed from first job inputs: targetType: 'inline' script: | echo $(MY_VAR) failOnStderr: false - ${{ each env in split('$(MY_VAR)', ',')}}: - task: PowerShell@2 displayName: 'Test' inputs: targetType: 'inline' script: | Write-Host '============================================================================================' Write-Host 'element: '${{env}} Write-Host '============================================================================================'
common-pile/stackexchange_filtered
How to get all elements in a selection from javascript I'm using window.getSelection() to get the highlighted selection in a contenteditable div. I can get the range of nodes with selection.getRangeAt(0). But now I'm stuck. How can I get the node/elements to do something with them, like add a class to each element in the range? I can do something like this, range.cloneContents().querySelectorAll('*').forEach(e => console.log(e)); to see what the would be but they are cloned, so doing anything with the elements does nothing in the actual document. So, I've got my selection, but how to I get a list of nodes/elements in the selection?
common-pile/stackexchange_filtered
I've a problem trying to create users with roles I'm using simpletest_clone to do my tests. what i want now is just to create an user for every existing role i've created (I dont need just the list of permissions, i need the user to have the exact role i want) public function testProbando(){ foreach(user_roles() as $clave => $rol){ $this->privilegedUser=$this->drupalCreateUser(array()); $this->privilegedUser->roles = array($clave => $rol); user_save($this->privilegedUser); $this->drupalLogin($this->privilegedUser); $this->drupalLogout(); } } but in the verbose it simply doesn't log in and i can't get any clue what to do How many roles are defined in your test before you try to create users? Tests set up a new skeleton of a site and it won't have the roles that your current site has unless they're defined in the test. mmmmmm from 20 to 30, im not sure, anyway... i'm using simpletest_clone so , at least i get all the roles i had i my site using user_roles() I'm not sure what "from 20 to 30" means for which roles are created. Try $this->debug(user_roles()) to see what roles exist in your test. Just a note, but you might want to consider using user_roles(TRUE) to exclude the anonymous user.
common-pile/stackexchange_filtered
how to pass commas when entering in textfield We are developing a Worklight Hybrid mobile application using Jquery mobile. I want to pass commas when entering digits in a number text field. Text field maxlength 9. I want the control to show values like this 5,652,895. Please can anyone tell me where I am missing the logic? $(document).on('keyup', '.value', function() { if(event.which >= 37 && event.which <= 40) return; $(this).val(function(index, value) { return value .replace(/\D/g, "") .replace(/\B(?=(\d{3})+(?!\d))/g, ",") ; }); }); <input onKeyDown="if(this.value.length==9 && event.keyCode != 8)return false;" id="txtVehicleValue" placeholder="Vehicle Value" name="vehicleValue" class="value"> try this https://jsfiddle.net/1kfsx6rp/15/ thanks Poria, but i want to dynamically pass the commas. If you are using html5 control like type="number" then use pattern otherwise use jquery/javascript format onmouseout event. try maskMoney: http://www.jqueryscript.net/demo/jQuery-Currency-Input-Filed-Mask-Plugin-maskmoney/ Solution for this Question $(document).on('keyup', '.number', function() { if(event.which >= 37 && event.which <= 40) return; $(this).val(function(index, value) { return value .replace(/\D/g, "") .replace(/\B(?=(\d{3})+(?!\d))/g, ",") ; }); }); <div class="qic-form-group showError"> <input onKeyDown="if(this.value.length==9 && event.keyCode != 8)return false;" class="clearTxtFld number" placeholder="Vehicle Value" name="vehicleValue"> </div> Try this: <input class="number" onkeyup="addComma(this);"> Jquery: function addComma(obj) { $(obj).val(function(index, value) { return value .replace(/\D/g, "") .replace(/\B(?=(\d{3})+(?!\d))/g, ","); }); } thanks Jayesh.it's working in js fiddile but it's not working in mobile application hmm yes.After .keyup function i write alert but it's not comming updated code with function..try that..i hope it will work Yes i try, when i entering fourth digit it's automatically araising jayesh,$(document).on('keyup', '.number', function() i wrote this code after this line i am getting alert. and i am entering the number when i entering fourth digit it's automatically araising. keyup it's working but commas not comming Thanks so much for the helping Jayesh, i removed type="number" in input tag it's working. jayesh, after entering total value i need to add dynamically decimal like 5,652,895.000
common-pile/stackexchange_filtered
Comment a PHP line containing # / character How do I comment out the below line of PHP code $html = preg_replace('#(<br */?>\s*)+#i', '<br />', $html); Although the line can be disabled by something like if (0==1) $html = preg_replace('#(<br */?>\s*)+#i', '<br />', $html); But still this is not a comment. I think the ?> is the issue as it thinks it's the end of the PHP code. If you want to get it working till a proper answer comes, change the regex to '#(<br */?\>\s*)+#i' - think the \> fools it. Best I could come up with is stripping your regex pattern into it's own variable, then splitting this string using '.'. I was inspired by the following answer, which also suggests redoing the regex, but not sure if that is an option. Source: https://stackoverflow.com/a/12498301/3324415 Sample: /* $pattern = "'#(<br *" . "/?>\s*)+#i'"; $html = preg_replace($pattern, '<br />', $html); */ I think you are missing some quotes in your regex. The problem is that ?> what @Nigel Ren mentioned in the comment. The /? Pattern can be omitted because * this make it. //$html = preg_replace('#(<br *>\s*)+#i', '<br />', $html); The problem also occurs when strings like $string = "?>xxxx"; should be commented out. In this case ? can to be replaced by \x3f (Note: In double quotes ! ). $string = "\x3f>xxxx"; This is the same string for PHP, but is not an PHP end tag.
common-pile/stackexchange_filtered
How to stop one process and go to next process in shell script? I have a script to download consecutive satellite and radar images as they come online, later combine them into satellite image animation and radar image animation. I created two separate scripts to download images from satellite and radar. I run these from the shell script same time. python ./rad/rad_retrieval.py; python ./sat/sat_retrieval.py Satellite and radar images updated online every 30 min, so these 2 python scripts will download images every 30 min until we stop the process. Part 2, has the code to combine each satellite and radar image into animation/movie with ImageMagick. # Part 1 echo starting... python ./rad/rad_retrieval.py; python ./sat/sat_retrieval.py # Part 2 #combining downloaded satellite images into video cd /home/Cast/sat_retrieved echo saving video for satellite images convert -delay 50 20210516-*.jpg Satellite_retrieved.mp4 echo saving video : Success #combining downloaded radar images into video cp Satellite_retrieved.mp4 /home/Cast/ cd /home/Cast/Radar_retrieved/ echo saving video for radar convert -delay 50 20210516-*.gif Radar_retrieved.mp4 echo saving video : Success This is my script, I want to stop part 1 after a while with user input and go to part 2 without stopping the entire shell script. How to do that? You can ignore SIGTERM and set a handler for SIGINT to kill children upon its arrival in the parent shell. This way the user can simply hit Ctrl-C and skip the first part. # first part python ./rad/rad_retrieval.py & python ./sat/sat_retrieval.py & trap '' term trap 'kill 0' int wait trap - term int # second part
common-pile/stackexchange_filtered
Need suggestions on Javascript for image rollover with text change in <div> I'm trying to write a javascript that will do two things. First when you roll over a thumbnail of a picture it loads the larger view in a div container. That part works. But the other thing is that there is a description that goes with each picture that needs to load in a different div container. So far I get the one description loaded and then it gets stuck and the next won't load. I think I just need a little push with the type of objects and methods and such to use. I'm obviously not an experienced javascripter. Thanks in advance for any suggestions you can offer Sue B. Perfect case for jQuery... Try this... http://jsfiddle.net/jchandra/dY8Dp/ Basically I'm adding a data- attribute to store the real pic URL and reusing the title tag for the description. If you insist on pure JavaScript, it's a bit ugly, but ... here it is... http://jsfiddle.net/jchandra/aDe3u/
common-pile/stackexchange_filtered
I'm not getting loops to take a new value after each loop? I'm trying to solve a problem where I try to get my loop to take a new value after every loop. The program is suppose to fine me my Interest payment,principal payment an current balance, doing so my interest is suppose to be less an lesser every time I loop but its only looping the first answer over an over Here is the output which the first answer is correct but the other three is Enter Loan Amount:500 Enter Annual Interest:50 Total payment:4 Enter Loan Length :1 Interest PaymentPrincipal PaymentCurrent Balance Interest Payment Principal Payment Current Balance 62.5 62.5 62.5 62.5 It supposed to be 12.5% of the balance after the first payment. public static void main(String[] args) { Scanner input = new Scanner(System.in); //variabled decleared double rate; double payment; int amt = 1; //input System.out.print("Enter Loan Amount:"); double principal = input.nextDouble(); System.out.print("Enter Annual Interest:"); double interest = input.nextDouble(); System.out.print("Total payment:");//12=monthly,4= quartely,2=semi-annually and 1=annually double period = input.nextDouble(); System.out.print("Enter Loan Length :"); int length = input.nextInt(); //proces rate = interest / 100; double period_rate = rate / period; double n = period * length; payment = (principal*Math.pow((1+period_rate),n))/n; System.out.printf("\n"+"Interest Payment"+" Principal Payment "+" Current Balance "); for(int i=1; i<=n; i++){ double principal_payment=0; double current_balance; double payment_interest; current_balance=(principal-principal_payment); payment_interest=(principal*period_rate); principal_payment=(payment-payment_interest); principal=current_balance; System.out.println(payment_interest+""); } You don't have anything that's changing inside your loop. You'll get the same result every time. any assistance will do am new to programming thanks What is principal here? Where is it declared? You're calculating "current_balance", but it's a local inside the loop (declared inside the loop) and its value is not used anywhere. What you basically need to do is to update "principal" inside the loop. i have just edited it am suppose to find the interest for each payment after each loop Forget about programming. Get pencil and paper and work through the calculations for several months. Then transfer those calculations to code. You get ahead of yourself when you start coding before you understand what the problem is. i know my calculations well because i do use pen an paper since am new am not good with loops an am stuck on that area Go back to the pen and paper and look at what you do. Give a name to each value you calculate. Note where you "loop" in the paper calculation, and which values you carry over from one iteration to the next. There's nothing special about loops -- it's not a magical formula. You just do what you'd do on paper. You are giving the same value, to all the iterations of the for. Thats why you are getting always the same output. If you want new value each time, either you prompt to the user to give you new input for each iteration. Or you do this before the for, store the input in arrays and work on them inside the loop. Something like this pseudo code: for(i = 0; i < N; i++) { //read principal from user input //read payment from user input // ect... payment_interest=(principal*period_rate); ... } You can see here how to Read a Double From the Keyboard. Note that inside the loop you only need to ask the user for parameters that can vary. Try change the line: principal=current_balance; to: principal = principal - principal_payment; or change the loop to this: double current_balance = principal; for (int i = 1; i <= n; i++) { double principal_payment = 0; double payment_interest; //current_balance = (principal - principal_payment); payment_interest = (current_balance * period_rate); principal_payment = (payment - payment_interest); current_balance = current_balance - principal_payment; System.out.println(payment_interest + ""); } really, worked for me with your code: Enter Loan Amount:500 Enter Annual Interest:50 Total payment:4 Enter Loan Length :1 Interest Payment Principal Payment Current Balance 62.5 45.284271240234375 25.916576385498047 4.127919673919678 one question though how do you get it to .2f
common-pile/stackexchange_filtered
Scope for containers in C++ Let's say I have something like the following piece of code: int main() { vector< vector<int> > vecs; int n_vecs; cin >> n_vecs; for (int i = 0; i < n_vecs; i++) { int n_nums; cin >> n_nums; vector<int> tmp; for (int j = 0; i < n_nums; i++) { int num; cin >> num; tmp.push_back(num); } vecs.push_back(tmp); } } which populates a vector of vector<int>s gradually. From some testcases, I understand that after the for loops finish, the vector is constructed as expected. However, I can't understand why is that: shouldn't the tmp vector be out of scope after the outer for loop finishes? Does a copy of it get inserted into the vecs vector? (The same applies for maps) Yes, a copy of tmp is push_backed. And to be more precise, tmp is constructed and destroyed for every iteration. Yes, a copy is made. See documentation for push_back: The new element is initialized as a copy of value There are two overloads for the function. In your example, the void push_back( const T& value ) overload is chosen because you are passing a named object and have not applied std::move, hence the copy. If you passed an unnamed object or applied std::move, then the other overload would be chosen, "stealing" the contents of tmp to initialise the new object at the end of the vecs vector. But that doesn't even matter for your question. In either case, the fact that tmp's lifetime ends afterwards (because of its scope in the source code) is irrelevant. The vecs vector already contains and owns a new element, and what happens to tmp is none of its concerns. Perhaps the most important thing to keep in mind is that C++ standard containers are designed so that you can use them as easily as plain ints. You can copy them, return them, pass them around and assign them, and the results will always be as expected. This is because C++ standard containers own their contents. There is a lot of downvoting going on for this question. What's wrong? Does a copy of it get inserted into the vecs vector? Yes.
common-pile/stackexchange_filtered
Show that $\sum ^{\infty}_{n=1} e^{-n} \sin nz$ is analytic in the region Show that $\sum ^{\infty}_{n=1} e^{-n} \sin nz$ is analytic in the region $A=\{z|-1<Im \;z<1\}$ Idea: Let $D$ be a closed disk in $A$, let $\delta$ be its distance from the boundary $Im \;z = \pm1$ take $z=x+iy \in D$ i have to show that $| e^{-n} \sin nz| \le e^{-n\delta}$ ..how to this prove Recall that the uniform limit of analytic functions is analytic. As the finite sum of analytic functions, each partial sum is analytic. So, you need to show uniform convergence, which is perhaps what you were doing. Computing the modulus of the summand, $$ \left| e^{-n}\frac{e^{niz}-e^{-niz}}{2i} \right|\leq e^{-n}|e^{niz}| $$ now write $z=x+iy$, and you find $$ e^{-n}|e^{nix-ny}|=e^{-n}e^{-ny} $$ now as long as we can get some separation from the left hand point of the strip, i.e. if we can take $$ -1+\delta<\Im(z) $$ for some $\delta>0$, then the series converges uniformly by the Weirstrass M test and since $$ e^{-n}e^{-ny}\leq e^{-n}e^{-n(-1+\delta)}=e^{-n\delta} $$ which is summable.
common-pile/stackexchange_filtered
How do I declare 'sub-objects' in PHP I'm relatively new to OOP in PHP, and I'm not sure if what I'm trying to do is possible or recommended. In any case, I can't figure it out. Are there any tutorials or documentation which might help? I have a system in which each user has a number of 'Libraries'. Each Library contains a number of 'Elements'. DB set up is as follows: user_libraries - id (unique) - user_id (identifies user) - name (just a string) elements - id (unique) - content (a string) library_elements - id (unique) - library_id - element_id where library_id is the id from user_libraries, and element_id is that from elements. I want to be able to access a given user's library, and their elements. I've set up the library class, and can use it to retrieve the list of libraries (or a sub-list). I do this like this: $mylibraryset = new LibrarySet(); $mylibraryset->getMyLibraries(); which gives (when I use print_r): LibrarySetObject ( [user_id] => 105 [data_array] => Array ( [0] => Array ( [id] => 1 [user_id] => 105 [type] => 1 [name] => My Text Library ) [1] => Array ( [id] => 2 [user_id] => 105 [type] => 2 [name] => Quotes ) ) ) Now, what I'd like to be able to do is for each of those libraries (the elements in data_array), to retrieve all the elements. The best idea I've had so far is to do something like: foreach($mylibrary->data_array as $library) { $sublibrary = new Library(); $sublibrary -> getAllElements(); } where Sublibrary is another class which has the function getAllElements. I can't quite get it to work though, and I'm not sure I'm on the right lines... Is there a way that I can then end up being able to do something like the following, to retrieve a specific element? $mylibrary->sublibraries[0]->element[0] <?php class Library { public $element; public $data; public function __construct($sublibrary) { $this->data = $sublibrary; } public function getAllElements() { // populate $this->element using $this->data } } class LibrarySet { public $user_id; public $data_array; public $sublibraries; public function getMyLibraries() { // populate $this->data_array $this->sublibraries = Array(); foreach($this->data_array as $index => $sublibrary) { $this->sublibraries[$index] = new Library($sublibrary); $this->sublibraries[$index]->getAllElements(); } } } $mylibraryset = new LibrarySet(); $mylibraryset->getMyLibraries(); $mylibraryset->sublibraries[0]->element[0] ?> Wow, thank you! I wasn't expecting a full answer, but you've really helped. And it helps me to make sense of it as well. Thanks again.
common-pile/stackexchange_filtered
SSRS Sorting option showing beginning of the column I have created a matrix report in SSRS and added a sort option to the first column. when I deployed in the report server, then sort option showing at the beginning of the column. I've never seen this before but I don't use the interactive sort much to be honest. Have you tried other browsers? Does the same happen in other reports? Does it look OK in Visual studio (or Report Builder if that's what you used to design the report) @AlanSchofield, this issue is only in the browser. In Visual studio, it is showing correctly Have you tried different browsers, different reports?
common-pile/stackexchange_filtered
Restart hyperopt from local MLFlow runs I'm currently running a parameter search which is going to take a few days, I'm using hyperopt and recording the results using mlflow. The server is going to be restarted automatically (oversight on my part) and for various reasons can't be delayed. This would also be useful to know if it crashes. I didn't dump the hyperopt trials (lesson learned for next time) Is it possible to use the MLFlow records stored locally to rebuild the trials object and restart the space search from where it is going to be left off. I've logged all the parameters and the results into MLFlow. I think I can do it manually - read the results and run dummy "experiments" which just return the values then use that trial object to do the rest using the real thing. Is there some formal/quick way of doing this I haven't been able to find (I've looked but I'm not sure I'm finding the right search terms).
common-pile/stackexchange_filtered
Example of modified configuration for gatsby-plugin-offline? I'm trying to get my head around gatsby-plugin-offline. The README that comes with the plugin gives an example of the default options, but the example isn't in a format that can be pasted into gatsby-config.js for playing-around purposes. I'm struggling to figure out how to do that; e.g. if you just cut and paste, modify for the different syntax, it bombs out on the ${rootDir} reference. I'm pretty familiar with service workers, but Gatsby has a lot of foo under the hood, and I'm not conversant enough yet with the system to know where to start looking for a fix. Seems like rootDir must give the path to your build directory, e.g.: const rootDir = `${__dirname}/public`
common-pile/stackexchange_filtered
Screen capture from NPAPI or javascript I'm writing an npapi plugin. I was wondering if there is a way to capture the browser screen from my plugin using either npapi or javascript. Any help would be appreciated. Thanks What are you trying to achieve? And on what platform(s)? There isn't a way to do it with JavaScript, but you could do it with native code couldn't you? I guess we could do it with native code, but im not sure how ? I don't know anything about writing plug-ins to be honest. From what I understand you have to write code to target different operating systems correct? If so, I'd start searching for how to do screen captures on different platforms. Here is how you can do it on OSX: http://developer.apple.com/mac/library/samplecode/SonOfGrab/ Someone on the FireBreath mailing list recently created a plugin with FireBreath that does this on windows; he was using it with selenium for automation testing, I believe. He had mentioned possibly making it open source; I'd consider posting a question to the FireBreath list and see if he's willing to share. http://groups.google.com/group/firebreath-dev In Mozilla you can achieve this by using Canvas.prototype.drawWindow(). But access to this method is allowed only to privileged code, i.e. extensions.
common-pile/stackexchange_filtered
Read JSON from /assets folder into an ArrayList in Android? First, I have researched this question a lot. I learned how to read from my text file in the assets folder. The problem is that I don't want to end up with a string because the file is actually an arraylist written using json and inside that arraylist are objects. I need to access one object only. Here's what I mean: I have a Book class, which has an int called chapter, an int called title, and an int called pageNum. I created several Book objects and added them to an ArrayList. Then I used the following code to write my ArrayList to a text file (in a regular java project): ArrayList<Book> aList = new ArrayList<Book>(); aList.add(book1); //etc...add more Book objects here... File aFile = new File("books.txt"); FileOutputStream aFileStream = new FileOutputStream(aFile); JSONOutputStream jsonOut = new JSONOutputStream(aFileStream); jsonOut.writeObject(aList); jsonOut.close(); That code creates a text file which I then put into the /assets folder in my Android project because I want it included with the app. In a non-Android java project I could simply use the following code to repopulate an ArrayList so that I could parse Book obects from specific indexes: File bFile = new File("books.txt"); FileInputStream bFileStream = new FileInputStream(bFile); JSONInputStream jsonIn = new JSONInputStream(bFileStream); Arraylist<Book> bList = (ArrayList<Book>) jsonIn.readObject(); Book aBook = bList.get(253); //some arbitrary index The json code I'm using comes from quickconnectfamily.org. You have to add a file called qc_json.jar to the build path of your project. http://www.quickconnectfamily.org/qcjson/more.html The problem in Android is when I read the file using InputStream, I can only get the entire file into a string, the code above doesn't work in Android. I can't wrap JSONInputStreams around an InputStream, only around a FileInputStream. But it seems I am unable to use FileInputStream. So what I need is a way to create an ArrayList rather than a string in my Android app. Without giving away too much about my app, the app basically generates a random number and creates a Book object from that index in the ArrayList. Then the user is quizzed with info from that specific book. Sounds silly, but the real app is much cooler. I'm open to solutions, alternative methods of storing objects in a text file, etc. Please don't simply post criticism about my grammar, syntax, or application idea. I'm pretty new to app development and I couldn't care less about personal opinions. If anyone wants to see more code I can upload it, but it doesn't seem necessary at this point. Thanks. Hmmmm seems like the docs state that a plain InputStream is valid... Of course, you could use another library (e.g. Jackson), or use the SQLite DB. You can read the file in as a string and use gson to deserialize it to an object. https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples I tried Jackson, but I kept getting a classCastException. Thanks for the help though, I actually figured out the solution and I will post it as an answer. I figured out the solution. I connected my Evo 4G and tested the app and it worked. Here's what I did: I used the following method to read from the file, which is what I was doing before: InputStream is = appContext.getAssets().open("books.txt"); int size = is.available(); buffer = new byte[size]; is.read(buffer); is.close(); String bufferString = new String(buffer); When you do this, you end up with a String of the entire file. This is what I was able to do before, but what I wanted was a way to convert the String to an ArrayList of Book objects. Here's how I accomplished this: //convert string to JSONArray jsonArray = new JSONArray(bufferString); //parse an Object from a random index in the JSONArray JSONObject anObject = jsonArray.getJSONObject(randomNum); Book aBook = new Book(); aBook.setTitle((String) anObject.get("title")); //you can continue to set the different attributes of the Book object using key/value pairs from the Book class (e.g. setPageNum, setChapter, etc). I don't know, maybe that was obvious to some people, but I really couldn't find any examples that did this. In a different question someone mentioned using the json library native to Android org.json and so I tried that and it worked.
common-pile/stackexchange_filtered
mac os x lion configuration problem with gitosis I'm trying to setup gitosis on my mac mini with mac os x lion (clean install). Basically a followed this guide I also looked at this question If I try to clone the gitosis-admin.git repo i get the following error: git clone git@<IP_ADDRESS>:gitosis-admin.git Cloning into gitosis-admin... Assertion failed: (argv0_path), function system_path, file exec_cmd.c, line 30. error: git-shell died of signal 6 fatal: The remote end hung up unexpectedly I also tried to use localhost, the ip or the remote ip. One thing i noticed, if i try to login as my git user (a standard mac user, without password) trough ssh i can't login (makes sens), but if I set a password I thought I should get an answer like PTY allocation request failed on channel 0 Connection to gitserver closed. but I can login like normal. I've been searching for around a week, and a found no result in the internet with this error... Edit: One thing, I also installed gitosis on my macbook pro, following the same instructions and it worked! What am I missing? okay strange, I figured out... Somehow I've to specify the complete path from the git user's home direcotry: git clone git@host:repositories/gitosis-admin.git with this command I can clone the directory
common-pile/stackexchange_filtered
Best way to deallocate an array of array in javascript What is the best way to deallocate an array of array in javascript to make sure no memory leaks will happen? var foo = new Array(); foo[0] = new Array(); foo[0][0] = 'bar0'; foo[0][1] = 'bar1'; foo[1] = new Array(); ... delete(foo)? iterate through foo, delete(foo[index]) and delete(foo)? 1 and 2 give me the same result? none? foo = null; should be enough for the garbage collector to get rid of the array, including all its child arrays (assuming nothing else has a reference to them). Note that it will only get rid of it when it wants to, not immediately, so don't be surprised if the browser's memory consumption doesn't drop straight away: that isn't a leak. It potentially gets more complicated if any of those array elements contain references to DOM nodes. It only gets more complicated in IE6. For those visiting here in 2014, please note that there is almost never reason to set something to null or try to "deallocate" it (a concept which does not exist in JS), or do anything else to get the GC to do anything. It does just fine by itself, thank you very much. you can't delete variable, set it null foo = null; .. or use a namespace object var namespace = {}; namespace.foo = []; delete namespace.foo; I think Array.splice also might do the trick for you. Its an alternative to using delete on each index. Ref: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Splice You can also combine it with Array.forEach like this: foo.forEach(function(element,ind,arr){ arr.splice(ind,1); //emptying the array }); foo = null; //remove ref to empty array If you just use the forEach part, you will empty the foo array. I think internally the splice method removes a reference so you will be good removing elements this way.The last line then removes the reference to the empty array that is left. Not very sure on this but worth some research. There is no point in clearing each array, unless they're referenced elsewhere. foo.length = 0; can do exactly the same. Doing it this way is O(n^2) :( Splicing from the front of the array is O(n) since every element gets reindexed. The solution you suggest does this n times, giving O(n^2) complexity.
common-pile/stackexchange_filtered
Am I underestimating the differences between these two hands if I bid them the same way? In the first case, I was in "third" position, only them vulnerable at match points. Here I pre-empted 3 diamonds with the following 13 high card point hand: ♠ 2 ♡ KT ♢ AKQ6432 ♣ J53. I would not have done in the first or second position, but opposite a passed partner, I didn't see much of a chance of missing a slam. But it raised eyebrows with others at the table because I had 13 high card points. The following hand, which I had played a few days earlier, was more obviously pre-empt material: ♠ A86 ♡ 2 ♢ AQ987432 ♣ 3. But I opened it 1 diamond instead of 4 diamonds in first position (neither vulnerable) to give my partner a chance to speak. The opponents found their heart fit, bid and made five hearts giving us a bottom. I feel that the two hands are similar enough to bid the same way, and that either "pre-empt" or "one diamond" could be the right bid depending on position, vulnerability, and other factors. Putting aside the fact that the first hand has 13 (Milton) "Work" points, and the second one, "only" 10. I consider the first hand to have 7.5 potential winners, and the ability to make 9-10 tricks if partner has his statistical average of 9 "Work" points. I believe the second hand may have 8 potential winners because the eighth diamond compensates for the lack of the king, and similar potential of making a 3-4 level contract. And I believe that both hands have only two defensive tricks (the ace of diamonds and a side honor). Am I wrong to consider the two hands equivalent and bid them the same way, or are there major differences that I have overlooked? In all my non-Namyats playing partnerships, I'm opening the first hand 3N in 3rd seat. @AlexanderWoo: I have recently "come around" to pre-empting on this hand for a reason that surprised me. That is, with seven playing tricks, I can "bid to make" with seven tricks in hand, and a reasonable hope that partner will have the two I need, (instead of expecting to go down one or more). If I have 13 hcps, the average of the other three players is nine. And if partner doesn't have two tricks, the opponents might have a game that the pre-empt might prevent. I have narrowed the question by focusing only on my own thinking (and its possible flaws, rather than what "people" generally think. Short answers: Yes. Yes. Yes. Yes. That's what makes bridge interesting. There is no right answer(*). It depends on your partner, your partnership, your agreed system, your opponents, the state of your game, the field, and your level of caffeination. Among others. Please remember there is exactly one person whose opinion matters here. You say you got "raised eyebrows" from the table. If it was the opponents, their opinion Does Not Matter - especially if the preempt worked. If it was partner...? Is this a new partner? Maybe stick to stuff she will understand. Is this a partner that will preempt aggressively (or open aggressively)? Then the chance that you will win an auction starting at the 1-level is lower than if partner is sound and could have (say) QJ9xxx in one of the majors or have a flat 12 count. So, better to bid at the 3 level(**). Does your partner try to blame you for all your bad results? Then do the thing that will Win The Post-Mortem(***). Sure, it may not win the board, but both you and partner are more likely to be concentrating on the next hand when it comes rather than the argument you get into on this one. Is this a pair you expect to beat playing with the field? Then make the field bid. Similarly, if in a team game you think you're better than them, why open yourself up to a "random" 6-10 IMP swing with an unusual bid? Is RHO a "can't be preempted" player? Maybe now's the time to bid 3 and get them too high with 20-20. Is RHO a player that really pays attention to the auction? Again, a 3-bid with the 13-count, or a 1-bid with the 10-count, might elicit a misplay. At least, if you're known to be a "straight actor", anyway. Are the opponents frisky with the red card? Maybe it's time to walk the dog (bid 1, then 2, then 3, hoping to eventually get doubled) with the likely 8 tricks, and go for +530 (or -100 into -140 or -300 into -620). Especially if your room is full of people who will re-re-bid bad suits just because they're long. Are your opponents the best pair in the room? Then they're likely to beat you anyway, but even they might not be able to find the 30-point-deck slam if you open 3. If the opponents are weaker - not really much weaker, frankly - it might be harder to find the same 30-point-deck slam opposite a "real opener". Is this a regular partnership? Then you should have discussed this already; do what partner wants you to do (including "use your own judgement"). Is this a pickup? Well, usually in your local community, you have a good guess as to how they think from how they play against you - but if the information's balanced, it might be better to "play straight". Are you running a 45% game? Maybe it's time to try something unusual to get you to 50%. Is 42% going to get partner yelling at you? Maybe it's time to play straight and take your 45%. Similarly, are you running a 62% game? Do you want to increase randomness by taking an uncommon action? Or hope you can ride your good game with your better than average luck/skill? Re: suit - that's always a consideration. That's (one of the reasons) why requirements for 3♣ and 3♦ openers are frequently different than 3♥ and 3♠ openers. In third seat, it's more interesting, though, because the other big reasons are "what does partner need to bid 4?" and "what should partner have to sacrifice (especially 4♠ over 4♥)?" which might actually give you more flexibility in minor preempts than major ones. All of this (and more, I'm sure) to say, the primary answer is "yes, you can use judgement to make an off-system call, or even an off-normal call. In fact, doing it at the right times more often than others is one of the things that makes a better player. Third seat favourable is one of the 'freest' times - good for thinking about it." Do I think your judgement is right on these hands? Well, my personal belief is that the overstrong preempt in this position is more likely to work in your favour than the upgraded 1-opener. But there's never a guarantee, and I am not Larry Cohen. The secondary answer is "if you annoy or confuse your partner, you will not score well, and you are less likely to be asked again." To me, that's more important. The tertiary answer is "this session (like all sessions) is an audition." If you want partners in future that accept some off-book judgements, then play that way. If you want partners who make The Right Call, then do that. Play the way you want to be thought of by the person who might have a game free next week, both technically and in the way you treat your partner, and they might ask you sometime. (*) There almost never is "the Right Answer" in bridge (at least, in the auction). Again, that's what makes bridge interesting. "I am right because The Book says so" died with Goren; unless you have agreed with partner/the rubber club rules/the "one system" event to Play By The Book. Similarly, one swallow does not make a summer. Just because this hand got a bad result, doesn't mean the judgement was bad (or vice versa). There are people out there that look at the result on each hand and work out how best to get to the winning score; these players are called "Resulters", and they either burn through partners not willing to be wrong again (even if it would have been right 70% of the time) or end up with a system so full of exceptions and convolutions that they can't bid the 60% of the "normal" hands correctly. (**) or 3NT with the first one, if you play Gambling. Yes, "zero outside controls", but partner with 2 aces and out won't bid 3NT after 3♦ either. And if partner's also on the risk-taking side (and you're not going to have a problem if she guesses wrong), she might pass with "nothing" and hope to go -250 or -300 into game. (***) Do Not actually try to win the post-mortem. With pickups, avoid having a post-mortem beyond "do you want this call with my hand?" or "did we agree to play one-way or two-way Drury?" With a (want-to-be) regular partner, the post-mortem should not be something to win or lose, rather something to get on the same page over, or decide that something needs to change, or work out how better to get a message across in a way that both players can understand. The thing here is that the kinds of partners who look for ways to make it "your fault" are less likely to have something to hang on to if you play it straight. So play it straight and avoid the hassle. It must be nice to be able to play enough Bridge to be confident as to whether you're currently (!) "running a 45% game" versus slightly more or less. It is, yes. But "estimating your game" is a critical skill in duplicate, given that unlike most other games, you don't get an up-to-date running score. I have a Mike Lawrence book - "play a swiss teams with..." Hand 1, he ends with "as I expect they will bid game, I estimate a 10 IMP loss." And he keeps a running estimate for the other 55 boards. And compares his estimate to the "real result" at the end of each match. It's that key a skill. If you aren't there yet, try explicitly ranking your scores as you write them, on a 0-4 scale. See how close you get, after 3 or 4 sessions. With the edits and the change in focus, my other answer (while still valid, and I will refer most of my arguments for what I state here, there) looks like it's a little odd. Mostly because it assumes the answer to the current question asked is understood. So, let's look at that. Am I wrong to consider the two hands equivalent Oh yes. The two hands are very different. One of them will take 9 tricks in diamonds opposite effectively nothing; and 9 tricks in 3NT if partner has something in the black suits. It is also likely that they can make 4 of either major, especially if partner has three diamonds - and at that point, 5♦ is a great sacrifice at these colours. The other one needs a lot of help to take tricks on offense. Sure, partner's singleton ♦K is "a lot of help", but without it you could lose 3 diamonds and the four outside cards if partner's 8-count is in the round suits. Or if partner's spades are such that you only have one spade loser, that's 300 into likely to be no game. Even 100 (undoubled) into no game is likely to be poor. But let's be less concerned about bad fits, and say that they can make game. Now partner's sacrifice could be 800 or 1100! The additional difference between the two hands is the second "sure" trick of the ♠A vs the "half-trick" (less than that, actually, as if they do have points for game, LHO's hand will be significantly stronger than RHO's, so more likely to have the A) of the ♥K. So it's more likely that "some cards" will hold them to 9 tricks. Now partner's sacrifice is only 500, but it's a phantom. But: and bid them the same way, Absolutely. If they both fit your agreements for a third-seat pre-empt, then you could bid them both as a pre-empt. And that agreement isn't wrong; the description of one partner's third seat weak 2s is "she has 13 cards, some of which (at least 5) are hearts." Partner will take that into account when deciding what to do - which may lead to less-than-optimal results. That's the downside to go with the upside of "good luck lefty, you're at the 3 level" more often. You can also agree that in third seat, you can take liberties with your 1 bids. In a standard framework, there are downsides to that, as partner has to "not hang" you when you step out, which makes it more difficult to have good auctions when you actually have the goods, but it can be very effective, especially in a weaker field. As implied in the other answer, it does tend to be more effective in the majors than diamonds, though. Why "a standard framework"? I play Precision, and I play Precision so that I can open good 10 counts (even in first seat) and partner won't hang me. I can bid that solid suit 1♦, and if I get a second chance bid 3♦ to show "tricks and a long suit", because I'm limited to 15 HCP. I can rebid 2♦ with the broken suit (and maybe bid 3 later) showing that hand. Or maybe I can't; see other answer for "it's less likely to work". are there major differences that I have overlooked? Absolutely. See 1. Are the differences sufficient to mean that it's wrong to make the same call third seat favourable with them both? See the other answer. Summary: up to what partner will expect, and what "stepping out" actions partner will forgive you for, and how willing you are to take the blame for a bad result when you "step out", no matter what partner did after. For those saying "but what about pickups, where you don't know any of that?": As in my other answer, it's only very rarely you have a "true pickup" without knowledge from playing against them, or playing with common partners, or even from knowing how "people in the area" are. as a club Director, I've played "pickup" (to fill in a table, or as the spare) more than most; and when I do, I rarely have time to discuss system well (I frequently describe our system as "we started discussing 5 minutes after game time. We've agreed...") Even then, I get three things, and one of them is "what's your preempt style?" (the other two are "what do we play against their 1NT", and "what answers to 4NT?") If you do not know this - even with a pure pickup - you can't judge these hands correctly for your partner, and they can't judge what to do after. So find out beforehand. "and 9 tricks in 3NT if partner has something in the black suits." - if partner only has a club stopper, surely it won't be hard for opponents to find spades? I did very carefully say "suits". It's actually more likely to make if the only stopper is in the spade suit, for the reason you mention. Ah, I naturally understand "something in the black suits" as meaning either, not necessarily both. But I guess you would have said "something in a black suit".
common-pile/stackexchange_filtered
get position (index) of td element identified by class name i have this code <tr id="3" class="gradeA odd focus row_selected"> <td class="center">Kids Footwear 2</td> <td class="sorting_1 center focus">200</td> <td class="center">50</td> <td class="center">200</td> <td class="center">30-34</td> <td class="center">234-343</td> <td class="center">200</td> <td class="center">25</td> <td class="center">1.23</td> </tr> i want to fetch the index value of <td> element which contains the class focus so if within the <td> element the focus class is set on first `<td>` then return 0 second `<td>` then return 1 third `<td>` then return 2 and so on.how do i go with this in jQuery? thank you. You can use the index method. If you have more than one tr element containing a td with the focus class then you will probably want to make the selector specific to the tr you care about: var index = $("td.focus").index(); From the jQuery docs: If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements. Update (see comments) You can use children or find to get the td elements from the tr, and then use the above code: var index = tr.find("td.focus").index(); okay little bit of confusion here, i have the <tr> elements fetched from a function and assigned to a javascript variable var tr = $(this).parent(); i need a continuation from here. perfect, just as i thought i should be using find() you posted it :), thank you.
common-pile/stackexchange_filtered
sap ui5 planning calendar - title text size I am creating the appointments in planning using the following XML tags, I wanted to reduce the appointments the size of the title in each appointments - title="{title}". Also wanted to increase the height of appointment to show more data. <appointments> <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" text="{info}" type="{type}" tentative="{tentative}"> </unified:CalendarAppointment> </appointments> Saying 'wanted' means that you wanted to in the pass but no longer. Pedantry aside, assuming you mean want, you need to supply more information. Increase the size of the title where? On a web page, in an application? Have you written any code? You can assign CSS class to your Planning calendar and modify the respective CSS classes to suit your requirements. CSS Classes: sapUiCalendarApp: controls the height of each appointment. sapUiCalendarAppTitle: controls the font-size of title of each appointment. So, let us assign our own class to our planning calendar so other developer code is impacted ( or the entire library CSS is not updated) CSS code: .myCalendar .sapUiCalendarApp { height:5rem; } .myCalendar .sapUiCalendarAppTitle { font-size:.5rem; } XML CODE: We need to add our CSS class to our planning calendar: <PlanningCalendar class='myCalendar' id="PC1" startDate="{path: '/startDate'}" rows="{path: '/people'}" appointmentsVisualization="Filled" appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false"> ....... <appointments> <unified:CalendarAppointment startDate="{start}" endDate="{end}" icon="{pic}" title="{title}" text="{info}" type="{type}" tentative="{tentative}"> </unified:CalendarAppointment> </appointments> ............. You can modify the above CSS classes to suit your requirements. Let me know if any additional information is required.
common-pile/stackexchange_filtered
Velocity addition as a special case of change of reference frame In this question, I want to restrict the discussion to classical mechanics as understood before 1900; that is, to exclude any discussion of relativity (however, if there is a neat generalization I would be eager to hear about it). As I go back and reread a classical mechanics textbook, I am again struck by how opaque solutions involving relative velocities and velocities in different frames are. As is well-known, if $\textbf{V}$ is the velocity of a particle in frame $S$ and $\textbf{V}_0$ is the velocity of frame $S'$ which moves rigidly relative to $S$, then the relative velocity of the particle in $S'$ is $$\textbf{v}' = \textbf{V}-\textbf{V}_0$$ My question is, is this just a special case of how we "translate" between different frames? As per this question/answer, the most general relationship that we can have between the position of a particle as expressed in two different frames (neither of which need be inertial -- this is just a statement about how different vectors are related) is \begin{equation} \mathbf{R}(t)=\mathbf{R}_{0}(t)+\mathbf{r}(t)=\mathbf{R}_{0}(t)+\Bbb{S}(t)\:\mathbf{r}^{\prime}(t) \end{equation} where I here use the notation of the linked answer. Then do I obtain the rule for addition of velocities by simply differentiating the above and solving for $\textbf{v}' \equiv d\textbf{r}'/dt$? That is, using the standard dot notation for time derivatives, \begin{equation} \dot{\mathbf{R}}(t)=\dot{\mathbf{R}}_{0}(t)+\dot{\Bbb{S}}(t)\:\mathbf{r}^{\prime}(t)+\Bbb{S}(t)\:\dot{\mathbf{r}}^{\prime}(t) \end{equation} and solving for $\dot{\mathbf{r}}^{\prime}(t)$? The presence of $\mathbf{r}^{\prime}(t)$ seems to obscure this. In the special case I mentioned at the start of the question wherein $S'$ moves rigidly so that $\Bbb{S} \equiv id$ I seem to recover the right answer, but I ask this question because I'm not sure if I'm missing the bigger picture somehow. These details don't seem to be mentioned as explicitly/mathematically as I would like in my textbook (Taylor's Classical Mechanics). To link it with the common formula, since $S$ is orthogonal, it satisfies: $$ SS^T=1 $$ Taking the derivative: $$ \dot SS^T+S\dot S^T=0 $$ so $\dot SS^T$ is skew symmetric. In 3D, a skew symmetric operator can be uniquely represented as the cross product by a vector, so there exists $\omega$ such that: $$ \dot Sr’=\omega\times r $$ Your formula is therefore: $$ \dot R=V_0+\omega\times r+v’ $$ where I’ve set $v’=S\dot r’$ the velocity of the particle in the second frame (converted to the first frame), and $V_0=\dot R_0$. You then define $\omega$ as the angular velocity of the second frame with respect to the first frame. This is a standard definition of angular velocity (perhaps not for engineers but for mathematicians/physicists it is and is related to the more general study of Lie algebra and Lie groups). Intuitively, $\dot S$ captures the velocity part, while the $S^T$ allows you to stay in the first frame. Note that $S^T\dot S$ is also skew symmetric. It corresponds to the angular velocity in the second frame $\Omega$: $$ \dot S r’=S(\Omega \times r’) $$ Note that both antisymmetric operators are related by a conjugation via $S$, or equivalently $\omega=S\Omega$. Hope this helps. Noted, thank you. I guess my main question that I want to confirm though is whether (or not) the typical velocity addition type of manipulations are indeed really special cases of the development which you and I have given here? Is that a fair statement? Just following up here. Thanks so much for the lovely answer. I am curious about "You then define $\omega$ as the angular velocity of the second frame with respect to the first frame." Is this standard? Is there another definition which we can show is equivalent to this one? I think this question is related to my question (4) on Frobenius's answer here (https://physics.stackexchange.com/questions/67053/velocity-in-a-turning-reference-frame).
common-pile/stackexchange_filtered
VC-dimension of parity functions Consider the boolean hypercube $\{0,1\}^N$. For a set I $\subseteq$ {1,2,...N}, we define the parity function $h_I$ as follows. For a binary vector x = $(x_1, x_2, ...,x_N) \in \{0,1\}^N$, $h_I(x) = \bigg(\sum_{i\in I}x_i\bigg)mod 2$ What is the VC-dimension of the class of all such parity functions, $H_{N-parity} = \{h_I:I\subseteq \{1,2,..., N\}\}$? [Courtesy: Shai Ben-David et al.,] We have $\vert H_{N-parity}\vert = 2^N$, and since this is a finite number, we know that VCdim$(H_{N-parity}) \leq \log_2{2^N} = N$. If we can find a subset of $\{0,1\}^N$ of cardinality $N$ which is shattered by $H_{N-parity}$, then we conclude that VCdim$(H_{N-parity})=N$. But notice that such a set is possible if you take $x_i=e_i$, i.e., the vector of all zeros with a $1$ at the $i_{th}$ position, $i=1, 2, \dots, N$. Given any subset $K\subset \{1,2,\dots,N\}$, we wish to find a hypothesis $h$ with the property that $h(x_i)=1$ for all $i\in K$. Simply let $I=K$ and the result easily follows. $ Claim: VC-dimension(H_{N-Parity})=N $ The upper bound is given by the $\log H_{N-parity}$ , which gives $N $ as there can be at most $2^N$ many such functions. For the lower bound of the VC-dimension we need to show that there is a set of size $N$ which can be shattered. Let the set be S. $S=\{x \in {0,1}^N | \sum_{i=1}^N x_i=1\}$ To show $\forall S' \subseteq S, \exists h \in H_{N-Parity} ~such ~that~~ h \cap S=S'$. Here is $h$ for a particular $S'$. $$h(x)=\sum_{i=1}^N x_i~, where~ i \in \\{ i \in [N]~ |~ e_i \in S' \\}$$. In simple engish, h is defined to be parity of the bits which is set to 1 for each element in S'.
common-pile/stackexchange_filtered
How to assign category to specific rows in R data frame, in a new column? In a time series dataset, what would be a good way to group sets of rows such that they have a unique identifier in a new column? For instance (in a very abridged manner), taking this: library(tidyverse) data <- read_csv("snippet.csv") print(data,n=29) # A tibble: 29 x 5 Port Timestamp MultiPort dev_value dev_unit <chr> <chr> <chr> <dbl> <chr> 1 PortConRef1 2/26/2020 12:39:40 PM n -38.1 ‰ 2 PortConRef1 2/26/2020 12:39:41 PM n -38.0 ‰ 3 PortConRef1 2/26/2020 12:39:42 PM n -38.2 ‰ 4 PortConRef1 2/26/2020 12:39:43 PM n -38.1 ‰ 5 PortConRef1 2/26/2020 12:39:44 PM n -38.3 ‰ 6 PortConRef1 2/26/2020 12:39:45 PM n -37.9 ‰ 7 PortConRef1 2/26/2020 12:39:46 PM n -38.3 ‰ 8 PortRef1 2/26/2020 12:40:48 PM n -9.82 ‰ 9 PortRef1 2/26/2020 12:40:49 PM n -10.2 ‰ 10 PortRef1 2/26/2020 12:40:50 PM n -9.75 ‰ 11 PortRef1 2/26/2020 12:40:51 PM n -9.89 ‰ 12 PortRef1 2/26/2020 12:40:52 PM n -10.1 ‰ 13 PortRef1 2/26/2020 12:40:53 PM n -10.1 ‰ 14 PortRef1 2/26/2020 12:40:54 PM n -10.3 ‰ 15 PortSampleB 2/26/2020 12:51:14 PM n -5.13 ‰ 16 PortSampleB 2/26/2020 12:51:15 PM n -4.70 ‰ 17 PortSampleB 2/26/2020 12:51:16 PM n -4.90 ‰ 18 PortSampleB 2/26/2020 12:51:17 PM n -5.03 ‰ 19 PortSampleB 2/26/2020 12:51:18 PM n -4.76 ‰ 20 PortSampleB 2/26/2020 12:52:50 PM y -5.15 ‰ 21 PortSampleB 2/26/2020 12:52:51 PM y -4.97 ‰ 22 PortSampleB 2/26/2020 12:52:52 PM y -5.11 ‰ 23 PortSampleB 2/26/2020 12:52:53 PM y -4.71 ‰ 24 PortSampleB 2/26/2020 12:58:49 PM y -5.19 ‰ 25 PortSampleB 2/26/2020 1:00:21 PM n -4.75 ‰ 26 PortSampleB 2/26/2020 1:00:22 PM n -5.20 ‰ 27 PortSampleB 2/26/2020 1:00:23 PM n -4.95 ‰ 28 PortSampleB 2/26/2020 1:00:24 PM n -5.06 ‰ 29 PortSampleB 2/26/2020 1:00:25 PM n -4.81 ‰ # Remove reference gas rows data2 <- data %>% filter(`Port`=="PortSampleB") # Convert timestamp column to useable time library(lubridate) data2 <- data2 %>% mutate( time=mdy_hms(`Timestamp`)) > print(data2,n=15) # A tibble: 15 x 6 Port Timestamp MultiPort dev_value dev_unit time <chr> <chr> <chr> <dbl> <chr> <dttm> 1 PortSampleB 2/26/2020 12:51:14 PM n -5.13 ‰ 2020-02-26 12:51:14 2 PortSampleB 2/26/2020 12:51:15 PM n -4.70 ‰ 2020-02-26 12:51:15 3 PortSampleB 2/26/2020 12:51:16 PM n -4.90 ‰ 2020-02-26 12:51:16 4 PortSampleB 2/26/2020 12:51:17 PM n -5.03 ‰ 2020-02-26 12:51:17 5 PortSampleB 2/26/2020 12:51:18 PM n -4.76 ‰ 2020-02-26 12:51:18 6 PortSampleB 2/26/2020 12:52:50 PM y -5.15 ‰ 2020-02-26 12:52:50 7 PortSampleB 2/26/2020 12:52:51 PM y -4.97 ‰ 2020-02-26 12:52:51 8 PortSampleB 2/26/2020 12:52:52 PM y -5.11 ‰ 2020-02-26 12:52:52 9 PortSampleB 2/26/2020 12:52:53 PM y -4.71 ‰ 2020-02-26 12:52:53 #... 10 PortSampleB 2/26/2020 12:58:49 PM y -5.19 ‰ 2020-02-26 12:58:49 11 PortSampleB 2/26/2020 1:00:21 PM n -4.75 ‰ 2020-02-26 13:00:21 12 PortSampleB 2/26/2020 1:00:22 PM n -5.20 ‰ 2020-02-26 13:00:22 13 PortSampleB 2/26/2020 1:00:23 PM n -4.95 ‰ 2020-02-26 13:00:23 14 PortSampleB 2/26/2020 1:00:24 PM n -5.06 ‰ 2020-02-26 13:00:24 15 PortSampleB 2/26/2020 1:00:25 PM n -4.81 ‰ 2020-02-26 13:00:25 #note that data from the original dataset has been removed between rows 9 and 10 to ease reproducibility and giving each section (defined by row number or 'time') a unique letter category. In the abridged example above, there is a gap in 1 hz data collection between rows 5 and 6 corresponding to multiport switch from "n" to "y". This pattern repeats every six minutes such that in the full dataset there are eight alternating 6 minute groups of "n" and "y" with 90 seconds between. As it is 1 hz data, each 6 minute group has 360 rows. I'd like each six minute y and n period to have a different letter category, such as "a" through "h". The goal is to have a separate boxplot for the data from each time period to plot on top of the raw data, which as it stands looks like this: What are you using to define where your groups are separated? Is it grouped by minute (given that you're separating 12:51 from 12:52 here). Also - it can be helpful to post some of your data in a format that others can test - see https://stackoverflow.com/help/minimal-reproducible-example and perhaps use dput. There are ways to split time up but it would be helpful to be able to check your date/time format and test it out before suggesting solutinos Thanks, edited to hopefully help with reproducibility and understanding. The groups are defined by the switch from n to y (and vice versa) which occurs at 6 minute intervals, with a 90 second gap in between each. I do change the date/time format for plotting purposes (see edits). We can use rleid from data.table to get a unique number every time MultiPort changes and use it to index predefined letters vector. library(dplyr) df %>% mutate(cat = letters[data.table::rleid(MultiPort)]) Thank you, that worked well. Based on my answer below where I show the completed box plots, do you have an idea of a good way to calculate and show standard error of the mean (s/√n) for each "cat" group on its box plot? Sorry, I am not much into plotting. However, you check https://stackoverflow.com/questions/25999677/how-to-plot-mean-and-standard-error-in-boxplot-in-r and https://stackoverflow.com/questions/38599335/how-to-add-standard-error-bars-to-a-box-and-whisker-plot-using-ggplot2 if they are of any help. If not feel free to ask a new question. We can use rle from base R df$cat <- letters[with(rle(df$MultiPort), rep(seq_along(values), lengths))] As an update, here's what I used to get the box plots on to the time series. #from Ronak's answer df1 <- df %>% mutate(cat=letters[data.table::rleid(MultiPort)]) df1 %>% ggplot(mapping=aes(x=`time`,y=`dev_value`))+ geom_point()+ geom_boxplot(aes(data=cat,fill=MultiPort))+ ylab("13C vs Intl. Std. (‰)")+ xlab("Time")+ theme(legend.text = element_text(size=12), legend.title = element_text(size = 14), axis.title.x = element_text(size=20), axis.title.y = element_text(size=20), axis.text.x = element_text(size=14,colour="black"), axis.text.y = element_text(size=18,colour="black"), legend.box.background = element_rect(color="black", size=2))+ scale_fill_manual(values=c("dodgerblue1","red"),labels=c("Reference","Sample"))+ theme(plot.tag.position = c(0.8, 0.02))
common-pile/stackexchange_filtered
Sqlite 3 select statemen I need to do a somewhat complex select in sqlite3 if you guys can help me? I got a 'messages' table holding the following fields: from | to | message_text | message_timestamp and the rows: a | b | Hi | 101 a | b | How are you? | 103 b | a | Fine,thanks | 104 c | a | Hey dude! | 115 a | b | I need to tell you something. | 1102 d | b | Yo dude | 1234 b | d | Yea dude, whatsup? | 1443 I'd like to select the last messages from the above conversation in chronologic order by disregarding if the message was sent form x to y or form y to x, the xy or yx pair should be taken into account. So for the example above, you'd get something like this: b | d | Yea dude, whatsup? | 1443 a | b | I need to tell you something. | 1102 c | a | Hey dude! | 115 Thanks!! Just looking into GroupBy clause. Looks promising. One trick which works here to use the scalar min/max trick to collect records sharing the same from/to or to/from pairs into the same logical group. In the query below, the innermost subquery buckets would collect, for example, from b to d into the same bucket as from d to b. Then we aggregate over this to find the latest timestamp, and finally join back to your original table to retrieve the entire rows you want. SELECT m1.* FROM messages m1 INNER JOIN ( SELECT t."from", t."to", MAX(t.message_timestamp) AS max_ts FROM ( SELECT MIN("from", "to") AS "from", MAX("from", "to") AS "to", message_text, message_timestamp FROM messages ) t GROUP BY t."from", t."to" ) m2 ON MIN(m1."from", m1."to") = m2."from" AND MAX(m1."from", m1."to") = m2."to" AND m1.message_timestamp = m2.max_ts ORDER BY m1.message_timestamp DESC; Note: Please don't use SQL keywords like from and to when naming your columns (or tables, or databases). I needed to escape from in double quotes to get the query to work. Output: Demo here: Rextester (The demo is in MySQL since Rextester does not support SQLite. The only difference is that MIN is replaced by LEAST, and the columns are escaped slightly differently.) Combine two temporary results, one with from/to, and one with to/from. Then filter out the duplicates by enforcing that the value in the first column is less than the second one. Then you can use a simply grouping over these columns: SELECT c1, c2, message_text, max(message_timestamp) FROM (SELECT "from" AS c1, "to" AS c2, message_text, message_timestamp FROM messages WHERE "from" < "to" UNION ALL SELECT "to", "from", message_text, message_timestamp FROM messages WHERE "to" < "from" ) GROUP BY c1, c2; (Using bare columns in an aggregated query requires SQLite 3.7.11 or later.)
common-pile/stackexchange_filtered
CSS whole page vertical and horizontal align Since 4k monitors are nascent, I need to align a small page from all four sides of the monitor. It consists of absolutely positioned divs, which are placed inside a container. The body: <div id="mainArea"> div elements containing text, images, links go here. </div> The css: body { background-image: url(); } .mainArea { position: absolute; width: 882px; height: 420px; left: 50%; top: 50%; transform: translate(-50%, -50%); I've tried a number of suggestions on the internet, but they basically solve horizontal and vertical alignment for simple content, like text or images, not for the whole website. These somehow do not work in my case, perhaps due to my inexperience. Any assistance appreciated. Your CSS looks like it should work as long as there are no other positioned elements that are ancestors of mainArea. Perhaps the problem is that your have written .mainArea in your CSS, which would select elements with the class mainArea, but your HTML has mainArea as an ID. Your CSS should say #mainArea to reference the element with that ID. The original psot should have had # instead of . I changed it here on stackoverflow because it was shown in a big font in relation to the rest of the code. This is why i've decided to change. Now, this give me the following look - http://alsem.lv/index_de2.php Give this a look :) https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ (Vertical Centering – Solved by Flexbox – Cleaner, hack-free CSS) hhmm. Doesn't work - http://alsem.lv/index_de4.php Use calc: position: absolute; width: 882px; height: 420px; left: calc((100vw - 882px ) / 2); top: calc((100vh - 420px ) / 2); transform: translate(-50%, -50%); Update. The following seemed to work: .cn { display: flex; justify-content: center; align-items: center; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 1246px; height: 810px; } Output - http://alsem.lv/index_de4.php I've checked the view using different resolutins on http://quirktools.com/screenfly/#u=http%3A//alsem.lv/index_de4.php&w=1920&h=1080&a=4 It shows well on bigger screens, but this method fails on smartphones and tablets, eating out space atop. Any suggestions?
common-pile/stackexchange_filtered
Problem when running PowerShell I've a PowerShell script file to create results source. It works well on staging, but has some problems on UAT. First of all is the trouble with Get-SPSite. I've managed to resolve it. However, when I was trying running Get-SPEnterpriseSearchResutlItemType, It threw an error: Attempted to perform an unauthorized operation. I couldn't found more information other than that error. I then tried going to Search Result Sources in Site Settings and encounter error. From log, Application error when access /_layouts/15/manageresultsources.aspx, Error=There was an exception in the Database. Please retry your operation and if the problem presists, contact an administrator. Microsoft.Office.Server.Search.Query.Pipeline.SearchObjectDatabaseException: There was an exception in the Database. Please retry your operation and if the problem presists, contact an administrator. Getting Error Message for Exception Microsoft.Office.Server.Search.Query.Pipeline.SearchObjectDatabaseException: There was an exception in the Database. Please retry your operation and if the problem presists, contact an administrator. Can you narrow where the problem is? are you administrator of the search service? Are you running elevated? @Nk SP, Matthew: We now only have problem when accessing Search Setting in general, like Search Result Sources or Search Result Types. The log only tells me "there was an exception in the Database" as posted above. Please advise.
common-pile/stackexchange_filtered
Solr Docker Hosting Best Practice - How to - Need suggestion I need to host Solr server with many cores for few clients. Currently I am hosting it externally, on third party hosting provider. So i don't have to manage this. However, I am now planning to host it ourselves and considering to use Docker on public cloud. All the Solr cores are having few changes into the schema file (managedschema, where we make changes using Solr API) and solr config & data-import configurations which is used by DIH. We have our own custom config files, that we already have as config-set. And we use the same while creating new Solr core. However, I am not sure what is the best approach this and whether to use configset or not? Like when I use config-set, every time I need a new solr core, I need to add configset to the Solr by copying folder, making changes to the DIH files, etc. and update Dockerfile to copy this folder to Solr server inside docker. And need to do docker-compose down and up -d again. And then I create new core using configset. This can cause some down-time each time I need to add a new core. Now, when I don't use configset, then I need need to manually move few solr core config files to the running docker, which is a manual task as well. Moreover, if we lose data, we lose all configurations too. And need to create it manually again. I am not sure which is the best way to work with this. Pls suggest the best standard way which is easy and more reliable in long run. You're ready for Kubernetes. @MichaelHampton Pls share some more details how it will help in my case, and especially which is the best way to proceed.
common-pile/stackexchange_filtered
AngularJS + Bootstrap3: How to send information from a navvar to a view I have a very simple webpage that is using Bootstrap3 + AngularJS1.2. The main page uses a fixed nav-bar with some Dropdowm menus. Each menu item calls the same controller (the only thing that changes is the route parameter). The controller retrieves the data and returns always to the same view (which renders such data). What I'd like now is how to display a "user-friendly" version of the collection name. A very quick (and very, very dirty) way to do it could be: pass the view title as a request parameter, which the controller extracts and puts in the view model. Example: http://jsfiddle.net/gC64y/ What it really bad about this (IMHO) is that the title will be visible in the location bar. A cleaner alternative, I believe, would be to have a model in the parent scope that has an array like: menu = [{'urlPath':'data/collection-first', 'title':'The First Collection'},...] .. and then pass to the controller just the index of the array element corresponding to the clicked menu item. However, before start playing with alternatives, I'm curious about what would be recommended way do this in the "Angular-way" (which I'm just learning, by the way). Thank you, Can you create separate views for each of action? i think it would be better way. There is a very nice answer already on a similar topic. http://stackoverflow.com/questions/12506329/how-to-dynamically-change-header-based-on-angularjs-partial-view @Nikhil: Yes, I could, however all of them would be exactly equal except for the title. True, the common part coud be factored out using ng-include (I believe...) but even after doing that the amount of extra lines and duplication doesn't feels right to me. @AlexanderNenkov: nice tip, thanks. I see the cons of this solution similar to my comment above (in this case instead of duplicating the views, I would be duplicating the controllers). So far, I'm inclined to use an array of "menuItem" objects in the parent ng-init (each item with properties such as title, url, etc.), passing the menu index to the controller, and then inside the controller use $scope.$parent.menu[idx] to retrieve it. I'll left the question open for some days waiting for alternatives. Maybe I should put this array in a service, and inject the service to the controller?) I have used what I mentioned in my commet above: So far, I'm inclined to use an array of "menuItem" objects in the parent ng-init (each item with properties such as title, url, etc.), passing the menu index to the controller, and then inside the controller use $scope.$parent.menu[idx] to retrieve it Thanks,
common-pile/stackexchange_filtered
How to Display contents from controller to full calendar bootstrap in codeigniter I need to display json content data from controller to full calendar in php , Here is my controller function Test_Function() { $data = "{"Results":{"Results":[{"Title":"Mr","Name":"xxxxx","Date":"2016-06-04T00:00:00","Data":"Birthday","email":"sasa@asfda.com","Telephone":1234567890},{"Title":"Mr","Name":"yyyyy","Date":"2016-06-05T00:00:00","Data":"Birthday","email":"qwee@rrrrr.com","Telephone":7412589630},{"Title":"Mrs","Name":"zzzzzzz","Date":"2016-06-07T00:00:00","Data":"Anniversary","email":"asdaf@qwe.com","Telephone":1234567890}]}}"; echo $data; } I need to display Name, Data, Email and phone number in the date provided in full calander Here is the part of full calendar var date = new Date(); var d = date.getDate(), m = date.getMonth(), y = date.getFullYear(); $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, buttonText: { today: 'today', month: 'month', week: 'week', day: 'day' }, //Random default events events: [ { title: 'All Day Event', start: new Date(y, m, 1), backgroundColor: "#f56954", //red borderColor: "#f56954" //red }, { title: 'Long Event', start: new Date(y, m, d - 5), end: new Date(y, m, d - 2), backgroundColor: "#f39c12", //yellow borderColor: "#f39c12" //yellow }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, backgroundColor: "#0073b7", //Blue borderColor: "#0073b7" //Blue }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, backgroundColor: "#00c0ef", //Info (aqua) borderColor: "#00c0ef" //Info (aqua) }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false, backgroundColor: "#00a65a", //Success (green) borderColor: "#00a65a" //Success (green) }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', backgroundColor: "#3c8dbc", //Primary (light-blue) borderColor: "#3c8dbc" //Primary (light-blue) } ], editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function (date, allDay) { // this function is called when something is dropped I don't really see what your question is. How can we help you? I need to display Name, Data, Email and phone number in the date provided in full calander
common-pile/stackexchange_filtered
Configuring a new DHCP scope in Server 2008 R2 As I was running through the scope wizard in DHCP for Windows Server 2008 R2, the wording on the wizard was slightly confusing: it seems to imply that changes I make to the default gateway and DNS servers for this new scope will be applied for ALL scopes. That doesn't really make sense, but I wanted to ask to be sure: can the new scope wizard mess up other scopes or global DHCP settings? In short, no. The only thing that will mess up existing scopes is if you run the wizard and create scopes that overlap. Other than that, each scope is treated independent of each other. You can check out this blog post for a little more info. Also, make sure you're not setting Server options as opposed to Scope options. Server options apply to all scopes, although corresponding Scope options will take precedence over Server options.
common-pile/stackexchange_filtered
Facebook´s Conversion API Custom Audience I´m trying to create a Custom Audience on Facebook´s Conversion API following this guide: https://developers.facebook.com/docs/marketing-api/audiences/guides/audience-rules Ive got my data on a JSON: const rule = { "inclusions": { "operator": "or", // Required. and or or. "rules": [{ "retention_seconds": 3500, //Required. Integer (in seconds) for the retention window of the audience. Min=1; Max=365 days "event_sources": [{ "id": "<OFFLINE_EVENT_SET_ID>", "type": "offline_events" }], "filter": { "operator": "and", // Required. and or or. "filters": [{ "operator": "=", //If field set to event, must use =. "field": "event", //event "value": "purchase" }, { "operator": ">", "field": "value", "value": "50" } ] } }] } } const audienceData = { "name": "Customs", "rule": rule, "access_token": access_token } Pushing it with axios: async function CustomAudience(audience) { try { return await axios.post(`https://graph.facebook.com/${api_version}/${audienceID}/users`, audience); } catch (error) { console.error(error); } } customAudience(audienceData); I know i can do it with offline conversions, (among other things, because it gives me the option on field) For Store Visits Custom Audiences, use 'event' or store_visit_country. My question is regarding "retention seconds" as they are offline conversions, I do not have retention_seconds, and according to the documentation, they are required, and I can not modify my JSON data, as it comes from a CRM. And when you do a Custom Audience manually, you do not have to specify retention_seconds... What is the best practice here? Re build a JSON and add a fake retention_seconds seems dirty, but its a required field... “and I can not modify my JSON data, as it comes from a CRM.” - but the Axios code you have shown is “yours”, is it not? Then I don’t see any reason why you should not be able to make changes to what that audienceData variable contains at that point? Yes I can make any change at that level, but the question is what should I add? I dont want to add any made up retention_seconds value, I cant find any default value, and as its required, its got to be in. So its a question of "what" more than "how". “as they are offline conversions, I do not have retention_seconds” - but even Facebook’s own examples under https://developers.facebook.com/docs/marketing-api/audiences/guides/offline-custom-audiences use them. “For example, to target people who spent more than USD1000 in the past 90 days” – and then they use "retention_seconds":7776000 accordingly. Who do you want to target with your custom audience here, if you say you don’t have any retention_seconds? People who did something in the last zero seconds? I can’t see your scenario making much sense yet, tbh.
common-pile/stackexchange_filtered
Javascript Regex for Indian price validation I want to validate price format which can have values as eg. ₹ 3.50L,₹ 3.50, ₹ 3.50Cr,₹ 99.50L, ₹ 3L,₹ 300.50Cr, ₹ 350Cr, ₹ 3,50,000 ,₹ 1 I have tried this Regex : ^₹ ([0-9]+(,[0-9]+)*|[0-9]+(.[0-9]+)*(L|Cr))+$ which should fail for price ₹ 3,50L but it still show as pass. What changes I need to make Could you describe your rules in human-readable sentences? Also I don't quite get your use of point and comma. Why do you think it should fail for the price ₹ 3,50L? According to the regex you have there ([0-9]+(,[0-9]+) and it fits the 3,50 Maybe ^₹ [0-9]+(?!,[0-9]+(?:L|Cr)?$)(?:,[0-9]+)*(?:\.[0-9]+)?(?:L|Cr)?$? price ₹ 3.50 is equivalent to $ 3.50 and if number has comma(,) then if should not be follwed by L or Cr. Also, number could either have . or , at a time followed by any number. As already commented by Hubert Grzeskowiak, describe your rules in human-language so it will be possible to write the relevant regex according to what you are looking for. Maybe my answer here can help you: http://stackoverflow.com/a/37571199/2064981 Hi @WiktorStribiżew , your regex works for all cases except price ₹ 3,500 See https://regex101.com/r/LVKHz7/3 @WiktorStribiżew cases below ₹ 3,50L should not match: https://regex101.com/r/LVKHz7/4 Following regex will get your work done: ^₹ (([0-9]+\,[0-9]+)|([0-9]+[.]?[0-9]*(?:L|Cr)?))$ ([0-9]+\,[0-9]+) : Will match values where ',' is used without L or Cr. ([0-9]+[.]?[0-9]*(?:L|Cr)?) : Will match values with L or Cr. Here '.' may or may not be used. Use cases on Regex101
common-pile/stackexchange_filtered
Plotting implicit function using fsolve I am trying to plot an implicit function using scipy.fsolve but cant seem to get it to work. I want to plot the function z(x,y) where x + y + z + sin(z) = 0 using scipy.fsolve. import numpy as np import scipy import matplotlib.pyplot as plt f = lambda x,y: scipy.optimize.fsolve(lambda z: x + y + z + np.sin(z), x0 = 0).tolist()[0] x = np.linspace(-1,1,50) y = np.linspace(-1,1,40) X,Y = np.meshgrid(x,y) Z = f(X,Y) fig =plt.figure() plt.show() ` This gives me "_minpack.error: Result from function call is not a proper array of floats". I dont see why this would be since I can call the function on individual values and its return type is float. It seems like the controversial line is Z = f(X,Y). Thankful for any help! EDIT The original error is fixed for the most part however def z_func(x, y): z_solve = scipy.optimize.fsolve(lambda z: x + y + z + np.sin(z), x0=np.zeros_like(x)) return z_solve.tolist()[0] x = np.linspace(-1,1,50) y = np.linspace(-1,1,40) X,Y = np.meshgrid(x,y) X = X.reshape(-1) Y = Y.reshape(-1) Z = z_func(X,Y) fig =plt.figure() ax = plt.axes(projection='3d') ax.plot_wireframe(X, Y, Z, color = 'red') plt.show() now gives me AttributeError: 'float' object has no attribute 'ndim' I've never used Lambda functions before, so I don't know what's going on there, but I can spot a few issues: (1) f is not properly defined as a function. You need a def f(x, y): somewhere. (2) You aren't plotting anything. (3) You probably want a 3D plot, so you will need a ax = fig.add_subplot(projection = '3d') and ax.plot_surface(X, Y, Z). I will post a full answer once I figure out the lambda function part. What are you trying to do, exactly? It might help me understand how to help. ` This gives me "_minpack.error: Result from function call is not a proper array of floats". This is because you're sending 2D arrays (X and Y) in the fsolve function. Try reshaping X and Y before the f() call. X = X.reshape(-1) Y = Y.reshape(-1) You'll come across a second error because the x0 is set to a unique 0 value while it should have the same shape as X and Y. Here is an example (you can flat it as a lambda function if you want): def z_func(x, y): z_solve = scipy.optimize.fsolve(lambda z: x + y + z + np.sin(z), x0=np.zeros_like(x)) return z_solve.tolist()[0] EDIT following the additional information provided in the comments section To plot a 3D wireframe, you will X, Y and Z inputs to be 2D arrays. So the steps would be: keep the 2D shape of either X or Y (same ones) outputted by the meshgrid function, flatten X and Y to get all positions and compute Z for each position. reshape X, Y and Z to the initial 2D shape call ax.plot_wireframe(X, Y, Z) # [...] X, Y = np.meshgrid(x,y) grid_shape = X.shape # same has Y.shape # Flatten X and Y to get all possible positions X = X.reshape(-1) Y = Y.reshape(-1) positions = np.dstack([X, Y])[0] # Compute Z values for each position Z = np.array([f(xpos, ypos) for xpos, ypos in positions]) # Reshape everything to be plotted in 3D axis X = X.reshape(grid_shape) Y = Y.reshape(grid_shape) Z = Z.reshape(grid_shape) fig = plt.figure() ax = plt.axes(projection='3d') ax.plot_wireframe(X, Y, Z, color = 'red') You should get the following figure : Thank you, seem to solves most of the problem however ` def z_func(x, y): z_solve = scipy.optimize.fsolve(lambda z: x + y + z + np.sin(z), x0=np.zeros_like(x)) return z_solve.tolist()[0] x = np.linspace(-1,1,50) y = np.linspace(-1,1,40) X,Y = np.meshgrid(x,y) X = X.reshape(-1) Y = Y.reshape(-1) Z = f(X,Y) fig =plt.figure() ax = plt.axes(projection='3d') ax.plot_wireframe(X, Y, Z, color = 'red') plt.show() ` now gives me AttributeError: 'float' object has no attribute 'ndim' following @Jacob Ivanov comment, please give us more information about what you're trying to plot. I want to plot the function z(x,y) where x + y + z(x,y) + sin(z(x,y)) = 0 using scipy.fsolve in a 3D graph. @flowerlilypad I've updated to answer to my best understanding of what you're trying to achieve Yes, that looks like what I want. Does not seem to work for me though. When I run it I get "ValueError: cannot reshape array of size 1 into shape (40,50)" Did you change Z to be Z = np.array([f(xpos, ypos) for xpos, ypos in positions]) ?
common-pile/stackexchange_filtered
How to define "selected" option of select that serves as AngularJS filter I am pretty experienced with Javascript and jQuery, but I am a total noob with regards to AngularJS. Currently I am filling my model from an $http.get, so in the beginning (after page load) the model is empty. The view for the model is a table, and I use a <select> element to filter this table as follows: <select ng-model="herkunftFilter.herkunft"> <option value="BTRG">BTRG</option> <option value="BTRGMA">BTRGMA</option> <option value="DBLATT">DBLATT</option> <option value="DBLATTMA">DBLATTMA</option> </select> This is the controller. I think it all comes down to applying a specific filter here ... but how do I do that?? var monitoringViewApp = angular.module('monitoringViewApp', []); monitoringViewApp.controller('MonitoringCtrl', function ($scope, $http){ $http.get('api/getmonitorview').success(function(data) { $scope.monitoringTasks = data; // set the filter herkunftFilter.herkunft to be 'BTRG' // but HOW? }); }); With this construct I wanted to preselect the first herkunft content of the data model as the selected option of the <select> element, so that the filter doesn't start empty. But it is empty ... what do I need to do? The <select> works as a filter for these table rows: <tr ng-repeat="task in monitoringTasks | filter:herkunftFilter:true"> <td style="display: none;">{{task.herkunft}}</td> <td style="width: 50%">{{task.task}}</td> <td>{{task.countEingang}}</td> <td>{{task.countInArbeit}}</td> <td>{{task.countFehler}}</td> </tr> Any suggestions as on how can I set a selected option after my model has loaded, so that the filter automatically applies and doesn't stay empty? Try this way <select ng-model="selectedherkunftFilter" ng-options="monitoringTasks.herkunft for monitoringTask in monitoringTasks"> <option ng-if="!selectedherkunftFilter" value="">Select Value</option> </select> It doesn't work like that. The goal seems to be to apply a specific filter in the $http.get callback (success) ... but how?
common-pile/stackexchange_filtered
How to get steamcommunity market item lowest price using Javascript and jQuery? I'm coding from time to time and make scripts for fun and to help others. How can I get JSON from other site? As we know, there are cross-domain restrictions.. This is what I'm trying to get: http://steamcommunity.com/market/priceoverview/?appid=730&currency=3&market_hash_name=StatTrak%E2%84%A2%20M4A1-S%20|%20Hyper%20Beast%20(Minimal%20Wear). I have tried this: $.ajax({ url: 'https://jsonp.afeld.me/?url=http://steamcommunity.com/market/priceoverview/?appid=730&currency=3&market_hash_name=StatTrak%E2%84%A2%20M4A1-S%20|%20Hyper%20Beast%20(Minimal%20Wear)', type: 'GET', dataType: 'jsonp', success: function(data) { console.log(data); } }); I would really appreciate your help. Thanks! :) Do you have any errors or output? Uh, i forgot to mention. I get a GET error with link in script. When i open link from script, I get blank array "[]", i should get "{"success":true,"lowest_price":"65,90\u20ac","volume":"17","median_price":"72,--\u20ac"}" Try to delete this: https://jsonp.afeld.me/?url= and use just URL Then I get error due to cross-domain-policy
common-pile/stackexchange_filtered
C write struct in array I need to make a self made malloc simplified a bit. The memory pool is just an array of unsigned chars. I'm planning on having a struct that is a header, containing the size of the memory block, a flag ('A' for allocated, 'F' for free) and a pointer to the next header (though I guess this isn't necessary because you already have the length of the block) Anywho, I have no idea how to easily store the struct inside the memory pool. This is my current code: #include <stdlib.h> #include <stdio.h> #include "ex1.h" #define POOL_SIZE 500 unsigned char mem_pool[POOL_SIZE]; unsigned char *ptr = &mem_pool[0]; typedef struct header Header; Header h; struct header{ int size; char flag; Header * next; }; void ma_init(){ h = (Header){ .size = POOL_SIZE - sizeof(Header), .flag = 'F', .next = NULL}; } Now ofcourse the h Header is not inside the mem_pool. Logically, int the initialisation it should be mem_pool[0] = (Header){ ..., since this is the first field of the mem_pool. Of course I could put pointers inside the array, but that would sort of ruin the aspec tof having a mem_pool. So how should I store a struct (or whatever) in a certain location of the array? maybe a linked list of allocation records either at the start of the pool or outside of it? Your memory pool is just a blob of allocated memory and you are free to treat and interpret any portion of that memory in any way you want, you just need to be careful in your bookkeeping. So you can declare that the first byte of your memory pool is the first byte of your header struct: struct header *h = (struct header *)mem_pool; h->flag = 'F'; // this will be set after you allocate the first block // you would set it to h + sizeof(struct header) + allocation size h->next = NULL; So as long as you have the start of your blob and your sizes/pointers are correct, you can just continue to cast the appropriate blob of memory as your struct. This only works if mem_pool is correctly aligned for struct header *, otherwise the behaviour is undefined. Since mem_pool is an array of a character type, it might not have the right alignment. One way to ensure mem_pool has the right alignment is to make it be a member of a union that also contains a pointer. Alternatively, if the pool is allocated with malloc that would also work because malloc'd memory is guaranteed to be aligned correctly for any type.
common-pile/stackexchange_filtered
generating data with two variables I'm trying to generate a file, given the number of cars (i) and the arrival time (j), but I can't make the code work properly. For example if want 5 vehicles between depart 0 and 60 [i=5,j=(0,60)] generate something like these: <routes> <vehicle id="left_0" type="typeWE" route="left" depart="8" /> <vehicle id="left_1" type="typeWE" route="left" depart="17" /> <vehicle id="right_2" type="typeWE" route="right" depart="39" /> <vehicle id="up_3" type="typeNS" route="up" depart="50" color="1,0,0"/> <vehicle id="left_4" type="typeWE" route="left" depart="58" /> <routes> This is the code: from __future__ import absolute_import from __future__ import print_function import os import sys import optparse import subprocess import random def generate_routefile(): random.seed(47) N = 800 # number of cars M = 1600 # demand per second from different directions pWE = 1. / 10 pNS = 1. / 30 with open("800_r.rou.xml", "w") as routes: print("<routes>", file=routes) lastVeh = 0 vehNr = 0 for i in range(N): for j in range(M): if random.uniform(0, 1) < pWE: print(' <vehicle id="right_%i" type="typeWE" route="right" depart="%%j" />' % ( vehNr, i, j), file=routes) vehNr += 1 lastVeh = i if random.uniform(0, 1) < pEW: print(' <vehicle id="left_%i" type="typeWE" route="left" depart="%i" />' % ( vehNr, i), file=routes) vehNr += 1 lastVeh = i if random.uniform(0, 1) < pNS: print(' <vehicle id="down_%i" type="typeNS" route="down" depart="%i" color="1,0,0"/>' % ( vehNr, i), file=routes) vehNr += 1 lastVeh = i if random.uniform(0, 1) < pNS: print(' <vehicle id="up_%i" type="typeNS" route="up" depart="%i" color="1,0,0"/>' % ( vehNr, i), file=routes) vehNr += 1 lastVeh = i print("</routes>", file=routes) if __name__ == "__main__": generate_routefile()` The error is line 36, in generate_routefile vehNr, i, j), file=routes) ValueError: unsupported format character 'j' (0x6a) at index 64 I'm trying to add a variable for the arrival time of the vehicles (depart), the code work only wheni is the only variable. This works, but whit this code i can only define the depart value: for i in range(N): if random.uniform(0, 1) < pWE: print(' <vehicle id="right_%i" type="typeWE" route="right" depart="%i" />' % ( vehNr, i), file=routes) vehNr += 1 lastVeh = i but this doesn't, but in this i would define the numbers of cars and the depart time: for i in range(N): for j in range(M): if random.uniform(0, 1) < pWE: print(' <vehicle id="right_%i" type="typeWE" route="right" depart="%j" />' % ( vehNr, i, j), file=routes) vehNr += 1 lastVeh = i I have no idea what SUMO is. Regardless, where exactly is the error occurring? Please [edit] your question and add the full traceback you're getting to it. You are using %j in a format string (next to depart=), and that isn't supported. Please the correct code for your variable type (maybe %d) Which Python version are you running? Instead of %s, %d, %i you can now use f'' or the older but familiar str.format(). you may use format. ' <vehicle id="right_{}" type="typeWE" route="right" depart="{}"'.format(i, j) Ok I see what you mean now. %i is a placeholder for an integer meanwhile %j is not recognized in python. This has nothing to do with i or j. Using %i twice is not a problem. And if we look carefully at the code that does not work: print(' <vehicle id="right_%i" type="typeWE" route="right" depart="%j" />' % ( vehNr, i, j), file=routes) You are trying to insert 3 values but you only have two potential placeholders (%i, %j) (remember %j is an incorrect one). you are right using %i twice is not a problem. but i want to use two variable i and j, and the i variable have to create 100 vehicles rute and the j varible have to take a number between 0 and 1600. Any suggestion how to do it ? @AlexanderMartínez Sorry but I'm not understanding what you mean 100 %. Can you try to update your question? The i in %i refers to the type of value to be displayed (integer); it has absolutely nothing to do with the name of the variable being displayed. "%i" % j is perfectly valid code.
common-pile/stackexchange_filtered
How to click a specific link with jQuery I'm trying to simply click a link whenever someone presses the right arrow key, but nothing is happening. I've got this link: <a title="party pics! 16" href="/photos/photo/new-party-pics-16/" id="next-in-gallery"> <img src="http://localhost/static/photologue/photos/cache/thumbnail16.jpg"> </a> and this jQuery: <script type="text/javascript"> $(document).keydown(function(e){ if (e.keyCode == 39) { $("a#next-in-gallery").click(); return false; } }); </script> Seems to do nothing, though. Thoughts? How about <script type="text/javascript"> $(document).keydown(function(e){ if (e.keyCode == 39) { document.location.href = $("a#next-in-gallery")[0].href; return false; } }); </script> ? That'll do. Thanks! Can't neglect plain old JS. $("a#next-in-gallery").trigger('click'); maybe you have to remove return false; Nope, that doesn't seem to cut it either. http://api.jquery.com/trigger/ look at the first example you see... that's exactly like it. Maybe there's something else changing the behavior of that anchor? Could you try it on different browsers? I haven't tried it on any other browsers, but I'm testing in Chrome, so my confidence is pretty high with that... That's the only JS or jQuery targeting that anchor. I bet it's because the jQuery was above the link and since I didn't do it on ready, it was unable to actually grab the link before it loaded. But then again.. it's a keypress.. so I don't know.
common-pile/stackexchange_filtered
jQuery Sorting a list by span So i have something linke that: <ul id="list"> <li class="item"> <a> <span class="name> name1 </span> </a> <a> <span class="name> name2 </span> </a> <a> <span class="name> name3 </span> </a> </li> </ul> how can i sort this list by the name alphabeticaly? kind regards http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery How is the list built? Is it all client-side? Can you do the sorting on the server-side before the list is rendered? Is it a static list? @aSeptik: He wants to sort by a class name within a span within an anchor. Your example is good for reference but isn't a solution for this question. Try this plugin: http://james.padolsey.com/javascript/sorting-elements-with-jquery/ using a custom comparator, something like this: $('li').sortElements(function(a, b){ return $(a).find('.name').text() > $(b).find('.name').text() ? 1 : -1; }); People are pretty fast with google lol. I came up with that exact link and was just typing an answer when I realized someone has answered already haha. For those wondering before testing, this works exactly as advertised. js file is available here: https://github.com/padolsey-archive/jquery.fn/tree/master/sortElements PS It wasn't case insensitive for me however, so for example Xylophone would appear before rlink in a list, I chained .toLowerCase() to both instances of text() and it appears to be working. demo http://jsbin.com/itudoc/2 $(function() { var names = elements = []; $('.item .name').each(function(i, item) { var name = $.trim($(this).text()) + '_' + i; names[i] = name; elements[name] = $(this).parent().remove().clone(); }); $.each(names.sort(),function(i, item) { $('.item').append(elements[item]); }); }); For simple cases, you don't even need a plugin. This code worked for me to sort a list of links: function sortAlpha(a,b){ return $(a).find('a').text().toLowerCase() > $(b).find('a').text().toLowerCase() ? 1 : -1; }; $('#thelist li').sort(sortAlpha).appendTo('#thelist'); No need for span tags with this method. (the basic idea isn't my own, I copied it from somewhere, but don't remember where from.)
common-pile/stackexchange_filtered
CSS Gradient on Android I'm trying to make this gradient to work on Android but I don't know the right css option. HTML: <div class="bottom-logo"> <div id="logo" class="logo-menu-green">blaa</div> </div> Css: #logo{ font-family: "Lato", "Open Sans"; font-weight: bold; position: absolute; z-index: 999; background: #6699cc; background: -moz-linear-gradient(left, #6699cc 0%, #3399cc 20%, #009999 37%, #009966 52%, #999999 68%, #9933cc 73%, #990099 90%); background: -webkit-gradient(linear, left top, right top, color-stop(0%,#6699cc), color-stop(20%,#3399cc), color-stop(37%,#009999), color-stop(52%,#009966), color-stop(68%,#999999), color-stop(73%,#9933cc), color-stop(90%,#990099)); background: -webkit-linear-gradient(left, #6699cc 0%,#3399cc 20%,#009999 37%,#009966 52%,#999999 68%,#9933cc 73%,#990099 90%); background: -o-linear-gradient(left, #6699cc 0%,#3399cc 20%,#009999 37%,#009966 52%,#999999 68%,#9933cc 73%,#990099 90%); background: -ms-linear-gradient(left, #6699cc 0%,#3399cc 20%,#009999 37%,#009966 52%,#999999 68%,#9933cc 73%,#990099 90%); background: linear-gradient(to right, #6699cc 0%,#3399cc 20%,#009999 37%,#009966 52%,#999999 68%,#9933cc 73%,#990099 90%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#6699cc', endColorstr='#990099',GradientType=1 ); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } I tried but it doesn't work. Thank you. EDIT: A solution would be to use SVG filters. What is version of android? Android 4.2.1 android http://caniuse.com/#search=gradient this version support gradient. Post your HTML+css this code work only in chrome. Property -webkit-text-fill-color: transparent; don't support by other browsers. I think that android 4.2.1 don't support this too http://stackoverflow.com/questions/18403028/cross-browser-css-3-text-gradient android not in IE -ms- or filter: Only solution i can think of after my fair share of issues with Android. Replicate the gradient into a graphical tile, and merely change the following. Took your code and imported it here. Visual file CSS #logo{ font-family: "Lato", "Open Sans"; font-weight: bold; position: absolute; z-index: 999; background-image: url(img/thegradient.jpg); background-repeat: no-repeat; } Also the gradient didn't even appear until i removed these two lines -webkit-background-clip: text; -webkit-text-fill-color: transparent; If this is not what you were looking for i recommend using the javascript method introduced in the comments on your post. Best of luck.
common-pile/stackexchange_filtered
Ms SharePoint 2007 Template Customization After downloading the free templates from Microsoft's site I want to combine some features of two templates together. For example, there is a "Contact Management" template and a "Marketing Site" template. Each template has its own "contacts section/form". Ideally, I want to use both templates on my SharePoint server while having them referring to the same contacts. Again, currently each has its own contacts. I expect this to be a fairly simple task, but I'm fairly new to SharePoint and not sure where to start with this task. I've been looking around, but no luck so far. Any help would be greatly appreciated. Thanks. I'm assuming you're referring to the Fantastic 40 templates that can be downloaded from here. I'd like to say otherwise but unfortunately this isn't a simple task! There is no out-of-the-box way to link two different contacts lists to one set of contacts. You can of course develop such a solution. If you want to get started with programming SharePoint, have a look at this question for some useful resources. This document might also be helpful in researching the templates themselves further.
common-pile/stackexchange_filtered
Deep copy in ES6 using the spread syntax I am trying to create a deep copy map method for my Redux project that will work with objects rather than arrays. I read that in Redux each state should not change anything in the previous states. export const mapCopy = (object, callback) => { return Object.keys(object).reduce(function (output, key) { output[key] = callback.call(this, {...object[key]}); return output; }, {}); } It works: return mapCopy(state, e => { if (e.id === action.id) { e.title = 'new item'; } return e; }) However it does not deep copy inner items so I need to tweak it to: export const mapCopy = (object, callback) => { return Object.keys(object).reduce(function (output, key) { let newObject = {...object[key]}; newObject.style = {...newObject.style}; newObject.data = {...newObject.data}; output[key] = callback.call(this, newObject); return output; }, {}); } This is less elegant as it requires to know which objects are passed. Is there a way in ES6 to use the spread syntax to deep copy an object? See http://stackoverflow.com/questions/27936772/deep-object-merging-in-es6-es7. This is an XY problem. You shouldn't have to work much on deep properties in redux. instead you should just create another reducer that works on the child slice of the state shape and then use combineReducers to compose the two (or more) together. If you use idiomatic redux techniques, your problem of deep cloning objects goes away. "Is there a way in ES6 to use the spread syntax to deep copy an object?". For the general case, impossible. Calling the spread syntax at the top any level overwrites the properties with depth that should have been merged. Does this answer your question? What is the most efficient way to deep clone an object in JavaScript? Does this answer your question? How to Deep clone in javascript No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do. If you really want to deep copy: Use a library. For example, lodash has a cloneDeep method. Implement your own cloning function. Alternative Solution To Your Specific Problem (No Deep Copy) However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function. Specify that all callbacks passed to mapCopy must return new objects instead of mutating the existing object. For example: mapCopy(state, e => { if (e.id === action.id) { return Object.assign({}, e, { title: 'new item' }); } else { return e; } }); This makes use of Object.assign to create a new object, sets properties of e on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary. mapCopy can be really simple now: export const mapCopy = (object, callback) => { return Object.keys(object).reduce(function (output, key) { output[key] = callback.call(this, object[key]); return output; }, {}); } Essentially, mapCopy is trusting its callers to do the right thing. This is why I said this assumes you control all call sites. Object.assign does not deep copy objects. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - Object.assign() copies property values. "If the source value is a reference to an object, it only copies that reference value." Right. This is an alternative solution that does not involve deep copying. I'll update my answer to be more explicit about that. In 2023+ we can use https://developer.mozilla.org/en-US/docs/Web/API/structuredClone Use JSON for deep copy var newObject = JSON.parse(JSON.stringify(oldObject)) var oldObject = { name: 'A', address: { street: 'Station Road', city: 'Pune' } } var newObject = JSON.parse(JSON.stringify(oldObject)); newObject.address.city = 'Delhi'; console.log('newObject'); console.log(newObject); console.log('oldObject'); console.log(oldObject); This only works if you don't need to clone functions. JSON will ignore all functions so you won't have them in the clone. Aside from functions, you'll have issues with undefined and null using this method You'll also have issues with any user-defined classes, since prototype chains are not serialized. Your solution using JSON serialization has some problems. By doing this you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object. Also, some objects are converted to strings, like Date, Set, Map, and many others. I was having a horrible nightmare of trying to create a true copy of an array of objects - objects which were essentially data values, no functions. If that is all you have to worry about, then this approach works beautifully. Plz consider adding comments info in the answer otherwise it might develop wrong base of knowledge for beginners. If address does not exist, and you attempt to set newObject.address.city you will get an error. This is such a brilliant hack I find structuredClone https://developer.mozilla.org/en-US/docs/Web/API/structuredClone moves the needle slightly, the approach made popular by lodash(cloneDeep) is still the most stable and consistent; especially with Functions (you can rework it with generators to yield some perf gains too). I don't advise using the example from the OP unless it's just demo code, data type losses and various other caveats tend to always crop up. From MDN Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax). Personally, I suggest using Lodash's cloneDeep function for multi-level object/array cloning. Here is a working example: const arr1 = [{ 'a': 1 }]; const arr2 = [...arr1]; const arr3 = _.clone(arr1); const arr4 = arr1.slice(); const arr5 = _.cloneDeep(arr1); const arr6 = [...{...arr1}]; // a bit ugly syntax but it is working! // first level console.log(arr1 === arr2); // false console.log(arr1 === arr3); // false console.log(arr1 === arr4); // false console.log(arr1 === arr5); // false console.log(arr1 === arr6); // false // second level console.log(arr1[0] === arr2[0]); // true console.log(arr1[0] === arr3[0]); // true console.log(arr1[0] === arr4[0]); // true console.log(arr1[0] === arr5[0]); // false console.log(arr1[0] === arr6[0]); // false <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> arr6 is not working for me. In browser (chrome 59.0 which supports ES6 I get Uncaught SyntaxError: Unexpected token ... and in node 8.9.3 which supports ES7 I get TypeError: undefined is not a functionat repl:1:22 @AchiEven-dar not sire why you got an error. You may run this code directly in stackoverflow by pressing the blue button Run code snippet and it should run correctly. arr6 is not working for me too. In browser - chrome 65 arr6 might compile in some implementations, it just never does what author expected it to do. I often use this: function deepCopy(obj) { if(typeof obj !== 'object' || obj === null) { return obj; } if(obj instanceof Date) { return new Date(obj.getTime()); } if(obj instanceof Array) { return obj.reduce((arr, item, i) => { arr[i] = deepCopy(item); return arr; }, []); } if(obj instanceof Object) { return Object.keys(obj).reduce((newObj, key) => { newObj[key] = deepCopy(obj[key]); return newObj; }, {}) } } This function is the fastest! Result from benchmark: jsonparsejsonstringify x 5,662 ops/sec ±2.79% (91 runs sampled) structuredClone x 6,755 ops/sec ±2.76% (85 runs sampled) lodash_cloneDeep x 2,008 ops/sec ±2.74% (92 runs sampled) deepCopyFunction x 26,257 ops/sec ±2.82% (86 runs sampled) Fastest is deepCopyFunction You can use structuredClone() like the following: const myOriginal = { title: "Full Stack JavaScript Developer", info: { firstname: "Javascript", surname: " Addicted", age: 34 } }; const myDeepCopy = structuredClone(myOriginal); structuredClone() You can use structuredClone() that is a built-in function for deep-copying. Structured cloning addresses many (although not all) shortcomings of the JSON.stringify() technique. Structured cloning can handle cyclical data structures, support many built-in data types, and is generally more robust and often faster. However, it still has some limitations that may catch you off-guard: 1-Prototypes : If you use structuredClone() with a class instance, you’ll get a plain object as the return value, as structured cloning discards the object’s prototype chain. 2-Functions: If your object contains functions, they will be quietly discarded. 3- Non-cloneables: Some values are not structured cloneable, most notably Error and DOM nodes. It will cause structuredClone() to throw. const myDeepCopy = structuredClone(myOriginal); JSON.stringify If you simply want to deep copy the object to another object, all you will need to do is JSON.stringify the object and parse it using JSON.parse afterward. This will essentially perform deep copying of the object. let user1 = { name: 'Javascript Addicted', age: 34, university: { name: 'Shiraz Bahonar University' } }; let user2 = JSON.parse(JSON.stringify(user1)); user2.name = 'Andy Madadian'; user2.university.name = 'Kerman Bahonar University' console.log(user2); // { name: 'Andy Madadian', age: 33, university: { name: 'Kerman Bahonar University' } } console.log(user1); // { name: 'Javascript Addicted', age: 33, university: { name: 'Shiraz Bahonar University' } } Spread operator / Object.assign() One way to create a shallow copy in JavaScript using the object spread operator ... or Object.assign() like the following: const myShallowCopySpread = {...myOriginal}; const myShallowCopyObjectAssign=Object.assign({},obj) Performance When it comes to performance the creator Surma has pointed out that JSON.Parse() can be a bit faster for small objects. But when you have a large object, complex object structuredClone() starts to get significantly faster. Browser support is pretty fantastic And even is supported by Node.js. Unfortunately Object.assign and spread operator doesn't work when object has functions. @Vishal Kumar Sahu- It's your right. In some cases, you have to try the other ways. such as structuredClone() const a = { foods: { dinner: 'Pasta' } } let b = JSON.parse(JSON.stringify(a)) b.foods.dinner = 'Soup' console.log(b.foods.dinner) // Soup console.log(a.foods.dinner) // Pasta Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that. Here's my deep copy algorithm. const DeepClone = (obj) => { if(obj===null||typeof(obj)!=='object')return null; let newObj = { ...obj }; for (let prop in obj) { if ( typeof obj[prop] === "object" || typeof obj[prop] === "function" ) { newObj[prop] = DeepClone(obj[prop]); } } return newObj; }; You also need to check if 'obj[prop]!==null' as typeof(null) also return 'object' // use: clone( <thing to copy> ) returns <new copy> // untested use at own risk function clone(o, m){ // return non object values if('object' !==typeof o) return o // m: a map of old refs to new object refs to stop recursion if('object' !==typeof m || null ===m) m =new WeakMap() var n =m.get(o) if('undefined' !==typeof n) return n // shallow/leaf clone object var c =Object.getPrototypeOf(o).constructor // TODO: specialize copies for expected built in types i.e. Date etc switch(c) { // shouldn't be copied, keep reference case Boolean: case Error: case Function: case Number: case Promise: case String: case Symbol: case WeakMap: case WeakSet: n =o break; // array like/collection objects case Array: m.set(o, n =o.slice(0)) // recursive copy for child objects n.forEach(function(v,i){ if('object' ===typeof v) n[i] =clone(v, m) }); break; case ArrayBuffer: m.set(o, n =o.slice(0)) break; case DataView: m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.byteLength)) break; case Map: case Set: m.set(o, n =new (c)(clone(Array.from(o.entries()), m))) break; case Int8Array: case Uint8Array: case Uint8ClampedArray: case Int16Array: case Uint16Array: case Int32Array: case Uint32Array: case Float32Array: case Float64Array: m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.length)) break; // use built in copy constructor case Date: case RegExp: m.set(o, n =new (c)(o)) break; // fallback generic object copy default: m.set(o, n =Object.assign(new (c)(), o)) // recursive copy for child objects for(c in n) if('object' ===typeof n[c]) n[c] =clone(n[c], m) } return n } Comments are in the code for those looking for explanation. Here is the deepClone function which handles all primitive, array, object, function data types function deepClone(obj){ if(Array.isArray(obj)){ var arr = []; for (var i = 0; i < obj.length; i++) { arr[i] = deepClone(obj[i]); } return arr; } if(typeof(obj) == "object"){ var cloned = {}; for(let key in obj){ cloned[key] = deepClone(obj[key]) } return cloned; } return obj; } console.log( deepClone(1) ) console.log( deepClone('abc') ) console.log( deepClone([1,2]) ) console.log( deepClone({a: 'abc', b: 'def'}) ) console.log( deepClone({ a: 'a', num: 123, func: function(){'hello'}, arr: [[1,2,3,[4,5]], 'def'], obj: { one: { two: { three: 3 } } } }) ) If the Object.prototype or any other prototype object in the chain has enumerable properties your cloned object will have those properties as its own. Don't use in for an object properties iteration. function deepclone(obj) { let newObj = {}; if (typeof obj === 'object') { for (let key in obj) { let property = obj[key], type = typeof property; switch (type) { case 'object': if( Object.prototype.toString.call( property ) === '[object Array]' ) { newObj[key] = []; for (let item of property) { newObj[key].push(this.deepclone(item)) } } else { newObj[key] = deepclone(property); } break; default: newObj[key] = property; break; } } return newObj } else { return obj; } } const cloneData = (dataArray) => { newData= [] dataArray.forEach((value) => { newData.push({...value}) }) return newData } a = [{name:"siva"}, {name:"siva1"}] ; b = myCopy(a) b === a // false` I myself landed on these answers last day, trying to find a way to deep copy complex structures, which may include recursive links. As I wasn't satisfied with anything being suggested before, I implemented this wheel myself. And it works quite well. Hope it helps someone. Example usage: OriginalStruct.deep_copy = deep_copy; // attach the function as a method TheClone = OriginalStruct.deep_copy(); Please look at https://github.com/latitov/JS_DeepCopy for live examples how to use it, and also deep_print() is there. If you need it quick, right here's the source of deep_copy() function: function deep_copy() { 'use strict'; // required for undef test of 'this' below // Copyright (c) 2019, Leonid Titov, Mentions Highly Appreciated. var id_cnt = 1; var all_old_objects = {}; var all_new_objects = {}; var root_obj = this; if (root_obj === undefined) { console.log(`deep_copy() error: wrong call context`); return; } var new_obj = copy_obj(root_obj); for (var id in all_old_objects) { delete all_old_objects[id].__temp_id; } return new_obj; // function copy_obj(o) { var new_obj = {}; if (o.__temp_id === undefined) { o.__temp_id = id_cnt; all_old_objects[id_cnt] = o; all_new_objects[id_cnt] = new_obj; id_cnt ++; for (var prop in o) { if (o[prop] instanceof Array) { new_obj[prop] = copy_array(o[prop]); } else if (o[prop] instanceof Object) { new_obj[prop] = copy_obj(o[prop]); } else if (prop === '__temp_id') { continue; } else { new_obj[prop] = o[prop]; } } } else { new_obj = all_new_objects[o.__temp_id]; } return new_obj; } function copy_array(a) { var new_array = []; if (a.__temp_id === undefined) { a.__temp_id = id_cnt; all_old_objects[id_cnt] = a; all_new_objects[id_cnt] = new_array; id_cnt ++; a.forEach((v,i) => { if (v instanceof Array) { new_array[i] = copy_array(v); } else if (v instanceof Object) { new_array[i] = copy_object(v); } else { new_array[i] = v; } }); } else { new_array = all_new_objects[a.__temp_id]; } return new_array; } } Cheers@! I would suggest using the spread operator. You'll need to spread a second time if you need to update the second level. Attempting to update the newObject using something like newObject.address.city will throw an error if address did not already exist in oldObject. const oldObject = { name: 'A', address: { street: 'Station Road', city: 'Pune' } } const newObject = { ...oldObject, address: { ...oldObject.address, city: 'Delhi' } } console.log(newObject) this is also the recommened way for react, but i requires knowledge of the object: https://beta.reactjs.org/learn/adding-interactivity#updating-objects-in-state This is a very old question but I think in 2022 there are many ways to solve this. However, if you want a simple, fast and vanilla JS solution check this out: const cloner = (o) => { let idx = 1 const isArray = (a) => a instanceof Array const isObject = (o) => o instanceof Object const isUndefined = (a) => a === undefined const process = v => { if (isArray(v)) return cloneArray(v) else if (isObject(v)) return cloneObject(v) else return v } const register = (old, o) => { old.__idx = idx oldObjects[idx] = old newObjects[idx] = o idx++ } const cloneObject = o => { if (!isUndefined(o.__idx)) return newObjects[o.__idx] const obj = {} for (const prop in o) { if (prop === '__idx') continue obj[prop] = process(o[prop]) } register(o, obj) return obj } const cloneArray = a => { if (!isUndefined(a.__idx)) return newObjects[a.__idx] const arr = a.map((v) => process(v)) register(a, arr) return arr } const oldObjects = {} const newObjects = {} let tmp if (isArray(o)) tmp = cloneArray(o) else if (isObject(o)) tmp = cloneObject(o) else return o for (const id in oldObjects) delete oldObjects[id].__idx return tmp } const c = { id: 123, label: "Lala", values: ['char', 1, {flag: true}, [1,2,3,4,5], ['a', 'b']], name: undefined } const d = cloner(c) d.name = "Super" d.values[2].flag = false d.values[3] = [6,7,8] console.log({ c, d }) It's recursive and self-contained, all the functions needed are defined in the function cloner(). In this snippet we are handling Array and Object types if you want to add more handlers you can add specify handlers like Date and clone it like new Date(v.getTime()) For me Array and Object are the types that I use the most in my implementations. This doesn't clone arrays with properties. Here is my approach for DeepCopy/DeepMerge to overcome limitations of Object.assign for the objects with function. Helper = { isObject(obj) { return obj !== null && typeof obj === 'object'; }, isPlainObject(obj) { return Helper.isObject(obj) && ( obj.constructor === Object // obj = {} || obj.constructor === undefined // obj = Object.create(null) ); }, mergeDeep(target, ...sources){ if (!sources.length) return target; const source = sources.shift(); if (Helper.isPlainObject(source) || Array.isArray(source)) { for (const key in source) { if (Helper.isPlainObject(source[key]) || Array.isArray(source[key])) { if (Helper.isPlainObject(source[key]) && !Helper.isPlainObject(target[key])) { target[key] = {}; }else if (Array.isArray(source[key]) && !Array.isArray(target[key])) { target[key] = []; } Helper.mergeDeep(target[key], source[key]); } else if (source[key] !== undefined && source[key] !== '') { target[key] = source[key]; } } } return Helper.mergeDeep(target, ...sources); }, }
common-pile/stackexchange_filtered
Two teenagers tinker with quantum simulation software after school. The weirdest part isn't that the particles are connected—it's that measuring one literally determines the other's state instantly, no matter the distance. But that violates relativity, right? Nothing travels faster than light, so how can the correlation be instantaneous? That's the beauty of non-locality. No information actually travels between them. Think of it like this—when we create a Bell state, we're putting two particles in superposition where they're both spin-up and spin-down simultaneously. Until measurement collapses the wavefunction. But here's what I don't get—if I measure particle A as spin-up along the z-axis, particle B becomes spin-down. What if I had measured A along the x-axis instead? That's where Bell's inequality comes in. If particles had predetermined hidden variables—like little instruction sets saying "be spin-up if measured along z, spin-down if measured along x"—then measurements along different axes would satisfy certain statistical bounds. But they don't. The correlations violate those bounds, proving the particles genuinely don't have definite properties until measured. Exactly. And that's not just theoretical anymore. The violation shows up in real experiments with photons, electrons, even larger systems. What about entanglement transfer? I read that you can move entanglement along a chain of particles through interactions. Right, like in spin chains with Heisenberg coupling. If you have three particles and entangle the first two, the interaction can gradually transfer that entanglement to particles two and three, while particle one becomes disentangled. The oscillations in correlation functions show it moving back and forth. It's almost like entanglement is a resource that can be redistributed rather than just created or destroyed. That has huge implications for quantum computing. You could use those transfer mechanisms to route quantum information between different parts of a processor without direct connections. And for error correction too. If entanglement gets degraded in one location, you might be able to redistribute it from healthier parts of the system. The math gets crazy though. Once you go beyond simple two-particle Bell states, the tensor product spaces explode in complexity. But that's also why quantum systems can encode so much information. A classical bit is just
sci-datasets/scilogues
REST API Limits documentation/explanation, specifically 'PermissionSets' -> 'CreateCustom'? For the most part I can use common sense and deduce Salesforce's REST Api limits. For example, "DailyWorkflowEmails" = "Daily workflow emails" and "DailyAsyncApexExecutions" = "Daily asynchronous Apex method executions (batch Apex, future methods, queueable Apex, and scheduled Apex)"... However I wanted to further understand some of the data - I couldn't find it specifically called out in in the documentation... Specifically the 'CreateCustom' within the 'PermissionSets'. Any idea the differences between these two? The 'PermissionSets' are how many Permission Sets are in the org (Note: standard permission sets that come with manage packages count against you in this respect.) The 'CreateCustom' is simply the Custom Permissions within a particular created permission set. Below is a screenshot and Salesforce's documentation around these: https://help.salesforce.com/articleView?id=perm_sets_custom_perms.htm&type=5 https://help.salesforce.com/articleView?id=custom_perms_overview.htm&type=5 However I see that there are two sObjects in the system called CustomPermission and CustomPermissionDependency - which has 0 records in my org. However I'm curious as to why that differs from the 88 the REST API says that I used up. I'll specifically ask Salesforce Support this and post back.
common-pile/stackexchange_filtered
Trying to filter and map to output unique values Is the code below possible if it is manipulated correctly, it's currently not working for me, i also maybe be going about it the wrong way? Trying to filter and then map so that I can avoid duplicate 'Subnames' App.js render() { const results = !this.state.resultFound ? null : this.state.search.filter((item, index) => this.state.search.indexOf(item) === index).map(item => ( <Search key={item.key} subname={item.subname} clickedSub={() => this.getUniqueSubs2(item)} /> )) ) return ( <div> {results} </div> ) } Search.js const search = (props) => { return ( <button onClick={props.clickedSub}> {props.subname} </button> ) } indexOf method will not work properly since you are not operating over primitive values but on objects. The strict comparison === will fail in this case. You could try e.g. Array#reduce to get rid of the dupes. const arr = [{ subname: 'foo', name: 'a' }, { subname: 'boo', name: 'b' }, { subname: 'foo', name: 'c' }]; const r = Object.values( arr.reduce((s, a) => (a.subname in s ? a : s[a.subname] = a, s), {}), ); console.log(r); Could you explain what the purpose of "=a, s)" is? got lost there @Prav Yeah, sure - , s) is just a comma expression - it works the same if you just would write return s; Echo of indexOf not working on objects, but an example with filter, indexOf, and map. let search = [{ key: 1, subname: 'a' }, { key: 2, subname: 'a' }, { key: 3, subname: 'b' }, { key: 4, subname: 'b' }] let seen = []; let result = search.filter((item, index) => { if (seen.indexOf(item.subname) === -1) { seen.push(item.subname) return false } return true }) .map(o => ({ newValue: 'abc', ...o })) document.querySelector('#test').innerHTML = JSON.stringify(result) <h1 id='test'></h1>
common-pile/stackexchange_filtered
Update Asset Indexes gives "getFileList() is not implemented" Thank you in advance for any tips on this. Barely-related-background: I made a mistake on my development machine. In gparted, I chose "ignore" instead of "cancel". This is called 'choosing poorly'. Anyway, I now have freshly reinstalled my OS, apache, php, etc. Now, as the title says, when I click "Update Asset Indexes" it gives a popup saying getFileList() is not implemented Any suggestions what I need to do? This exception in thrown in the class craft\volumes\MissingVolume that states one of your Volumes has an invalid class /** * @inheritdoc */ public function getFileList(string $directory, bool $recursive): array { throw new NotSupportedException('getFileList() is not implemented.'); } Maybe you uninstalled a plugin that adds a certain Volume class like S3 or something? Thank you, Robin. If I disable all plugins, the problem persists. The only installed plugins, by the way, are Redactor, Wordsmith, Environment Label, Element Index Defaults, and my own calendar plugin. Could it be something other than a plugin? Disabling a plugin causes the issue... You should check all volumes and ther classes/types. You can also go into your DB and check if there is anything besides a local volume OK, yes, you nailed it. In Craft2 we had used S3 as a volume for a while, but then stopped using it but left it there, but Craft3 requires (and offers) a plugin for S3, and I didn't have the plugin. So for this case, I just deleted the unneeded S3 volume and all fixed.
common-pile/stackexchange_filtered
How to create a static library with g++? Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the .a? I would also like to know how can I compile a static library in and use it in other .cpp code. I have header.cpp, header.hpp . I would like to create header.a. Test the header.a in test.cpp. I am using g++ for compiling. You can create a .a file using the ar utility, like so: ar crf lib/libHeader.a header.o lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do: mkdir lib Then run the above ar command. When linking all libraries, you can do it like so: g++ test.o -L./lib -lHeader -o test The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link. where test.o is created like so: g++ -c test.cpp -o test.o and what is with lib/libHeader.a? ar rcs ...isn't it better than ar crf? @linuxx: main.o will be the object file you create out of main.cc @linuxx: the exact flags you use with the ar utility are your decision based on your requirements. Looking up the man pages for ar would be a good idea. how to test the library using test.cpp? Replace main in the above code with test and C with cpp. In other words, my main.C (that I have used for illustration) and your test.cpp are, in all likelihood, equivalent. Can you please tell me what is main.o? In my code i have header.cpp, header.h and the test.cpp(the code where i would like to test the header.a library). Wouldn't it be -lHeader instead of -llibHeader ? This is a great answer and he have OP more than he asked for Create the .o (as per normal): g++ -c header.cpp Create the archive: ar rvs header.a header.o Test: g++ test.cpp header.a -o executable_name Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written: g++ test.cpp header.cpp -o executable_name Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules. How do we include multiple modules? Good one! Sometimes we see ranlib which in GNU simply means ar s.
common-pile/stackexchange_filtered
Is there an adverse impact to deleting a question so quickly that the OP may not see it? Here's a question that was deleted in record time: https://stackoverflow.com/questions/46433927/why-doesnt-the-else-statement-work This of course is a rite of passage for every C and C++ programmer, using = instead of == in an if statement. Of course it should be closed (although I'd rather see it flagged as a dupe instead of a typo). But if it's deleted before the OP gets a chance to see the outcome, how will they figure out what they did wrong? Aren't we just inviting them to ask the question again? I thought we were supposed to let the Roomba get around to deleting questions in due time. I would worry less about this if I knew the OP could see their question along with the comments and answers even after it was deleted. Can they? A user will see their own deleted posts, but only for a limited time. The OP can see deleted questions in the past 60 days if they hit the checkbox on their question list. As for manually deleting the question it had a answer that was up voted which I believe stops the roomba. @NathanOliver thanks for that explanation of the manual delete. I updated your title. It's really not about if the OP can see their deleted questions or not, it's more about the lingering after-effects. @gunr2171 They can see their own deleted questions forever. They only have a page linking them to the question temporarily. @Makoto but the question in the title was the one I really wanted to know the answer to. And now I do. @NathanOliver: Roomba looks at total score, not up/down as individual metrics. A zero or negative scored answer would still trip the Roomba. @MarkRansom: Edit the body of your question around that premise then. @Makoto Cool. TIL. Unfortunately the question would attract answers, and since the answers are almost guaranteed to be correct, they'll attract upvotes, which results in the question never being deleted due to it having an answer that the community has indicated is useful. Deleting it with delete votes bypasses that possibility. @KevinB: Maybe you should codify that as an actual answer instead of a comment. well, it's not an adverse effect to deleting it quickly, it's an adverse effect to not deleting it quickly. Can the OP of the question see the answers to the question if the question is deleted? I know they can see the comments, but i'm unsure of the answers, since the answers are reported as being deleted at that point as well. @KevinB Yes. The answerers on the other hand can't, even if they have a link. @NathanOliver I know they used to not be able to, but I thought that was changed. @KevinB how do you mean "Unfortunately the question would attract answers"? It must be closed to vote to delete and then in that state it needs 5 people to vote to reopen it before answers can be given. @MartinSmith right. if it doesn't get closed quickly, it'll attract answers. That's irrelevant to the Q here. The Q here is about quick deletions not closures. @MartinSmith deletion is impossible if it isn't closed. Yes, closing is a necessary prerequisite for a question being deleted by community vote. Once it is closed no answers can be given. So why is it necessary to rush to delete it? Your comment about "Unfortunately the question would attract answers" is solved by closing not by deleting. Deletion happens when votes are applied to the Q after it is already in a state where no answers can be given. the sample question is a typo question. completely useless. quick closure is necessary if the question is to be closed before it receives answers, answers that would prevent said useless question from being collected via the roomba @Kevin, you keep talking about closure. No one here is talking about closure; they're talking about deletion. Obviously the question needs to be closed. The issue is, does it need to be immediately deleted after it's closed? immediately, maybe not, but if it has upvoted answers... manual deletion is the only alternative to leaving it sitting around forever. doing it while it is active has the best chance for it actually happening. Possible duplicate of What is Stack Overflow’s goal? as they said in duplicate, "You have it backwards, I think..." I honestly don't give a sh!t about what question askers get or miss. I use Stack Overflow to solve my programming problems. I search for solutions to these in Google and I want my searches to return meaningful results and I don't want my searches to return garbage left at the site because someone felt a pity about next brainless asker who didn't bother to check for duplicates Exactly. it's certainly not the situation that always occurs, but if the question isn't closed fast enough (very common), we're often left with correct, upvoted, useless answers to a useless question with a title that will more often than not attract users that have a different problem. the only way to remove said useless question + answers at that point is deletion. But if it's deleted before the OP gets a chance to see the outcome Lets debunk several things wrong with this sentence: The author can always see their deleted post. Always. What the author can't see is the list of their deleted posts which were deleted after 60 days. Inbox notifications are only invalidated if the content that caused those notifications is deleted. All in all, OP do always get the chance to see the outcome: that their question was closed and deleted. So that's not a problem. how will they figure out what they did wrong? Since above is not true, this question is irrelevant. They can figure out. It will be on their deleted post. Aren't we just inviting them to ask the question again? I've seen cases where OP keep asking the same question, again and again, since they don't get an answer. We aren't making it more likely as they got their response: do your homework before asking. I thought we were supposed to let the Roomba get around to deleting questions in due time. Roomba is just a convenience given our short attention spans. Also, that it's a freaking drag to go back to the questions that were closed 2 days ago just to delete them. Roomba allows you to fire-and-forget your close votes and concentrate on the questions that can at least be fleshed out. Also, we were given delete votes for deleting post. We are allowed to vote to delete immediately if the score is -3 or less. Not using the moderating power within the confines of what it is allowed when we feel it's warranted is several times worse. See this little fun page screen shot and read this blog post. So, no, you are not supposed to wait for roomba. I would worry less about this if I knew the OP could see their question along with the comments and answers even after it was deleted. Can they? They can't see the answers on their deleted questions, as the answers aren't theirs (unless they got 10k and can see everyone deleted post). Comments and their own questions are visible. You may consider changing the answer from 1st person to 3rd person, so that you don't give the impression that you have earned the privilege to delete posts (10K), let alone to instantly delete them (20K), when you clearly have not. @user000001 I've earned that privilege on other sites. Also, that's irrelevant. "We" here is the community. Let me offer this from a different perspective: a code consumer I have an error. I do the right thing and Google it. I get a page filled with question after question asking the same thing over and over. Worse, a lot of them are junky answers to the question. They point out a typo and that's it. As Shog9 noted years ago it sucks to find your answer is in another castle. We delete link-only answers as Low Quality. But not deleting some of these low quality questions is creating the exact same situation. Just how many questions are we going to force users to sort through find that really useful question with a great answer? In many cases the answer is 0. Slap it into another question and let SO sort it out. So we did. We closed it as a typo and deleted it. Maybe a duplicate would have been more useful, but exactly how many signposts does one need? It's important to note that deletion is harder than closure (immediate deletion requires a -3 and 3 20k+ users), and we don't have as many delete votes as closed. Most closed questions never get deleted (fun fact: accept or upvote an answer and it will not Roomba). In fact, many bad questions don't even get closed. At the end of the day we're about signal-to-noise. SO succeeds because we keep it that way. I get annoyed trying to find an answer in nothing but noise. That's why SOCVR exists. It's also why I voted to delete the example question. I've raised this issue on SO CVR before, since a number of quick deletions are organised there. I've objected to it in chat, because it seems to be a good way to get a new user to feel really defeated: a closed question can be recovered, but a closed and deleted one feels rather mean, even though that is rarely the intent of the delete-voters. Cast delete votes on old questions, by all means, but otherwise I think brand new questions that are closed quickly should just wait for the Roomba. Even if the OP tries to edit it to improve it, and it is still off-topic, I am not sure deletion is appropriate, since that prevents anyone from giving advice in the comments. (Aside: I should say I am in favour of SO CVR generally, and participate from time to time in raising and processing collaborative close requests. I think everyone in the room is community-minded and well-intentioned, and I just disagree on this small part of an otherwise good process). The SOCVR isn't about "deletions". It's about streamlining the process of closing questions. Well indeed @Cerbrus, but some immediate deletions are organised there ([tag:del-pls]) Only for the exceptionally bad cases, though. Certaily not "a lot" The only time I've seen (or made) a deletion recommendation for a post that would've been roomba'd is when it was clearly OT and could not be saved (and I wanted my downvotes back). Like this. Is there an adverse impact here? (@SotiriosDelimanolis: Yay meta effect) heh, OT (referring to the linked question), but i find it humorous that there's a jobs area on SO while we don't allow jobs questions on SO. The undelete vote is a joke, right? Damn.... I agree; this is a problem. Too many people are abusing deletion as a sort of "super-downvote", a way to take out their (quite reasonable) frustration with these types of questions. The correct way to deal with these questions is to close them (either as a duplicate or some other reason, but duplicate is probably preferable, if a good target exists) and downvote them. That serves all required purposes: it gives the asker feedback, it gives the system feedback, it stops the question from being pushed into the faces of potential answerers, it prevents an influx of duplicate and/or similarly low-quality answers, and probably more things that I'm forgetting. Rapid, manual deletion of these questions simply isn't necessary, and generally does more harm than good. As others have pointed out in the comments, questions that have been closed and are zero- or negatively-scored will be automatically deleted in due time by a cleanup process (one we affectionately refer to as the Roomba). If you delete it sooner than that, you prevent the person from actually receiving the feedback we're trying to give them. (Yes, users can see their own deleted questions, but only if they know how to find them. Users who are new to the site probably don't know how. Anecdotal evidence certainly suggests that they do not.) Deleting it sooner, rather than later, doesn't help push the asker any further toward a question-ban. In fact, if you're really cynical, you'd say that it can only hurt, because deleted questions can't receive additional downvotes. If you're optimistic, it means that the person can't learn from their mistakes and can't even fix the question, transforming it into something that does meet our guidelines. Stop trying to "punish" people by deleting their low-quality questions. The only questions you need to be deleting immediately after closure are questions that are actively causing harm. Another beginner or typo question is not actively causing harm—not once it's closed and downvoted. I'll even go one step further: the overzealous deletion of duplicate questions is harmful. I'm starting to see that a lot, especially in certain tags. (I won't call out names here; I'm hoping you know who you are). The whole point of duplicates is to serve as sign posts to the master question, where all the good answers are collected. If you go around prematurely deleting these duplicate stubs, you're only shooting ourselves in the collective foot, because you increase the chances that people will ask more duplicates because they were unable to find the answer they were looking for, using whatever bogus search terms they happened to type in. "Unfortunately the question would attract answers, and since the answers are almost guaranteed to be correct, they'll attract upvotes, which results in the question never being deleted due to it having an answer that the community has indicated is useful. Deleting it with delete votes bypasses that possibility." (source: Kevin B). The deletion often isn't really to "punish" the OP, but to prevent other people from gaining form the bad question, by answering it. @Cerbrus If the question is closed, then it cannot be answered, making that irrelevant. Cody, those easy questions often get somewhere between 3-10 answers before it's closed. Sure, the answers are correct, and everyone knows they are, because it's yet another duplicate, so those answers will still gather upvotes while the question is closed, while preventing the roomba from doing it's job. That's why those questions are being deleted. To stop people from profiting from, basically, junk. @CodyGray but duplicate is probably preferable, if a good target exists Piggybacking off of Cerbrus' comment, I disagree with your answer, if the question is one that has a dozen signposts already, one more is just noise, and also noise that inadvertently rewards some FGITW answerer with a few rep they probably shouldn't have gained. Though that is another question... are people allowed to 'profit' on SO for knowing and answering something that's been known and answered before? Or is rep only deserved for truly new solutions, like in the fields of science? If this were a question with no upvoted answers, and one that hasn't been asked a ton of times before, I would agree with you; mark it as a duplicate and let the system take care of it in due time. Clearly I am missing something. It was a question with no upvoted answers. Yes, if a question has a dozen signposts already, then it probably isn't useful, but that's frequently not the case in the deletions I've looked at, and certainly wasn't the case in the question in question. I will admit I'm not terribly concerned about stopping people from earning reputation from contributing answers that are perceived as useful. Bad questions being on the site does harm by junking up search results. Removing bad questions is not intended to punish a user for harming the site; it's intended to prevent the harm. Signposts are basically only good for the title, and only as valuable as that title. Not to mention, there are many other good reasons to close and delete a question quickly, besides duplication. In particular, typo questions can only be useful signposts if a canonical exists, which requires the typo not to be idiosyncratic. One's own deleted question is normally easy to find for a user who actually cares. In fact, it's trivial if the user cared enough to leave a browser tab open to refresh and wait for an answer.
common-pile/stackexchange_filtered
JS Client Side Cookies Prematurely Expire on Mobile Browsers I have a web-page that uses cookies. I've set the expiry on the cookies to 365 days and in the developer console I can see that the expiry is correct. But only on mobile the cookies expire within about a week, instead of a year. From what I've read this has to do with mobile browser sessions but I didn't find a viable solution using JQuery or vanilla JS. If possible I would like to refrain from switching over to client side session storage. This is the way I set my cookies: var setCookie = function(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires +" ;"/*path=/"/;*/ } Taken from here: https://www.w3schools.com/js/js_cookies.asp Upon further inspection the problem appears to only occur on ios. I've Come Across This Thread https://stackoverflow.com/questions/46774629/cookie-persistence-in-ios-safari-chrome Which stated that domain is required when defining ios cookies and without it they would not be presistent.
common-pile/stackexchange_filtered
Unable to Decode Custom IPv6 Security Header During Reassembly I am currently working on securing IPv6 packet fragments using a custom security header that contains cryptographic information, such as a MAC and nonce. Here is the overall process I am following: Fragmentation Process: 1. Break the Packet into Fragments: The packet is split based on the network's MTU. Each fragment includes: a) Standard IPv6 header Standard Fragment Header b) A custom Security Header containing: - MAC: Ensures payload integrity. - Nonce: Unique identifier for each packet. - Security Type: Flag indicating encryption or authentication. 2. Attach the Headers and Send Fragments: Each fragment includes the custom Security Header (serialized as JSON) and the payload. ``` Reassembly Process: 1.Fragments are received in no specific order. 2. Each fragment's custom Security Header is parsed and verified: - MAC verification using HMAC-SHA256. - Nonce consistency check to ensure fragments belong to the same packet. 3.Once all fragments are verified, they are buffered, sorted, and reassembled. ``` The Issue: During reassembly, I am unable to decode the custom Security Header properly. The reassembly logic fails when parsing the header from the fragment payload. Fragmentation logic: from scapy.all import * import hashlib import hmac import json import os # Function to generate a MAC for fragment integrity def generate_mac(data, key): """Generate HMAC-SHA256 for integrity.""" return hmac.new(key.encode(), data, hashlib.sha256).hexdigest() # Function to create a custom IPv6 Security Extension Header (serialized as JSON) def create_security_header(nonce, mac, encryption_flag): """Create a custom security header and serialize it.""" header = { "Next Header": 44, # Fragment Header "Header Length": 4, # Example fixed size (4 = 32 bytes) "Security Type": 1, # 1 = MAC-based integrity "Encryption Flag": encryption_flag, "Nonce": nonce, "MAC": mac } return header # Return the header dictionary # Function to fragment an IPv6 packet and save the fragments to a PCAP file def fragment_packet(packet, max_size, filename, key="secretkey"): """ Fragment the packet, attach security headers, and save to PCAP. :param packet: The IPv6 packet to fragment. :param max_size: The MTU size for fragmentation. :param filename: The name of the .pcap file to save fragments. :param key: The key used for MAC generation. :return: List of fragments. """ fragments = [] fragment_size = max_size - 40 # IPv6 header size is 40 bytes payload = bytes(packet[Raw]) if Raw in packet else b"" total_payload_len = len(payload) nonce = os.urandom(4).hex() # Generate a 32-bit random nonce for i in range(0, total_payload_len, fragment_size): fragment_payload = payload[i:i + fragment_size] # Generate MAC for this fragment mac = generate_mac(fragment_payload, key) # Create the custom security header and serialize it to JSON sec_header = create_security_header(nonce, mac, encryption_flag=0) # Serialize the security header as JSON and ensure proper encoding security_header_json = json.dumps(sec_header) # Create the fragment header frag_header = IPv6(dst=packet[IPv6].dst) / \ IPv6ExtHdrFragment(id=12345, offset=i // 8, m=1 if i + fragment_size < total_payload_len else 0) # Embed the serialized JSON security header and the fragment payload together frag_with_sec = frag_header / Raw(load=security_header_json.encode() + fragment_payload) fragments.append(frag_with_sec) # Save all fragments to a PCAP file wrpcap(filename, fragments) print(f"Fragments saved to {filename}") return fragments # Example usage if __name__ == "__main__": # Create a large IPv6 packet large_packet = IPv6(dst="2001:db8::1") / UDP(sport=1234, dport=80) / Raw(load="A" * 3000) # Fragment the packet and save to PCAP max_mtu = 1280 # IPv6 MTU fragments = fragment_packet(large_packet, max_mtu, "fragments.pcap") # Optionally, send the fragments print("Sending fragments...") for frag in fragments: frag.show() send(frag) Reassembly logic: from scapy.all import * import hashlib import hmac import json # Function to verify the MAC of a fragment def verify_mac(fragment_payload, key, received_mac): """Verify the MAC of a fragment's payload.""" calculated_mac = hmac.new(key.encode(), fragment_payload, hashlib.sha256).hexdigest() return calculated_mac == received_mac def parse_security_header(sec_header_raw): """Parse the security header, which is expected to be in JSON byte format""" if not sec_header_raw: print("Error: Security header is empty or malformed.") return None try: # Inspecting the raw security header data before parsing print(f"Raw security header data: {sec_header_raw[:256]}") # Inspect the first 256 bytes return json.loads(sec_header_raw.decode()) # Convert the byte string back to a dictionary except json.JSONDecodeError as e: print(f"Error: Failed to decode security header. {e}") return None # Function to reassemble fragments def reassemble_fragments(fragments, key="secretkey"): """Reassemble fragments into the original payload.""" fragments.sort(key=lambda frag: frag[IPv6ExtHdrFragment].offset) # Sort by offset payload = b"" # Placeholder for reassembled payload nonce = None # Store the nonce for consistency check for frag in fragments: # Extract the raw payload and security header (the first part of the fragment) raw_payload = bytes(frag[Raw]) # Extract the raw payload from the fragment # Extract the security header (first part of the raw payload) header_len = len(json.dumps({"Next Header": 44, "Header Length": 4, "Security Type": 1, "Encryption Flag": 0}).encode()) sec_header = parse_security_header(raw_payload[:header_len]) # Adjusted to handle proper header length fragment_payload = raw_payload[header_len:] # The actual fragment payload starts after the security header # Ensure security header is valid if sec_header is None: print(f"Invalid security header for fragment with offset {frag[IPv6ExtHdrFragment].offset}") return None # Verify MAC if not verify_mac(fragment_payload, key, sec_header["MAC"]): print(f"MAC verification failed for fragment with offset {frag[IPv6ExtHdrFragment].offset}") return None # Check nonce (ensure all fragments belong to the same packet) if nonce is None: nonce = sec_header["Nonce"] # Set nonce from the first fragment elif nonce != sec_header["Nonce"]: print(f"Nonce mismatch for fragment with offset {frag[IPv6ExtHdrFragment].offset}") return None # Append fragment payload to the full payload payload += fragment_payload return payload # Example usage if __name__ == "__main__": # Simulate receiving fragments fragments = rdpcap("fragments.pcap") # Read the fragments from the PCAP file # Reassemble fragments print("Reassembling fragments...") reassembled_payload = reassemble_fragments(fragments, key="secretkey") if reassembled_payload: print("Packet reassembled successfully:") print(reassembled_payload.decode()) # Decode and print the reassembled packet payload else: print("Failed to reassemble packet.") Things I have tried: Inspecting the Raw Security Header: I used print(sec_header_raw[:256]) to examine the data. It seems there is extra padding or misalignment. Header Length Calculations: I set the expected header size explicitly to match the serialized JSON size. JSON Decoding: The error occurs during json.loads() when parsing the security header. It appears the raw payload contains unexpected bytes. Questions How can I ensure that the custom security header (JSON-encoded) is properly extracted from the fragment payload? Could the issue be caused by improper byte alignment or padding when embedding the header and payload?
common-pile/stackexchange_filtered
How to confirm mysql database backup using mysqldump in PHP Here is my code: <?php $backupfile = 'bkp_dbcreditors_' . date("Y-m-d-H-i-s") . '.sql'; $command = "C:\wamp\bin\mysql\mysql5.6.17\bin\mysqldump -u root -pare048 dbcreditors > $backupfile"; system($command); echo "Backup taken."; exit(); ?> Is there a way to confirm that backup is not taken, if such happens? Read the return value of the system($command). http://php.net/manual/en/function.system.php It returns false on failure. could you please add code how to read the return value of system()? if (system($command)!=FALSE) { echo "Backup taken in file ". $backupfile; } else{ echo "Backup failed"; } exit(); but it does not work I finally figured it out: if (!system($command, $return)) { echo "Backup taken in file ". $backupfile; } else{ echo "Backup failed"; }
common-pile/stackexchange_filtered
Why my label is not scaling properly on DPI change? I have created a WinForm along with a Label in Visual Studio 2022: namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } } Designer: namespace WinFormsApp1 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.MaximumSize = new System.Drawing.Size(200, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(197, 39); this.label1.TabIndex = 0; this.label1.Text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.ClientSize = new System.Drawing.Size(369, 115); this.Controls.Add(this.label1); this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private Label label1; } } App.manifest: <?xml version="1.0" encoding="utf-8"?> <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity version="<IP_ADDRESS>" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC Manifest Options If you want to change the Windows User Account Control level replace the requestedExecutionLevel node with one of the following. <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> Specifying requestedExecutionLevel element will disable file and registry virtualization. Remove this element if your application requires this virtualization for backwards compatibility. --> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- A list of the Windows versions that this application has been tested on and is designed to work with. Uncomment the appropriate elements and Windows will automatically select the most compatible environment. --> <!-- Windows Vista --> <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />--> <!-- Windows 7 --> <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" /> <!-- Windows 8 --> <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />--> <!-- Windows 8.1 --> <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />--> <!-- Windows 10 --> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /> </application> </compatibility> <!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation --> <!-- <application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> </windowsSettings> </application>--> <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) --> <!-- <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="<IP_ADDRESS>" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> --> </assembly> App.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <System.Windows.Forms.ApplicationConfigurationSection> <add key="DpiAware" value="true" /> <add key="DpiAwareness" value="PerMonitorV2" /> <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" /> </System.Windows.Forms.ApplicationConfigurationSection> </configuration> Program.cs: namespace WinFormsApp1 { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } } When run the app, on a 100% (96Dpi) screen: However, when I move to a larger-scaled screen (175%): What am I missing to have a proper scaled label on both screens? Your Project says you're targeting .NET 6+, apparently, but you have both app.manifest and app.config setup as this was a .NET Framework Project, with also the former that would override the latter, resulting in a SystemAware .NET Framework app, not PerMonitorV2 -- Add <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> to the Project's configuration file. In app.manifest, only uncomment the System versions you plan to support (without any specific intervention to support Windows 7, it applies to Windows 10 and 11 only), app.config is irrelevant As a note, the new Project configuration pane of the latest Visual Studio also allows to specify the DpiAwareness. No need to modify the Project's configuration file manually -- It's always quite important to mention the .NET version in use Where exactly shall I put <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> in the app.config? "new Project configuration pane": I have the latest VS2022 (Version 17.4.4), but if I go to Project -> Properties, then find for "dpi", it shows me empty screen. You still haven't said what version of .NET you're targeting (i.e., he most important information is missing) -- <ApplicationHighDpiMode> is added to the main <PropertyGroup> of a Project's configuration file (.csproj) that uses the Microsoft.NET.Sdk schema -- I have no idea what you wrote about in your last comment I'm using .NET Framework 4.8 (but this question was done with .NET 6). I have created a new question specifically targeting to .NET Framework 4.8, which has been closed, as community is not aware of the differences between .NET Framework, and .NET (Core). blah
common-pile/stackexchange_filtered
Google Appengine: Budget and Daily Spending Limit not Working I am using flexible environment. I setup a billing account and set the following: Budget: 0.01$ Daily Spending Limit: 0.01$ But I am already being charged 5$. How is that possible? This is the line which tells me where the charges are comming from: App Engine Flex Instance Core Hours 5,769 Minutes $5.06 App Engine Flex Instance RAM 96.15 GB-hour $0.68 Google Compute Storage PD Capacity 1.43 GB-month $0.06 This is what my budget looks like Specified amount This billing account 50% $7.25 / $0.01 as you can see it shows a even higher charge.. I thought if you set a daily spending limit/budget it will just stop serving request and wait until the free quota is available again the next day.. That is what I want for now, I don't need this server running 24/7 at the moment and charging my card. I disabled the application for now, but that can't be a solution.. I don't want to have to disable/enable the server every time I want to work on it. Do I have to unlink my credit card? I just want the server to stop overcharging me, and stop serving requests once the free quota is over. This is what I have set in the AppEngine panel Enabled (Daily spending limit: $0.01) Settings Quotas reset every 24 hours. Next reset: 12 hrs Am I doing something wrong? please have a look at following link https://cloud.google.com/appengine/pricing#Billable_Resource_Unit_Costs For me it sounds that spending limit is only available for the standard environment and not for the flexible environment. Anyway application at the flexible environment are always running 24 hours with one instance and not like the standard enviroment which shutsdown after some time. This behaviour for flexible environment is described in this article https://medium.com/google-cloud/three-simple-steps-to-save-costs-when-prototyping-with-app-engine-flexible-environment-104fc6736495#.izm31z93r Even it's standard environment the billing amount is incorrect from time to time in my experience. You'll have to ask the billing support for refund, make sure you ask for escalate the ticket as the junior staffs will just be wasting your time.
common-pile/stackexchange_filtered
Error with beautiful soup: list index out of range I'm a **very new programmer to python. Working on a webcrawler using urllib and beautifulsoup. Please ignore the while loop at the top and incrementation of i, I'm just running this test version, and for one page, but it will eventually include a whole set. My problem is that this gets the soup, but generates an error. I'm not sure that I'm collecting the table data correctly, but I hope that this code can ignore the links and just write the text to a .csv file. For now I'm focused on just printing the text to the screen correctly. line 17, in <module> uspc = col[0].string IndexError: list index out of range HERE is the code: import urllib from bs4 import BeautifulSoup i=125 while i==125: url = "http://www.uspto.gov/web/patents/classification/cpc/html/us" + str(i) + "tocpc.html" print url + '\n' i += 1 data = urllib.urlopen(url).read() print data #get the table data from dump #append to csv file soup = BeautifulSoup(data) table = soup.find("table", width='80%') for row in table.findAll('tr')[1:]: col = row.findAll('td') uspc = col[0].string cpc1 = col[1].string cpc2 = col[2].string cpc3 = col[3].string record = (uspc, cpc1, cpc2, cpc3) print "|".join(record) possible duplicate of Beautifulsoup for row loop only runs once? In the end, I solved this problem by changing the following line: for row in table.findAll('tr')[1:]: to: for row in table.findAll('tr')[2:]: the error was because the first row of the table had split columns
common-pile/stackexchange_filtered
"Are you a human" type of page in django In order to prevent DOS type of attacks to my django site, I am considering to show a Captcha page if my web app things it is hit by a certain IP too often. Similar to what SO is doing when you show too mach activity. How is the best way to do that in django? My initial ideas so far are A decorator in front of every view A custom django middleware What would you suggest? Maybe there exist already django apps for that? You are right, there are existing Django Apps which do this. Try to "design" (not code) the whole thing yourself & then look at how these apps are implemented. You'll learn this way. Here are the links django-simple-captcha django-captcha django captcha & images A custom middleware would be best. If I understood your requirements, you want to both log how often the IP hits the web app and then to show the Captcha page for authorization. Keep in mind that this will keep Google and other search engine bots out as well if you won't add anything to deal with them specifically (e.g. User agent checking etc).
common-pile/stackexchange_filtered
how can a US citizen buy foreign stocks? my question is 2-fold: can an online broker let a US citizen buy stocks on the paris exchange? are there any pitfalls to buying foreign stocks in the us? (e.g. tax consequences here or in france, dividend currency exchange issues, etc.) background/details: i would like to buy some shares of michelin (ML.PA). unfortunately, i am in the US, and it is only traded on the paris exchange. i tried buying it with my tradeking account, but it says "The symbol you have entered is not a recognized stock symbol.". i also have accounts with several other brokers, and i am probably going to hold this stock for 1-10 years. I'm able to buy MGDDF (Compagnie Generale des Etablissements Michelin SCA) on the PINK Sheets via Schwab. There is also an ADR on the pink sheets, ticker MGDDY Your first question is a service recommendation question, which is off topic. I recommend you edit it out. @MichaelKjörling i have updated the question to be more vague. i hope that put's it within topic by moving it into the realm of "what's possible" questions rather than "which vendor is best" questions. @quid thanks for the datapoint! i was investigating that route myself. looks like some brokers charge large "foreign settlement" fees to trade OTC foreign stocks, but not ADR's (e.g. tradeking=75$). also, it looks like there is a 0.2% fee charged on buying french stocks, but i'm not sure if that applies to ADR's. if you don't make an answer out of your comment, i probably will. For question #1, at least some US-based online brokers do permit direct purchases of stocks on foreign exchanges. Depending on your circumstances, this might be more cost effective than purchasing US-listed ADRs. One such broker is Interactive Brokers, which allows US citizens to directly purchase shares on many different foreign exchanges using their online platform (including in France). For France, I believe their costs are currently 0.1% of the total trade value with a 4€ minimum. I should warn you that the IB platform is not particularly user-friendly, since they market themselves to traders and the learning curve is steep (although accounts are available to individual investors). IB also won't automatically convert currencies for you, so you also need to use their foreign exchange trading interface to acquire the foreign currency used to purchase a foreign stock, which has plusses and minuses. On the plus side, their F/X spread is very competitive, but the interface is, shall we say, not very intuitive. I can't answer question #2 with specific regards to US/France. At least in the case of IB, though, I believe any dividends from a EUR-denominated stock would continue to accumulate in your account in Euros until you decide to convert them to dollars (or you could reinvest in EUR if you so choose). it looks like using an ADR is the way to go here. michelin has an ADR listed OTC as MGDDY. since it is an ADR it is technically a US company that just happens to be a shell company holding only shares of michelin. as such, there should not be any odd tax or currency implications. while it is an OTC stock, it should settle in the US just like any other US OTC. obviously, you are exposing yourself to exchange rate fluctuations, but since michelin derives much of it's income from the US, it should perform similarly to other multinational companies. notes on brokers: most US brokers should be able to sell you OTC stocks using their regular rates (e.g. etrade, tradeking). however, it looks like robinhood.com does not offer this option (yet). in particular, i confirmed directly from tradeking that the 75$ foreign settlement fee does not apply to MGDDY because it is an ADR, and not a (non-ADR) foreign security.
common-pile/stackexchange_filtered
How to Format Pre-populated Input Fields I am populating a telephone input field with data from an API call when the page loads. I have a function that formats phone numbers to look like this: +1<PHONE_NUMBER>. But the function is only working when there is a keyup event. I am trying to get this pre-populated input value to be formatted with this same function. I've tried changing the event from keyup to load, onload, but it has no affect. I tried wrapping the function in a setTimeout delay, but that didn't work either. I know I'm missing something simple... <!DOCTYPE html> <html> <body> <form> <label>Telephone</label> <input type="tel" onload="phoneMask()" value="<?= data.phone ?>"/> </form> <script> //Format telephone numbers function phoneMask() { var num = $(this).val().replace(/\D/g,''); $(this).val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18)); }; $('[type="tel"]').keyup(phoneMask) </script> </body> </html> At the bottom of the page, in the script section add this: function phoneMask() { var num = $("input[type=tel]").val().replace(/\D/g,''); $("input[type=tel]").val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18)); }; $(document).ready(function() { phoneMask(); } ); I have edited your phoneMask function. This will call your phoneMask function once the page has loaded. This works on the assumption that there is only going to be one box of type tel. Otherwise you will need to wrap the code in phoneMask areound an each with the selector using each. I copied and pasted this immediately above the tag but no luck.
common-pile/stackexchange_filtered
javascript textarea value with new line from database Below there is a script which adds a signature in a textarea field. The signature comes from a database table and it is a text column. Also, before adding it into the text area, it adds two new lines in front to give space for writing. $value = '\n\n'.$signature['usertext']; <script type="text/javascript"> var signature = "$value"; var ta = document.getElementById('emailbox'); ta.value = signature; </script> The problem comes when the signature added in the database is more than one lines. It simply doesn't get added into the textarea. The value of the usertext column is this: test550550 adsadasdasdas Any help would be thanked. how does the database store new lines in the field? is $value = '\n\n'.$signature['usertext']; PHP code? Is it javascript or php? i think javascript use "+" instead of "." for string concatenation. So your $value = '\n\n'.$signature['usertext']; might need to be changed to $value = '\n\n' + $signature['usertext'];
common-pile/stackexchange_filtered
How TeslaUnread for Nova Launcher works? Hi am doing a project and I need to show off some social app (Facebook, Whatsapp) notification (unread count, not by the notification listener service) in my application. I tried in many ways, but I not able to get the answer and I see the "nova launcher" they are showing the exact notification unread by tesla Have any idea how TeslsUnread works. I need to get the unread count for all the apps. So you haven't looked at or tried anything yourself before starting a bounty? This isn't a complete question. What is teslaunread? What isnt working? @NickCardoso I tried manys ways after that only i posted question here
common-pile/stackexchange_filtered
Do I need OpenGL in Ubuntu 22.04 to run Chrome? I have been unable to run Chrome since upgrading to 22.04 on my HP Compaq dc7800p with Intel® Core™2 Duo CPU E8500 and Intel® Q35 Graphics. Chrome worked fine in 20.04. The link on Applications in 22.04 wouldn’t work. Downloading and installing the real Google Chrome didn't work. Uninstalled everything. Downloaded and reinstalled Google Chrome and got error messages primarily because “OpenGL ES 2.0 is not supportable.” “Intel or NVIDIA OpenGL ES drivers are not supported” also appears. Do I need to get OpenGL or just revert my old machine to 20.04? I don't use google-chrome sorry, but I've not noted any issues with chromium (default repository version) on any any release of Ubuntu (or flavors) on hp dc7700, dc7800 or like boxes. Thanks. For some reason it has started to work.
common-pile/stackexchange_filtered
How to update a node/element in xquery marklogic How can we update a value in xquery other than node-replace? I have an element called title which is empty , I should be updating the value as “submitted”. Sample file: <books> <title></title> </books> I assume you are asking for an alternative to xdmp:node-replace() because this XML doc is an in-memory object and not (yet) a persisted document? You could perform a recursive descent typeswitch xquery version "1.0-ml"; (: This is the recursive typeswitch function :) declare function local:transform($nodes as node()*) as node()* { for $n in $nodes return typeswitch ($n) case text() return $n case attribute() return $n case comment() return $n case processing-instruction() return $n case element (title) return <title>submitted</title> default return element {$n/name()} {local:transform($n/(@*|node()))} }; let $books := <books foo="x"><!--test--><?PITarget PIContent?> <title></title> </books> return local:transform($books) , but I find that to be tedious and don't like for general purpose transformations if you wind up needing more complex transformation scenarios. For more complicated transformations of in-memory XML structures in XQuery, then I would look to use Ryan Dew's XQuery XML Memory Operations library: import module namespace mem = "http://maxdewpoint.blogspot.com/memory-operations" at "/memory-operations.xqy"; let $books := <books> <title></title> </books> return mem:copy(fn:root($books)) ! ( mem:replace(., $books/title, element title {"submitted"}), mem:execute(.) ) When transforming XML (whether in-memory or documents in the database), I prefer XSLT. You could use either xdmp:xslt-invoke() (with an installed stylesheet) or with xdmp:xslt-eval(): xquery version "1.0-ml"; let $xslt := <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="title"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:text>submitted</xsl:text> </xsl:copy> </xsl:template> </xsl:stylesheet> let $books := <books> <title></title> </books> return xdmp:xslt-eval($xslt, $books)
common-pile/stackexchange_filtered
Nitrogen - Dynamically creating Events I am a beginner with Erlang/Nitrogen. I am toying with a bidding system back by a mnesia db. On my index page I have the following code and the various items and their properties get created dynamically from the database: %% -*- mode: nitrogen -*- -module (index). -compile(export_all). -include_lib("nitrogen/include/wf.hrl"). main() -> #template { file="./site/templates/bare.html" }. title() -> "Meir Panim Gala Dinner silent auction". body() -> Header = [#panel{id=header, body=[#h1{text="Meir Panim Gala Dinner silent auction"}]}], {atomic, Items} = item_database:get_all(), Elements = lists:map(fun(X) -> {item, Index, Title, _, Picture, _, _, Reserve, CurrentBid} = X, #panel{id=items, body=[ #span{id=title, text=Title}, #image{id=image, image= "images/" ++ Picture}, #span{id=currentbid, text="Current bid: £" ++ integer_to_list(CurrentBid)}, #span{id=reserve, text="Reserve: £" ++ wf:to_list(Reserve)}, #link{id=showalert, text="More info / Place your bid", postback="showalert"++integer_to_list(Index)} ] } end, Items), wf:f([Header, Elements]). {atomic, Items} = item_database:get_all(), Actions = lists:map(fun(X) -> {item, Index, _, _, _, _, _, _, _} = X, event("showalert"++integer_to_list(Index)) -> wf:wire(#alert{text="action "++integer_to_list(Index)++" clicked"}) end, Items). I tried to create my events in the same manner but it was not working. In my code the alerts will be replaced with lightboxes containing a form to accept bids. Please help and tell me what I am doing wrong. I'd recommend you using Records instead of pattern matching over tuples like {item, Index, _, _, _, _, _, _, _} = X. I will bear that in mind. Any idea for the events creation question? As far as I know you catch events in page with "event". so I would try something like : postback={bid, Index} and at down catch it with : event({bid, Index})-> %% do stuff ok; event(_)-> ok. update: this is only an example of how you can fix it, its not the best way. %% -*- mode: nitrogen -*- -module (index). -compile(export_all). -include_lib("nitrogen/include/wf.hrl"). main() -> #template { file="./site/templates/bare.html" }. title() -> "Meir Panim Gala Dinner silent auction". body() -> Header = [#panel{id=header, body=[#h1{text="Meir Panim Gala Dinner silent auction"}]}], {atomic, Items} = item_database:get_all(), Elements = lists:map(fun(X) -> {item, Index, Title, _, Picture, _, _, Reserve, CurrentBid} = X, #panel{id=items, body=[ #span{id=title, text=Title}, #image{id=image, image= "images/" ++ Picture}, #span{id=currentbid, text="Current bid: £" ++ integer_to_list(CurrentBid)}, #span{id=reserve, text="Reserve: £" ++ wf:to_list(Reserve)}, #link{id=showalert, text="More info / Place your bid", postback={bid,Index}} ] } end, Items), wf:f([Header, Elements]). event({bid, Idx})-> %% you would better have a function to get one item at a time in item_database case item_database:get_by_index(Idx) of {atomic, X} -> %% This is not the right way, use records {item, Index, Title, _, Picture, _, _, Reserve, CurrentBid} = X, wf:wire(#alert{text="action "++ Title ++" clicked"}); _ -> wf:wire(#alert{text="item not found"}) end; event(_)-> ok. That is ok but would make me define my events manually when I actually want to define them dynamically so if I have 100 items in the database 100 events will be created on my page without my having to write the event function 100 times or with a case statement with 100 different tuples. I might not have understood your answer... @elimayost in erlang you can have functions creating functions but nitrogen needs a base "event" handler for postback. and with the code you dont really need 100 event handler, only 1 for each kind. I am gonna rewrite it so you can understand it more clearly. Ofcourse you need to rewrite it for your usage. Thanks for your answer and effort. I have also persevered and came up with an answer not dissimilar to yours (although it is probably not the right way of doing it but it works). I will post my answer below. @elimayost I still dont understand why you are not using erlang instead of binary->list->substring->binary->list conversion. I am gonna update, you can easyly capture postbacks like : postback={showinfo, Index} postback={registerbid, Index} and to capture them you can use : event({showinfo, Index})-> ok; event({registerbid, Index})-> ok; event(_)-> ok. This would save you a lot of trouble and you wont do so match binary->list conversion. The penny dropped after reading your last answer. That will indeed simplify the code quite a lot. It seems that beginners tend to complicate something that is otherwise simple to implement (-: Thanks again. %% -*- mode: nitrogen -*- -module (index). -compile(export_all). -include_lib("nitrogen/include/wf.hrl"). main() -> #template { file="./site/templates/bare.html" }. title() -> "Welcome to Nitrogen". body() -> {atomic, Records} = item_database:get_all(), Elements = lists:map(fun(X) -> {item, Index, Title, _, _, _, _, _, _} = X, #panel{body=[ #span{text=Title, style="font-size: 20px; font-weight: bold;"}, #br{}, #link{text="more info / place your bid", postback="showinfo"++integer_to_list(Index)}, #br{}, #link{text="register your bid", postback="registerbid"++integer_to_list(Index)}, #br{}, #br{}, #lightbox{id="lightbox"++integer_to_list(Index), style="display: none;", body=[ #span{text=Title, style="font-size: 24px; font-weight: bold; color: #ffffff;"} ]} ]} end, Records), wf:f([Elements]). event(Event) -> case (re:run(Event, "showinfo")) of {match, _} -> [_, _, SI] = re:split(Event, "(showinfo)"), ShowIndex = binary:bin_to_list(SI), wf:wire(#show{target="lightbox"++ShowIndex}); _ -> ok end, case (re:run(Event, "registerbid")) of {match, _} -> [_, _, RI] = re:split(Event, "(registerbid)"), RegisterIndex = binary:bin_to_list(RI), wf:wire(#alert{text="registerbid"++RegisterIndex++" clicked"}); _ -> ok end.
common-pile/stackexchange_filtered
How can I customize font and page in laravel dompdf? I get from here : https://github.com/barryvdh/laravel-dompdf My controller is like this : public function listdata() { $pdf=PDF::loadView('print_tests.test_pdf'); $pdf->setPaper('L', 'landscape'); return $pdf->stream('test_pdf.pdf'); } My view is like this : <script type="text/php"> if ( isset($pdf) ) { $x = 72; $y = 18; $text = "{PAGE_NUM} of {PAGE_COUNT}"; $font = $fontMetrics->get_font("Arial", "bold"); $size = 6; $color = array(0,0,0); $word_space = 0.0; // default $char_space = 0.0; // default $angle = 0.0; // default $pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle); } </script> I use this : "barryvdh/laravel-dompdf": "^0.7.0", When executed, the font is not Arial and the page is not display. How can I solve it? Have you loaded the "Arial" font into dompdf? The fonts available in a new install of dompdf are: helvetica, times (or times-roman), courier, dejavu sans, dejavu serif, dejavu sans mono, symbol, zapfdingbats. Plus the generic family names: sans, sans-serif, monospace. @BrianS, How can I load the Arial font into dompdf? The easiest way to set up a new font is to specify it in your CSS using an @font-face declaration. You need to pay attention to the font-related configuration properties for laravel-dompdf. The Dompdf Unicode How-To covers the basics for adding a font. try in laravel 5.5 above. 1.first download the font which u want to add(or set) as .ttf extenstion 2.store inside laravel storage folder like this storage/fonts/yourfont.ttf 3.Use CSS @font-face rules inside your blade.. 4.for example create sample.blade.php file like this <html> <head> <meta http-equiv="Content-Type" content="charset=utf-8" /> <style type="text/css"> @font-face { font-family: 'yourfont'; //you can set your custom name also here.. src: url({{ storage_path('fonts/yourfont.ttf') }}) format('truetype'); font-weight: 400; // use the matching font-weight here ( 100, 200, 300, 400, etc). font-style: normal; // use the matching font-style here } body{ font-family: "yourfont", //set your font name u can set custom font name also which u set in @font-face css rule </style> </head> <body> Check your font is working or not... </body> </html>
common-pile/stackexchange_filtered
I've been reviewing some differential blood counts and one stands out. The total leukocyte count is within a normal range, but the composition is skewed. How so? A neutrophilia suggesting a bacterial infection? No, the neutrophils are fine. It’s the eosinophil count that's significantly elevated, but without the classic signs of an allergic reaction or asthma. That is unusual. High eosinophils without an allergic context forces you to look elsewhere. What are the patient's other symptoms? Chronic abdominal discomfort, some unexplained weight loss. Nothing that screams infection in the typical sense, like a fever. So, not a classic bacterial or viral pathogen. The immune system is clearly responding to something, but it's a specific kind of response. Eosinophils are granulocytes, but they're not the primary responders for common infections. Exactly. Their major basic protein is quite effective, but not against bacteria. It’s more suited for damaging the exterior of larger organisms. Larger organisms… like parasites. That would fit the picture. The immune system isn't trying to engulf the pathogen, but rather to attack it externally. My thoughts precisely. A helminth infection, for instance. Something like a tapeworm would trigger that kind of specific eosinophilic response. And it would align perfectly with the gastrointestinal symptoms and weight loss. The parasite lives in the gut, causing local irritation and nutrient malabsorption. It’s a fascinatingly targeted reaction. The body recognizes the invader is too large for phagocytosis by neutrophils or macrophages and deploys a specialist. It makes you wonder about the coevolutionary arms race. The parasite evolves to evade the immune system, and the host develops highly specific cells like eosinophils to counter it. The elevated count is a clear footprint left by the parasite. It’s a direct indicator of a specific kind of battle being waged. So, the next logical step would be stool sample analysis to look for ova and proglottids. Yes, that would confirm the diagnosis. The bloodwork has already told us what kind of enemy to look for.
sci-datasets/scilogues
D3JS Force network: Links to nodes that are grouped using formula in transform fnt I am applying a formula to cluster nodes in D3js force network graph. I do not know how to get my links to attach to the new, clustered node locations. For the nodes I changed my original code from: force.on("tick", function() { node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); To code that clusters the nodes by their category (nodeCategory): node.attr("transform", function(d) { var xm = d.x + intensity*Math.cos(angle*nodeGroup(d.nodeCategory)); var ym = d.y + intensity*Math.sin(angle*nodeGroup(d.nodeCategory)); return "translate(" + xm + "," + ym + ")"; }); The nodes now cluster successfully based on their category in the data. However, I do not know how to update the code for the links (edges). The links are no longer attached to the nodes and reflect the non-clustered node locations: edges.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); How do I apply the transformation to the links? Any help would be greatly appreciated! EDIT: Here is a jsfiddle that illustrates the problem. Tim The problem is that the links are in the wrong place because the nodes are displaced from their (d.x,d.y) positions by the grouping transform. So d.source.x and d.source.y are not the position you want for the link. You need to update d.x and d.y to reflect the true position of the node so that the links are where you want. The usual way to do this would be something like... force.on("tick", function(e) { node.attr("transform", function(d) { d.x += (intensity*Math.cos(angle*nodeGroup(d.nodeCategory)) - d.x)*e.alpha; d.y += (intensity*Math.sin(angle*nodeGroup(d.nodeCategory)) - d.y)*e.alpha; return "translate(" + d.x + "," + d.y + ")"; }); edges.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); } The idea is to have a position regulator with varying gain that is a function of the force alpha. That way the speed at which the nodes are moved at decays with time. Here it is in context... //Width and height for SVG area var w = 500; var h = 200; // nb_group, angle, intensity: Used in clustering the nodes var nb_group=4; var angle = 2*Math.PI/nb_group; var intensity = 100; var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h) var colors = d3.scale.category10() .range(["#FFFF00", //YELLOW "#377eb8", //BLUE "#4daf4a", //GREEN "#e41a1c", //RED ]); var dataset = { "nodes":[ {"id":0,"name":"A","nodeCategory":"1"}, {"id":1,"name":"AA","nodeCategory":"1"}, {"id":2,"name":"B","nodeCategory":"2"}, {"id":3,"name":"BB","nodeCategory":"2"}, {"id":4,"name":"C","nodeCategory":"3"}, {"id":5,"name":"CC","nodeCategory":"3"}, {"id":6,"name":"D","nodeCategory":"4"}, {"id":7,"name":"DD","nodeCategory":"4"}, {"id":8,"name":"DDD","nodeCategory":"4"} ], "edges":[ {"source":0,"target":2,"value":""}, {"source":1,"target":3,"value":""}, {"source":2,"target":4,"value":""}, {"source":3,"target":5,"value":""}, {"source":4,"target":6,"value":""}, {"source":5,"target":7,"value":""}, {"source":6,"target":8,"value":""}, {"source":7,"target":0,"value":""}, {"source":8,"target":1,"value":""} ] } var force = d3.layout.force() .nodes(dataset.nodes) .links(dataset.edges) .gravity(.5) .charge(-100) .linkDistance(10) .size([w, h]) .start(); var drag = force.drag() .on("dragstart", dragstart); var edges = svg.selectAll("line") .data(dataset.edges) .enter() .append("line") .style("stroke", "black"); var nodes = svg.selectAll("g.node") .data(dataset.nodes) .enter() .append("g") .on("dblclick", dblclick) .call(drag); nodes.append("circle") .attr("r", 10) .style("fill", function(d) { return colors(d.nodeCategory); }) .style("stroke", "black") // Mousover Node - highlight node by fading the node colour during mouseover .on('mouseover', function(d){ var nodeSelection = d3.select(this).style({opacity:'0.5'}); }) //Mouseout Node - bring node back to full colour .on('mouseout', function(d){ var nodeSelection= d3.select(this).style({opacity:'1.0',}) }) // dx sets how close to the node the label appears nodes.append("text") .attr("class", "nodetext") .attr("dx", 12) .attr("dy", ".35em") .text(function(d) { return d.name }); // Just the name // Edge Paths var edgepaths = svg.selectAll(".edgepath") .data(dataset.edges) .enter() .append('path') .attr({'d': function(d) {return 'M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y}, 'id':function(d,i) {return 'edgepath'+i}}) .style("pointer-events", "none"); force.on("tick", function(e) { // position regulator for nodes must update d.x and d.y BEFORE links are positioned nodes.attr("transform", function(d) { d.x += (intensity*Math.cos(angle*(d.nodeCategory)) + w/2 - d.x)*e.alpha; d.y += (intensity*Math.sin(angle*(d.nodeCategory)) + h/2 - d.y)*e.alpha; return "translate(" + d.x + "," + d.y + ")"; }); edges.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); // ORIGINAL transform for Nodes: // nodes.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); // New Transform for nodes: // PROBLEM HERE edgepaths.attr('d', function(d) { var path='M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y; //console.log(d) return path}); }); // Double click to 'unfix' the node and have forces start to act on it again. function dblclick(d) { d3.select(this).classed("fixed", d.fixed = false); } // Set the "fixed" property of the dragged node to TRUE when a dragstart event is initiated, // - removes "forces" from acting on that node and changing its position. function dragstart(d) { d3.select(this).classed("fixed", d.fixed = true); } body { margin: 0; } svg { outline: 1px solid red; } <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> Hi Cool Blue. The speed and decay are working fine in my graph. My problem is that after I switch to clustering the nodes based on adding the formula (code block #2), the edges (lines) are no longer attached to the nodes. The line position x1,y1 for source and x2,y2 for target locations no longer correspond to the node locations. The edges appear on the graph but are all at the wrong locations because I have transformed the node points but not the start and end of each line that connects two nodes. I hope that is clearer. - T Cool Blue : Still having trouble getting your code to work for me. I added a JSFiddle to my original post. I'd appreciate it very much if someone would try altering that code to show me how to change the code for the edges (links/lines) in that example. OK, I'll take a look... do you get the basic point of my suggestions? Yes! Now I get it. Thank you very much for taking the time to adjust my code and show the functional example. This helped my understanding very much and I will be applying this in several future graphs so I really appreciate your effort. My original answer was full of typos so sorry about that. I could have added the w/2,h/2 offset in the tick function instead of using the transform and maybe you should do it that way... I updated the snippet to be like that.
common-pile/stackexchange_filtered
How can I store the output of a query into a temporary table and use the table in a new query? I have a MySQL query which uses 3 tables with 2 inner joins. Then, I have to find the maximum of a group from this query output. Combining them both is beyond me. Can I break down the problem by storing the output of the first complicated query into some sort of temporary table, give it a name and then use this table in a new query? This will make the code more manageable. Thank you for your help. Have you tried CREATE TEMP TABLE? you can do all this in one query submit what you have tried so far. if you want to make temporary tables you can but 2 inner joins is not that much to require a temp table This is very straightforward: CREATE TEMPORARY TABLE tempname AS ( SELECT whatever, whatever FROM rawtable JOIN othertable ON this = that ) The temporary table will vanish when your connection closes. A temp table contains the data that was captured at the time it was created. You can also create a view, like so. CREATE VIEW viewname AS ( SELECT whatever, whatever FROM rawtable JOIN othertable ON this = that ) Views are permanent objects (they don't vanish when your connection closes) but they retrieve data from the underlying tables at the time you invoke them. Sorry for bothering you, do you recommend using mysql temporary tables in a situation like this (https://stackoverflow.com/questions/45164132/why-i-cant-use-the-name-of-the-derived-tablesubquery-result-again) ? @Accountant In short, no. In generic MySQL, temp tables are close to useless because of their restrictions. MariaDB 10.2 (a MySQL fork) has common table expressions, which are the good way to solve that problem. Or, use a view to avoid typing the subquery twice.
common-pile/stackexchange_filtered
Tab order issue in IE with initial Javascript select of field in form I'm trying to achieve the following behaviour in html: user is presented with a form involving several text fields. The fields are populated with default values, but in many cases the user will wish to enter their own. When the page loads, the value in the first field is selected, so the user can either replace it by simply starting to type and tabbing out to the next field, or simply leave it and tab out. Here's a pared down example of what I have: <html> <body onload="document.getElementById('helloField').select()"> <form> <input id="helloField" value="hello"/><br/> <input value="goodbye"/><br/> <input type="submit" value="Submit"/> </form> </body> </html> This works in Chrome (and Firefox I believe, but I don't have it here). In IE, the field is selected as intended, but when the user hits tab, the browser tabs out to its address bar rather than to the goodbye field. If I replace the select with a simple focus, like <body onload="document.getElementById('helloField').focus()"> the tabbing is okay in all browsers, but this isn't what I want. I want the user to be able to start typing right away to replace the default value. Anyone have any ideas? Thanks. Focus, then select. Also consider putting the code in a script block directly after the input in question. If you have a bunch of images on the page, document.onload can fire quite a lot later, and the last thing you want is to be typing away in an input box when onload fires and hijacks your focus (making you delete the contents of the box). <input id="helloField" value="hello"/><br/> <script type="text/javascript"> var hello= document.getElementById('helloField'); hello.focus(); hello.select(); </script> Try setting the tab order of the fields using tabindex: <html> <body onload="document.getElementById('helloField').select()"> <form> <input id="helloField" value="hello" tabindex="1" /><br/> <input value="goodbye" tabindex="2" /><br/> <input type="submit" value="Submit" tabindex="3" /> </form> </body> </html>
common-pile/stackexchange_filtered
Is charging 18650 lithium ion cells with lower current better? I have a 3p12s 18650 Li-ion battery pack that I use for my e-bike. I charge it with a balance charger. I know that charging with too high current is bad for battery life. But is it "the lower the better"? If not, is there any recommended minimal charging current? Is charging at 0.1 C safe? My only goal is to prolong the battery life (number of cycles). I charge it only at night so I don't care about it taking long time. In the data sheet of the cells I use (Sony US18650V3) there is only specified maximum charge current 1 C. It says nothing about minimum charge current. What's more, I've never seen any batteries data sheet mentioning "minimum charge current". C/10 is safe but then CV cutoff needs to set to 5% to 10% CC rate minimum but CV must never exceed 4.2 https://electronics.stackexchange.com/questions/270292/unable-to-understand-drones-lipo-battery-capacity-loss/270670?r=SearchResults&s=7|14.5679#270670 and lowV cutoff ought to be increased as much as practical for shorter useage but overall longer Ah lifetime. Thermal sense display is best for monitoring ageing rate. Instead of thinking about what charging regimes will prolong battery life, it's probably best to flip that on its head and say what use regimes will reduce the number of cycles, and then avoid those. The best way to kill Lithiums is to charge to too high voltage, or discharge to too low voltage. Sacrifice some capacity by charging to less than 4.2v, and stopping before you get to the end point, and you'll avoid killing your cells. Pro-tip, this is what electric car manufacturers do to be able to give an 8 year warranty on the traction battery pack. The next way to reduce battery life is to run them too hot. Once you've taken car of voltage limits and temperature, high charge and discharge currents can reduce the life, but not by as much as those first two factors. A low current does not reduce life. The only way a low charging current might contribute to a reduced life is in the hands of an inexperienced designer who thinks that lithium cells behave like nickel or lead, and that if the current is low enough, then a gentle overcharge is permissible. With lithiums, no overcharge is ever permissible, see the second paragraph. Also charging at different rates but to same voltage does not contribute to the same level of charge. Eg: at 1C to 4.2V has a bit less level of charge compared to charging at 0.5C to 4.2V. Therefore charging at too low (eg: 0.1C) to 4.2V can actually do more harm than charging at say 0.5C to 4.2V.
common-pile/stackexchange_filtered
Swift 4.2, how to define a protocol for specific class or subclass I need a protocol which can be implemented by UIView only. So my code is like this: // Code 1 protocol FooBar where Self: UIView { var name: String? { get set } } // The default implementation. extension FooBar { var name: String? { get { return objc_getAssociatedObject(self, &AssociationKey.name) as? String } set { objc_setAssociatedObject(self, &AssociationKey.name, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } } private struct AssociationKey { static var name = 0 } But when I use it, I found that the variable must be declare with var. // Code 2 class TestView: UIView, FooBar { } let testView = TestView() testView.name = "TestView" // Xcode Error: Cannot assign to property: 'testView' is a 'let' constant So I modify the protocol's definition, add AnyObject to the protocol: // Code 3 protocol FooBar: AnyObject where Self: UIView { var name: String? { get set } } It works, but get a Xcode warning "Redundant constraint 'Self' : 'AnyObject'", which means the ": AnyObject" is Unnecessary. I'm confused, without "AnyObject" the protocol can not work correctly, but add the "AnyObject", the Xcode tells me "Redundant"! Is it a Swift syntax error or a Xcode complier bug? The following code is my Solution, but not perfect! So I want someone tell me a better way to do this. Thank you! // Code 4 protocol _FooBar: AnyObject { // define a base protocol at first } protocol FooBar: _FooBar where Self: UIView { var name: String? { get set } } // The default implementation. extension FooBar { var name: String? { get { return objc_getAssociatedObject(self, &AssociationKey.name) as? String } set { objc_setAssociatedObject(self, &AssociationKey.name, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } } private struct AssociationKey { static var name = 0 } class TestView: UIView, FooBar { } let testView: FooBar = TestView() testView.name = "Test" Configuration: Xcode 10.0, Swift 4.2 In Code 2, testView is a FooBar and it behaves as FooBar would, and not a class TestView. If you want to be able to change some property of a FooBar define testView as a var. Plus, any properties declared in TestView that are not already in FooBar can't be accessed from testView as long as it is a FooBar. Better have testView as TestView. In Swift 4.2, superclass constrained protocols aren't properly implemented yet – compare https://stackoverflow.com/q/50913244/2976878 & https://stackoverflow.com/a/50647762/2976878. In the latest master snapshot, your second example works as expected. Thanks! Is it means that is a feature of swift in future? @Hamish @mlibai Correct – Swift 5 will the first version of Swift to properly support superclass constrained protocols.
common-pile/stackexchange_filtered
Cheap vs. expensive catalytic converters for F250 The catalytic converter on our truck got stolen and we need to get it replaced. The truck is a 2001 Ford F250 Super Duty with a V8 5.4l gasoline engine. There are very cheap universal converters out there; NAPA offers the 53033 that should be viable for that truck (according to the site) for less than a hundred bucks. There are also much more expensive universal ones. What would be the key differences compared to the cheap one, beyond a possible longer life expectancy? It's an old truck, so durability is a secondary concern. We are in Oregon, which just follows the federal exhaust standards. To phrase the question differently: Why would anybody buy one for $400 at all? (They are not even California rated; I understand that those are more expensive.) Or perhaps the actual question is "can I just install the cheap one, car will run fine and it will pass the DEQ inspection with it?" ;-). Although not versed in 50 state emissions regulations, California forbids non oem catcons. New York may be second, following California. California has unique smog issues, hence tight regulations over vehicle emissions control. Another reason catcons are expensive; new vehicle warranties mandates higher quality oem catcons to avoid repeated replacement. Inexpensive catcons can meet federal/state emissions but for how long? You'll have to determine what your state's emissions regulations are and whether inexpensive catcons are allowable. If your state DMV can't help. repair shops can. @FDryer Ah, forgot to mention Oregon. Yes, California approved ("C.A.R.B") converters are much more expensive, apparently because more precious catalyst metals are need to achieve better conversion. Personally, unless someone corrects me, I think catcons are catcons; they're designed to convert exhaust byproducts to harmless gases. I'm not familiar with design criteria so there's a lot of latitude that may differentiate oem catcons from equal aftermarket products meeting the same criteria. As to longevity, that's solely up to aftermarket manufacturers to prove their catcons meets or exceeds oem parts. I don't know of third party reviews that do that. This is a buyer beware scenario in selecting replacement catcons. The post catcon O2 sensor is supposed to monitor catcon efficiency.
common-pile/stackexchange_filtered
Issue with Selenium: Inconsistent Behavior with Multiple Browser Windows In the provided context, I encountered an issue while using Selenium with my regular Google Chrome profile. Specifically, when I attempt to launch Selenium in a separate window while my browser is already open (without connecting to an existing session), it fails to retrieve cookies and other profile-related information. Interestingly, starting Selenium before manually opening the browser seems to resolve the issue. However, if I open the browser while Selenium is already running, it does not retain the cache, such as the login status on Steam or the volume settings on YouTube videos. Strangely, logging into a Google account remains unaffected. I am seeking assistance from anyone who has encountered and resolved a similar problem. I would greatly appreciate any guidance or suggestions. Please find below the code I am currently using: chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--headless") chrome_options.add_argument("user-data-dir=C:\\Users\\Server\\AppData\\Local\\Google\\Chrome\\User Data") chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--remote-debugging-port=9223") chrome_options.add_argument( "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/<IP_ADDRESS> Safari/537.36") driver = webdriver.Chrome(options=chrome_options) As a beginner in Selenium, this behavior is new to me, and most of the solutions I have come across involve connecting to an existing session, which is not suitable for my case. Unfortunately, I haven't found a specific solution that addresses this particular issue. Any assistance or insights would be highly appreciated. BTW: If I use "C:\\Users\\Server\\AppData\\Local\\Google\\Chrome\\UserData\\Default" instead of "C:\\Users\\Server\\AppData\\Local\\Google\\Chrome\\User Data" the cookies are not transmitted to Selenium
common-pile/stackexchange_filtered
Why is numpy.exp on a complex meshgrid array giving the wrong real part? I have a nested array of complex numbers, xi: [[[ 2.51325641-2.34963293j 2.17949212-1.57079633j 2.51325641-0.79195972j] [ 2.15322703+3.14159265j 0.00000000+1.57079633j 2.15322703+0.j ] [ 2.51325641+2.34963293j 2.17949212+1.57079633j 2.51325641+0.79195972j]] [[ 2.44651048-2.3486959j 2.11452586-1.57079633j 2.44651048-0.79289676j] [ 2.08450333+3.14159265j 0.00000000+1.57079633j 2.08450333+0.j ] [ 2.44651048+2.3486959j 2.11452586+1.57079633j 2.44651048+0.79289676j]]] and taking numpy.exp gives me the following: np.exp(xi): [[[ -8.67181418e+00 -8.78636871e+00j 5.41404995e-16 -8.84181457e+00j 8.67181418e+00 -8.78636871e+00j] [ -8.61260674e+00 +1.05474013e-15j 6.12323400e-17 +1.00000000e+00j 8.61260674e+00 +0.00000000e+00j] [ -8.67181418e+00 +8.78636871e+00j 5.41404995e-16 +8.84181457e+00j 8.67181418e+00 +8.78636871e+00j]] [[ -8.10419460e+00 -8.22665532e+00j 5.07350124e-16 -8.28565631e+00j 8.10419460e+00 -8.22665532e+00j] [ -8.04059693e+00 +9.84689130e-16j 6.12323400e-17 +1.00000000e+00j 8.04059693e+00 +0.00000000e+00j] [ -8.10419460e+00 +8.22665532e+00j 5.07350124e-16 +8.28565631e+00j 8.10419460e+00 +8.22665532e+00j]]] However the real parts of some of the elements are incorrect when I check them individually, e.g. the 2nd column of the first row of the first nested array: In [1]: np.exp(2.17949212-1.57079633j) Out[1]: (-2.833893031963725e-08-8.8418145374224597j) but others are fine (e.g. array 1 row 1 column 1). In [2]: np.exp(2.51325641-2.34963293j) Out[2]: (-8.671814171261488-8.7863687332566318j) This makes no sense to me, because the numpy.exp documentation seems to imply that e^(a+ib) is calculated as e^a*(cos(b) + i sin(b)), so I don't see how the imaginary part can be correct while the real part is not. Is it possible to make numpy.exp work consistently for my array? EDIT: It's been pointed out that defining xi as above does give the correct result with np.exp; it also works in my python environment when I define it as a standalone array of the values above. However, np.exp(xi) still doesn't seem to work correctly with the way I've generated xi: d = np.array([0.91651514, 0.9797959]) spacing = 3 limit = 4 x = np.linspace(-limit, limit,spacing) y = np.linspace(-limit,limit,spacing) X, Y = np.meshgrid(x, y) def z(x,y): return x + 1j * y z = z(X, Y) xi = [] for i in range(len(d)): xxi = np.arccosh(z/d[i]) xi.append(xxi) xi = np.asarray(xi) Is there something about the way I've created xi that makes it work strangely with numpy.exp? is this a 3D tensor? because it's 3x3x2. @HadiFarah yup it's a shape (2,3,3) array. does np.exp not work on those? I am testing it now to be sure, I never tried on anything above 2D, just wanted to make sure to get it right. it computes the correct results on mine as well. Try to look if you are passing something incorrectly. Up to rounding error, 5.41404995e-16 and -2.833893031963725e-08 are both 0. @HadiFarah I can't think of anything I'm doing wrong, unless arrays made using np.meshgrid passes things differently to np.exp? I've edited the question to show how I've made xi, which might be the problem (except I don't see why it would be or how to fix it) I think it is as @user2357112 said, it is only a rounding errors because your error are all values that tend towards zero. This is very possible because you are doing exponent of a trigonometric function of a fraction, while we during testing copy the values of xi as 2.51325641-2.34963293j ... inside your machine it is probably 2.51325641.... - 2.34963293...j ... some more values that are not printed that would only show up for when an a mathematical operation is suppose to tend to zero. If I do print(xi[0][0][0]) and print('%.30f' % xi[0][0][0]) >> 2.513256407818519 2.513256407818519111430077828118 @HadiFarah ah okay i think you're right! taking np.exp(2.179492122140042731359699246241-1.570796326794896557998981734272j) does give me 5.41404995e-16 -8.84181457e+00j, so it makes sense now :) thanks for the explanation! According to my results, numpy seems to indeed compute the correct results: Traceback from my console: import numpy as np xi = np.array([[ [2.51325641-2.34963293j, 2.17949212-1.57079633j, 2.51325641-0.79195972j], [ 2.15322703+3.14159265j, 0.00000000+1.57079633j, 2.15322703+0.j ], [ 2.51325641+2.34963293j, 2.17949212+1.57079633j , 2.51325641+0.79195972j]], [[ 2.44651048-2.3486959j , 2.11452586-1.57079633j , 2.44651048-0.79289676j], [ 2.08450333+3.14159265j , 0.00000000+1.57079633j , 2.08450333+0.j ], [ 2.44651048+2.3486959j , 2.11452586+1.57079633j , 2.44651048+0.79289676j]]]) xi Out[7]: array([[[2.51325641-2.34963293j, 2.17949212-1.57079633j, 2.51325641-0.79195972j], [2.15322703+3.14159265j, 0. +1.57079633j, 2.15322703+0.j ], [2.51325641+2.34963293j, 2.17949212+1.57079633j, 2.51325641+0.79195972j]], [[2.44651048-2.3486959j , 2.11452586-1.57079633j, 2.44651048-0.79289676j], [2.08450333+3.14159265j, 0. +1.57079633j, 2.08450333+0.j ], [2.44651048+2.3486959j , 2.11452586+1.57079633j, 2.44651048+0.79289676j]]]) np.exp(xi) Out[8]: array([[[-8.67181417e+00-8.78636873e+00j, -2.83389303e-08-8.84181454e+00j, 8.67181420e+00-8.78636870e+00j], [-8.61260674e+00+3.09174756e-08j, -3.20510345e-09+1.00000000e+00j, 8.61260674e+00+0.00000000e+00j], [-8.67181417e+00+8.78636873e+00j, -2.83389303e-08+8.84181454e+00j, 8.67181420e+00+8.78636870e+00j]], [[-8.10419466e+00-8.22665531e+00j, -2.65563855e-08-8.28565627e+00j, 8.10419461e+00-8.22665536e+00j], [-8.04059697e+00+2.88640789e-08j, -3.20510345e-09+1.00000000e+00j, 8.04059697e+00+0.00000000e+00j], [-8.10419466e+00+8.22665531e+00j, -2.65563855e-08+8.28565627e+00j, 8.10419461e+00+8.22665536e+00j]]]) np.exp(2.17949212-1.57079633j) Out[9]: (-2.833893031963725e-08-8.84181453742246j) I am using Python 3.6.5 (Anaconda Python), with NumPy version 1.14.3. Have you tried verifying your results on another machine/other python instance? good idea! I just updated both anaconda and numpy to check - but it still doesn't work when I run my entire code (in qtconsole)... but if I define xi on its own the standalone array does give me the correct np.exp(xi). I think @HadiFarah might be right that I'm passing something incorrectly, I'll give it another look!
common-pile/stackexchange_filtered
Jquery ajax url in controller action Can some body explain How actually jquery ajax method url points to a controller action?I mean the machinery behind the technology.For example $("#Location").autocomplete({ source: function (request, response) { $.ajax({ url: '/Vacancy/AutoCompleteLocations', data: request, dataType: "json", type: "GET", minLength: 2, success: function (data) { response($.map(data, function (item) { return { label: item.REF_DESC, value: item.REF_DESC, id: item.REF_ID } })); } }); }, select: function (event, ui) { $("#hdLocationId").val(ui.item.id); } }); I want to know how url: '/Vacancy/AutoCompleteLocations' points the particular action means the machinery. If you mean how the computer find the action from url:'/Vacancy/AutoCompleteLocations',see http://msdn.microsoft.com/library/vstudio/system.web.routing.route An asp.net-mvc application has something called a Route Table. The Route Table maps particular URLs to particular controllers. An application has one and only one Route Table. This Route Table is setup in the global-asax file. In case you don't have Route Table, application will always give 404 error. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } Case -1. Consider a case when you have Area in your application. But, you did not mention the Area name in the URL. Example localhost/ControllerName/ActionName. If you Pay attention to the URL, there is no Area Name. Also there is no such Controler in the Root Controller Directory. This Controller exists in the Area. Let's say you have following Area in your application. Now you type the url : localhost/Test/Index and hit enter. Now the question is what is happening in background? Let's added a Reference of RoureDebugger. You can get the Dll from this location. Then I added a line of code in my global-asax file under Application_Start Handler. RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); When I execute the application. This shows me following output, instead of Index page response. If you pay attention to the above screenshot, Default Route is enabled which is present in the global-asax file. It's because default Url without constraint will locate the Controller anywhere in the application. But the View is neither present in the Root Folder View's Directory nor present in the Shared Folder View's Directory. Finally you will get 404 error. How can I get rid of this issue ? I faced the similar issue in the past and found the corrective action. below is the new version of default Route in global-asax file. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); var route = routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults new[] { "MvcApplication1.Controllers" } ); route.DataTokens["UseNamespaceFallback"] = false; } In the above code I added Namespace in the constraint and route.DataTokens["UseNamespaceFallback"] = false; in the route. After doing this and using the above mentioned URL, Controller Action Method will never be executed because Area Name is not present in the Controller. Also I figured out one more important information regarding the DataTokens when the Url does not contains the Area Name and Default Route does not contain the NameSpace information. below is the screenshot. The Data Token information will not be available when the Url does not contains the Area Name and Default Route does not contain the NameSpace information. Now, after adding the NameSpace and adding the Area Name in the Url as per the revised Default Route. We will get the DataToken Information as shown below in the screen shot. Below is the RouteData Output after adding the Area Name in the Url As you can see the Area Route is enabled now. Hope this will help you. Thanks In ASP.NET MVC, the URL are of the following form http://HostName/ControllerName/ActionName/Id you can validate it by looking at the routes defined in Application_Start So for your URL /Vacancy/AutoCompleteLocations (which is a relative URL means it will be appended next to the URL in your browser's address bar), Vacancy is the name of the Controller (try and find VacancyController.cs in Controllers folder) and AutoCompleteLocations is the name of the Action (a function in VacancyController.cs file) The Id part is usually optional. First of all $("#Location").autocomplete({ source: function (request, response) { $.ajax({ url: 'URL.Action("ActionName","ControllerName")', data: request, dataType: "json", type: "GET", minLength: 2, success: function (data) { response($.map(data, function (item) { return { label: item.REF_DESC, value: item.REF_DESC, id: item.REF_ID } })); } }); }, select: function (event, ui) { $("#hdLocationId").val(ui.item.id); } }); We are define route either in Global.asax or route table. routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); This is define First one is Controller and another is action Name. It's concern of Routing system that is very constomizable. A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route. By default in MVC project you have following route: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); That says that: In your first segment should be name of controller, if not - by default it will be Home; In your second segment should be name of controller action, if no - by default it will be Index. And the last segment is id, but it's optional. So id you have default route and url '/Vacancy/AutoCompleteLocations' then you will call controller Vacancy and action AutoCompleteLocation.
common-pile/stackexchange_filtered
Desktop Infrastructure - My Windows 7 Loads the incorrect profile I have Windows 7 Professional 64Bit installed, at start up when I enter my username and password it loads as per normal, but i could not see any of my programs installed or find any of my files, after digging around in the C drive i found the user folder and i could see three profiles my profile, public and temp, my files are all in my profile folder, but when i log in (using my usual profile) it seems to direct me to the Temp Folder. Has anyone come accross this and can you please help me to fix this? Is the machine a member of an AD domain? Are you logging in with a domain account or a local account? Is there anything in the event viewer related to failed profile loads? Server Fault is for professional systems administrators. We assume that you've done a minimal level of troubleshooting and log gathering before you ask a question here. Windows thinks your existing profile is corrupt for some reason. This could be many things, security issues, corrupted ntuser.dat, registry problems. "I have tried everything I know" does not help us. Be specific. @ChrisS after troubleshooting, i also came to the same conclusion that windows thinks the profile is corrupt, but i couldnt find anything wrong with the profile itself,only with the association of windows associating the wrong profile with the wrong user name,which leads me to believe the registry is not directing the right username to the right profile, my big question now is, and sorry for not wording it clearly on the day i posted the first time,how do i fix this or is it even fixable? The Event Log will have an entry every time you try to login with "Windows cannot logon you because the profile cannot be loaded" plus more information. Check it out and it will point you in the right direction. Thank you Chris S, youre information was of great value.
common-pile/stackexchange_filtered
ASP.NET Configure update button in GridView I am using C# ASP.NET on VS2005. I have a gridview table but it does not have a selection for Enable Editing when I right click on the Smart Tab. Thus I manually added the edit button with the following code: AutoGenerateEditButton="True" The edit button has successfully appeared on my gridview like this: When I click on the Edit button, the page is refreshed and the row is now editable: However, when I pressed on the update button, I was brought to the error: Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified. https://i.sstatic.net/W97K0.png I have no clue on how I can input or configure the UpdateCommand because I don't see any background code for the Update button. Need help from experienced. Thank you in advance. Edited: Added INSERT query in SqlDataSource1, however I still met the same error when I press the Update button. As you asked for example in your comment, please have a look.. You need to re-configure the SqlDataSource1 control though which you can add support for INSERT, DELETE, UPDATE along with SELECT. Take a look at this tutorial. Thanks, I will configure now. But can I have an example on how my INSERT statement will be? I am not sure how do I bind the INSERT statement with that specific editable row. Thank you while configurting sqldatasource when you configure the select statement for the gridview,there is a option as "advanced".click on that and then click on 'generate update,insert nad delete statements". In your code I think you have not handled the event for "Update". Have a look at the below example hope it might help you, check for the "UpdateCommand". Also write a Update event in C# to update. <asp:DetailsView ID="ManageProducts" runat="server" AllowPaging="True" AutoGenerateRows="False" DataKeyNames="ProductID" DataSourceID="ManageProductsDataSource" EnableViewState="False"> <Fields> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" /> </Fields> </asp:DetailsView> <asp:SqlDataSource ID="ManageProductsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" DeleteCommand= "DELETE FROM [Products] WHERE [ProductID] = @ProductID" InsertCommand= "INSERT INTO [Products] ([ProductName], [UnitPrice], [Discontinued]) VALUES (@ProductName, @UnitPrice, @Discontinued)" SelectCommand= "SELECT [ProductID], [ProductName], [UnitPrice], [Discontinued] FROM [Products]" UpdateCommand= "UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice, [Discontinued] = @Discontinued WHERE [ProductID] = @ProductID"> <DeleteParameters> <asp:Parameter Name="ProductID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="Discontinued" Type="Boolean" /> <asp:Parameter Name="ProductID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="Discontinued" Type="Boolean" /> </InsertParameters> </asp:SqlDataSource> For example, try this out... Firstly create a method to handle the update record. private void UpdateOrAddNewRecord(string parametervalue1, string parametervalue2) { using (openconn()) { string sqlStatement = string.Empty; sqlStatement = "Update TableName set Name1 =@Name1 where Name2@Name2"; try { // SqlCommand cmd = new SqlCommand("storedprocedureName", con); //cmd.CommandType = CommandType.StoredProcedure; SqlCommand cmd = new SqlCommand(sqlStatement, con); cmd.Parameters.AddWithValue("Name2", parametervalue2); cmd.Parameters.AddWithValue("@Name1",parametervalue1); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert/Update Error:"; msg += ex.Message; throw new Exception(msg); } finally { closeconn(); } } Now create the row updating method.. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string ParameterValue1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text; string ParameterValue2 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Name UpdateOrAddNewRecord(ParameterValue1, ParameterValue2); // call update method GridView1.EditIndex = -1; BindGridView(); Label2.Visible = true; Label2.Text = "Row Updated"; } Create Row Cancelling event.. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; //swicth back to default mode BindGridView(); } Create row editing... protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindGridView(); } There are so many other way out to do this same activity in different fashion. This is most elementary way. Anyways if you find it useful, please mark it as your answer else let me know...
common-pile/stackexchange_filtered
Google Analytics - Get Number of Session Per UserId I'm using Google Analytics and SegmentIO in our site. I've enabled the UserId feature. Is there a way to query Google Analytics per userID? For example: get number of session per userID? UserId enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. This is an internal value used by google analytics to group your data, it is not something you can see. If you have enabled it your data should already be using it. more info can be found here About the User ID feature In GA you can not control user id explicitly. Try user action oriented analytic platforms like http://mixpanel.com or http://www.devmetrics.io. For example, in devmetrics your can explicitly set user id for registered users and than your can explore all actions performed by a specific user (drilldown UI): <html> <head> <!-- devmetrics.io start --> <script type="text/javascript"> (function (doc, inst) { window.devmetrics = inst; inst.q = inst.q || []; inst.init = function (token) { this.token = token; }; inst.userEvent = function (eventName) { inst.q.push(eventName); }; var a = doc.createElement("script"); a.type = "text/javascript"; a.src = 'http://rawgit.com/devmetrics/devmetrics-js/master/jdevmetrics.js?' + Math.floor(((new Date()).getTime() -<PHONE_NUMBER>573) / 8640000); var e = doc.getElementsByTagName("script")[0]; e.parentNode.insertBefore(a, e); })(document, window.devmetrics || []); devmetrics.init("your-id"); </script> <!-- devmetrics.io end --> <script> devmetrics.userEvent('page_opened'); devmetrics.setUserId(191); // set your real users id </script> </head> <body> <button onclick="devmetrics.userEvent('button_click');">click to send event</button> </body> </html>
common-pile/stackexchange_filtered
Does Windows 10 defragmentation damage your SSD? I was having a conversation with one of my colleagues about installing Windows 10 on his machine, then he suddenly dropped a bomb that installing Windows 10 would reduce the life of his SSD since Windows automatically defragments the SSD which reduces its life. I didn't find any concrete evidence of this theory, except for a few discussions about defragmentation on Reddit. Does anyone have concrete evidence on this theory? This seems like it might be better for the folks over at Super User. Yes de-fragmentation reduces life of ssd. However you can turn auto de-fragmentation off, and I believe that Microsoft's Windows detects SSDs and disables auto de-fragmentation. Also Gnu/Linux file-systems such as ext, do not need de-fragmentation (except in a few very rare use-cases). However there are many other good reasons not to use Microsoft's Windows10. Back when SSD's first started becoming popular, a lot of users would attempt to manually instruct Windows to defrag their SSD's, as they wanted to protect their fancy new toy. This problem with user behavior was probably one of the motivating factors that got Microsoft to make the process of disk maintenance more automatic, to avoid such user error. Also, note that Microsoft implemented TRIM support about 10 years ago, making Windows the first major operating system to really handle SSD maintenance correctly. The TRIM command avoided the same sort of unnecessary wear-and-tear that defragging would put on the drive. Windows 10 recognizes SSDs and treats them differently than standard HDDs, meaning that there is actually no risk on damaging your SSD. To quote Scott Hanselman No, Windows is not foolishly or blindly running a defrag on your SSD every night, and no, Windows defrag isn't shortening the life of your SSD unnecessarily. Modern SSDs don't work the same way that we are used to with traditional hard drives. http://www.hanselman.com/blog/TheRealAndCompleteStoryDoesWindowsDefragmentYourSSD.aspx I don't have enough rep to fix (remove) apostrophes form answer — the society for the removal of unnecessary apostrophe's. Also, Windows 10 does maintenance work on the SSD which is REQUIRED to keep it functioning correctly.
common-pile/stackexchange_filtered
How to create a custom filter at .net core I try one of the following without any success. 1. Validate a property's (username) value in the model binding with another property's value in the model (id, to find the user). 2. Validate all the sent model to a put request in the controller. How can i create a custom filter to catch all the model to one of the property's value by use another value in the sent model? You can use Fluent Validator in .NET Core for such validations Step 1 :- Register it in the startup public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining<Startup>()); } Step 2 :- Define the validation rules like this public class RegistrationViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class RegistrationViewModelValidator : AbstractValidator<RegistrationViewModel> { readonly IUserRepository _userRepo; public RegistrationViewModelValidator(IUserRepository userReo) { RuleFor(reg => reg.FirstName).NotEmpty(); RuleFor(reg => reg.LastName).NotEmpty(); RuleFor(reg => reg.Email).NotEmpty(); RuleFor(reg => reg.FirstName).Must(DoesnotExist); } bool DoesnotExist(string userName) { return _userRepo.FindByUserName(userName) != null; } } Step 3:- IN the controllers [HttpPost] public IActionResult FormValidation(RegistrationViewModel model) { if (this.ModelState.IsValid) { ViewBag.SuccessMessage = "Great!"; } return View(); } Refer this link for the complete documentation thanks but it is not helf. What i need is to check the sent user model the consists of user id, some other information the user name and to check if the exists username in the db of the user by the id in the model. It is a little bit more complicated from empty or not empty @liolrn, Sure. You can check for existence of username in DB as well. For ex:- If you are using some repository classes inject that dependency to RegistrationViewModelValidator .cs and call a method in it to find out if the use exists. @liolrn, look at the edited answer above if it helps
common-pile/stackexchange_filtered
Wilcoxon signed-rank test in R I am trying to duplicate a Wilcoxon signed-rank test example in this Wikipedia post using R. The data is as follows: after = c(125, 115, 130, 140, 140, 115, 140, 125, 140, 135) before = c(110, 122, 125, 120, 140, 124, 123, 137, 135, 145) sgn = sign(after-before) abs = abs(after - before) d = data.frame(after,before,sgn,abs) d$rank = rank(replace(abs,abs==0,NA), na='keep') d$multi = d$sgn * d$rank (W=abs(sum(d$multi, na.rm = T))) W = 9 However, the test statistic value that R produces (undoubtedly due to some mistake that I am making in setting up the function or interpreting the output) is: wilcox.test(d$before,d$after, paired = T, alternative = "two.sided", correct=F) Wilcoxon signed rank test data: d$before and d$after V = 18, p-value = 0.5936 alternative hypothesis: true location shift is not equal to 0 This (V=18) is different from the 9 value in the Wikipedia post. What am I missing? You didn't report the warnings: "Warning messages: 1: In wilcox.test.default(d$before, d$after, paired = T, alternative = "two.sided", : cannot compute exact p-value with ties" AND 2: In wilcox.test.default(d$before, d$after, paired = T, alternative = "two.sided", : cannot compute exact p-value with zeroes @42- I didn't think it was relevant in the way that it wouldn't affect the calculation of the test statistic. But I may be wrong. Feel free to add it as an edit, if you think it could help. It seem relevant in that the fact that one particular test in your cited article had one result but that another test also described in that article is used by the R wilcox.test. YOU SHOULD INVESTIGATE THE CAUSE OF A WARNING. R reports the V-statistic, which is the sum of the positive ranks. The Wikipedia example computes it slightly differently, as the sum of all ranks, regardless of sign. In other words, both versions are correct (and equivalent). This CrossValidated post might be helpful. Stumbled upon this and found it incredibly useful as well as the other CrossValidated post mentioned by @jdobres. Just to expand a little on the answer above which is correct but in hopes that it will help someone in the future because it was very confusing at least to me initially. Note that in R if you reverse the entry order of the paired variables you will get different V values but the same p value. That's what brought me here. If they reported the W statistic you would expect to see a sign change not a different magnitude as you get with V. wilcox.test(d$before, d$after, paired = T) wilcox.test(d$after, d$before, paired = T) But it all comes back together, since as the Wikipedia article notes S is equal to the total rank sum (having removed the zero difference entries) so our S is: sum(rank(1:9)) So the two possible V statistics are bound to add to 45 (18 & 27). And the difference between them is the W statistic (9). Finally back to the Wikipedia example we can now easily divine Siegel's T statistic, it is the smaller of the two sums of ranks of given sign; therefore, T would equal 3+4+5+6=18 (or the smaller of the two V's we could compute).
common-pile/stackexchange_filtered
ListSerializer in Django Restful - When is it called? I have the following code for my serializers.py: from rest_framework import serializers from django.db import transaction from secdata_finder.models import File class FileListSerializer(serializers.ListSerializer): @transaction.atomic def batch_save_files(file_data): files = [File(**data) for data in file_data] return File.objects.bulk_create(files) def create(self, validated_data): print("I am creating multiple rows!") return self.batch_save_files(validated_data) class FileSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = FileListSerializer model = File fields = (...) # omitted I'm experimenting with it on my Django test suite: def test_file_post(self): request = self.factory.post('/path/file_query', {"many":False}) request.data = { ... # omitted fields here } response = FileQuery.as_view()(request) It prints I am creating multiple rows!, which is not what should happen. Per the docs: ... customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class. So what am I not understanding? I passed in many:False in my post request, and yet it still delegates the create function to the FileListSerializer! {"many": False} in the POST request doesn't mean anything to the serializer. Are you passing in the keyword arg many=False when instantiating the serializer in your API View? You should add code for your view here. Possible duplicate of How do I create multiple model instances with Django Rest Framework? Per the docs: The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer You can add many=True to your serializer class FileSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): kwargs['many'] = kwargs.get('many', True) super().__init__(*args, **kwargs) Potential dupe of How do I create multiple model instances with Django Rest Framework?
common-pile/stackexchange_filtered
Rotating an object correctly when you can only rotate world axis. This question may be useful to some people, but it is not posed correctly for my particular situation, please see: Simulating simultaneous rotation of an object about a fixed origin given limited resources. So, I am using the Processing programming language to create an animation where a box rolls around the screen. The tricky part is that the box can be moving in the X and the Y directions at the same time. I am drawing the box by simply calling a function called box(), so I am not calculating the vertices based on rotation and then drawing the shape, rather, I am performing a rotation of the coordinate system itself and then drawing a box. The problem here is that processing only lets you rotate about the world axis, so as much as I would like to do, say: rotateY(radians(60)), rotateX(radians(30)) to rotate the box 60 degrees to the right and then 30 degrees up, calling rotateY() also shifts the X axis itself, so you don't get what you want. I am looking to derive a trigonometric relationship (likely by taking advantage of the third axis, Z, which you normally wouldn't need to rotate) that I can use in order to simulate the rotation of an object about a fixed set of axis. Let me try to use some examples to show you what I mean: So this is what the box looks like if it is not rotated at all. There is also a Z axis, which I have drawn in blue, but you can't see it because of the angle. When the box is rotated it will become visible. If, before I draw the box, I call: rotateY(radians(60)); rotateX(radians(30)); I get: Again, this is because when I rotated about the Y axis the relative angle of the X axis was shifted , so after the call to rotateY(radians(60)) the axes were effectively like this: I want to derive a relationship that I can use to simulate a way of rotation such that after performing rotateY(radians(60)) the axis would effectively look like(drawing this one with paint: To clarify, I don't care what the axes actually look like, I only want the end result to be equivalent to what it would be if the axes existed as they do in the picture above. Again, I think this is possible if I utilize the third axis somehow as a way of correcting the rotation, but I am not sure how to go about it. I have been trying at it for a while now and I can't seem to get something that works across all situations. You don't need to know programming to solve this. I am looking for some mathematical theories/formulas that I can use to my advantage. Thanks in advance, hopefully the pictures make it clear. Please don't hesitate to ask me to clarify. Why on Earth does the command include "radians" if the axes are being rotated in degrees?? the respective rotate functions all expect their arguments to be in radians, so I am using a separate function, called radians(), to convert the degrees that I specify to their equivalent values in radians and passing the result to the rotate function. I see. I apologize for asking such a trivial question, I'm not familiar with the Processing language. Probably, Euler Angles is what you want. You can find relevant mathematics around https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions#Conversion_formulae_between_formalisms It looks like you have access to a function that will perform a rotation about the axes that are aligned with your object. If you want to rotate about an axis as it is in the initial configuration, you should conjugate your rotation. Let's say you first rotate by $R_y(\theta)$ about the $y$ axis (aligned with the object in the initial configuration). If you then want to rotate about the $x$ axis as it was in the initial configuration, instead of applying $R_x(\phi)$, you should apply $R_y(\theta) R_x(\phi) R^{-1}_y(\theta)$. The full rotation then becomes $$R_y(\theta) R_x(\phi) R_y^{-1}(\theta) R_y(\theta) = R_y(\theta) R_x(\phi)$$ i.e. the order is reversed. If this doesn't work, try the physics stackexchange; they know about reference frames. Also, see: http://en.wikipedia.org/wiki/Active_and_passive_transformation http://en.wikipedia.org/wiki/Rotation_(mathematics) Whats the difference between theta and the one with the vertical line? Theta is the angle that you want your object to rotate about the global y axis, while phi is the angle you want to rotate it about the global x axis. also you mention I should do an inverse rotation after rotating x, can you give an example of what you mean by that please? I'm sorry I'm not very experienced with math. If you did rotateX(phi) rotateY(theta) rotateZ(eta), the inverse would be rotateZ(-eta) rotateY(-theta) rotateX(-phi). However, you don't need that; what my analysis shows is that although you should "conceptually" do an inverse, it cancels the R_y that was there, so all you have to do is rotateX(phi) rotateY(theta) to achieve what you want. This confuses me. Are you saying that rotating an object about the objects relative axes is equivalent to rotating it about the fixed axis I defined? Well, any rotation can be performed either as a sequence of absolute rotations about fixed axes, or as a sequence of relative rotations about rotating axes. What I showed (if I understood your question correctly) is that to perform the absolute rotation "first rotate about the absolute y axis by theta and then rotate about the absolute x axis by phi", you can do it by performing "first perform a rotation about the relative x axis (which we take to be equal to the global x axis at this point) by theta, followed by a rotation about the new y axis by phi". Let us continue this discussion in chat.
common-pile/stackexchange_filtered
Fill DataSet from List of class Items I've searched SO for common questions, but they didn't match my task. I have a class with many(about 50) ValueTyped properties. And there are needs to fill a new DataSet object with class's properties. For example, if I have this: public partial class MyClass { public int Id {get; set;} public string Name {get; set;} // and other public properties } I need a two functions to return Filled DataSet with a single row for single MyClass item. Filled DataSet with a multiple rows for multiple MyClass items. public partial class MyClass { public DataSet GenerateDataSet(MyClass source); public DataSet GenerateDataSet(IEnumerable<MyClass> source); } I've tried many solutions like below, but it's unable to compile since DataRow doesn't have public constructor. var ds = new DataSet(); ds.Tables.Add(new DataTable("DataTableName")); var table = ds.Tables[0]; table.Rows.Add(new DataRow(new DataRowBuilder(table, 0))); public partial class MyClass { public DataSet GenerateDataSet(MyClass source) { return GenerateDataSet(new[] { source }); } public DataSet GenerateDataSet(IEnumerable<MyClass> source) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds.Tables.Add(dt); dt.Columns.Add("Name"); dt.Columns.Add("Id", typeof(int)); // other columns... foreach (MyClass c in source) { DataRow dr = dt.Rows.Add(); dr.SetField("Name", c.Name); dr.SetField("Id", c.Id); // other properties } return ds; } } DataRow dr = dt.Rows.Add(); that was that magic code string I was looking last time. Thank you a lot! @KamikyIT: you can also use dt.Rows.Add(c.Name, c.Id, ...). But i prefer my approach because then you can specify the columns and their value which is less error-prone. I'll mark your answer as correct(SO needs time for this). Again thanks! consider "implicit" operator if you want to be super c# fancy : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit
common-pile/stackexchange_filtered
WhatsApp web without camera Is it possible to load WhatsApp web without camera?. My front and back camera are broken and I am not able to load WhatsApp web without it. Anyone knows if it is possible to load it without the camera?
common-pile/stackexchange_filtered
embedding html to screen Well i have var message, which has any type of character... I replace :) with <img src="..." .../> and http://www.youtube.com/watch?v=id with <a href="...">...</a> Then I run $(".chat_message").html(message); What must I do to embed anything excepts the html tags I make as html code to screen?? The question is a little bit wirred for me. It is possible to reduce a whole site to a "script src" tag. If you want to embed a video check dynamic object model (DOM). What must I do to embed anything excepts the html tags I make as html code to screen?? I'm going to assume you want each character in message except the ones you replace with HTML tags to show literally on the screen. var messageHTML = message.replace(/&/g, "&amp;") .replace(/</g, "&lt;").replace(/>/g, "&gt;"); will put the HTML equivalent of message in messageHTML*. Once messageHTML contains a string of HTML, you can replace all occurrences of ":)" safely and correctly since that is just a simple HTML -> HTML conversion. messageHTML = messageHTML.replace(/:\)/g, "<img ...>"); Now you can use jQuery's .html(messageHTML) to inject message with your tags into the DOM. * - the white-space will differ unless you're embedding in a context with CSS white-space: pre or white-space: pre-wrap Stab in the dark (your question isn't very clear). This takes in a string, replaces all the HTML tags with ASCII codes, the somewhat weird part is then grabbing that sanitized output and adding the smiley image: var message = $('<p>stuff in <span>here</span> :)</p>').html(); $(".chat_message").text(message); $(".chat_message").html($('.chat_message').html().replace(/:\)/g, "<img />")); Here is a demo: http://jsfiddle.net/5fT5b/1/ The following example handles web-site URLs and non-ASCII characters: var message = "My name is Andy :) - and my fav web-site is http://stackoverflow.com"; //Protect against HTML characters (you might want to add more). message=message .replace("&", "&amp;") .replace("<", "&lt;") .replace("<", "&gt;"); //Protect against non-ASCII characters. message=message .replace(/[\x80-\xff]/, "*"); //Handle smilies. message=message .replace(":)", '<img src="..." />'); //Handle embedded web-site addresses. The "$0" bit says to repeat the matched thing. //The "https?" matches "http" and "https". If you want something smarter then check out //http://www.w3schools.com/js/js_obj_regexp.asp message=message .replace(/https?:[^ ]+/g, '<a href="$0">$0</a>'); $(".chat_message").html(message); I vaguely remember reading about properly HTML encoding text and that there were a bunch of characters above ASCII 128 that could potentially be used to inject scripting. The [\x80-\xff] bit should protect against those. .replace("<", "&gt;"); is a copy-and-paste error, and even if it were fixed it would still be broken. "<<".replace("<", "&gt;") == "&gt;<" because replace with a string only replaces the first occurrence.
common-pile/stackexchange_filtered
Excel vba - find row number where colum data (multiple clauses) I need a function in VBA that finds the row number based on 2 where clauses. Here is the Excel sample: ** A B C D** 1 id1 day1 val1 xxx 2 id2 day1 val2 xxx 3 id3 day1 val3 xxx 4 id1 day2 val1 xxx 5 id2 day2 val2 xxx 6 id3 day2 val3 xxx I need to find the row number (in this case row number is 2) where B = "day1" and A = "id2". Based on the row number, I need to further get the values of other columns, i.e. C2, D2 Hope that the question is clear. Thank you! With your data setup like that, you can use the MATCH function to get the row number: =MATCH(1,INDEX(($A$1:$A$6="id2")*($B$1:$B$6="day1"),),0) If there are no matches for those criteria, the formula will return an #N/A error. You can also change the criteria to be cell references, for example: =MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0) For the second part of your question, returning values with the found row number, you can use the INDEX function to return a value from a column. So pretending the Match formula is in cell H1, these two formulas will return the value from column C and D respectively: =INDEX($C$1:$C$6,H1) =INDEX($D$1:$D$6,H1) Alternately, you could put it all into a single formula: =INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)) And if you don't want to be looking at errors, you can use an IFERROR on excel 2007+ =IFERROR(INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)),"No Matches") Error checking for Excel 2003 and below: =IF(ISNA(MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)),"No Matches",INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0))) [EDIT]: I am including a VBA solution per user request. This uses a find loop, which is very efficient and flexible, and shows how to extract values from other columns once a match has been found: Sub tgr() Dim rngFound As Range Dim strFirst As String Dim strID As String Dim strDay As String strID = "id2" strDay = "day1" Set rngFound = Columns("A").Find(strID, Cells(Rows.Count, "A"), xlValues, xlWhole) If Not rngFound Is Nothing Then strFirst = rngFound.Address Do If LCase(Cells(rngFound.Row, "B").Text) = LCase(strDay) Then 'Found a match MsgBox "Found a match at: " & rngFound.Row & Chr(10) & _ "Value in column C: " & Cells(rngFound.Row, "C").Text & Chr(10) & _ "Value in column D: " & Cells(rngFound.Row, "D").Text End If Set rngFound = Columns("A").Find(strID, rngFound, xlValues, xlWhole) Loop While rngFound.Address <> strFirst End If Set rngFound = Nothing End Sub I tried this in Excel and it works. I need this to be done using a macro in VBA. How this would be translated into a VBA code (macro)? Thank you. In VBA you can do a brute force check like the following: Public Sub Test() Dim message As String Dim row As Long row = Find("id1", "day2") message = "Not Found" If (row > 0) Then message = ActiveSheet.Cells(row, 3).Value End If MsgBox message End Sub Function Find(aVal As String, bVal As String) As Long Dim maxRow As Long Dim row As Long maxRow = Range("A65536").End(xlUp).row For row = 2 To maxRow Dim a As String a = ActiveSheet.Cells(row, 1).Value b = ActiveSheet.Cells(row, 2).Value If a = aVal And b = bVal Then Find = row Exit Function End If Next row Find = -1 End Function
common-pile/stackexchange_filtered
The result of my search isn't appearing using php code <html> <body> <form action="checkorderstatus.php" method="post"> <input id="search" type="text" placeholder="Type here"> <input id="submit" type="submit" value="Search"> </form> </body> </html> <?php require_once 'loginorder.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) { die($conn->connect_error); } if (isset($_POST['submit'])); $query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'"; $result = $conn->query($query); //run the query and get the result if (!$result) { die($conn->error); } $rows = $result->num_rows; $query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'"; $result = mysqli_query($conn, $query); ($row = mysqli_fetch_row($result)); { echo $row['1']; print_r($row); } ?> I'm trying to display the status description when the statusid is entered into the search but it's not displaying anything other than Array ( [0] => product is in transit ) and I'm getting 3 errors Notice: Undefined variable: search in C:\wamp64\www\groupproject\checkorderstatus.php on line 20 Notice: Undefined variable: search in C:\wamp64\www\groupproject\checkorderstatus.php on line 28 Notice: Undefined offset: 1 in C:\wamp64\www\groupproject\checkorderstatus.php on line 36 Does this answer your question? "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP None of your input elements has a name attribute. Might want to read PHP : Dealing with Forms - Manual Problems There are a host of problems with your code as it stands... Forms posted to PHP use the name attribute in the $_POST superglobal Therefore you are effectively not submitting anything when you submit your form Add the name="..." attribute to each of your form elements to fix this Your if statements are by and large redundant Not least because you don't post anything as per point 1 You should be using prepared statements for user generated input to protect your database from attack and or corruption Your code is generally confusing and not laid out very well I'm not sure what half of your brackets, ifs and function calls are supposed to be doing The notice you're getting is because you never set $search in your PHP Solution N.B This assumes that all of the code is in the one file [`checkorderstatus.php] and that it submits to itself. Additional note: I'm not sure that LIKE '%...% is the best solution here. It appears you're looking for id which, presumably (?) is a number? In which case I would simply user: WHERE deliverystatus.statusid = SEARCH_ID The below code follows that premise. If however you are indeed in need of LIKE then you should update the query like: WHERE deliverystatus.statusid LIKE ? and update the search term in the code: $search = "%".$_POST["search"]."%"; Updated HTML form <form action="checkorderstatus.php" method="post"> <input id="search" name="search" type="text" placeholder="Type here"> <input id="submit" name="submit" type="submit" value="Search"> </form> Using mysqli mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli ($hn, $un, $pw, $db); if(isset($_POST["submit"])){ $search = $_POST["search"]; // Prepare the search term $sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?"; $query = $mysqli->prepare($sql); // Prepare the statement $query->bind_param("i", $search); // Bind search valus as an integer (use "s" if it's a string) $query->execute(); // Execute the query $query->store_result(); // Store the result $query->bind_result($status_description); // Bind "statusdescription" to a varaible while($query->fetch()){ // Loop through result set echo $status_description}."<br>"; // Echo each match to a newline } } Using PDO $pdo = new pdo( "mysql:host={$hn};dbname={$db}", $un, $pw, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => FALSE ] ); if(isset($_POST["submit"])){ $search = $_POST["search"]; // Prepare the search term $sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?"; $query = $pdo->prepare($sql); // Prepare the statement $query->execute([$search]); // Execute the query binding search as the parameter while($result = $query->fetchObject()){ // Loop through result set echo $result->statusddescription."<br>"; // Echo each match to a newline } }
common-pile/stackexchange_filtered
URL getting returned when trying to obtain value from select tag I am new to flask and Javascript. All I am trying to do is to create a form with a dynamic dropdown list, get the values selected and put them in a database. Now I am in the first phase of getting the dynamic dropdown lists created. Here is my python part of the code. class Form(FlaskForm): site = SelectField('Site', choices=[(' ', ' '), ('International', 'International'), ('Domestic', 'Domestic')]) location = SelectField('Location', choices=[]) city = SelectField('City', choices=[]) street = SelectField('Street', choices=[]) sub_street = SelectField('BuildingStreet', choices=[]) floor = SelectField('Floor', choices=[]) room = SelectField('Room', choices=[]) side = SelectField('Side', choices=[]) @app.route('/') def basic(): return render_template('basic.html') @app.route('/Welcome', methods=['GET', 'POST']) def index(): form = Form() location_choice_list = [(locations.id, locations.location) for locations in Hostname.query.filter_by(site='International').all()] form.location.choices = remove_duplicates.unique_list(location_choice_list) city_choice_list = [(cities.id, cities.city) for cities in Hostname.query.filter_by(site='International').all()] form.city.choices = remove_duplicates.unique_list(city_choice_list) street_choice_list = [(streets.id, streets.street) for streets in Hostname.query.filter_by(site='International').all()] form.street.choices = remove_duplicates.unique_list(street_choice_list) sub_street_choice_list = [(sub_streets.id, sub_streets.sub_street) for sub_streets in Hostname.query.filter_by(site='International').all()] form.sub_street.choices = remove_duplicates.unique_list(sub_street_choice_list) floor_choice_list = [(floors.id, floors.floor) for floors in Hostname.query.filter_by(site='International').all()] form.floor.choices = remove_duplicates.unique_list(floor_choice_list) room_choice_list = [(rooms.id, rooms.room) for rooms in Hostname.query.filter_by(site='International').all()] form.room.choices = remove_duplicates.unique_list(room_choice_list) side_choice_list = [(sides.id, sides.side) for sides in Hostname.query.filter_by(site='International').all()] form.side.choices = remove_duplicates.unique_list(side_choice_list) return render_template('index.html', form=form) @app.route('/location/<site>') def location(site): print(site) choice_list = Hostname.query.filter_by(site=site).all() locationObjp = {'id': '', 'location': ''} c = [{'id': ' ', 'location': ' '}] for location in choice_list: locationObj = {} locationObj['id'] = location.location locationObj['location'] = location.location if locationObj['location'] != locationObjp['location']: c.append(locationObj) locationObjp = locationObj else: locationObjp = locationObj return jsonify({'Location_Choice_list': c}) @app.route('/city/<location>') def city(location): print(location) choice_list = Hostname.query.filter_by(location=location).all() cityObjp = {'id': '', 'city': ''} c = [{'id': ' ', 'city': ' '}] for city in choice_list: cityObj = {} cityObj['id'] = city.city cityObj['city'] = city.city if cityObj['city'] != cityObjp['city']: c.append(cityObj) cityObjp = cityObj else: cityObjp = cityObj return jsonify({'City_Chocie_list': c}) So first I have created a class with all the dropdowns that the user gets to select from the form. Except for the site, all the other choices are populated initially with options corresponding to "International". i.e. All locations corresponding to "International", all cities corresponding to "International" and so on. I have used a small function that I have put up as a module to remove duplicate entries in the database that can't be avoided. Initially, when the form is displayed, everything works as expected. I have not put up the basic.html file because it just contains a link to "/Welcome". Also, there is no problem with the remove_duplicates function that I have used as a module. This is my HTML part of the code. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </head> <body> <form method="POST"> {{ form.hidden_tag() }} {{ form.site.label }} {{ form.site }} {{ form.location.label }} {{ form.location }} {{ form.city.label }} {{ form.city }} {{ form.street.label }} {{ form.street }} {{ form.sub_street.label }} {{ form.sub_street }} {{ form.floor.label }} {{ form.floor }} {{ form.room.label }} {{ form.room }} {{ form.side.label }} {{ form.side }} <input type="submit"> </form> <script> var site_select = document.getElementById("site"); var location_select = document.getElementById("location"); console.log(site_select); console.log(location_select); site_select.onchange = function() { site = site_select.value; console.log(site); fetch('/location/' + site).then(function(response) { response.json().then(function(data) { var optionHTML = ''; for (var location of data.Location_Choice_list) { optionHTML += '<option value="' + location.id + '">' + location.location + '</option>'; } location_select.innerHTML = optionHTML; }) }) } var city_select = document.getElementById("city"); location_select.onchange = function() { location = location_select.value; alert(location); fetch('/city/' + location).then(function(response) { response.json().then(function(data) { var optionHTML = ''; for (var city of data.City_Choice_list) { optionHTML += '<option value="' + city.id + '">' + city.city + '</option>'; } city_select.innerHTML = optionHTML; }) }) } </script> </body> </html> Here is where the problem is. As we can see, there are two routes '/location/' and '/city/'. These two routes are to return a jsonified version of the locations that belong to a particular site and cities that belong to a particular location. The javascript does a fetch to these URLs and then uses the entries in the jsonified output to form the select statements for the next dropdowns. Now here the first dependent dropdown (location), on selecting "site", changes perfectly as expected. I have just written the exact function for getting the cities for a particular location. As can be seen from the code, the onchange values of the site and location are got through the usual (.value) attribute of the select statement. For the site, I get the correct value after selecting. But for location, after selecting, the value that is getting returned (I have alerted) is "http://<IP_ADDRESS>:5000/Welcome" and so this value is being used by the javascript while fetching which obviously will lead to a 404 error. So I am not sure, why the first function is working fine and the second is not. I want to know the reason why the location value is getting captured as a URL instead of the value selected. Because it's getting returned as a URL, I am getting the dreadful "Uncaught (promise) unexpected token < at position 0. I have also tried to print out the initial site_select and location_select values which also good without any errors. I have looked into a lot of posts in the net for this but nothing has worked till now and it's been a week now with this dreadful error. Thanks for the help in advance. so your problem is with line location = location_select.value;. In location variable you are getting url instead of id. Am I correct? Yes, I am getting the URL instead of the actual value of location that is selected from the dropdown. what val is present in object location.location? Your location variable is conflicting with the window.location variable, which is taking the current document url- https://developer.mozilla.org/en-US/docs/Web/API/Window/location var list = [{"id":" ","location":" "}, {"id":"CN0","location":"CN0"},{"id":"India","location":"India"},{"id":"Japan","location":"Japan"},{"id":"Honkong","location":"Honkong"},{"id":"GB0","location":"GB0"}]; const countries = document.querySelector('#countries'); let optionHTML = ""; list.forEach((obj) => { optionHTML += '<option value="' + obj.id + '">' + obj.location + '</option>'; }); countries.innerHTML = optionHTML; countries.addEventListener('change', function() { location = this.value; // alert(location); alert(window.location === location); }); <select name="" id="countries"></select> Instead use different variable other than location or use block-scoped variable using let or const which are not hoisted and does not conflicts with the global variables. var list = [{"id":" ","location":" "}, {"id":"CN0","location":"CN0"},{"id":"India","location":"India"},{"id":"Japan","location":"Japan"},{"id":"Honkong","location":"Honkong"},{"id":"GB0","location":"GB0"}]; const countries = document.querySelector('#countries'); let optionHTML = ""; list.forEach((obj) => { optionHTML += '<option value="' + obj.id + '">' + obj.location + '</option>'; }); countries.innerHTML = optionHTML; countries.addEventListener('change', function() { let location = this.value; console.log(location); }); <select name="" id="countries"></select> {"Location_Choice_list": [{"id":" ","location":" "}, {"id":"CN0","location":"CN0"},{"id":"India","location":"India"},{"id":"Japan","location":"Japan"},{"id":"Honkong","location":"Honkong"},{"id":"GB0","location":"GB0"}]} This is the jsonified version containing the locations for site "International" returned by the def location(site) function. I will correct this --- locationObj['id'] = location.id locationObj['location'] = location.location. c is initially a list containing one dictionary item. Then I append each dictionary element to this list. So finally the {'Location_Choice_list': c} will have Location_Choice_List and the value c will be list with each element in it being a dictionary. Below is the select statement for location initially obtained from def(index): CN0India Japan Honkong GB0 Also there is actually no problem with this function. When I press "International", all the locations corresponding to it are getting populated in the locations dropdown. Also, the same works when I give the site as "Domestic". The problem is when I select a particular location, the value location is taking is this URL "http://<IP_ADDRESS>:5000/Welcome". So there is something wrong with second function. Changed the location variable to countries. Things worked. Thankyou so much @AshwinKumarS - If the solution solves your problem, mark it as accepted to indicate that problem has been solved.
common-pile/stackexchange_filtered
golang how to use tool find where the ticker leak? I find my process use high cpu when there was not business request I use go-torch find most of the cpu was waste in runtime.timeproc I think it must because time.NewTicker leak(not stop) in somewhere, or create ticker in a for loop so how can i using any tool to find it in fact, i had search it and ever ticker was follow a defer ticker.Stop() Can you please add a minimal and complete example following https://stackoverflow.com/help/mcve ? Your question is really hard to answer otherwise I doubt ticker (or the time pkg) is causing CPU load. Tickers can leak memory however, if you don't stop (to reclaim the channel they rely on). See the example here. I find the method to find out the leak Ticker In heap profile, you can type: go tool pprof http://xxx/debug/pprof/heap tree time.NewTicker can it will show where the ticker create, something like the following:
common-pile/stackexchange_filtered
Java thread state transition, WAITING to BLOCKED, or RUNNABLE? There seems to be a discrepancy between SO consensus and nearly every Java thread state diagram on the Internet; specifically, regarding thread state transition from WAITING after notify() or notifyAll() is invoked... WAITING never goes directly to RUNNABLE The thread is WAITING until it is notified...Then it becomes BLOCKED... Once this thread is notified, it will not be runnable...This is..Blocked State. So the concensus on SO is: a thread transitions from WAITING to BLOCKED after invoking notify() or notifyAll(); diagram below illustrates this transition in green. Question Why do most state diagrams on the web illustrate the transition from WAITING to RUNNABLE, not BLOCKED? Depiction in red shows the incorrect transition; am I missing something? Why would I ask the person who drew the diagram when based on your comment they don't know better? :-) I said "don't or didn't". If you ask them, they may discover that they are wrong. Or they may already have discovered. So you're saying my diagram is more accurate than roughly 106,000 Google results? Hellulalua! No. I doubt that there are 106,000 different state diagram images on the web ... If that is the case, what is special with TIMED_WAIT ? why it is directly going back to RUNNABLE, instead of moving to BLOCKED ? there are some clearer answers, if you need. https://stackoverflow.com/q/15680422/2361308 Any diagram that shows a notify invocation bringing a thread from WAITING to RUNNABLE is wrong (or is using an unclarified shortcut). Once a thread gets awoken from a notify (or even from a spurious wakeup) it needs to relock the monitor of the object on which it was waiting. This is the BLOCKED state. Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait. This is explained in the javadoc of Object#notify(): The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. and Object#wait() The thread then waits until it can re-obtain ownership of the monitor and resumes execution. Makes sense. But, surely that's true of TIMED_WAITING too then? Except if it has entered the TIMED_WAITING state due to sleep(t) that is. @mystarrocks According to the Thread.State javadoc, WAITING is for the parameterless Object#wait, while TIMED_WAITING is for the overload that accepts a wait time. Yes, this applies to both. Concerning sleep, a thread doesn't unlock any held monitors, it still owns them by the time it wakes up. I am focusing on the problem recently. as the Oracle document Thread.State says we can use LockSupport.park() to put the current thread into 'WAITING' or 'TIMED_WAITING' state. so when you try the LockSupport.unpark(), the specified thread will return to 'RUNNABLE' from 'WAITING'/'TIMED_WAITING'. (I am not sure whether it will go through the 'BLOCKED' state) I think LockSupport.unpark() will cause the specified thread state changing from WAITING to RUNNABLE directly. It is worth to mention that is also true for Thread.interrupt() method during WAITING state while in lock.wait() method. Thread.interrupt() method will firstly make WAITING thread BLOCKED with isInterrupted flag set to true, and only after reacquiring lock interrupted thread will be able to throw InterruptedException (that is obvious, as it cannot handle exception, by that continuing execution without having exclusive lock before). (example here) Simply to say Always WAITING -> BLOCKED to be able again compete for the lock, and after that to acquire it eventually and run its' code RUNNABLE.
common-pile/stackexchange_filtered
Need to Fetch Row which have count 2 i have table A such as TABLE1 ======================= | id | product_id | filter_id | category_id | | 16 | 33 | 6 | Null | | 23 | 40 | 16 | 76 | | 48 | 20 | 6 | 45 | | 69 | 10 | 6 | 87 | | 70 | 10 | 9 | 67 | Now i have to find product_id 10 which have filter_id 6 and 9 Please always provide what you have already tried. use one of this samples SELECT * FROM TABLE1 WHERE products_id = 10 AND filter_id IN (6,9); OR SELECT * FROM TABLE1 WHERE products_id = 10 AND (filter_id = 6 OR filter_id = 9); IMO I think OP want to find row have count(product_id) = 2, as in title of OP's question @Pham X. Bach - yes you right - take the answer from Pham X. Bach You could just use having select product_id, count(product_id) from teble1 group by product_id having count(product_id) = 2;
common-pile/stackexchange_filtered
Is it possible to block non-PyPI requests during pip install? In 2017 and 2018 there were these infamous stories about malicious packages being uploaded to the PyPI (Python Package Index) which tried to do all sorts of things (collecting and sending data, reverse shells etc) during installation as pip and setuptools would execute setup.py install automatically when setting up a new package. Would it be possible to block or at least warn about any network requests going to non-PyPI servers that happen during a package installation? Is it a good counter-measure for this kind of a situation? That depends on what measures you're willing to take. There are a number of ways to do this, from mandatory access controls to seccomp brokers or patches to netfilter. The simplest way would be to run the installer under a specific group, and have netfilter deny network access to any IP but whitelisted ones. Is it a good counter-measure for this kind of a situation? No. Unfortunately what you're planning to do won't address this specific threat. Here, the attackers compromised the package on PyPI itself, hence it was downloaded from the original source, so limiting downloads only to PyPI would have no effect. In most cases, these compromised packages come in two flavours: Attackers gain control of a legitimate package and inject malicious code into it. e.g. NPM event-stream Attackers create a malicious package that looks similar to the legitimate package (jeIlyfish vs. jellyfish) -- the form uses the upper-case 'i' instead of 'l'. It's hard to address this without some tooling, ultimately it's nice to be able to build everything yourself, but sooner or later you're going to need external packages -- and sometimes those external packages get compromised. Even without attackers, legitimate CVEs are found in commonly used package and require upgrades on your part to protect your application. For this you need a tool, that scans your requirements.txt file and validates against a list of known vulnerable packages (either through this type of compromise or something else). Of course this is more post-build rather than pre-build, but you can incorporate into your build pipeline if required (validate requirements.txt before building). If you publish your code on Github, it automatically is scanned by Github against known vulnerable packages and warns you via email and on the repo homepage. There are other tools like pyup, synk, etc that do exactly the same thing. One of the requirements of Pypi is that the URI contains "api/pypi" on the path, so with a good firewall you can put a rule that only allows your domain that you trust pip and you can reject the rest with a regular expression that contains the api/pypi. You can accomplish this with setting up a Pi-Hole that proxies all of our DNS requests and then just write a regex blocking rule that blocks 'api/pyp' in the URL
common-pile/stackexchange_filtered
What is meant by the quantities written in the parenthesis of the below sentence of a problem? A rare Pokémon has appeared on your radar, you think it might be a Lapras, and you’re trying to track it down. As you’re walking down a straight road, you notice that your radar changes its distance indicator from 3 footprints (within 1 km) to 2 footprints (within 100 m) at point A. Then, after walking another 100 m, the distance indicator goes back up to 3 footprints at point B. I assume that "footprints" is a unit of length in PokemonGo which I haven't played. Exactly, how the change is taking place in different distances in 2 situations? It would be nice if you'll supplement your answer with a figure or something. NB- It is a part of a problem of an ongoing contest and I'm not looking for any hints or solutions but I just seeks the understanding of the meaning of the sentence given above. From what I understand, the number of footprints acts as an indication of how far away the particular Pokemon is to you. i.e. 3 footprints $\Rightarrow$ the Pokemon is $\leq 1$km away. 2 footprints $\Rightarrow$ the Pokemon is $\leq 100$m away. "Footprints" is not a unit of length since $3$ footprints $\ne \frac32 $ $2$ footprints. In other words, more footprints means further away, but the relationship isn't necessarily linear. Imagine yourself at the center of a circle of radius $100$ m. Then any Pokemon within that circle is $2$ footprints (or closer) to you. If a Pokemon is outside of that circle, but still within a bigger $1$ km circle, then it will appear as $3$ footprints away. Alternatively, you can think of it as concentric circles around the Pokemon like in the following diagram:
common-pile/stackexchange_filtered
Discount of Asian vs European vols I understand the discount for Asian vs. European vol depends on time to expiry and length of averaging period. This makes sense intuitively; a short averaging period far away blurs into a single expiry, while a close---but long---averaging period is very different from a bullet. Is there a rule of thumb to approximate that discount?
common-pile/stackexchange_filtered