Would a responsive design work for a yelp-like site/service?

Question: I'm in the process of developing a review/rating site similar in functionality to Yelp (but on a smaller scale) and I'm going with a Mobile-First approach, and was wondering if I should just make the whole thing responsive, or would such a service be better suited with a separate mobile site?
From what I've gathered responsive designs are more suited to content-heavy sites as opposed to more "task-based" sites like say Gmail but obviously on a site like Yelp you have lists of businesses, lists of user reviews, etc, etc so I was thinking responsive might be the right approach. The biggest problem i've envisioned would be keeping the mobile experience from loading all the heavy assets that would be easier to retrieve on a desktop/desktop connection but all other features (location based, etc) can be done with HTML5 API's right now (from what I can tell).
Would appreciate some feedback on the matter if anyone has good insight into this.
Comment: Mobile-first is the way to keep the weight down of the small-screen presentation of a responsive site.  More resources can be loaded *only* for large screens if desired by using media queries to @import additional CSS and use JavaScript to bring in more content and install mouse-oriented input processing. Of course, without JavaScript the site will be substandard but you still can make it usable.  This is a fairly new strategy and new techniques are quickly being developed to proceed this way, so you have to keep current on the technology.
Comment: There's no simple way to answer "responsive vs. separate mobile site". As is, this question is overly broad.
Comment: @DA01 that's why i limited the scope of the question to cover a "yelp-like" site, given the type of site that is as opposed to a more "complex" web app like Gmail, etc
Comment: The 'type' of site has no real bearing on the question, though. There are so many, many variables involved with making the decision.
Answer: Of course it will work. In general - preparing a separate, mobile site is an approach of the past, and in many ways responsive web design is superior, e.g.:

User ends up with only one link, no matter on which device he is, so he can send a link from his mobile to desktop and go to the same page.
The site content is indexed just once by the search engines, always with the same address.
You can provide similar user experience on various devices, by degrading some elements in the UI that are less important.

Anyway, should you create a mobile version, it should be responsive as well due to the number of the mobile devices: first, it needs to be prepared for touch, secondly - for different resolutions (from tablet to lores mobile phones). And in each case you have to focus on not only clear presentation of the content, but also on the size of navigation elements.
And if you worry about the transfer rates for the images, you can always use adaptive images: http://adaptive-images.com/
Comment: I think the 2-site solution is still viable but is becoming less popular and it takes much more resources to do it right.  Other than that I think your advice is good. +1
Comment: Well, it still is "a solution", but getting less and less popular. And indeed, the proper maintenance of separate, mobile website needs more resources.


Webmock and hash issues

Question: The error message is this

WebMock::Response::InvalidBody:
         must be one of: [Proc, IO, Pathname, String, Array]. 'Hash' given

I am using the code below to test the google library for getting the user info in my controller
stub_request(:get, "https://www.googleapis.com/userinfo/v2/me")
      .to_return(
        body: {email: "firstname.lastname@example.com", name: "Petros"},
        headers: {"Content-Type"=> ["application/json","charset=UTF-8"]}
      )

This is the controller code
service = auth_with_oauth2_service(calendar_account.get_token)
      response = service.get_userinfo_v2

      calendar_account.user_id = current_user.id
      calendar_account.email = response.email
      calendar_account.name = response.name

auth_with_oauth2_service contains this
def auth_with_oauth2_service(access_token)

    auth_client = AccessToken.new access_token
    service = Google::Apis::Oauth2V2::Oauth2Service.new
    service.client_options.application_name = "****"

    service.authorization = auth_client

    return service
  end

response content form
#<Hurley::Response GET https://www.googleapis.com/userinfo/v2/me == 200 (377 bytes) 647ms>
Success - #<Google::Apis::Oauth2V2::Userinfoplus:0x007ff38df5e820
 @email="****",
 @family_name="Kyriakou",
 @gender="male",
 @given_name="Petros",
 @id="",
 @link="***",
 @locale="en-GB",
 @name="Petros Kyriakou",
 @picture=
  "***",
 @verified_email=true>

service being the authorization with google and then request the user data which i can access with response.email and response.name.
However since the google gem gets the info and creates a hash out of it, i cannot do any JSON.parse etc on a string.
What is the way of going about this?
Test suite: Rspec, capybara, webmock, VCR
Comment: I would recommend mocking that service directly, rather than mocking the HTTP call globally. I think you'll have an easier time of it. `allow(my_service).to receive(:my_method).and_return(my_results)`
Comment: Yeah, it's going to be more like: `allow(Google::Apis::Oauth2V2::Oauth2Service.new).to receive(:get_userinfo_v2).and_return(OpenStruct.new( name: "Petros", email: "email@example.com" ))`
Comment: @steel hey thanks for your message, however i am not entirely sure how to utilize this, i wrote this, `allow(service).to receive(:get_userinfo_v2).and_return(email: "firstname.lastname@example.com", name: "petros")` but i get undefined local variable or method "service" which kind of makes sense?
Comment: @JamesMilani hmm getting unauthorized with this
Answer: In WebMock, Hash is not accepted as response body. If the response body is json, You need to encode your hash as json:
{ email: "email@example.com", name: "Petros" }.to_json

Answer: EDIT:
Following up on Steel's comment, if you're going to use the stub method, then you are going to need to chain the stubs. You can give this a try:
service = Object.new
allow(Google::Apis::Oauth2V2::Oauth2Service).to receive(:new).and_return(service)
allow(service).to receive(:get_userinfo_v2).and_return(OpenStruct.new( name: "Petros", email: "email@example.com" ))

This makes what's happening fairly explicit.
Comment: hey `.to_json` cleared the error but now i get `undefined method 'email' for nil:NilClass` i suppose it has something to do with the service, needs to be stubbed as well? i added more code please see `auth_with_oauth2_service`
Comment: Yeah, I guess in your controller `response` is now nil, and it's calling `.email` on it. Hmmmmm. I'll keep thinking on it.
Comment: Can you log the `response` object on a successful call and post what that object is in the question? Thanks!
Comment: Hey sure jsut added the response!
Comment: I updated my edit. I'm curious what you think about that approach.
Comment: hey still doesn't work `WebMock::Response::InvalidBody:
       must be one of: [Proc, IO, Pathname, String, Array]. 'OpenStruct' given`
Comment: Shoot, just figured out testing it myself, and that doesn't work either.

Webmock and hash issues


Mass Effect 3 will be on Origin, how will this affect me with my two other Mass Effect games being on Steam?

Question: As you know EA had a fall out with Steam earlier this year (2011). This meant that any newly released games by EA would only be available through Origin and not any other source.
This is troubling for me as I do not know how it will affect me in keeping my character consistency throughout all the games (as you maintain your character stats, features) all through the Mass Effect series.
Do you think Mass Effect 3 will be able to detect my previous games even though they are located in the Steam folder?
Thanks
Answer: As Mass Effect and Mass Effect 2 saves your games in a non-Steam-specific location ([My Documents]/Bioware/Mass Effect and [My Documents]/Bioware/Mass Effect 2) Mass Effect 3 should not have any problem finding your previous save games.
Comment: Thanks for the swift and concise response! Have A Happy New Year
Comment: @rayman24 You might want to accept the answer, indicating the problem has been solved and [upvote it when you can do so](http://gaming.stackexchange.com/privileges/vote-up).


Foreground app notification is almost empty, background app gets notification but without custom data

Question: I'm working on an Android app in Kotlin and I want to send notification in order to click on it and open a custom view.
I've implemented notification thanks to Firebase. I can send notification thans to Firebase, but the notification are well displayed (with the right icone (= triangle), the right title and the right message) only if the app is in background, but the custom data (key => val) provided in firebase are not detected.
For the foreground app, if I send the notification from Firebase, I can display the custom data (key => val), but the notification doesn't have title, message or custom icone (it has the square/rounded icone)
Instead of showing all my code, I prefere to give you the link I've followed.
https://www.android4dev.com/firebase-pushnotification-android/
I want to have the same result on both side so I can get the custom data.
See the result :
Comment: Anyone's got the answer ? Same problem for me.
Comment: Anyone got the answer?
Answer: There are two types of FCM messages and the behaviour changes based on it.

Notification messages (these are handled by the SDK automatically)
Data messages (handled by the app)

Use notification messages when you want FCM to handle displaying a
  notification on your client app's behalf. Use data messages when you
  want to process the messages on your client app.
  https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

I think that you should use data messages instead of notification messages to have a consistent behaviour.
Comment: Ok thanks. Do you have any sample links to give please ? (not only docs, can't find a recent example...)


Is this box bonded properly to the ground?

Question: The receptacle is from the mid-1950's and my multimeter shows that it is grounded. There are a solid 120 volts when testing between live and ground. I noticed a bare copper wire coming from the cloth wiring in the back tied to a screw connected to the box. I looked around for usable screw holes in the box to screw a ground screw into but they were all way too large. Does this look okay? I get good continuity here between the green insulated copper ground wire I added and the rest of the box.  The green wire goes to the ground screw on the new outlet in this case.
Comment: I like the question. I consider this work reasonable, but I'd like to hear a Code answer about using the cable clamps in metal boxes as ground screws. Also the upper ground is NOT how you do a shepherd's hook; the lower has it right.  It's fine to have a thru-ground, but it needs to tightly wrap somewhat more than 180 degrees around.
Comment: @Harper-ReinstateMonica 250.148(C) prohibits the use of a non-dedicated-to-grounding screw for grounding a box
Comment: I'm no expert in US wiring, but I guess that it's the connection between the box and the ground (perhaps a real ground spike, via your distribution board). In the UK, that bare wire would have to be sleeved inside the box with green-and-yellow sleeving, and should connect to the outlet first, with a separate sleeved wire from the outlet earth terminal to the metal box (if the fixing screws don't perform that function). But I continue to marvel at how different US regulations are.
Comment: @ThreePhaseEel That explains why they sell pigtailed ground screws. I was always curious about that.
Comment: Let's say you're not an electrician and can't afford one at the moment. Would this be a high priority to DIY in your opinion?
Answer: I do a lot of work on older homes and see stuff like this all the time.  Keep in mind that the equipment grounding conductor (EGC), that bare safety ground, was not always present in wiring systems.  If you see old homes - a little older than this one - with two-prong receptacles, those were wired back before the EGC was part of the system.
I think when the EGC was introduced, people were not exactly sure how to terminate it.  You'll see the EGC wrapped around any handy screw.  If it makes solid contact, and the screw is still doing it's job, it's probably not an issue, but it is not code compliant.
In this case, it doesn't look like that wrapped EGC is making solid contact, and it definitely is interfering with the screw clamping that clamp so the cable is secure.  So from a strictly practical standpoint there is room for improvement here.
The NEC has the following rule, but I am not sure it would have been in the code at the time of construction:

250.148(C) Metal Boxes. A connection shall be made between the one or more equipment grounding conductors and a metal
  box by means of a grounding screw that shall be used for
  no other purpose, equipment listed for grounding, or a
  listed grounding device.

In addition, code requires that the box be listed and installed according to the manufacturer's instructions, and there's no way the manufacturer's instructions suggested the clamp screw be used for a ground screw.  That rule goes back so far, it was probably a rule when this was installed, but I think when the EGC was new, inspectors were not super strict about things.  But that's just my guess.
You'll notice in this picture that you have nonmetallic cable with a cloth jacket.  Always be careful handling cable / wiring this old, the insulation is often brittle.  This insulation looks like thermoplastic rather than rubber so it's probably not too bad to handle.  The EGC is smaller than the line and neutral conductors - probably 16 gauge EGC with 12 AWG or 14 AWG line / neutral - which is not an issue.
Since it's no big deal to make this A-OK I would remove the bare ground from the clamp screw and make that clamp snug as it should be - but not super tight, not necessary and that old cable may be fragile.
I'd then splice the green wire, the bare ground, and a 6" bare ground pigtail with a wire nut, and bond the other end of the ground pigtail to the box by a suitable method.  It's very possible that old box doesn't have the usual 10-32 threaded hole for a ground screw, so the easiest DIY thing to use is a grounding clip:

Grounding clips don't require any special tools to install and you don't have to reach inside the box to do what you need to do:
Comment: Great photos. +
Comment: This is an amazing answer.  Thank you, I'll make the upgrade.
Comment: Is drilling and tapping a hole for a ground screw also acceptable?
Comment: @canadianer - Drilling and tapping a hole would be acceptable, the way the rules (NEC 314.40(B) and 250.8(A)(5)) work out a 10-32 screw is usually used.
Comment: Check the size of the grounding conductor, if it is #16 it might be too small for the sizes allowed with the clips, generally they are sized for #10-#14.
Comment: Thanks @JACK and Martian!
Comment: @NoSparksPlease - that's OK, the ground clip is going on the new short pigtail, then the pigtail, the grounding conductor of the cable, and the green wire will be spliced with a wire nut.
Answer: The box is metal therefore the box needs to have a ground wire attached to the box. This is protects you from getting shocked in the event there is a potential at the box. If it were not grounded… if you touched the box and then touched something grounded.. you would become part of the circuit to carry the electricity back to ground.
The bare copper wire coming out of the romex should have continuity all the way back to your panel and landed on the ground bar. It doesn't have to be continuous but it does need to be spliced appropriately where ever there is a splice. (By one method or another every bare copper and green ground wire should be connected together with a few exceptions that are not specific to this topic)
The receptacle or switch needs to have a green or bare copper wire coming off of the green screw on the device.
All green and/or bare copper conductors are to be wire nutted together. Whenever you are terminating wires. You need to leave 6" or more wire coming out if the box. They can't be shorter than that.
You are required to use green or bare copper. No other color.
Keep in mind there are requirements for box fill, depending what you are putting in that box… you may need a deeper box with more room so you don't cause a fire and burn the house down.
To answer your question… NO it does not look good and I would make you fix it. Reason being, among other reasons, yiu bonded your new green wire to a piece bolted on to the housing. You need to bond it to the actual housing. Then, anything touching the housing is bonded. Right now, if you took one of the clamps out, the box is no longer bonded. I know, silly right? Here is specifically why..  imagine a scenario where you have 4 sets of wires coming into the box (just like yours). Two coming in to the box in the top & two coming in to the bottom. Let's say you were demoing the top set, you have to take the clamp out. You have the wire attached to that screw. Once you remove the screw the whole box is ungrounded. You then continue to replace whatever you removed and you move the wires left in the box that are under the other strap. At that time the old insulation falls off your black wire and make contact with the metal clamp or back of box. Now you stick your hand in there while holding the the ground wire, grounded device, anything grounded or a neutral conductor. You then become part of the circuit and you get shocked.
Also, don't twist the wire around the screw. Just crimp on a fork or ring stakon and screw it into a box like if you bought UL listed grounding pigtails from the store.
Comment: "Also, don't twist the wire around the screw." Needs citation. Granted, a pre-fabbed ground wire with ring clamp might be easier, but it sounds like you're saying this is _not_ acceptable and that needs some supporting evidence.


Probability of first to win n matches and score distribution

Question: A game is played between two players. Winning a single game gives one point. The probability of winning a single game is P and losing is S=1-P.
If this game is played until a player wins N times what is the probability of winning depending on N, P and S?
I have tried to calculate this but only managed to 4 see below. not sure if it is correct but believe so. I would like to have the answer in the same format for larger N up to 10 or if possible generally for N.
N=1: P
N=2: P^2 * ( 1 + 2*S )
N=3: P^3 * ( 1 + 3*S + 4*S^2 )
N=4: P^4 * ( 1 + 4*S + 10*S^2 + 20*S^3 )
The above format is informative regarding the distribution of scores and their probability
Answer: I will change your notation a bit to conform to general practice, so that
the probability of winning a single game is $p$ and losing is $q=1-p$.
A player wins with exactly $n$ games if and only if s(he) wins the last one; also, the other player can win $k$ games,  $ k = 0\;\; thru\;\; (n-1)$ games.
The $(n-1)$ wins before the last  can thus be interspersed in $\binom{n+k-1}{n-1}$ ways
For $n=4$, e.g., $Pr = p^4[\binom33 + \binom43q + \binom53q^2 + \binom63q^3]$
You should now be able to put it in a general formula, and work out for any $n$
Btw, for $n=3$, there is an error in your calculations.
It should be $p^3[\binom22 + \binom32q + \binom42q^2] = p^3(1+3q +6q^2)$


Dell XPS 15 Keyboard typing double characters in Gnome Software Center

Question: This is very weird. I had just installed Ubuntu server and Gnome. Typing in the search bar of the Gnome Software center results in double characters.
I haven't faced this anywhere else yet.
Also I cannot access the software sources where I can install hardware drivers and such.
Answer: I also had this bug, but I was able to solve the problem by installing ubuntu-software instead of gnome-software.
Comment: This seems to have been solved. I updated my system yesterday and the problem seems to no longer exist. Try updating your system


Openfaces TabbedPane not working properly

Question: I'm having a problem with an Openface TabbedPane in a JSF application so I created a new application to test the TabbedPane. I have the following code in my page:
<code><h:form>
  <o:tabbedPane>
    <o:subPanel caption="Tab 1">
      <h:outputText value="Hello from tab 1"/>
    </o:subPanel>
    <o:subPanel caption="Tab 2">
      <h:outputText value="Hello from tab 2"/>
    </o:subPanel>
    <o:subPanel caption="Tab 3">
       <h:outputText value="Hello from tab 3"/>
    </o:subPanel>
    <o:subPanel caption="Tab 4">
       <h:outputText value="Hello from tab 4"/>
    </o:subPanel>
  </o:tabbedPane>
</h:form>
</code>
Initially tab 1 is shown. The next tab I click works (no matter which is the next) but no other tab when clicked works. For example when I click tab 2 I can see its contents but when I then click tab 3 I its contents are not shown and I still see previous tab's contents. I checked Mojarra's version on my Glassfish and it is 2.1.6. When I force the loading mode to be "client" everything is working but when I force it to be "server" I get the following error when I try to click a third tab:

[Ljava.lang.Object; cannot be cast to com.sun.faces.application.view.StateHolderSaver
Answer: There are some state-related issues with Mojarra 2.1.6, which are known to prevent OpenFaces from working correctly.
Officially, only Mojarra 2.0.3 is currently supported, but according to the preliminary testing Mojarra 2.1.8 appears to work as well (it still has to undergo additional testing before we declare compatibility with this version officially, but you can try see if it's acceptable for you).


Displaying Border on TextBlock when TextBlock placed inside ScrollViewer

Question: I have WPF application, In one of My WPF form has TextBlock. I placed TextBlock inside ScrollViewer for providing scrolling functionality. I want Border on TextBlock so, I have written following code in XAML.
<ScrollViewer Margin="230,32,12,147">
    <Border BorderThickness="1" BorderBrush="Black">
          <TextBlock Name="textBlock1"></TextBlock>
      </Border>
 </ScrollViewer>

With scrollBar GUI displayed like below.

Bottom Border display on scroll down to the TextBlock. User Experience is not good for this design. So, I tried with below code but Border is not displaying.
<Border BorderThickness="1" BorderBrush="Black">
    <ScrollViewer Margin="230,32,12,147">
          <TextBlock Name="textBlock1"></TextBlock>
     </ScrollViewer>
 </Border>

How I can display Border When TextBlock placed inside ScrollViewer?
Comment: I solved with
Answer: Set border in ScrollViewer control!
<ScrollViewer Margin="230,32,12,147" BorderThickness="5">
      <TextBlock Name="textBlock1"></TextBlock>
 </ScrollViewer>

In properties window, expand Other group and set BorderThickness
Next code works well:
<ScrollViewer Height="116"  Margin="115,112,0,0" Width="269">
        <Border BorderBrush="Silver" BorderThickness="5" Height="100" Width="200">
            <TextBlock Height="69" Name="textBlock1" Text="TextBlock" />
        </Border>
    </ScrollViewer>

Code example for outside border:
<Border BorderBrush="Silver" BorderThickness="5" Height="100" HorizontalAlignment="Left" Margin="167,104,0,0" Name="border1" VerticalAlignment="Top" Width="200">
        <ScrollViewer Height="83" Name="sv" Width="184">
            <TextBlock Name="textBlock1" Text="TextBlock TextBlockTextBlockTextBlock TextBlock TextBlock TextBlock TextBlock TextBlockTextBlockTextBlock TextBlock TextBlock TextBloc TextBlock TextBlockTextBlockTextBlock TextBlock TextBlock TextBloc TextBlock TextBlockTextBlockTextBlock TextBlock TextBlock TextBloc" TextWrapping="Wrap" />
        </ScrollViewer>
    </Border>

Comment: Did you set `BorderBrush` color?
Comment: Yes, Border is not displaying after setting BorderBrush="Black"
Comment: Ok, ScrollViewer's Border works in Silverlight, but not in WPF. Look at my answer, it was edited.
Comment: In your solution if I specified  Height & width property of Border then scrollbar is not displaying if I have 100 lines text in TextBlock. As my Question I want Both ScrollBar as well as Border outside Scrollviewer so, User Experience is good. You can see I achieved scrollbar and border in my question (see image). but problem with user experience. I want to display Border outside scrollviewer.
Comment: Yes, You are right It's working in Silverlight But I want that in WPF. my question on WPF.
Comment: I've tried your second code example. In this way, border will be displayed if you manually set border-width and border-height.
Comment: Thanks. Yes It's working if I specified Width and Height in Border style then It will Fix size. I don't want to fix size so, In my second solution I removed Margin property from Scrollviewer and put that in Border.


DRF: How to get Users object in a get method as a Response?

Question: How can I get all user objects in get method in views.py with other models?
views.py
class WebDashboardViews(generics.ListAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,permissions.IsAuthenticated,)
    serializer_class = serializers.DashboardSerializer

    def get(self, request, format=None):
        all_user_queryset = models.User.objects.all()
        if not all_user_queryset:
            total_user = 0
        else:
            total_user = all_user_queryset.count()
        total_android_user = models.UserMobileDevice.objects.filter(os="Android")
        if not total_android_user:
            total_android_count = 0
        else:
            total_android_count = total_android_user.count()
        content = {'total_user':total_user,'total_android_count':total_android_count, all_users: all_user_queryset}
        return Response(content)

I want the user object in all_users key. But I am getting an error:

Object of type User is not JSON serializable

My serializer code is :
class DashboardSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        field = ['id','created_at','name']

I am not sure what I am doing here. Any help will be highly appreciated. Thanks
Answer: You get that error because you are trying to respond with not-serialized objects here: all_users: all_user_queryset
You need to serialize them first (I guess you have an UserSerializer, if don't, just rename your DashboardSerializer to UserSerializer because it is just what it is):
user_serializer = UserSerializer(all_user_queryset, many=True)
content = {'total_user':total_user,'total_android_count':total_android_count, all_users: user_serializer.data}
return Response(content)


Why doesn't java allow use of type parameter with super keyword?

Question: If
public void foo(List<? super Integer> list){}

is valid, what's wrong with
public <T super Integer> void foo(List<T> list){}

If second one can't be allowed, since it does not make sense as it will allow any type to be qualified to satisfy constraint on T, what's different with first case?
Comment: What do you want to use `T` for? In the sense of PECS, given a `List`, `T` isn't useful because you can never get an element out of that list (because it's a consumer, not a provider), for example, to see what its type is.
Comment: So you want to be able to put `Integers`, `Numbers` and `Objects` in the list? `String` is an `Object`, should that be allowed in the list?
Answer: Consider the acronym PECS:

Producer Extends, Consumer Super

Given a List, T isn't useful because you can never get an element out of that list (because it's a consumer, not a producer), for example, to see what its type is: it is simply a consumer that it is safe to pass an Integer to.
Answer: This is one of those questions where the answer is that you'd have to ask the language designers. My guess is that there simply aren't the use cases to justify it.
If you try hard enough you can think of examples that require it, but they're so contrived that I don't think it's worth it. Here's the simplest method I can think of that (I think) couldn't be written without this feature.
static <T super Integer> void combineAndAdd42(Set<T> set1, Set<T> set2) {
    set1.add(42);         // This line requires T super Integer.
    set1.addAll(set2);    // These 2 lines require both Sets have the
    set2.addAll(set1);    // same type, so it can't be done with wildcards.
}


Change accordion arrow up down via js

Question:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css">

Heading

  Accordion

    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

I am using bootstrap accordion in my project, while clicking on the arrow button it is not changing. I want, when accordion remains collapse arrow head should be down, when it expands arrow heads should be in the upper direction.
Below is my codepen url. Thanks in advance.
https://codepen.io/makhan196/pen/VJPNgd
Accordion

    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Answer: You can try something like this with Jquery,hope it helps

$("a[href$='#demo']").click(function() {

  let attr = $("#demo").attr("class");
   if (attr=="collapse show") {
    $("i").removeClass("fas fa-chevron-up");
    $("i").addClass("fas fa-chevron-down");
} else {
   $("i").removeClass("fas fa-chevron-down");
    $("i").addClass("fas fa-chevron-up");
  }

})
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css">

Heading

    Accordion

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Change accordion arrow up down via js


How to avoid NullPointerException in a Fragment with a delayed Runnable

Question: I have an app with 5 tabs, 3 are the same fragment and two are two different fragments. This problem happens in all 5 fragments since the code is the same.
When I click the tabs really fast and there's some text in my AutoCompleteTextView, the app crashes.
I've tried to check if my components (listAdapter and ArrayAdapter) are not null before asigning or initializing them.
override fun afterTextChanged(s: Editable?) {
            val db = DataBaseHandler(context)
            var listAdapter: ArrayAdapter<String>

            Handler().postDelayed({
                search = etSearch.text.toString().trim()
                if (search.length >= 3){
                    resultList.clear()
                    products = if (isNumeric(search)) db.readData_SomeProductsId(search)
                        else db.readData_SomeProductsDesc(search)
                    for (product in products!!)
                        resultList.add(product.prod_description)
                    if (resultList.size == 1){
                        product = products!![0]
                        ETClear(etSearch)
                        addProduct()
                    } else{
                        if (resultList.size > 1){
                            listAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, resultList)
                            etSearch.setAdapter(listAdapter)
                            etSearch.showDropDown()
                        }

                    }
                }
            }, 600)

            etSearch.setOnItemClickListener{ parent,view,position,id->
                val selectedItem = parent.getItemAtPosition(position).toString()
                product = db.readData_ProductDescription(selectedItem)!!
                ETClear(etSearch)
                addProduct()
            }
        }

The error shows as follows:
06-05 18:01:49.034 26859-26859/com.example.said.puntodeventa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.said.puntodeventa, PID: 26859
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
    at android.view.LayoutInflater.from(LayoutInflater.java:234)
    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:178)
    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:163)
    at com.example.said.puntodeventa.SaleFragment1$onViewCreated$1$afterTextChanged$1.run(SaleFragment1.kt:109)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7231)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Thanks in advance
Comment: I guess the problem is more the `context` variable/property which may be set to/returns null sometimes.
Comment: `DataBaseHandler(context)` appears to be a likely candidate.
Answer: You can't assume your Fragment will always have a non-null Context.
To fix this, it's good to understand where onAttach and onDetach fit in the Fragment lifecycle.
You've got a Runnable chunk of code that you're purposely delaying execution by 600 milliseconds.  That will be more than enough time for the Fragment to be detached from its parent Activity in race conditions like the "When I click the tabs really fast" scenario you've mentioned.
The NullPointerException occurs inside of the ArrayAdapter constructor when it tries to create a LayoutInflater from your passed in Context (which is null).
According to your stack trace, the line of code in your Runnable that causes this is:
listAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, resultList)

One way to fix this would be to null-check the context as the first line in your Runnable block and early return if it is null.
Comment: I added ` } else if (context != null){
                            listAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, resultList)
                            etSearch.setAdapter(listAdapter)
                            etSearch.showDropDown()
                        }` Thank you so much!


I keep losing the Internet connection in Ubuntu 11.10

Question: I recently assembled a new desktop with an ASUS PCE-N15 wireless network adapter and my home wireless network is detected and I am able to connect to it and even access the Internet.
However, after little time I lose the Internet connection, not the wireless connection to the home network, and have to manually disconnect and reconnect in order to get Internet working.
Anyone has any ideas?
UPDATE: /var/log/messages
Apr 19 13:46:50 videl kernel: [13415.875472] rtl8192c: Loading firmware file rtlwifi/rtl8192cfw.bin
Apr 19 13:58:08 videl kernel: [14093.833899] cfg80211: Calling CRDA to update world regulatory domain
Apr 19 13:58:08 videl kernel: [14093.913925] cfg80211: World regulatory domain updated:
Apr 19 13:58:08 videl kernel: [14093.913926] cfg80211:     (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
Apr 19 13:58:08 videl kernel: [14093.913927] cfg80211:     (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
Apr 19 13:58:08 videl kernel: [14093.913929] cfg80211:     (2457000 KHz - 2482000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
Apr 19 13:58:08 videl kernel: [14093.913930] cfg80211:     (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
Apr 19 13:58:08 videl kernel: [14093.913932] cfg80211:     (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
Apr 19 13:58:08 videl kernel: [14093.913933] cfg80211:     (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
Apr 19 13:58:13 videl kernel: [14098.456988] rtl8192c: Loading firmware file rtlwifi/rtl8192cfw.bin

UPDATE 2: The result of running ip route list with and without internet connection is the same:
default via 192.168.1.1 dev wlan0  proto static
169.254.0.0/16 dev wlan0  scope link  metric 1000
192.168.1.0/24 dev wlan0  proto kernel  scope link  src 192.168.1.7  metric 2

Comment: `tail /var/log/messages`, please.
Comment: If you mean you can talk to other machines on the local network but not machines on the Internet, then perhaps it means the default route in the routing table is getting dropped.  When you next encounter the problem, run `ip route list` and paste the output in your question.
Comment: Could be an IP address conflict. Check your computers IP address against your routers DHCP table, and make sure that your computer name matches up. You could also try powering off the router for a bit to let it reassign ip addresses...

Just a few thoughts.
Comment: I've checked, it is not an IP conflict :(
Answer: It's the same driver (rtl8192ce) as in this question - and a very similar behaviour. Best solution up to now is to use kernel 3.0.0-14. It's not perfect but better than any of the later kernels.
Comment: I didn't try changing the kernel, but I looked at the post you mention and followed one of the answers that suggests running `watch sudo iwlist wlan0 scan` which does keep the Internet connection alive. Thanks.
Comment: I guess I was wrong, it took a few hours but the Internet connection eventually failed...
Comment: The problem seems to be gone, I've re-installed Ubuntu and kept kernel 3.0.0-12. Thanks.


Can I automate my system survey?

Question: System Survey is a core feature of Stellaris. It allows my glorious Empire to extend its frontiers and find new forms of life to discover and resources to exploit.
But after a few decades, I find that I spend most of my time assigning new targets to my Science Ships, or forget to give them a new system to explore after they finish their assignment.
Is there a way to set my ship in an automated Survey mode, where they will automatically go to a new system when their assignment is done? Or at least, give them a queue of system to survey so I can send them on a round around my border and focus on other tasks while they scan?
Answer: You can queue orders.
This can be applied to any order, holding SHIFT when assigning orders will put them in a queue. I don't think there is a way to automate the process entirely but stacking them in a queue will help. The only problem with this is if there are any hostile forces the queue will be disrupted and won't continue until you re-assign. One good thing about the system is that if there are any anomalies you can research them and it won't break the queue it will just place it at the top to be done first and then continue.
I will take a look at home tonight if there is any method of automation and update this if I find a solution.
Comment: One way to dodge the hostile forces issue is to set the behavior to passive, but that just means they'll ignore the hostiles and keep scanning until they're destroyed. If there's some way to remove only the top system from the queue that would be awesome
Answer: There is a Feature called Automatic Exploration that is unlocked by the Physics Technology Automated Exploration Protocols. This will allow your Science Ships to explore the galaxy while controlled by AI (though it will still need a scientist, as I recall). It also increases your surveying speed by 25%.
The only prerequisite for this technology to appear in your Physics tech choices is that the current game year be 2210 or later. Here is what it looks like in-game:
Comment: There are multiple mods that allow automated surveying from the start, such as [this one](http://steamcommunity.com/sharedfiles/filedetails/?id=784249404). Of course, any mods will disable achievements if you wanted those.
Comment: @Shadur Yep, that kind of mod has been a must-have for a lot of players since release. Only reason I did not include anything about mods in my answer is because OP didn't include the [tag:mods] tag.

Can I automate my system survey?


Conjugate of conjugate partition

Question: Let $\lambda=(\lambda_1,\dots,\lambda_r)$ is a partition of $n$ and denote $\lambda'$ the conjugate partition of $\lambda$, with $\lambda'_j=\#\{i\,|\,\lambda_i\ge j\}$.
I'm struggling to try to prove that $(\lambda')'=\lambda$ using only the definition of conjugate partition and without using Ferrers diagrams.
More specifically, I'm trying to justify why these two numbers are equal
$$(\lambda')'_k=\#\{j\,|\,\lambda_j'\ge k\}=\#\{j\,|\,\#\{i\,|\,\lambda_i\ge j\}\ge k\}$$
$$\lambda_k=\#\{j\,|\,\lambda_k\ge j\}$$
but I can't figure it out with the indexes and sums appearing.
Could someone help me to develop the steps?
Answer: We use the convention to write a partition $\lambda=\left(\lambda_1,\dots,\lambda_r\right)$ using ordered parts:
$\lambda_1\geq \lambda_2\geq\cdots\geq \lambda_r\geq 1$. We also write a partition sometimes in the form $\lambda=\left(\lambda_j\right)_{j\geq 1}$ and identify it with the $r$-tupel $\lambda=\left(\lambda_j\right)_{1\leq j\leq r}$ of its non-zero entries.

We obtain using OPs prime notation for conjugate partitions
\begin{align*}
\lambda&=\left(\lambda_j\right)_{j\geq 1}\\
\\
\lambda^{\prime}&=\left(\lambda_j^{\prime}\right)_{j\geq 1}=\left(\#\{q\big|\lambda_q\geq j\}\right)_{j\geq 1}\\
&=\Big(\sum_{{q\geq 1}\atop{\lambda_{q}\geq j}}1\Big)_{j\geq 1}\tag{1}\\
\\
\color{blue}{\lambda^{\prime\prime}}&=\left(\lambda_j^{\prime\prime}\right)_{j\geq 1}=\left(\#\{q\big|\lambda_q^{\prime}\geq j\}\right)_{j\geq 1}\\
&=\Big(\sum_{{q\geq 1}\atop{\lambda_{q^{\prime}}\geq j}}1\Big)_{j\geq 1}\tag{2.1}\\
&=\Big(\sum_{{q\geq 1}\atop{\#\{r|\lambda_r\geq q\}\geq j}}\Big)_{j\geq 1}\tag{2.2}\\
&=\Big(\sum_{{q=1}\atop{\#\{r|\lambda_r\geq q\}\geq j}}^{\lambda_j}\Big)_{j\geq 1}\tag{2.3}\\
&=\left(\lambda_j\right)_{j\geq 1}\tag{2.4}\\
&\,\,\color{blue}{=\lambda}
\end{align*}
and the claim follows.
Comment:

In (1) we write the cardinality of the set as sum adding up $1$ whenever the condition $\lambda_{q}\geq j, q\geq 1$ for a given $j$ is true.

In (2.1) we use the sum notation again as in (1) but now with $\lambda_{q^{\prime}}$.

In (2.2) we write $\lambda_{q^{\prime}}$ as cardinality of the set with parts $\lambda_r$.

In (2.3) we note that since $\lambda_j$ is at the $j$-th position of the partition the index $q$ is bounded by the upper limit $\lambda_j$. Indeed, if $q>\lambda_j$ the parts with $\lambda_r \geq q$ are left to the position of $\lambda_j$ and so this number of parts is less than $j$.

In (2.4) we respect that in (2.3) whenever $q\leq \lambda_j$ all parts to the left of $\lambda_j$ fulfil the condition $\#\{r|\lambda_r\geq q\}\geq j$.
Comment: Perfect! Thank you!
Comment: @FreeFunctor: You're welcome! :-)

Conjugate of conjugate partition


Tool to send request and receive response

Question: I am trying to inspect some html, which is not displayed correctly in IE. when I look at the html in IE and FF, they are both different slightly and this might be causing the issue.
I want to grab html returned from the server and thus do not want to send request using a browser.
can anyone advise me any such tool ??
Comment: Are you looking at the HTML source (with View Source) or the generated DOM (with debug tools)? The source should be the same in both cases.
Answer: If you are using linux or unix system, you can use curl to do that.
to send GET request:
curl "<< request-url >>"

to send POST request:
curl --data "<< post-parameter >>" "<< request-url >>"

And you can use -X option to define what HTTP method you want to send with.
or maybe you're using Windows, you can use the web tool to send GET/POST requests like
http://hurl.it/
Answer: curl would do the trick. curl http://www.google.com, for example.


how to set the search form next to the site title in wordpress

Question: I want to move the:  next to the site title.
For now the search form is under the site title.
I just dont know how to put the "get search" inside the "echo bloginfo".
I want the search form in the right side (after the title.)
This is the php file:
<body <?php body_class(); ?>>

    <hgroup>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"  rel="home"><?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

    </hgroup>

                <?php get_search_form(); ?>

    <?php if ( get_header_image() ) : ?>
    <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php header_image(); ?>" class="header-image" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" />
    <?php endif; ?>

Answer: get_search_form() used to display search form you can put like below or you can also adjust with css code.
  <hgroup>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"  rel="home"><?php bloginfo( 'name' ); ?>

 <?php get_search_form(); ?>

<?php bloginfo( 'description' ); ?>

        </hgroup>

Comment: hey, thanks for the answer. in the css i dont have somthing that relative to the search form Except the:  .widget_search label {
 display: inline-block;
 font-size: 13px;
 font-size: 0.928571429rem;
 line-height: 1.846153846;
}  so what can i do?


SQL: Data Cleaning

Question: I am facing a problem which I do not know how to categorize. So, pardon me for the generic title. I have a dataset like:
Table1: Column1, Column2, Column3.
According to my business logic, for a pair of 'Column1 Column2', the Column3 can have only one unique value. So below table is a problematic one because of the second entry:
Table1
Column1  Column2  Column3
A1       B1       R
A1       B1       O   << ERROR! for A1-B1 pair only one value on column3 is accepted
A2       B2       R
A2       B3       J
A3       B3       K
A4       B5       K

From above table I would like to find the problematic entries:
A1       B1       R
A1       B1       O

Thanks in advance for your help !
Answer: Using your example column names, you can run the following query to just see the Column1/Column2 pairs that have more than 1 value in Column 3.
SELECT Column1, Column2, COUNT(DISTINCT Column3) as Column3
FROM Table1
GROUP BY Column1, Column2
HAVING COUNT(DISTINCT Column3) > 1

You can omit the HAVING line to see the complete list of Column1/Column2 pairs.

SQL: Data Cleaning


What is the proper way to handle connections betweeen client/server in .NET Framework?

Question: In socket programming, specifically TCP Sockets, if you have two programs (client and server) where the client is a loop that keeps taking the user's input then does a write stream while the server repeatedly listens by using TCPListen's AcceptTCPClient method (.NET Socket classes). On the client side program, at the end of each iteration, do you close the the connection with the server then re-instantiate the TCPClient class at the beginning of the next iteration?
I assume this because the server wants close connection with (dequeue your TCPClient socket?) in order to serve the waiting connections. However, I don't think it is computationally proper to re-instantiate the TCPClient class every time (client side). I tried to use the Connect and Close methods, but they yield run-time errors.
Comment: There is no reason for the server to close connections to serve others. Take a look at asynchronous sockets and you'll be all set. Currently you are doing it wrong.
Comment: I think you are right, the listening method is blocking which implies that the current connection must be closed?. I think I should complete go through all the concepts to gain a whole perspective. Thank you.
Comment: 'the listening method is blocking which implies that the current connection must be closed' Where do you get that idea ?
Answer: You certainly could make all your connections short lived, but you certainly don't need to.
The Accept loop is really there so multiple clients can connect. There is nothing that says you can't just leave your connection open until you are actually done.
As far as re-instantiating goes, you are taking a far bigger hit by re-establishing the TCP socket, so I wouldn't worry about the object construction too much.
Comment: @Furified Not if you do it right. Whatever call you are making that does that is the *wrong* one. Now, if *you* did something silly like overwriting your old variable, thats your problem :)
Comment: @Furified Unfortunately I cannot speak to the accuracy of your book. That said, I've done this several times and *never* had the experience you are describing.
Comment: The TCPListen's AccceptTCPClient returns a TCPClient instance with the current accepted client and will replace it with the previous one. So the previous client will receive a run-time error when resending again because the connection will be closed, which forces you to reconnect again (didn't work when using client.Connect()) and gives you only one option which is to re-instantiate the client to connect to the server again.
Comment: It was the way presented in the book I am using (TCP/IP Programming using Csharp).
Comment: Can you suggest several references to explain exactly what is going on under the hood. Not too lower level though. Thanks.
Comment: Oh yes, @BradleyDotNET, be a good boy and fetch *several* references.  There's a good chap.
Comment: @SamAxe Why is the mockery?
Comment: AcceptTCPClient creates a new tcpclient for a new client connection that is totally unaware of the previous one. You probably did not read the book very well.
Comment: At the end (Ch5), there is an explanation of everthing that is going on, it's called Under the Hood, which explains what is specifically going on and such as the Data structures used and shows the issues rising from application programs and such, I should have jumped to this chapter from the start. Thanks.


GFCI receptacle will not reset

Question: My GFCI tripped and would not reset. I jumpered out the outlet and all power returned to normal. I assumed it was a defective GFCI so I replaced it. Same problem. Power is available at the line side, but when the reset button is pushed the GFCI just trips again. I reversed the wires, thinking that maybe I had line and load reversed, but that didn't work either. I jumpered out the outlet again, and the power came back on downstream. Any suggestions??
Comment: You should consider all downstream devices as suspect. I don't think wires will have suddenly changed position - unless you have been changing other things which you have not mentioned - possible of course.
Comment: What is connected to the LOAD terminals of this GFCI in terms of outlets, lights, hardwired loads, and so on?
Answer: Never do random things in electrical. You will stumble upon combinations that will work but will kill you.
Pause to learn what exactly it is you are doing.  Only then proceed.
OK, so you had a GFCI that was previously installed and worked before, and now suddenly is tripping.
The most important point is that GFCI devices are capable of protecting downline loads.  Those are the ones that are now dead.

First, unplug all the appliances that are downline from the GFCI device, and plugged into it if it's a receptacle.  That will clear up 99% of your problems in a "didn't trip before, now does" situation.  Once it clears, start plugging stuff in again When you plug a certain appliance in, it will trip.  Try that in a different GFCI and see if it still trips there. Off to the appliance repair it goes.
Second, unwire the GFCI device and disconnect and cap off the LOAD wires only.  Now, see if the GFCI device clears.  If it does, the problem is in either a hardwired device (lamp, fan etc.) or is in the wiring itself.

Then, you reconnect LOAD and start removing hardwired devices.  You need to remove both hot and neutral to have an effective test.  Obviously when you remove a device and it stops tripping, you found the problem.
If you have removed all hardwired devices and it still trips, then you must do a bug-hunt for any crossed neutrals - anywhere a device uses one cable's hot yet another cable's neutral. Also check for this in the GFCI itself.  If you get stuck or confused, take photos and post them here.

Third, if the GFCI device still won't clear with nothing on LOAD, and (if it's a GFCI receptacle) nothing plugged into it, then you definitely have a bad GFCI.  Otherwise, you do not.

GFCI receptacle will not reset


Store Generic list in Cookies

Question: I want to store my generic list into cookies because session expire again and again when i change code and rebuild. i want to store my list in cookies so that cookies is not expire when i rebuild.
How to Store My generic list into Cookies.?
I tried this :
List<EvaluationModel> evalModel = (List<EvaluationModel>)Session["ESearch"];
HttpCookie cookie = new HttpCookie("evalModel");
cookie.Value = evalModel;
cookie.Expires = DateTime.Now.AddHours(24);
Response.SetCookie(cookie);

But its say cannot implicitly convert type generic.list to string.
Thanks
Comment: I don't see any generic list in your code and "not working" is not a description that is good enough.
Comment: "EvaluationModel" seems to be a class and not a list. Does that class contain a list? Please elaborate.
Answer: A cookie is just string data; the only way to do that would be to serialize it as a string (xml, json, base-64 of arbitrary binary, whatever) and again deserializing it back when you need it.
Also serializing a generic list means it will create a big string which will be running to and fro the client/server. Hence your request/response will be heavy and hence slow.
IMO, caching this at the server is the correct thing; don't put this in a cookie.

Store Generic list in Cookies


Mounting light on cedar siding

Question: Contractor installed exterior lights on cedar siding using blocks like this http://www.aifittings.com/catalog/siding-mounting-blocks/siding-mounting-kits-with-built-in-box/ rather than building something like https://www.thisoldhouse.com/sites/default/files/styles/content_box/public/migrated/images/14-norm-advice.jpg . Am I getting an inferior product?
Comment: Hello, and welcome to Stack Exchange. Links tend to break; it's better if you add the images to your question. That said, make sure that you provide a link to the source for the images.
Answer: The method shown in the This Old Hose picture fairly involved, you're basically letting a flat area into the siding, then letting an electrical box into that flat.  It has to be done just right, especially if it's added on after the siding is finished.  It allows you to use matching cedar or other aesthetically pleasing material for the flat.
The Arlington box is simple and easy to use, it installs without really disturbing the siding, less chance for a mistake or failure that will cause a leak, and fully code compliant when installed properly.  I don't think you could call it inferior in any way.

Mounting light on cedar siding


OpenSSL API: CRL checking doesnt work me

Question: I'm trying to add to my X509_store, CRLs management.
I did that:
int x509_add_crl_to_store( X509_STORE * store, const char * crl_file ){
STACK_OF(X509_CRL) *crls = 0;
X509_CRL *x;

CHK(!store, SSL_FAIL);

if (X509_STORE_set_default_paths(store) != 1){
    MITM_PRINT_ERR("Error loading the system-wide CA certificates");
    return SSL_FAIL;
}

if(load_crls_from_PEM(crl_file, &crls) != 1)
{
    MITM_PRINT_ERR("load_crls_from_PEM failed.");
    return SSL_FAIL;
}

while((x=sk_X509_CRL_pop(crls)) != 0){
    if(X509_STORE_add_crl(store,x) != 1){
        MITM_PRINT_ERR("Failed to add CRL to store.");
        return SSL_FAIL;
    }
    else{
        MITM_PRINT_ERR("Succedded to add CRL to store.");
    }
}

/* set the flags of the store so that CRLs are consulted */
//X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL| X509_V_FLAG_TRUSTED_FIRST);

return SSL_OK; }

The issue is:

If I enable the last lines:
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);

so the CRL checking is working BUT the trusted store is not checked anymore.
And of course, if I disable those lines, the trusted CA checking is working but not the CRLs.
Any idea ???
Thanks
Mikael
Comment: When you say "trusted store is not checked anymore" do you mean the untrusted CAs are checked first or do you mean the certificate chaining process entirely fails?
Comment: I mean the root certificate is no more recognized as trusted (and it appears in the store). I don't know exactly if the verification failed or the trusted store is not checked at all .... because it is done internally by openSSL. Thanks
Answer: One should be very careful while enabling the CRL flag X509_V_FLAG_CRL_CHECK_ALL in combination with X509_V_FLAG_CRL_CHECK, because the combined effect of both is to require the presence of every CRL corresponding to all the CAs in the chain of trust. So if you added the CA cert Verisign.pem to your trust store, and it is part of the chain of trust, you must add the CRL Verisign_CRL.pem.
In your particular case, you have added all the certs in /etc/ssl/certs directory using X509_STORE_set_default_paths(store). To get verification to work correctly, you need to add a CRL corresponding to every CA in that directory which you expect to be part of the chain.
A better method would be to narrow down your list of CAs to those for which you have CRLs, and add them individually using X509_STORE_add_cert(store, ca_cert).


Is this ground attached to the wrong water pipe?

Question: I recently noticed that I have ground wires attached to metal water pipes in my home, as shown in the following image.
The area marked A is where the water service enters the home with that blue handled valve being the main shut off.
The area marked B shows two exposed wires (assumed grounds) that are secured to the pipe which is the water heater's outgoing pipe.
Am I incorrect in thinking that the grounds should be secured to the other pipe, the one that brings water service into the home?
Comment: Do you have a ground rod(s) installed outside the foundation?
Comment: Is the hot water pipe not the supply under ground as it exits? If it is in contact with earth for 10' it would have met code when installed. Normally the supply is bonded and the meters and valves were jumpered with copper wire, if this was an early plastic pipe feed but galvanized in the home this may have been the reason it was bonded that way code only required 10' of pipe in contact with earth.
Comment: I originally posted an answer but have deleted due to confusion (and downvotes). Basically, my opinion (debatable...) is that there appear to be non-metal parts in between "A" and "B" and that "A" would (or likely was at one time) a compliant grounding location but that "B" likely is not and that checking for a low resistance between "A" and "B" would show if that is the case. I'll leave the rest to the experts.
Answer: Grounding, bonding, water pipes, and your situation
The old-school way of grounding a house to the cold water pipe performed two functions, not just one:

It grounded the house electrical system to protect it against induced lightning and static charges
And it bonded the house plumbing to the electrical system to allow fuses to blow or breakers to trip if a wire faulted to the plumbing

Nowadays, Code requires us put in a dedicated electrode (ground rods or an Ufer for most folks) to deal with problem 1, and that's what you can do here -- running 6AWG copper from the main panel (optionally through a conduit) to a pair of ground rods spaced 8' apart and driven 8' into the ground will get you a serviceable grounding electrode in most areas.
You will still need to move the existing grounding/bonding wire from the hot pipe to the cold pipe and add a 6AWG jumper from the cold pipe to the hot pipe, though -- this will ensure that your piping is properly bonded to the electrical system so that you don't wind up with a shocking tub spout because the dishwasher shorted out.
Comment: +1 *You will still need to move the existing grounding/bonding wire from the hot pipe to the cold pipe* - that's what I was (essentially) trying to say as part of my now deleted answer.
Answer: Code requires the water pipe to be bonded at the point or within 5' of entering the home. Having additional grounding may have been added for portions that have been replaced with plastic but not completely removed the metallic plumbing. I have seen this on both copper and galvanized pipe. I also know some that add grounding at water heaters but it is not required . for many years /decades water pipe was the only ground many homes had as long as the pipe was in contact with earth for 10' it was legal. Meters , valves had jumpers to main contunity. If this is your main ground it is probably fine but I have found several older homes that had the supply lines replaced with plastic and the home had no ground. Adding 2 ground rods and running a #6 copper to the main service panel would be all that is needed to bring it up to modern code. No update is required by code.
Comment: The catch here is we don't know if this is the ONLY grounding, in which case it sure doesn't look right, or if this is old (replaced with something better) or extra.
Comment: This looks fine to me as code that was in place for many years. No it is not current code but almost no home built 30 years ago would pass current code and no updates would be required. In fact as I posted in my answer all that would be needed to meet modern code is 2 ground rods and #6 copper to the main panel.
Comment: If this is the **only** ground wire, connected at "B", does that really work if there are plastic parts in various connectors so that there isn't continuous metal path from "B" to "A" to earth?
Comment: This may very well NOT be the main ground as this home started out small and many additions over the years.

If I wanted to go the route with two rods, what are the specifics on that.  Can I run a #6 copper from the ground bus in the panel, through a conduit of some kind, 12 - 15 feet from the panel and attach to 2 grounds rods more or less right next to each other?  How far do I need to pound them into the ground?  6'?  8'?
Comment: Since that is on the secondary side of the water heater I don't think that was ever code unless there is 10' of pipe in contact with earth after that point , we don't know if this is in a basement but it is a split level so that could have met code requirements at the time  10' of pipe in concact with earth. Not that much different as today's 2ea 8' ground rods. The single water pipe was standard for many decades so I stand by my statement, just as knob and tube is still legal there is no requirement to upgrade, could it create a better ground system? Possibly but not always.


Plumber got his sewer jetter hose stuck. Whose fault is it?

Question: On Wednesday, a service plumber came to my house to jet the drain for my kitchen sink.  He came around 9 a.m. and by 9:30 had pushed his hose beyond the clog.  Then he spent 3 hours trying to get his hose out.  He went to lunch and came back with a helper (his boss, I think) and they spent another 3 hours trying to get the hose out.  They finally left, leaving my kitchen drain open and the water off.  They said they couldn't be back Thursday, but would be back Friday.  Meanwhile, I was supposed to have the septic tank pumped so that they could look into it and see if the hose was in there.  (They also wanted to cut 4-inch pipes in the basement to see if the hose had gone other places.)
Thursday, I paid a guy $750 to pump out my septic.  Then I had another guy, recommended by the septic pumper, to do more work.  He had to cut a hole in the top of the (cement, 60-year-old) tank. $450.  The hose had somehow wrapped and knotted itself around a pipe.  See pic.  The last guy and I were able to untangle the hose and I pulled it back about 6 feet into my kitchen.
Friday, the two original buffoons showed up, finished pulling the hose out, cleaned up, put my trap back on and now the kitchen sink is functional.  Now comes the bill.  They want to charge me for the 9 man-hours these two spent failing to get their hose out of my drain.  I am not so inclined.   I spent $1200 already getting their hose out for them.  They ought to be paying me.
If there had been some problem with my line, like the pipe was crushed or broken, then maybe it could be my fault.  But in this case, the pipe is fine and the problem was that he ran the hose way too far into my septic tank, where it jetted crazily around and tied itself in knots.
You can see the hose wrapped around the horizontal PVC at the upper left in the pic.  I feel like I should bill them for part of he $1200.  The tank was full and needed pumping, so I can eat the $750.  But the $450 was done strictly for them to get their hose back.  Then, it seems bizarre to me, that they'd try to charge me $2000 for their screw up and their failure to correct the screw up.
So my question is:  Who should pay and what?  Are my perceptions correct or am I all wet?
Comment: They pay.  They are supposed to be trained on how to use their tools.  They goof up and/or damage/cause more work, it is their dime.  Should only pay for the first half hour or estimated job cost.  Plumber really had to work to do that.
Comment: Most places have governing bodies/associations that license plumbers/electricians/contractors, so people don't get burn by Joe down the street.  Most of them need to leave your house/property as it was or better.  Most TV stations have a consumer unit to help people against corporations/licensed contractors/businesses.  They might tell one person to (something) off, but they bend over backwards to help when their name is on TV
Comment: You paid $750 to have your septic tank pumped? Around here (MN, USA) it's usually around $200 or so. Seems quite extreme even considering regional differences.
Comment: Yes you are correct, and they're desperate.  Unfortunately the building boom and the Great Resignation have combined to create a great shortage of competent tradesmen - the good ones are neck deep in large contracts and you and I are left to scrape the bottom of the barrel.  People who should not be businessmen or perhaps even plumbers.
Comment: You definitely should not pay them one dime.   Request reimbursement for the expenses you incurred....in a reasonable letter like your post (without the word buffoons).   Minus, of course, the original cost of the job. Any money you give them would be money down the drain.
Comment: Paying even in part can be used against you as taking responsibility for the entire bill. Pay nothing until the argument is resolved.
Comment: Despite the reality TV popularity of this question, it's off topic here. It's a legal/contractual matter. Voting to close.
Comment: What really gets me is that all this was over a *hose*.  Even the septic pumping costs seem more expensive than just replacing the hose and augering out the portion of hose still in the pipes.  These guys don't even know how to cut their losses.
Comment: @PhilippNagel  Agreed with your comment about cost of pumping. $750 is about double what it should be.
Comment: Was the cost to pump out the tank increased by an 'emergency' appointment?
Comment: @MichaelRichardson Yes.  I was "lucky" that the company had a guy working about 4 blocks away, so he came an hour after calling.  Worse:  I'm going to hook up to city sewer next week and I'm have the septic tank taken out of service.  So I'll have to pump it again in a few days.
Comment: You do not owe them a single dime!! In fact, you should present them a bill for $1,200. That is incomprehensible incompetence on their part. By the way, that seems to be a regular snake, not a jetter.
Answer: WOW!  So you got a plumber to unclog a drain, he screwed up and got his hose stuck, then wanted to cut pipes to find it, then wanted you to pump the septic tank to see if they could find it there. WOW, just WOW.   And then you had to get involved with the filth of a septic tank.  Geeze. I dk how much you've already paid, but if you haven't paid the alleged "plumbers", I wouldn't pay them a G D dime and if they didn't like it, take me to small claims court. If you're a nice guy, you might compromise by offering to pay for the initial service call, but not the followup work to retrieve their precious hose.   But if it were me, I'd tell them to pound sand.
Answer: Unless they roll over when you tell them to pound sand (they should!) I'd try to get a quick consult with someone versed in the laws of your area. Maybe get a strongly worded letter from them on official looking letterhead.
The problem with not paying your bill is that someone could potentially slap a lien on your property, which would cause all manner of bother.
Comment: Good  call.  A sternly worded letter from an atty can go a long way to getting this resolved.   To reduce legal fees, in the past when I had a conflict, I drafted the letter with all the details, gave it to my atty for final editing and printing on his letterhead. Works well.  I even had to do that with the IRS one time.
Answer: I do not think there are any lawyers here.
But you have the evidence (the photo)
IMHO: With it you can ask the plumber to pay for repairs and getting it out.
Unless it is some cowboy, he has a license and has to be insured.
Or get ready for this in your state.
How to File a Complaint with the Contractors State Licensing Board
He would not risk losing his licence and will probably have his insurance pay.
Comment: Even where not required by law, any *reputable* plumber will be insured (perhaps even bonded).  After all, if they flood your house and ruin your floors, they don't want to pay for that out of pocket. If they're *not* insured, make a big stink about it and they'll likely back off for fear you'll sue for the costs involved on your end.
Answer: Don't communicate with them except over email. They are liable for the amount you had to spend to rescue their equipment and get your drain working again. Tell them if they don't pay up your expenses, you will file a complaint with the BBB and take them to small claims court.
Do not send them a dime. Keep your communication cordial but not friendly -- this is business and you will get screwed.
Without justice, these bufoons will keep on doing the same stupid S4¡t to other unsuspecting homeowners.
Comment: Couldn't agree more!


How to write Real and Imaginary matrix notation for $ \mathbf C=\begin{bmatrix}(x_1+jy_1) \ (x_2+jy_2) \\ (x_3+jy_3) \ (x_4+jy_4) \end{bmatrix}$?

Question: I am reading this communication article:
I am confused as to how to write these notation to prove the properties, for example if I take A to be a $2\times2$ matrix like:
$$ \mathbf C=\begin{bmatrix}(x_1+jy_1) \ (x_2+jy_2) \\
   (x_3+jy_3) \ (x_4+jy_4) \end{bmatrix}$$ now how to write this in the real and imaginary matrix form. I tried to do by adding all real and imaginary parts at the given locations respectively.But that doesn't prove the properties.
Answer: At first glance, if $z \in \mathbb{C}^n$ then $\hat{z} \in \mathbb{R}^{2n}$. Similarly, $A \in \mathbb{C}^{n \times m}$ then $\hat{A} \in \mathbb{R}^{2n \times 2m}$ since $\Re(A), \Im(A)$ will be a $n \times m$ matrix.
So for your $\mathbf{C}$:
$$\hat{\mathbf{C}} = \left [ \begin{array}{rr} \left ( \begin{array}{rr} x_1 & x_2 \\ x_3 & x_4 \end{array} \right )  & \left ( \begin{array}{rr} -y_1 & -y_2 \\ -y_3 & -y_4 \end{array} \right )  \\ \left ( \begin{array}{rr} y_1 & y_2 \\ y_3 & y_4 \end{array} \right )  & \left ( \begin{array}{rr} x_1 & x_2 \\ x_3 & x_4 \end{array} \right )     \end{array} \right ]$$


Reset values of a select box, separate button or inside select?

Question: I have a filter form with two select boxes to filter results. I've a red button to reset search and view all results, but I'm not sure if I should add "All" at the beginning of each select box?
What are your opinions and why?
Answer: If i understand issue correctly you want to select multiple states to filter by. I would probably approach it like this, have a reset button within a dropdown to clear all selected tick boxes:
http://z2l32f.axshare.com/#g=1&p=home&c=1
and sorry for ghetto prototype.


Premature optimization in Java: when to use "x = foo.getX()" vs simply "foo.getX()"

Question: When I find myself calling the same getter method multiple times, should this be considered a problem?  Is it better to [always] assign to a local variable and call only once?
I'm sure the answer of course is "it depends".
I'm more concerned about the simpler case where the getter is simply a "pass-along-the-value-of-a-private-variable" type method.  i.e. there's no expensive computation involved, no database connections being consumed, etc.
My question of "is it better" pertains to both code readability (style) and also performance.  i.e. is it that much of a performance hit to have:
SomeMethod1(a, b, foo.getX(), c);
SomeMethod2(b, foo.getX(), c);
SomeMethod3(foo.getX());

vs:
X x = foo.getX();
SomeMethod1(a, b, x, c);
SomeMethod2(b, x, c);
SomeMethod3(x);

I realize this question is a bit nit-picky and gray.  But I just realized, I have no consistent way of evaluating these trade-offs, at all.  Am fishing for some criteria that are more than just completely whimsical.
Thanks.
Comment: Is foo immutable (at least through the lifetime of x)? If not, then they are not the same.  It is not enough that getX has no side effects.  If SomeMethod1 invokes foo.setX then they are not the same.

If they are not the same, then rather than worry about readability or performance, choose the correct one.
Comment: This is a scenario where there's only one thread that updates foo I presume?
Comment: +1 for the use of whimsical in a question
Answer: The choice shouldn't really be about performance hit but about code readability.
When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
And it's really better to read:
String username = user.getName();
SomeMethod1(a, b, username, c);
SomeMethod2(b, username, c);
SomeMethod3(username);

than
SomeMethod1(a, b, user.getName(), c);
SomeMethod2(b, user.getName(), c);
SomeMethod3(user.getName());

Comment: IMO, `user.getName()` is sometimes easier to read, because you don't have to search (and scroll up) to the position where it's been set. You'd probably name the variable `username` too, if it were set via `request.getUsername()` - so which one is it?
Comment: @chris_l like I said each variable name has its own meaning in the context where it's used. And yes, I would probably name `request.getUsername()` username too. And if I had to use both, there would be a reason, like a new username and an old one. newUsername, oldUsername could fit. It's all about the context.
Comment: @Colin: That's true (and BTW, I'd do the same), but when you're scrolled down to the end of the method, you don't see the context immediately. So when you just see `username`, you don't know exactly what it is at first.
Comment: Java method names should start with lowercase.
Comment: I just copy/pasted them from the question.
Comment: @chris_l It's pretty much guaranteed that *user* was set before *username* was, so you'd have to scroll up even further to understand the context that *user.getName()* is being invoked in. As such, the definition of *username* is going to be closer to the code that uses it, then that of *user*.
Comment: @Vladislav: We're back to "it depends", because it really does (and that's why I said that it's "sometimes" easier). Often, you don't have to *understand* the context. All you want, is to understand a few lines of code very quickly (say 10 seconds). After that, you can scroll up to reassure, that you've understood the context. The thing that's really hard is, when you have to scroll up and down again and again (or worse: waste short-time memory to remember multiple variable names), before you even have a feeling what these few lines do.
Answer: For plain getters - those that just returns a value - HotSpot inlines it in the calling code, so it will be as fast as it can be.
I, however, have a principle about keeping a statement on a single line, which very often results in expressions like "foo.getBar()" being too long to fit.  Then it is more readable - to me - to extract it to a local variable ("Bar bar = foo.getBar()").
Answer: They could be 2 different things.
If GetX is non-deterministic then the 1st one will give different results than the 2nd
Personally, I'd use the 2nd one. It's more obvious and less unnecessarily verbose.
Comment: The word you're looking for is "idempotent". `x+=2; return x;` is completely deterministic, but will give different results when called multiple times.
Comment: @Michael Madsen: true. sloppy thinking on my part
Answer: I use the second style if it makes my code more readable or if I have to use the assigned value again. I never consider performance (on trivial things) unless I have to.
Comment: Plus it may be easier to set a breakpoint to X x = foo.getX(); to examine the value returned.
Answer: That depends on what getX() actually does. Consider this class:
public class Foo {
    private X x;

    public X getX() { return x; }
}

In this case, when you make a call to foo.getX(), JVM will optimize it all the way down to foo.x (as in direct reference to foo's private field, basically a memory pointer). However, if the class looks like this:
public class Foo {
    private X x;

    public X getX() { return cleanUpValue(x); }

    private X cleanUpValue(X x) {
        /* some modifications/sanitization to x such as null safety checks */
    }
}

the JVM can't actually inline it as efficiently anymore since by Foo's constructional contract, it has to sanitize x before handing it out.
To summarize, if getX() doesn't really do anything beyond returning a field, then there's no difference after initial optimization runs to the bytecode in whether you call the method just once or multiple times.
Comment: If I have understood it correctly, HotSpot can inline the getX() even if it calls more code.  The decision is based on the size of the method - not what it actually does.
Comment: I seem to remember reading in some stuff on jruby that Hotspot currently inlines up to 9 nested calls
Comment: The JVM should have no problem inline getX and cleanUpValue.
Comment: Follow this method, and you're programming against the underlying implementation, while you _should_ be programming against the interface.
Comment: What if Foo has a public setX method?  (Especially if the application is multi-threaded.)  Even if getX just returns a field, the field itself might change and calling the method multiple times may return different values.
Comment: @emory: Being essentially just a memory pointer eventually after all the JIT runs and optimization, that doesn't matter - assuming of course that there's no synchronization between the methods or explicit returnal of a copy in the accessor method (`getX()`).
Answer: Most of the time I would use getX if it was only once, and create a var for it for all other cases. Often just to save typing.
With regards to performance, the compiler would probably be able to optimize away most of the overhead, but the possibility of side-effects could force the compiler into more work when doing multiple method-calls.
Answer: I generally store it locally if:

I'm will use it in a loop and I don't want or expect the value to change during the loop.
I'm about to use it in a long line of code or the function & parameters are very long.
I want to rename the variable to better correspond to the task at hand.
Testing indicates a significant performance boost.

Otherwise I like the ability to get current values and lower level of abstraction of method calls.
Answer: Two things have to be considered:

Does the call to getX() have any side effects? Following established coding patterns, a getter should not alter the object on which it is called, the in most cases, there is no side effect. Therefore, it is semantically equivalent to call the getter once and store the value locally vs. calling the getter multiple times. (This concept is called idempotency - it does not matter whether you call a method once or multiple times; the effect on the data is exactly the same.)
If the getter has no side effect, the compiler can safely remove subsequent calls to the getter and create the temporary local storage on its own - thus, the code remains ultra-readable and you have all the speed advantage from calling the getter only once. This is all the more important if the getter does not simply return a value but has to fetch/compute the value or runs some validations.

Assuming your getter does not change the object on which it operates it is probably more readable to have multiple calls to getX() - and thanks to the compiler you do not have to trade performance for readability and maintainability.


Write specific parts from string into another string

Question: I'm currently writing a script to monitor hosts via a python script and ping. The ouput of ping is saved into the variable response which is perfectly working. The content of response variable looks like this:

Now I would like to save the marked values into the variables min, avg and max, but I have no idea how to do this?
Comment: it would be helpful for those looking at your question to see an embedded image (rather than a link). Better yet you could include the text log text so that it can be searched for.
Answer: You can process the string like this:

split it by lines x = response.splitlines()
get the last line x = x[-1]
get the substring that contains the values x = x.split(" = ")[1]
get the individual min, max, avg values min, avg, max = x.split("/")[:3] (this way they will be stored as strings)
to save them as numbers, you can do this instead: min, avg, max = map(float, x.split("/")[:3])


PHP: Compare float value from MSQL database with variable

Question: I have a table in my database called users with one column called mon of type Float. I want to compare the column with an input from a texbox assigned to a variable.
$amt_chk = mysqli_query($conn, "SELECT mon FROM users WHERE id = '$user_id'");

       if (isset($_POST['mon']) > ($amt_chk)) {

            $results="

                    ×
                    Not enough Funds!

";
       }

Comment: in sql query `"SELECT mon FROM users WHERE id = '$user_id' and mon = '$_POST['mon']'"`..... this is a sample query. i suggest use PDO with bind parameters
Comment: what sort of comparison are you trying to perform, greater than, equal to, less than, not equal to and you haven't stated your problem
Comment: can you elaborate more on this ? What exactly problem you want to solve?
Comment: Sorry if i wasn't clear earlier. It's should work like a payment system. The code i posted is supposed to check the database for how much money (mon) is left in it and warn the user when he/she tries to send more than he/she has.
Answer: I would try floating both values to make sure you are comparing 2 floats:
if (isset($_POST['mon'])) :
    $amt_chk = mysqli_query($conn, "SELECT mon FROM users WHERE id = '$user_id'");
    $mon = (float) $_POST['mon'];
    $amt_float = (float) $amt_chk;
    if ($mon > $amt_float) :
        // do your thing
    endif;
endif;

Answer: If you intend to compare float with character data, you can use CAST or CONCAT. It is not advisable to typecast your MySQL result, and you must think about the types of data you are using and storing. A better approach would be to typecast the input data (in $user_id), as it doesn't mingle with the database data.
However, you may use cast() as bellow:
 SELECT CAST(mon AS CHAR) FROM users WHERE id = `$user_id`

The cast function typecasts the result into type you supply. From the MySQL documentation:

Cast functions and operators enable conversion of values from one data type to another.

https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html
You can also use CONCAT as it expects string arguments, and implicitly converts float to char.
SELECT CONCAT(mon) FROM users WHERE id = `$user_id`

More at the official documentation: https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html


jQuery.post() in Wordpress

Question: I am currently writing a chatbox plugin for Wordpress.
This plugin uses a jQuery.post() method to send data to a php file in order to write the output to an html file, which in turn will be loaded to the chat window using jQuery.
Inside the php file I use to write the chat log to an html file I need to use Wordpress API functions, but this php file is not included by Wordpress, and therefore has no access to the Wordpress API.
Is there a way to send this chat data to a php file that is included by Wordpress so I can use the Wordpress API? What would be the best way to tackle this problem?
Comment: WordPress Codex is a great place: http://codex.wordpress.org/Writing_a_Plugin
Comment: @valentinas I have spent the past 2 hours delving through the codex trying to find an answer to my question. I did not find it so I figured I'd try here.
Answer: You can use wp_localize_script for sending ajax url in a JavaScript object to the pages:
function my_localized_vars() {
    return array(
      'site_url' => get_bloginfo('url'),
      'ajax_url' => admin_url('admin-ajax.php')
    );
}
wp_localize_script('needle', 'object_name', my_localized_vars());

Then you can add an action and handle the request.
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
And for getting the url using JavaScript you can code:
var url = object_name.ajax_url;

Comment: This is a much better approach. My original answer of simply including the wp-blog-header.php file is a pretty lazy method.
Comment: @maiorano84 I usually do not use wordpress, in my last project which was a wordpress theme I found that this way is the standard way for using ajax in wordpress, it worked for me.
Comment: I was complimenting you. This was a good answer, and is the correct method of implementing AJAX Requests.
Answer: Instead of having a separate PHP file, wrap it in WordPress plugin. WordPress Codex will tell you how to write a plugin and how to wire it up to handle your ajax request.
Once you have it working as a  plugin you will be able to access all WordPress APIs.

jQuery.post() in Wordpress


Does .NET Embedding work on Visual Studio on Windows or only VS on mac?

Question: I have an Xamarin ios class library that I want to .Net Embedding to 'embed' for use by an Xcode Objective-C app
Answer: from the docs
Requirements

To use .NET Embedding with Objective-C, you'll need a Mac running:
<code>macOS 10.12 (Sierra) or later
Xcode 8.3.2 or later
Mono 5.0
</code>
You can install Visual Studio for Mac to edit and compile your C#
  code.

Note

Earlier versions of macOS, Xcode, and Mono might work, but are
  untested and unsupported
      Code generation can be done on Windows, but it is only possible to compile it on a Mac computer where Xcode is installed
Comment: That didn't answer the question I had in mind.  I will clarify and rephrase it:  Does .NET Embedding work on Visual Studio on Windows or only VS on mac?  I would prefer on Windows, since that where the rest of the product code is.
Comment: The consensus I see online is that remote control by Visual Studio on Windows of MacOS  to do .Net Embedding doesn't work.
Answer: Yes, embeddinator 4000 works in Windows 10 with Visual Studio 2019.
I have generated .aar for Android + Java.
However, there are many limitations of the generated aar.
e.g. functions that use non-primitive types get ignored and you do not have those in generated aar etc.


Prove or disprove: $f \circ g$ is onto $\Bbb R$ then g is onto $\Bbb R$.

Question: Prove or disprove: $f \circ g$ is onto $\Bbb R$ then g is onto $\Bbb R$.
I am tending towards disproving it, but I have no idea how, I saw here a few examples with discrete groups and the integers, but I have no idea.
Can you please help?
Answer: Hint
$f:(0,\infty)\to\mathbb{R},f(x)=\ln x$
$g:\mathbb{R}\to(0,\infty),g(x)=e^x$


What use is Cutting Fluid?

Question: I've noticed in the Chemistry Workshop I have the ability to craft Cutting Fluid:

The wiki entry is currently a little vague on details, only explaining that it can be broken down into some base parts again. So what is the use of Cutting Fluid?
Answer: The only use of Cutting Fluid I've been able to observe so far, is that it can be scrapped for Oil, which is one of the most used components you'll ever find in the wastelands, along with adhesive.
For adhesive, you have Vegetable Starch, which can be cooked in any Cooking Station.
Comment: Fair enough. I just figured it must've been used in a recipe or something. Seems a little backward that it's only use it to craft it then de-craft it back into oil haha. Oh well.
Comment: @Robotnik: Could also be it will be used more in new DLC.
Comment: @Robotnik Oil is not an ingredient in making it. Steel and purified water are extremely common (assuming you have purifiers making water), and bone and acid are not too hard to find. It's not quite as convenient as Vegetable Starch, but it's a good way to get extra oil.
Comment: @DCShannon - I realise that, my point was if it's only use is to be made into oil, why not just make the recipe output 'oil'? Why 'Cutting Fluid' specifically?
Comment: @Robotnik Ah, okay, I see what you're saying. I'd imagine just for flavor, although if the weight or value of the cutting fluid is significantly different than the oil you can get from it, that might be a factor as well.

What use is Cutting Fluid?


Java Getting each int in Output of Array to have commas?

Question: I have the output of my array that looks like 123611 (example numbers).
I am trying to get the output to be nicely formatted 1,2,3,6,11
I have not been around Java too much and I cannot remember how to go about doing this. Thanks!!
Here is my code:
int array3[] = { 1, 2, 3, 6, 11 };

for (int i = 0; i < array3.length; i++)
    System.out.print(array3[i]);

Answer: You can use Streams available from Java 8,
Note here I'm using the integer wrapper class Integer, not the primitive type int
Integer array3[] = { 1, 2, 3, 6, 11 };

System.out.println(Stream.of(array3)
 .collect(Collectors.mapping(String::valueOf, Collectors.joining(",")))
);

As @Jelaby mentioned, it's better to use map(), which converts each Integer to String first, then join it
Integer array3[] = { 1, 2, 3, 6, 11 };

System.out.println(Stream.of(array3)
                         .map(String::valueOf)
                         .collect( Collectors.joining(",")));

Comment: Good idea. You can get an `IntStream`
from an `int` array with `Arrays.stream()`, and I would say that using `map()` or `mapToObj()` to transform the stream is more idiomatic than using a mapping collector. For example:  `Arrays.stream(array3).mapToObj(String::valueOf).collect(Collectors.joining(","))` (if using `Integer` instead of `int` you'd use `map` instead of `mapToObj`).
Comment: Oh cool, I didn't know about mapToObj method, Thank you
Answer: You simply need to print them as well =)
for(int i=0; i< array3.length; i++)
    System.out.print(array3[i] + (i <array3.length-1 ? ",":"") );

This is will leave the trailing comma off, and print one between each entry
Answer: Here is an easy way to do this:
import java.util.Arrays;

public class SO {
  public static void main(String[] args){
    int[] a = {1,2,3,6,11};
    System.out.println(Arrays.toString(a));
  }
}

This outputs:
[1, 2, 3, 6, 11]

Or you can strip out the chars you don't want like this:
System.out.println(Arrays.toString(a).replaceAll("\\[|\\]|\\s", ""));

Which outputs:
1,2,3,6,11

Answer: You can print , after each element except last one using this loop
for (int i = 0; i < array3.length - 1; i++)
    System.out.print(array3[i] + ", ");

and later print last element of array without , after it.
System.out.println(array3[array3.length - 1]);

Or just use
String arrStr = Arrays.toString(array3);//will produce "[1, 2, 3, 6, 11]"
System.out.println(arrStr);
//if you want to remove [...] brackets you can substring them with
System.out.println(arrStr.substring(1,arrStr.length()-1));

Answer: I would bet this is what you're looking for:
Arrays.toString(array3);

The output is:
[1, 2, 3, 6, 11]

If you don't want the square brackets, just strip them.
Answer: int array3[] = { 1, 2, 3, 6, 11 };
String s ="";
for (int i = 0; i < array3.length-1; i++){
    s +=array3[i]+", ";
}
s +=array3[array3.length-1];
System.out.print(s);

is essentially the same as Array.toString() but without [],
and doesn't use if statment or ternary (?:) in each iteration to check if it's the last element.In genaral, building a String first, is a better practice, because its faster and you get a string to process, System.out and its gone.
Comment: Use StringBuilder like stringBuilder.append(), because String is immutable every time it creates