Save states of child rows with checkboxes in inflated expandablelistview

Question: I have a working expandablelistview in my Android project, where each child contains an ImageView, a TextView, an EditText, and a Checkbox:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="#CCCCCC"
android:orientation="horizontal" >

<ImageView
    android:id="@+id/imgname"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="True"
    android:contentDescription="@+id/imgdesc"
    android:paddingLeft="1dp"
    android:scaleType="fitCenter"
    android:src="@drawable/logo_grey" />

<TableLayout
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_toLeftOf="@+id/check1"
    android:layout_toRightOf="@+id/imgname"
    android:stretchColumns="0" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/desc"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:textSize="13dp"
            android:background="#CCCCCC"
            android:textColor="#777777"
            android:textStyle="bold" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="fill_horizontal" >

        <EditText
            android:id="@+id/content"
            style="textViewStyle"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:fadingEdge="none"
            android:focusable="true"
            android:hint="@+id/contenthint"
            android:isScrollContainer="true"
            android:minWidth="150dp"
            android:singleLine="false"
            android:textSize="10dp"
            android:textStyle="italic" >
        </EditText>
    </TableRow>
</TableLayout>

<CheckBox
    android:id="@+id/check1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:focusable="false"
    android:gravity="right" />
 </RelativeLayout>

For the purposes of writing to my SQLite database, I want to create a list which, for each child where the checkbox's value is true, contains the text from the TextView desc and the text from the EditText content, perhaps as an array of value pairs. The operation would be triggered by the user via a Button on the ExpandableListActivity. But I'm not sure how to identify the values of the widgets after inflating the view. I'd appreciate a little heads up, I've not been able to find a good answer online!
Answer: I'm not exactly a professional myself, but i'll give it my best shot. first it'd help if you had something to keep track of checkbox states in your expandablelistview. If you don't already have one. Here's what i use, which i adapted from Android ExpandableListView with Checkbox, Controlling checked state:
//  set checkbox states
ArrayList<ArrayList<Integer>> check_states = new ArrayList<ArrayList<Integer>>(children.length);
public void setChildrenAndValues() {
    for(int i = 0; i < children.length; i++) {
        ArrayList<Integer> tmp = new ArrayList<Integer>(children[i].length);
        for(int j = 0; j < children[i].length; j++) {
            tmp.add(1);
        }
        check_states.add(tmp);
    }
}

then in get childview:
    childcb.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (childcb.isChecked()) {
                check_states.get(groupPosition).set(childPosition, 1);
            }else{ check_states.get(groupPosition).set(childPosition, 0);
            }
        }
    });

Thus following along the same vein, to save your content for your database, you might try this on some button's void onclick method:
    if (check_states.get(groupPosition).get(childPosition) == 1) {
        desc_content4db.put(desc_tv.getText().toString(), content_et.getText().toString());
    }else{
        // placeholder code, w.e. you want
    }

and this else where:
HashMap<String,String> desc_content4db = new HashMap<String, String>();

I have no idea if desc_tv/content_et.getText().toString() would work like you want it to. what's likely and seemingly more clumsy is that you might already need to have an ArrayList of Hashmaps of all the content ready - and then copy over all the stuff that you want to put in the database depending on if it corresponds to the checkbox at which ever position checked. It doesn't sound pretty but it might work.
More ideal i would guess if you could step through the check_states list and depending on it it's 1 or 0, copy the edit_text and text_view at that id or position. sadly that's above my level right now. if you can do that, then more power to you.


Trying to POST to database with Simple Form and Rails

Question: Trying to use the simple-form gem with Rails to POST to my database (postgresql). I have followed a few videos but I'm not entirely sure what's going wrong. My form worked before I made the method to post (obviously didn't do anything).
Here's the error I get.

Straight away I was thinking a routes issue. But I've had a crack for a while and can't fix it.
undefined method `client_assets_path' for #<ActionView::Base:0x0000000000ccd8>
Did you mean?  clients_new_path

Here's my repo if it helps with the models.
Here's my form:
<%= simple_form_for @clients do |f| %>

            <%# Home %>
            <%= f.input :ppor %>

            <%= f.button :submit %>

    <% end %

Here's my method in Client Controller:
class ClientController < ApplicationController
  def index
    @clients = ClientAsset.all
  end

  def new
    @clients = ClientAsset.new
  end

  def create
    @clients = ClientAsset.new(client_asset_params)
    if @clients.save
      redirect_to @clients
    else
      render :new
    end
  end

  private
  def client_asset_params
    params.require(:id).permit(:ppor)
  end
end

and here's my routes:
Rails.application.routes.draw do

  devise_for :admins
  root to: "planner#index"

  get "/index", to: "planner#index", as: :index

  get "/howto", to: "planner#howto", as: :howto

  get "/products", to: "planner#products", as: :products

  get "/planners", to: "planner#planners", as: :planners

  get "/admins/sign_in", to: "admin#sign_in", as: :sign_in

  get "/admins/sign_up", to: "admin#sign_up", as: :sign_up

  devise_scope :admin do
    get "/admins/sign_out" => "devise/sessions#destroy"
  end

  get "/admins/password/edit", to: "devise/password#edit", as: :edit

  get "/dashboard", to: "client#dashboard", as: :dashboard

  get "clients/new", to: "client#new"

end

Answer: Your instinct that you have a routing issue is correct.
The standard/default behaviour on a form like yours is to POST to the specified resource's 'index path' (/clients in your case). However, you have not defined a POST route.
The reason you get an undefined method error instead of a 'no route for' error is that simple_form_for assumes that your route has a 'named path helper' of the form 'class_name_path' that will give it the appropriate destination URI. Since you don't have a route defined, simple_form doesn't find the associated method and you get a missing method error.
So, at a minimum you would need:
get "/clients/new", to: "client#new"
post "/clients", to: "client#create", as: 'client_assets'

The as: option is necessary because by default Rails creates the helper using the resource path name (clients) but simple_form_for assumes the that resource path is derived from the model name (client_assets).
As an aside, Rails works best and easiest when you stick to convention. If you are new to Rails, using things such as resourceful routing and naming conventions for models and controllers (e.g., ClientAsset (model) ClientAssetsController (controller)) can make your experience with Rails quite a bit smoother.
Answer: You have a few things going on that are probably causing issues.  You're missing a route to your create method in your controller.  The HTTP verb should be POST. But this will probably not fix your problem. I will try and help point you in the right direction.
There is something I noticed in your routes file and I want to try and help steer you onto the restful path.  Most rails developers will shy away from creating routes like:
get "clients/new", to: "client#new"
Rails is amazing and handles this for you.  I would remove this and add this to your routes file:
resource :clients
This will automagically provide all the needed routes.  Index, show, new, create and destroy.
Once you add that to your routes file, run this in your shell (from the project directory) rails routes
You should notice you have all the routes I mentioned before.
Second thing I wanted to point out is your controller.  The class name for controllers are pluralized.  Model names are singular.
class ClientController < ApplicationController
a normal rails convention would be:
class ClientsController < ApplicationController
The third thing I would like to point out is this:
def new
  @clients = ClientAsset.new
end

Looking at your repo I can tell you this isn't right.  You shouldn't be instantiating a ClientAsset instance in a Client controller.
In a Client Controller, I would expect to see something like:
def new
  @client = Client.new
end

Using @client as you have in your form would never work, it will be looking for a completely different route and controller.
TBH, this is a lot to take in.  If you want, I can send up a PR in your repo to help get you back on track if you are interested.


Create date object to use in Calendar Plugin in Ionic 2

Question: I am using the Calendar Plugin for Ionic 2 (http://ionicframework.com/docs/v2/native/calendar/).
To create a new event I use:
createEvent(title, location, notes, startDate, endDate)

Where startDate is of type Date.
I have a string with the startdate:
date = '2017-02-02 15:36:00'

How can I convert this to use as startDate?
I tried:
var startDate = Date.parse(date);

But Sublime tells me that this is not the type it is expecting.
My complete code looks like this:
var startDate = Date.parse('2017-01-01 12:00:00');
Calendar.createEvent('Name', '', '', startDate, startDate).then(
                  (msg) => { },
                  (err) => { }
                );

The error I get:

Typescript Error Argument of type 'number' is not assignable to
  parameter of type 'Date'.
Comment: do u get any errors using the above approach?
Answer: The error you are getting is because Date.parse returns a number and not a Date.
I have accomplished creating a Calendar event by using Moment.
You can install this package by using the command npm install moment --save and npm install @types/moment --save-dev and importing it in your class with this import: import * as moment from 'moment';.
The following code can be used to create your Date object:
let startDate = moment('2017-02-02 15:36:00').toDate();
Try making the event with that Date, worked for me :)


debug script that are returned as part of response on chrome

Question: I have a page that load html section via ajax call. The response contains html as well as javascript file.
Now i am trying to find a way to put debug point on that javascript file.
On IE, I can simply search some javascript function that is present on that file on debugger tab and it will take me to script block containing javascript file  and i can set debug points there.
But i am not sure how can i achieve this using chrome.
UPDATE
I am returning thymeleaf fragments using ajax which include javascript file
<!DOCTYPE html>

    //my html goes here

Comment: Ajax will not execute returned content. Can you briefly describe how you execute the Javascript, please?
Comment: I'm not familiar with Thymeleaf, but from that pseudocode and the docs I [assume that `/js/test.js` would be loaded as a separate request](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#flexible-layouts-beyond-mere-fragment-insertion). If this is true, is the request made? You should see it at least in the Network panel.
Comment: yes i can see on network panel but i can't put debug point on that `js` file.
Comment: Ensure its served with 200 OK. Ensure the script is executed. Put an `alert("Hello")` into `test.js`. It should at least pop up. In the network panel the type for `test.js` shall be "script". Do you have an ad blocker running? What Chrome version is it? Try adding the script tag (without the `th:` namespace) to the index.html directly to narrow down issues with the script insertion rather than with the script itself.
Comment: i am not sure if you understand my question or not. Everything is working fine. all script are running fine. All i want is to debug `test.js` file using chrome.
Answer: Firebug comes in with its JavaScript debugger. I'm used to using a debugger in every language I deal with, so using Firebug is a no brainer. Since it supports breakpoints, stopping execution and inspecting local variables and the rest of the scope generally beats alerts and console.logs for me.
For more details please check this link
http://beerpla.net/2009/12/17/how-to-make-firebugs-javascript-debugger-break-inside-dynamic-javascript-using-the-debugger-keyword-ie-chrome-too/
Comment: i am looking for how to do with chrome developer tools.


Can I remove one side frame of the cabinets above the refrigerator?

Question: The space for the refrigerator is more narrow than I'd like. Both sides have a wall/panel extending from the cabinets above. The space is 33"w x 72"h. The new fridge would likely by 36"w x 70"h (covering a light switch a little). Picture here:

I've basically only come up with one solution:
Saw off left side just below cabinet. In this case, what kind of support would I need for the cabinets above?
It would be great if I could preserve the cabinet/housing as is, and simply move the left wall over a little bit, but that doesn't seem trivial.
Thanks!
Answer: Long and boring, but the proper way...
You will have to see how the cabinet is fastened. If it is screwed on the sides to the "walls" of the housing then you need to remove it before removing the "walls"
If the cabinet is screwed on the back- to the actual wall (even id it has side screws) then empty it out completely and you should be able to safely detach the wooden "wall" you want to move.
In this case you will need pad out the extra space in-between the cupboard and wooden wall you are moving with another piece of wood that will fit. You need 3" inches.
A nice way would be to pad both sides of the cabinet with 2" thick pieces of wood to give you an extra 4". Painting it white will make it look like it should be there.
Then you need to screw from inside the right side of the cabinet through the padded wood into the wood of the existing cupboard -- but not so the screw comes out the other side. You need to measure precisely the length. screw in each corner and centre. Then put the left wall back in and screw from the left side inside the cupboard the same again.
You obviously have a problem with the light switch. IF you got enough space inside you could make a square opening in the side "wall" that you are moving and put the switch in there. The wires will be behind the fridge any way - just insulate them with some flex plastic pipe for wires.
The light switch will have to get moved to something similar like this. You can mount it flush /countersink it into the wall you are moving. The biggest problem is cutting out the hole to the correct size. You can go larger but you cant shrink. So be careful and try to fit it several times.

It is not an easy undertaking- but I would not do it any other way.
If you cant be bothered ...
If you cant be bothered doing it the right way. Then put several wall bolts in the back of the cupboard in the corners and centres. Then remove the left "wall" and put your fridge in.
But this will NOT work if you have a drywall behind the fridge.
Comment: Point #1 is probably the way to do it.  You can probably buy a 3" filler board from the cabinet supplier.  My only issue is with the light switch.  It will need to be moved, or access will need to be cut out of the side board, which will look a bit messy.
Comment: I'm with you on way #1, but not #2. If helen can find studs, screwing through horizontal framing braces in the cabinet into the studs should work. If not, any "bolting technique requires direct access to the wall and even then, only a few types are adequate to hold a cabinet. Illustrated is an expansion anchor in concrete which could work (if you got access), but in drywall, etc., it would be a bad idea.
Comment: Oh yea. Sorry I did not realise there was dry wall behind the cabinet. I did mine recently, also got new fridge. We have brick so I could use heavy duty bolts. For drywall you will  to come up with something else.
Comment: Ye- The light switch will need some attention to make it look slick enough. Like i suggested. Counter sinking it into the wall that is getting moved might be a good solution.
Answer: I had exactly this scenario in my house.
What I did was to get a piece of wood that matched the cabinetry and screwed it to the studs to provide a rail for the back of the cabinet to sit on.
I then marked the stud locations inside the cabinet, and screwed it to the studs as well.
Keep in mind that your cabinet back is probably only decorative, so you may need to add some blocking inside to get a good holding bolt.  From your picture, it's important to get a good connection in the top left corner.


Telephone Termination Block upgrade

Question: I recently moved into a house which has a screw type termination block:

I am trying to get DSL service and self-install is not working so they are sending a technician out.  I will get charged $100 if its a wiring problem inside the house.  To ensure that problem isn't on my side, plan on running a new line to my wiring closet (which as CAT6 Punchdown panel) and disconnect all existing lines.
Is there a better way to terminate the phone line from the phone company then the screw type termination block?  (I fear my stranded 24awg CAT6 wire is not making a good connection, and possible noise/signal quality)
I am looking at something like this from Amazon:

But my concerns are:

The Current setup as a grounding wire... I don't see one in the Open House block
The wire from TelCo is very thick; I tried connecting it to a CAT3 Keystone Jack just to test the connection and wire would not stick in place.

Any other general advice on integrating Telco lines with CAT6 wiring is appreciated.
Comment: The good news is the wire into your house appears to be old single pair flat (non-twisted) cable. AFAIK, that cable is not dsl compatible.  That will need to be upgraded for dsl. They will also install a modern demarc when it's replaced.
Answer: Demarc
The Demarcation point or DMARC or Network Interface for a phone line is simply the first place in the building where you can access the phone line to connect your own equipment. In a new installation, this will typically be an RJ11 jack in a box installed outside the building (for typical single-family home installation) or either an RJ11 jack or a punch block in a wiring closet for an apartment or an office building. The phone company guarantees a high-quality connection to that point.
In many installations the DMARC will actually have both RJ11 and a punch block. That allows you to securely attach a cable going into your house while still allowing for testing at the DMARC by plugging a phone, modem, test set, etc. directly into the DMARC outside.
The problem of course is older houses. In an older house the DMARC will often be a cable running into an old screw type jack (as pictured) or spliced directly to multiple cables for distribution through the house, or spliced to one cable which then daisy chains through the house. That leads to a game of finger-pointing as to where the problem lies.
The solution is normally for the phone company to install a modern DMARC (either outside or, if it is more convenient for them, inside) and patch your existing wiring into it. This is quite commonly done in my area (Verizon) for FIOS installations - the technician brings fiber to the house near the existing entry point and connects the existing home cable into the FIOS box. The FIOS box has an RJ11 test jack for every phone line. But even if you are only getting DSL, the phone company may decide to install a new DMARC to make things simpler for everyone.
Internal Cabling
Once you have a good DMARC, you may need to redo the cabling in the house. I prefer to put a DSL modem (or modem/router) near the DMARC so that I can split the cable coming from the DMARC to the modem (no filter) and everything else (one filter, installed inline). The normal procedure is to filter each non-DSL connection (phone, fax, answering machine) and just make sure the DSL modem is not filtered, wherever you install it.
The cabling to the DSL modem should be high-quality. But CAT6 is overkill. I normally use CAT5 or CAT5e, but even CAT3 is quite adequate for DSL. All the other cabling in the house can remain as is, particularly if it is filtered early on.
Recommendation for your particular setup
In your case, it appears that the cabling currently coming from the street to your nominal DMARC is crappy (that's the technical term). If you have not done so already, try (a) disconnect all other devices, (b) connect just the DSL modem at the first possible location (presumably that is the pictured jack) and make sure it does NOT get a reliable signal. Assuming it doesn't (as I believe you have already determined), have the phone company do "whatever they want" as long as they end it with a DMARC that is accessible that they can show produces a good signal. While they may argue that their testers can verify the signal, I'd want to see a DSL modem go from off->slow blink->fast blink->connected before letting the technician leave.
Then put in a splitter right after the DMARC. One side goes either straight to the DSL modem or via CAT3/5/5e/6 to the DSL modem. The other side goes to a filter and from there to all your existing phone cabling.
You may need to wire up a couple of extra jacks to make this all work - e.g., short wire from splitter to filter, short wire from filter to a new jack, then connect new or existing cabling to that new jack. Use jacks that have standard 110 punchdown connectors (the same as you have on RJ45 jacks for Ethernet) and use a proper punch tool. In general I would do that (I've learned the hard way) for all phone cabling from this point forward - even if you just want to wire up an extra regular phone extension.

Telephone Termination Block upgrade


Get autocomplete selector after ajax call

Question: I am trying to find the selector of a jquery autocomplete in the "success" after making an ajax call.  In the "success" I am looking for $(this) to be $(".itemDescInput") but it is not.  How would I find that selector at that point?
$(".itemDescInput").autocomplete({
    source: "invoices/invoice_items.php",
    select: function(event, ui) {
        var $it_desc = ui.item.value;
        $.ajax({
            type: "POST",
            url: "invoices/invoice_items_prices.php",
            data: "it_desc="+$it_desc,
            success: function(result){
                if(result != '') {
                    $(this).find("input .itemCostEach").val(result);
                }
            }
        });
    }
});

Answer: Within success(), this does not refer to your selector but to your AJAX settings. You can change what this points to by setting context in your ajax() call. See the documentation.
For example:
    $.ajax({
        context: this,  // You could pass 'this' in directly if you wanted :)
        success: function(result) {
            // Refer to 'this' in the way you expect
        }
    });

Comment: Perfect, that is what I was missing!  Thanks!
Comment: Or you can also try creating a variable referring to $(this) immediately as first statement in select and then refer to the variable in success callback of ajax.


How to add new activity's children into another activity's children

Question: I want to add one Activity in to my current Activity's RelativeLayout(Parent) after a click on a Button. I want to do it dynamically, not from xml file. I'd like to know how and where to attach the code, and how would the code look. A simple example would do.
Comment: Do you mean `Fragment`?
Comment: Do you mean by **Fragments** or you want to change the **layout** only
Comment: with FrameLayout, we can add new fragment in current activity's children element. But, I am just wondering, is it possible to add whole new activity as one of the child of current activity?
Answer: Fragments are the way to do this if your target API allows.  An Activity is not a View, and has a very different life cycle.
That said, the deprecated TabActivity is an Activity that appears inside a TabHost - so it isn't impossible.  But TabActivity is (I'm guessing) probably supported via nasty internal hacks that can't be generally supported by normal Activities.
Comment: And if your target API is less than 11, you can always use the support library! :)


Multiplatform runBlocking coroutine tests fail if last assertion doesn't have a Unit return type

Question: I'm testing my coroutine functions in my Kotlin Multiplatform project.  I've mocked out the implementation behind them, so no actual await occurs during tests.
Consider the following test, curated from the test README:
@Test fun testAsyncFunction() = runBlocking {
    val result: List<myClass> = myService.someSuspendFunction()

    assertEquals(result.first()?.name, "name")
    assertNotNull(result.first()?.someRequiredValue)
}

The second assertion has a return type of T, which causes its result to be returned to the runBlocking function, throwing the following error:
Invalid test class 'com.example.shared.core.service.ExampleTests':
  1. Method testAsyncFunction() should be void

I've found 2 solutions to this, either I can swap the two assertions around (assertEquals has a Unit return type, thus no issues), or write val ignored = assertNotNull(result.first()?.someRequiredValue).  However neither of these two solutions are ideal, as I'll either have extraneous code that my IDE is warning me to remove, or my assertions are out of order.
What is the best solution to this issue?
Comment: I'm not sure where the multiplatform aspect comes in, especially given that `runBlocking` is not available in common code (only on JVM and Native). Note that you can use `kotlinx-coroutines-test`'s `runBlockingTest` for this kind of test instead of `runBlocking`. Its signature doesn't suffer from the same problem. Also as of `1.6.0-RC` the testing library has become multiplatform, so you can use `runTest` in common code
Answer: The problem is that the method is inferring the return type from runBlocking, which returns value from the inner suspending function.
You can force it to generate a void return type by specifying the return type : Unit explicitly rather than rely on the inferred value.


Can't direct a domain to a static page using AWS S3

Question: I followed this tutorial How to Point your Domain to an S3 Website Bucket and it works well.
My domain e.g. domain.com points my S3 Bucket bucket.com.s3-website.eu-central-1.amazonaws.com.
However, the index.html does not show by default e.g. if I use the URL domain.com I get this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>AE243F85AC91D283</RequestId>
<HostId>zAcaxygehDiR1EC6/JJADndO+JlvA7dYSAu+uOL7qWtdDGWLLQ+vGCoqescLUAKLH51/kLD/StM=</HostId>
</Error>

However, if I use domain.com/index.html or bucket.com.s3-website.eu-central-1.amazonaws.com the index.html page appears.
It's only if I use domain.com instead of the above that it doesn't show.
The bucket has all public permissions.
Comment: Have you specified index.html as index document on the bucket as shown [here](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/static-website-hosting.html)?
Comment: Yes, I did specify it.
Comment: Did you see my answer? Did it help?
Answer: You're getting an error. If you are only interested in showing the index.html page whenever the plain domain.com url is used, then you need to specify index.html as the error page as well.
Alternatively, you can do this with a redirect rule in the box below
<RoutingRules>
    <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals >
    </Condition>
    <Redirect>
      <ReplaceKeyWith>index.html</ReplaceKeyWith>
    </Redirect>
    </RoutingRule>
</RoutingRules>


DataTables Responsive: Remove row when columns are hidden

Question: I am using DataTables to create grid.
It's a great tool, but I have a problem with which occurs when the grid columns are hidden for example on mobile or other small devices where there is not enough room to display all columns.
Problem:
Removing grid row when columns are hidden. When are columns are showing it works just fine.
Table code:

      Name
      Position
      Office
      Age
      Start date
      Remove

      Name
      Position
      Office
      Age
      Start date
      Remove

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25

        <button type="button" class="btn btn-info btn-sm removeRow">Remove this row</button>

      Jena Gaines
      Office Manager
      London
      30
      2008/12/19

        <button type="button" class="btn btn-info btn-sm removeRow">Remove this row</button>

Javascript code:
$(document).ready(function() {
  $('#example').DataTable({
    responsive: true
  });
});

$(".removeRow").click(function() {
  var table = $('#example').DataTable();
  table.row($(this).parents('tr')).remove().draw();
});

I am attaching link to jsfiddle. You can clearly see it works when columns are shown, and it breaks when columns are hidden.
I wonder if anyone else came across similar issue, any help would be appreciated.
Comment: Don't understand what you mean by "breaks" in the fiddle when pressing remove on both rows it works as expected.
Comment: Nvm i see what you mean. The reason why is that the structure of the html changes when the responsiveness kicks in.
Comment: Also when it is responsive your remove button is added to the dom after the plus icon is pressed. so there is no event attached to it. so you have two problems. The remove button is no longer a child of the tr you want to remove and there is no event attached to it.
Comment: Maybe you can try `$(document).on("click",".removeRow",function() {. EDIT: even this will be necessary because the child element is dynamically added you need to implement an other additional method which has to respond to this changes
Comment: Thank you for tips,  I have managed to fix the issue. I will post answer soon.
Answer: I have managed to fix the issue. I decided to post it in case anyone else has similar problem.
This wasn't working because HTML structure changes when columns are collapsing. To fix this I added extra check, to verify if columns are collapsed or not.
Amended code:
$(document).on("click", ".removeRow", function() {
    var table = $('#example').DataTable();
  var row;

  console.log($(this).closest('table'));
  if($(this).closest('table').hasClass("collapsed")) {
    var child = $(this).parents("tr.child");
    row = $(child).prevAll(".parent");
  } else {
    row = $(this).parents('tr');
  }

  table.row(row).remove().draw();

});

It's now working fine.
Here is updated jsfiddle.


How can i post a blog on LinkedIn?

Question: I want to post a blog on linkedIn so how it's possible?I have completed LogIn functionality in LinkedIn.Please Help me in Posting blog from my native application.if some one got the idea then please explain me with code.i have completed authentication process but after authentication successful it gives me one code like "61592".and Message like this:"You have successfully authorized [AppName].Please return to your application and enter following security code to grant access: 61592 "
Comment: @Ankit Could you please provide more details about what, specifically, you're trying to do and how it is a programming issue.
Comment: I believe he wants to create a blog post from a native iPhone app.
Comment: That'd be a cool question, but I think we're just wishing this one made sense.
Comment: superuser's already got one [(user crossposted)](http://superuser.com/questions/140597/can-any-one-please-tell-me-how-can-i-connect-to-linkedin-from-my-nativa-applicati) ... @Berkay: when you post a comment that a question belongs on another Trilogy site, you should inform the OP that the question can be migrated automatically, and that they should not crosspost.  thanks!
Comment: belongs to superuser.com
Comment: I want to post some Text Message from my native application and it should be posted in LinkedIn's Wall and every one should read it.Like facebook we can post our message to facebook's wall.
Comment: See also this question: http://stackoverflow.com/questions/2085048/how-can-i-integrate-linkedin-within-an-iphone-application and this one: http://stackoverflow.com/questions/2809036/linkedin-connectivity-from-my-native-iphone-application
Answer: If you want to make blog posts appear in your LinkedIn feed, the easiest way to do this is to use another blog and have it syndicated on LinkedIn. For example if you have a blog on http://posterous.com you can send posts to your blog via email and have it autopost to your LinkedIn  profile, by configuring up the "Autopost" options in "Settings" on posterous.com.
Comment: No Actually i don't want to do like that when i go for the Registration and if it will get succeed then automatically the content which i have should posed on LinkedIn Wall.
Comment: I really can't understand the question then. The method I suggested would automatically post the content on the LinkedIn wall. The same thing happens if you syndicate your Twitter feed. My LinkedIn profile works this way, if you want to see an example: http://uk.linkedin.com/in/snim2
Comment: can you give me the Sample code for posting some content on Wall of LinkedIn.Actually i got the above message with security code from that i don't understand what to do?i can give you my sample code if you want?i have never implemented before it that's why i don't understand please understand my situation.
Comment: I think it would clarify your question a lot if you posted the sample code.

The solution I was suggesting didn't actually require any code. Are you writing an application?
Comment: http://github.com/ResultsDirect/LinkedIn-iPhone
You can get the Sample code from here and In this code you have to provide API key and Secrete key and you can understand the problem.IT will give you authentication Only.

How can i post a blog on LinkedIn?


moving file to ntfs volume

Question: I have a nfts disk that I use to keep movies and music: on ubuntu, I created a folder onto this disk and moved a video file from my ext4 disk to that folder. Turned out I could not access to the folder on windows 7. Is this some kind of permission-related problem? Can sombody help to set the disk in order to receive and run files from either os?
Comment: ok..turned out that if the folder is created on ubuntu, it cannot be read by windows, at least that particolar one...so I created the same folder on windows and then i moved the file from the previous folder to the new one (on ubuntu). The file is now visible and playable on windows...this is not  "solved" but at least I got my file back.
Comment: If you suspect permission related problems, you should provide informations about the permissions of that folder!
Answer: I am afraid that you moved the file with root permission. It also happens when you format your ntfs disk from ubuntu. Ubuntu does not give enough permission by default. Install ntfs-config. Give Internal and External writer permission to ntfs partition using ntfs-config. And also change your moved files permission
<code>sudo chmod -R 755 /media/ntfsdiskname/
</code>

moving file to ntfs volume


How to generate groovydoc from jenkins global library

Question: I have a jenkins global library and I want to document it. I want to use groovydoc.
The library contains classes and global vars
src/<package-name>
vars

Generating documentation for the classes is no problem:
groovydoc -sourcepath src -d doc 'main.pipeline' '*.groovy'

But how can I generate documentation for the vars?
Answer: To ensure everything was reported in the right packages, without having to enumerate all the packages, I used:
mkdir -p doc/

groovydoc -d doc -private -nomainforscripts -sourcepath src:vars \
    $(find src/ vars/ -name \*.groovy -printf '%P\n')

This incantation convinces Groovydoc to get the packages right without requiring me to tediously list them all, which is the main challenge.
If your find doesn't have -printf, replace -printf '%P\n' with | cut -d '/' -f 2-. The effect is the same; strip the leading src/ or vars/.
Comment: Linux or windows soloution?
Answer: What worked for me:
groovydoc -d docs -sourcepath "src;." my.package vars

Exports everything in vars as DefaultPackage and my.package contained in the src folder.
Comment: THis is working but only one packet is taken instead of all packet
Answer: Maven solution:
<plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.7.1</version>
    <executions>
      <execution>
        <goals>
          <goal>addSources</goal>
          <goal>addTestSources</goal>
          <goal>compile</goal>
          <goal>compileTests</goal>
          <goal>groovydoc</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <sources>
        <source>
          <directory>${project.basedir}/vars</directory>
          <includes>
            <include>**/*.groovy</include>
          </includes>
        </source>
        <source>
          <directory>${project.basedir}/src</directory>
          <includes>
            <include>**/*.groovy</include>
          </includes>
        </source>
      </sources>
      <testSources>
        <testSource>
          <directory>${project.basedir}/test</directory>
          <includes>
            <include>**/*.groovy</include>
          </includes>
        </testSource>
      </testSources>
      <docTitle>Jenkins Shared Libs</docTitle>
      ${titre}
      ${titre}
      <windowTitle>${titre}</windowTitle>
    </configuration>
  </plugin>

Answer: Had the same problem at work today and sadly can't try my solution now, but try using the directory containing both src and vars as sourcepath. Then you can reference your src and vars subdirectories in your command like this:
groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\ vars\

If that doesnt work, try referencing each package seperately somewhat like this:
groovydoc -sourcepath [PATH_TO_YOUR_LIB] -d doc src\org.foo.some_package src\org.foo.some_other_package vars\

Alternatively, or as a workaround, you could use the IntelliJ IDE and its "Generate GroovyDoc..."-Tool:

Start IntelliJ and open any Groovy project (create a new one if there isnt an existing one)
From the menu bar Tools > Generate GroovyDoc...
Choose your source path containing your jenkins pipeline library as Input directory (containing both src and vars) and any path as Output directory
Press Start
GroovyDoc should be in the specified Output directory
Comment: The output I get is completely unusable. The structure of the shared libraries is not standard groovy. For example the files in /vars are not classes but just methods listed in a file.
Answer: i was facing the same issue. i just needed an overview with parameters. I know there is lots of space for improvement, but works for my usecase:
import groovy.io.FileType
import java.util.regex.*;

class DocGenerator {
    String run(String root_path) {

        def list = []

        def dir = new File(root_path)
        dir.eachFileRecurse(FileType.FILES) { file ->
            if (file.name.contains("groovy"))
                list << file
        }

        String output = "| Method | Doc |\n"
        output += "| ------ | ------ |\n"

        list.each {
            output += "| ${it.name.replace(".groovy","")} | ${getComment(it.text.replace("\r\n","
"))} |\n"
        }

        println(output)
        return output
    }

    String getComment(String txt) {

        String re1 = "(\\/\\*[\\d\\D]*?\\*\\/)";    // C Comment 1
        String re2 = ".*?";    // Non-greedy match on filler
        String re3 = "def";    // Word 1
        String re4 = ".*?";    // Non-greedy match on filler
        String re5 = "call";    // Word 2

        Pattern p = Pattern.compile(re1 + re2 + re3 + re4 + re5, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(txt);
        if (m.find()) {
            String ccomment1 = m.group(1);

            return m.group(1)
        }

    }

}

app = new DocGenerator()
app.run "C:\\Git\\JenkinsSharedLibrary\\vars"

My output was intended to be added to an readme.md. But i think you get the point


What are the different tiers of technology?

Question: All the technology upgrades I've found have a suffix which seems to determine the tier or effectiveness, such as "Tau" or "Sigma". How many of these tiers are there and which is the strongest?
Comment: I've heard that Theta is the most powerful or effective, but I don't know of the other ranks.
Comment: These levels are no longer applicable. They are now labeled (from lowest to highest) C, B, A, S.
Answer: There are four tiers of tech upgrades: Sigma, Tau, Theta and Omega. Their comparative strengths rank as follows:
Omega > Theta > Tau > Sigma
The stronger the upgrade, the rarer/more expensive the materials required to build it will be, as noted by @David Yell.
As noted by user @SGR, not every tech has four tiers -- four is the maximum you'll see, and the comparative ranks shown above still apply to techs with fewer tiers of upgrades.
(Source, Source, Source)
Comment: It's worth noting that the the higher tiers of blueprint require rarer ingredients and greater quantities too.
Comment: Do you need all 4 tiers of an upgrade to get the bonus? I have thetha hyperdrive but won't let me go to blue galixys that need it
Comment: Can this answer include the strength of these tiers?  How much of the circle-meter fill up with a tier 3 tech, for example.
Comment: @Carl I'm not sure which circle-meter you're talking about (on holiday right now, so can't boot up the game). I did, however, add the upgrade "numbers" if that helps. Feel free to edit the answer with the information you're talking about.
Comment: User Lockness has said they found a +5.
Comment: @DCShannon Saw that, and found out that the numbers vary between blueprints. Removed modifier numbers from answer.
Comment: @michael Perhaps your warp drive doesn't have enough warp cells to make the jumps required. I would *assume* that you'd need a cell for each system travelled through.
Comment: Hyperdrive upgrades stack.
Comment: @michael The color of a star system doesn't matter when warping. I've seen no references to needing certain hyperdrives to visit a system. Warpdrive upgrades let you warp farther away and that's it.
Comment: @VanBuzzKill I can guarantee that the basic warp drive won't let you warp to a blue star. I don't recall the exact message but it's different from the "too far" one.


What should I do with my Sightstone as a Support?

Question: I'm wondering what I should do with my sightstone. Should I leave it just a sightstone, upgrade it to ruby sightstone or upgrade it to any of the Eyes?
I understand that it's situational, just give me an example when to do it and when not to.
Answer: Always upgrade to Ruby sightstone if you are going to be getting a lot of items that you can use on your carry. Ruby gives you an added cooldown percentage of these items.
I usually find that Frost Queen's Claim is better than the Eye in 90% of cases.
Talisman can be useful in certain cases, if you're facing a very mobile team comp, but the eye is probably better in most cases.
Face of the mountain is pretty good if you are against a lot of assassins and your adc isn't sivir. It's also good if your team has a lot of assassins so you can shield them when they go into battle.
Answer: As a compliment to ChaseC's answer, the main reason to go for one of the combination items rather than Ruby Sightstone is if your support build does not have many on-use items.  Tanks are the most obvious example - an off-tank type support may value rushing certain items against specific carries, like taking Randuin's Omen against Ashe.  If you are your team's only tank, taking a hybrid item means you can focus your other items on varied defensive items; while Face of the Mountain and Ruby Sightstone grant a decent amount of health, per point armor and magic resist give you more effective health.
Besides tanks, some support players like to build up their AP to make their abilities more powerful rather than rely on item effects.  In this case, the argument for hybrid items is basically the same - by getting your gold generation and upgraded sightstone more cheaply and in one item, you can start building toward useful AP items more quickly.
Answer: The only time you get Ruby Sightstone is if you plan on making use of its passive, and even then the passive is only ok because generally fights don't happen often enough to require lower item cooldown (which are pretty low already). Otherwise you're wasting a whole item slot for extra wards and some health.
I do like Frost Queen's Claim a lot and will often get it on certain supports, but I still think the Eye is a better game item overall.


can't access value of input when i have it inside foreach loop (using post method)

Question: I have a form contains one input (type button) and one image.
when i click on the button it supposed to delete the image (submit the form and get the value of the input which is the id of the image, using post method).
But i can't access the value of the input when i have it inside foreach loop.
because every input created inside foreach has the same name.
https://i.stack.imgur.com/0D2Wu.png
i tried var_dump and there is just null value.
this is the form inside the camera view:
foreach($data['galleries'] as $gallery) :
    ?>

    <form action="<?php echo URLROOT; ?>/gelleries/camera"
   method="post">
    <input type="button" class="button" name="delete" id="abc"
   value="<?php echo $gallery->galleryId; ?>" onclick="return
   Deleteqry(<?php echo $gallery->galleryId; ?>);">

    </form>
    <?php endforeach; ?>

and this is the controller:
<?php
    class Galleries extends Controller {
     $this->galleryModel = $this->model('Gallery');
   }
    $galleries = $this->galleryModel->hiFive();
    $datashow = [
        'galleries' => $galleries
    ];
    .....
    public function camera(){
     if (isset($_POST['delete']) && !empty($_POST["delete"])){
        $imgid = $_POST["delete"];
      $this->galleryModel->deleteimg($imgid);
      echo "deleted!";
    exit;
 }
 else
    echo "error";
    $this->view('/galleries/camera', $datashow);
 }

and this is the model where i execute the queries:
<?php
   class Gallery {
   private $db;

   public function __construct(){
    $this->db = new Database;
   }
   .....
      public function deleteimg($id){
       $this->db->query("DELETE FROM galleries WHERE id = :id");
       $this->db->bind(':id', $id);
       if($this->db->execute()){
       return true;
     } else {
      return false;
   }
   }
   }

The Deleteqry inside onclick event of the button it's just a function where i check if i get the id of the image when i click on the button:
function Deleteqry(id)
{
 if(confirm("Are you sure you want to delete this row?")==true)

 window.location="http://localhost:8001/camagru/galleries/camera?
 &del="+id;
  return false;
 }

Comment: creating multiple forms in a loop is more or less OK but you MUST ensure that any elements that have an ID attribute have a unique ID rather than `id="abc"` etc
Comment: @RamRaider i changed now with galleryId; ?> .. so every element has unique id .. but i still can't remove the image
Comment: what does `Deleteqry` do? You have not added that to the question
Comment: it's just a javascript function where i check if i get the id of every image when i click on the button .. i add it now on the post above
Answer: Add hidden input field in your form block with value of gallery ID, like this:
 <form ...>
    <input type="button" class="button" name="delete" value="DELETE NOW">
    <input type="hidden" name="GallID" value="<?php echo $gallery->galleryId;?>" >
 </form>

And in your controller read that value from hidden field:
if (isset($_POST['delete']) && isset($_POST['GallID']) && !empty($_POST["delete"])){
    $imgid = $_POST["GallID"];
    $this->galleryModel->deleteimg($imgid);
    echo "deleted!";
}

This works completly without javascript.


SSRS Group Sort Using Group Variable

Question: I'm looking to sort group Part using variable Coverage. The variable's expression:
=( IIF(ISNOTHING( SUM(Fields!OnhandQty.Value) ), 0, SUM(Fields!OnhandQty.Value)) +
   IIF(ISNOTHING( Fields!WIP.Value ), 0, Fields!WIP.Value)
) / IIF(ISNOTHING( SUM(Fields!RequiredQuantity.Value) ), 0, SUM(Fields!RequiredQuantity.Value) )

I'm able to save report (using Report Builder) with no errors, but I get the error:
The processing of SortExpression for the table 'TablixCustomer' cannot be performed. The comparison failed. Please check the data type returned by the SortExpression. (rsProcessingError)
Why?
Comment: Could you explain the sort logic that you want, there may be a better way of doing it.
Answer: Your expression SUM(...Value) will fail if .Value is ever null and becomes a String value of #error. So try changing your expressions to this: Note that it checks the value before aggregating the value instead of aggregating before checking for null.
=( SUM(IIF(ISNOTHING(Fields!OnhandQty.Value), 0, Fields!OnhandQty.Value)) +
   IIF(ISNOTHING( Fields!WIP.Value ), 0, Fields!WIP.Value)
) / SUM(IIF(ISNOTHING(Fields!RequiredQuantity.Value), 1, Fields!RequiredQuantity.Value))

Comment: @AlanSchofield I edited to avoid divide by zero error.
Comment: This will fail is RequiredQuantity is nothing as it will attempt a divide by zero. This issue was present in the OP's expression though.

SSRS Group Sort Using Group Variable


A mix of single and bulk delete

Question: I'm working on a UI that will allow users to save thousands of records. They also have the ability to organize these records into Projects.
In the main records screen, we allow bulk delete - ie: you can check off multiple items then delete them in bulk. This is because, as mentioned, thousands of records.
However, in the Projects screen, we don't anticipate users having a lot of Projects. There will only be 3 or 4, so bulk editing isn't really necessary here, so I was thinking of only allowing users to delete one Project at a time.
This is what the records screen with bulk editing looks like. Note that the "Delete" button will only appear after at least one item has been checked off.

The Projects screen almost looks exactly the same, but without the checkboxes/ability to bulk delete.

I guess we can mirror the UI for consistency, but I just don't think bulk editing is necessary for something that won't even contain a ton of items.
Is it ok to have a mix of bulk and single editing in the UI?
Answer: It's perfectly reasonable to mix these patterns, based on what they're dealing with.
Imagine an e-commerce website that supports creating multiple wish lists. I would expect that they would let me remove several items from a wish list at one time, but I wouldn't necessarily be surprised if they made me delete only one wish list at a time. This feels natural because a list is a grouping object, so deleting a list is a larger, more destructive action. Deleting a number of wish lists at once would be giving me more destructive power than I'll typically need. To not allow me that option is to protect me from accidentally deleting everything, and accepting that I'll be slightly inconvenienced if I'm ever actually in need of that functionality.
However, I might style the rows a bit differently to visually reinforce the slightly different behaviors available. For example, records, which support the bulk-delete, might be a bit narrower which would also naturally better display the large numbers of them. Conversely, I'd show the projects with more padding, and perhaps a larger font to illustrate that these are "larger" objects than records.

A mix of single and bulk delete


Google Scripts: Trigger not working or script only runs once

Question: I am new to Google Scripts so I have been struggling with this issue for some days now. Gone through multiple sources and none have the same issue as me.
I have set a time-based trigger for my script to import a CSV from my Gmail into a sheet. The emails sent are reports pulled daily from DV360 which are then used to populate a Data Studio Dashboard.
My first issue is that either the trigger isn't working properly (which may be unlikely) or that there is something wrong with my code. One weird thing which I have noticed is that the trigger works for one of the reports but does not work for the remaining 6.
I have multiple scripts in this project which all import different CSV attachments from different emails and each populate their own tab in a Google Sheets file.
Once I have run the script once and it has populated its respective sheet, it won't run again even if there is an email with a more recent attachment in my inbox (for example if I ran the script the following day, it won't populate the sheet with that specific day's report).
Below is the code I have used.
<code>function importCSVFromGmail() {
  var threads = GmailApp.search("Label:Audience_List");
  var message = threads[0].getMessages().pop();

  var attachment = message.getAttachments()[0];

  if (attachment != null) {
    var attachName = attachment.getName();

    // Is the attachment a CSV file
    if (attachName.substring(attachName.length-4) === ".csv") {
      var id = "1cl5nZiJ2Jh__pMig-BoGTKpE9kM8-5nYe178WdI6ChI";
      var name = "Audience_List_Backend";
      var sheet = SpreadsheetApp.openById(id);
      var tab = sheet.getSheetByName(name);
      var tabInfo = sheet.getSheetByName("Audience_List_Backend");
      tabInfo.getRange("A1").setValue(new Date());

      // Clear the content of the sheet
      tab.clearContents().clearFormats();
      var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      tab.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
  }
}
</code>
Thank you in advance for any assistance!
Comment: Hello @RoryLittle! I think that @Tanaike deductions are correct and you should definitely follow them. I recommend changing the way that you use to read the file extension in the `IF` check to the style described [here](https://stackoverflow.com/a/45925016/). Please, report back with your findings so we can help you better.
Comment: Can I ask you about your question? About `Trigger not working or script only runs once`, the function of `importCSVFromGmail` is not run. Although the function of `importCSVFromGmail` is run, the script in the if statement is not run. Which is your situation?
Comment: It is the second situation where importCSVFromGmail does run but the statement does not seem to run on the second time I run it. The first time it populates a sheet with the correct report
Comment: Thank you for replying. From your replying, I could understand that although `importCSVFromGmail` is run, the script in the if statement is not run. In that case, how about checking the values used at the if statement again? In your script, it seems that those are `attachment` and `attachName.substring(attachName.length-4)`. If this didn't lead to the solution, I apologize.
Answer: The solution was simple.
Split each Script File out into its own project and trigger them individually using a time-based trigger.
Therefore the 7 actions I required each had their own project with a time-based trigger.


How do I find a specific cell within a cell array?

Question: Let's say I have a cell array containing 1x2 cells. eg. deck = {{4,'c'},{6,'s'}...{13,'c'}...{6,'d'}}
How can I find the index of a specific cell? E.g I want to find the index of the cell with the values {13,'c'}.
Thanks!
Answer: Try cellfun with isequal:
>> deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}};
>> targetCell = {13,'c'};
>> found = cellfun(@(c) isequal(c,targetCell),deck)
found =
     0     0     1     0

cellfun let's you check anyway you want (not just isequal).  For example, if you want to check based on the string element in each cell:
>> targetLetter = 'c';
>> found = cellfun(@(c) strcmp(c{2},targetLetter),deck)
found =
     1     0     1     0

Comment: Nice job with `isequal`!
Answer: Another method I can suggest is to operate on each column separately.  We could use logical operators on each column to search for cards in your cell array that contain a specific number in the first column, followed by a specific suit in the second column.  To denote a match, we would check to see where these two outputs intersect.  We can do this by combining both outputs with a logical AND when we're done:
deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}};
target_card = {13, 'c'};

deck_unroll = vertcat(deck{:});
a1 = cat(1, deck_unroll{:,1}) == target_card{1};
a2 = cat(1, deck_unroll{:,2}) == target_card{2};
found = a1 & a2

found =

     0
     0
     1
     0

Because deck is a nested cell array, I unrolled it so that it becomes a 2D cell array where each row denotes one card.  This is stored in deck_unroll.  Once I do this, I further unroll the cells so that the first column gets placed into a numeric array and we search for a particular number (13 in your example) and the second column gets placed into a string array where we search for a particular character ('c' in your example).  This is done with the help of cat to extract each element from a particular column and we construct an array out of these elements.


Xcode UIImageView animation jumps back to original position..

Question: I'm pretty new to xcode.  trying to play around a bit, but ran into this strange behavior...
i'm using CoreMotion acceleration to move an image around on the screen.
shortening the moving the UIImageView Movement code...
<code>        dispatch_async(dispatch_get_main_queue(), ^{

        CGRect recta = movingImage.frame;

        //data is the coremotion info.
        float dataAccelerationX = data.acceleration.x;
        float dataAccelerationY = -data.acceleration.y;

        float movetoX = recta.origin.x + (dataAccelerationX * stepMoveFactor);
        float maxX = self.view.frame.size.width - recta.size.width;

        float movetoY = (recta.origin.y + recta.size.height) - (dataAccelerationY * stepMoveFactor);
        float maxY = self.view.frame.size.height;

        movingImage.frame = recta;
    });
</code>
while this is occurring, i have a button, that simply creates another UIImageView on a existing UIView...
<code>-(void)addInAnotherImage
{
    dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"making UIImageView with image file");
    UIImageView *someImage =[[UIImageView alloc] initWithFrame:CGRectMake(200,200,200,200)];
    someImage.image=[UIImage imageNamed:@"someimage.png"];
    [self.view addSubview:someImage];
    });
}
</code>
when this occurs, the movingImage jumps back to the original position it started from.  I'm hoping to achieve the addInAnotehrImage to trigger while movingImage is floating around the screen using acceleration of CoreMotion.  Anyone can help me identify why the movingImage jumps back to original position when the addInAnotherImage is run?
Answer: Never mind!  i found the issue.
The movingImage was setup with an IBOutlet.  had constraints on it.
what i did was change the UIImageView type from
<code>IBOutlet UIImageView *movingImage
</code>
to
<code>@property (nonatomic, strong) UIImageView *movingImage;
</code>
then synthesized it, and setup beginning coordinate at the ViewDidLoad.


How to bundle UI with Microservice

Question: We have nearly 70+ microservices with Spring Cloud. Everything works as expected. But, we have a big giant UI Angular app which is consuming all services.
I have read somewhere that the better approach is to bundle UI along with service to avoid dependencies. Sounds good, but couldn't pointers for it. Just got that there is a UI composition pattern but couldn't connect how could it really help.b
How do we really couple a service with the UI as one system and ship(deploy) it? Is it really worth? If so, can someone point me to any sample example? How to combine different HTML responses of various services at client side?
Answer: Maybe Self-Contained Systems (SCS) is what you are looking for. Each Service provides its own UI which may be part of the whole.
A brute force (and not that beautiful) integration approach would be separate Angular Apps presented in iframes.
Sadly I have too little experience on that topic to help you more.

How to bundle UI with Microservice


Rails log file stops logging if I touch it. How to get it logging again?

Question: My log files generate a LOT of output, and it's difficult to tell where the current action I'm looking at started logging. I though it would be as simple as deleting what was currently in the log file immediately before making the action (or at least adding some spacers), but editing the log files seems to make the application stop logging completely!
I can reset the application to start it logging again, but that brings me right back to square one - digging through a whole bunch of unneeded logs without knowing where the bits I actually wanted start.
Is there a way to edit the log file without killing Rail's ability to log?
Answer: Instead of deleting the file, do
cat /dev/null > log/production.log # or whatever the path to your file is

The problem is that when you delete the file, Rails still has the file open, so it is continuing to write to this now "deleted" file.  By catting /dev/null to the file, you will clear out all of its contents without changing where the file handle is writing to.
Answer: My best guess as to why this is happening is that the I/O stream is being interrupted and corrupted (because you're modifying the file) while it's open (your application is running). You either need to restart your app or use Rob's solution.
However, an alternative solution is to use tail to view only the last 10 lines, you can specify more lines with tail -n 30, or whatever amount you wish. An even better solution is to use tail -f, which will show the file's tail and then print out new data as it is written to the file; very useful for monitoring log files.


Warning "attempt to present ViewController whose view is not in the window hierarchy - Objective C

Question: I'm trying to call a controller, if has response error, and redirect the user for login controller.
<code> UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"EventManagerStoryboard" bundle:[NSBundle mainBundle]];
LoginViewController *loginController = [storyboard instantiateViewControllerWithIdentifier:@"loginID"];
[loginController viewDidLoad];
loginController.showOnlyLoginForm = YES;

[self presentViewController:loginController animated:YES completion:Nil];
</code>
and I facing this warning -

Attempt to present Attempt to present LoginViewController: 0x7fc958201130 on ProfileController: 0x7fc9583118e0 whose view is not in the window hierarchy!
Comment: my note was regarding the call to `viewDidLoad`, it wasn't supposed to solve your problem. anyway, the error message is pretty self explanatory. your code is called when the `self` is not presented, so `self` cannot present other view controllers. but without more context, nobody will help you any better. there might be tens or hundreds reasons why that happens, but without seeing the rest of the code we can just guess.. In other words, the code you showed is OK, the problem is in the rest of the code.
Comment: I would recommend to use 'loadViewIfNeeded' instead of directly calling `viewDidLoad` callback
Comment: You should _never_ call `viewDidLoad` yourself - it's called automatically once the view controller's view is loaded
Comment: @MilanNosáľ there's no diference.
Answer: Don't run this code in viewDidLoad try it in viewDidAppear
<code> [self presentViewController:loginController animated:YES completion:Nil];
</code>
Edit:
use in appDelegate if you implement navigationController
<code> [(UINavigationController *)self.window.rootViewController pushViewController:vc animated:YES];
</code>
Comment: Actually I'm running in connectionDidFinishLoading
Comment: Does ProfileController is shown or where you implement connectionDidFinishLoading
Comment: I'm implement connectionDidFinishLoading on my app delegate. I force the logout of user when have some responser error.
Comment: you may implement navigation controller to accomplish this as there is not viewController in appDelegate to present your login or use notification center / delegate to tell another viewController to make the present instead of appdelegate
Comment: but your log identifies that you want to present it in a viewController named ProfileController , even self present .... will not run in app delegate
Comment: But I need get the information about user, when they open the after terminate.

Warning “attempt to present ViewController whose view is not in the window hierarchy - Objective C


OpenX php fatal error when APC is enabled

Question: I am trying to migrate openX from a RHEL server to an Ubuntu based.
I am hitting the following error whenever APC is enabled:
Fatal error: Interface 'OX_M2M_M2MTicketProvider' not found in /var/www/openx/lib/OA/Central/M2MTicketProviderImpl.php on line 33
as soon as I switch apc off, everything works fine.
has anybody encountered this?
thanks in advance
UPDATE: This actually only happens when apc.stat=0. It is probably worth mentioning that the config file is symlinked to a shared storage (glusterFS)
UPDATE 2:
On M2MTicketProviderImpl.php if I change
require_once (dirname ( FILE ) . "../../../OX/M2M/M2MTicketProvider.php");
to
require_once (LIB_PATH . "/../OX/M2M/M2MTicketProvider.php");
it works.
But I would like to find a solution where I dont need to hack the openX code.
Answer: simple solution for that is settings:
<code>apc.include_once_override = 0
</code>


Deploying an SSIS Package

Question: I have a a project with multiple packages under the SSIS_Packages folder. Can i deploy one of those package instead of the project? The documentation here indicates to use .SSISDeploymentManifest. I don't want to deploy all the packages under the project, just one to SQL Server 2005.
Answer: Check the dtutil utility out (following sample taken from here) :
<code>dtutil /DestS [servername] /FILE [filename].dtsx /COPY SQL;[foldername]\[filename]
</code>
Answer: Easies would be to create a new SSIS project in VStudio containing only the desired package and deploy this single package.
Comment: This is what I've been doing but this is not the way.
Answer: If you want to just deploy a single package, you can also use the File -> Save Copy As ... functionality in BIDS:
1) Open package.
2) Click inside package whitespace to focus package.
3) In the BIDS menu, go to File -> Save Copy of  As ...
4) Fill in the pop-up box appropriately (Destination server name, authentication, package path on the server, protection level).
If you need to repeat this process, your best bet is to create a batch file that runs the dtutil executable with the appropriate command-line arguments.

Deploying an SSIS Package


Breakpoint in dart library does not work

Question: I am experimenting with Dart and libraries and I cannot seem to get a breakpoint to work in my library class.
I've created a library in lib/myLib/myLib.dart, defined a class there and set a breakpoint in the constructor. I construct this class from my main method, defined in web/test.dart. Breakpoints which are set in the main method are hit, but the breakpoints from the library are not hit. I am certain the code executes though, as i can step into the library's code from the main method.
Is this a known issue, or do i need to configure something? I am using Dart Editor version 1.0.0_r30798 and DartSDK version 126.96.36.199_r30798 on Windows 7 64-bit.
Answer: I have sometimes issues with breakpoints. Either they get ignored or the execution halts at the breakpoint but instead of the file with the code a new window with an error message is opened in the Editor('file not found' or similar).
In such cases I use the Dartium integrated debugger whihc never let me down.
F12 in Dartium > Editor dialog > choose 'no' > Dartium developer tools tab sources > open source from 127.0.0.1:3030 node > set breakpoint > start reload/execution with F5
Answer: You are probably importing your own library like this:
import "package:mylib/lib.dart";

If so, you should put your breakpoint in the files located under the "packages" folder in your project.
Alternatively, you can import your lib with a relative path:
import "../lib/lib.dart";

Comment: Hmm, i had tried this both ways IIRC, and had set breakpoints in all packages folders as well, but now that i try it again this seems to work, but only if i import with the relative path.
Answer: Bubblewrap, can you create a small test case demonstrating the issue, and file a bug at dartbug.com/new, w/ the test case attached?


Android homescreen Widget - Search

Question: I was wondering if it was possible to create a Android HomeScreen widget which has a search bar, which when a user enters some text and presses enter, it will open the corresponding app and searches within in.
I currently have a widget that contains a logo and a text view, however, when you click on the widget, nothing happens. The keyboard doesnt even pop up. Can anyone help?
Currently I have it randomly setting the textview with a random number, and onclick, changing the number
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="horizontal" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        android:src="@drawable/logo_menu" />

    <TextView
        android:id="@+id/widget_search_textview"
        android:layout_width="0dp"
        android:layout_gravity="center_vertical"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="10dp"
        android:clickable="true"
        android:layout_weight="1"
        style="@style/FontStyle.edit_text_view_light" />

</LinearLayout>

Manifest:
<receiver android:name="android.widget.SearchWidget" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/search_widget_provider" />
        </receiver>

Class:
public class SearchWidget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

      // Get all ids
      ComponentName thisWidget = new ComponentName(context,
              SearchWidget.class);
      int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
      for (int widgetId : allWidgetIds) {
        // create some random data
        int number = (new Random().nextInt(100));

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
            R.layout.search_widget_layout);
        // Set the text
        remoteViews.setTextViewText(R.id.widget_search_textview, String.valueOf(number));

        // Register an onClickListener
        Intent intent = new Intent(context, SearchWidget.class);

        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.widget_search_textview, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
      }
    }

}//End of Search Widget Class

App Provider:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="50dp"
    android:minHeight="50dp"
    android:initialLayout="@layout/search_widget_layout"
    android:resizeMode="horizontal"
    />

Answer: A TextView does not accept user input. A TextView is a label, for output.
In an activity, you can use an EditText for user input. EditText is not supported in an app widget.
Hence, to your question:

I was wondering if it was possible to create a Android HomeScreen widget which has a search bar, which when a user enters some text and presses enter, it will open the corresponding app and searches within in.

That is not strictly possible.
Comment: So you are unable to create a search widget?
Comment: @JamesKing: If by "search widget" you mean a widget that accepts text input used for a search, correct. There is nothing stopping you from responding to a tap on a widget and offering a search interface at that point via an activity. AFAIK, the Google Search widget worked that way: tapping on the "field" would bring up a dialog-themed activity that overlaid the app widget, with a real `EditText` for typing.

Android homescreen Widget - Search


Proving that a function from $R^{n+1}-{0\}$ to $S^n$ is continuous.

Question: Given the function $f: R^{n+1}- \{0\} \rightarrow S^n$ defined by $f(x)= \dfrac{x}{\Vert x\Vert}$, prove that $f(x)$ is continuous.
I have tried to use the fact that $\mathbb{R}^{n+1}-\{0\}, S^n$ are metric spaces, so that I can use an epsilon-delta proof.
However, I was not able to get to the last part of the inequality
$$ \left\Vert\frac{x}{\Vert x\Vert}-\frac{x_0}{\Vert x_0\Vert}\right\Vert.$$
I am open to another method.
Comment: Hmm, since $\mathbf{0}\in \mathbb{R}^{n+1}$, what is $f(\mathbf{0})$? Do you mean the domain to be $\mathbb{R}^{n+1}\setminus\{\mathbf{0}\}$?
Comment: Ok, what have you tried?
Comment: If you haven't done this already, take a look [here](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) for tips on how to ask a good question, and in particular look [here](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question#9960) for the importance of providing context, including perhaps your own work, what you already know about the question, and so on. As it stands, you are simply demanding that we give you a proof. Such demands attract close votes and down votes.
Comment: MPW- yes I have tried to look at the proof for $f(x)=\frac{1}{x}, \mathbb{R}-\{0\} \rightarrow S^1$. However, this proof does not translate for $n \geq 1$
Answer: Scalar multiplication is continuous as a map $s: \Bbb R \times \Bbb R^{n+1} \to \Bbb R^{n+1}, s(t,x)=t \cdot x$. This follows by inequalities like
$\|t\cdot x - t'\cdot x'\|  =\|(t\cdot x - t'\cdot x) + (t' \cdot x - t' \cdot x)\| \le |t-t'| \cdot \|x\| + |t'|\|x- x'\|$, from which we can show that whenever $t_n \to t_0$ in $\Bbb R$ and $x_n \to x_0$ in $\Bbb R^{n+1}$ we also have $t_n \cdot x_n \to t_0 \cdot x_0$ in $\Bbb R^{n+1}$ as well.
Also the norm map is continuous from $\Bbb R^{n+1}$ to $\Bbb R$ so if $x_n \to x_0$ in $\Bbb R^{n+1}\setminus \{0\}$, we have that $\|x_n\| \to \|x_0\|$ and as $g(x)=\frac{1}{x}$ is continuous from $(0,\infty)$ to $\Bbb R$, we also have $\frac{1}{\|x_n\|} \to \frac{1}{\|x_0\|}$ and then applying the first fact about scalar multiplication, $f(x_n) = \frac{x_n}{\|x_n\|} = \frac{1}{\|x_n\|} \cdot x_n \to \frac{1}{\|x_0\|} \cdot x_0 = \frac{x_0}{\|x_0\|} =f(x_0)$. QED.
We don't need sequences (but they suffice), and can also write $f$ as a  composition of continuous maps instead. But that's the basic idea: norm, and scalar multiplication on $\Bbb R^{n+1}$ and inversion on the reals are all continuous and $f$ is a combination of these operations.
Comment: Thanks I see, nice use of composition of functions.


Home wireless lock

Question: How can I improve my home with a kind of front door lock that would act like those car that can unlock when it receive signal of the key in your pant?
My goal would be to keep my keys in my pant without having to use them everytime I am near of the door.
What is your suggestion?
Comment: How about a small RFID tag implanted under the skin, then install a reader hooked up to an actuator to unlock the door. Then every time you walked near the door it would just unlock automatically, no need to carry keys!
Comment: It sounds like you want a proximity sensor, so you don't even have to push a button.
Comment: If you do this, make sure you don't leave your keys/phone near the door when you get home.
Comment: Yeah you are right, I usually keep them in my pocket all the time. And this is why I would need a small range. 1 or 2 meters would be perfect.
Answer: Here is a device that allows you to unlock the door via Bluetooth.
Here is a home-brew device built by an electronics enthusiast.
A while ago I heard about this and i really wanted to do it with my house as well.
In terms of security, it is secure as long as you have your phone with you and nobody can hack the signal. You pair with the Bluetooth lock once using a strong password, then on each sync it checks the phones MAC address and Password. This makes it difficult to spoof the key (but a strong password is still important).
Some more references
http://www.labnol.org/gadgets/unlock-car-door-with-mobile-phone/4892/
http://www.ohgizmo.com/2009/05/21/use-bluetooth-signals-to-open-your-garage-door/
Answer: You can find this one Morning Industry Brass Remote-Controlled Keyless Entry Knob, at Home Depot for $112.00.

Description:
Never worry about losing keys or
fumbling around with door locks again
with the Morning Industries Brass
Remote-Controlled Keyless Entry Knob.
This door knob utilizes
radio-frequency technology to open and
comes with a pair of remote controls
that fit conveniently on key chains.

Keyless door lock allows remote-control entry
Brass finish
Supports usage with up to 15 different remote controls
Auto-lock function re-locks the knob automatically 10 seconds after
every unlock
Anti-scan code-hopping technology prevents intruders from hacking into
the lock's radio frequency
Distinct audible tones provide notifications for locking, unlocking,
jams and low battery
Installation involves no wiring
Includes 2 keychain remote controls, 2 keys for emergency use and
an adjustable backset
MFG Brand Name : Morning Industry
MFG Model # : 51891
MFG Part # : 51891

This seems to be exactly what you are looking for. The installation does not seem to be any more difficult than the installation of a traditional lock, so it should be a very DIY friendly project.
NOTICE: I have never used this product, so I can not encourage nor endorse it's use.  Use at your own risk.
Comment: This is what I want :)
Comment: I would be very carefull with these locks! The remote sends a signal via 900Mhz that anybody can intercept and save (like a car remote) then easy to get into your house if somebody knows how!!! And.. they dont even need to get your signal becuase they can use a signal generator to brute force the lock with spam signals.. and poof- open. For BEST securioty you need 2 way authentication-- like the bluetooth MAC ADRESS challenges PASSWORD.
Comment: @ppumkin: maybe so, but it does say it has "Anti-scan code-hopping technology" to prevent intruders from hacking the frequency.  I'm not saying this is the most secure system, just showing the OP that there are systems available that do what they want.
Comment: Nice thing about this is that you have to actually push the button.  I don't like the idea of the door unlocking every time I walk near it, particularly if you're going to the door to investigate a possible intruder with your phone or keys in your hand.
Comment: I am search something that will unlock without having to press anything. That defeat the purpose if I have to go in my pocket getting the remote. What I search is something that when I am under 1 or 2 meters that it unlock.
Comment: @Daok: They have what you describe in some vehicles, so I would guess a home version is not too far off.  I cannot find any products on the web that match all your requirements, most proximity locks require a "fob" or "smart card" and only have a read distance of an inch or so.
Answer: I have found a website that use "RFID". Never hear about it but it seems to be a solution.
Here is the link http://www.instructables.com/id/Arduino-RFID-Door-Lock/
Answer: Your big-box Home Depot-like store sells keyless entries that work just like your car locks.
Comment: Do you have a link because I can't find them.
Answer: Here's something from Kwikset.  Not sure if it has a keychain remote though.  Just DAGS for "wireless door lock home" and I'm sure you'll get all kinds of results.
Comment: When I type that on Google I just get stuff that let me open my door from internet. I want something like for car. Something that just let me open it when I am under 1 or 2 meters.
Comment: Really deserves a minus.. as not on topic..

Home wireless lock


Assigning column in a df based on a condition from a different df

Question: Probably a simple problem, but I am struggling to get my head around it as a relative beginner. I have two dfs, of which df1 and df 2 are subsets:
<code>#df1
ID1 = c("1","2","3","4","5")
DisDate1 = c("2010-05-11","2010-07-16","2010-10-25","2010-12-04","2011-03-18")
ReAdLim1 = c("2010-06-10","2010-08-15","2010-10-24","2011-01-03","2011-04-17")
df1 = data.frame(ID1,DisDate1,ReAdLim1)

#df2
ID2 = c("1","1","1","2","2","2")
DisDate2 = c("2010-09-19","2010-11-16","2011-04-17","2011-06-04","2011-10-11","2011-12-04")
df2 = data.frame(ID2,DisDate2)
</code>
I simply want to create an additional column in df2 where the ReAdLim1 date from df1 is assigned to each unique ID to create what is depicted by df3:
<code>#df3
ID3 = c("1","1","1","2","2","2")
DisDate3 = c("2010-09-19","2010-11-16","2011-04-17","2011-06-04","2011-10-11","2011-12-04")
ReAdLim3 = c("2010-06-10","2010-06-10","2010-06-10","2010-08-15","2010-08-15","2010-08-15")
df3 = data.frame(ID3,DisDate3,ReAdLim3)
</code>
Any suggestions would be greatly appreciated.
Answer: Is this what you're looking for?
<code>merge(df2, df1, by.x = 'ID2', by.y = 'ID1')
</code>
Comment: Thanks for the merge suggestion. Yes that should work, although when scaled up to a larger df (26000 rows, 90 cols) I will have to code around it a little bit.
Comment: If you're looking for speed, I'd explore the `data.table` package or the `%l%` function in the `qdap` package if you're just looking to return one column


OpenTTD Loading & Unloading times

Question: I'm trying to calculate the time for a train to load at a station.
This website
states that a full load and unload cycle takes (capacity * 2 / load_amount) days
So a full load would be (capacity / load_amount)
It also states that a "load amount" is loaded in these times:

Trains: 40 ticks
RV: 20 ticks
Ships: 10 ticks
Aircraft: 20 ticks

Using these formulas, for a monorail train with 108 passenger carriages (5076 passengers) and 10 mail carriages (370 bags of mail), it would take 5446/40 days = 136 days.
(Note: The train is on a station length 64, and the train is length 60)
However, the train actually only takes around 10 days to fully load, very different to the calculated value.
So my overall question: What is the correct formula to use to calculate load times?
Comment: I would very much appreciate any ideas that might lead to a solution, even if they're not a full answer
Answer: You're mis-interpreting "load amount".
load_amount is an internal attribute of a wagon or vehicle that determines how big a chunk of cargo is loaded during each cycle.  For example, a train wagon with a load_amount of 16 will load 16 units of cargo every 40 ticks.  If the wagon has a capacity of 40 units, it'll take 100 ticks to fully load.
If a train fully fits into a station, each wagon will load independently, so the total loading time will be the loading time of the slowest wagon in the train.

OpenTTD Loading & Unloading times


React - Context

Question: I have a problem with React - Context.
For now I just want to pass the value'hello' but unfortunately it does not find the value.
This is my Context:
import React from 'react';

const MovieContext = React.createContext();

class MovieProvider extends React.Component{

    constructor(props){
        super(props)

        this.state={

        };
    };

    render() {
        return (
            <MovieContext.Provider value={'hello'}>
                {this.props.children}
            </MovieContext.Provider>
         );
    }
}

export {MovieProvider,  MovieContext};

Here is my Layout which collects my Provider:
import React from 'react';
import Header from './Header';
import { MovieProvider } from './context';

class Layout extends React.Component{
    render(){
        return(

            <MovieProvider>
                <>

                    {this.props.children}
                </>

            </MovieProvider>

        )
    }
}

export default Layout;

And here is my index which should display 'hello':
import React from 'react';
import Layout from '../components/Layout';
import {MovieContext} from '../components/context';

class Index extends React.Component{

    static contextType = MovieContext

    render(){

        const value = this.context;
        console.log(value)
        return(

                <Layout>
                    {value}

Home Page

                </Layout>

        )
    }
}

export default Index;

I tried to put the provider in my Index Component but unfortunately it doesn't work either. Mostly I followed the doc and I thought I had done everything well haha
Comment: its easier with hooks, just fyi
Answer: The value is not valid in Index component, as according to Context API, you have to use Context.Consumer in any Context.Provider's child in order to reference the context's value.

When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree. - Context API

class Layout extends React.Component {
  render() {
    return (
      <MovieProvider>
        <MovieContext.Consumer>
          {value => (
            <>
              {value}

Home Page

            </>
          )}
        </MovieContext.Consumer>
      </MovieProvider>
    );
  }
}

Comment: I saw a video where the person doesn't immediately use the Consumer and it worked, weird.
Thanks again :)
Comment: You **don't have to** use `Consumer` **immediately**, you can use it in any child (depth) within the provider tree as mentioned
Comment: Ok, Thank you :)

React - Context


how to display an image instead of the file field in yii

Question: In yii i have a echo CHtml::activeFileField($model, 'image'); . it displays the usual <input type="field ... DOM object . how can i display an image instead of the file input field . so when clicked the user can choose a file ?
is there a way to do it via yii ? or jquery in yii ? Thank you
Answer: You can do it very easy via css: input[type="file"]{opacity:0;} and the label next to it have an image background witch you can position absolute over it. Be sure to have set an width and height for your input so it not exceeds your label size
Answer: It can do what you are looking.
echo CHtml::image($src,$alt = '',$htmlOptions = array());

But for input file you have to make an input field to upload a file.


after create new application annotations does not work

Question: I new in Play and Scala/Java.
I install typesafe-stack from typesafe.com and create new project for test: g8 typesafehub/play-scala
After I create Java annotation TestAnn.java:
package ann;

import play.mvc.With;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@With(TestAnnAction.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
@Inherited
public @interface TestAnn {

}

and TestAnnAction.javaenter code here:
package ann;

import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Action;

public class TestAnnAction extends Action<TestAnn> {
    @Override
    public Result call(Http.Context ctx) throws Throwable
    {
        System.out.println("called");

        return null;
    }
}

And add this to Application.scala controller:
package controllers

import play.api._
import play.api.mvc._

import ann.TestAnn

object Application extends Controller {

   @TestAnn
   def index = Action {
     Ok(views.html.index("Your new application is ready."))
   }

}

Then i run application by "sbt run", but I do not saw string "called" in terminal after request index page. No errors and no results.
What I do wrong?
Update: if I create java controller all works fine.
Application.java
    package controllers;
import play.*;
import play.mvc.*;

import views.html.*;

import ann.TestAnn;

public class Application extends Controller {

  @TestAnn
  public static Result index() {
    return ok(index.render("Your new application is ready."));
  }
}

Answer: You should call delegate.call(ctx) instead of just returning null.
public class TestAnnAction extends Action<TestAnn> {
    @Override
    public Result call(Http.Context ctx) throws Throwable
    {
        System.out.println("called");
        return delegate.call(ctx);
    }
}


How to fix a glitch for the Oblivion walker trophy in skyrim?

Question: I have all the Daedric artifacts and I got all of them in my inventory and everything but for some reason the game isn't giving me the trophy is this fixable? I can't platinum the game, like I would have liked  to, with out this one. Did I do something wrong?
Comment: @DanmakuGrazer I'm not so sure if it's a dupe, and same could be said about the question that was duped by the one you linked. If the OP really belives it's a bug it can't be a dupe as theo ther questions don't mention bugfixes at all. Then again, the OP could be wrong
Comment: @Oak OP asked the same question twice instead of editing the first to include more information.
Comment: Did not notice that @DanmakuGrazer, thanks mate
Answer: It has been known to be a bug. Some of the things you can check/try, source
1.

When you did the Hircine quest, did you get both the ring and the Savior's Hide? Next time around, get both. It's a glitch and only with both of those artifacts plus others do you get the Oblivion walker achievement. If you have, however, the unofficial patch, that particular glitch is fixed, but the Oblivion Walker achievement won't trigger.

2.

I think if you run a unofficial texture pack it has problems with the Ring of Hircine quest, so I've read on these forums. Search for it on the board cos I'm sure there was a similiar thread about not being able to get the achievement.


Why is there a 1/2-inch hole drilled in my heater exhaust?

Question: I have a Carrier high efficiency furnace which uses 2-inch PVC pipes to pull in combustion air from outside and exhaust the combustion gasses back outside (through a concentric vent, but that's not really important.)
It seems that the installer drilled a 0.5" hole in the exhaust pipe about 2 feet up from the heater.

When the heater is running, you can feel air coming out of this hole, it is warm and moist, and it smells like you would expect natural gas exhaust to smell. (Before you ask, yes, there IS a carbon monoxide detector right outside the door of the room, and no, it does not detect anything.)
The issue I have is that there is a lot of water vapor present in the exhaust, which condenses on the inside of the pipe and then drips out through the hole, collecting in a large puddle on the floor. (If you look closely at the picture, you can see the trail of water below the hole.)
(I notice that my neighbors always have clouds of water vapor coming out of their exhaust on cold days, but I never do. As far as I can tell, the reason for this is that their exhaust pipe is only a few feet long since their unit is right next to an exterior wall, while my pipe is 30 feet long so the water has space/time to condense.)
In any case, the puddle is annoying and messy, and the room is too narrow to just put a bucket there -- it would obstruct the walkway to the washer/dryer.
Right below the exhaust pipe (not shown in the picture) is the condensate pump for the heater drain and humidifier drain. (For some reason, they piped the AC drain directly to outside but the other two drains to a pump which goes to the sink.)

Am I correct that condensation in such a long pipe is normal?
If not, what is wrong with my furnace?
If I seal up the hole so the condensation has to drain back through the unit and out the actual furnace drain, will that cause any damage?
If I can't seal the hole, is there a simple way to catch the moisture at the hole and direct it into the condensate pump instead of onto the floor?
Comment: I've seen holes like that for efficiency measurements. They're usually filled with silicone caulk. Perhaps the plug fell out.
Comment: Call the installer and ask him if the hole is intended, and necessary, and if so what's going wrong.
Comment: If that room is used for laundry, it should have a CO alarm in that room.  I would be uncomfortable with only one alarm in this situation.
Answer: The short answer is this: it makes no sense for a sealed combustion appliance to intentionally leak exhaust gases to the building interior. There was probably a legitimate reason for the hole to be drilled -- maybe there was a need to measure the pressure inside that pipe to assure the installation was okay, or as part of the troubleshooting of a "blocked exhaust" error code thrown by the furnace controls -- it's difficult to be sure. In any case it seems reasonable to seal the hole.
I can't speak for your specific appliance, but in general, yes it's normal to have condensate when longer exhaust lengths are involved. The liquid may flow to the exterior or back to the appliance depending on the slope of the exhaust. Some appliances are designed to receive and drain the condensate; others are not (but a condensate catchment accessory may be available). Consult the appliance installation instructions for details.
You mentioned both an air conditioner drain and a heater drain. Does the heater drain originate in the inducer fan housing? If so it sounds like your furnace is equipped to deal with condensate. I'd verify that the drain is working, maybe by running a few ounces of water in through that exhaust hole and verifying that most of it flows out the drain. Then seal up the hole in the exhaust pipe.
Exhaust condensate is somewhat corrosive (acidic), so it should be handled with materials designed to deal with it. A puddle of condensate on the floor is Less Ideal.
Comment: I had an HVAC technician here for an unrelated reason. He saw the bucket of water on the floor, saw the hole above it, and immediately said "that is for an exhaust gas analyzer, but there should be a plug in it!" He put in a plug, and the dripping is gone.
Comment: @MosheKatz: that looks like an Answer to me!
Comment: @keshlam I considered it a confirmation that Greg's answer is correct, that's why I didn't post it as a separate answer.
Comment: @Mazura They did not charge me anything extra for using the analyzer when they were replacing the gas valve and were making sure it was adjusted properly.
Comment: Yes, the heater drain comes from the inducer housing.I know that it handles the condensate properly, because I can occasionally see the condensate pump running. I suspect that if I close up the hole the pump will just have to run more frequently, but the question then is really just if there is a continuous downslope from the exhaust to the drain. I will see if the manual says anything about that.
Comment: "A manufacturer's representative who sells combustion analyzers told me he urges contractors to use an analyzer on every call and charge a small fee for the use. He calls it an emission test fee and further suggests you give a printout of the readings to the customer with the service report." https://www.pmmag.com/articles/100856-should-you-own-a-combustion-analyzer See also, *how to charge your customers more money*
Comment: Yep. At least in my area, it's simply a tool used in fine-tuning the burner, just as an exhaust sniffer can be used when fine-tuning an auto engine to cleanest combustion. Or there may be places where that is indeed mandated and charged for, just as the exhaust test is sometimes part of a mandated yearly inspection. Could it be abused? Sure. So can a screwdriver.