text
stringlengths
70
452k
dataset
stringclasses
2 values
I have a technical interview for a spatial data analyst position - what should I expect? The job is handling spatial data for a public health research study. I don't have any specifics about the interview other than the interviewer, who is the lead GIS analyst for this organization. I assume there will be questions about projects I've done and maybe a live exercise. Is there somewhere I can find data-related practice exercises that would be helpful? Is there anything I'm missing or should prepare for? To be asked about analysing spatial data? I work in a similar role. Expect to be asked about your experience in GIS (ESRI, QGIS etc), obtaining data from various data sources, Python scripting, various spatial operations (intersecting, voronoi polygons, heatmaps), ETL (eg using SSIS) and probably database maintenance (or geodatabase if they're an ESRI shop) - maybe some postgres or spatial SQL. Is there somewhere I can find data-related practice exercises that would be helpful? Is there anything I'm missing or should prepare for? If you are applying to such position one would assume or expected that you actually know about spatial data analysis, so it puzzles me a bit that you are asking such question. If you know about such topics then I suggest you rehearse or go over the things you know, the tools you know how to use, past projects you could mention, etc.. We can't guess what they are going to ask you in the interview, so be prepared to showcase all your knowledge on the matter. Now, if you don't know about spatial data analysis then it is very unlikely that you will learn what's needed by doing some practice exercises on the topic, and even if you somehow managed to get hired this could turn into an ordeal later on (and will eventually be obvious that you are not fit for the role).
common-pile/stackexchange_filtered
concurrentStoreAndDispatch - where and how can I set it's value I am dealing with a migration to AWS AmazonMQ. I would like to set this value,"concurrentStoreAndDispatch", and cant find a way to change the default value. Thanks for your help I found it in the configuration of the broker - it is in the XML as a comment. concurrentStoreAndDispatch and set it as you need.
common-pile/stackexchange_filtered
How to make mouse in Windows 7 act the same as Windows XP In Windows XP using TweakUI I could enable an option so that when my mouse goes over an inactive window, it makes that window the active window. There is also another separate option so that if the window becomes active, it automatically becomes the topmost window. I like to enable the former but not the latter. For Windows 7 I have not been able to find the same thing. What I found instead is an option inside windows that does something similar. If I move my mouse over an inactive window, I have to hover over it for a while before it becomes active. It is not instantaneous. The second problem is that once it does become active, it automatically makes itself the topmost window, covering other things I don't want covered. In summary, this is what I want in Windows 7: When my mouse goes over an inactive window, it immediately makes it the active window. When it activates the window, it does not raise it above other windows. Very poorly written question. You're asking about a TweakUI feature in WinXP. Not a Win XP feature. Your title doesn't make that clear Thanks Phoshi for your answer. Since I stumbled on this link from a google-search I'm going to fill in some of the information missing from here and give a complete step-by-step guide for it: To get X-mouse working from a Vanilla Windows 7 install: Open the Control Panel Choose "Ease of Access" Choose "Change how your mouse works" Tick the box next to "Activate a window by hovering over it with the mouse" and hit "OK". Open regedit Locate HKEY_CURRENT_USER\Control Panel\Desktop\UserPreferenceMask - change the first byte only, you need to subtract hexidecimal 40 from value that is there (eg DF becomes 9F) - this disables Auto-raise on Activate Locate HKEY_CURRENT_USER\Control Panel\Desktop\ActiveWndTrkTimeout - change its value to something small. Lower values will make it more difficult to use floating temporary windows (such as the taskbar notification area widget) because they disappear of something else gets focus as you move to them, but lower values also improve responsiveness. You might start with 250ms and tweak it from there. Log out, log back in, et voila,... Steps 1-4 were mentioned in passing in the question, but not enumerated. Steps 5-8 are exactly what Phoshi said. Instead of manual registry hacks, try using system calls from SystemParametersInfo, especially SPI_GETACTIVEWINDOWTRACKING, SPI_GETACTIVEWNDTRKZORDER, SPI_GETACTIVEWNDTRKTIMEOUT. Using these calls also save you from having to log out/in in order to apply the settings. I created X-Mouse Controls, which implements them. X-Mouse Controls: Microsoft Windows utility to manage the active window tracking/raising settings. This is known as x-mouse behavior or focus follows mouse on Unix and Linux systems. You only need to run it once, it is small, open source and takes care of the details for you. (source: joelpurra.com) Thank you! A minimalist GUI front-end that [1] allows changing w/o needing a log out/in, [2] doesn't make me muck around with hexadecimal conversion in the registry, and [3] propagates changes to ease of access center so that it seems like it's doing things 'properly'. Right then! Open regedit, and let's get to work. Change HKEY_CURRENT_USER\Control Panel\Desktop\UserPreferenceMask into 9F 3E 07 80 12 00 00 00 Then change HKEY_CURRENT_USER\Control Panel\Desktop\ActiveWndTrkTimeout to 0 (you might have to switch the datatype to decimal). Then log out, log in, and (hopefully) enjoy your window switching! Works, but makes accessing hidden icons in the taskbar impossible. I click the arrow to expand the list, then when I try to move my mouse to the box it disappears before I reach it. Nevermind, I can access it I click on the arrow, then press tab to activate it. A little icky, but workable, I guess. You could use alt-tab more, maybe? This AutoHotkey script does that. Check the first lines, there are some parameters that change the behavior of the script: hover_task_buttons = 1 ; hover over taskbar button to activate window hover_task_group = 1 ; hover to select (or exit) from a window-group menu ; (for Windows' "Group similar taskbar buttons" feature) hover_task_min_info = 0 ; only show info for minimized windows, don't activate hover_start_button = 1 ; hover over start button to open start menu hover_min_max = 1 ; minimize or maximize by hovering over the min/max buttons hover_any_window = 0 ; activate any window by hovering (except the taskbar) hover_no_buttons = 1 ; ignore hover if a mouse button is in the down state hover_delay = 500 ; hover delay, from when the mouse stops moving ; WORKS, BUT NOT PERFECTLY: (brings the window forward, then puts it back in place) hover_keep_zorder = 0 ; don't bring windows forward, only activate them You'll be interested in the last one listed above, hover_keep_zorder, with the caveat that it does not work perfectly (it worked fine for me though). Don't forget to also set hover_any_window to 1. Vote timeouts are getting silly! I accidentally clicked ^ again, taking my previous upvote away, and now it won't let me re-upvote! Finding a trivial point to edit was difficult, darn your well-formed text :P Works, but makes accessing hidden icons in the taskbar impossible. I click the arrow to expand the list, then when I try to move my mouse to the box it disappears before I reach it. Oops, the above comment was meant for the person with the reg hack. I tried this and it didn't do anything. Perfect solution!
common-pile/stackexchange_filtered
Showing that $V \unlhd S_4$, so that $S_4$ is not simple. Let $V = \{id, (12)(34),(13)(24),(14)(23)\}$. I am trying to show that $V \unlhd S_4$, so that $S_4$ is not simple. As I understand it, to show that $V \unlhd S_4$ $-$ i.e. that $V$ is a normal subgroup of $S_4$ $-$ I need to show that $\forall x, \forall y \in V (xy^{-1} \in V)$ and that $\forall s \in S_4$, ( $sVs^{-1} = V)$. Is this correct? If so, how many checks do I need to make? Naively, a whole bunch. But at least for normality, if you know anything about what conjugation does to cycle structure, you can basically just appeal to that. Your set $V$ has $5$ elements, which cannot be a subgroup of $S_4$ which has $24$ elements. You can show $S_4$ is not simple since $A_4$ is a normal subgroup. If instead you're trying to $A_4$ is not a simple group, it may be easier to appeal to the Sylow theorems (specifically the third one) if you know them. Apologies everyone, I have adjusted the question. let $S_4$ act on the variables $x_1,x_2,x_3,x_4$ by permutation of suffixes in the obvious way. now define the three expressions: $$ A =(x_1x_2-x_3x_4)^2 \\ B =(x_1x_3-x_2x_4)^2 \\ C =(x_1x_4-x_2x_3)^2 $$ given any $\sigma \in S_4$ the action just defined induces a permutation of $A,B$ and $C$. can you (a) check that this construction gives a homomorphism $S_4 \to S_3$. (b) show that the kernel of this homomorphism is your group $V$? if so, then you have shown that $V \triangleleft S_4$ You could also use $x_1x_2+x_3x_4$, etc, and avoid squaring. This construction is related to the resolvent cubic associated to a degree four polynomial, where one takes $f$ with roots $r_1,\ldots,r_4$ and defines the cubic with roots $r_1r_2+r_3r_4$, etc. This allows to obtain the Galois group of $f$ by looking at that of $g$. thanks for that insight, Pedro Can you explain each part a bit more? I'm still new to group theory. Are you saying that each of the variables $x_i$ are the elements of $V$ or are they something else? Also, what do you mean by $(x_1x_2 - x_3x_4)^2$? For the case of $A$, am I just considering the cycle $(x_1x_2x_3^{-1}x_4)(x_1x_2x_3^{-1}x_4)$? If not, what is the meaning of $-x_3$? the framework is a group acting on a set. you could think of the $x_i$ as generators for an algebraic structure, e.g. a commutative polynomial ring such as $\mathbb{R}[x_1,x_2,x_3,x_4]$. Since all elements in $V$ are involutions, it's easy to check $V$ is a subgroup. Note that any conjugation will not change the order of an element. If $\exists s,v$ such that $svs^{-1}\notin V$, $svs^{-1}$ must be of the form $(i\ j)$. Then by symmetry, all elements of form $(i\ j)$ will be in the conjugacy class containing $V$. So the conjugacy class containing $V$ will consist of $6+3+1=10$ elements, which doesn't divide $|S_4|=24$. Contradiction. P.S. To show that $A_4$ is normal is much easier.
common-pile/stackexchange_filtered
How to convert those characters not quoted to upper case? To format thousands of SQL queries I need to convert all the characters not in quotation mark pair to upper case. For example: select * from region where regionkey = 'America' to be converted to SELECT * FROM REGION WHERE REGIONKEY = 'America' With perl I'm able to convert those quoted characters to upper case by: perl -p -e 's/('.+?')/\U\1/g' and get: select * from region where regionkey = 'AMERICA' The question is how to "reverse" the capture result, say, to march to not in quotation marks? are there quotes in the quotes? e.g. 'Hawai\'i'? SQL keywords are not case-sensitive. Why does it matter? @JimGarrison I'm working with a SQL engine which has all the database object names (incl. tables, views, fields) case-sensitive. I don't care it's "sELECt fROm" or "sElEcT FoRm", but REGIONKEY or RegionKey does matter. In my use case all the objects are named in upper case, to simplify the processing, I just convert everything outside the quote to upper case. Table/Column names shouldn't be case-sensitive unless quoted. Which DB engine are you using? @JimGarrison An in-house built one done by some students many years ago... s/([^']*)('[^']*'|\z)/\U$1\E$2/g so perl -pe's/([^'\'']*)('\''[^'\'']*'\''|\z)/\U$1\E$2/g' ysth suggests a mixed-quote approach: perl -pe"s/([^']*)('[^']*'|\z)/"'\U$1\E$2/g' If the quotes can have backslash escapes in them, change '[^']*' to '(?:[^'\\]+|\\.)*' Split the string on quoted substrings and uppercase every other chunk. Like this my $str = "select * from region where regionkey = 'America'"; my $uc; $str = join '', map { ($uc = !$uc) ? uc : $_ } split /('[^']*')/, $str; print $str; output SELECT * FROM REGION WHERE REGIONKEY = 'America' One-liner: perl -pe'$_ = join "", map { ($uc^=1) ? uc : $_ } split '"/('[^']*')/"', $_'
common-pile/stackexchange_filtered
Saving dynamic formset with more than one form I've built dynamic forms using django formsets and javascript, but unfortunately on submitting the form only the first form is submitted. I'd like all dynamically added forms to be submitted also. Any help would be appreciated. Views: def routestepinfo(request): class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False RouteStepFormSet = formset_factory(RouteStepForm, formset=RequiredFormSet, extra=1, can_order=False, can_delete=True) if request.method == 'POST': formset = RouteStepFormSet(request.POST) if formset.is_valid(): for form in formset.forms: form.save() print 'apple' return redirect("/buildpage/") else: formset = RouteStepFormSet() return render(request, "buildpage/routestepinfo.html", {'formset' :formset}) HTML <form id= "myForm" method = 'POST' action="{% url 'buildpage:routestepinfo' %}" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <div id="form_set"> {% for form in formset %} <table class='no_error'> <tbody>. {{form.as_table}} </tbody> </table> {% endfor %} </div> <p><input type = "button" value = "Add another step" id = "add_more" ></p> <div id="empty_form" style="display:none"> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </div> <div id="forms"></div> <p>&nbsp;</p> <p>&nbsp;</p> <input type = "submit" name = "Submit Steps"> </form> JS Clone: <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> You don't appear to be giving each dynamic form a unique name attribute. eg. any INPUT's etc inside your formset.empty_form.as_table will need there name attribute modifying. Unless of course your have them prefixed with __prefix__. If you look at the forms in chrome debugger, are all you field's getting unique name attributes. Hi Keith, according to the docs providing a BaseFormSet gives an automatic prefix of prefix, unless I've misunderstood. BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript. So I guess the follow up question is, is there a method of creating unique ID's with each additional form through javascript? I think this line -> $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); is your problem, your not actually replacing anything.. var h = $('#form_set').find('#empty_form').html(); $('#form_set').append($('#empty_form').html(h.replace(/__prefix__/g, form_idx)) I would also suggest, to make sure this is doing what you expect, that from say Chrome debugger have a look at the Elements tab and see what name attributes have been set. I'm a bit of a javascript amateur myself, using that line has given the error Cannot read property 'replace' of undefined Sorry, yeah.. Looking at your HTML, you #empty_form, is not inside your #form_set.. So it should have just been var h = $('#empty_form').html(); Interestingly, the cloned elements look like this I assume form_idx is then undefined. var form_idx = $('#id_form-TOTAL_FORMS').val(); where is #id_form-TOTAL-FORMS getting set? Hi Keith, so I fixed the id issue, but still only one form is saving. I don't think javascript is the fix for that, so I'm trying out different things on my views. Fixed it ! Only took a week. Here's how it worked eventually. Views are largely unmodified, just added commit=False to save the list. def routestepinfo(request, slug=None): RouteStepFormSet = formset_factory(RouteStepForm, formset = RequiredFormSet, extra=1) if request.method == 'POST': formset = RouteStepFormSet(request.POST) print formset if formset.is_valid(): for form in formset.forms: form_item = form.save(commit=False) print form form_item.save() messages.success(request, "Record created") return redirect ("/buildpage/") else: formset = RouteStepFormSet() return render(request, "buildpage/routestepinfo.html",{'formset':formset}) Javascript was the main thing that changed, with quite a few additions and quite a bit of SO help. The prefix was the first issue, and that was fixed by using formset.empty_form and modifying it from there. Another vital part was updating the total forms, which fixed the saving issue. <script> $(document).ready(function() { $('.add-item').click(function(ev) { ev.preventDefault(); var count = $('#items-form-container').children().length; var tmplMarkup = $('#item-template').html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count); $('div#items-form-container').append(compiledTmpl); // update form count $('#id_form-TOTAL_FORMS').attr('value', count+1); $('html, body').animate({ scrollTop: $("#add-item-button").position().top-200 }, 800); }); }); </script> Finally the html. This combined some of my own stuff with a very helpful SO post(forgot the question it came from), where formset is generated as an empty form and cloned from there.: <div type="text/html" id="item-template"> <table> {{ formset.empty_form.as_table }} </table> </div> <font face = Flexo> <form id= "myForm" method = 'POST' action="{% url 'buildpage:routestepinfo' %}" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <div id="items-form-container"> {% for form in formset.forms %} <div id="item-{{ forloop.counter0 }}"> <table> {{form.as_table}} <table> </div> {% endfor %} </div> <a href="#" id="add-item-button" class="btn btn-info add-item">Add Step</a> <input type = "submit" name = "Submit Steps"> </form> Hope this helps some people. Cheers
common-pile/stackexchange_filtered
XArray: Create a new coordinate / dimension from an attribute I'm using a library (georinex) that reads GPS RINEX data and returns an xarray in return. The typical data I would get in return from parsing the rinex file from one GPS receiver station is for example this one: <xarray.Dataset>Users\eballes\Desktop\share\226_day\225_highrate\00\abpo225a00.14n Dimensions: (sv: 12, time: 2) Coordinates: * time (time) datetime64[ns] 2014-08-13 2014-08-13T02:00:00 * sv (sv) <U3 'G01' 'G03' 'G07' 'G08' ... 'G27' 'G28' 'G32' Data variables: SVclockBias (time, sv) float64 nan nan nan ... 0.0003767 -0.0003641 SVclockDrift (time, sv) float64 nan nan nan ... 2.728e-12 8.413e-12 SVclockDriftRate (time, sv) float64 nan nan nan nan nan ... 0.0 0.0 0.0 0.0 IODE (time, sv) float64 nan nan nan nan ... 89.0 60.0 85.0 64.0 Crs (time, sv) float64 nan nan nan nan ... -29.56 100.2 78.56 DeltaN (time, sv) float64 nan nan nan ... 3.904e-09 5.106e-09 M0 (time, sv) float64 nan nan nan nan ... 0.6369 1.585 -1.493 Cuc (time, sv) float64 nan nan nan ... 4.929e-06 4.02e-06 Eccentricity (time, sv) float64 nan nan nan ... 0.01919 0.01139 Cus (time, sv) float64 nan nan nan ... 9.466e-06 8.697e-06 sqrtA (time, sv) float64 nan nan nan ... 5.154e+03 5.154e+03 Toe (time, sv) float64 nan nan nan ... 2.664e+05 2.664e+05 Cic (time, sv) float64 nan nan nan ... -7.078e-08 -1.863e-08 Omega0 (time, sv) float64 nan nan nan nan ... 2.154 1.175 -1.948 Cis (time, sv) float64 nan nan nan ... -4.619e-07 -1.434e-07 Io (time, sv) float64 nan nan nan ... 0.9641 0.9871 0.9473 Crc (time, sv) float64 nan nan nan nan ... 338.2 208.2 206.5 omega (time, sv) float64 nan nan nan ... 0.3215 -1.71 -0.1162 OmegaDot (time, sv) float64 nan nan nan ... -7.925e-09 -8.374e-09 IDOT (time, sv) float64 nan nan nan ... 5.997e-10 6.879e-10 CodesL2 (time, sv) float64 nan nan nan nan nan ... 0.0 0.0 0.0 0.0 GPSWeek (time, sv) float64 nan nan nan ... 1.805e+03 1.805e+03 L2Pflag (time, sv) float64 nan nan nan nan nan ... 0.0 0.0 0.0 0.0 SVacc (time, sv) float64 nan nan nan nan nan ... 2.0 2.0 2.0 2.0 health (time, sv) float64 nan nan nan nan nan ... 0.0 0.0 0.0 0.0 TGD (time, sv) float64 nan nan nan ... -1.071e-08 -3.26e-09 IODC (time, sv) float64 nan nan nan nan ... 89.0 60.0 85.0 64.0 TransTime (time, sv) float64 nan nan nan ... 2.592e+05 2.592e+05 FitIntvl (time, sv) float64 nan nan nan nan nan ... 4.0 4.0 4.0 4.0 Attributes: version: 2.1 svtype: ['G'] rinextype: nav filename: abpo225a00.14n As you can see Coordinates are time and sv. However for my particular problem I would need to add the data variable TransTime as a Coordinate. Unfortunately I am not able to get anything working and I haven't found any example useful for modifying the structure of an already existing xarray since I assume the most normal approach would be to create it directly with the correct coordinates. The code up to this point is straightforward using this data after uncompress it: import georinex as gr nav = gr.load('abpo225a00.14n') And is in this point where I should transform nav into something similar to: <xarray.Dataset>Users\eballes\Desktop\share\226_day\225_highrate\00\abpo225a00.14n Dimensions: (sv: 12, time: 2) Coordinates: * time (time) datetime64[ns] 2014-08-13 2014-08-13T02:00:00 * sv (sv) <U3 'G01' 'G03' 'G07' 'G08' ... 'G27' 'G28' 'G32' * TransTime (TransTime) <values from TransTime variable> Try nav = nav.assign_coords(TransTime=nav.TransTime]) Technically from my question the accepted answer is correct. Unfortunately it was not enough for my problem which I couldn't really formulate correctly. When assigning coordinates with the accepted answer the resulting Xarray had this shape: Coordinates: * time (time) datetime64[ns] 2014-08-13 2014-08-13T02:00:00 * sv (sv) <U3 'G01' 'G03' 'G07' 'G08' ... 'G27' 'G28' 'G32' TransTime (sv, time) <values from TransTime variable> which is not what I was actually looking for (or at least it was not something useful for me) since the new coordinate was depending on the other two indexes and was not indexed itself. I realized that what I really wanted was not a new coordinate but a change of index. In the end what actually work for this goal was to go to the DataFrame level, remove the current indexes, create new indexes and come back to an xarray nav = gr.load(file_path).to_dataframe().dropna(how='all') nav = nav.reset_index(['time', 'sv']) nav = nav.set_index(['sv','TransTime']) nav = nav.to_xarray() I hope this may be useful for somebody starting in XArray/Pandas that come across to this question not fully knowing what they want.
common-pile/stackexchange_filtered
Conditionally specifying switch parameters in PowerShell I'm writing a PowerShell script that uses the SharePoint 2010 New-SPWeb cmdlet to create sites defined by an Xml file: <?xml version="1.0" encoding="utf-8" ?> <siteStructure> <site> <url>Corporate</url> <name>Corporate</name> <language>1033</language> <addToQuickLaunch>0</addToQuickLaunch> <addToTopNav>0</addToTopNav> <useParentTopNav>1</useParentTopNav> </site> </siteStructure> The New-SPWeb cmdlet has three switch parameters: AddToQuickLaunch AddToTopNav UseParentTopNav I'm having trouble figuring out how to only set the switch parameter when the matching value in the Xml is 0 or $true. It's almost like I need some sort of inline-if syntax when calling New-SPWeb to set the three switch parameters. $siteStructureData = [xml](Get-Content .\Data-SiteStructure.xml) # find the template to use $webTemplate = Get-SPWebTemplate | Where {$_.Title -like $templateName } if ($webTemplate) { # iterate through and create sites foreach ($siteToCreate in $siteStructureData.siteStructure.site) { "Creating site $webtitle at $URL/$webUrl" # http://technet.microsoft.com/en-us/library/ff607579.aspx New-SPWeb ` -Url "$URL/$siteToCreate.url" ` -Name $siteToCreate.name ` -Template $webTemplate ` -Language $siteToCreate.language # set -AddToQuickLaunch # set -AddToTopNav # set -UseParentTopNav } } else { throw ("Could not find template $templateName"); } Many thanks! Wow! I am doing exactly the same thing! Only nearly 2 years later Calculate the $result ($true or $false) before: $result = ... And use it after: New-SPWeb ` -Url "$URL/$siteToCreate.url" ` -Name $siteToCreate.name ` -Template $webTemplate ` -Language $siteToCreate.language ` -AddToQuickLaunch:$result ` -AddToTopNav:$result ` -UseParentTopNav:$result Thank you, Roman. I wasn't aware of that syntax for switch parameters. Yes, it is not easy to discover... Long time ago I had a problem as well. Thanks for that... Just discovered in powergui if you put a colon after a parameter, the intellisense lets you know you can specify $true or $false There is one more way. You can use splatting like this: $params = @{ Url = "$URL/$siteToCreate.url" Name = $siteToCreate.name Template = $webTemplate Language = $siteToCreate.language } # if needed, add the keys to the hashtable if ($result) { $params.AddToQuickLaunch = $true $params.AddToTopNav = $true $params.UseParentTopNav = $true } # now you just pass the parameters: New-SPWeb @params More about splatting: What does the "@" symbol do in Powershell? http://blogs.msdn.com/b/powershell/archive/2009/01/02/how-and-why-to-use-splatting-passing-switch-parameters.aspx
common-pile/stackexchange_filtered
ufw differentiates block-and-log from unmatched log I insert block rules using this kind of statements sudo ufw insert 1 deny log from <IP_ADDRESS>/24 I have a few hundreds of such deny-log rules. ufw will block the IP and log the event. However, another feature that comes with ufw logging low is that ufw will also log packets not matching the defined policy. I want to separate or differentiate the ones I explicitly set as deny log from the ones because of unmatching. --log-prefix in /etc/ufw/user.rules looks promising, but once I add new rules to ufw through the ufw interface, my modifications on user.rules are lost. How do I set up so that for each entry in ufw.log, I can quickly tell if it's blocked by my deny-log rules or because of not matching the defined policy?
common-pile/stackexchange_filtered
Where do I view impression tracking? I've started using impression tracking in my content blocks, but where do you actually view the report? Can someone provide me with a pathway, thanks. Impression tracking allows you to track links built with ampscript. This is because when you build links with amspcript, they will not have friendly names unless you use Impression Regions or alias tags. Once you have declared the impression regions and tagged them with unique identifiers, you can view the information in the Reports or through Data Extracts. For Reports, Navigate to Email Studio > Tracking > Reports Under Tracking Reports, you get the options of "Impression Tracking by Job" or if you are concerned about a Triggered Send, "Impression Tracking for Triggered Sends" You get a warning that these reports are not been updated and advised to use analytics builder. To access the reports via analytics builder, Scroll over the marketing cloud icon in the top left to access the drop down and analytics builder Select "Reports" then go on to "Email" The Impression Tracking Reports are at the bottom of the page. If you use case involves feeding this data directly into 3rd party systems then I would recommend using data extracts. Here you can access SendJobImpression, SentImpressions. References: Marketing Cloud Reports Types of Data Extracts The Reports shown above are not automatically enabled. We had to reach out to our Rep to have those reports available for us to use.
common-pile/stackexchange_filtered
Clock cycle and R-type command execution times How long will the clock cycle take in ns and how long will it take for the R-type command ADD $1, $2, $3 to execute, in a: Single-cycle datapath Multi-cycle datapath Pipelined datapath For a single cycle processor, the timing of a cycle and the timing of an instruction are the same value.  All the functions have to be able to occur in the same cycle, so add up the timings of all the functions, and that is both the minimum timing that a cycle can be and also the timing of an instruction. For multi-cycle processor and pipelined processor, the timing of cycles and instructions are separate, as instructions are spread over multiple cycles. For the pipelined processor, every function (stage) must have the same cycle time, because all the stages overlap.  So, the cycle time is the max among the individual stages.  Multiply that cycle time by the number of stages and that is the duration of an instruction.  (Also due to the stage overlap, every instruction goes through every stage.). So, this gives the timing of one instruction going through the whole pipeline; however, because instruction execution overlaps, in the ideal situation, there is one instruction completed per cycle, despite going through 5 pipeline stages at one cycle each, so that gives another answer to the number of cycles for an add instruction. Multi-cycle, is more complicated (compared with pipelined) because without overlap of the stages there is no real requirement that (1) all stages have the same duration, and (2) that every instruction executes all of the stages. Regarding the former, the timing of each stage is potentially varied, as there is no reason to draw out any individual stage longer than necessary.  The way that would be done is to run a much faster clock and make the individual stages some multiple of that faster clock.  For example, using a 1ns clock, the first stage could take 3 cycles for 3ns of work, then 2, 2, 4 and 2, respectively.  That makes the first question awkward to answer, because it asks in terms of clock speed which would have to be 1ns in my example, but could also be 1/2 ns or 1/4 ns, as long as each stage uses as many cycles as it needs to result in that duration. Regarding the latter, the Data Mem stage is irrelevant to an add instruction, so would most likely be skipped by the stage controlling unit.  In that situation the timing of an add instruction would be the sum of just the relevant stages. In a pipelined CPU (with bypass forwarding as shown), later instructions can use the result in the cycle after add $1, $2, $3 runs in the ALU stage. Also, it doesn't need its inputs ready until it hits the ALU stage. So you could argue that it's a single-cycle instruction (both throughput and latency). Talking about the whole length of the pipeline is not relevant for ADD. Good point about clocks for a multi-cycle implementation. We don't know if those are just max critical-path lengths (but limiting to the same clock speed as pipelined), or if those are the actual times spent during execution. Stuff like this (as well as lack of attempt / effort) is why I downvoted the question. But since you posted an interesting answer, I edited again to inline the image.
common-pile/stackexchange_filtered
Finding word association strengths from an input text I have the written the following (crude) code to find the association strengths among the words in a given piece of text. import re ## The first paragraph of Wikipedia's article on itself - you can try with other pieces of text with preferably more words (to produce more meaningful word pairs) text = "Wikipedia was launched on January 15, 2001, by Jimmy Wales and Larry Sanger.[10] Sanger coined its name,[11][12] as a portmanteau of wiki[notes 3] and 'encyclopedia'. Initially an English-language encyclopedia, versions in other languages were quickly developed. With 5,748,461 articles,[notes 4] the English Wikipedia is the largest of the more than 290 Wikipedia encyclopedias. Overall, Wikipedia comprises more than 40 million articles in 301 different languages[14] and by February 2014 it had reached 18 billion page views and nearly 500 million unique visitors per month.[15] In 2005, Nature published a peer review comparing 42 science articles from Encyclopadia Britannica and Wikipedia and found that Wikipedia's level of accuracy approached that of Britannica.[16] Time magazine stated that the open-door policy of allowing anyone to edit had made Wikipedia the biggest and possibly the best encyclopedia in the world and it was testament to the vision of Jimmy Wales.[17] Wikipedia has been criticized for exhibiting systemic bias, for presenting a mixture of 'truths, half truths, and some falsehoods',[18] and for being subject to manipulation and spin in controversial topics.[19] In 2017, Facebook announced that it would help readers detect fake news by suitable links to Wikipedia articles. YouTube announced a similar plan in 2018." text = re.sub("[\[].*?[\]]", "", text) ## Remove brackets and anything inside it. text=re.sub(r"[^a-zA-Z0-9.]+", ' ', text) ## Remove special characters except spaces and dots text=str(text).lower() ## Convert everything to lowercase ## Can add other preprocessing steps, depending on the input text, if needed. from nltk.corpus import stopwords import nltk stop_words = stopwords.words('english') desirable_tags = ['NN'] # We want only nouns - can also add 'NNP', 'NNS', 'NNPS' if needed, depending on the results word_list = [] for sent in text.split('.'): for word in sent.split(): ''' Extract the unique, non-stopword nouns only ''' if word not in word_list and word not in stop_words and nltk.pos_tag([word])[0][1] in desirable_tags: word_list.append(word) ''' Construct the association matrix, where we count 2 words as being associated if they appear in the same sentence. Later, I'm going to define associations more properly by introducing a window size (say, if 2 words seperated by at most 5 words in a sentence, then we consider them to be associated) ''' import numpy as np import pandas as pd table = np.zeros((len(word_list),len(word_list)), dtype=int) for sent in text.split('.'): for i in range(len(word_list)): for j in range(len(word_list)): if word_list[i] in sent and word_list[j] in sent: table[i,j]+=1 df = pd.DataFrame(table, columns=word_list, index=word_list) # Count the number of occurrences of each word in word_list all_words = pd.DataFrame(np.zeros((len(df), 2)), columns=['Word', 'Count']) all_words.Word = df.index for sent in text.split('.'): count=0 for word in sent.split(): if word in word_list: all_words.loc[all_words.Word==word,'Count'] += 1 # Sort the word pairs in decreasing order of their association strengths df.values[np.triu_indices_from(df, 0)] = 0 # Make the upper triangle values 0 assoc_df = pd.DataFrame(columns=['Word 1', 'Word 2', 'Association Strength (Word 1 -> Word 2)']) for row_word in df: for col_word in df: ''' If Word1 occurs 10 times in the text, and Word1 & Word2 occur in the same sentence 3 times, the association strength of Word1 and Word2 is 3/10 - Please correct me if this is wrong. ''' assoc_df = assoc_df.append({'Word 1': row_word, 'Word 2': col_word, 'Association Strength (Word 1 -> Word 2)': df[row_word][col_word]/all_words[all_words.Word==row_word]['Count'].values[0]}, ignore_index=True) assoc_df.sort_values(by='Association Strength (Word 1 -> Word 2)', ascending=False) This produces the word associations like so: Word 1 Word 2 Association Strength (Word 1 -> Word 2) 330 wiki encyclopedia 3.0 895 encyclopadia found 1.0 1317 anyone edit 1.0 754 peer science 1.0 755 peer encyclopadia 1.0 756 peer britannica 1.0 ... ... ... However, the code contains a lot of for loops which hampers its running time. Specially the last part (sort the word pairs in decreasing order of their association strengths) consumes a lot of time as it computes the association strengths of n^2 word pairs/combinations, where n is the number of words we are interested in (those in word_list in my code above). So, the following are what I would like some help on: How do I vectorize the code, or otherwise make it more efficient? Instead of producing n^2 combinations/pairs of words in the last step, is there any way to prune some of them before producing them? I am going to prune some of the useless/meaningless pairs by inspection after they are produced anyway. Also, and I know this does not really fall into the purview of code review, but I would love to know if there's any mistake in my logic, specially when calculating the word association strengths. Review Styling Import should be at the top of the file Use a if __name__ == '__main__': guard Split some functionality into function, keeping everything in the global namespace is considered bad form Use str.translate for cleaning texts This should faster compared to regex substitution Secondly you can use string.punctuation which in is in the standard library, making your first code block: trans_table = str.maketrans('', '', string.punctuation.replace('.', '')) trans_text = text.translate(trans_table).lower() You'd still need to clean the wiki references [15]...etc from the text though Why do you import nltk 2 times? Just import nltk once Using set lookup is O(0) Instead of checking if a variable is in a list you should compare against a set, this will improve performance, see Python time complexity stop_words = set(nltk.corpus.stopwords.words('english')) Use list comprehension List comprehension should be a bit faster compared to appending in a for loop, and it is considered Pythonic, Secondly you can pre-process the text to hold a list of sentences, instead of calculating it everytime word_list = set( word for sent in trans_text.split('.') for word in sent.split() if word not in stop_words and nltk.pos_tag([word])[0][1] in desirable_tags ) sentences = [ set(sentence.split()) for sentence in trans_text.split('.') ] Use enumerate if you need both the item and the index table = np.zeros((len(word_list), len(word_list)), dtype=int) for sent in sentences: for i, e in enumerate(word_list): for j, f in enumerate(word_list): if e in sent and f in sent: table[i,j] += 1 Use collections.Counter() for counting words And you can create a dataframe from Counter in one go with count_words = pd.DataFrame.from_dict(Counter(word_list), orient='index').reset_index() But you don't need to convert it to a dataframe at all, since you can get the word count by just reading the Dictionary count_words = Counter(word_list) ... assoc_df = assoc_df.append({'Word 1': row_word, 'Word 2': col_word, 'Association Strength (Word 1 -> Word 2)': df[row_word][col_word]/count_words[row_word]}, ignore_index=True) Note that I am not really into Pandas/Preprocessing so I might have missed a few things :) I'll definitely try these suggestions. The biggest problem seems be in the last segment - all the other code blocks finish within a minute or two each, at max. But the last segment for calculating word pair association strengths, with a different piece of input text that produces 800 odd words in word_list, is going on running for the last 2 hours. So, that's the more urgent part. I might take another stab at it when I have some time again. Or maybe someone else will pick that up. "Using set lookup is O(0)" You mean O(1).
common-pile/stackexchange_filtered
Programmatically implement WCF with Certificate I am quite new to WCF and trying to get my head around the security. I am still reading and learning, but I came to a point where I got a working version of WCF with Certificate authentication. I know that the code has some weaknesses; however, my initial goal was to create communication using certificate authentication. Also, I wanted to create everything programmatically (no Web.config configurations for the services or clients). The reason for this is that the client should be able to link an Assembly (Class Library) and get access to the server. Also, I am loading the certificates from the file system (again, I know this is not secure). I would like to get a little bit feedback. The following client snippet is creating an object that I can use to connect to the server. The anonymous type T is my service interface e.g. IService. Here is my client implementation: var url = "URL TO WS"; var binding = new WSHttpBinding { Security = { Mode = SecurityMode.Message, Message = {ClientCredentialType = MessageCredentialType.Certificate} } }; var endpoint = new EndpointAddress(url); var channelFactory = new ChannelFactory<T>(binding, endpoint); if (channelFactory.Credentials != null) { channelFactory.Credentials.ClientCertificate.Certificate = new X509Certificate2(@"PATH\TO\Client.pfx"); // Client Certificate PRIVATE & PUBLIC Key channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; // I know this is not good, but I dont have a valid certificate from a trusted entity } wcfClient = channelFactory.CreateChannel(); return wcfClient; The service is a bit more complex. I use .svc files with their code-behind. If I understand the use of .svc files correctly, then I believe this is the entry point where the .NET framework creates a ServiceHost and automatically opens it? In my implementation I do not open the ServiceHost, I only implemented a ServiceHostFactoryBase and referenced it in the .svc Markup language. Look at the Factory section - this is the part where I implement my custom Host Factory. <%@ ServiceHost Language="C#" Debug="true" Service="Service.Services.LevelService" CodeBehind="LevelService.svc.cs" Factory="Service.Security.ServiceHostFactory.HostFactory" %> And my custom Host Factory looks like this: public class HostFactory : ServiceHostFactoryBase { public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses) { var serviceType = Type.GetType(constructorString); if (serviceType.GetInterfaces().Count() != 1) throw new NotImplementedException("The service can only have one implemented interface"); var interfaceType = serviceType.GetInterfaces()[0]; var myServiceHost = new ServiceHost(serviceType, baseAddresses); var httpBinding = new WSHttpBinding(); httpBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; httpBinding.Security.Mode = SecurityMode.Message; myServiceHost.Credentials.ServiceCertificate.Certificate = new X509Certificate2(@"PATH\TO\Server.pfx"); myServiceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; myServiceHost.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator(); myServiceHost.Credentials.ClientCertificate.Certificate = new X509Certificate2(@"PATH\TO\Client.cer"); myServiceHost.AddServiceEndpoint(interfaceType, httpBinding, String.Empty); return myServiceHost; } } The custom validator doess't do much yet, but here it is as well: public class MyX509CertificateValidator : X509CertificateValidator { public override void Validate(X509Certificate2 certificate) { // Check that there is a certificate. if (certificate == null) { throw new ArgumentNullException("certificate"); } // Check that the certificate issuer matches the configured issuer. //throw new SecurityTokenValidationException("Certificate was not issued by a trusted issuer"); } } If I understand correctly, the Server has ONLY the PUBLIC key of the client registered since I only reference the .cer file. My big question is now, if I would like to get anything like this on a production server - and lets assume nobody will actually get the executables (including the certificates), would this be a possible solution to keep unwanted people out of my webservice? Basically, I don't want anybody else consuming my webservice - only if you have the proper certificate. Also, how much of an issue is the part where I set on the client: CertificateValidationMode = X509CertificateValidationMode.None I know there are many questions - but overall, I would like to know if I made some fundamental mistakes in this implementation. Ok, after going through a lot of tutorials and demo applications, I figured out that the best way to go ahead is actually using the Certificate Store on Windows. However, I still might consider a hybrid solution where the Server has the certificates in the Certificate store and the client has it embedded in a resource. If you are struggling with WCF and Certificates, have a look at those links: IIS7 Permissions Overview - ApplicationPoolIdentity I was able to create Transport as well as Message secured WCF web services. I would suggest to READ the linked articles because there is so much information that will make you understand certificates and their usage. Especially when dealing with self-singed certificates! I ended up implementing wsHttpBinding using Message Security Mode + Client Certificate with ChainTrust. Hope this will help someone else! Could you please explain, how did you set that ChainTrust programmatically? Please note that I've found ChainTrust is the default, see https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/working-with-certificates
common-pile/stackexchange_filtered
Which is the best way to fetch 1-M relationship data? I am using Yii framework and I have a Post that has many comments, I need to get a list of posts, and each post should hold the latest 5 comments with it. First Option: Is to make a join between posts and comments table and in the PHP code I should normalize the posts list to remove the duplicates and put the commets inside each related post. Second Option: Is to load the posts list, then in PHP code iterate over these posts list and load the comments for each post using a separate sql hit. Which one has the best performance and is there any better way to do it? This sounds like the old Top N per Group problem. This question and others linked from it might be helpful. You should never have incremental hits on your database because of the data. Therefore, the first option would be the wisest one. If you do a join and then filter away the stuff you do not need, your program will be a lot faster than if you do one more database lookup for each row the previous query returned. For more information, have a look on lazy and eager loading here: http://www.yiiframework.com/forum/index.php/topic/34412-eager-loading-vs-lazy-loading/ yes, I agree with this answer, loading all data in one query is much better than second option. thanks for pointing me into the right direction, also I think this article will be helpful to apply the above concept using Yii framework http://www.yiiframework.com/wiki/428/drills-search-by-a-has_many-relation/
common-pile/stackexchange_filtered
Is there any way to opt out of Core Bluetooth state restoration? Do someone know how to opt out of CB state restoration once the CBCentralManager has already been instantiated with a restoration identifier? Basically I want to turn CB state restoration off again depending on some conditions (= I don't want to use state restoration all the time). Do I have to simply dealloc the centralManager and create a new instance without restoration identifier? You are absolutely correct. The application itself opts in when you specify in the info.plist file that you'd like the app to have the ability to have bluetooth functionality in the background. The user then ultimately gets to decide whether your app can work on the background via the uialertview that pops up on first launch or in the device's settings. You then decide whether each central manager (and/or peripheral manager) you instantiate will opt in or not. You can even have one central manager opt in and another one not opt in and have them active at the same time. I currently do this in my app and it works really well. One central manager is opted in and is always scanning. When I need it, I instantiate a second central manager that does not opt in and is only active for a few seconds.
common-pile/stackexchange_filtered
Restrict Custom Post Type to One Item I'm looking to build a plugin that stores settings for a companion app my Wordpress site works with. I've gotten to the point where I have a custom post type mobile_settings that stores labels and colors unique to the companion app. I've gotten to the point where I have my new post type and it's meta values stored, as well as created a new admin page. Here's what I can't figure out to do: On the admin page, navigate the user to the "New Item" view if no mobile_settings have been created. If a single mobile_settings record has been created, navigate the user to it's edit view. Once I have those, I know how to hide the custom post type from the UI, so the user will think it's a straight "options" page instead of a custom post type. We are strictly building this from scratch in order to maintain a database structure that works for our needs. It's actually not as hard as I thought it would be =) Any tips would be appreciated. Edit: I guess some code would be appreciated too, huh? add_menu_page( 'Mobile Settings', 'Mobile Settings', 'manage_options', 'mobile-settings.php', function () { $mobile_settings = get_posts(array('post_type' => 'mobile_settings', 'posts_per_page' => 1)); if (count($mobile_settings) > 0) { wp_redirect(get_edit_post_link($mobile_settings[0]->ID) . '&noheader=true'); exit; } }, 'dashicons-smartphone', 5 ); Have you considered using the wp_options table and just building an options page, instead of a whole CPT? It seems like that would be easier to tailor to your needs. I haven't -- could you point me to a tutorial? Also, would it be extensible enough to store arrays? https://codex.wordpress.org/Creating_Options_Pages Thanks to @WebElaine -- I'm converting my custom post type into a Settings page. Can you tell I'm new to this? =)
common-pile/stackexchange_filtered
Who Should Fill a Sinkhole? I've got a sinkhole in my back yard of a tear down home (torn down from an old duplex from 1950 and rebuilt). The hole is about 5 feet wide and 4 feet deep. The corner of the deck has sunk in the hole and is temporarily hanging in the hole. I've had a contractor offer to fill it with concrete for $700. They mentioned the possibility of a drainage issue but my drains are newly and correctly installed. A similar post (without an answer) stated that if this issue persisted into something larger we would have a huge boulder that would need to be removed on top of whatever else may be causing the problem. I also spoke with a few architectural landscapers and they gave me large price points to JUST examine and determine the cause of the issue. One of them said it may be an old septic tank from the original property. I am located in the Atlanta area and have not heard of this possibility. I've heard of debris pits but not sure that's the issue. My question is what should I do? Has anyone done this type of work before? Is there a good idea of what causes sinkholes in this part of the country (Atlanta area)? I'd appreciate any help. (I currently have it lifted off the ground with some cinder blocks. UPDATE: I had a landscape architect come out this afternoon and he is adamant that it is an old well. One from before 1950 most likely. He cited his 20 yrs of experience but in the last 2-3 years he has done about 3-4 of them a year as houses in my area (Atlanta, GA) are getting torn down and rebuilt. His plan would be to dig down deeper, about twelve feet or until water is found, and then cap the well with concrete. After that he would fill with dirt to the top of the sinkhole. first you need to find out if it's a natural sink hole or man-made. If you are in an area with natural sink holes (such as Florida) there may not be a whole lot you can do other than collect insurance and move. Odds are, though, that's it's man-made and an old cess pit is certainly a common possibility. You'd want someone to come look at it to examine it in person. That seems like a lot of concrete. Is that really an option for a sinkhole rather than just filling with dirt (I don't know, curious)? A 5' round hole at 4' deep would be something like 11 yards of concrete. I wouldn't fill with concrete unless I was sure nobody would ever want to dig in that area again (no additions to the house, no garden structures, no fences...) What's wrong with filling with sand or soil or something equally normal for the area? Do you have a picture? And in the picture what are the dimensions. Nobody can even speculate without these. @DMoore I have added images above. Is the hole continuing to get bigger? Or did appear and the size stabilize? Not sure if I should add this to my answer but it is a comment so,,, We used 3/8 steel rod sharpened on 1 end and a larger maybe 1-1/2" pipe welded on to form a T we would push the point in to find the top & edges , also for finding pipes may be handy to check the tops were 18-24" below the grass @mikes it has not gotten any bigger since I noticed it. I have a landscape architect coming to look tomorrow. But it is scheduled to rain on Wednesday. May have to fill with dirt before then. @keshlam I could do dirt/gravel mix but I am just wondering if maybe it would go deeper if I fill like that, or expand. Fill with dirt, not concrete. The only concrete you might need would be to support that post, and there are several options for that, most of which can stay near the surface in your area (shallow frost.) As for "getting deeper" - if it's man-made, you fill it and are done. If the earth is opening up and swallowing your house, you move and fight with insurance. Only in the latter case does the dirt have somewhere to go to. Not what I expected at all with the size description in the text. Thanks for the pictures - that makes it much more clear. I have filled several of these when I lived in California, abandoned Old redwood septic tanks that finally rotted out, I would check into that. Natural or something like this, I would only use fill dirt / rock . cement would cost way more and wont stop it if it continues to grow. use caution if you do fill it as there may be several feet of the top that has not given way but a person walking on top could be enough for it to let go, a couple of 2"X8"X8' boards laid down to the hole is what we used after I went through 1. the home ones we filled were ~6' round and maybe 6'deep ,the Motel one was close to 20' and at least 8' deep
common-pile/stackexchange_filtered
Why is my output in byte-code and how do I get the string representation? I've filled an array with instances of an object, sorted it using the compareTo method and I'm try to return the sorted list. import java.util.Arrays; public class test { public static void main(String[] args) { Patients1 assetList = new Patients1[5]; assetList = new Patients1[5]; assetList[0] = new Patients1("VINTJAC001"); assetList[1] = new Patients1("LEWGCOL002"); assetList[2] = new Patients1("HENFBOR003"); assetList[3] = new Patients1("ARTDMAN004"); assetList[4] = new Patients1("KISCBIS005"); Arrays.sort(assetList); System.out.println (Arrays.toString(assetList)); } } public class Patients1 implements Comparable<Patients1>{ private String patient_id; public Patients1(String patient_id){ this.patient_id=patient_id; } public String getPatient_id(){ return patient_id; } @Override public int compareTo(Patients1 p) { int result = 0; int compare = patient_id.compareTo(p.patient_id); if(compare < 0){ result = -1; } else if (compare > 0){ result = 1; } else if (compare == 0){ result = 0; } return result; } } However, this is the output I get: [samples.Patients1@15db9742, samples.Patients1@6d06d69c, samples.Patients1@7852e922, samples.Patients1@4e25154f, samples.Patients1@70dea4e] /*samples is the package name and Patients1 is the class that has the compareTo method*/ It should be: [ARTDMAN004, HENFBOR003, KISCBIS005, LEWGCOL002, VINTJAC001] (sorted list) What am I doing wrong or just not doing? You need to override the toString method in your Patients1 class. Hey thanks alot! I guess looking at code too long makes you overlook the simple things. And @Reimeus thanks for the link. It helped alot!
common-pile/stackexchange_filtered
Title not showing on AngularJS (directive inside a directive) I have a directive inside another directive using AngularJS. The title that is called ( {{questions.n3A.name}} ), is not being displayed. Here's my js: .directive('myRating', function() { return{ restrict: 'E', template: '<div><div class="row question">{{questions.n3A.name}}</div> \ <div class="row rating" ng-controller="RatingDemoCtrl"> \ <rating value="rate" max="max" readonly="isReadonly" state-on="\'glyphicon-star rated\'" state-off="\'glyphicon-star\'"></rating> \ <div class="col-md-12"> \ <button class="btn btn-sm btn-danger form-control" ng-click="rate = 0" ng-disabled="isReadonly">Clear</button> \ </div> \ </div> \ </div>', replace: true, scope: { text: '@' } }; }); $scope.questions = { "n3A": { "name": "How safe did you feel on your trip?", "ID": "n3A" }, "n3B": { "name": "How did you get there?", "ID": "n3B" }, }; I also made a Pluncker. When clicking on Yes and South America/Asia/Africa, the title should display on top of the stars. Any idea of what am I missing? You are creating an isolated scope of the directive with scope: {text: '@'} That way, directive has no idea about what scope.questions variable refers to. If you remove scope property out of myRating directive declaration, it will work
common-pile/stackexchange_filtered
c# list object is out of scope. Not sure how to handle it So, I have a simple C# application. The application lets a user enter a test score, and click Add button. When clicked, the text box contents (if valid) should enter into the list object. My current code is saying that it the object doesn't exist in the current context. private void ScoreCalculatorApplication_Load(object sender, EventArgs e) { List<int> scoreList = new List<int>(); } private void btn_Add_Click(object sender, EventArgs e) { scoreList.Add();//this line has the problem } So, I am not sure why the scoreList doesnt exist, because the ScoreCalculatorApplication_Load method executes on loading the app. Anyway, I also considered something like this: private void ScoreCalculatorApplication_Load(object sender, EventArgs e) { //remove this method. } private void btn_Add_Click(object sender, EventArgs e) { //is there a test to see if this object exists? if (//see if the list does not exist) //if not existant, create it here. scoreList.Add(); } So, The problem is I dont know how to test if the object exists. declare it as a member of your class. more specific, please? your form is a class, look to the top of the source file! @user3175451 Please ask for further clarification or accept an answer. Going through your questions, you don't seem to have accepted any answers at all. You can do this by clicking the outline check-mark under the answer that best fits your problem. The problem here is that you're creating scoreList in a more restrictive scope than btn_Add_Click exists in. You've defined it within the scope of the ScoreCalculatorApplication_Load method, which means that reference will be automatically garbage collected after the method completes, and will never be accessible outside that method. If you want the scoreList object to be accessible to all methods within your class, you need to make a field or property. Within the class scope, create and initialize a List: private List<int> scoreList = new List<int>(); private void ScoreCalculatorApplication_Load(object sender, EventArgs e) { /// put whatever else you need to do on loading here } scoreList will now be accessible within any given instance of your class. Note that if you need scoreList to be accessible by other objects, you should make it a public property, rather than a private field. Note that there's not really a need to check whether an object "exists" in the sense you seem to mean -- the program will not compile and run if you've referenced an object or method that does not exist in that scope. If you like, you can check if the scoreList has been initialized and can be populated by checking if it is null, e.g. if (scoreList == null). furkle answers the main issue. Just wanted to answer your supplmentary question that now scoreList is in scope you can test if it has been initialised with if(scoreList==null) Sorry, didn't see that there - I'd already finished adding exactly that to my answer.
common-pile/stackexchange_filtered
Scrapy spider converts float / int to string I always receive a string in my result, even in exported JSON. Using double translate to replace everything. The decimal_serializer was just for testing purposes. I called print(value) inside and it returned a valid float value. In my result it's always unicode string. add_value('offerCountNew', 1.3) returns valid float value in my result. I also tried removing any processor or serializer. Any ideas on what I am doing wrong? Item offerCountNew = scrapy.Field(output_processor = TakeFirst(), serializer = decimal_serializer) Spider l.add_xpath('offerCountNew', 'number(translate(//*[@id="olp_feature_div"]//a[contains(@href, "new")], translate(//*[@id="olp_feature_div"]//a[contains(@href, "new")], "0123456789", ""), ""))') Result 'offerCountNew': u'1.0', JSON "offerCountNew": "1.0", def process_float_or_int(value): try: return eval(value) except: return value offerCountNew = scrapy.Field(input_processor = MapCompose(lambda x: process_float_or_int(x)), output_processor = TakeFirst()) Thank you, it's working! Can you explain what you did and what caused the issue? If the path is not found the default value is False, how to implement that case correctly so the value stays False instead of nan input_processor gets called when item entered to the pipeline and mapcompose is simmilar to python map function. everytime when item comes to the pipeline map compose will run process_float_or_int function on each element. If you want to know more then refer to https://docs.scrapy.org/en/latest/topics/loaders.html#declaring-input-and-output-processors
common-pile/stackexchange_filtered
C#: Groupby, Difference of data in dataset Following is my dataset which I get from the database: Id -- Date -- ClockIn -- ClockOut 1 -- 1/1/2016 -- 1/1/2016:09:00:00 -- 1/1/2016:17:03:00 1 -- 1/2/2016 -- 1/1/2016:09:00:00 -- 1/1/2016:11:30:00 1 -- 1/2/2016 -- 1/1/2016:13:00:00 -- 1/1/2016:15:03:00 Expected result 1 -- 1/1/2016(8 hrs) -- 09:00:00 -- 17:03:00 1 -- 1/2/2016(4 hrs) -- 09:00:00 -- 11:30:00 -- 13:00:00 -- 15:03:00 Question: I want a group-by on Date field and difference of clockIn/out and its sum for the day Here is the code what I am trying but not able to get it work: var resultSet = from newSet in Dtinfo.AsEnumerable() group newSet by new { uid = newSet.Field<int>("UID"), gDate = newSet.Field<DateTime>("wDate"), inTime = newSet.Field<DateTime>("punchIn"), outTime = newSet.Field<DateTime>("punchOut"), location = newSet.Field<String>("locName"), typeName = newSet.Field<String>("typeName"), } into counter select new { UID = counter.Key.uid, wDate=counter.Key.gDate, punchIn = counter.Key.inTime, punchOut = counter.Key.outTime, locName= counter.Key.location, typeName= counter.Key.typeName, diff = (counter.Key.outTime - counter.Key.InTime).TotalHours, }; I am getting the difference but I need the group by and sum to work as well. Any light on the path would be helpful. here is the query. I am returning anonymous class with Date - date which was grouped by TotalHours - sum of all entries for that day Entries - entries, another anonymous class It is probably better to replace them with named classes. var res = from newset in Dtinfo.AsEnumerable() group newset by newset.Field<DateTime>("wDate") into counter select new { Date = counter.Key, TotalHours = counter.Select(a => a.Field<DateTime>("punchOut") - a.Field<DateTime>("punchIn")).Sum(a => a.TotalHours), Entries = counter.Select(a => new { uid = a.Field<int>("UID"), gDate = a.Field<DateTime>("wDate"), /*other fields here * * */ }) };
common-pile/stackexchange_filtered
PHP RSS based schedule I have a (probably) simple PHP question. I'm pulling a schedule from an RSS feed. The RSS output looks like such: 17th Jan 2011 : Day 2 18th Jan 2011 : Day 3 19th Jan 2011 : Day 4 20th Jan 2011 : Day 5 I'm trying to remove all the information so only "Day x" remains. The schedule runs on an 8 day cycle, however I am limiting the RSS parser to only one Day so I get the current day. I'm using this to pull the RSS: $rss->parse(); $rss->showStories('1'); After a bit of tinkering I came up with this. $i=1; while($i<=8) { if (preg_match("/Day 3/i", "Day ".$i)) { echo $i; } else { $i++; } } Obviously the problem starts here: if (preg_match("/Day 3/i", "Day ".$i)) { I want this to find what the current schedule day is and then display corresponding data. Am I approaching this the right way could someone point me in the right direction please? Thanks! EDIT: Fixed code is below for anyone that wants it: <?php $url = ""; $rss = simplexml_load_file($url); if($rss) { $items = $rss->channel->item; foreach($items as $item) { foreach ($item->title as $story) { if (!preg_match(date("/jS M Y/"), $story)) continue; preg_match("/Day (\d+)/", $story, $m); echo $m[1]; // should print "2" if today is January 17 break; // stop searching } } } ?> I'm sorry, but I can't understand what you're asking. What exactly is the thing you'd like to get in the end? Basically, I want a daily schedule based of what "day" it is - so when the RSS feed says it's Day 2 I can have it display information pertaining to Day 2. I hope I'm making this clear enough >< You don't say which RSS library you are using, but something along the lines of foreach ($rss->stories as $story) { // skips stories that are not today if (!preg_match(date("/jS M Y/"), $story)) continue; preg_match("/Day (\d+)/", $story, $m); echo $m[1]; // should print "2" if today is January 17 break; // stop searching } could work. But without any more code it is hard to help further. I wasn't referring to because I didn't know the best way to approach that - I'll try this out now thanks. Is there anyway to just cut everything out so I have "Day X"? You need to show a little more code so that I can give a more specific answer. $rssData = $rss->showStories('1'); echo str_replace(date("jS M Y"), "test" ,$rssData); $rssData would output as 17th Jan 2011 : Day 2 I looked at the above code and I seem to be getting an error on this line: if (!preg_match(date("/jS M Y/")), $story)) continue; Thanks for your help but I'm still getting an error. Warning: Invalid argument supplied for foreach() here foreach ($rss->showStories('2') as $story) { check what showStories returns (e.g. with var_dump($rss->showStories('2'));. I actually believe that you should try to replace this with something like i wrote above (foreach ($rss->stories as $story) {) Odd...vardump is returning this: 17th Jan 2011 : Day 2 18th Jan 2011 : Day 3 NULL Well, I just made a "fake" array and populated it with dates and it's working so I'm getting somewhere!
common-pile/stackexchange_filtered
What option will generate fewer aquifers in world gen? I am facing an aquifer at every conceivable location it seems. I finally figured out how to tunnel through on a freezing map, but I don't want to spend so much time above ground. My dwarves need their tunnels. As a side note, you can tunnel through on a non-freezing map as well by dropping large sections of above layers into the aquifer below. 3 Options: The Lazy Newb Pack way: Just click the Aquifers button after running lazy newb pack.exe Changing WorldGen Settings: Courtesy of Chrissi from the bay 12 forums To actually answer the question.... yes, you can render a world with significantly less aquifers (I have done it) by increasing the minimum elevation in the parameters. Try 20 or 40 or something. It also reduces oceans, but oceans are what cause aquifers in the first place. Obviously this has other side effects on world gen like making the world more mountainous and making oceans smaller/nonexistent depending on how high the minimum elevation is. There is no option to just turn off Aquifers in the advanced mapgen, although I believe some mods do have that option. Editing the raws: Text editor (All operating systems) Find the files in Dwarf Fortress/raw/objects (new world) or Dwarf Fortress/data/save/regionNN/raw/objects (already saved world). Open the three files with a text editor (e.g. Notepad). (inorganic_stone_layer.txt, inorganic_stone_mineral.txt, and inorganic_stone_soil.txt) Use Edit->Replace, and replace [AQUIFER] with (AQUIFER). (Use 'Replace All'). To restore the tags later, do the same in reverse. (Replacing (AQUIFER) with [AQUIFER]).
common-pile/stackexchange_filtered
How to pass coordinates from lists to multiple stepper motors at the same time, not in sequence? I want to make multiple stepper motors turning at same time, with L298N driver. My idea is using relative coordinate on Milling machine, and separate x, y, z value from input coordinate before doing relative positioning calculation. The code is def coordinate(inputlist, d): D = int(d) l = ast.literal_eval(f"[{inputlist}]")#do not use "eval()" code lx = [x for x,y,z in l] ly = [y for x,y,z in l] lz = [z for x,y,z in l] x_value(lx, axisx, D) y_value(ly, axisy, D) z_value(lz, axisz, D) def x_value(lx, axisx, D): delay = D stepper = axisx x = lx xv = [] for f in range(len(x)-1): bx = x[f+1] - x[f] xv.append(bx) print(xv) for steps in xv: if (steps >=0): forword(delay, steps, stepper) elif (steps <=0): backward(delay, steps, stepper) def y_value(ly, axisy, D): delay = D stepper = axisy y = ly yv = [] for g in range(len(y)-1): by = y[g+1] - y[g] yv.append(by) print(yv) for steps in yv: if (steps >=0): forword(delay, steps, stepper) elif (steps <=0): backward(delay, steps, stepper) def z_value(lz, axisz, D): delay = D stepper = axisz z = lz zv = [] for h in range(len(z)-1): bz = z[h+1] - z[h] zv.append(bz) print(zv) for steps in zv: if (steps >=0): forword(delay, steps, stepper) elif (steps <=0): backward(delay, steps, stepper) def forword(delay, steps, stepper): for i in range(steps): for halfstep in range(8): for pin in range(4): GPIO.output(stepper[pin], seq[halfstep][pin]) time.sleep(int(delay) / 10000) def backward(delay, steps, stepper): seq.reverse() for i in range(-int(steps)): for halfstep in range(8): for pin in range (4): GPIO.output(stepper[pin], seq[halfstep][pin]) time.sleep(int(delay) / 10000) seq.reverse() try: while True: inputlist = input("Coordinate List (Unit is 10um, 1mm = 100 (10um)):") d = input("speed of stepper(do not less then 7):") coordinate(inputlist, d) No matter how I tried, the three stepper motors are turning separately. I want to make stepper motors turning at same time, no matter what value I put in with coordinate form (x1,y1,z1), (x2,y2,z2)......., (xn,yn,zn) Does this answer your question? How do I iterate through two lists in parallel? In fact, you already have what you need. Create a single loop over l, don't use lx, ly, lz. You have organized your code using functions. Good. However, they all bottom out with halfstep iterations and a call to time.sleep(int(delay) / 10_000) which is not compatible with your design goals. You cannot sleep there. Why? Because you have other plates to keep spinning, other motors to keep stepping. linspace is a very simple function. You don't have to call it directly, but you should create a list or generator that captures what it does. We need to produce a schedule across all motors. Pick some convenient resolution, maybe 1 msec or 10 msec, and produce delta x,y,z figures that you want to achieve starting at each timestamp. When all deltas are zero, you're done and can stop emitting schedule rows, as all motors have achieved desired positions. Now we need to implement that schedule. Step through each timestamp, then through each motor, and issue halfstep commands as needed. This took a moment to do. Consult the current time and sleep till next interval. Lather, rinse, repeat till all schedule rows are consumed. What have we accomplished here? We pulled the sleep() up a level, so it's not peculiar to a specific motor. We command one or more motors to halfstep if needed, then pause while they all do that, then loop again to see if there's any more commands that still need to be issued. just so - instead of waiting, it's probably fairly easy to switch to setting the next time an action should take place and skip if it's not that time yet
common-pile/stackexchange_filtered
Linux - KVM - very slow disk io The I/O performance of my new server is pretty low. I Googled and tried everything I can imagine. First of all, here are the Hardware Components: AMD Opteron(tm) Processor 6344 4x Seagate ST3000VX000 Its currently running on a software RAID5. Throughput from the host machine: # dd if=/dev/zero of=testfile bs=64k count=16k conv=fdatasync 16384+0 records in 16384+0 records out 1073741824 bytes (1.1 GB) copied, 4.44095 s, 242 MB/s Current throughput on the guest system: # dd if=/dev/zero of=testfile bs=64k count=16k conv=fdatasync 16384+0 records in 16384+0 records out 1073741824 bytes (1.1 GB) copied, 94.8643 s, 11.3 MB/s I'm using a self-compiled QEMU + LIBVIRT, plus a self compiled Linux kernel (3.10.32-lns-opteron-kvmhost). I can provide parts out of the kernel configuration. Linux Kernel (HOST): 3.10.32-lns-opteron-kvmhost Linux Kernel (GUEST): 3.10.2-lns-opteron-kvmguest QEMU Version: 2.0.0 Libvirt Version: 1.2.4 I'm running both kernels on another system (same processor, but other hdds), which is running with full I/O performance. I did not install the other system, so I can't reliably reproduce the problem. HDD Configuration of the guest: <disk type='block' device='disk'> <driver name='qemu' type='raw' cache='none' io='threads'/> <source dev='/dev/vmstore/guest-data'/> <target dev='vda' bus='virtio'/> </disk> As you can see I'm using LVM. I don't have any performance issues with the CPU / Memory - only with the disk I/O. Can you reproduce this performance with a fresh Fedora or RHEL build? As a guest system? or as host? The host of course. Self compiling is nice, but stock stuff gets tested and verified sorry, its currently not possible for me to reinstall the host machine. But do you have any idea? I have a RHEL machine with the host and the guests providing very similar IO throughput counts. Actually, that's 8 RHEL machines and about 90 guests. The only obvious problem I see in your configuration is io='threads'. This is unlikely to provide better performance than io='native'. Beyond that, I also don't recommend compiling any of these components (kernel, libvirt, QEMU) yourself unless you already have a deep understanding of them. Better to use a well-tested and known working package from a Linux distribution which has optimized it for performance and stability. RHEL/CentOS and Fedora work fine. I can't vouch for any other distribution. Hi Michael, thanks for your response; ive already tried the io="native". But just for safety i did it again. The Write Performance is now down to 5mb/s (on the guest) You've got other issues, then. See the second paragraph :) have you tried to use noop scheduler in your vm guest? I was ext4 on kvm guest and I had the same problem, I was using the default caching mode and I solved the problem, disabling the write barrier on guest and on host filesystem
common-pile/stackexchange_filtered
Using power cord without battery inserted in laptop Can I use the charger to power the computer without the battery? Will it damage the computer? Also see: http://superuser.com/questions/12358/is-it-better-to-use-a-laptop-on-battery-or-on-ac-power, http://superuser.com/questions/296667/using-a-toshiba-laptop-without-the-battery, http://superuser.com/questions/454179/using-a-laptop-without-battery Every laptop I have owned to retirement would work with the battery removed and/or with a completely exhausted battery installed. IMHO, most laptops are more ergonomic with the battery installed. On an aside, it is best to avoid intentionally draining the battery. Li Ion batteries are good for about 300 charging cycles. So unless you need to use it off the cord, save those cycles. Some Acer (and maybe others) laptops with a faulty battery actually spend so much time checking if the battery is loading, that they slow down tremendously. Removing the battery and operating on the mains cable returns the laptop to normal speeds. The only risk you run is power failures. It depends on your computer, but usually you can. And it can't damage the computer in any way.
common-pile/stackexchange_filtered
How should the foot washing by Jesus be interpreted? Jesus provides a teaching to his disciples in John 13:1-17 (ESV). 1 Now before the Feast of the Passover, when Jesus knew that his hour had come to depart out of this world to the Father, having loved his own who were in the world, he loved them to the end. 2 During supper, when the devil had already put it into the heart of Judas Iscariot, Simon's son, to betray him, 3 Jesus, knowing that the Father had given all things into his hands, and that he had come from God and was going back to God, 4 rose from supper. He laid aside his outer garments, and taking a towel, tied it around his waist. 5 Then he poured water into a basin and began to wash the disciples' feet and to wipe them with the towel that was wrapped around him. 6 He came to Simon Peter, who said to him, “Lord, do you wash my feet?” 7 Jesus answered him, “What I am doing you do not understand now, but afterward you will understand.” 8 Peter said to him, “You shall never wash my feet.” Jesus answered him, “If I do not wash you, you have no share with me.” 9 Simon Peter said to him, “Lord, not my feet only but also my hands and my head!” 10 Jesus said to him, “The one who has bathed does not need to wash, except for his feet, but is completely clean. And you are clean, but not every one of you.” 11 For he knew who was to betray him; that was why he said, “Not all of you are clean.” 12 When he had washed their feet and put on his outer garments and resumed his place, he said to them, “Do you understand what I have done to you? 13 You call me Teacher and Lord, and you are right, for so I am. 14 If I then, your Lord and Teacher, have washed your feet, you also ought to wash one another's feet. 15 For I have given you an example, that you also should do just as I have done to you. 16 Truly, truly, I say to you, a servant is not greater than his master, nor is a messenger greater than the one who sent him. 17 If you know these things, blessed are you if you do them. Consider the historical social and religious context of the traditional Passover service. During a traditional Passover meal, a bowl of water is used to wash one’s hands before eating the bitter herbs, and again before making the blessing over the matzahs. But what Jesus did here with his disciples was never a part of the traditional Passover service of his time. However, it was customary for a host to give his guests water for washing their feet. It was also customary to wash one’s feet before meals and before going to bed. Genesis 18:1-6 ESV 1 And the Lord appeared to him by the oaks of Mamre, as he sat at the door of his tent in the heat of the day. 2 He lifted up his eyes and looked, and behold, three men were standing in front of him. When he saw them, he ran from the tent door to meet them and bowed himself to the earth 3 and said, “O Lord, if I have found favor in your sight, do not pass by your servant. 4 Let a little water be brought, and wash your feet, and rest yourselves under the tree, 5 while I bring a morsel of bread, that you may refresh yourselves, and after that you may pass on—since you have come to your servant.” So they said, “Do as you have said.” 6 And Abraham went quickly into the tent to Sarah and said, “Quick! Three seahs of fine flour! Knead it, and make cakes.” Genesis 19:1, 2a ESV 1 The two angels came to Sodom in the evening, and Lot was sitting in the gate of Sodom. When Lot saw them, he rose to meet them and bowed himself with his face to the earth 2 and said, “My lords, please turn aside to your servant's house and spend the night and wash your feet. Luke 7:44, 45 ESV 44 Then turning toward the woman he said to Simon, “Do you see this woman? I entered your house; you gave me no water for my feet, but she has wet my feet with her tears and wiped them with her hair. 45 You gave me no kiss, but from the time I came in she has not ceased to kiss my feet. Notice that neither Abraham nor Lot offered to wash the feet of their guests, nor did they have a servant do so. Jesus didn't tell Simon that he should have offered to wash Jesus' feet. Dan Fefferman provides this reference to the Babylonian Talmud in his excellent answer to Was the use of the woman's hair to clean Jesus' feet considered an indecent act (Luke 7:36-50)?: Foot-washing was a service which the wife was expected to render her husband (Yer. Ket. v. 30a); according to Rab Huna, it was one of the personal attentions to which her husband was entitled, no matter how many maids she may have had; likewise, according to the Babylonian Talmud (Ket. 61a), besides preparing his drink and bed, the wife had to wash her husband's face and feet (comp. Maimonides, "Yad," Ishut, xxi. 3; Shulḥan 'Aruk, Eben ha-'Ezer, 80, 4). Thus in John 13, Jesus demonstrated something to his disciples during the Passover meal to make a point. Here are four ways that we can interpret his actions. They are not necessarily exclusive of each other. If Jesus demonstrated that he came to earth as a humble servant, then how much more should his disciples do so as well? This is a kal v’chomer argument. Ritual foot washing is instituted as a mandatory practice. Jesus insists that he must wash his disciples’ feet, but only their feet because they are already bathed. This ritual can be interpreted as a symbol of God’s ongoing forgiveness after baptism. Disciples are expected to serve each other: the stronger disciple in the faith acts as a servant to the weaker one in the Kingdom of God as Jesus himself demonstrated. Interpreting the imagery that Jesus presented, it seems that Jesus is also addressing our attitude toward sins we commit after baptism. Washing each other’s feet implies that we should confess our sins to each other. Literal foot washing by Jesus is described only in the Gospel of John. Currently, this ritual is performed by the Pope and at least one Protestant denomination. How would you interpret this passage—would you choose one or more of the interpretations above or something different—and how did you come to your conclusion? There are very reputable sources on all sides of this debate. It doesn't have to be historical. John's gospel is particularly a very subjective, creative narrative presenting an interpretative drama or picture/story. Mark's gospel alone is strictly historical. The way one interprets this passage will be subjective as well, there's no way of pinpointing an exact historical and objective purpose and teaching other than to teach humility, servitude. ALL eyewitness accounts are abstractions from the totality of the information available. The gospels aren't fictionalized versions of the events ... "For we did not follow cleverly devised myths when we made known to you the power and coming of our Lord Jesus Christ, but we were eyewitnesses of his majesty." – 2 Peter 1:16-21 ESV "That which was from the beginning, which we have heard, which we have seen with our eyes, which we looked upon and have touched with our hands, concerning the word of life— the life was made manifest, and we have seen it, and testify to it" – 1 John 1:1,2 ESV I expanded my answer to include church fathers. Very nice. Thank you, Perry! It's helpful to consider how the early saints came to interpret this action by Jesus. Things to consider: Whether your theology has ordinances or sacraments (communion and baptism), Christians recognized these early in church history. Not everything that Christ commanded is an ordinance or sacrament. The church fathers only noted Christ washing feet as showing his humility. The following quotes are massive but only a brief summary of the material. After showing the dignity of Christ, the Evangelist now commends his humility, which Christ showed by washing the feet of the disciples. -- Thomas Aquinas. (2010). Commentary on the Gospel of John: Chapters 1–21 (F. Larcher & J. A. Weisheipl, Trans.; Vol. 3, pp. 8–9). The Catholic University of America Press. And since he who had come from God and was going to God is now washing the feet of others, he is treading under foot the universal tendency to pride. -- Ibid. Vol. 3, p. 9. Note that, according to Origen, our Lord began to wash the feet of his disciples right before his passion, for if he had washed them a long time before, they would have become dirty again. So he began to wash them a short time before he would wash the apostles with the water of the Holy Spirit, after his passion: “Before many days you shall be baptized with the Holy Spirit” (Act 1:5). In short, when our Lord put water into the basin, this indicated the pouring out of his blood; and when he began to wash the feet of his apostles, this indicated the cleansing of our sins. -- Ibid. Vol. 3, pp. 10–11. After our Lord showed that his humble service was necessary, he then urges that it be imitated. -- ibid. Vol. 3, p. 16. And with this in mind he concludes, If I then, who am greater, because I am your Lord and Teacher, have washed your feet, then you who are not as great, because you are disciples and servants, ought, far more than I, to wash one another’s feet: “Whoever would be great among you must be your servant … even as the Son of man came not to be served but to serve” (Mt 20:26). -- Ibid. Vol. 3, p. 20. This is the closet they came to associating foot washing with confessing sin: I reply, according to Augustine, that every one should wash the feet of others, either in a physical or spiritual way. And it is much better, and true beyond argument, that one should do this in a physical way, so that a Christian will not consider it beneath him to do what Christ did. For when a person stoops down to the feet of his neighbor, humility is awakened in his heart, or if already there it is made stronger. If one cannot do this in a physical way, it should at least be done in one’s heart. When feet are washed, their stains are washed away. So we wash the feet of our neighbors in a spiritual way when, as far as we can, we wash away their moral stains. This is done in three ways. The first way is by forgiving their offenses, as in “And if one has a complaint against another, forgiving each other; as the Lord has forgiven you, so you also must forgive” (Col 3:13). Another way is by praying because of their sins, according to “Pray for one another, that you may be healed” (Jas 5:16). These two kinds of washing can be done by all the faithful. The third way belongs to prelates, who ought to wash by forgiving sins by the power of the keys: “Receive the Holy Spirit. If you forgive the sins of any, they are forgiven” (20:22). -- Ibid. Vol. 3, p. 20. A good indication of the significance of foot washing is in Luke 7:36-50. These were the common courtesies expected to show dinner guest in the first century. Do you see this woman? I entered your house; you gave me no water for my feet, but she has wet my feet with her tears and wiped them with her hair.  You gave me no kiss, but from the time I came in she has not ceased to kiss my feet. (Luke 7:44–45, ESV) And so there was given to us the example of the Son of God, which cannot be in error and is adequate for all situations. Thus Augustine says: “Pride is not healed if it is not healed by the divine humility”; and the same is true of avarice and the other vices. -- Vol. 3, p. 21. Dr. Bailey gave a full discussion here: Chapter 18: "The Woman in the House of Simon the Pharisee." LUKE 7:36–50. This is a significant statement because "loved to the end" is bracketed first with the foot washing and last with the crucifixion. Now before the Feast of the Passover, when Jesus knew that his hour had come to depart out of this world to the Father, having loved his own who were in the world, he loved them to the end. (John 13:1, ESV) Jesus' act was the example of a servant: 13:4 Wrapped a towel. Jesus—who knew that God the Father had put all things under his power, and that he had come from God and would return to God through death—got up from the table that evening, took off his outer clothing, and wrapped a towel around his waist. The first lesson Jesus taught on his last evening with his disciples was an enacted parable, taking the role of a lowly servant. This common household task routinely performed before eating (Ge 18:4; 19:2; 43:24; Jdg 19:21) had apparently been neglected because none of the disciples was willing to humble himself to serve the others in this lowly task. Customarily, the position of reclining couches around a table for a meal positioned a diner’s head toward the table and their feet to the outside of the circle. Jesus probably poured water over his disciples’ feet catching it in the basin and then dried them with the towel. -- Jobes, K. H. (2021). John through Old Testament Eyes: A Background and Application Commentary (A. T. Le Peau, Ed.; p. 213). Kregel Academic. Bailey, K. E. (2008). Jesus through Middle Eastern Eyes: Cultural Studies in the Gospels (p. 239). IVP Academic. There is nothing wrong with accompanying communion with foot washing, but if it is done, the point should be made clear to the congregation about the servant's heart that Jesus portrayed and the example Jesus set. For I have given you an example, that you also should do just as I have done to you (John 13:15, ESV) A new commandment I give to you, that you love one another: just as I have loved you, you also are to love one another.  By this all people will know that you are my disciples, if you have love for one another.” (John 13:34–35, ESV) The point to Jesus' act of foot washing is more important than the ceremony. If washing feet or some other action matching one's culture gets this point across, then it is good. The point of a servant's heart is clear. Also the cleansing from a bath refers to the cleaning that would take place through Christ's sacrificial death. It is not clear what the additional cleansing from washing the feet symbolizes. Perhaps this: "Above all, keep loving one another earnestly, since love covers a multitude of sins...." (1 Peter 4:8, ESV) A person's kind actions can better the heart of the receiver and the giver becomes more like Christ, thus the sanctification of becoming more conformed to the image of Christ. Thank you, Perry. The Biblical references that I provided seem to indicate that guests would simply be provided water in which to wash their own feet. The Talmudic reference indicates that only wives, not servants, wash their husband's feet. Let me also note that I've been deeply disappointed when following up on accepted "authoritative" works from the nineteenth century. In my experience, it seems that some authorities would often fabricate their extra-biblical cultural assertions based on speculation to fulfill their theological constructions. Just a warning to the wise. In the Luke 7 Jesus wasn't even provided the water to wash his feet., but that is a good point. In John 13 the apostles had the water, but apparently hadn't washed their feet. It would be a rich person, that had a servant to wash feet, but by Jesus washing feet, he was acting as a servant. Anyway, Jesus saw an opportunity to make a point. I would address that point based on what the apostles would have understood. Peter's initial reaction showed what Jesus was doing was quit humbling. Yes, and it seems like the apostles were confused as Jesus noted, Peter especially! This was something that Jesus noted when he said, "What I am doing you do not understand now, but afterward you will understand.” After what? After Jesus rising from the dead or after Pentecost? And how would that help Peter understand? Jesus' statements, especially in the gospel of John, often had double meanings usually the physical and spiritual. When it comes to Judas, clean definitely had a double meaning. Jesus probably made two points with washing the feet. With foot washing it is easier to see this sanctifying affect than confession: "Above all, keep loving one another earnestly, since love covers a multitude of sins...." (1 Peter 4:8, ESV) A person's kind actions can better the heart of the receiver and the giver becomes more like Christ. Great points, Perry! @Dieter "But afterward you will understand." It refers to the realization that would come after the cock crowed, and Peter had denied Jesus 3 times. The meaning behind Jesus' actions in John 13 and the words he spoke in vv. 8-10 would then become clear to him. Excellent point, Nhi. And Jesus provided Peter the opportunity to affirm him 3 times afterwards. "Feed my sheep," should be the role of a lowly shepherd who serves and protects the sheep under his care. In contrast, consider God's perspective on shepherds and some sheep in Ezekiel 34. @Dieter I agree. Perhaps more than anything else, Peter's experience of mercy helped him to love Jesus even more (cf Lk 7:47) and to follow his example of humble service to those placed under his care. All I can do is offer some general comments about foot washing. The attitude to foot washing is quite varied - some churches include it in their communion services, and some do not. The Pope washes 12 sets of feet once per year; Queen Elizabeth II used to wash some feet of the poor once per year but then used "Maundy Money" (I believe King Charles III has decided to continue this via the practice of "Maundy Money"); several denominations include the rite in their service. Even within some denominations, the practice is quite varied. Those who include the foot washing usually do so for one of two reasons: . purely for historical reasons to better experience the atmosphere of the time of Jesus . for theological reasons because (as they say) Jesus commended the practice three times in John 13:14, 15, 17. Those who do not include foot washing suggest that it is unnecessary because it was merely the custom of the time. However, the same "excuse" is also offered by some denominations for not having communion at all. Biblically, the closest we get to any instruction about this is provided by Jesus as recorded in John 13: V14 - Therefore if I, the Lord and the Teacher, have washed your feet, you also ought to wash the feet of one another. V15 - For I gave you a pattern, that as I did to you, you also should do. V17 - If you know these things, you are blessed if you do them. Thank you, Dottard. This inconclusiveness you've pointed out is exactly why I'm asking the question and looking for the practical application of biblical Hermeneutics. First of all, bear in mind that you, as an approved workman of God's word, are required by God not to make stuff up: 1 Peter 1:20 Knowing this first, that no prophecy of the scripture is of any private interpretation. [Emphasis added] "private (Gr. idios) interpretation" = "one's own interpretation". You (as above) are also required to "rightly-divide" (Gr. orthotomeō) God's word, the word of truth, according to 2 Timothy 2:15. There is exactly one way, mathematically, to rightly-divide God's word. All other ways are wrongly-dividing. If you don't understand what you are reading, try reading the immediate context. If that fails, try a remoter context. You are simply lazy if you don't. Someone quoted John 13 above, you hardly need anything more to understand what is written. The Bible is an Eastern ("oriental") book. It contains Hebrew idioms & expressions, as well as customs from the lands and times in which it was written, from the people unto whom it was first written. No where in the book does God instruct the church of God to keep or observe these particular things. They are not commandments. They are, however, a perfectly acceptable way of communicating to people in a way they can understand. What Jesus meant to communicate in John 13 is perfectly clear to anyone who can read the words that are written. You don't need a commentary, an expert, or an "authoritative source". The word of God is always the "authoritative source", unless, for instance, Josephus, Erasmus, Luther, the pope, or anyone else is greater than God. I have my doubts. Of one thing I'm certain, the loving God of the Bible does not hide behind a cloak of incomprehensibilty. There are a number of useful reference books for investigating "orientalisms". Here's two easy to read: James Freeman - Manners and Customs of the Bible Bishop K.C. Pillai - Light Through an Eastern Window (vols 1 & 2) "The washing of feet" is one such custom from the lands and times of the Bible. As you might suspect, people in that time did not always have the beautiful shoes and boots we use today. They didn't have paved sidewalks and streets everywhere. The floor of a building or tent might be just compacted soil. Thus, as they walked about anywhere, their feet would get dirty. Because of this, when one went to the home of friends or family, there would likely be a place inside to wash one's feet. It was practical, not "ceremonious" as someone asserted. The host himself could offer to do it in an additional show of hospitality. In a very prosperous house, a hired servant or a slave would be offered to do it for you. How refreshing it would have been (try it sometime) to get just your dirty, sweaty feet all cleaned up! Jesus Christ, who was surely "master" to his disciples, could have demanded a foot washing any time he wanted. Peter was certainly up for the chore. You read the rest yourself because God's word itself (as usual) gives you all you need. If you start, unprompted and unexpectedly, washing people's feet in the western, modern world, you are going to get some curious looks at best. Thank you, posit, for your answer and the two book references to ANE cultural practices, which I requested. I emphatically agree with your general principles. There are passages in the Bible that require considerable study to understand and this is okay. If you noticed from my question, I was careful to find instances and references in the scriptures regarding foot washing practices. Conversely, I've learned to be skeptical of authorities claiming that servants at that time customarily washed the feet of guests, since a number of other claims that I've researched turned out to be fiction. @Dieter - since you seem to be attempting to go down the straight path, let me recommend E.W. Bullinger's "Figures of Speech" as well. Perhaps 30-40 of these are discussed in any English language curriculum; in the languages of the original "God-breathed word" there were more than 200. Perhaps the most frequently missed/unappreciated Hebrew language idiom is the "idiom of permission" used throughout the Scriptures, particularly the old T. Finding out exactly what it is and how it was used will save yourself a lot of grief! Since you are a "Herman Eutics" kind of guy, you ought to be able to codify exactly what must be done to "rightly-divide" the Scriptures. Make a distinct, perfectly respectable list, publish it, and then apply it honestly without fail or remorse. You'll likely go through numerous iterations before it is worthy of the approval of God, the only approval worth seeking. Let me also recommend you take a lesson from Eve's conversation with the serpent in Genesis 3. He tricks her thusly: 1) Consider what I have to say! 2) Get her to doubt God's word. 3) Get her to engage and respond. 4) Get her to add words to God's word. 5) Get her to change God's word. 6) Get her to outright contradict God's word. The same damnable things go on today a thousand times a minute. A thousand times a minute to both men and women. BTW, Adam was not deceived. Neither should you be.
common-pile/stackexchange_filtered
Biblatex with custom labels Summary Can I have custom citation labels while using biblatex? Discussion In mathematics it is not uncommon to use custom labels for referring to other books/articles. E.g., "... see [Hart, p196]." when referring to some page in Hartshorne's Algebraic Geometry. This way of referencing in the end usually becomes a convenient mix of the 'author', 'authortitle' and 'title' citation styles. There is not really a way to predict how something is referred to. For example, the Stacks project is might be referred to as [Stacks], and Grothendiecks EGA as [EGA]. On the other hand, books with multiple authors might be labeled using the first letters of their family names (as in [KM] for Katz-Mazur). As far as I know, having these custom labels is only possible when setting the bibliography by hand. I have not seen a way how to do this with BibTex or any of its derivatives. Questions I really like biblatex since it enables me to tweak lots of things concerning citation styles. I know that there is the possibility to use some custom fields in the .bib file. It probably is possible to use one of these custom fields to define the custom citation label of the entry. Furthermore, in the biblatex stylesheets this custom field should be employed for the in-text citations as well as for the entry in the bibliography. This leads to the following questions Does anyone know of a citation style that does this? Is this easy to accomplish? Can anyone provide me with some code for a setup? I don't really know how to do this myself (I've only done some small tweaking of biblatex styles before). Just use the shorthand field in your bib file. This field overrides the citation label in all standard biblatex styles. When data forming the citation label are missing you can use the fallback label field. Here's a sample document using the biblatex-examples.bib file from the documentation. \documentclass{article} \usepackage[T1]{fontenc} \usepackage[american]{babel} \usepackage{csquotes} \usepackage[style=verbose]{biblatex} \addbibresource{biblatex-examples.bib} \begin{document} \null\vfill One of the entries by \citeauthor{kant:ku} uses the shorthand ``KU'' \autocite{kant:ku,cms}. The entry for \citetitle{cms} uses the label ``CMS'' \autocite{cms,kant:ku}. \end{document} Here is an excerpt from the same document in the authoryear style. Great, that is exactly what I was looking for! Somehow I must have missed this in the manual. Or rather, I did not understand what was meant with this option. Thanks again! No problem. Initially I learned more by looking at the examples. These can be found in the same folder as the manual. They're all based on the bib file I mentioned.
common-pile/stackexchange_filtered
High validation accuracy and training accuracy but low test accuracy I have a LSTM model that has good training accuracy(~90%) and excellent validation accuracy(> 95%) but it gives poor results when I test it on data it hasn't seen. I am training hyperparameters using my validation set. I don't imagine it is an overfitting problem because in that case my validation loss would be high but it isn't. I would really appreciate any help. Thanks! Welcome to Cross Validated! Are you training hyperparameters by using your validation set? Yes i am training hyperparameters using validation set Please include that critical information in your question. Just did. Thanks!
common-pile/stackexchange_filtered
Computing tie strength from multiplex graphs I have a number of overlapping igraph objects. I would like edges in each igraph object to have an attribute called tie_strength based on count of common edges between nodes (vertices). e1 <- data.frame(replicate(2,sample(1:10,20, rep = TRUE))) e2 <- data.frame(replicate(2,sample(1:10,20, rep = TRUE))) e3 <- data.frame(replicate(2,sample(1:10,20, rep = TRUE))) merged_edge <- rbind(e1,e2,e3) multiplex_g <- graph.data.frame(merged_edge) E(multiplex_g)$tie_strength <- count.multiple(multiplex_g) I do not know how to copy tie_strength to corresponding edges in g1, g2, g3. Any ideas? Could you please update this question with example graphs g1, g2, and g3 and then specify based on those graphs how you would compute tie strength? Essentially I am saying that tie strength = aggregate of different ties between alters. For example if g1 = advice network, g2 = friendship network, and g3 = manager network, and if alters "Bob" and "Jane" have ties in all three networks, then their tie strength is stronger than if they had say a tie in only one network. In this case I would want to weight tie (edge) with 3 or 1 in g1, g2 and g3 (depending on case).
common-pile/stackexchange_filtered
How can I convert a gt_tbl object into a flextable object? I've been struggling to export my gt_tbl object to Word, because the output ignores all formatting as mentioned in previous posts (**gt** will not format column labels in Word output) I thought a reasonable solution would be to convert my gt_tbl object to a flextable and then export as a Word. However, I could not find any function capable of this. There's a function called as_flex_table from the gtsummary package, but when I try to use it I get the following message: Error: Error in argument 'x='. Expecting object of class 'gtsummary' I also thought of scrapping the gt table altogether and creating a flextable from scratch, but gt has some features that are too difficult to implement with other packages, such as the tab_row_group function. Here's an example below: table1 <- gtcars %>% dplyr::select(model, year, hp, trq) %>% dplyr::slice(1:8) %>% gt(rowname_col = "model") %>% tab_row_group(label = "powerful", rows = hp <= 600) %>% tab_row_group(label = "super powerful", rows = hp > 600) table1 %>% as_flex_table() #This returns the error I really can't find any function to convert a gt_tbl to either a flextable or gtsummary object, please I need some help :( Be sure you're on the latest version of gt. Word output is great since the last release. You cannot covert gt tables into any other format Also don't use tab_style(). Use cols_label(mpg = md("MPG")) I would disagree (politely) with the characterization that "Word output is great". It's definitely not. Still can't cross-reference or caption, and I have continued to struggle to get attractive formatting. See this open issue: https://github.com/rstudio/gt/issues/1140, and a whole slew of others: https://github.com/rstudio/gt/issues?q=is%3Aissue%20is%3Aopen%20docx I get that word is considered passe by many, but in my area (medical research) it is still (by far) the most common
common-pile/stackexchange_filtered
Using WIFI and LAN at the same time I am hooked up to WIFI and can use the internet, I also am connected to a LAN network that is a different network. The IP for LAN is static as is the Gateway. When my WIFI is enabled I cannot get routed to IP addresses through the LAN gateway. Is there anyway to prioritize which gateway I should be using? Example, WIFI is set to DHCP while giving me an IP of <IP_ADDRESS> Subnet <IP_ADDRESS> and Gateway of <IP_ADDRESS>. The LAN port is set to static of <IP_ADDRESS> Subnet <IP_ADDRESS> and Gateway of <IP_ADDRESS>. The 10.145.204.xxx network has routing setup to get to 10.145.203.xxx network. I cannot get to devices on the 10.145.203.xxx network without disabling my WIFI connection. Any help is appreciated, thanks much! Would be helpful if we knew what OS you were using You need to use windows metrics to prioritize traffic from one interface to another. With Windows 7, there was a DOS command to make this happen. With Windows 10, you can use the GUI to get this done. Follow this link to see how it's done: https://pandapow.info/how-to/win10-set-network-adapter-metric/
common-pile/stackexchange_filtered
The inverse of AND operation (multiplication) in binary I want to change the below equation into an equation for x (x=~~). a = (b⨁x)⋅c⨁d where (a, b, c, d, x)∈{0, 1} and ⨁, · means XOR (addition) operation and AND (multiplication) operation, respectively. The above equation can be changed as follows a⨁d = (b⨁x)⋅c And then, I'm not sure how to compute "c" in the above equation.
common-pile/stackexchange_filtered
running pyspark with dependency package like numpy, pandas and scikit-learn I am recently starting to use pyspark to use the scikit-learn. However, we don't have permission to install the dependency package like numpy in the worker node. Is it possible that we package a virtualenv and use --py-files to dynamically send to the worker and somehow extract it and tell spark to use my own python (with the dependency). Appreciate any comment. Thanks Pylab stack comes with relatively complex dependencies so simple copy of an environment may be not sufficient. Moreover it is few hundred megabytes that have to be transfered for each task. The best approach is probably to ask an administrator to install these globally or provide isolated environment. If it is not possible but you have access to pip on worker machines you can try to use forEachPartition to install dependencies in the user space. Thanks. Wonder after I manage to install dependencies in my user space, how could I tell the python to use the dependencies in my space for pyspark. If packages are installed using pip install --user ... it should already on the path. If not you can always use sys.path.append. @Mike: I'm having the same issue. May I know how you resolve it? How to properly load a virtual environment to the master and all the slave workers: virtualenv venv --relocatable cd venv zip -qr ../venv.zip * PYSPARK_PYTHON=./SP/bin/python spark-submit --master yarn --deploy-mode cluster --conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=./SP/bin/python --driver-memory 4G --archives venv.zip#SP filename.py This answer was immensely helpful! It is worth mentioning a few additional points for future readers. The first point is that SP is a variable representing the name of the unzip folder of the archive provided, you can use MYFOO here as long as it follows the format uri_to_archive/archivename.extension#MYFOO. The second point is that if the venv will be used frequently, it's worth loading to hdfs via hadoop fs -copyFromLocal -f uri_to_archive/archivename.extension /hdfspathhere/archivename.extension. Then you can reference the path in your command as PYSPARK_PYTHON=./MYFOO/bin/python spark-submit --master yarn --deploy-mode cluster --conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=./MYFOO/bin/python --driver-memory 4G --archives hdfs://<hdfshost>/hdfspathhere/archivename.extension#MYFOO filename.py. The third point is that this approach works with *.tar.gz archives, not just *.zip archives.
common-pile/stackexchange_filtered
fillText not available on OffscreenCanvas? I seem to be having trouble rendering text to an OffscreenCanvas (in Chrome 61.0.3). Is the method missing or is there something I need to do to get this working? const oOffscreenCanvas = new OffscreenCanvas(480,480); const oOffscreenContext = oOffscreenCanvas.getContext('2d'); oOffscreenContext.fillStyle = 'red'; oOffscreenContext.fillRect(0, 0, 64, 64); oOffscreenContext.fillStyle = 'white'; oOffscreenContext.fillText('help', 32, 32); .... produces.... Uncaught TypeError: oOffscreenContext.fillText is not a function Use the console to view the 2D context object console.log(oOffscreenContext). On my chrome (current beta 6/10/2017 (au date)) ) The following are missing in regards to text. ctx.font, ctx.fillText, ctx.strokeText, ctx.measureText, ctx.textAlign, ctx.textBaseline If they will ever be supported I can not say. Ok, so it seems the text API isn't available at the time of writing this question
common-pile/stackexchange_filtered
Type 'Foo<T>' is not assignable to type 'T extends string ? string | Foo<T> : Foo<T>' I have the following code: class Foo<T> { x?: T extends string ? string | Foo<T> : Foo<T> } function bar<T>(): Foo<T> { const x: Foo<T> = { } return { x } } Why does the compiler yield the following error for return { x }? Type 'Foo<T>' is not assignable to type 'T extends string ? string | Foo<T> : Foo<T>'. ts(2322) Foo<T> should satisfy both string | Foo<T> and Foo<T>, so it should also satisfy the type of Foo.x regardless of whether T extends string or not, right? It's a current limitation of TypeScript. The compiler completely defers the evaluation of a distributive generic conditional type (like T extends string ? ... : ...), so it has no idea what kinds of value might be assignable to it. See ms/TS#46429 for a pull request which implemented the current behavior; performance is just too terrible if the compiler tries to do this. So that's the answer to the question as asked. If you want a workaround I'd refactor any conditional types where the left and right overlap to move the overlap out, like this playground link shows. Does this fully address the question? If so I'll write up an actual answer post. If not, what am I missing? @jcalz As for the refactor you suggested, it unfortunately doesn't work for my case, since the property definition is actually written in a third-party library. So I'll be forced to do something like return { x: { } as any }. I agree that, no matter what T is, the type Foo<T> should be assignable to T extends string ? string | Foo<T> : Foo<T>. This is actually a little tricky to verify, since if T is a union type (e.g., number | Date), then Foo<T> will not be a union type (e.g., Foo<number | Date>), but T extends string ? string | Foo<T> : Foo<T> will be a union type (e.g., Foo<number> | Foo<Date>). That's because T extends string ? ... : ... is a distributive conditional type which splits unions into their members before evaluation, and reunites into a new union afterward. So the fact that the conditional type is always assignable to Foo<T> independently of T depends specifically on the definition of Foo<T>, and the fact that it is covariant in T (see this Q/A for a discussion of variance). But the compiler does not see this. Why? Well, generally speaking, the evaluation of conditional types that depend on generic type parameters is deferred by the compiler. There was some work done in microsoft/TypeScript#46429 to allow a type to be assignable to a conditional type if it was assignable to both the true and false branches of that type, but this only works for non-distributive types that don't use the infer keyword. Since you have a distributive type, it doesn't work here. So, evaluation of T extends string ? string | Foo<T> : Foo<T> is deferred until such time as T is specified. Inside the body of bar(), T is unspecified, so the conditional type is not evaluated there. It is essentially opaque to the compiler, and it won't be able to verify that you can assign a value to it, unless that value is also of the identical conditional type. And Foo<T> is not. So the compiler complains. Playground link to code
common-pile/stackexchange_filtered
Update XML data for multiple nodes I want to update the Isselected plan data based on the selected plan SET @DataXml.modify(' replace value of (/*/Plans/Plan[sql:variable("@PlanID")]/Details/IsSelected/text())[1] with sql:variable("IsSelectedValue")') but the above query always update the first one. <Plans> <Plan> <Details> <IsSelected>true</IsSelected> </Details> </plan> <Plan> <Details> <IsSelected>false</IsSelected> </Details> </plan> <Plan> <Details> <IsSelected>false</IsSelected> </Details> </plan> </Plans> if((SELECT count(Col.value('(Details)[1]', 'nvarchar(max)')) AS Selected FROM @DataXml.nodes('Options/Option') AS Tbl(Col)) > 1) BEGIN SET @DataXml.modify(' replace value of (/*/Options/Option[sql:variable("@OptionID")]/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")') END ELSE BEGIN SET @DataXml.modify(' replace value of (/*/Options/Option/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")') END if I can get the node count like say for the above data It should return count 3 I can manage to fix this. This answer is probably to late... But it might still be helpfull... I must admit, that I did not understand your issue completely. Try this out: A mockup-XML DECLARE @xml XML= N'<Plans> <Plan> <Details> <IsSelected>true</IsSelected> </Details> </Plan> <Plan> <Details> <IsSelected>false</IsSelected> </Details> </Plan> <Plan> <Details> <IsSelected>false</IsSelected> </Details> </Plan> </Plans>'; --This query will answer your question if I can get the node count like say for the above data It should return count 3 I can manage to fix this SELECT @xml.value('count(/Plans/Plan)','int') AS CountOfPlans; --And this query will change the second <IsSelected> to a new value DECLARE @position INT=2; DECLARE @newValue VARCHAR(100)='blah'; SET @xml.modify('replace value of (/Plans/Plan[sql:variable("@position")]/Details/IsSelected/text())[1] with sql:variable("@newValue")'); SELECT @xml; The first returns a "3" and the second this XML <Plans> <Plan> <Details> <IsSelected>true</IsSelected> </Details> </Plan> <Plan> <Details> <IsSelected>blah</IsSelected> </Details> </Plan> <Plan> <Details> <IsSelected>false</IsSelected> </Details> </Plan> </Plans>
common-pile/stackexchange_filtered
c# Cannot call abstract generic method from static base class method I have a base class with a static method which I want to call an abstract generic method but can't work out how to do this. This is a different question to the one asked before, I cannot access the TryGetFallback abstract method from a static method on the base class. The code I have so far is below. public abstract class BaseClass { public long Id { get; private set; } public BaseClass(long id) { this.Id = id; } } public abstract class BaseClass<T> : BaseClass where T : BaseClass, new() { protected BaseClass(long id) : base(id) { } public static T Get(long id) { T item; return TryGet(id, out item) ? item : default(T); } public static bool TryGet(long id, out T item) { item = null; // Try to get item from cache here if (item != null) { return true; } else { // Item not in cache so call TryGetFallback to attempt to retrieve it // Call TryGetFallback function // item = TryGetFallback(id); return item != null; } } protected abstract T TryGetFallback(long id); } public class DerivedClass : BaseClass<DerivedClass> { public DerivedClass() : base(0) { } protected override DerivedClass TryGetFallback(long id) { throw new NotImplementedException(); } } I've tried to instantiate T as a new property and call TryGetFallback from that but the method isn't available. What error are you getting? Is it a compile time or runtime error? You can't call an instance method from a static method. You can't call an instance method from a static method, unless you instantiate a class in the method itself. @BenRobinson: Or use a reference you get from somewhere else, of course. @JonSkeet Yes or that ;-) I've tried instantiating T as a class and calling the method from there but it's not compiling. @dasblinkenlight this is not the same question as previously asked. I am having trouble calling the TryGetFallback method from a static method on the base class. The previous question was regarding inheritance. @NeilT It looks like you're having trouble with the same issue that your other question is discussing - i.e. trying to get a missing instance by calling an instance method (this time, from a static context, but it does not change anything). The answer is the same, you cannot do it. @dasblinkenlight I've just managed to solve this problem and posted my solution on the previous question.
common-pile/stackexchange_filtered
Does System Integrity Protection have any effects on OS's besides Mac OS? If I understand correctly, SIP is a security feature that protects certain folders on Mac OS from modification, even by root users. I don't know how it works on a low level though, and I was wondering if enabling/disabling it has any positive/negative effects on other OS's installed on a Macbook, such as Windows or Linux distros. So, does it? No, SIP is only applied within a macOS partition. You can have a look at /System/Library/Sandbox/rootless.conf to see which folders and files get protected by default. SIP is a macOS feature/function that's applicable to El Capitan and later; it's not dependent on the Mac hardware. If you're not running macOS, there's no SIP.
common-pile/stackexchange_filtered
What is the Sitecore Horizon 9.3 default style sheet and how can it be updated? On the Sitecore Horizon 9.3 "On-premise Installation guide" it says to update the default stylesheet. Which one is the default stylesheet? How can we update it? I did update the "horizon.xpsinglesc.dev.local\sitecore\Horizon.Client\Horizon.Client\dist\assets\css/index.css" However it dit not work. In Horizon when you try to use alignment and indentation feature, it basically adds the .rte-indent-* (where * is 1-8), rte-align-justify, .rte-align-center and .rte-align-right classes to the selected section. The Style will only work if you have the above CSS style(in your question) in your default CSS file. Here default CSS file is your website's default CSS (generally main.css) file which is used to style your website, not the horizon one.
common-pile/stackexchange_filtered
Model Binding to a List MVC 4 Is there a pattern to bind an IList of items to the view. I seem to be having issues with the HttpPost. I know Phil Haack wrote a nice article but it is dated and he said they might have a fix with MVC 4. Please consider adding more detail, including relevant code and links to your question to make it clearer. Here's a good checklist to get you started: http://tinyurl.com/so-list Binding a list to a view. What is not clear about this? There are variations depending on what your form looks like. Some View code would help. Collections are not persisted on postback. Selecting a list of items, or a form that has a textbox for each item, or a form that has a textbox for each property of each item, all possible variations on "binding a list to a view" and require different techniques. You said you have issues with the HttpPost. Apparently that means you have some code with a specific problem, care to show it? You've made reference to some article by Phil Haack, but no link. There isn't only one way to "bind a list of items to a view". Don't presume upon the generosity of the community who is answering your question. Here's the the url with Phil's article. http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx I'm trying to keep it as simple as possible. There's nothing wrong with my code, it's more of an MVC issue. The issue is Model Binding a List. There are endless permutations, say it's a simple List of Cars. @JT refer to the answer here: http://stackoverflow.com/questions/7008714/passing-ienumerable-or-list-model-to-controller-using-httppost/7009837#7009837 @JT We didn't say anything was wrong with your code. We need to see your viewmodel+view attempt to know what list binding technique will work for your scenario. This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though. ViewModel looks like this: public class MyViewModel { public List<Person> Persons{get;set;} } View(with BeginForm of course): @model MyViewModel @for( int i = 0; i < Model.Persons.Count(); ++i) { @Html.HiddenFor(m => m.Persons[i].PersonId) @Html.EditorFor(m => m.Persons[i].FirstName) @Html.EditorFor(m => m.Persons[i].LastName) } Action: [HttpPost]public ViewResult(MyViewModel vm) { ... Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form. Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback: @for( int i = 0; i < Model.Persons.Count(); ++i) { if(i != 4)//conditionally hide 5th item, { //but BUG occurs on postback, all items after 5th will not be bound to the the list @Html.HiddenFor(m => m.Persons[i].PersonId) @Html.EditorFor(m => m.Persons[i].FirstName) @Html.EditorFor(m => m.Persons[i].LastName) } } I use mvc 5.1 and in stead of ++1 i had to do it like this: @{ ++i; }, inside a @foreach() block. @Yustme Perhaps, it might have also been if you had HTML tags, you would need the @{ } to switch that context back to C# code. But good tip either way. Declaring "i" and then using a foreach is pretty ugly especially when we have FOR LOOPS. Also please do not use a specific List implementation unless you really need to. Good point, sometimes I can't use EditorFor and must build the <input> and like the ease of having the iterator variable still as it feels very non-DRY to repeat the index access all over the place. In this example there is no use for the person variable so I've switched from foreach to for. Can we do it using asp tag helpers ? A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it. public class ListModel<T> { public List<T> Items { get; set; } public ListModel(List<T> list) { Items = list; } } and when you return the View you just need to simply do: List<customClass> ListOfCustomClass = new List<customClass>(); //Do as needed... return View(new ListModel<customClass>(ListOfCustomClass)); then define the list in the model: @model ListModel<customClass> and ready to go: @foreach(var element in Model.Items) { //do as needed... } ~Controller namespace ListBindingTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { List<String> tmp = new List<String>(); tmp.Add("one"); tmp.Add("two"); tmp.Add("Three"); return View(tmp); } [HttpPost] public ActionResult Send(IList<String> input) { return View(input); } } } ~ Strongly Typed Index View @model IList<String> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @using(Html.BeginForm("Send", "Home", "POST")) { @Html.EditorFor(x => x) <br /> <input type="submit" value="Send" /> } </div> </body> </html> ~ Strongly Typed Send View @model IList<String> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Send</title> </head> <body> <div> @foreach(var element in @Model) { @element <br /> } </div> </body> </html> This is all that you had to do man, change his MyViewModel model to IList. Steve, thanks for the info, this works fine. My issue, perhaps I didn't explain was Binding a dynamic List. Sanderson nails it in this post http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ @JT It doesn't matter if I statically type the list in the controller, or grab it from a database or a file. Where the list comes from is irrelevant to model binding. My issue was with HttpPost. When a list of objects changes in the view, the values do not get posted correctly. This is what Sanderson addressed and I'm using his method. The MVC team knows about this and Sanderson's method is the best I've seen. I apologize to everyone for not being clear.
common-pile/stackexchange_filtered
Hardhat Smart Contracts With NodeJs I am trying to implement smart contracts with hardhat. From the hardhat documentation, I have seen that we can use the following command to deploy the contract - npx hardhat run scripts/deploy.js In scripts/deploy.js, const { ethers } = require("hardhat"); async function main() { const Referral = await ethers.getContractFactory("Referral"); const referral = await Referral.deploy("0", "1", "2", "3"); let contractAddress = referral.address; console.log("Contract deployed to address:", contractAddress); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); }); I wanted to deploy the contract on a trigger somewhere in node.js and store the contract address in some storage. But using the above command, I would get the output in the terminal and would have to extract it out using exec of nodejs. I wanted to have a function in scripts/deploy.js which I can use to deploy the contracts and can call it from some place in nodejs. Also, it would help in passing some parameters to the function that the Referral.deploy would take in 0, 1, 2, 3... I am very new to web3 ecosystem and trying to see if something like above is achievable. I wanted to deploy the contract on a trigger somewhere in node.js What do you mean? User makes a post request to our node server and then I should deploy the smart contract. So if deployment of smart contract can happen through a function call from where the post request is made, I can store its address accordingly there itself. To call with param, extract it to a function, for example: const { ethers } = require("hardhat"); async function deployContract(param1, param2, param3, param4) { const Referral = await ethers.getContractFactory("Referral"); const referral = await Referral.deploy(param1, param2, param3, param4); return referral.address; } module.exports = deployContract; Then call it from somewhere else: const deployContract = require("./scripts/deploy"); async function main() { const contractAddress = await deployContract("0", "1", "2", "3"); console.log("Contract deployed to address:", contractAddress); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); });
common-pile/stackexchange_filtered
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification with nested ListView I am using Custom ListView with BaseAdapter. My custom ListView contains another custom ListView so I am calling another BaseAdapter on getView(). It is displaying data perfectly but when I touch on any item on nested ListView, app crashes and it is showing below error : java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131296379, class com.amibiotech.dynamin.NonScrollListView) with Adapter(class com.amibiotech.dynamin.MyOrderProducts)] Please help me to solve this. Do you want to expend list view data. why not use expendable list view ? @RashiduzzamanKhan, I am showing Products data in nested ListView. I dont know about expendable listview. If you problem is like this then you can see this: http://www.learn-android-easily.com/2013/07/android-expandablelistview-example.html or http://www.tutorialsbuzz.com/2014/07/android-simple-expandable-listview.html Yes, I checked some tutorials but in my app, there is no facility like expand and collapse. Can you please help me solve problem with my current issue ?
common-pile/stackexchange_filtered
How to remove duplicate elements in a list while preserving order? I just saw a short video from Seth Ladd on Collections. A Set has only unique elements (are not ordered), but sometimes i need an ordered list and i want to remove all duplicates (the 2nd occurrence of an element e.g. String should be removed from the list) original input to a list: A, B, C, B, D, A should result in A, B, C, D. I need to keep the order. A result like B, A, D, C would not help me. Why is there no such function? Because the Dart team made the same decision to not provide one, like the designers of many other standard libraries before them. Do you want such a function? Then you'll either have to implement it yourself, or find a library to do it for you. What is the goal of this question? To find out why this isn't part of the standard library, or to find out how to do it regardless of that fact? All those operations on a list would be O(n^2) naively. To get better bounds, either sorting or a Set would be used internally. This should be easy to create a helper function for this (if one doesn't exist) using Sets and a probe. (As for why these aren't defined on a list itself - not constructive.) Possible duplicate of How to delete duplicates in a dart List? list.distinct()? (Note how removing the irrelevant question and altering the title made this question "Constructive". It's also a duplicate, but perhaps now there will be less down-votes.) I would like to know what the reason for the lack of that function is. @Gero The reason is it does not exist - this sort of question is generally "Not Constructive". It would require getting a rational from the language/library author(s) or WG. In a few rare occasions this is available - i.e. a proposal was rejected - but it is usually very hard to track down. @Gero However, on practicality notes, arguments can be made - in a retrospective view - for separations of concerns and a high (which is bad) cost/benefit ratio. For instance, it's easy to say that all items in a Set must support ordering (and possibly hashing); would it be proper to extend this requirement to items in a List? For the record, here is the bug that requests this feature: https://code.google.com/p/dart/issues/detail?id=8274 It's fairly easy to implement on your own: Iterable distinct(Iterable i) { var set = new Set(); return i.where((e) { var isNew = !set.contains(e); set.add(e); return isNew; }); It'd be even nicer if Set.add() returned a bool that indicated whether the set was modified: Iterable distinct(Iterable i) { var set = new Set(); return i.where((e) => set.add(e)); } You can file feature request bugs of course. Edit: As Florian points out, the above solution only works if the returned Iterable is only used once. Subsequent uses will return Iterators with no elements, because even element has been seen already on the first use. To solve this we need to keep a visited set for every Iterator created from the returned Iterable, not just one for the Iterable. We can do that by creating Iterable and Iterator subclasses like with WhereIterable/WhereIterator: Iterable distinct(Iterable i) => new DistinctIterable(i); class DistinctIterable<E> extends Iterable<E> { final Iterable<E> _iterable; DistinctIterable(this._iterable); Iterator<E> get iterator { return new DistinctIterator<E>(_iterable.iterator); } } class DistinctIterator<E> extends Iterator<E> { final Iterator<E> _iterator; final Set<E> _visited = new Set<E>(); DistinctIterator(this._iterator); bool moveNext() { while (_iterator.moveNext()) { if (!_visited.contains(_iterator.current)) { _visited.add(_iterator.current); return true; } } return false; } E get current => _iterator.current; } Yes, this is much longer, but it'll work correctly with many-use finite Iterables and one-use infinite Iterables. The infinite iterable use case could easily have problems with memory, which is an argument for not including it in the core lib and forcing developers to make some decisions about what exactly they need. thx for the answer. I think i needed distinct() like 1 year ago and i wrote my own removeDuplicates(). I thought they need some time to implement the "official" dart-distinct(). And now I hear it is still not available. I just wonder: why? There are a lot of things that aren't there yet. Did you file a feature request? The solution works, but only, if the iterator is used only once. Accidentally pressed and then spent too much time before updating the comment... The reason it only works once, is, that the returned iterable will redo the 'where' every time it is used. But the 'set' will not be reset. One easy solution is to force the evaluation of the filter with ".toList()". Tricky, @FlorianLoitsch, thanks for pointing out the problem. I was thinking that this would preserve the laziness but I see the issue. This is why these utilities should be in the core lib :) I'll try to add a correct version. Use toSet and then toList var ids2 = ["A", "B", "C", "B", "D", "A"]; var result = ids2.toSet().toList(); [A, B, C, D] and what if my list has instances of a class? like [Instance of Foo], [Instance of Foo], [Instance of Foo]? Is it possible to remove the duplicates while preserving the object instances? Justin Fagnani already gave a good answer. Here is another one: Iterable distinct(Iterable i) { var map = new LinkedHashMap(); i.forEach((x) { map[x] = true; }); return map.keys; // map.keys.toList() would free the map for GC. } note: LinkedHashMap is now in dart:collection, and we are probably going to add an InsertionOrderedSet soon. Using generics and generators, you can make a function that works with Iterables of any type Iterable<T> distinct<T>(Iterable<T> elements) sync* { final visited = <T>{}; for (final el in elements) { if (visited.contains(el)) continue; yield el; visited.add(el); } } Usage of distinct(["A", "B", "C", "B", "D", "A"]) Or if you'd like to wrap it into an extension: extension IterableDistinctExt<T> on Iterable<T> { Iterable<T> distinct() sync* { final visited = <T>{}; for (final el in this) { if (visited.contains(el)) continue; yield el; visited.add(el); } } } Usage of ["A", "B", "C", "B", "D", "A"].distinct()
common-pile/stackexchange_filtered
Hudson's bedroom, math homework scattered across her desk. You know what's weird about saying "four is even"? We're talking about four like it's this actual thing sitting somewhere in the universe, but where exactly is the number four? That's just how we learned to talk about math. Like when little kids play house and say "the baby is crying" about their doll. They're not confused about what's real. But mathematical fictionalism goes deeper than that. When I say "four is even," I'm supposedly making a claim that's false if numbers don't actually exist, but true within the mathematical story we all agree to tell. The pretense runs so deep we forget we're pretending. Think about it - when you calculate your change at a store, are you really committed to abstract objects floating in some platonic realm? No, but the calculation still works. Maybe that's the point of the pretense. We act
sci-datasets/scilogues
How to change dropdown font for all the items? How to fit the content of the dropdown in one line without ellipsis? I have some stuff I'd like to change in my dropdown. The website is https://community.entermedschool.com/ Below is the list of things I have tried along with the code I used. But none of them seem to be working... Increase the font size for all of the items in the dropdown menus. Change the font-weight for all the items in the dropdown to 400. #primary-menu * { font-size: 17px; font-weight: 400; } Auto-scale the dropdown size so that all the items fit in one line. .sub-menu { width: fit-content; } Any help would be much appreciated! Thanks in advance! Edit: The dropdown with which I want these changes is the primary header which I have highlighted here: I want all of the dropdowns to basically expand automatically so that all of the content 'breathes' in it. It is not clear where in the linked page the issue is to find. Please add more details like html in a minimal reproducable example at best in a stack snippet. See how to ask Just updated now. I answered your question. Please give a feedback... Your width: fit-content; is working but there is no space left for the ::after (the right arrow >). Therefor you could add a margin-right to each li in the submenu (for example 15px) and subtract that amount from the right-property of the ::after: .sub-menu li { margin-right: 15px; } .site-header .sub-menu .menu-item-has-children:not(.hideshow):after { { ... right: 0; //instead of 15px ... } It works if i change it in the dev tools...
common-pile/stackexchange_filtered
Per-user SVN branch testing with Jenkins? I'm about to start setting up a testing suite for an existing piece of software. The software repo is using SVN (I tried convincing them to move to git, but it's not going to happen in the near future), and each user has their own branches in svnroot/branches/user/<branchname>. I would like to set up Jenkins to run a bunch of automated tests on the trunk, but I would also like to be able to run those tests on arbitrary branches before they are merged into trunk. Ideally, I would like those users to be able to login (via LDAP, I guess? They already have accounts on the system), and nominate a branch for running tests on. I don't want to automatically run tests on all branches, because there are a lot of branches, many of which are inactive, and some of the tests will probably fairly resource hungry. Is there a way to do something like this in Jenkins? Why not have a job that points to each branch and does SCM polling so only runs when that branch has a change? That way you aren't listening on the whole repository in each job. I imagine you have a small finite set of user based branches. Alternatively, you could set up a parameterized job and have the user type in the name of the branch. @JeanneBoyarsky: read the third paragraph. I did. My solution lets you choose which branches you are polling; so you aren't running against the whole repo. With polling, you don't run a build unless there are changes. So you wouldn't be running tests against inactive branches.
common-pile/stackexchange_filtered
Google Maps API: Static Map returns Error and no map is available I opened an account on Google, and I went to https://console.developers.google.com/cloud-resource-manager to create a Key to use Google Maps static API. I used that Key, on-site pages as well as on AMP pages but while on AMP it works fine, on the normal HTML Page, Google's API returns an error. Investigating it with Developer Tool of Chrome, it returns MissingKeyMapError which it has no sense because the same key is running on the AMP version of the site. I debug the webpage (generated by PHP) and I saw: all Geo-data, are correctly retrieved from Google, by CURL etc ... Just the Javascript of Google doesn't return the map ... I attach a screenshot of the error code from JS Console of Chrome: Here below the variable contanining my Key (written in setup.php file) $key_gigs = "_____________MYKEY______________"; here CLASS I use for AMP as well as for normal HTML pages: <?php class geo { public function CoOrdinates($address_) { global $key_gigs; // Setup.php //echo $address_; echo $key_gigs; exit; // debug purpose $curl_ = curl_init(); $url_map = "https://maps.googleapis.com/maps/api/geocode/json?address=$address_&sensor=false&key=$key_gigs"; curl_setopt($curl_, CURLOPT_URL, $url_map); curl_setopt($curl_, CURLOPT_HEADER, false); curl_setopt($curl_, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl_, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_, CURLOPT_ENCODING, ""); $curlData = curl_exec($curl_); curl_close($curl_); $data = json_decode($curlData, true); //print_r($data); exit; // debug purpose $ret_ = [ 'city' => $data["results"][0]["address_components"][2]["long_name"], 'country' => $data["results"][0]["address_components"][5]["long_name"], 'iso' => strtolower($data["results"][0]["address_components"][5]["short_name"]), 'lat' => $data["results"][0]["geometry"]["location"]["lat"], 'lon' => $data["results"][0]["geometry"]["location"]["lng"], 'time-zone' => $this->TimeZone($data["results"][0]["geometry"]["location"]["lat"],$data["results"][0]["geometry"]["location"]["lng"]), ]; //print_r($ret_); exit; // debug purpose return $ret_ ; } public function TimeZone($lat_,$lon_) { //echo $lat_." ".$lon_; exit; $query_json = "https://maps.googleapis.com/maps/api/timezone/json?location={$lat_},{$lon_}&timestamp=0&sensor=false"; $json_timezone = file_get_contents($query_json); $data_time_zone = json_decode($json_timezone, true); return $time_zone = $data_time_zone["timeZoneId"]; } } ?> Here the interested part of the PHP code that generates the page (it's located into the pre-processor of the page) $address = add_plus($Address.", ".$Number.",".$Code."+".$City.",".$Country); // Creates and manages object from Class geo(); $geo = new geo(); $coordinates = $geo->CoOrdinates($address); $city = $coordinates['city']; $country = $coordinates['country']; $iso = $coordinates['iso']; $lat = $coordinates['lat']; $lon = $coordinates['lon']; $time_zone = $coordinates['time-zone']; // GEO Debug //echo $city." ".$country." ".$iso." ".$lat." ".$lon." ".$time_zone; exit; And here the META tag for the Google JS. The following code lines, are located into the page itself: <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script> Here the visualization code. Variables like $venue, etc, are generated by the pre-processor of the page, and data, taken from dB <!-- Map style="width: 60vw; height: 33.8vw;" --> <section> <h2 class="h_special"><? echo $Name; ?> - EVENTO</h2> <div id="gmap" style=""></div> <script type="text/javascript"> var myLatLng = {lat: <? echo $lat; ?>, lng: <? echo $lon; ?>}; var myOptions = { zoom: <? echo $zoom; ?>, center: new google.maps.LatLng(<? echo $lat; ?>, <? echo $lon; ?>), // mapTypeId: google.maps.MapTypeId.ROADMAP // mapTypeId: google.maps.MapTypeId.SATELLITE mapTypeId: google.maps.MapTypeId.HYBRID // mapTypeId: google.maps.MapTypeId.TERRAIN }; var map = new google.maps.Map(document.getElementById("gmap"), myOptions); var marker = new google.maps.Marker({position: myLatLng, map: map, title: '<? echo $venue; ?>'}); </script> </section> As the Javascript API error code documentation as well your screenshot shows, MissingKeyMapError occurs because you are missing an API key in your Javascript API load URL and has nothing to do with the Static Maps API: <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script> You need to add an API key to that URL, as the Getting Started documentation says. You also do not need the sensor parameter: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY"></script> Hi @Preston , In another website, I used exactly the same code, and I didn't put the key right there where you did suggest. But it works very well. Thus I still don't understand why it doesn't work on the same code, just another domain, another user . Set up is the same for both website. Working page (without the key you suggested) https://www.liciafox.net/venues/io-non-ti-lascero-mai Same code here, but not working: https://www.barbaravagnini.it/venues/barbara-e-band That's why I opened this thread. ... Right? On Jun 22, 2016, the Javascript API was required to use an API key due to sweeping Standard Plan changes. Any domains that were already using the JS API before that date could continue to work without an API key. But any domains created after that date are required to use a key. If that is a new domain, you will need to add an API key. Thank you so much @Preston for the clarification. Indeed I now put the key and it works Glad to hear! Happy to help
common-pile/stackexchange_filtered
How to setup htaccess to show new posts on WP site? I'm using VPS CentOS + Apache + Wordpress. Not using any Cache plugin but htaccess instead. All work good except my home page wont refresh if I write new post. Only new visitors can see new posts. This is htaccess I currently use. Please take a look and give me advice. Let's say to refresh homepage every 1 hour? #Force WWW + SSL #RewriteCond %{HTTP_HOST} !^www\.example\.com #RewriteRule (.*) https://www.example.com/$1 [R=301,L] #RewriteCond %{HTTPS} !=on #RewriteRule ^/?(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteCond %{HTTPS} =on RewriteRule ^/?(.*)$ http://%{HTTP_HOST}/$1 [L,R=301] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # Compress text, html, javascript, css, xml <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript </IfModule> <ifModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file .(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </ifModule> <ifModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 5 seconds" ExpiresByType image/x-icon "access plus 7200 seconds" ExpiresByType image/jpeg "access plus 7200 seconds" ExpiresByType image/png "access plus 7200 seconds" ExpiresByType image/gif "access plus 7200 seconds" ExpiresByType application/x-shockwave-flash "access plus 7200 seconds" ExpiresByType text/css "access plus 7200 seconds" ExpiresByType text/javascript "access plus 7200 seconds" ExpiresByType application/javascript "access plus 7200 seconds" ExpiresByType application/x-javascript "access plus 7200 seconds" ExpiresByType text/html "access plus 600 seconds" ExpiresByType application/xhtml+xml "access plus 600 seconds" </ifModule> # 480 weeks <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|svg)$"> Header set Cache-Control "max-age=290304000, public" </FilesMatch> # 2 DAYS <FilesMatch "\.(xml|txt|php)$"> Header set Cache-Control "max-age=172800, public, must-revalidate" </FilesMatch> # 2 HOURS <FilesMatch "\.(html|htm)$"> Header set Cache-Control "max-age=600, must-revalidate" </FilesMatch> FileETag None SetOutputFilter DEFLATE BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary # Disable server signature ServerSignature Off Have you confirmed in the network traffic (browser tools > network tab) that this is indeed a client-side caching issue? What mime-type is your server responding with for HTML pages (I would assume text/html - but to be sure)? Add the HTTP response headers to your question. Your "caching" directives already state a 10 minute cache time (considerably less than your "1 hour" goal), so this would seem to be OK (there are often other things, like cookies that can break the cache anyway). "Won't refresh" - you mean when you hit F5 or Ctrl+F5? You don't generally need both mod_expires (ExpiresByType) and mod_headers (Header set Cache-Control) - these are doing the same thing. I will refresh if I hit F5. If I visit my site incognito mode I'll get fresh content. It won't refresh if I visit site now, and once again for about 5-6 hours (if post has been published in between) "Add the HTTP response headers to your question." - when in incognito mode. @w3dk can you please show me how to add HTTP response. I don't really know much about this. It is my first time dealing with VPS and apache. I have live site with good google position and now I'm worry not to lose that. Thank you
common-pile/stackexchange_filtered
How to post a sticky (highlighted) status to page wall programmatically? I can post regular status updates to my page wall with php by using curl... $url = sprintf("https://graph.facebook.com/%s/feed", $pageName); $params = array(); $params['access_token'] = 'access token'; $params['description'] = "blah blah bla"; $params['message'] = "check my new site !"; $ch = curl_init(); $res = curlRequest($url, $params, $ch); As I post new status updates, of course older ones gets pushed down. With the new timeline feature, you can "highlight" a status to keep it on top for 1 week. I am trying to figure out how to specify a post as "highlight" when I am posting it programmatically without having to actually go to the page and highlighting the status. Thanks, No, sorry there isn't a way to programmatically make posts sticky. You have to do this manually. I'm suspecting you can transmit keyboard commands to accomplish this. . . Figure out what keyboard commands do this operation on the page and then transmit them during the curl session. . . Almost anything you can do with a mouse, you can do with a keystroke. -Let your Robot do your work for you. . . -K That answer is so stupid, you must be joking … (please?)
common-pile/stackexchange_filtered
How to run cookie only once I have a script that I only want to run the first time the user goes to the new_profile view, so I want to save a cookie and then check if there's the cookie, if not, run the script, if yes don't run the script I have a controller like this: def sign_up() cookies.permanent[:is_first_time] ||= true redirect_to new_profile end And in my view I have: <% if cookies[:is_first_time] %> <script> console.log("script loaded"); </script> <% end %> Is there an option to have something like this: <% if cookies[:is_first_time] = true %> <script> console.log("script loaded"); cookies[:is_first_time] == false; </script> <% end %> I would suggest different naming <% unless cookies[:script_was_loaded] %> <script> console.log("script loaded"); <% cookies[:script_was_loaded] = true %> </script> <% end %> I am not entirely sure if I understand what you want to do but from the example code I would guess that you actually want to do this: <% if cookies[:is_first_time] %> <script> console.log("script loaded"); <% cookies[:is_first_time] = false %> </script> <% end %>
common-pile/stackexchange_filtered
Use of Leaflet to display raster image from WMS GeoServer I'm trying to display raster images from GeoServer on a Leaflet map. Simply like this: var map = L.map("mapid").setView([15.6261, -61.44361], 13); var wmsLayer = L.tileLayer.wms('http://localhost:8080/geoserver/wms?', { layers: 'geo:africa' }).addTo(map); Once the web page is open, the map div is totally grayed out. In the network section of inspect page the WMS request to GeoServer is composed of bbox, srs and other data which are all wrong for the layer being requested: http://localhost:8080/geoserver/wms?service=WMS&request=GetMap&layers=geo:xxx&styles=&format=image/jpeg&trasparent=false&version=1.1.1&width=256&height=256&srs=EPSG:3857&bbox=-6834081.824921039,1751325.19206996,-6829189.855110788,1756217.1618802093 While the request should have these parameters (taken from GeoServer): http://localhost:8080/geoserver/geo/wms?service=WMS&version=1.1.0&request=GetMap&layers=geo:xxx&bbox=-30.0044643,-40.00446437384,65.00446439304,40.0044643&width=768&height=646&srs=EPSG:4326&styles=&format=application/openlayers The screen appears as follows: What could be the problem? Please edit the question and add info about all wrong WMS request and how should all right request look like. I changed it by adding the missing information @TomazicM Your map is using EPSG:3857 (the default for Leaflet) and thus requests data using that same CRS from the WMS. Enable serving images in EPSG:3857 for your WMS and it should work. The result does not change even if i add a new Gridset in GeoServer with EPSG:3857 try zooming out - you may be looking off the edge of your data Layer name suggest your map is of Africa, but view center coordinates [15.6261, -61.44361] (lat, lng) are SE of Dominica island, above South America. I don't know why but it took a long time to load the image on the map, so even when I zoomed out I couldn't see it, thanks. But how does the transformation of the projection take place? The request to the GeoServer is always with EPSG:3857, but the native srs of the image is EPSG:4326
common-pile/stackexchange_filtered
How to stop Text to Speech when Voiceover is speaking, or vice versa in Swift? Right now, my app implements AVSpeechSynthesizer to read out instructions for each screen. The app also takes into consideration when Voiceover accessibility feature is enabled. The problem I'm facing now is that the text to speech feature overlaps with the voiceover feature. Is there a solution to detect that when a user navigates to another element on the screen, TTS stops speaking, or when TTS is speaking, voiceover doesn't speak until TTS finishes (the former is preferred though). The current development is on iOS 8, using Swift. OPTION 1 You could listen for when new elements are focused by observing UIAccessibilityElementFocusedNotification notifications [[NSNotificationCenter defaultCenter] addObserver:yourTTSManager selector:@selector(interruptTTSFunction:) name:UIAccessibilityElementFocusedNotification object:nil]; and interrupt your custom speech synthesis announcements when they are received. Pros: Gives the VoiceOver user a lot of control. Cons: You don't know when VoiceOver is done reading off the newly focused control, so you can't use this to interrupt and restart announcements. OPTION 2 You can tell VoiceOver to pause and restart by posting UIAccessibilityPostNotification(UIAccessibilityPauseAssistiveTechnologyNotification, nil); before your announcement and UIAccessibilityPostNotification(UIAccessibilityResumeAssistiveTechnologyNotification, nil); after it is complete. Pros: Your announcement will get read off in it's entirety. Cons: You take control out of the users hands when you pause VoiceOver. RECOMENDATION If your announcements are short, pausing and resuming the AT isn't a terrible solution. Otherwise, I would recommend allowing VoiceOver users to interrupt/cancel your announcements by listening for UIAccessibilityElementFocusedNotification events, and canceling any active announcements when they are received. Hi Chris! Thanks for your suggestion! However, I can't seem to find the Notification method that you're using. The only available ones to use are from this link. I have tried overriding the accessibilityElementDidLoseFocus() and accessibilityElementDidBecomeFocused() methods as well but doesn't seem to be of help when I navigate to the next element in VoiceOver accessibility mode. Any ideas on this? It's not a method at all. You have to register to listen for notifications. If you don't know what these are you should read up about them, as the answer to that is outside of the scope of this question: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Notifications/Articles/Registering.html Thanks for the clarification Chris! As I'm still new to this, I would just like to clarify if UIAccessibilityElementFocusedNotification is available to use on iOS8? And if yes, do you mind sharing a link on how to go about carrying this out? (: Here is a link to a blog post about posting notifications: http://www.deque.com/blog/dynamic-notifications/ Not all accessibility notifications can (or rather should) be posted, others are posted by iOS and in turn observed by the application. But, this isn't accessibility specific. Only the notification names are accessibility specific, the concept of posting and listening for notifications is identical across all iOS Framework APIs. I'd be happy to provide a deeper answer, but you should ask a different question, as this answer doesn't really belong under this question. I added code snippets for how to do this in the answer, if you need more help PM me! According to UIAccessibilityConstants.h: Currently, these notifications only apply to Switch Control. So you can' pause VoiceOver, which my testing confirms :( Option one is better anyway! Hi Chris, thanks for your help but UIAccessibilityElementFocusedNotification doesn't seem to be available for iOS 8 ): You can also track this using the UIAccessibilityFocus protocol. Same concept, just different API. The notification is very handy, too bad! Hi Chris, yeah I was trying out the UIAccessibilityFocus protocol at the start, however it doesn't seem to work. I asked this question separately here, hoping that someone knows how to get it to work. Anyway, thanks for your help Chris, hope someone else will find your solution useful (: I tried your solution but still have questions. I made an edit to the question. I placed a bounty on my question https://stackoverflow.com/questions/60008538/why-isnt-uiaccessibilitynotification-is-not-moving-to-correct-argument Can you take another look?
common-pile/stackexchange_filtered
Calculate average rating of 5 ratings How can calculate this array: $ratings = [ 1 => 220, 2 => 31, 3 => 44, 4 => 175, 5 => 3188 ]; To a number (the average vote) like: 4 or 3.5 Neither 4 or 3.5 is the average of the ratings you posted. @Daan, not part of the question. You should be more clearer. Why do you want 4 or 3.5 returned? Think a bit about it: what exactly do you want to compute? Start with an item without any ratings. Add a rating, let's say 3 stars. What is average now? Why? Add another rating, let's say 4 stars. What is the average rating now and why? Iterate a couple of times more and find the formula yourself, it's not that difficult. The basic way to calculate the average is simply to add everything up, and divide it by the total number of values, so: $total = array_sum($ratings); $avg = $total/count($ratings); printf('The average is %.2f', $avg); The same logic applies to your values, only you need the average rating, so let's get the total number "rating points" that were given, and divide them by the total number of votes: $totalStars = 0; $voters = array_sum($ratings); foreach ($ratings as $stars => $votes) {//This is the trick, get the number of starts in total, then //divide them equally over the total nr of voters to get the average $totalStars += $stars * $votes; } printf( '%d voters awarded a total of %d stars to X, giving an average rating of %.1f', $voters, $totalStars, $totalStars/$voters ); As you can see here, the output is: 3658 voters awarded a total of 17054 stars to X, giving an average rating of 4.7 Divide the total numbers of stars to the total number of votes: $average = array_sum(array_map( function($nbStars, $howManyVotes) { return $nbStars * $howManyVotes; }, array_keys($ratings), // the stars: 1, 2, ... 5 array_values($ratings) // the votes for each nb. of stars )) / array_sum(array_values($ratings)); i belive that this will work for you guys $result['total_star'] = $this->db->select_sum('course_rating_start')->where('course_id',$course_id)->get('course_rating_review')->row(); $result['total_rating'] = $this->db->where('course_id',$course_id)->count_all_results('course_rating_review'); $avg = $total_star/$total_rating; Add 220 times a rating of 1, 31 times a rating of 2 and so on. Then divide by the total. <?php $ratings = Array ( 1 => 220, 2 => 31, 3 => 44, 4 => 175, 5 => 3188 ); $max = 0; $n = 0; foreach ($ratings as $rate => $count) { echo 'Seen ', $count, ' ratings of ', $rate, "\n"; $max += $rate * $count; $n += $count; } echo 'Average rating: ', $max / $n, "\n"; ?>
common-pile/stackexchange_filtered
When I imagine a chiliagon, I understand it has a thousand sides, but I can't actually visualize all those sides distinctly like I can with a pentagon. That's exactly the puzzle though - if you can't see the thousand sides, what are you actually decoding when you claim to imagine it? Your visual system isn't processing anything picture-like. But maybe that's the point. The decoding mechanism might be fundamentally different for complex geometric concepts versus simple ones. With the pentagon, you're extracting spatial information directly from something quasi-perceptual. Right, and Kosslyn's mental scanning experiments suggest we do decode spatial relationships from images the same way we would from real objects. The time it takes to shift attention between parts corresponds to actual distances. Which implies the decoding process preserves geometric structure. But then how do we decode something like the chiliagon? Are we switching to a completely different representational format? I think we're always using both systems
sci-datasets/scilogues
System.Dbtype for a DB2 Timestamp value I have an internal library which has an API to call DB2 Stored Procs. As part of the parameter binding, the syntax is: SPParameter(string paramName, DbType dbType, object paramValue) One of the input params of the Stored Proc is of the type Timestamp. I am unable to find a System.DbType enum which will work in this case. The possible enums and the error i get are: Date: Error in DB Write: ERROR [42884] [IBM][DB2/LINUXX8664] SQL0440N DateTime: Error in DB Write: ERROR [42884] [IBM][DB2/LINUXX8664] SQL0440N DateTime2: Error in DB Write: No mapping exists from DbType DateTime2 to a known DB2Type. Time: Error in DB Write: ERROR [42884] [IBM][DB2/LINUXX8664] SQL0440N Any suggestions on which enum to use?any other approach? While maybe not the best idea, worth a shot. Try using string or int types, for their respective Alphanumeric, Signed Numeric or Packed Numeric DB2 types. I've had success in the past this way. I found the issue was in the order of Params i was entering. Even though I name the Params, it is required for them to be in order in which they are defined in the Stored Proc. Correcting the order solved the issue SQL0440N means that the procedure you're trying to call does not exists, so I suspect three times out of four the error is not in the data type you are using.
common-pile/stackexchange_filtered
Find whether the sequence is convergent . Find whether the sequence $(a_n)$ given by $a_{n+1}= \sqrt{a_n}+\sqrt{a_{n-1}}$, where $a_1=1$ and $a_2=2$, is convergent. So , $a_{n+1}-a_{n}= \sqrt{a_n} + \sqrt{a_{n-1}} -a_n \implies \sqrt{a_n}(1-\sqrt{a_n})+ \sqrt{a_{n-1}}.$ Now I assumed the sequence is $>1$ and I showed it by induction then , $a_{n+1}-a_{n} < \sqrt{a_{n-1}}$.Any help from here ? What do you mean by “the sequence”? $a_{n+1} = \sqrt{a_n} + \sqrt{a_{n-1}}$ does not define a singe sequence. What is $a_1$? And I suppose there is a typo in your second line? The expression on the right hand side of $\Rightarrow$ is not an expression. Note: $a=\sqrt a+\sqrt a\implies a=4$ or $a=0$ @J.W.Tanner or $a=0$ Ad the main question: Typically, for recursively defined sequences, one first shows that these are convergent and then takes the limit on both sides of the definition to obtain the limit value. We show that the sequence is convergent by showing that it's bounded and monotone. Claim 1. $2 \le a_n \le 4$ for all $n \ge 2.$ Proof. We prove this via induction. For $n = 2, 3$, it is manually verified. Let $P(n)$ denote the statement "$2 \le a_n \le 4$". Assume that $n \ge 4$ and that $P(k)$ is true for all $2 \le k \le n-1$. We prove that $P(n)$ is true. By hypothesis, we have \begin{align} a_n &= \sqrt{a_{n-1}} + \sqrt{a_{n-2}}\\ &\ge \sqrt{2} + \sqrt{2} = 2\sqrt{2}\\ &\ge2. \end{align} Similarly, we have \begin{align} a_n &= \sqrt{a_{n-1}} + \sqrt{a_{n-2}}\\ &\le \sqrt{4} + \sqrt{4}\\ &=4. \end{align} This proves the statement. Claim 2. $a_n \le a_{n+1}$ for all $n \ge 1$. Proof. Let $P(n)$ denote the statement "$a_n \le a_{n+1}$". $P(n)$ can be manually verified for $n = 1, 2, 3.$ Assume that $n \ge 4$ and that $P(k)$ is true for all $1 \le k \le n-1$. We prove that $P(n)$ is true. Using the hypothesis, we see that $$a_n \ge a_{n-1} \ge a_{n-2}.$$ (Note that $n \ge 3$, so all these terms are defined.) By the previous claim, we also see that all the terms are positive and thus, we can conclude $$\sqrt{a_n} \ge \sqrt{a_{n-2}}. \quad (*)$$ Now, we have \begin{align} a_{n+1} - a_n &= \sqrt{a_n} + \sqrt{a_{n-1}} - \sqrt{a_{n-1}} - \sqrt{a_{n-2}}\\ &= \sqrt{a_n} - \sqrt{a_{n-2}}\\ &\ge 0. \end{align} The last inequality followed using $(*)$. This proves this claim as well. By Claim 1, the sequence is bounded and by Claim 2, the sequence is monotone. Thus, the sequence converges. (The value of the limit can be found to be $4$.) The sequence is not increasing if you start counting like $a_3=2.4142$,$a_4=1.9566$,$a_5=1.532140$ The value of $a_4$ is $\sqrt{\sqrt{2}+1} + \sqrt{2} = 2.967... > a_3$ and similarly, $a_5$ is also greater than $a_4$.
common-pile/stackexchange_filtered
Npgsql Error With Column I have a Model and have the same database table. Both are synchronized. I have another database at some other server and I am ussing the same model for it but different dbContext. My system what it does it check in the local dbcontext and fetch some rows then it checks the same row with unique id. But when it Adds the row in the table it gives me the error of ERROR: 42703: column "etrue" does not exist I dont know what is wrong my table has the same columns as declared in the Model here is my model using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CacsSynchronizer.Models { public class Cards { [Key] public string ecode { get; set; } public string ename { get; set; } public string designation { get; set; } public string department { get; set; } public Nullable<System.DateTime> modifidedate { get; set; } public string fname { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string telres { get; set; } public Nullable<System.DateTime> birth { get; set; } public string division { get; set; } public Nullable<System.DateTime> timingin { get; set; } public Nullable<System.DateTime> timingout { get; set; } public string jemail { get; set; } public string altemail { get; set; } public string mobile_no { get; set; } public string vehicle { get; set; } public string company { get; set; } public byte[] tpl { get; set; } public Nullable<System.DateTime> registered { get; set; } public Nullable<System.DateTime> validity { get; set; } public string type { get; set; } public string serial { get; set; } public byte[] photo { get; set; } public Nullable<bool> manual { get; set; } public string visit_to { get; set; } public Nullable<bool> deo { get; set; } public Nullable<bool> employee { get; set; } public Nullable<bool> active { get; set; } public string printing { get; set; } public string modifideby { get; set; } public string container { get; set; } public string gate1 { get; set; } public string gate2 { get; set; } public string gate3 { get; set; } public string gate4 { get; set; } public string gate5 { get; set; } public string gate6 { get; set; } public string gate7 { get; set; } public string level { get; set; } public string containerout { get; set; } public Nullable<bool> psf_staff { get; set; } public string gateno { get; set; } public string gate_in { get; set; } public string gate_out { get; set; } public string visit_name { get; set; } public string gate8 { get; set; } public string gate9 { get; set; } public string gate10 { get; set; } public string gate11 { get; set; } public string gate12 { get; set; } public string gate13 { get; set; } public string gate14 { get; set; } public string gate15 { get; set; } public string own_nic { get; set; } public string gate16 { get; set; } public string gate17 { get; set; } public string gate18 { get; set; } public string gate19 { get; set; } public string gate20 { get; set; } } } here is my code to manipulate public bool SyncLocalToCentralCards() { using (CacsLocalContext CacsLocalEnt = new CacsLocalContext()) { IList<Cards> CardsData = CacsLocalEnt.Cards.SqlQuery("Select * From cards where ecode='3110305101335'").ToList(); if(CardsData != null) { for (int i = 0; i <= CardsData.Count;i++ ) { string ecode = CardsData[i].ecode; using (CacsCentralContext CacsCentral = new CacsCentralContext()) { IList<Cards> CentralCards = (from cards in CacsCentral.Cards where cards.ecode.Equals(ecode) select cards).ToList(); if (CentralCards.Count != 0) { return true; } else { CacsCentral.Cards.Add(CardsData[i]); try { CacsCentral.SaveChanges(); Components.MainWindowComponents.SyncUpdateCount(1); } catch (Exception ex) { Components.MainWindowComponents.StatusUpdate(ex.Message); } } } } return true; } else { return false; } } } Error in the Insert Statement Generated by Entity Framework INSERT INTO "public"."cards"("ecode","ename","designation","department","modifidedate","fname","address1","address2","address3","telres","birth","division","timingin","timingout","jemail","altemail","mobile_no","vehicle","company","tpl","registered","validity","type","serial","photo","manual","visit_to","deo","employee","active","printing","modifideby","container","gate1","gate2","gate3","gate4","gate5","gate6","gate7","level","containerout","psf_staff","gateno","gate_in","gate_out","visit_name","gate8","gate9","gate10","gate11","gate12","gate13","gate14","gate15","own_nic","gate16","gate17","gate18","gate19","gate20") VALUES (E'3110305101335',E'M WAHEED',E'DR',NULL,NULL,E'M SADIQ',E'DIS. BAHAWAL NIGAR',E'',E'',NULL,TIMESTAMP '1989-08-27T00:00:00.0000000',NULL,NULL,NULL,NULL,NULL,NULL,E'TLA862',E'ZATRANSPORT TR',decode('pw==', 'base64'),TIMESTAMP '2013-03-05T22:56:36.0000000',TIMESTAMP '2013-03-06T22:56:36.0000000',E'CL',E'6050313822',decode('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigkJyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCACQALADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDlWIpAeaQ05Bk9OKGSkTKuQKlEWaIl6VaRRjFZ3LSK4hyakEXNWkiHXrUqxjHSlcLFLyievSk8sjnFXzH7U0xCi4rFQLT1XnnrU4jA7UFQB0p3uKxDjFKrflSSMMVGDTTIZZDc1KklVM5PvUyn1poktBqlib5xVQPU9uctTJNVD8tKxpiHilJqBCMaYSKVqZmgQ00wjAp5NRucUDOPPrT0xTRzUmOKtnQkSowU5q1HKKoZNKHINTa47mzFIvapwRisVJ2B69auxTmoa1Gncv8AFNYVXa4A6mo2uqALDECo3aoWuAc80nm5p2BjZDUeSO9SMc9KhOc9apGbJVOTUyn0qBakBq0jNsm3cdas2xywqkGq3aH07UMTNZTxQTTAeKXPNZkiNTCcU5j71Vmm2nrQBMSBUbHIqETjHJo80EUwOajGTVgRcVDGeelW0xiiR2dCMwg00xkHpVwcikZcmpuFit5foKsQp2pNmDyKsRrgUNjSIJR261XPNXZFGajMYxxQmTYqgHpUgPWpBDSrDk07isxm7imZ+bNTOm0GoAMtTuS0SrzTs44pPu9aaapMiSsS7qu2fWs4Ma0LM9OKGzNmoDxQTTFORxSkmoEIx4qjdH0Gauk1A8YY9KQXKODtz0oYttq00QqOSPK46Ux3OfQjHFWEfmqq4wKnj9e1EjrRcR8ipDjFQp1zmpN2FqSxAfmqynFU/M+bnFTrKuOtIQ5+uaOKjLZPWng0DHYFO4phbHSo2fAzTJYk7Db1qBetI75pydKojqOY8VFu5pXNR5yapGcyUHJ68Vp2fQVlJ9a1rQZWmzKRfB4pc00HFGagTFJph4pc+tITQIYRTD6U9uaYc4oA5dcGpozVVGJxzU6nmmztLQbFK0oxVZ5Djio95zU2C5Kz5NKJSKjBJ68UE4osIsxybmqyDxWcsm01YSXI60WKTLBbFQSPSl+pqCR8d6EtRNhu+apA/HpVXdzT1bI4qzNskZs9aRTz7U3OTQPpxTMyVcbgK2bQEKKxouoNbdrwgpMzkWs0Gm0ualiEY0h5oJyKTPFACMeaYTTj+dMJpCORU1MjVWB/OnI3PNaNHYWuvWlCjtSKwIqRR61JQgOaRqfs96QpSERHrTkJBHNOKGmk4H0oETFjjrVd3NKXyO1QluadhMcDk04GoxgGng85piRIDzTs88UwEYpVJzTRMkWIsZHrWzbcKKxYT84FbVvwo9KT2MZFnOaCaaDmlqRATxTTSnpmkJ4zSuAhph9KceelRkmgRyGTj3o70AUlaWOskWTjmrCzVUHToMUueaVgvYvLNx0pwlFUt+OlO3HHGKQ7ll5BUTP2qMsc80hPFCQmxxOQaTmmmlBPNMTuKOnIp44NR5NOU9yaBbkuTQOhpmfSnduOtA2WbblxxW3D9ysS2xvGDW3F90YpNmMyagGm96CeKRmKx4pucUdetB96QCGmmlNNJoA5EcCk4oNArU6gpw9DSYOKUc4pAKO2DRyOaTFAPvQA40ZHUUe9J70hMd1pR6UinnrS9KBBThwaaPypRk0DHE8UA80055GaUUMLlyz5YVtx/drGsVy3TitlM7fekzGe5Jmim5OaXFSQApSaSkJyKAEY0xunFOzimseKAOU8th2pNprUMApjW+TnFaXOlyM/n0oA4HFX/swySKabQgUri5in9KMYq2Lamtb46UDuiv8AXrScjipTEQemaTYcdKAuNBwOaTJ7U4oc9OtJtIPNACg8U4dKbt+tKOwoBMMZPvTl6+tJjIPtSrgUAaFkOa1VOBWZZrgCtGpZjLckB4pScimDk0UiB9NzgYpN1GexoADxzTSc5xQTmmE+maAP/9kAAAAAAA==', 'base64'),ETRUE,E'58',NULL,NULL,NULL,E'0',E'asifjbl',NULL,E'NO',E'NO',E'NO',E'NO',E'NO',E'NO',E'NO',E'1',NULL,NULL,E'6',E'',E'',E'Wiltrans Cargo Services',E'NO',E'NO',E'NO',E'NO',E'NO',E'NO',E'NO',E'NO',NULL,E'NO',E'NO',E'NO',E'NO',E'NO'); I dont know why it is put E in the column values First, I don't see an "etrue" attribute in your model class, so it's unclear why your code would be generating queries to make use of it. Second, that error is from the database - the column doesn't exist in one (or both) of the tables. If the model in the code is supposed to use that column, then it needs to be added to the database. thanx for your reply. well there is no such column in both of the tables i dont get it what seems to be the problem .. The database error should come with the query that generated the error. If your client isn't showing you that query you can open up the database logs and check there. ok i will check the logs User re-posted as http://stackoverflow.com/q/20651886/398670 @ShakoorAlam The advice you got is good. Look at the server logs to see what query was run, and the full error message. Also figure out where in your code etrue appears; it isn't in the listing above. Make sure you're connecting to the same server you think you are, and that both are running the same version of the schema. Yes I am connecting to the same server with two databases for development enviroment and both are running on the same version that is public schema where are the server logs saved in postgreSql @ShakoorAlam Sure it's really the same? Query information_schema via your Entity Framework connection to each, and compare the column lists. select column_name from information_schema.columns where table_name = 'mytablename' and table_schema = 'public'; @ShakoorAlam Did you look up where the server logs are saved before asking? -> google. found the log ... should i post the Insert Query error in the post ? Please check its putting E before every column value .. let us continue this discussion in chat @ShakoorAlam The E'value' stuff is unrelated. It's the escape-string syntax. See the PostgreSQL user manual (lexical structure section) for information on escape-strings. They are not related to your problem. I just got it fixed .... the problem is with the npgsql VisitedExpression.cs file which was compiled and had a bug with it while fetching the primitive datatype and putting the Boolean switch case with the String Switch case which was appending the escape-string Append('E') so i changed it compiled it... and it works now Thanks to all here This looks like a bug in Npgsql introduced in commit 864c4e9 and fixed in commit b07ae85 on July 5, 2013. It looks like version <IP_ADDRESS> and later contains this fix. Updating the NuGet package will get the update, or you can get the binaries from their releases page. Can you please provide me the link to lates npgsql dll after updating the package i am getting this error The instance member of the entity framework provider type Npgsql.NpgsqlServices did not return an object that inherits from base class... It looks like I was wrong, the latest version doesn't contain the fix. You'll need to build from source. can you please tell me the correct source so that I can build it... I am new to this PostgreSql I cannot, I know nothing about Npgsql. I was able to find this answer by simply searching Google for "npgsql etrue"; the first hit described your exact problem. However, most open source projects have a README file or other file in the root of the repository that tells you how to build them. I suggest you spend some time investigating that.
common-pile/stackexchange_filtered
sqlite: How can results be made unique according to a column Currently, the following sqlite query returns 45 records. I know that only 4 albums exist. How can the query be made to return only those records that are unique to albumTable.album. Pseudo Code: where albumTable.album is UNIQUE query = new StringBuilder(); query.append("select albumTable.album, artistTable.artist, songTable.filepath "); query.append("from albumTable "); query.append("inner join artistTable "); query.append("on albumTable.artistID = artistTable.artistID "); query.append("inner join songTable "); query.append("on albumTable.albumID = songTable.albumID "); Use DISTINCT for the selection. For more info: http://www.tutorialspoint.com/sqlite/sqlite_distinct_keyword.htm EDIT: Maybe you can select with distinct from the current result. Something like this: SELECT DISTINCT albumTable.album FROM (SELECT albumTable.album, artistTable.artist, songTable.filepath from albumTable inner join artistTable on albumTable.artistID = artistTable.artistID inner join songTable on albumTable.albumID = songTable.albumID ) I don't have such database to test the query ... Thank you for your response. I tried your suggestion. However, I initially got an sql exception of albumTable.album doesn't exist. I fixed that problem by just using album but the result was only album data. I then added "select album, artist, filepath from (...)" but that returned 45 records when I should be getting 4. I figured out the problem and I marked your answer as correct because your solution would have worked with some small modifications if not for the faulty logic I used. The problem is that a filepath is associated with a song not an album. Therefore, the result couldn't possibly be 4. I still need a filepath but only from a single song in that album. I'll make that task a sperate query.
common-pile/stackexchange_filtered
django how to rename PK field in a url if anyone can help me with how to rename pk for a class(table) when I use it in the urlpattern. (my goal is using many classes(tables ) PK in the same url and I want to know how to rename PK field for each table) My code below is just for one class(table) for simplicity: models.py: class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("basic_app:school_detail",kwargs={'pk':self.pk}) views.py: class SchoolListView(ListView): model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_details' model = models.School template_name = 'basic_app/school_detail.html' and my current urls.py (which I want to edit) : urlpatterns = [ url(r'^$',views.SchoolListView.as_view(),name='school_list'), url(r'^(?P<pk>\d+)/$',views.SchoolDetailView.as_view(),name='school_detail'),] So my goal is to make the urls.py file look like this(school_pk instead of pk): urlpatterns = [ url(r'^$',views.SchoolListView.as_view(),name='school_list'), url(r'^(?P<school_pk>\d+)/$',views.SchoolDetailView.as_view(),name='school_detail'),] I know I should add a function below class SchoolDetailView in views.py but I don’t know how ? I am still learning so any help will be highly appreciated..Thanks in Advance You mean changing the value of pk of some instance? I mean renaming pk value in the url so instead of pk I use some other name. I need this becuse later I will need to have multiple PK in same url(each Pk for different class(table). like for example a student in a specific school... the url will be something like : url(r'^school/(?P<school_pk>\d+)/student/(?P<student_pk>\d+)/$',views.StudentDetailView.as_view(),name='student_detail'), .....in this case if I leave PK without renaming it.. django will not understand which PK I am referring to (school table PK or Student table PK). When declaring your model you can make a field primary by including primary_key=True, eg class School(models.Model): name = models.CharField(max_length=256, primary_key=True) You can then use name within your URL. I would recommend using unique slug fields. EDIT The URL isn't interested if it is called pk or slug or name. It is interested in the pattern. If you have a URL patterns url(r'^(?P<slug>[\w\\-]+)/$', views.Type1View.as_view(), name="slug"), url(r'^(?P<city>[\w\\-]+)/$', views.Type2View.as_view(), name="city"), Both {% url 'slug' slug %} and {% url 'city' slug %} will produce a URL or /slug/ and both will call Type1View.as_view() You need to ensure your URLs are unique. If you want to refer to 3 tables then your url pattern is url(r'^(?P<slug>[\w\\-]+)/(?P<slug1>[\w\\-]+)/(?P<slug2>[\w\\-]+)/$', MyView.as_view(), name="someName"), And then within your view define def get_objects(self) or def get_queryset(self) to pick up the info you want. ...I already tried this....this also gave me an error...Generic detail view SchoolDetailView must be called with either an object pk or a slug Yes, so use a slug as your primary key @ HenryM but what if need to refer to 3 tables? I will use pk for one ,slug for the second ..what will I use for the third? ..like if I have school---student--- subject grade...I am sure there is a way to rename pk or slug otherwise it is impossible to deal with relational database in real world.
common-pile/stackexchange_filtered
pgfplots, overshooting problem How can I avoid the overshooting below 0? This is the code I use: \documentclass{article} \usepackage{etex} \usepackage{pgfplots} \pgfplotsset{compat=newest} \usepgfplotslibrary{ternary} \usepgfplotslibrary{groupplots} \usetikzlibrary{pgfplots.groupplots} \begin{document} \begin{tikzpicture} \pgfplotsset{every axis/.append style={solid}, every tick/.append style={semithick,color=black}, } \begin{axis}[smooth, scale only axis = true, width = 0.9\textwidth , height = 0.35\textwidth, scaled ticks = false, minor tick num =0, thick, ymin =-0.2, ymax =0.7, xmin =0, xmax=72, legend style={font=\footnotesize, legend pos =north west}, tickwidth = 0.15cm, grid style ={dashed}, ylabel = {y}, xlabel={x}, grid = both ] \addplot [no markers] coordinates{ (0,0.5) (2,0.0) (4,0.01) (6,0.02) (8,0.03) (10,0.06) (12,0.09) (14,0.13) (16,0.18) (18,0.23) (20,0.28) (22,0.32) (24,0.36) (26,0.40) (28,0.43) (30,0.46) (32,0.48) (34,0.50) (36,0.51) (38,0.53) (40,0.54) } ; \end{axis} \end{tikzpicture} \end{document} What do you mean with "overshooting"? When you look at the y-values, they don't go below zero Don't use smooth. Two unrelated things: \usetikzlibrary{pgfplots.groupplots} isn't needed when you already have \usepgfplotslibrary{groupplots}. And empty lines inside the optional argument to axis isn't allowed, it will cause errors. (Which is why Mike added the % in his answer.) You have a few options here: don't use smooth, which makes hard corners (not shown below), set tension to a lower value, which reduces the overshot, but makes harder corners, if permissible, you could add a point, or you could combine the last two options (not shown below) (The legend shows the value for tension.) \documentclass{article} \usepackage{etex} \usepackage{pgfplots} \pgfplotsset{compat=newest} \usepgfplotslibrary{ternary} \usepgfplotslibrary{groupplots} \usetikzlibrary{pgfplots.groupplots} \begin{document} \begin{tikzpicture} \pgfplotsset{every axis/.append style={solid}, every tick/.append style={semithick,color=black}, } \begin{axis}[smooth, % scale only axis = true, width = 0.9\textwidth , height = 0.35\textwidth, scaled ticks = false, minor tick num =0, thick, ymin =-0.2, ymax =0.7, xmin =0, xmax=72, % legend style={font=\footnotesize, legend pos =north west}, % tickwidth = 0.15cm, grid style ={dashed}, % ylabel = {y}, xlabel={x}, grid = both ] \addplot+[no markers,tension=0.2] coordinates{ (0,0.5) (2,0.0) (4,0.01) (6,0.02) (8,0.03) (10,0.06) (12,0.09) (14,0.13) (16,0.18) (18,0.23) (20,0.28) (22,0.32) (24,0.36) (26,0.40) (28,0.43) (30,0.46) (32,0.48) (34,0.50) (36,0.51) (38,0.53) (40,0.54) } ; \addlegendentry{0.2} % default value: tension=0.55 \addplot+[no markers] coordinates{ (0,0.5) (2,0.0) (4,0.01) (6,0.02) (8,0.03) (10,0.06) (12,0.09) (14,0.13) (16,0.18) (18,0.23) (20,0.28) (22,0.32) (24,0.36) (26,0.40) (28,0.43) (30,0.46) (32,0.48) (34,0.50) (36,0.51) (38,0.53) (40,0.54) } ; \addlegendentry{0.55 (default)} \addplot+[no markers,tension=0.9] coordinates{ (0,0.5) (2,0.0) (4,0.01) (6,0.02) (8,0.03) (10,0.06) (12,0.09) (14,0.13) (16,0.18) (18,0.23) (20,0.28) (22,0.32) (24,0.36) (26,0.40) (28,0.43) (30,0.46) (32,0.48) (34,0.50) (36,0.51) (38,0.53) (40,0.54) } ; \addlegendentry{0.9} \addplot+[no markers] coordinates{ (0,0.5) (1,0.1) % added point (2,0.0) (4,0.01) (6,0.02) (8,0.03) (10,0.06) (12,0.09) (14,0.13) (16,0.18) (18,0.23) (20,0.28) (22,0.32) (24,0.36) (26,0.40) (28,0.43) (30,0.46) (32,0.48) (34,0.50) (36,0.51) (38,0.53) (40,0.54) } ; \addlegendentry{added point} \end{axis} \end{tikzpicture} \end{document} Thank you! Not using smooth in combination with tension, works perfectly! If you don't use smooth, tension has no effect.
common-pile/stackexchange_filtered
How can I change precedence behavior of CSS to stop overriding css classes? <input type="checkbox" value="true" name="role" id="role1" class="margin-class" checked="checked"> input[type="checkbox"] { height: 1.42857em; margin-bottom: 1.42857em; position: relative; top: 6px; } .margin-class { margin-bottom: 0; } Both these css comes from bundle.css where I am not allowed to make any change. But I want to apply margin class necessarily. Here selector css is overriding class css. I know the rule of precedence where selector css has more precedence. But is there anyway by which I can override the rule. I am not allowed to use local css too and not allowed to make any changes like !important and all. I mentioned I cannot use !important are inline styles an option? No, Sorry for these many restrictions. then my friend youre Stuck Yes, Anonymous Friend!! Thats why I came here and asked the question!!! :) If you can't modify the bundled CSS or supply your own stylesheet, your only recourse is using an inline style attribute: <input type="checkbox" value="true" name="role" id="role1" style="margin-bottom: 0" checked="checked"> Or applying the style using JavaScript, if you can't modify the HTML either. If you can't do any of these things, then you're pretty much stuck. If that rule is intended to apply to certain elements with the class, then the bundled CSS was poorly written. You can't change how the cascade works other than by using the features given to you (and even then it's not really changing how it works). We generally don't supply any local styles. I have tried this. Its working but not acceptable. :) :) Thanks . I will think of your suggestion soon. @LearningCoding: Let's make this simple: What are you allowed to do? @jbutler483 I am allowed to add some html above and below checkbox. I am allowed to change checkbox into some other control. and in the html I will add I can use margin-class You've ruled out every possible way of adding styling to the element: Adding a css file, adding local css, adding inline css + adding css via jquery. What you've pretty much asked is 'How to add a style without adding any styling'. @LearningCoding Try this jsfiddle. Click the button. I have used java script to make the changes. document.getElementById('role1').style.top ='50px' You can put all such changes in a function, then call the function on window Load (There is no need for the button, just for illustration only). Hope this helps. Man , Its same as applying local css. Sorry I think there is no solutions . Better I will remove this question. I dnt think it will be possible to change precedence any how. It has the same effect as applying local css. But reading your question made me think that, you were not allowed to touch CSS. Anyway I just gave it a shot. You can be bit more specific like providing id's to the selector and providing it the styles!! try adding inline code as , "margin-bottom:0 !important " for the checkbox since you told you cannot add inline style use javascript or jquery to add style like role1.style.margin-bottom = '0';
common-pile/stackexchange_filtered
Stable Id vs DiffCallback for RecyclerView I have a custom class for data shown in my RecyclerView. Each object and thus each row has a unique id value for id field in the class. Whenever I refresh data, the list gets cleared, repopulated and notifyDataSetChanged() is called. This causes for blinking effect. During these refreshes, although id stays the same, some other fields are changing and some of these changing fields should be reflected in the item view. Should I be using setHasStableIds(true) combined with getItemId() OR should I use DiffCallback where I can override areItemsTheSame() and areContentsTheSame()? If I use former, I am not sure if it can detect changes in other fields and update the row. If you can, you should always prefer DiffCallback. Stable IDs can only compare identity, but not contents. This leads to exactly the blinking effect you describe on item content change, because RecyclerView is forced to assume that the content might have changed, and rebind it/execute the item changed animation. DiffCallback has no such limitation, and will always do the right thing if the callback is correctly implemented.
common-pile/stackexchange_filtered
MongoDB regenerate .ns file We accidentally deleted mongo db .ns file from storage path. All the datafiles .0...n are stil existing. But when <DB>.ns file not exist, mongo cannot see the database and also collections. Is there a way to rescue database ? Is there a way to regenerate <DB>.ns file in order to use existing datafiles. Or any other help? Now that's a good question. You don't happen to have any sort of backup, do you? If yes, you could restore with a different dbpath and try to use the restored .ns file in the original dbpath. What version of mongodb are we talking about, btw? Hi @MarkusWMahlberg, thanks for your help. Mongo version is 2.6.7. And we dont have up to date backup, unfortunately This is nothing with a short answer. I see some possibilities, but there are too many factors for a quick answer. You might want to contact me (see my website). But honestly, I have just some ideas on what we can try.
common-pile/stackexchange_filtered
PS script to check status of a service and install a new windows service PS Script Scenario 1-> Check if service exists -> if doesn't exists -> copy item and install windows service and start. -> If exists -> Stop Windows service & delete it and copy item from folder and Install & start the service. Below is my script $service = Get-Service -Name XXX -Computername YYY if($service.Status -eq $NULL) { Copy-Item "C:\location\*" "\\yyy\d$\Location" -Force -Recurse sc.exe \\yyy create xxx start=auto DisplayName="value" binPath= D:\Build\test.exe sc.exe \\yyy description xxx "value" sc.exe \\yyy start xxx Write-Host "xxx STARTED" } else { sc.exe \\yyy stop xxx Write-Host "xxx STOPPED" sc.exe \\yyy delete xxx Write-Host "xxx DELETED" Copy-Item "C:\Location\*" "\\yyy\d$\Location" -Force -Recurse sc.exe \\yyy create xxx start=auto DisplayName="value" binPath= D:\Build\test.exe sc.exe \\yyy description xxx "value" sc.exe \\yyy start xxx Write-Host "xxx STARTED" } Is my approach right and I see error if there is no service name XXX. How to override this error and continue with the If condition statement. Error- Get-Service : Cannot find any service with service name 'Spoole'. At line:1 char:12 + $service = Get-Service -Name Spoole + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Spoole:String) [Get-Service], ServiceCommandException + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand this seems like a right approach, the only thing that is missing - error handling, your script would still write xxx STARTED even if sc.exe threw an error, also, there's the New-Service cmdlet, not sure when did it happen to appear. On my opinion this question is too broad to be answered here, thou You could use $service = Get-Service -Name XXX -Computername YYY -ErrorAction SilentlyContinue To supress the error.
common-pile/stackexchange_filtered
How to change jQuery version in magento <IP_ADDRESS> I am new in magento and cms in general so my question is what are the steps to accomplish this task ? i have found solutions for newer version. Extension that i downloaded require jQuery > 1.8 and i found out that my actual version is 1.7.2. Any help is appreciated. First on your page press CTRL + U (if chrome), than CTRL + F. type jquery, find line where ..scrip... src="...jquery.1.7.2...> (you need jquery file, not jQuery plugin or smth.) this step for find name of jquery file, becouse it can be jQuery.min.1.7.2.js jQuery.1.7.2.js and etc...) Copy file name Open any IDE or smth. For load magento project files if you haven't it. Use function like Find in folder, and look for copied name. It should be in theme layouts folder or base layouts folder. Download right jQuery version and put it where is old one. Comment that line where xml loads old jQuery, and load new one in local.xml. (or just replace in that xml, but it is bad practice, better make changes in local.xml) Thanks will try it for sure
common-pile/stackexchange_filtered
Proof of the integral operator in $L^2(\mathbb{R})$ being self-adjoint "by hand" Suppose we have an integral operator $A$ such that $$Af(x) = \frac{1}{\sqrt{2\pi}}\int\limits_{\mathbb{R}}e^{-\frac{(x-y)^2}{2}}f(x) \, dy$$ This operator is bounded and $\|A\|=1$ (see Norm of the integral operator in $L^2(\mathbb{R})$.). So in order to prove $A$ to be self-adjoint it's suffice to show that it is symmetric, i.e. $$\forall f,g\in L^2(\mathbb{R}):\,\, \langle Af, g \rangle = \langle f,Ag \rangle$$ We can prove it using unitary Fourier transform $F$ and its property that $\langle f,g \rangle = \langle Ff, Fg \rangle$ for any $f,g\in L^2(\mathbb{R})$: $$ \langle Af, g \rangle = \langle FAf, Fg \rangle = \langle \exp\left[-\frac{x^2}{2}\right](Ff), Fg \rangle = $$ $$ = \langle Ff, \exp\left[-\frac{x^2}{2}\right](Fg) \rangle = \langle Ff, FAg \rangle = \langle f, Ag \rangle $$ So operator $A$ really is self-adjoint. The question is how one proves this fact without using Fourier transform? My attempts: $$\langle Af, g \rangle = \int\limits_\mathbb{R}\left( \frac{1}{\sqrt{2\pi}} \int\limits_{\mathbb{R}} e^{\frac{-(x-y)^2}{2}}f(y) \, dy \right)\overline{g(x)} \, dx.$$ Move the constant outside of the outer integral and the actor $\overline{g(x)}$ inside of the inner integral: $$\langle Af, g \rangle = \frac{1}{\sqrt{2\pi}} \int\limits_\mathbb{R} \int\limits_{\mathbb{R}} e^{\frac{-(x-y)^2}{2}}f(y)\overline{g(x)} \,dy\,dx$$ It's to justify the following interchange of integrals: $$\langle Af, g \rangle = \frac{1}{\sqrt{2\pi}} \int\limits_\mathbb{R} \int\limits_{\mathbb{R}} e^{\frac{-(x-y)^2}{2}}f(y)\overline{g(x)} \, dx\,dy$$ Move real-valued function and real constant under conjugation line and function $f(y)$ that doesn't depend on $x$ outside of the inner integral: $$\langle Af, g \rangle = \int\limits_\mathbb{R} f(y)\int\limits_{\mathbb{R}} \overline{\frac{1}{\sqrt{2\pi}}e^{\frac{-(x-y)^2}{2}}g(x)} \, dx\,dy$$ Do conjugation before integration: $$\langle Af, g \rangle = \int\limits_\mathbb{R} f(y)\left(\overline{\int\limits_{\mathbb{R}} \frac{1}{\sqrt{2\pi}}e^{\frac{-(x-y)^2}{2}}g(x) \, dx}\right) \, dy = \langle f, Ag \rangle$$ So if we justify the interchange of integrals, the result will stand. You can justify the interchange of orders of integration by letting $$ G(x,y) = e^{-(x-y)^{2}/2} $$ and noticing that $G(x,y)f(x)\overline{g(y)}$ is jointly measurable in $x,y$, and is bounded by \begin{align} |G(x,y)f(x)\overline{g(y)}| & = |G(x,y)^{1/2}f(x)||G(x,y)^{1/2}\overline{g(y)}| \\ & \le \frac{1}{2}G(x,y)|f(x)|^{2}+\frac{1}{2}G(x,y)|g(y)|^{2}. \end{align} So the expression on the left is absolutely integrable on $\mathbb{R}\times\mathbb{R}$ because the expression on the far right is absolutely integrable. Fubini's Theorem now applies to justify the interchange of orders of integration. That's awesome, thank you! Fubini's Theorem... I should've studied better.
common-pile/stackexchange_filtered
Two rows in asp.net gridview itemtemplate and footertemplate I have a page where I need to create a view where we can add rows and that view needs to look like this. Here the second row has a big textbox. On filling the data and clicking Add new link the row should be saved in DB and be visible, and a new footer row should appear to fill the new data. I went thru google and SO and found ListView, DataList but I couldn't figure out a way to achive this. I know this question may be a duplicate. But I wanted to show what I need through screenshot. Please help me a little more and guide to correct direction. Thanks. You can do this in the RowCreated event of the GridView. However the extra rows will be placed above the normal header and footer rows. In here you can also add controls to the extra rows if you want. But keep in mind that dynamically created controls have to be recreated on every PostBack, so databinding must not be inside the IsPostBack check. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { //cast the sender back to a gridview GridView gv = sender as GridView; //check if the row is the header row if (e.Row.RowType == DataControlRowType.Header) { //create a new row GridViewRow extraHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert); extraHeader.BackColor = Color.Red; //loop all the columns and create a new cell for each for (int i = 0; i < gv.Columns.Count; i++) { TableCell cell = new TableCell(); cell.Text = "ExtraHeader " + i; //add the cell to the new header row extraHeader.Cells.Add(cell); } //add the new row to the gridview gv.Controls[0].Controls.AddAt(0, extraHeader); } //check if the row is the footer row if (e.Row.RowType == DataControlRowType.Footer) { //create a new row GridViewRow extraFooter = new GridViewRow(0, 0, DataControlRowType.Footer, DataControlRowState.Insert); extraFooter.BackColor = Color.Green; //add one cell with colspan 2 TableCell cell1 = new TableCell(); cell1.Text = "ExtraFooter 1"; cell1.ColumnSpan = 2; extraFooter.Cells.Add(cell1); //add another one with colspanning the rest TableCell cell2 = new TableCell(); cell2.Text = "ExtraFooter 2"; cell2.ColumnSpan = gv.Columns.Count - 2; extraFooter.Cells.Add(cell2); //add +2 to the row count. one for the extra header and 1 for the extra footer int insertIndex = gv.Rows.Count + 2; //add the new row to the gridview gv.Controls[0].Controls.AddAt(insertIndex, extraFooter); } }
common-pile/stackexchange_filtered
Do I have to keep a copy of all values put into views in my UIKit app? I have a view controller with a view loaded from a NIB. As I understand it, the view can be unloaded from memory at any time by by controller. Say my app goes into the background, for example. If I have values, such as text in a text field, those values will be lost when the view is unloaded. Or I might want to set those values before the view is loaded, in which case my outlets are not set and I am not able to do it yet. Therefore, do I need to keep a shadow copy of all values in my user interface, so that I can re-set them in viewDidLoad: if the view gets unloaded and then loaded again? Or am I doing things the wrong way? In case of app going to background, implement methods to save and restore app. UIApplication will let you know when focus is going to and has changed in following UIApplicationDelegate methods: – applicationDidBecomeActive: – applicationWillResignActive: – applicationDidEnterBackground: – applicationWillEnterForeground: See help for more details. Forgot about memory warnings... Solutions depend from case to case. In my experience, when it comes to the point when your visible view is removed to clear some memory, you don't want to implement recovery mechanism but test for memory leaks, observe memory allocations, optimize memory management or rethink design. Ok but that only works around one specific cause for a view being unloaded. What about every other reason for a view being unloaded? Including ones that perhaps aren't documented. I don't think UIViewController makes any guarantees about when a view is unloaded. Well, UIViewController views are entirely managed by UIViewController. Look up View Controller Programming Guide for iOS to get clear picture. My suggestion is: don't worry. Even if you get into those situations, you'll be inclined to optimize memory usage, rather than worry about recovery. UIVIewController does tons of really tricky work for you so make sure you do the other part properly. The only other reason why view might get unloaded is you destroyed it by popping view controller from nav controller, for instance and you want new VC instance next time you push it. Don't keep references. General rule is if you let UIViewController manage your view, well, let him manage it. When you're done with view, destroy UIViewController or remove view from superview. If you want custom view controller, check this document: http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html
common-pile/stackexchange_filtered
Charset problems with PHP I have a problem with a PHP code that transforms accent characters in non accent characters. I have this code working a year ago but I'm trying to get this to work but without success. The translation is not done correctly. Here is the code: <?php echo accentdestroyer('azeméis'); /** * * This function transform accent characters to non accent characters * @param text $string */ function accentdestroyer($string) { $string=strtr($string, "()!$?: ,&+-/.ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ" , "-------------SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"); return $string; } ?> I have tested to save the document in UTF-8 but gives me something like this: "azemy�is" Some clues on what can I do to get this working correctly? Best Regards, A better solution may be to transliterate those characters automatically using iconv(). As for the reason your function doesn't work, it may have something to do with the fact that echo strlen('Š'); outputs 2. The documentation explicitly refers to single byte characters. Also, $a = 'Š'; var_dump(strtr('Š', 'Š', '!')); // string(2) "!�" So the first byte has been matched but the second one (leftover) isn't a byte pointing to a valid Unicode character. Update Here is a workign example using iconv(). $str = 'ŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚ'; $str = iconv("utf-8", "us-ascii//TRANSLIT", $str); var_dump($str); // string(37) "OEZsoezY?uAAAAAAAECEEEEIIII?NOOOOO?UU" Some characters didn't quite translate, such as ¥ and Ø, but most did. You can append //IGNORE to the output character set to silently discard the ones which don't transliterate. You could also drop all non word characters too using a Unicode regex with \pL. Thanks for the reply. I have tested iconv() but without success. What should I do get this characters without accents? Best Regards, No, \pL is not word characters. It is only letters!! Besides mere Letters, word characters in Unicode include all Letter Numbers, all Connector Punctuation, all Marks, and all Other Alphabetics. @tchrist Wouldn't \PL be the not matching? Cheers. The assertion was that you could use \pL to find all non-word characters. You cannot.
common-pile/stackexchange_filtered
Regional water treatment facility, afternoon tour with student interns. A: The dissolved oxygen readings dropped significantly near the industrial outflow - that suggests contamination is affecting aquatic life support capacity. B: But how do we know it's actually from that source? Temperature and salinity changes could indicate point source pollution, but we'd need to test upstream and downstream to isolate the cause. A: Goo
sci-datasets/scilogues
Renderring React Components in Laravel Livewire Stack? I'm wondering if there's a way to render react components in Livewire. I just got started with Laravel and I have little-to-no experience in using the Livewire stack. I have a messaging application implemented in react and would like to integrate this to a laravel livewire project that I am doing, what I am trying to ask is basically what are the extra steps that I need to do to accomplish the task? I could not find a tutorial or any online video that discusses this to a level that I can understand however, I tried doing it by creating simple react components and rendering it using: <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 p-6"> <p>Discover page</p> @inertia </div> And when I load the page I get the error message Undefined variable $page referring to @inertia line You can check out this : https://github.com/ijpatricio/mingle . I haven't used it but a youtube video demonstrate that we can : https://www.youtube.com/watch?v=9Pj87lvjV-0
common-pile/stackexchange_filtered
Will chaos (or other problems) result from letting my players use Open5e.com instead of the WOTC collection of books? I'm DM of a group that just completed a one-year long campaign, and we are about to start anew. But my players have asked if instead of using the ever-growing list of official published WOTC books, they can instead just use all the material indexed on open5e.com, as regards all player options beyond the core rules, such as sub-classes, spells, feats, etc. My question is, have any other DMs done this before, and did it create balance issues, or any other friction or difficulty in running a table? If you did this, then were there any caveats or adjustments you had to make to preserve continuity, integrity, consistency, or balance of the game? Are there any preparations from a DM perspective that seem necessary? A good answer will refer to actual experience at your table as substantiation. "all player options beyond the core rules" that are indexed on open5e.com are from third party publishers (and some content by the maintainers)? That's a totally different set of options to those available in WotC books @User23415 Open5e.com is purportedly a curated selection of quality third party published 5e materials, not just random untested homebrew. I am not familiar with the material directly, hence my question. Yes, it's likely to create problems and highly likely to create chaos Open5e.com content mainly comes from various third party publishers, the only official content on there is the basic set of core 5e rules. What you are doing is basically giving your players a blanket permission to bring in anything from a huge list of homebrew options, there are probably hundreds of ways these homebrews can create unforeseen (and problematic) interactions with one another, especially since they come from several different publishers and probably haven't been play-tested to the extent that the official content has been. Most of the options seem to come from Kobold Press, which I have personally used at my table, they are generally considered to create good content but I have still managed to find things that were not balanced well or had the potential to break the game when combined with something else. I often use third party content in my campaigns and what I would recommend is that you either go through the content, consider each one carefully (yes, it's a lot of work if you want to cover everything) and curate a list of allowed, pre-approved options OR allow your players to pick from everything but with the explicit understanding that you reserve the right to review and potentially veto any third party content they decide to incorporate into their characters. How exactly this will play out depends on the type of players at your table. Are they the type that tend to min-max, rules-lawyer and/or look for and exploit loopholes and corner cases? If the answer is yes, then I would tend to be conservative with third party options as there's a high risk they will find something that breaks the game balance. A great answer! esp last paragraph! How much do you trust your players? You can make fundamentally broken characters using WotC rules with no 3rd party content. Doing so with 3rd party content is also possible. If you trust your players to have both the self control and system mastery to tell that the rules they use to make their character have problems, then there really isn't an issue with using 3rd party rules for characters. You should make it clear that any and all rules a player uses to make a character are up for discussion and modification later. If someone makes a nuclear wizard based off of the "magic missile is one damage roll", or creates an infinite simulacrum chain, or a bunch of other frankly crazy builds, you'd have to have that conversation in a pure-WotC game. An issue that can happen is that people who like playing around with rules are more likely to be the ones wanting to use a wider selection of rules to play around with. And if they lack self control or have a different perspective than you do, they could pick rules that cause problems at your table - be they annoying to adjudicate, overshadowing other players at the table, or out of the scope of what you want the PCs to be doing. To prepare for such a thing: Have practice with homebrewing rules yourself. Not just academic knowledge, but see what happens when your rules are used. Get everyone on board with rulings not rules of 5e. Make it clear that you will be making on-the-fly rulings that could override the rules they used to make their character. Talk to each player about how they view their character. Not just the mechanics, but what do they see their character as being good at, weak at, etc. Because matching player expectations to character capabilities (and calibrating those expectations!) is more important than the exact rules used to express character capabilities. Do this with players you can trust. Let them know that you are relying on that trust; this can't work as an adversarial game where they try to "sneak" a rule into the game past the DM. Communicate to the players that the purpose of the open homebrew rules should be to take a character idea and express it mechanically. You can be inspired by mechanics to make a character idea. If you aren't sufficiently confident with letting your players do all of this, you can instead approve things on a case by case basis. Make it clear your approval is conditional! And that players (if they plan on some combo down the line) should describe that as well to avoid possible disappointment. Most tables I've been at allow people to propose homebrew content to be used by their character. At a number of tables I've had DMs actually ask players to try out some specific homebrew content (not even theirs) as it fit the setting/story they are doing. D&D it not a finely tuned machine. D&D for most of its existence has had groups playing with widely divergent sets of rules and having fun; often the different rules where because they misunderstood the rules in insanely different ways! And despite that, the game can work. The social contract is far more important than the actual specific mechanics. This is also a really smart answer. +1. 2nd answers don't always get the respect they deserve. I esp. like your last few paragraphs. @Jack Agree. The players at my table are (mostly) pretty responsible, so the last paragraphs are on point. This could have been an "accepted answer" as well.
common-pile/stackexchange_filtered
Worklight Direct update is not working for Windows App Direct Update is not working for my Worklight App while for android and ios the feature is working as expected. Application Descriptor <windowsPhone8 version="1.0"> <uuid>xxxx-3235-xx-a24e-fdxxxxx6ac</uuid> <pushSender/> <security> <encryptWebResources enabled="true"/> <testWebResourcesChecksum enabled="false"/> <productId>xxxxxxx-7b4a-xxxxx-b387-078e8fa0c3d5</productId> <applicationId>NextMobile</applicationId> </security> </windowsPhone8> authenticationConfig.xml <customSecurityTest name="Adapters-securityTest"> <test realm="wl_antiXSRFRealm" step="1"/> <test realm="wl_remoteDisableRealm" step="1"/> <test realm="wl_authenticityRealm" step="1"/> <test realm="wl_directUpdateRealm" mode="perSession" step="1"/> <test isInternalUserID="true" realm="YesAuthRealm" step="1"/> <test realm="wl_deviceNoProvisioningRealm" isInternalDeviceID="true" step="2"/> </customSecurityTest> What version of Worklight/MobileFirst are we talking? IBM mobile first version 7.0 with fix pack <IP_ADDRESS>-MFPF-StudioP2-IF201603212143 Direct update feature is not working in windows So you make some changes to your application, deploy the new wlapp to the server, you application connects to the server and you do not see direct update coming to your device ? Or do you see the direct update pop-up but then it fails or update ? What exactly is the "issue" ? You have a custom security test defined with Direct Update (<test realm="wl_directUpdateRealm" mode="perSession" step="1"/>), but you did not apply this security test to the Windows Phone environment (<windowsPhone8 version="1.0">). Try applying it. Other than this you are not explaining how the feature is failing for you. By not even getting an update notification, or getting it back it fails downloading, or fails extracting and so on.
common-pile/stackexchange_filtered
why postgresql-9.4 has no installation candidate $ sudo apt-get install postgresql-9.4 Reading package lists... Done Building dependency tree Reading state information... Done Package postgresql-9.4 is not available, but is referred to by another package. This mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'postgresql-9.4' has no installation candidate I'm using ubuntu 16.04 postgresql-9.4 has been updated to postgresql-9.5 in the default Ubuntu 16.04 repositories. To install it open the terminal and type: sudo apt install postgresql-9.5 postgresql-9.x has been updated to postgresql-9.6 in the default Ubuntu 17.04 and 17.10 repositories. postgresql-9.x has been updated to postgresql-10 in the default Ubuntu 18.04 repositories. Ubuntu 16.04 only ships PostgreSQL 9.5 (postgresql-9.5). PostgreSQL 9.4 is not available in any supported version of Ubuntu If you don't need a special version of PostgreSQL you can just install the package postgresql to install whatever version your Ubuntu ships. In this case a distro upgrade will automatically upgrade PostgreSQL if needed. This is a duplicate of my previously posted answer. Do you want to fade out or shall I contribute? – @karel .. you answered 13:00:52 and Florian 13:01:03 - that's within 11 seconds, so probably both answers has been written in parallel. That is also the opinion of some moderators. The opinion of some moderators in case you're interested is that several duplicate answers to the same question can be posted if they are posted within a few minutes of each other. However the privilege of posting multiple duplicate answers without them being possibly closed as duplicate answers fades out over time.
common-pile/stackexchange_filtered
Replace multiple numbers with other numbers in a string using REGEX c# so I have hundreds of these lines below( i trimmed alot), I want to capture the DEFAULT value and set to 0.99 but only for the lines WITH <Movement display_name="Movement type can be session or system ,independent of type and min and max, I am new to REGEX, this is the best I could do, however its not what I want, I know there exist replace in regex but I wasnt able to finish the first part, please help true true false true false true false true false true false true false true false RED BLUE YELLOW GREEN WHITE LIGHT GREY DARK GREY PURE RED ORANGE LIGHT BLUE DARK BLUE MAGENTA LIGHT GREEN <!--Default Values--> <Indexed display_name="Indexed" type="system" datatype="pos_int" max="4" min="1" security_level="SU" default_value="2" /> <IndexingColor1 display_name="IndexingColor1" type="system" datatype="list" security_level="SU" default_value="RED"> <Cube> <ShowFrame display_name="ShowFrame" type="system" datatype="list" security_level="CU" default_value="true"> <list> <ListItem>true</ListItem> <ListItem>false</ListItem> </list> </ShowFrame> <ShowFixedPoint display_name="ShowFixedPoint" type="system" datatype="list" security_level="CU" default_value="true"> <list> <ListItem>true</ListItem> <ListItem>false</ListItem> </list> </ShowFixedPoint> <FixedPointPosition display_name="FixedPointPosition" type="system" datatype="list" security_level="AU" default_value="0"> <list> <ListItem>-1</ListItem> <ListItem>-0.5</ListItem> <ListItem>0</ListItem> <ListItem>0.5</ListItem> <ListItem>1</ListItem> </list> <Timing> <FirstPresentation display_name="FirstPresentation" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> <Indexing display_name="Indexing" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> **<Movement display_name="Movement" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" />** <Pause display_name="Pause" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> <Feedback display_name="Feedback" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> <Answer display_name="Answer" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> <AutoValidate display_name="AutoValidate" type="system" datatype="float" max="0.0" min="0.0" security_level="CU" default_value="0.0" /> </Timing> MatchCollection Collections = Regex.Matches(parameters, "<Movement display_name=\"Movement\" type=\"(<type> .*?).*? min=\"(<min> .*?) .*? max=\"(<max> .*?)\" />", RegexOptions.Singleline); foreach(Match match in Collections) { Console.WriteLine(match.Groups["type"].Value); Console.WriteLine(match.Groups["max"].Value); } As you mentioned you need to capture and replace the max value, I will take into account only that non-capturing group. The special character \s+ is used to indicate one or more white spaces. Regex reg = new Regex("(Movement\s+display_name=\"Movement\"\s+type=\".*\" .*min=\".*\"\s+max=\").*(\")"); Now you can replace the not captured group, I mean the "max" value: reg.Replace(textToSearch, "$10.99$2"); What I did here was keep the captured groups and only replace the not captured value: "$1<replacement>$2". The captured groups can be accessed via reference by $<group>. You can test your Regular Expressions here: http://regexr.com/ I appreciate your help,the string(xml) is very long as you can see there are alot of default numbers ( default="123") i just want to change the ones that contain boldbold ---------OR--------- boldbold I would appreciate if you could write one generic for both and onle only for type="session" @jherax The answer I provided meets the criteria in your question when you posted first time. Now you have edited the question. You can first mark the correct answer, and later edit your post to add the new criteria. And please, add an EDITED section to be clearer. thanks, you guys showed me how to do it, I will post the answer shortly You can use a regex like this: max=".*?" And use the replacement string: max="0.99" Working demo string input = "YOUR STRING HERE"; Regex rgx = new Regex("max=\".*?\""); string result = rgx.Replace(input, "max=\"0.99\""); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result); I appreciate your help, but I didnt explain well(and im new to stackoverflow) the string(xml) is very long as you can see there are alot of default numbers ( default="123") i just want to change the ones that contain ---------OR--------- I would appreciate if you could write one generic for both and onle only for type="session" thanks, you guys showed me how to do it, I will post the answer shortly
common-pile/stackexchange_filtered
Magento cart is always empty on chrome and opera After i add some products to card and i open cart page it shows "the cart is empty". it just happens in chrome and opera; but every thing is ok in firefox. i have checked cookie management and every thing was fine there. what is the problem? *my magento is running on local server. Refer this: http://magento.stackexchange.com/questions/92886/cant-log-into-secure-ssl-magento-site-on-front-end-in-chrome Sounds like a cookie or session issue. It's hard to say with out more info so here are a few suggestions to start debugging: Use the chrome developer tools and inspect your cookies. There should be a cookie named "frontend" with a value of jumbled letters / numbers. Check your session storage (var/session/) for a file named sess_XXXXXXX where XXXXXXX matches the value for the frontend cookie. If those 2 things exist, it should work. var/session/ is empty. im using magento on local. have you given 777 permission to var/ folder ? if don't then give it. Check your app/etc/local.xml file. There should be a part that indicates where your session files should be stored whether that be files, database, memcache, etc. If not already set to files try changing it to files. Easier to debug. The code looks like this: <session_save><![CDATA[files]]></session_save>
common-pile/stackexchange_filtered
SL4 Dataform NewItemTemplate textbox value not getting bound I have a silverlight 4 application using MVVM which has a grid and dataform. the dataform has an EditItemTemplate and a NewItemTemplate. On Editing the EditItemTemplate code runs fine but upon adding a new item the NewItemTemplate code throws an error to the effect that barcode is required. Where could I be going wrong. Thanks in advance. NewItemTemplate xaml code <toolkit:DataField Label="Barcode :" FontWeight="Bold" Grid.Column="0" Grid.Row="0" Margin="1" IsRequired="True" HorizontalAlignment="Left"> <TextBox Grid.Column="1" Name="BarcodeId" Text="{Binding Barcode.BarcodeId,Mode=TwoWay, NotifyOnValidationError=True,ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch" Grid.Row="0" Margin="2" Width="300" TabIndex="0" /> </toolkit:DataField> EditItemTemplate code <toolkit:DataField Label="Barcode :" FontWeight="Bold" Grid.Column="0" Grid.Row="0" Margin="1" IsRequired="False" IsEnabled="True" HorizontalAlignment="Left"> <TextBox Width="200" Text="{Binding Barcode.BarcodeId,Mode=TwoWay}" FontWeight="Normal" /> </toolkit:DataField> NewItemTemplate xaml code <toolkit:DataField Label="Barcode :" FontWeight="Bold" Grid.Column="0" Grid.Row="0" Margin="1" IsRequired="True" HorizontalAlignment="Left"> </toolkit:DataField> EditItemTemplate code <toolkit:DataField Label="Barcode :" FontWeight="Bold" Grid.Column="0" Grid.Row="0" Margin="1" IsRequired="False" IsEnabled="True" HorizontalAlignment="Left"> </toolkit:DataField> Sorry had included the xaml in the question but was not showing I have no idea why this is not binding If anyone could provide me with a dataform that has the NewItemTemplate textbox which is working and some associated viewModel I would appreciate it
common-pile/stackexchange_filtered
Incoming calls from unsaved numbers showing UNKNOWN NUMBER in my MOTO G I recently bought this phone for my dad and its upgraded to lollipop. But whenever any call is coming from an unsaved number, its showing "UNKNOWN NUMBER calling. " The phone happens to be brand new and i haven't yet added a google account or started using play store. Please help. Thank you for your kind attention. This usually happens when your phone contract doesn't include caller ID. When you have caller ID, numbers will show and Google will do a search to show you who is the caller.
common-pile/stackexchange_filtered
Multidocument transactions using doctine-odm for mongodb doctine-odm does not support native strategy for multi document transaction support as per this document However, does anyone have figured out a workaround? According to mongodb, we need to create a session and pass it to every query in the transaction to take control over full commit rollback. this implementation does the same thing but it does not work. I get error while passing session to the ->flush() method. Error The \"writeConcern\" option cannot be specified within a transaction. Instead, specify it when starting the transaction. Try: $callback = function (Session $session) { /** your code here */ } $session = $client->startSession(); with_transaction($session, $callback, [ 'readConcern' => new ReadConcern(ReadConcern::MAJORITY), 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY, 1000), 'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY), ]);
common-pile/stackexchange_filtered
Not computable (but definable) real numbers, not related to the halting problem? The existence of not computable real numbers has been eating at me for a long time. However, I have not seen any example of such a number not related to the halting problem. Could any such number be defined? Below are my thoughts which are not part of the question and can be ignored: I can understand intuitively why NC numbers appear in the HP, because we are basically asking a certain class of machines to 'compute themselves'. Or rather, we are searching for a machine which knows everything about all the other possible machines. Not likely to happen. However, couldn't the problem be solved by generalizing the definition of computable functions? For example, taking quantum computing into account? Related: http://math.stackexchange.com/questions/462790/are-there-any-examples-of-non-computable-real-numbers Note that the reals computable by quantum computers are exactly those computable by regular computers - the only difference is the difficulty of computing them (in the complexity-theoretic sense). A better physical attempt to get beyond Turing computability is via black holes, but it's rough on the computer (and relies on a simplistic model of black holes).
common-pile/stackexchange_filtered
Esper - Detect absence of a certain event with WHERE I was looking to this question, i need this select * from pattern [every (timer:interval(10 sec) and not EventX)]; but with a WHERE id = "001", i dont know where to put the WEHERE. select * from pattern [every (timer:interval(10 sec) and not EventX(id="001"))];
common-pile/stackexchange_filtered
RuntimeException: Unable to create the cache directory (/var/www/sonata/app/cache/dev) I installed the Sonata admin bundle. After installation i refresh my page there is the cache problem then i use the following command to remove the cache: rm -rf app/cache app/log Then I recreate the directory: mkdir app/cache app/log But I got the following error: Runtime Exception : Unable to create the cache directory (/var/www/sonata/app/cache/dev). It looks like a file/directory permission problem. The directory has to be writeable by the webserver. After creating the directory you should adjust the permissions with chown -R www-data:www-data app/cache chown -R www-data:www-data app/log Or for Symfony 4+: chown -R www-data:www-data var This only works on linux systems. The user and group depends on your distribution. On Debian and Ubuntu this should be www-data, on CentOS it's afaik apache. Another solution would be not to delete the whole folders but only their contents via $ rm -rf app/log/* app/cache/* But please be careful with this command. I was having same issue on Ubuntu Server 16.04 and doing this chown -R www-data:www-data var/logs var/cache var/sessions resolved my issue, don't forget to clear cache.. Thanks. Similar solution for iTop if you encounter "RuntimeException : Unable to create the cache directory (/product/itop/itop/data/cache-production/twig/itop-core-update/...)". This solution is correct : https://stackoverflow.com/a/20128013/2400373 But is necessary change the 2 commands in Symfony3: First you should is inside the folder of project: $ sudo chown -R www-data:www-data var/cache $ sudo chown -R www-data:www-data var/logs After delete the cache: $ sudo rm -rf var/cache/* $ sudo rm -rf var/logs/* Regards I solved it changing user and group of folder var/cache and var/logs, then I cleaned cache: sudo chown -R www-data:www-data var/logs sudo chown -R www-data:www-data var/cache sudo rm -rf var/logs/* var/cache/* be careful with that sudo rm -rf /var/logs/* /var/cache/* you are removing root cache !! remove the slash bevor the var And for centos: chown -R apache:apache app/cache if you're coming here for Symfony Help you might have to do this as well if you delete the entire app/logs folder chown -R apache:apache app/logs it works Broks :) thanks , by the way can you explain me what is apache:apache ? why not the current user? It is mostly the permission issue. I have got resolved it on MAC using command: $ sudo chmod -R 777 <path/to/cache/directory> You might try: $ sudo chmod -R 777 /var/www/sonata/app/cache I found a similar problem when I was using the PHP symfony as the error picture. I found it after running command php bin/console cache:clear I solved it by removed everything inside the folder /app/var/cache Changing the CHMOD might help but in case the cache annoys you during the deveopment you can just deactivate it. Navigate to your app config file (located in ../app/config/config.yml from your root directory). Scroll to the twig configuration settings (under twig:) and change the cache value (which should be pointing to the cache directory) to false like so: twig: cache: false If you do not see any cache configuration entry, simply add the line above. of course you would need to reactivate it once the app is ready for production What is likely happening is that you are trying to create the file under apache/nginx. By default apache or nginx has umask set to 0022. From: http://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html Explain Octal umask Mode 022 And 002 As I said earlier, if the default settings are not changed, files are created with the access mode 666 and directories with 777. In this example: The default umask 002 used for normal user. With this mask default directory permissions are 775 and default file permissions are 664. The default umask for the root user is 022 result into default directory permissions are 755 and default file permissions are 644. For directories, the base permissions are (rwxrwxrwx) 0777 and for files they are 0666 (rw-rw-rw). You will need to manually set the umask to 0002, and reset it back to its previous setting before you can create the directories. On a mac computer it will be: $ sudo chown -R _www:_www var/cache $ sudo chown -R _www:_www var/logs If none of above work to you, call a "phpinfo()" on your php file and find for "User/Group" value. That's the user group to give permission to. Also check the path. In my case, I had return dirname(__DIR__) . '../../../../var/cache/ instead of return dirname(__DIR__) . '/../../../../var/cache/ (missing /) I had this problem with phpmyadmin 5.1.0 The solution was to specify the full path of the tmp directory, instead of relative path. On the configuration file config.inc.php I had: $cfg['TempDir'] = 'tmp' I changed it to: $cfg['TempDir'] = '/usr/share/phpmyadmin/tmp' Seems that the problem is something related to "matching" with some allowed paths. Maybe this solution can be extrapolated to other software that uses twig. to generalize so everyone can use this two commands can solve everyone problem. sudo chown -R $USER var/cache sudo chown -R $USER var/logs Further Info: $USER automatically replaces your username so it can be used by anyone. Just delete log and cache directories, then recreate them.
common-pile/stackexchange_filtered
Checking the probability of an object I am working on a simulation of trains leaving cities in the US on a random basis. How it works is every second (tick) I need to set the probablity of each city to a double value between 0 and 1. If a cities probability is 1 then a train needs to depart from the city. I have 6 cities that I am working with. Currently I have 6 threads, one for each city, that randomly generates a double and assigns it to the city every second and if a cities probablity changes to 1 a train object departs. The way I am doing it doesnt seem right to me due to the fact that if I had 100 cities I dont want to use a 100 threads. Does anyone have a better method? Why do you need multiple threads? Also, the probability will never be 1.000 This is my mistake and I know it. I am using the threads to set the probabilities all at the same time. I dont think i am interpreting the probability part correctly. @bp_ltd If you want them set at the same time, why not just use a standard method and set them all at once? You can then create a single thread to act as a "launcher" to simulate the departure of the train. Simply create the thread, pass the trailer identifier, and process from there. Thanks Timothy. Just not sure how to do that. Through a for loop? Is this a homework assignment? Maybe you can post the exact wording and anything you have tried already. Right now I don't think I quite understand what you are trying to do or what you are supposed to be doing. I would recommend always having only 2 threads. 1. TickChecker 2. ProbabiltyUpdater TickChecker will iterate through the list and find the city that matches probability to 1 and kicks it off. ProbabilityUpdater will iterate through the list and updates the probability value periodically. Same interval as the tickChecker or even less than that. If you want to use on the fly triggering of the probability checker use Observable pattern that way as soon as the probability changes to 1 you kick off your action. This way you don’t need multiple threads, as everyone in here are saying. Observable reference document.
common-pile/stackexchange_filtered
Using ID card authentication library c header I am pretty new to C++ (long line since last programming) but I was asked to take a look at a programming issue and alter a ready made code. Basically what we try to do is to use Id card authentication library. The below code aims to feed PIN and card reader name in order to authenticate: #include <iostream> #include <DigiSign_Toolkit.h> using namespace std; int main() { SValue pin, reader, tst; InitializeLibrary(); cout << "Test1" << endl; // debug SValueString("1234", pin); SValueString("Reader name X", reader); cout << "Test2" << endl; // debug BYTE tries; BYTE auth = 2; bool result = Authenticate(reader, auth, pin, tries); SValueFree(pin); SValueFree(reader); ReleaseLibrary(); return 0; In the code the function SValueString(xxx, yyy); which is used to put the authentication values to variables seems not to work (code not continuing but no errors) and if I comment the lines out the second cout << Test2 gets printed to console normally. The code is using these functions from C header file: struct SValue { DWORD len; BYTE *val; }; // BOOL DSAPI SValueString(const char *inValue, SValue &outValue); I have been digging around, but seem not to find anything that could work in here. So, all the help would be appreciated. You'll probably have more luck asking the library vendor for support, at a guess pin needs to be initalised from C header file: the part SValue &outValue); is invalid in C. If the code doesn't continue there is an error. Run your program in a debugger?
common-pile/stackexchange_filtered
How to run a dockerized dnsmasq name server within a tinc VPN with only one process per container I have a tinc VPN mesh network that is used by various types of hosts all over the world and I want to deploy a dockerized dnsmasq name server for use within that tinc mesh. I have already successfully built and configured a "fat" multi-process docker container (using runit) which does what I am looking for. It runs both a tinc process and a dnsmasq process and dnsmasq is configured to bind to the tinc network interface in the container. But now I am trying to build the same functionality using 1-process containers. I know how to build and configure a basic 1-process dnsmasq container and I know how to build and configure a basic 1-process tinc container. I can write a simple docker-compose file that will bring them both up. What I don't know how to do is something like using the tinc container as a gateway that exposes the dnsmasq container to the mesh network, allowing other hosts on that tinc network to run DNS queries against dnsmasq. Is that possible? After doing some intense googling and adapting similar use-cases with openVPN, I figured out a working setup. Conceptually, you bind the network of the dnsmasq container to the tinc container. Here's an abbreviated docker-compose.yml that shows the essentials: version: '3' services: tinc: ... dnsmasq: depends_on: - tinc network_mode: "service:tinc" If you docker exec -ti dnsmasq /bin/sh after bringing this up and then do an ifconfig inside the dnsmasq container, you will see the tinc network interface that the tinc container creates. So if your dnsmasq config binds to that network interface, it just works. Cool. What about routing from tinc clients to dnsmasq? I am struggling with similar seyup using openvpn If I understand what you are asking, then I don't know how to do that with openvpn which I don't use but understand as more of a point to point protocol. Tinc creates a mesh network like a virtual LAN so as soon as you have put the dnsmasq host on the tinc network, it is immediately available to every other host on that tinc mesh network. IOW, tinc routes for you; that's why I use it rather than something like openvpn.
common-pile/stackexchange_filtered
Screened Coulomb potential in metals One of the reasons why we can neglect electron-electron interactions in metals is the fact that their coulomb interaction is screened. I'm confused about the nature of this screening. In the literature the process is usually described like this: If we bring an additional charge inside a neutral metal, the coulomb potential of this charge will be screened due to electrons accumulating (or rejecting) at the charge. This leads to the Thomas-Fermi potential $$ \phi(r) =\frac{e}{r}\,e^{-r/r_{TF}}.$$ But if we consider the potential between electrons in the neutral metal, the screening must have a different origin because the electron density is homogeneous. The above mentioned approach can't be the reason can it? I think the only way for the electron-electron interaction to be screened in the neutral metal is by the presence of the positively charged ions. If we consider a small volume in the metal, the total charge inside will be zero so the long range potential falls off faster then $\frac{1}{r}$. It appears the literature claims that the other electrons are responsible for the screening but I can't see how this is possible. Edit: Maybe I should rephrase the question. In the literature, it seems the mechanism behind the screening is the dynamics of the electrons, rather then the presence of the ions, so my question is Q: How can this possibly be true, given that the electron distribution is homogeneous? in neutral metal it is the positive Ions. the mentioned screening is only for extra charges. Have look at these resources. That may give you some hints about electron-electron interaction http://sites.science.oregonstate.edu/~roundyd/COURSES/ph427/electron-electron.html and http://www.phys.ufl.edu/~pjh/teaching/phz7427/7427notes/ch2.pdf and https://core.ac.uk/download/pdf/158963317.pdf Electron gas is homogeneous, but it doesn't mean that the local charge density cannot fluctuate (as it DOES, indeed). It is true because the local charge operator doesn't commute with Hamiltonian. And screening is a direct result of local density fluctuations. Related (screening in the presence of a magnetic field): https://physics.stackexchange.com/q/710855/226902 Maybe not very useful regarding you question, but other way to see why e-e interactions in a metal can be neglected is by comparing typical kinetic to potential energy. $ E_F = \hbar^2k_F^2/2m$ and $U_{e-e} = e^2/{4\pi\epsilon_0d}$. Using the free electron relation $k_F = (3\pi^2n)^{1/3}$ and $d^{-1} \approx n^{1/3}$ you get $E_F/U_{e-e} \approx 5 a_B n^{1/3}$ where $a_B$ is the Bohr radius in SI units. When the potential energy is equal to or larger than the kinetic energy it is also known as the Mott criterion. The insight of appx is that counter-intuitively, as the density increases e-e interactions are negligible. Yes there are multiple reasons why we can neglect the interaction and I agree that for high densities it becomes a perturbation. Here I'm however only concerned with the screening argument.
common-pile/stackexchange_filtered
Most Man of the match Awards in IPL Which player have the most man of the match award record in IPL (Indian Premier League)? According to Wikipedia's List of Indian Premier League records and statistics, Chris Gayle has the most MOM awards, at 17. See the "Miscellaneous records" section.
common-pile/stackexchange_filtered
How would you host a Haskell web app on AWS? How would you go about hosting a Haskell web app on Amazon web services? What frameworks would you use? A bit unspecific... what do you mean by framework? What have you tried? Have not tried anything yet, but I did not find anything on Google about what others have done to setup a haskell webapp on aws, that's why I am asking on soverflow EC2 is basically having a server there.... so anything would work.... this for example. But if you feel particularly adventurous, you could try ghcjs and Amazon Lambda. Just don't forget to write a blog post about that if you go that way. I did deploy a Yesod app in AWS previously and there was no specific problem I faced. This chapter from the Yesod book was a great reference. I recently attempted to host a Scotty(Haskell) based web application onto Amazon Beanstalk. Since, there was no direct support for Haskell, I had to take the docker approach. The steps involved using a default docker image from Stack (I used stack to build my application), hosting on Docker Hub and referencing that image from Amazon Elastic Beanstalk. I documented that whole process in a sample HelloScotty project on Github Haskell web servers are just like any other web server application - they bind themselves to a port (usually 8080, 3000, etc in development) and serve over it. You could either force the application to bind to port 80 (via the -p flag in Yesod, or in the code with Scotty) as a super user, or you could reroute port 80 to your development port with iptables. However, this doesn't protect you against the process itself failing - for that you would need a watchdog integration, usually with systemd or Upstart. Other than that it's pretty standard.
common-pile/stackexchange_filtered
How are Kuberenetes secrets stored on Amazon EKS I set up a managed Kubernetes cluster via Amazon EKS. Now I’m wondering whether Kubernetes Secrets are stored securely (at rest and transit) by default or if there is additional configuration necessary. The relevant Kubernetes docs are not really helpful in this constellation l, all they say is that secret encryption depends on the cloud provider. Any help, links or samples are greatly appreciated! It appears the answer is yes, they are encrypted at rest, but this is hearsay. There's an open github issue on this topic, and nobody else can find definitive docs stating this, either.
common-pile/stackexchange_filtered
How to trace curvy lines in an image in Python? I'm trying to trace a few curvy lines (vessels) in a retina image. The vessels are very clear in the image, so I thought this would be very straight forward, but I'm having a hard time figuring this out. Here is a link to the actual image: https://drive.google.com/open?id=1cRTk37U7LSeaV6rhvg0K6FKYsnDhlQZr And I'm looking for the following tracing. Also would like to have that red tracing in a separate file: Try reading about cv2.adaptiveThreshold() Here is one possible approach implemented in Imagemagick. You likely can find similar functionality in OpenCV. Not the best detection, but gets most of the lines. Filter noise (20 iterations of -enhance) -- median filtering should work. Perform local area (adaptive) thresholding (-lat) Perform morphology thinning Use connected components processing to remove small isolate regions (<100) Do morphology dilate to thicken the lines. Input: convert img.jpg \ -enhance -enhance -enhance -enhance -enhance \ -enhance -enhance -enhance -enhance -enhance \ -enhance -enhance -enhance -enhance -enhance \ -enhance -enhance -enhance -enhance -enhance \ -negate -lat 50x50+1% \ -morphology Thinning:-1 Skeleton \ -define connected-components:area-threshold=100 \ -define connected-components:mean-color=true \ -connected-components 4 \ -morphology dilate octagon:3 \ result.png thanks for your response. Is this python code? No, as I mentioned, it is Imagemagick code.
common-pile/stackexchange_filtered
Dictionary losing its values somehow? I have a dictionary, private Dictionary<int, int> dict = new Dictionary<int, int>(); I call a foreach loop to go through my dataTable and populate the dictionary, foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows) { dict.Add(Convert.ToInt32(row["ItemNo"]), (int)row["QtyRcvd"]); } Later, in a different method that's called I want to recall some values from my dictionary using the following code int QtyChanged = (int)row["QtyRcvd"] - dict[Convert.ToInt32(row["ItemNo"])]; This throws an exception because the dictionary 'doesn't have that value' which it should. I've tried printing out all of the values in the dictionary just after their added and it's all there. but when I try and print it just before calling it in the other method above, it doesn't print anything. because supposedly it's blank. Does anyone see something I'm not seeing as to how this is happening? These methods are driven by a wpf button, in an mvvm System this is all taking place in the corresponding viewmodel private void ReceiveOrder(object sender) { //log each QtyRcvd for later comparison foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows) { dict.Add(Convert.ToInt32(row["ItemNo"]), (int)row["QtyRcvd"]); Console.Out.WriteLine(dict[Convert.ToInt32(row["ItemNo"])]); } foreach (KeyValuePair<int, int> kvp in dict) { //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value); Console.Out.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } ReceiveOrderDialogWindow dialog = new ReceiveOrderDialogWindow() { Topmost = true }; dialog.ShowDialog(); } Second call, once button is clicked inside of the ReceiveOrderDialogWindow private void requestSerials(object sender) { CommandsViewModel commands = new CommandsViewModel(new ModulesViewModel()); //for each row in our received order.. foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows) { foreach (KeyValuePair<int, int> kvp in dict) { //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value); Console.Out.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } int QtyChanged = (int)row["QtyRcvd"] - dict[Convert.ToInt32(row["ItemNo"])]; The only way a Dictionary could loose values is if you remove them. Maybe you accdidently create a new instance that is freshly initialized, just with some values no longer being there in teh datasource? We need to see more code. Something is happening between where you populated it and where you're using it, but you didn't include that "something". We need a [mcve] Make sure your dictionary populating code is called. BTW, ubVwr.Tables[0].Tbl.Rows... What is .Tbl.? Maybe row["ItemNo"] points to a different value or a different "row" that it was added? It's difficult to tell when there isn't complete code of what's going on. There's definitely no other instance being created. SubVwr.Tables[0].Tbl is a dataTable, like I said that's where the data is being pulled from and that works. @Tristan, please, share more code. What is shown here is bit ugly, but should work, so issue is somewhere else. Better. Please also add your console output, and also confirm that there are no other references to your dict not included in the question. I've looked over it multiple times, and there are no references to dict outside of the ones posted. dict appears to be a field belonging to the class(es) in which the two methods you've shown are defined. But we know that they're not the same instance of the class, even if it's one class, because we see you construct a new instance at the end of ReceiveOrder. And there's no attempt (shown) to pass the dict that you've populated into the dialog instance. Isn't the whole point of an MVVM system to keep the data outside of the view?? I should be able to contain it within the viewmodel. I don't want to pass the data to a wpf window. Youd need to demo some sample data going in. Reminder (due to title): it's == it is; its == belongs to it I found a solution, but the question has been put on hold...? Because it's desired result wasn't clear enough......? clearly I want the dictionary to NOT lose it's values. did that really need to be stated explicitly? do you people just love to flex your points on newer users? Is there sufficient information, currently, contained in the question to determine the result or did you have to rely upon information that only you had access to? The question was put on hold because five people believed that there was insufficient information supplied - and it certainly wasn't enough information to be able to run it for ourselves. There was enough information, as much information as there was to give. Making the dictionary static fixed my problem. I also posted any and all information requested. why even bother to ask , or to have me do that if you were planning on calling it insufficient anyways. No, there was not enough information. That's why several of us asked for more code and a [mcve], which still has not been supplied. You improved your question, yes, but the improvement isn't enough for us to identify the issue without guessing blindly. Take it on the chin, learn from your mistakes, move on and next time ask a more comprehensive question. Getting upset about a closed question is silly, you fixed the problem anyway so happy days. @Tristan Making the dictionary static fixed my problem. This proves Damien's point, that you were using different instances of the same class. In all likelihood, even though static has solved your problem for now, issues like these are often rooted in a less-than-perfect OOP approach, which is likely going to spawn more issues. A more fitting solution would be to e.g. overload the ReceiveOrderDialogWindow constructor to take a dictionary as parameter, so that you can pass the dictionary from one instance of ReceiveOrderDialogWindow to another. The shortest solution is not the best one.
common-pile/stackexchange_filtered
Retrieving Geolocation fields from a Lightning web component using getRecord() I am attempting to retrieve the value of a Geolocation field in a Lightning web component by using wire service with the uiRecordApi's getRecord() method. I can import the compound field or its individual pieces. import FIELD_Location from<EMAIL_ADDRESS>import FIELD_Latitude from<EMAIL_ADDRESS>import FIELD_Longitude from<EMAIL_ADDRESS> However when I attempt the call to getRecord() it fails @wire(getRecord, { recordId: '$id', fields: [FIELD_Name, FIELD_Latitude, FIELD_Longitude]}) wiredPhoto; It populates wiredPhoto.error with a message that Location__c does not exist. I worked around this by creating formula fields to hold latitude and longitude and I can read those using getRecord() without an issue, but that seems subpar. Has anyone else run into the same issue? Wondering if I'm missing something obvious or if this is a known limitation. EDIT: The requirement for not using @salesforce/schema is now documented in the LWC docs NOTE You can’t import geolocation fields from @salesforce/schema. Instead, to access a geolocation field or its constituent fields, use string syntax. // User.Place_of_birth__c is a compound custom field of type Geolocation const PLACE_OF_BIRTH_LAT_FIELD = 'User.Place_of_birth__Latitude__s'; const PLACE_OF_BIRTH_LON_FIELD = 'User.Place_of_birth__Longitude__s'; added based on comments It seems there is a bug for importing geolocation fields (able to import other compound fields like BillingCity). So, we can use direct string notation as below. Geolocation type fields are Compound Fields (like BillingAddress). Two main points to be highlighted from docs is : Geolocation is a compound field that counts toward your org’s limits as three custom fields: one for latitude, one for longitude, and one for internal use. Support for the compound field (geolocation) versus the field’s components (latitude and longitude) varies depending on the functionality you’re using in Salesforce. For example, you can create list views that show the field and its components, but you can’t select the compound geolocation field in Apex. You can run SOQL queries only on a geolocation field’s components. Compound fields are accessible only through the SOAP and REST APIs. The compound versions of fields aren’t accessible anywhere in the Salesforce user interface. Below is the working sample code: import { LightningElement, wire, api, track } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; export default class Poc extends LightningElement { @api recordId; @wire(getRecord, { recordId: '$recordId', fields: [ 'Account.Acc_Location__Latitude__s', 'Account.Acc_Location__Longitude__s' ] }) wiredAcc({ data, error }) { console.log('Account => ', JSON.stringify(data), JSON.stringify(error)); } } and its output: { "apiName": "Account", "childRelationships": { }, "fields": { "Acc_Location__Latitude__s": { "displayValue": null, "value": 1.2345678 }, "Acc_Location__Longitude__s": { "displayValue": null, "value": 2.3456789 } }, "id": "00128000009j45sAAA", "lastModifiedById": "00528000001IIBvAAO", "lastModifiedDate": "2019-08-25T14:37:49.000Z", "recordTypeInfo": null, "systemModstamp": "2019-08-25T14:37:49.000Z" } Note that you should ideally use imported fields instead of direct strings in parameter I have accepted your answer as you have provided an excellent bit of new information - that querying the __s fields by name rather than importing them does work and eliminates the need for formula fields. However, I wanted to also ask if you ran into the same error I did when trying to import the __s fields ... I am unable to query the imported latitude__s and longitude__s fields, have you had any luck? I am excluding the compound field from the query. Am also getting error - modified answer. Thanks, much appreciated! This is now documented in the LWC docs and I've added an update to the question reflecting that. The imports can be replaced as shown below: import FIELD_Latitude from<EMAIL_ADDRESS>import FIELD_Longitude from<EMAIL_ADDRESS> /** My code goes here*/ import { getRecord } from 'lightning/uiRecordApi'; const FIELD_Latitude ='Photo__c.Geolocation__Latitude__s'; const FIELD_Longitude ='Photo__c.Geolocation__Longitude__s'; const PHOTO_FIELDS = [FIELD_Latitude,FIELD_Longitude];
common-pile/stackexchange_filtered
How to instrument a statement just before another statement using clang I have to instrument certain statements in clang by adding a statement just before it. I have a pointer to an Expr object using which I need to insert another statement just before the statement containing it. Right now I am using a hacky approach which just moves back the SourceLocation pointer till I see a ; or } or {. But this does not work for all cases. eg when I try to instrument a for statement, it fails. Is there any class in clang which provides a method to do this in a more cleaner way? EDIT: Here is snippet of my code. I need to insert an assert just before the statement containing a pointer dereference. bool MyRecursiveASTVisitor::VisitUnaryOperator(UnaryOperator *E){ if (E->getOpcode() == UO_Deref ){ Expr *e1 = E->getSubExpr(); SourceLocation SL = E->getLocStart(); } return true; } Are you using clang plugin, LibTooling, of libclang? I am using LibTooling, i think. I used a starter code for instrumentation so I am not completely sure. You can use getSourceRange() on the statement which returns SourceRange SourceRange Class has getBegin() which will return SourceLocation. you can checkout https://github.com/eschulte/clang-mutate and see an example there... EDIT: In order to extract Expr out of Stmt you can checkout this SO question How to get Stmt class object from Expr object in Clang I do not have the Stmt pointer though, all I have got is the pointer to the Expr inside the statement. Is there a way to go up to the Stmt pointer using the Expr pointer? @anirudh - Can you show snippet of your code... I am not sure I understand what you have
common-pile/stackexchange_filtered
System.Net.WebException: The request was aborted: the request was cancelled I have a WCF service that has been giving me this error under load conditions (and I can't seem to recreate the error otherwise). We've been trying to find a way around it for about a week now with no such luck.. The error I see has two parts to it, System.ServiceModel.CommunicationException: An error: (The request was aborted: the request was cancelled.) occurred while transmitting data over the http channel. and: System.Net.WebException: The request was aborted: the request was cancelled. I've seen many people suggest to disable working with keep alive by overloading a method in the Reference.cs file and setting KeepAlive = false, however, our client side is using a service reference (in addition to web reference) and this option does not exist anymore. Another option I've seen was to add a custom Binding to the service instead of the BasicHttpBinding we are using now, but that would bother backwards support of the webservice to those who have been using a webReference (since CustomBinding is not SOAP enabled). Has anyone dealt with this error before? Is there a way to disable keep alive in WCF without affecting the server side? Is there anything other that keep alive that is known to cause this error? You can access Http Context and do what you want. Have a look here: http://blogs.msdn.com/b/justinjsmith/archive/2007/08/22/setting-http-headers-in-wcf-net-3-5.aspx I don't think that HTTP keep alive is responsible for this. WCF should be able to handle this by itself so the HTTP persistant connection is shared among requests and if it expires (it expires after 100s of inactivity) WCF creates new one without firing any exception. If your connection is aborted during request transmission then I expect there will be some other problem. You can use this custom binding as equivalent to BasicHttpBinding without HTTP keep alive: <bindings> <customBinding> <binding name="NoKeepAlive"> <textMessageEncoding messageVersion="Soap11" /> <httpTransport keepAliveEnabled="false" /> </binding> </customBinding> </bindings> Yes, it is responsible and I have seen it before. Wow, I just experienced this myself. What a surprise. Thanks, @Aliostad @Aliostad Just out of curiosity, are you also calling a Tomcat-based Java web service? I had this problem when trying to upload large files. I had to add this to the web.config of the web services <system.web> <httpRuntime maxRequestLength="10240" /> I had this exact same problem. In my case I was executing requests ASynchronously. I was sending a few hundred requests to the 'server' from my client. I am/was using basicHttpBinding. And in my app.config setting the openTimeout property was set to 60 seconds or one minute. Once I set that to a bigger number like 10 minutes, the problem has gone away. So for instance I changed all these values in my app.config file: <configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IScriptRunHost" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" to 10 minutes. This error can also be caused by mixing using clauses with asynchronous calls to WCF services. For example: using (ServiceClient proxy = new ServiceClient(proxyName)) { proxy.Open(); return proxy.FunctionCallAsync(parameters); //Return type being Task<ResultSet> } This will trigger a race condition between how fast can it dispose of proxy versus how fast the asynchronous Task<ResultSet> can be completed. Longer the task takes the more likely it will be to end up in a Faulted state and the Result containing a System.ServiceModel.CommunicationException. This can be fixed by removing the using clause: ServiceClient proxy = new ServiceClient(proxyName)) proxy.Open(); return proxy.FunctionCallAsync(parameters); //Return type being Task<ResultSet> Note that proxy should be persisted too so that once the asynchronous call is completed that a proxy.Close() can be done. This was helpful for my issue as well, which was a bit different: if your OperationContract returns Task<...> (as in Task<Foo> LoadFoo();), the issue is similar, disposing of the proxy beats resolving the Task to get reponse data. Bad API, yes, but that's what I have. I would advise to fix the race condition by simply awaiting the proxy.FunctionCallAsync. Not awaiting async code inside a using can produce all kinds of undefined behavior and should be avoided add this in app.config <system.net> <connectionManagement> <add address="*" maxconnection="5"/> <add address="https://api.limitedconnections.com*" maxconnection="2"/> <add address="https://api.moreconnections.com*" maxconnection = "10"/> </connectionManagement> </system.net> Refer the below link https://cdijkgraaf.wordpress.com/2019/12/02/configuring-maxconnection-in-biztalk/
common-pile/stackexchange_filtered
How to specify name in Django mail? I am using django's core.mail package in conjunction with django-registration for a new user sign up workflow. I have an email account, "no-reply@(mycompany).com" through my company's google mail service, that i want to use to send these emails. In the google mail account settings i set the name for the email account as "(MyCompany) Support" so that if I mail directly from google mail, the emails come in from the account as being from "(MyCompany) Support ". However, when i use django's email settings to send mail, the emails show up in a client's email box as being from "no-reply" which is ugly and may be a bit off-putting to a new client. Is there a way to specify a "Name" for an email address when sending using django's built-in mailer so that the see the "Name" displayed when they get the email? Here are my current settings in settings.py: EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 <EMAIL_ADDRESS>EMAIL_HOST_PASSWORD='**********' EMAIL_USE_TLS = True Please see this: http://stackoverflow.com/questions/2111452/giving-email-account-a-name-when-sending-emails-with-django-through-google-apps You can use "(MyCompany) Support<EMAIL_ADDRESS> as the from address in the call to send_mail. Those solutions are useful if you're using django's email package directly. However, i didn't want to look for a hook to override the way that django-registration uses send_mail so I found the following setting when going through the django files, which lets you set a default from email. DEFAULT_FROM_EMAIL='(My Company) Support<EMAIL_ADDRESS> and it worked! Figured someone else may find it useful, although i'm not so pretentious as to mark my own answer as correct. Looks like you can put the same value in for SERVER_EMAIL as well! You can use ADMINS and MANAGERS tuples in setting.py. E.g.: ADMINS = (('Your Name', 'email@company.com),) And then: django.core.email.mail_managers('subject', 'body') DEFAULT_FROM_EMAIL='(My Company) Support ' Helped me to solve the issue. Another explicit way is to use the Address read my other answer here from email.headerregistry import Address DEFAULT_FROM_EMAIL = Address(display_name="Company Name"<EMAIL_ADDRESS>
common-pile/stackexchange_filtered
How do I calculate the prediction interval for a multilevel meta-analysis? I am conducting a three-level meta-analysis on experimental data using the rma.mv() function from the metafor package. Here's an example code for the model fit: model <- metafor::rma.mv(yi, V, slab = author, data = data, random = ~ 1 | author/effect_size, test = "t", method = "REML") Unfortunately, the results do not include a prediction interval. In the meta package, the metagen() function has gives you the prediction interval on top of pooled estimate and confidence intervals, if you specify the argument prediction = TRUE. For an example, see here: https://bookdown.org/MathiasHarrer/Doing_Meta_Analysis_in_R/heterogeneity.html?q=prediction%20interval#het-R. Here's an excerpt from example results including the prediction interval: ## Number of studies combined: k = 18 ## ## SMD 95%-CI t p-value ## Random effects model 0.5771 [ 0.3782; 0.7760] 6.12 < 0.0001 # Pooled effect estimate ## Prediction interval [-0.0619; 1.2162] # Prediction Interval ## ## Quantifying heterogeneity: ## tau^2 = 0.0820 [0.0295; 0.3533]; tau = 0.2863 [0.1717; 0.5944]; ## I^2 = 62.6% [37.9%; 77.5%]; H = 1.64 [1.27; 2.11] ## ## Test of heterogeneity: ## Q d.f. p-value ## 45.50 17 0.0002 Is there a way to calculate the prediction interval using the rma.mv() function from metafor? If not, is there another way of calculating it for the case of a three-level random-effects model meta-analysis? Use predict(model). All right, thank you! Just what was needed.
common-pile/stackexchange_filtered
How can you register global components in Svelte? Vue (at least Vue 2) allows developers to register components globally: import MyComponent from '@/components/MyComponent' Vue.component('my-component-name', MyComponent) Which then results into: You can write or use component libraries (like Vuetify, Quasar, Ant etc.) without needing to import their components explicitly. You can easily override other global components by just calling Vue.component(...) when you want to extend or change their respective codebase without having direct access to the source code. I read in another SO post that Svelte does not support global component registration. However, I would still like to achieve the same results as given above. How would I approach this in Svelte? It's a good question to ask in the svelte discord I rolled my own when I needed a similar function (it was very handy when adding some interactive components to a WordPress site). Here's the code I used: /** * Turn a svelte element into a simple web component * The content inside the web component will be passed in as the `slot` attribute and it's of type: `Array<ChildNode>` * @param svelteElem * @param elemName */ export function elementify(svelteElem: any, elemName: string) { class newElem extends HTMLElement { svelteComp: any constructor() { super() //at this point the internal elements are not mounted yet, so we need to do it before the next `paint` cycle window.requestAnimationFrame(() => { let children: Record<string, Array<ChildNode>> = { '___': [] } Array.from(this.childNodes).forEach(elem => { let slotName = "___" if ((elem instanceof HTMLElement) && elem.getAttribute("slot")) slotName = elem.getAttribute("slot") if (!children[slotName]) children[slotName] = [] children[slotName].push(elem) elem.remove() }) let props: Record<string, any> = { slot: children, parent: this, } let attribs:Array<string> if (typeof(this.getAttributeNames)=="undefined"){ attribs = Array.from(this.attributes).map(x=>x.name) } else { attribs = this.getAttributeNames() } attribs.forEach(attr => { props[attr] = this.getAttribute(attr) }) let comp = this.svelteComp = new svelteElem({ target: this, props }) // transfer the properties and methods exposed by the component Object.getOwnPropertyNames(Object.getPrototypeOf(comp)).forEach(prop => { if (prop != "constructor") (this as any)[prop] = comp[prop] }) }) } // connectedCallback() { // } // disconnectedCallback(){ // } } customElements.define(elemName, newElem); } To use it, you simply do this: import MyComponent from './components/MyComponent.svelte' elementify(MyComponent,"my-component-name") After that you can use the <my-component-name> tag and the Svelte component will be mounted inside that component. My solution might have some flaws but it's been working for months in production.
common-pile/stackexchange_filtered
Problems to display the Form in the Template using CreateView What happens is that I am using CreateView and I find it curious that the code works when I put {{form}}, it displays all the fields and saves in the database (everything works very well) but when I break down the values ​​one by one for example: {{form.plates}}, {{form.type}}, it does not send anything to the database and it stays on the same page. Why is that? I just need it broken down clientes-add.html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row mb-3"> <div class="col-md-3"> <div class="mb-3"> <label>Customer type</label> <br> <div class="form-check form-check-inline"> {{ form.tipo }} </div> </div> </div> </div> <div class="row mb-3 only-corp hide-item"> <div class="col-md-12"> <div class="mb-3"> <label>Corporation name</label> {{ form.corporacion }} </div> </div> </div> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> You also need to render {{form.fieldname.errors}} for each {{form.fieldname}}. The error will be telling you why the form is not valid, but you cannot see them! You can test it if there is extra html you want to generate only if there are errors. {% if form.fieldname.errors %} <br> {{form.fieldname.errors }} {% endif %} Don't forget {{form.non_field_errors }} Hi, I just followed your recommendation but strangely nothing appears when I click the save button, the only strange thing is that it continues to work when rendering {{form}} and not individually {{form.tipo}}, {{form.corporacion }}, I tried only to put a field and not even with a field could it be saved
common-pile/stackexchange_filtered