text:
Q: How to build a homepage android application? I would like to know how this homepage from Google Docs app is build ?
Is there Multiple relative layout to display inline buttons?
And what about the tab bar at the top ?
Image :

A: I'd say that is made of:
1 Header : Horizontal LinearLayout
2 Lines : 2 Horizontal LinearLayouts included into one Vertical LinearLayout
<LinearLayout
    android:id="@+id/root"
    android:orientation="vertical">

    <LinearLayout
    android:id="@+id/header_layout"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:background="@drawable/header_gradient" >

        <LinearLayout
    android:id="@+id/header_layout_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_marginLeft="10dp" >

        <ImageView
            android:id="@+id/header_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp" />

        <TextView
        android:id="@+id/header_title"
        android:text="Docs"
        android:textSize="20dp" />

            </LinearLayout>

            <LinearLayout
        android:id="@+id/header_layout_add"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical|right" >

            <ImageView
                android:id="@+id/header_add"
                android:src="@drawable/add"
                android:layout_marginRight="10dp" />

            <ImageView
                android:id="@+id/header_search"
                android:src="@drawable/search"
                android:layout_marginRight="10dp" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/line_1"
        android:orientation="horizontal">

        <ImageView android:id="image_1" />
        <ImageView android:id="image_2" />
        <ImageView android:id="image_3" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/line_2"
        android:orientation="horizontal">

        <ImageView android:id="image_4" />
        <ImageView android:id="image_5" />
        <ImageView android:id="image_6" />

    </LinearLayout>

</LinearLayout>


text:
Q: Upgraded react native version After upgrading my react native version from 0.63.3 to latest version, I am getting the following errors:
> Could not resolve all files for configuration ':classpath'.
   > Could not find com.facebook.react:react-native-gradle-plugin:.
     Required by:
         project :

Following are the dependencies in my build.gradle file:
   dependencies {
        classpath("com.android.tools.build:gradle:7.0.4")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath("de.undercouch:gradle-download-task:4.1.2")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

Would anyone be able to explain this to me? It would be greatly appreciated if you could help!

A: The github issue that @RamaProg suggested does provide some insight but it was in the context of building react-native from source. And i believe that issue was created before 0.68.1 was a stable public release.
Following the upgrade guide here: https://react-native-community.github.io/upgrade-helper/?from=0.67.4&to=0.68.1
Suggests the following addititons to settings.gradle:
includeBuild('../node_modules/react-native-gradle-plugin')
if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") {
    include(":ReactAndroid")
    project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid')
}

And this change is what resolved the issue for me.

A: I got this issue recently after upgrading to v68+.
It was fixed when I added react-native-gradle-plugin package manually.
yarn add react-native-gradle-plugin
This package was not included in upgrade helper.

A: According to this RN issue: https://github.com/facebook/react-native/issues/33067
You issue might get fixed by going to your settings.gradle and replacing:
includeBuild('../node_modules/react-native/packages/react-native-gradle-plugin')

with:
includeBuild('../node_modules/react-native/packages/react-native-gradle-plugin') {
    dependencySubstitution {
        substitute(module("com.facebook.react:react-native-gradle-plugin")).using(project(":"))
    }
}

The problem is that you're using an older revision of the repo, therefore the wiki is updated to use the latest main. Building from source from different revision is generally not supported (i.e. you're on your own) as there are those kinds of incompatibilities, and we can't provide instructions for all the possible RN versions/branches.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails+Facebox: pop-up-window doesn't work I followed the source code form the rails3-devise-bootstrap-example to get my devise-login-page (that normally - without AJAX - works fine) in a popup window.
When I click on the login link nothing happens. The logfile tells me
Started GET "/facebox/fb_login" for 127.0.0.1 at 2014-01-09 19:15:0
  Processing by FaceboxController#fb_login as JS
  Rendered devise/shared/_links.erb (3.0ms)
  Rendered devise/sessions/_new.html.erb (1155.0ms)
  Rendered facebox/fb_login.js.erb (1251.0ms)
Completed 200 OK in 1509ms (Views: 1508.0ms | ActiveRecord: 0.0ms)

But no login-pop-up-window appears.
Here is the login link in my index.html.erb file
<%= link_to 'Login', fb_login_path, :remote => true %>

That starts my fb_login.js file
$.facebox('<%= escape_javascript(render :partial => 'devise/sessions/new') %>')

and should open _new.html.erb that looks like this:
<%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>

    <%= f.input :email, :required => false, :autofocus => true %>
    <%= f.input :password, :required => false %>
    <%= f.input :remember_me, :as => :boolean if devise_mapping.rememberable? %>

    <%= f.button :submit, "Sign in" %>

<% end %>

<%= render "devise/shared/links" %>

but it doesn't. What went wrong?

A: I got the answer by myself . Under assets/javascripts I had to define
jQuery ->
  $('a[rel*=facebox]').facebox()

# facebox - make modal

$(document).bind "loading.facebox", ->
  $(document).unbind "keydown.facebox"
  $("#facebox_overlay").unbind "click"

in a js.coffee file.


text:
Q: Magento 2 - Add Dynamic fields in Customer Account Information I want to add multiple emails into customers account information as per below screen-shot.

Any help would be appreciated.

A: Add dynamic custom field in customer edit/create form

Create file : [Namespace]/[Module]/view/base/ui_component/customer_form.xml
<?xml version="1.0" encoding="UTF-8"?>
    <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <fieldset name="customer">
            <dynamicRows name="multiple_emails">
                <settings>
                    <addButtonLabel translate="true">Add More</addButtonLabel>
                    <additionalClasses>
                        <class name="admin__field-wide">true</class>
                    </additionalClasses>
                    <componentType>dynamicRows</componentType>
                </settings>
                <container name="record" component="Magento_Ui/js/dynamic-rows/record">
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="isTemplate" xsi:type="boolean">true</item>
                            <item name="is_collection" xsi:type="boolean">true</item>
                            <item name="componentType" xsi:type="string">container</item>
                            <item name="positionProvider" xsi:type="string">attribute_options.position</item>
                        </item>
                    </argument>
                    <field name="emja_more_emails" sortOrder="10" formElement="input">
                        <argument name="data" xsi:type="array">
                            <item name="config" xsi:type="array">
                                <item name="source" xsi:type="string">customer</item>
                            </item>
                        </argument>
                        <settings>
                            Email
                            <dataType>text</dataType>
                            <dataScope>emails</dataScope>
                        </settings>
                    </field>
                    <field name="apply_to" formElement="multiselect"  sortOrder="20">
                        <settings>
                            <dataType>text</dataType>
                            Apply To
                            <disabled>false</disabled>
                            <dataScope>apply_to</dataScope>
                        </settings>
                         <formElements>
                            <multiselect>
                                <settings>
                                    <options class="[Namespace]\[Module]\Model\EmailTemplates"/>
                                </settings>
                            </multiselect>
                        </formElements>
                    </field>
                    <actionDelete  sortOrder="30">
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="componentType" xsi:type="string">actionDelete</item>
                            <item name="dataType" xsi:type="string">text</item>
                            <item name="fit" xsi:type="boolean">false</item>
                            <item name="label" xsi:type="string">Actions</item>
                            <item name="sortOrder" xsi:type="string">500</item>
                            <item name="additionalClasses" xsi:type="string">data-grid-actions-cell</item>
                            <item name="template" xsi:type="string">Magento_Backend/dynamic-rows/cells/action-delete</item>
                        </item>
                    </argument>
                </actionDelete>
                </container>
            </dynamicRows>

    </fieldset>
    </form>

Create di file for value selected in dynamic rows
[Namespace]/[Module]/etc/adminhtml/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Model\Customer\DataProvider">
        <plugin name="add-size-grouped-products" type="[Namespace]\[Module]\Model\Customer\DataProvider" sortOrder="5" />
    </type>
</config>

[Namespace]/[Module]/Model/Customer/DataProvider.php
<?php
namespace [Namespace]\[Module]\Model\Customer;

class DataProvider
{
    public function afterGetData(\Magento\Customer\Model\Customer\DataProvider $subject, $result)
    {

    if($result){
        $customer_id = key($result);
        $customer_data =  $result[$customer_id]['customer'];

        if($customer_data){
            if(array_key_exists('emja_more_emails',$customer_data)){
                $emja_more_emails = unserialize($customer_data['emja_more_emails']);
                if(count($emja_more_emails) > 0){
                    foreach ($emja_more_emails as  $value) {
                        //$logger->info($value);
                        $result[$customer_id]['customer']['multiple_emails']['multiple_emails'][] = $value;
                    }
                }
            }
        }

    }

        return $result;
    }

}

Create event for save data to customer
[Namespace]/[Module]/etc/adminhtml/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_save_before">
        <observer name="multiple_emails_save" instance="[Namespace]\[Module]\Observer\AddMultipleEmails" />
    </event>
</config>

[Namespace]/[Module]/Observer/AddMultipleEmails.php
<?php

namespace [Namespace]\[Module]\Observer;

class AddMultipleEmails implements \Magento\Framework\Event\ObserverInterface
{

     protected $_request;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request
    ) {
        $this->_request = $request;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getCustomer();
        $data = $this->_request->getParams();

        if($data){
            $customerData = $data['customer'];
            $serialize_emails = '';
            if(array_key_exists('multiple_emails',$customerData)){
                $serialize_emails =  serialize($data['customer']['multiple_emails']['multiple_emails']);

            }
            $customer->setEmjaMoreEmails($serialize_emails);
        }

    }
}


text:
Q: using SOAP web service for implementing login for iPhone sdk? it will be greatful  if you help me with this issue, i am a beginner on this platform and this is the first time am using SOAP service. , and i need to implement a login page. i don't know how to use the datas from the service.
POST /soap.asmx HTTP/1.1
Host: www.bids4all.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.bids4all.com/Login"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:xsd="http://www.w3.org/2001/XMLSchema"    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.bids4all.com" xmlns:types="http://www.bids4all.com/encodedTypes"   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <tns:Login>
     <Email xsi:type="xsd:string">string</Email>
     <Password xsi:type="xsd:string">string</Password>
    </tns:Login>
  </soap:Body>
</soap:Envelope>
HTTP/1.1 200 OK
 Content-Type: text/xml; charset=utf-8
  Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.bids4all.com" xmlns:types="http://www.bids4all.com/encodedTypes" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <tns:LoginResponse>
      <LoginResult xsi:type="xsd:boolean">boolean</LoginResult>
    </tns:LoginResponse>
  </soap:Body>
</soap:Envelope>

will you please help me with some cods? thank you in advance

A: There are 2 good tools to generate SOAP client for iOS. They are SudzC and wsdl2objc project. Both of them supply example codes.
You can either use one of them or generate your own request and post it by NSURLConnection.
Hope it helps...


text:
Q: Disable a  using JQuery

  Close

I am trying to make this
 appear disabled. Actually this
 tag will display like a button by CSS...
How do I make this
 tag appear disabled in JQuery?

A: Best way to create an element that looks like a disabled button is to create a disabled button. Do you know that <button> tag allows inserting complex html inside it?

A: if you use this P for a click event, and you mean "disable" to stop the event.
then you can unbind the event
    $("p").unbind("click")
or if you mean to lower the opacity as if it is disabled you can set the opacity via
    $("p").css("opacity",0.7),
or you can animate the opacity via
animate
    $("p").fadeTo("slow", 0.7);
This this solve the problem?

A: You need to create a disabled style in CSS and then apply it with jQuery

A: you can use $('p').remove() or $('p').empty() if by disabled you mean disappear.


text:
Q: при клике на элемент получить координаты клика Доброго времени!
Есть код:

function showareabtn(el) {

  el.stopPropagation();
  console.log(el);
  var x = el.originalEvent.layerX;
  var y = el.originalEvent.layerY;

  alert(x + " x " + y);

}
.areacol {
  width: 500px;
  height: 300px;
  overflow: hidden;
  background: #F00;
}

Скрипт должен выводить координаты клика, но он выдает ошибку, подскажите пожалуйста, что не так?

A: Нужно использовать не элемент, а событие event

function showareabtn(el, event) {

  event.stopPropagation();
  //console.log(el);
  var x = event.layerX;
  var y = event.layerY;

  alert(x + " x " + y);

}
.areacol {
  width: 500px;
  height: 300px;
  overflow: hidden;
  background: #F00;
}

A:
спасибо, но в силу специфики мне нужно что бы запускался скрипт именно
  через onclick и функцию, как нибудь можно это адаптировать под такое
  событие?

Вот так:

function showareabtn(el) {

  el.stopPropagation();

  var x = el.layerX;
  var y = el.layerY;

  alert(x + " x " + y);

}
.areacol {
  width: 500px;
  height: 300px;
  overflow: hidden;
  background: #F00;
}

A: В своей функции вы работаете с элементом, по которому кликнули, а надо с объектом события:

function showareabtn(e) {
  var e = $.Event(e);
  e.stopPropagation();
  console.log(e);
  var x = e.originalEvent.layerX;
  var y = e.originalEvent.layerY;

  alert(x + " x " + y);
}
.areacol {
  width: 500px;
  height: 300px;
  overflow: hidden;
  background: #F00;
}


text:
Q: Choice of Unit Cell on Band Diagram (Brillouin Zone Folding) I am looking at photonic band diagrams specifically, but my question relates to band diagrams in general.
For a honeycomb lattice, I can pick a (primitive) rhombic unit cell or a hexagonal unit cell. This is the case for the Hu and Wu paper:

*

*If I have set up my rhombic unit cell such that it is the same
geometry as my hexagonal unit cell and I sweep across the same
($k_x, k_y$) for my photonic band diagram, I should get the same photonic band diagram, right? (Just checking, I plotted it and got
something different so I think I did something wrong).

The band diagram of the hexagonal unit cell looks like this (which looked fine when I reproduced this one):

*If I use the correct reciprocal lattice vectors for my Brilouin zone sweep for each of the different unit cells, I should get different band diagrams (Eg in Hu and Wu paper where band crossing goes from K and K' points in rhombic graph to $\Gamma$ point in hexagonal graph due to Brillouin Zone folding). Can I derive or infer the photonic band diagram of the rhombic unit cell from the band diagram of the hexagonal unit cell?
A different example is in this paper where the unit cell is doubled:

*

*The band diagram of the primitive unit cell is on the left and the
doubled unit cell is on the right. The Brillouin zone for the
doubled unit cell is half the Brillouin zone of the original, so is
it just cutting the original band diagram in half and reflecting it (or is this horribly wrong)?
So if a hexagonal unit cell is three rhombic unit cells... do I cut
the photonic band diagrams in thirds or something?

This question looked similar but not sure how to apply that answer to the band diagram in Hu and Wu paper.

A: I recently encountered a similar phenomenon with body-centered cubic (BCC) and (simple cubic) SC lattices.  I think what I figured out there could answer your first question.
The figures below are photonic band diagrams of a same gyroid structure, each showing six bands.  The 1st figure use BCC cell, direction sequence N-P-G-N-H-G (G for Gamma), reproducing Fig 6 in this review by Dolan et al.  The 2nd figure use SC cell, direction sequence G-R-M-G-X-M, reproducing Fig 1a in this paper by Maldovan et al.

Not that there is a correspondence between the Brillouin zones of BCC and SC, namely P=R, N=M, H=2X.  So after changing the cell, H folds onto G by a reflection in X.  I have colored corresponding segments of the diagrams, which should facilitate the visualization of this folding.  Onto the G-R segment of the 2nd figure is also folded a P-H segment from BCC, which is unfortunately not shown in the 1st figure.  Also because of the folding, the 6 bands in the second figure correspond to the first 3 bands in the 1st figure, so one should not be surprised by the apparent difference in the "density" of bands.
I hope this helps you understanding Hexagonal lattice.  The diagrams are expected to be different, but should be related in a similar way as I show here.  I couldn't comment more without seeing your diagrams with the two choices of cells.


text:
Q: Use ExUnit.Assertions inside macro I have written a small macro for test cases.
    defmodule ControllerTest do
      @required [:phone, :country]
      defmacro create(fields) do
        quote do
          without = length(unquote(@required) -- unquote(field)
          if without != 0 do
            Enum.map(unquote(@required), fn(field) ->
              member = Enum.member?(unquote(fields), field)
              if member == false do
                expected_error = String.to_atom(Atom.to_string(field) <> " " <> "can't be blank")
                expected = {:error, expected_error}
               assert expected == {:error, expected_error}
              end
            end)
          else
            expect = {:success, "Record created"}
            assert expect == {:success, "Record created"}
          end
        end
      end
     end

Its working fine without assert. But when I try to use assert it says assert is undefined. I have try import ExUnit.Assertions inside the module but still the same assert is undefined.
What will be the possible solution for this to use assert inside the macro?
Thanks

A: You need to add the import inside the quote before you use assert. Adding it before quote will not make assert available inside quote.
defmacro create(fields) do
  quote do
    import ExUnit.Assertions
    without = ...
    ...
  end
end

Also, your Enum.map can be simplified like this:
for field <- unquote(@required), field not in unquote(fields) do
  expected_error = String.to_atom(Atom.to_string(field) <> " " <> "can't be blank")
  expected = {:error, expected_error}
  assert expected == {:error, expected_error}
end


text:
Q: Angular routing with href does not work on android browser I'm getting puzzled by this..
I have this piece of code:
<a href=" #/products/{{product.id}}"  ng-click="customFunction()">
Where product is an object with an 'id' element.
Where customFunction adds the product in a shopping cart
Both are combined because the route in the href element permits to access a new page where the added product is customizable.
The code and the routing is working fine cross browser except on mobile phone (android at least, both chrome and native browser). On android phone only the ng-click reacts on click. But i am still able to open the web page routed by href by pressing the link and opening in a new tab :oO
my routing looks like that (app.js):
    when('/products/:productId', {
                templateUrl: 'partials/store_composition.html',
                controller: 'mainCtrl'
            })

and in the main Ctrl is called the getProduct function:
  if ($routeParams.productId != null) {
    $scope.product = $scope.store.getProduct($routeParams.productId);
}

which access the store.js file here :
store.prototype.getProduct = function (id) {
for (var i = 0; i < this.products.length; i++) {
    if (this.products[i].id== id)
        return this.products[i];
}
return null;

}
And it works fine... Except on android!! but again the link exists if long pressed for new tab :s :s
Any idea?
Update:
I am noticing that the URL in the navbar of android/chrome never changes. Contrarly of whats happening in regular browsers (an URL such as app/index.html#/products/batavia400 is updated on top)
But except for the route i have linked in my post every other routing in my app are working (with no url update just the same... :/)
SOLVED:
I actually solved the problem by adding the
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

and its the user-scalable=nothat made the trick.
The screen was slightly, really slightly zoomed by default by android, and this was creating the conflict on user's touch on the div's link.
I guess if my web designing skills were better I wouldn't have had the problem ;)

A: I actually solved the problem by adding the
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

and its the user-scalable=nothat made the trick.
The screen was slightly, really slightly zoomed by default by android, and this was creating the conflict on user's touching the div's link.


text:
Q: How to have an active label on screen? Imagine in my app I have a label representing a virtual time and I want to change this label and update the time but this time is not system time and I want to be able to change it with different speeds (like every one real second is one or two minutes in this virtual time) and I also want to be able to call some functions at specific times.
I use UIKit.
How can I do this?

A: You will find that UIKit has UILabel.  UILabel is a pretty straightforward thing to use.  You can create it programmatically and position it, or use Interface Builder to create it as part of your View Controller's layout.
Either way, to update it, simply set the text property.
You can use NSTimer to update the text with a time and scale it using some sort of multiplier.  Time calculations get tricky, so you may need to open a different question with more specifics about your time update.
Use the scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: method to have it call a method on your object, then [NSTimer invalidate]; to cancel it.


text:
Q: Efficient data structure for finding non-overlapping range containing a number a data structure to store the start and endpoint of a range.
rangename      start     end

range1          10        11

range2          20        22

range3          0         5

now if i have to find the range in which a number 'x' may exist.
What would be the efficient way of storing this in c++ ?
I'm trying to use map. but then search to find the range might be expensive ( which i'm not sure of). Suggest a good data structure.
I should be able to find whether the element is present in a range or not. The ranges should not be mix and matched and no adjacent or other bounds.
If I need to a find an element 3, it is present in range 3, But an element 12 is not present at all. Just looping through cannot be an efficient way.

A: (I have changed this answer since the asker clarified that his ranges do not overlap.)
If the set of ranges does not change, you can use a sorted vector and binary search, as suggested in ravenspoint's answer.
If the set of ranges changes over time, you might still use a sorted vector, or you might want to use a std::map.  You need to try both and see which one is faster in that case.

A: vector< pair< int>> stored sorted so you can binary search perhaps?

A: Assuming the ranges do not overlap:
Store each range in a simple structure
range {
  int low;
  int high;
  string name;
}

Store the ranges in a sorted vector, by low.
Find required range using binary search for largest low less than target.

A: just dump all the values , starting and ending into a vector or array, and then sort it. since the ranges dont overlap, once the array is sorted, you will have start, stop,start,stop,etc.. then, you could use a binary search to find the index of the vector. then its just a question of whether its odd or even
assuming, you are getting the ranges from the stream
vector<int> ranges;
int n;
while(in >> n){
    ranges.push_back(n);
}
sort(ranges.begin(),ranges.end())

int x;
cout <<"please enter a value to search for: ";
cin >> x;
int index = binary_search(x,ranges);

if(index % 2){
    cout << "The value " << x << "is in the range of "
         << ranges[index-1] << " to " <<       ranges[index] << endl;
}else{
    if(ranges[index] == x){
         cout << "The value " << x << "is in the range of "
              << ranges[index] << " to " <<       ranges[index+1] << endl;
    }
    else{
         cout << "Value " << x << " is not in any range\n";
    }
 }

where binary search would be defined as
 int binary_search(int x, vector<int>& vec, int s = 0; int f = -1){
     if(f == -1)f=vec.size();
     if(s >= f) return s;
     int n = (f-s)/2 + s;
     if(vec[n] == x)return n;
     if(vec[n] < x)return binary_search(x,vec,s,n-1);
     return binary_search(x,vec,n+1,f);
 }

hopefully I didn't screw up the binary search, but it is designed in such a way, that if the value is not found, the index of the next largest value is returned.

A: why not use a B+ tree?
With B+ tree, the fan-out would be small and search would be fast too.


text:
Q: TFS Team Project Portal permissions I have added users to Contributor Group in Team Project, but they are not able access the Team Project Portal. What could be the problem?

A: You have to manage permissions to TFS, Sharepoint and Reporting Services separately. This means that adding people to TFS groups does not automatically add them to Sharepoint and reporting services groups.
Please check below MSDN library for information on how to add users to Share Point Portal:
http://msdn.microsoft.com/en-us/library/bb558971.aspx
You can also use TFS Administration tool, which provides the options to add users to TFS, Sharepoint and Reporting Services from single place.


text:
Q: Adding a class to a checkbox using .each Jquery Looking to add a class to each span wrapping a checkbox, so I can change the background colour of each one when the checkbox is checked.
I have the js written. But cant seem to get the Jquery to affect each item.
Also is this the best way of creating this effect?
https://jsfiddle.net/L2m9b3wj/
JQUERY:
$('.product-select input').change(function(){
            if($(this).is(":checked")) {
                $('.product-select .wpcf7-list-item').addClass("checkon");
            } else {
                $('.product-select .wpcf7-list-item').removeClass("checkon");
            }
        });

CSS:
.product-select {
    .wpcf7-list-item {
        width:30%;
        height:200px;
        background:red;
        display:inline-block;
        margin:0px auto;
    }

    .checkon {
        background:blue;
    }

}

HTML:

     <input type="checkbox" name="checkbox-328[]" value="Flexible Benefits">Flexible Benefits<input type="checkbox" name="checkbox-328[]" value="Holiday & Absence">Holiday & Absence<input type="checkbox" name="checkbox-328[]" value="Employee Comms">Employee Comms<input type="checkbox" name="checkbox-328[]" value="Custom Build">Custom Build

A:

$('.product-select input').change(function() {
  //get all the spans that are parents for the checkbox
  var $parentSpans = $(this).parents('span');

  if (this.checked) {
    $parentSpans.addClass('checkon');
  } else {
    $parentSpans.removeClass('checkon');
  }
});
.product-select .wpcf7-list-item {
  width: 30%;
  height: 200px;
  background: red;
  display: inline-block;
  margin: 0px auto;
}

.product-select .checkon {
  background-color: blue;
}

  <input type="checkbox" name="checkbox-328[]" value="Flexible Benefits">Flexible Benefits
  <input type="checkbox" name="checkbox-328[]" value="Holiday & Absence">Holiday & Absence<input type="checkbox" name="checkbox-328[]" value="Employee Comms">Employee Comms
  <input type="checkbox" name="checkbox-328[]" value="Custom Build">Custom Build

A: .closest('span.wpcf7-list-item') looks upwards the dom tree for the first parent matching the selector closest

$('.product-select input').change(function() {
  if ($(this).is(":checked")) {
    $(this).closest('span.wpcf7-list-item').addClass("checkon");
  } else {
    $(this).closest('span.wpcf7-list-item').removeClass("checkon");
  }
});
.product-select .wpcf7-list-item {
  width: 30%;
  height: 200px;
  background: red;
  display: inline-block;
  margin: 0px auto;
}

.product-select .checkon {
  background: blue;
}

  <input type="checkbox" name="checkbox-328[]" value="Flexible Benefits">Flexible Benefits
  <input type="checkbox" name="checkbox-328[]" value="Holiday & Absence">Holiday & Absence<input type="checkbox" name="checkbox-328[]" value="Employee Comms">Employee Comms
    <input type="checkbox" name="checkbox-328[]" value="Custom Build">Custom Build

A: I'd do it this way
$('.product-select input').change(function(){
    $('.product-select input:checked').parent().removeClass('checkon').addClass('checkon');
    $('.product-select input').not(':checked').parent().removeClass('checkon');
});

I remove() and then add to avoid duplicates.


text:
Q: Add content to cell when user clicks it I have a functionality in a JTable, that when user clicks the cell, it removes certain character in it (like when there's content - Hello, when user clicks it, it shows Hello). When it's no longer edited, it shows - Hello again.
My problem is that when some cell is selected (but not being edited yet) and I start typing  Hi, it doesn't remove the character, so the editable cell looks like - Hello Hi.
Same problem is when some cell is selected and user presses space key.
I want to add the functionality to the JTable, so that when the content of the cell starts to be edited (by any way - clicking/typing when selected/space key/and maybe there are more options I don't know about), I want to programatically change the content first. Another option would be removing it when the cell is selected (but then I have to remember position of the last selected cell, so that the character could be readded to it).
I've tried in propertyChange in class TableChangeListener:
 table.setValueAt(removeCharacter(table.getValueAt(row,column)), row, column);

but it doesn't work as the cell is already being edited and I cant change it.

A: *

*You will have to use your own implementation of Cell Editor to meet your own set of requirements.

*So create a custom CellEditor implementing FocusLisetener and ActionListener and implement the FocusGained and FocusLost function

*Implement the actionPerformed function too to update value on enter click.

*Handling the Focus event is a little bit tricky. As it tends to update the cell wrongly. That is why i had to pass the reference table to the CellEditor as a constructor parameter and read the cell row, col on Focus gain.

*To reflect the - xxxx: placing - before the cell value, try using a custom CellRenderer. Check out the official tutorial page for details with example. And the part of the credit goes to @mKobel.

An implemented custom cell editor for direction: assign it to your target table column and test.
Giff of my test result:

Code:
class CustomRenderer extends DefaultTableCellRenderer {

     public void setValue(Object value)
     {
         setText("- "+value);
      }
  }

class MyCellEditor extends AbstractCellEditor
                         implements TableCellEditor,
                                    FocusListener,
                                    ActionListener
{
    JTextField textFeild;
    String currentValue;

    JTable table;
    int row, col;
    public MyCellEditor(JTable table) {
        this.table = table;
        textFeild = new JTextField();
        textFeild.addActionListener(this);
        textFeild.addFocusListener(this);
    }

    @Override
    public Object getCellEditorValue() {
        return currentValue;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {

        currentValue = (String)value;
        return textFeild;

    }

    @Override
    public void focusGained(FocusEvent e) {
        textFeild.setText("");
        row = table.getSelectedRow();
        col = table.getSelectedColumn();

    }

    @Override
    public void focusLost(FocusEvent e) {

        if(!textFeild.getText().equals(""))
           //currentValue = textFeild.getText();
           table.setValueAt(textFeild.getText(), row, col);

        fireEditingStopped();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
       if(!textFeild.getText().trim().equals(""))
           currentValue = textFeild.getText();
       fireEditingStopped();
    }

}

A: I think you should not change the content of the cell at all.
What you need is to set on the table a TableCellRenderer that renders the cell values. Implement the cell renderer so that it shows the value "- Hello" (although your actual data could contain just "Hello"). The renderer just shows any component you want in the table. When user starts editing the cell, the renderer component is not shown. Actually you could also manipulate the editing component using a TableCellEditor.

A: Extracted from this comment:

The table shows prices like "$5" "20€" and when user clicks the cell
  to change the price, I'd like the sign to disappear. When user
  finishes editing (clicks enter or by other way), I want the symbol to
  appear again.

Although @Sage post is a really great and general solution (+1 for you :), in this particular case I'd implement a TableCellRenderer and TableCellEditor using JFormattedTextField which can manage the currency format matter, as follows:

*

*Set a generic number format to the renderer component: NumberFormat.getNumberInstance()

*Set a currency number format to the editor component: NumberFormat.getCurrencyInstance()
This way when the cell is displayed the currency sign will be shown but when the cell is being edited the currency sign will "disappear".
Take a look to this example of implementation:
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.text.NumberFormat;
import java.util.EventObject;
import java.util.Locale;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.NumberFormatter;

public class CurrencyEditor extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {

    JFormattedTextField editor;
    JFormattedTextField renderer;
    Integer clickCountToStart = 2;

    public CurrencyEditor(Locale locale) {
        initEditor(locale);
        initRenderer(locale);
    }

    private void initRenderer(Locale locale) {
        NumberFormat format = locale != null ?
                                        NumberFormat.getCurrencyInstance(locale) : NumberFormat.getCurrencyInstance();

        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setMinimum(Double.MIN_VALUE);
        formatter.setMaximum(Double.MAX_VALUE);
        formatter.setAllowsInvalid(false);
        renderer = new JFormattedTextField(formatter);
    }

    private void initEditor(Locale locale) {
        NumberFormat format = locale != null ?
                                        NumberFormat.getNumberInstance(locale) : NumberFormat.getNumberInstance();

        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setMinimum(Double.MIN_VALUE);
        formatter.setMaximum(Double.MAX_VALUE);
        formatter.setAllowsInvalid(false);
        editor = new JFormattedTextField(formatter);
        editor.setBorder(UIManager.getBorder("Tree.editorBorder"));
    }

    @Override
    public Object getCellEditorValue() {
        return editor.getValue();
    }

    @Override
    public boolean isCellEditable(EventObject anEvent) {
        if (anEvent instanceof MouseEvent) {
            return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
        }
        return true;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        return true;
    }

    @Override
    public boolean stopCellEditing() {
        fireEditingStopped();
        return true;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        if(value instanceof Double){
            editor.setValue(value);
        }
        return editor;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        if(value instanceof Double) {
            Color background = isSelected ? UIManager.getColor("Table.selectionBackground") : UIManager.getColor("Table.background");
            Color foreground = isSelected ? UIManager.getColor("Table.selectionForeground") : UIManager.getColor("Table.foreground");
            Border border = hasFocus ? UIManager.getBorder("Table.focusCellHighlightBorder") : BorderFactory.createEmptyBorder();

            renderer.setBackground(background);
            renderer.setForeground(foreground);
            renderer.setBorder(border);

            renderer.setValue(value);
            return renderer;

        } else {
            String message = String.format("Not supported for %1$1s class!", value.getClass());
            throw new IllegalArgumentException(message);
        }
    }

}

Disclaimer: it may not work properly with Nimbus look and feel as UIManager properties are named different. I've tested it using Metal, Windows, Windows Classic and Motif.
Here is the code I've used to test it:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Demo {

    private void initGUI(){

        DefaultTableModel model = new DefaultTableModel(new Object[]{"Item", "Price USD", "Price EUR"}, 0);
        model.addRow(new Object[]{"Fender stratocaster", 1599.99d, 1176.46d});
        model.addRow(new Object[]{"Gibson Les Paul", 1299.99d, 955.87d});
        model.addRow(new Object[]{"Pual Reed Smith Standard 24", 1999.99d, 1470.58d});

        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(500, 300));

        TableColumn priceUSD = table.getColumn("Price USD");
        priceUSD.setCellRenderer(new CurrencyEditor(Locale.US));
        priceUSD.setCellEditor(new CurrencyEditor(Locale.US));

        TableColumn priceEUR = table.getColumn("Price EUR");
        priceEUR.setCellRenderer(new CurrencyEditor(Locale.GERMANY));
        priceEUR.setCellEditor(new CurrencyEditor(Locale.GERMANY));

        JPanel content = new JPanel(new BorderLayout());
        content.add(new JScrollPane(table));

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().initGUI();
            }
        });
    }
}

Screenshot


text:
Q: How do you get arguments in python class to receive values? I'd like to create a class that draws a line using the Turtle module.
class Line(object):

    def __init__(self, coordinates):
        self.start_x = 0
        self.start_y = 0
        self.end_x = coordinates[0]
        self.end_y = coordinates[1]

    def drawing(self, pensize, pencolor):
        self.pensize = pensize
        self.color = pencolor

def main():
    turtle.setup(700,400, startx = 0, starty = 0)
    line = Line()
    turtle.done()
main()

How should I get the instant of the line class to receive coordinates on where the line needs to be drawn out to?
I already recognize that I can just use functions, but, for the sake of understanding how class works, I'd like to implement class to draw lines. The inspiration comes from a project I'm self-learning. The link to the project is:
http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/08_ClassDesign/TurtleSnowPeople/Project10.pdf

A: Python, unlike certain other languages, does not require that you create classes. It's possible, of course, but not necessary.
The simplest way to draw a line, of course, would to be to simply draw the line:
import turtle

def main():
    turtle.setup(700, 700, startx=0, starty=0)
    turtle.penup()
    turtle.goto(13, 42)
    turtle.pendown()
    turtle.goto(42, 13)
    turtle.done()

if __name__ == '__main__':
    main()

But obviously, you want to extract this out so you can repeat the operation without having to repeat those four lines. The simplest way to do that is to create a function. Since you have reference to the turtle module, all you need to pass in is the start and end coordinates:
import turtle

def draw_line(startx, starty, endx, endy):
    turtle.penup()
    turtle.goto(startx, starty)
    turtle.pendown()
    turtle.goto(endx, endy)

def main():
    turtle.setup(700, 700, startx=0, starty=0)
    draw_line(13, 42, 42, 13)
    turtle.done()

if __name__ == '__main__':
    main()

Alternatively you could use something like namedtuple:
import turtle
from collections import namedtuple

Point = namedtuple('Point', ('x', 'y'))

def draw_line(start, end):
    turtle.penup()
    turtle.goto(start.x, start.y)
    turtle.pendown()
    turtle.goto(end.x, end.y)

def main():
    turtle.setup(700, 700, startx=0, starty=0)

    start = Point(13, 42)
    end = Point(42, 13)
    draw_line(start, end)

    turtle.done()

if __name__ == '__main__':
    main()

But if you just really love classes you can still use them. Just put the same code into your class that you would've put anywhere else.


text:
Q: Split a string without separators in PowerShell I want to split a string and store the resulting tokens in variables.
For example, my string is 160519, and I want to split it in a way where 16, 05, and 19 are stored in separate variables.
I tried using -split, but because my string doesn't have separators, I'm finding it difficult to cut the string.

A: You actually can split the string like this if you use a regex.
$arr = $string -split "(..)" -ne ""

The . matches any single character. We then need to filter the array to remove empty values which is where the -ne "" comes in (Thanks mklement0 for the suggestion to replace | ? {$_}).
In action:
C:\Users\Paarth> $string = "160519"
C:\Users\Paarth> $arr = $string -split "(..)" -ne ""
C:\Users\Paarth> $arr
16
05
19
C:\Users\Paarth>

A: If you don't have a delimiter, you can't usefully use -split. Instead you'll have to use something like:
$d = '160519'
$a, $b, $c = $d.SubString(0, 2), $d.SubString(2, 2), $d.SubString(4, 2)

# (That is like doing:
$a = $d.SubString(0, 2)
$b = $d.SubString(2, 2)
$c = $d.SubString(4, 2)
# but doing all three in one go )

Stop here, this is all you need. :-)

Aside: you can index multiple characters out of a string, but they come out as individual characters and each need joining back up into strings again, so it's not neater and not clearer:
$d = '160519'
$a, $b, $c = ($d[0..1] -join ''), ($d[2..3] -join ''), ($d[4..5] -join '')

[Edit: I guess, if you really care, you can force -split to work for you, since you can describe two numbers with a regular expression. The problem with doing that is you normally split based on finding a delimiter, throwing the delimiter away, and keeping the rest. If you want to keep the delimiter you can do it with regex groups, but -split will output empty space where it thinks the content should be, so it takes an ugly workaround to make it work:
# split based on a regular expression describing two digits \d\d
# capture the digits in a group (\d\d)
# Filter the output through Where-Object   |?
# Only the numbers will pass, the empty space won't
$a, $b, $c = $d -split '(\d\d)' |? {$_}

Or a more standard use of regular expressions with the .Net [Regex] library:
$a, $b, $c = [Regex]::Matches($d, '\d\d') | Select -ExpandProperty Value

or in PowerShell
$d -match '(\d\d)(\d\d)(\d\d)'
$a, $b, $c = $matches[1,2,3]

# hey, this one's pretty nice.

]

A: try this
$text="160519"
$var0, $var1, $var2, $var3= $text -split "(\d{2})(\d{2})(\d{2})"
$var1
$var2
$var3


text:
Q: In what circumstances support of transaction is not that important? After posting the question here, I got to know that NoSQL are better at scaling out because they make a trade off between support for transaction and scalability.
So I wonder in what circumstances transactions are not that important so that scalability is more preferable to support of transaction?

A: Well, I would say first that NoSQL is better at scaling is some situations, but not all.
Full ACID transactions are Atomic, Consistent, Isolated and Durable.  If you lose transactions, you will loose some or all of ACID within the datastore.
There are many ways to restore these functions with other asynchronous systems like message queues that themselves are durable.  You can shove data onto a durable message queue, pop the data and deal with it in your NoSQL, then, when you can confirm it's stored to your required minimum, you can flag the message as consumed.  It's the D in ACID, but distributed and asynchronous.  There are ways to ensure the others, but they are often sacrificed to some extent, or moved into another place in the system.  With some NoSQL solutions, you just have to move consistency into the application so it doesn't try to store invalid data.
When you start moving away from database driven transactions, you must increase your application testing dramatically to ensure your system doesn't fail (for some values of fail).
There are essentially no situations where transactions and constraints are not important in a system that has both read and write requirements.  If they weren't you wouldn't care about your data at all (and some people don't, but regret it later).  There are however levels of "caring".  It's just a matter of how you end up at ACID or some pseudo-ACID that's "good enough".  RDMBS makes caring about your data cheap.  NoSQL makes caring about your data expensive, but, it makes scaling cheap(er) (in some cases).  There are many companies with multi-terabyte database in RDBMSes, so to say unilaterally that "they don't scale" is simply inaccurate.  Multi-terabyte SQL databases however, can cost lots of money, depending on the use case (you can after all just slap a RAID 10 array with a few 3TB drives onto a computer and throw a database engine on it.  Might take several minutes to a few hours to do any kind of table scan on a big table, or even indexed look-up though, but if you don't care, it's cheap and multi-terabyte).

A: The biggest category is read-only type queries, where an aborted or botched transaction can simply be repeated.  Anything where you are changing an underlying state, or want to guarantee once and only once activity, should have proper transactional semantics.
That is, "I want to order one widget, charge my credit card" should be a proper transaction: I don't want my card charged unless the widget is ordered, and the vendor doesn't want the widget sent unless the card is charged.  "Report the shipment status of order xyz" doesn't need to be transactional -- if I don't get an answer, I can hit reload.

A: Much of it is just a bit of lateral thinking.
Thw whole point of transcation is you wrap up several operations, and should any fail all that have succeeded get rolled back, and while the transaction is in progress, records are locked and unless you have read uncommitted going, you don't see any on the individual changes of state until the transaction is committed.
Doing all that with distributed systems is expensive, because you need one 'central' and difficult to scale point that needs to 'know' all about the others.
So instead or Order this, charge my card, and show me my current balance.
You do Try to order this, if it's instock charge my card, and if my card gets charged the current known balance will be this.
There's a risk, that the order will be placed, put payment fail, so you need to deal with that. There's a risk that the proposed balance of the card my not be entirely accurate, hence add weasel words and show the potential effect of payment as opposed to the result.
It's not so much are transactions important, it's seeing as they aren't as well supported in NoSQL systems, where/how can I get away with not using them.


text:
Q: AngularJS Web Api HttpHandler Image Downloader My AngularJS application is interacting with ASP.NET Web API to full fill the request which is working fine. it has an use case that allows user to download user specific secure PDF document. I have implemented this functionality as below
AngularJS:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 $scope.DownloadHandler = function (id, downloadURL) {

        FileStreamManager.getPdf(id, downloadURL)
             .then(function (result) {
                 // success
                 window.open(downloadURL + id, '_self', '');
             },
                 function (result) {
                     $scope.errors = result.data;
                 });

    };

Note : downloadURL is the Controller call like \ImageRepo\Get
Web Api Controller I have this implementation:

HttpResponseMessage response = new HttpResponseMessage();

            // DB call to to build the URL
            string fileName = "myLocation\Image\doc.pdf";
            if (!fileProvider.Exists(fileName))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            FileStream fileStream = fileProvider.Open(fileName);
            response.Content = new StreamContent(fileStream);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = fileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentLength = fileProvider.GetLength(fileName);
            return response;

Which is working fine. Due to the security issue, i was asked to implement this by using HttpHanlder which is pretty new to me. I have some question on the same.

*

*Should my AngularJS ng-click calls to my .ashx handler directly instead of a Controller URL? Or Should this call route through Controller? How?

*I have DB calls to build the image URL and update some the status. Can this be done in Handler itself?

*How would i make sure my documents are secured while downloading?

Please help.


text:
Q: pass ID when button is clicked to Action link I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)

The call for action link
@Html.Action("Menu", "MenuItem", new { id = "MenuId"})

"MenuId" must by a dynamic value based on which button is clicked.

A: Here goes my solution, use Html.ActionLink() -
@Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { @id = "MenuId" })

Then say you have image control like this -

Then you have simple JQuery script to replace query string in this way -

In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7

UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
    public JsonResult GetJson(string MenuId)
    {
        List<string> urls = new List<string>();
        urls.Add("https://google.com");
        urls.Add("https://bing.com");
        return Json(urls, JsonRequestBehavior.AllowGet);
    }

Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me

When you run the code, you should see following view -

When you enter the value and click on anchor tag -

And as a result, you will get all the results parsed -

A: You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}


text:
Q: Connecting to SQL Server using domain user through Invoke-Command I have a console app on a remote server that connects to a SQL server using the credentials of the user executing the process.
When I execute the console app on the server itself using a service account it picks up the credentials just fine and logs into the database successfully. However, in order to fit this in my organization's automated process, I need to execute the console app from another server witch is running with a different service account that does not have access to the database.
It looks something like this:
Automation server running under Automation Service account (no access to db)
calls
Application server under Application account and executes app (has access to db)
To simplify this, I've replaced the console app with a simple Powershell script that tries to connect to the database. The result is the same.
$Credential = New-Object System.Management.Automation.PSCredential $ApplicationUser, $SecurePassword

Write-Host "Running executable" -ForegroundColor Green
Invoke-Command -ComputerName $applicationServer -Credential $Credential -ScriptBlock {
    Write-Host $(whoami)
    $SQLServer = "YourServerName"
    $SQLDBName = "YourDBName"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $ServerName; Database = $DbName; Integrated Security=true;"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = 'StoredProcName'
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
 }

The above script fails with the following error message
"Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."
When I print the current user it claims that it is the application user, which should have access to the database.
It appears as if some of the user's credentials are stripped out when Invoke-Command is called but this is where my knowledge becomes limited.
Is there any kind of configuration that can enable this to work?
I am aware there's much easier alternatives but this is the infrastructure and security constraints I am limited by in my organization. (using a SQL user instead would've been a very easy alternative that we are not allowed)

A: string connectionString = $"Data Source=_ServerName;Initial Catalog=_DatabaseName;Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;User ID=_Username;Password=_Paasword";

Hello try this ConnectingString, but first change this information with yours
_ServerName, _DatabaseName, _Username, _Password


text:
Q: Trying to send string variable via Python socket I'm in a CTF competition and I'm stuck on a challenge where I have to retrieve a string from a socket, reverse it and get it back. The string changes too fast to do it manually. I'm able to get the string and reverse it but am failing at sending it back. I'm pretty sure I'm either trying to do something that's not possible or am just too inexperienced at Python/sockets/etc. to kung fu my way through.
Here's my code:
import socket

aliensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

aliensocket.connect(('localhost', 10000))

aliensocket.send('GET_KEY'.encode())
key = aliensocket.recv(1024)

truncKey = str(key)[2:16]
revKey = truncKey[::-1]

print(truncKey)
print(revKey)

aliensocket.send(bytes(revKey.encode('UTF-8')))
print(aliensocket.recv(1024))

aliensocket.close()

And here is the output:
F9SIJINIK4DF7M
M7FD4KINIJIS9F
b'Server expects key to unlock or GET_KEY to retrieve the reversed key'

A: key is received as a byte string.  The b'' wrapped around it when printed just indicates it is a byte string.  It is not part of the string.  .encode() turns a Unicode string into a byte string, but you can just mark a string as a byte string by prefixing with b.
Just do:
aliensocket.send(b'GET_KEY')
key = aliensocket.recv(1024)
revKey = truncKey[::-1]
print(truncKey)  # or do truncKey.decode() if you don't want to see b''
print(revKey)
aliensocket.send(revKey)

A: data  = ''
while True:
   chunk = aliensocket.recv(1)
   data +=chunk
   if not chunk:
        rev = data[::-1]
        aliensocket.sendall(rev)
        break


text:
Q: Mysql deadlock detection Does MySQL always detects the deadlocks automatically? Or the are some situations when MySQL just can't figure out that it's dealing with deadlock?

A: According to the docs, MyISAM, a table-level locking storage engine, is deadlock-free.
InnoDB has deadlock detection.
NDB detection is implemented through a timeout. You can set the TransactionDeadlockDetectionTimeout parameter for transactions.
So, whether its with roll backs or timeouts, the deadlock will eventually recover.

A: i think it depends upon which engine you are using like innodb can do this automatically.
more explanation is here.


text:
Q: Oreo ViewPager to display images from external storage filepaths So I am very new to both Java and Android and am working on an app for a project.  Within the app I would like to have my own image gallery / viewer specifically for the images we will be saving with the app.  As such I want to use a ViewPager to slide through the images, and have created a custom pager adapter.  Here are the relevant files:
CustomSwipeAdapter.java
package app.rpass;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;

public class CustomSwipeAdapter extends PagerAdapter {

    ArrayList<String> f = new ArrayList<String>();// list of file paths
    File[] listFile;
    private Context ctx;
    private LayoutInflater layoutInflater;
    ArrayList<Bitmap> images = new ArrayList<Bitmap>(); //list of bitmaps

    public CustomSwipeAdapter(Context ctx){
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return images.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == (LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        String[] output = f.get(position).split("/");
        textView.setText(output[output.length-1]);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView2);
        imageView.setImageBitmap(images.get(position));
        container.addView(item_view);
        return item_view;

    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }

    public void getFromSdcard()
    {
        File file= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"pictures");
        if (file.isDirectory()) {
            try{
                listFile = file.listFiles();
                for (int i = 0; i < listFile.length; i++) {
                    f.add(listFile[i].getAbsolutePath());
                }
            }
            catch(Exception e){
                Log.i("File Error","No File Could be Created");
            }
        }
        else{
            Log.i("File Error","Filepath was not a directory");
        }

    }
    public void makeBitmaps(ArrayList<String> files){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        for (int i = 0; i < files.size(); i ++){
            File imgFile = new File(files.get(i));
            if (imgFile.exists() && imgFile.canRead()){
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                options.inSampleSize = calculateInSampleSize(options,50,50);
                options.inJustDecodeBounds = false;
                images.add(BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options));
            }
        }
    }
    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

}

SlideActivity.java
package app.rpass;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class SlideActivity extends AppCompatActivity {

    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe);
        viewPager = (ViewPager)findViewById(R.id.view_pager);

        int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE =1;

        if (ContextCompat.checkSelfPermission(SlideActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Log.i("Permissions Error","No permission inside of SlideActivity");
            ActivityCompat.requestPermissions(SlideActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

        }

        adapter = new CustomSwipeAdapter(this);
        new AsyncTask<Void,Void,Void>(){
            ProgressDialog dialog = new ProgressDialog(SlideActivity.this);
            @Override
            protected void onPreExecute() {
                dialog.setMessage("Loading Data...");
                dialog.show();
            }

            @Override
            protected Void doInBackground(Void... voids) {
                adapter.getFromSdcard();
                adapter.makeBitmaps(adapter.f);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                if (dialog.isShowing()){
                    dialog.dismiss();
                }
                viewPager.setAdapter(adapter);
                viewPager.getAdapter().notifyDataSetChanged();
            }
        }.execute();
        //adapter.getFromSdcard();
        //adapter.makeBitmaps(adapter.f);
        //viewPager.setAdapter(adapter);
        //viewPager.getAdapter().notifyDataSetChanged();
    }
}

Swipe.xml
    <?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="fill_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

swipe_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/image_count"
        android:text=""
        android:textSize="25dp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginTop="25dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:layout_marginTop="25dp"
        android:scaleType="fitXY"
        android:id="@+id/imageView2"
        android:layout_width="50dp"
        android:layout_height="50dp" />

</LinearLayout>

My issue is that the textViews are being created just fine, and are giving the appropriate filepaths, but the images are not appearing.  I've searched many other examples and still can't figure out what I'm doing wrong.  I'm sure that I've been working on it so much that I simply have overlooked something.  Any input would be much appreciated.  Thanks!

A: In swipe_layout.xml the root LinearLayout has default orientation of horizontal and its first child TextView layout_width is set to match_parent. Hence, the second child ImageView is not visible. If you set the root view's orientation to vertical you should be able to see the ImageView too!
Edit: Uploaded screenshot
Android studio gives nice warning messages in these scenarios


text:
Q: Pandas: assert a column in the file to be a string I have a dataframe in a data file:
test_num|minval|maxval|test_name|unit|pin|condit
5|-0.0015|0.0015|Uoffset|V|1|Ucc=Uee=15V
6|-0.0015|0.0015|Uoffset|V|1|Ucc=Uee=15V
7|-0.0015|0.0015|Uoffset|V|2|Ucc=Uee=15V
8|-0.0015|0.0015|Uoffset|V|2|Ucc=Uee=15V

When the data is read, the column 'unit' becomes floating point:
info=pd.read_csv('pdinfo.dat',sep='|',index_col='test_num')
print(info)

5        -1.500000e-03  1.500000e-03    Uoffset V  1.0  Ucc=Uee=15V
6        -1.500000e-03  1.500000e-03    Uoffset V  1.0  Ucc=Uee=15V
7        -1.500000e-03  1.500000e-03    Uoffset V  2.0  Ucc=Uee=15V
8        -1.500000e-03  1.500000e-03    Uoffset V  2.0  Ucc=Uee=15V

I can't make it integer, because in various data files there may be 'pin' values like Q_11 or A3. How to assert the data in certain column to be a string?


text:
Q: how to pass a list from flask backend to a reactjs frontend? I am working whit a restful API, written by an ex-coworker, when I use a GET to send a json from the flask API to the frontend and then call the value in the json, I get a string instead an array, the list looks like this
['ETH/BTC','LTC/BTC','BNB/BTC']
Here is what I think is relevant from the code
The route:
@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
    user_id = current_user.get_id()
    bots = db.session.query(Bot).all()
    viewable_bots = db.session.query(BotUserCanView).all()
    user_bots = []
    names = []
    for x in bots:
        ub = get_bot_data_as_dict(x)
        if ub != None:
            names.append(ub['name'])
    return  {'ok': True,
            'msg':'Success',
            'data': json.dumps(names)}, 200

The JS to fetch the data
const [botnames, setBotsNames] = useState([]);

if(savedStrats.length==0){
      fetch('/auth/fetch_bots_names', {method: 'GET'})
      .then(res => {return res.text()}).then(response => {
        try {
          let r = JSON.parse(response);
          setBotsNames(r['data']);
        } catch {
          console.log(response);
        }
      });
    }

and as I pointed, the botnames value is a string like the example, but I need it as an array(I think an JS array?) in order to make a drop menu whit the elements of the list, thanks in advance

A: You can use jsonify to convert your data into JSON format and send it in a response.
You can either use keyword arguments or pass a dict.
The documentation clearly explains the usage.
from flask import jsonify

@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
    bot_names = [bot.name for bot in Bot.query.all()]
    return jsonify({
        'ok': True,
        'msg':'Success',
        'data': bot_names
    })

In React you use the Fetch Api like this.
fetch('/auth/fetch_bots_names')
  .then(resp => resp.json())
  .then(data => {
    setBotsNames(data.data);
  });

I haven't tested the code, but it should work.
You might want to take a look at Flask-Marshmallow if you want to send larger datasets.
Here is a quick example using Flask-Marshmallow in combination with marshmallow-sqlalchemy.
from flask import Flask
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)

class Bot(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

class BotSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Bot

with app.app_context():
    db.drop_all()
    db.create_all()

    bots = [Bot(name=f'bot-{i+1}') for i in range(5)]
    db.session.add_all(bots)
    db.session.commit()

@app.route('/bots')
def bots():
    bots = Bot.query.all()
    bot_schema = BotSchema(many=True)
    bot_data = bot_schema.dump(bots)
    return jsonify(data=bot_data)

The result of the query looks like this.
{
  "data": [
    {
      "id": 1,
      "name": "name-1"
    },
    {
      "id": 2,
      "name": "name-2"
    },
    {
      "id": 3,
      "name": "name-3"
    },
    {
      "id": 4,
      "name": "name-4"
    }
  ]
}


text:
Q: Routing config between internet load balancers and backend Im facing a problem due my lack of experiencie on routing.
I need to config the next things (all run on my computer virtualized, if works, i will pass it to hardware)
[internet] ---- [DMZR]--/--[GATEWAY]---/---[LoadBalancer]---/---[BACKEND]
internet: 192.168.10.0/24
gateway:10.10.10.0/29
Loadbalancer:10.10.10.0/29 | 10.10.1.0/24
Backend:10.10.1.0/24
Loadbalancer has 2 nic, on on the same net as gateway : 10.10.10.0/29 and the other on the same net as the backend 10.10.1.0/24
From the eth1 of the loadbalancer can i get internet. The problem its from the backend. I can not even get to the gateway, but i cant reach the other side of the load balancer (10.10.10.2). Weird, very weird.
I should say that, yesterday i was using on my host the ip 192.168.1.239, gateway 192.168.1.2 and when i changed to 192.168.2.5 gw 192.168.2.1 i cant achieve to let it work again.
My config:
Host: 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0e:0c:85:6f:bf brd ff:ff:ff:ff:ff:ff
    inet6 fe80::20e:cff:fe85:6fbf/64 scope link
       valid_lft forever preferred_lft forever
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
    link/ether 00:0e:0c:85:6f:bf brd ff:ff:ff:ff:ff:ff
    inet 192.168.10.5/24 brd 192.168.10.255 scope global br0
    inet6 fe80::20e:cff:fe85:6fbf/64 scope link
       valid_lft forever preferred_lft forever
4: dmzbr: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
    link/ether fe:54:00:32:14:a7 brd ff:ff:ff:ff:ff:ff
    inet 10.10.10.1/29 brd 10.10.10.7 scope global dmzbr
    inet6 fe80::24f2:a2ff:fe69:6cdb/64 scope link
       valid_lft forever preferred_lft forever
5: mzbr: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
    link/ether fe:54:00:59:d7:d1 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::7cfd:aaff:fe31:45dd/64 scope link
       valid_lft forever preferred_lft forever

iproute show host:
10.10.10.0/29 dev dmzbr  proto kernel  scope link  src 10.10.10.1
10.10.1.0/24 via 10.10.10.1 dev dmzbr
192.168.10.0/24 dev br0  proto kernel  scope link  src 192.168.10.5
default via 192.168.10.1 dev br0

iptables host
10.10.10.0/29 dev dmzbr  proto kernel  scope link  src 10.10.10.1
10.10.1.0/24 via 10.10.10.1 dev dmzbr
192.168.10.0/24 dev br0  proto kernel  scope link  src 192.168.10.5
default via 192.168.10.1 dev br0

iptables nat
Chain PREROUTING (policy ACCEPT 2206 packets, 439K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 3271 packets, 212K bytes)
 pkts bytes target     prot opt in     out     source               destination
   86  5582 MASQUERADE  all  --  *      br0     10.10.10.0/29        0.0.0.0/0

Chain OUTPUT (policy ACCEPT 2816 packets, 179K bytes)
 pkts bytes target     prot opt in     out     source               destination

config loadbalancer
auto lo eth0 eth1
iface lo inet loopback
iface eth0 inet static
        address         10.10.10.2
        netmask         255.255.255.248
        network         10.10.10.0
        broadcast       10.10.10.7
        gateway         10.10.10.1

iface eth1 inet static
        address         10.10.1.3
        netmask         255.255.255.0
        network         10.10.1.0
        broadcast       10.10.1.255
        gateway         10.10.1.3

ip route show
10.10.10.0/29 dev eth0  proto kernel  scope link  src 10.10.10.2
192.168.10.0/24 via 10.10.10.1 dev eth0
default via 10.10.10.1 dev eth0

iptables -nvL
Chain INPUT (policy ACCEPT 22897 packets, 22M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  eth0   eth1    0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  eth0   eth0    0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  eth1   eth0    0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 15503 packets, 1443K bytes)
 pkts bytes target     prot opt in     out     source               destination

iptables -t nat
Chain PREROUTING (policy ACCEPT 430 packets, 35328 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 2 packets, 168 bytes)
 pkts bytes target     prot opt in     out     source               destination
   59  3889 MASQUERADE  all  --  *      eth0    0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 30 packets, 1976 bytes)
 pkts bytes target     prot opt in     out     source               destination

config backend
i
face eth0 inet static
        address         10.10.1.4
        netmask         255.255.255.0
        network         10.10.1.0
        broadcast       10.10.1.255
        gateway         10.10.1.3

ip route show
10.10.10.0/29 via 10.10.1.3 dev eth0
10.10.1.0/24 dev eth0 proto kernel scope link src 10.10.1.4
default via 10.10.1.3 dev eth0

iptables on filter
nothing, all with policy accept
iptables on nat
nothing all with policy accept.
Thanks guys!!!!!

A: Have you enabled ip forwarding on load balancer?
cat /proc/sys/net/ipv4/ip_forward


text: Q: Move the message box only in the application area I have a message box to be displayed and I have set it to top most in C#. When the message box is displayed , I want to move it only in the opened application area and not any where else in the desktop.  Is it possible ??


text:
Q: How to limit power to multiple gpu's? I currently have 3 graphics cards 1 rtx3060ti and 2 rtx3080ti. One rtx3060ti is currently up and mining and I reduced it power consumption down from 200watts to 140watts using the command
sudo nvidia-smi -pl 140
in CLI. But now that i also want to mine on rtx3080ti's, I want to reduce rtx3080ti's power consumption down. So what do i need to do to get its power consumption down without affecting the power consumption of rtx3060ti.
I have install
sudo apt install nvidia-drivers-470 nvidia-smi
I m using ubuntu 20.04LTS.
I have also changed the
sudo nvidia-xconfig --cool-bits=28
Is it possible to:-
sudo nvidia-smi -pl 140 300 300
To reduce the power of rtx3060ti to 140, rtx 3080ti to 300 and rtx 3080ti to 300?

A: The nvidia-smi -i option should allow you to select an individual gpu to modify.  This option will accept the the gpu index, serial number, UUID, or PCI bus ID.


text:
Q: Collect Values + Model Builder ArcGIS 10.1 I have a question relating to the use of Collect Values in Model Builder.
I've just come across this post (Piping output of Iterate Raster tool into Raster Calculator tool using ModelBuilder?) and it's pretty much the same as what I want to do. I'm also adding in a user defined weighting to the iteration and then attempting to collect the values before running the cell statistics. The problem is that I'm not getting a set of unique outputs at the Output Values stage and it only return results for the last original rasters.
Any idea where I'm going wrong with this?


text:
Q: Performance of classifier with positive, negative, and unlabeled data The problem
I have a dataset where ca. 90 % of the dataset is unlabeled and the rest is positively and negatively labeled (unbalanced).
I want to describe the performance of a classifier on this dataset.
Are there any metrics which can describe recall and precision of the classifier while taking into account the unlabeled data as well?
This should be different to PU learning, since I have unlabeled, positive, and negative examples.
Example
My classifier classifies 10 samples as positive. Out of these 10, 1 has a positive label, 2 negative labels, and 8 are unlabeled.
My precision - ignoring the unlabeled - would be 1/(1+1) = 0.5
More extreme example with 10 selected as positive, out of these 1 with a positive label and 9 unlabeled would yield a precision of 1/(1+0) = 1.0
I feel that ignoring the unlabeled samples in the performance metrics might introduce a bias to the evaluation.


text:
Q: Concrete5 - CMS :: Get all file inside a file manager folder programmatically I have a folder structure likes this:
folder1
    subfolder1
           file1.pdf
           file2.pdf
    subfolder2
           file3.pdf
           file4.pdf

is there any way to retrieve all the pdf file's(programmatically) using the "folder1" id?

A: There is but make sure you don't go insanely deep with your folder structure, you don't want to go through hundreds of folders, hundreds of levels deep.
Here's the code
<?php
use Concrete\Core\Tree\Node\Type\FileFolder;
use Concrete\Core\File\FolderItemList;

// First grab the folder object
$folder = FileFolder::getNodeByName('Testing Folder');

if (is_object($folder)) {
    $files = [];
    // if we have a folder we need to grab everything inside and then
    // recursively go through the folder's content
    // if what we get is a file we list it
    // otherwise if it's another folder we go through it as well
    $walk = function ($folder) use (&$files, &$walk) {
            $list = new FolderItemList();
            $list->filterByParentFolder($folder);
            $list->sortByNodeName();
            $nodes = $list->getResults();

            foreach ($nodes as $node) {
                if ($node->getTreeNodeTypeHandle() === 'file'){
                    $files[] = $node->getTreeNodeFileObject();
                } elseif ($node->getTreeNodeTypeHandle() === 'file_folder'){
                    $walk($node);
                }
            }
        };
    $walk($folder);

    // we are done going through all the folders, we now have our file nodes
    foreach ($files as $file) {
        echo sprintf('%sfile name is %s and URL is %s%s', '<p>', $file->getTitle(), $file->getURL(), '</p>');
    }
}


text:
Q: How to make android dial the # key? My application can dial any number but if I add the # key to the string to call then the number gets truncated just before the #. For example
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + "131*4#23"));
startActivity(callIntent);

The "131*4#23" is just to test the code. I will be using # key in the main application but it is not working. What can I do?
NOTE: I have handled the permission and all the other numbers are working.

A: callIntent.setData(Uri.parse(String.format("tel:%s", Uri.encode("131*4#23"))));


text:
Q: In Directives on click button hide/show div I am trying to write a directive, where I am providing button so that when user will click on it some inner div will get hide . But I am not getting how can I do animation to hide /show clicked element directive as I am having many directives on my page.
Fiddle Example :: JSFiddle link
HTML ::

Middle

      <my-dir
        bgcolor="gray"
        myTitle="Anam"
        amount="29000"
        myheight="100"
        width="400"
        mycolor="cyan"
        save="saveChanges('custom directive')">template
      </my-dir>

Script ::
// add a directive
app.directive("myDir", function() {
  return {
    restrict: "E",
    scope: {
      myTitle: "@",   // by value
      myheight: "@",   // by value
      mywidth: "@",   // by value
      mycolor: "@",   // by value
      bgcolor: "@",   // by value
      amount: "=", // by reference
      save: "&"    // event
    },
    template:
      "

  And This is Title <button ng-init='collapsed=true' ng-model='collapsed' ng-click='collapsed=!collapsed'>Save</button> " +
  "

 This is dynamic content which i want to hide/show

" +
  "  {{myTitle}}+{{myheight}}:
",
    replace: true,
    transclude: false,
    link: function (scope, element, attrs) {

        // show initial values: by-val members will be undefined
        console.log("background is " +attrs.bgcolor);

        // change element just to show we can
        element.css("background", attrs.bgcolor);
        element.css("color", attrs.mycolor);
        element.css("height", attrs.myheight);
        element.css("width", attrs.mywidth);

        // // log changes to the 'amount' variable
    }
  }
});

How can I bind hide / show with animaion?

A: You can use ngAnimate module. First add a dependency:
var app = angular.module('plunker', ['ngAnimate']);

And after that setting up an animation is just a matter of writing CSS transitions/animations. For example:
.collapsible {
    -webkit-transition: all .6s linear;
    opacity: 1;
    background: #EFF;
    max-height: 150px;
}
.collapsible.ng-hide-add,
.collapsible.ng-hide-remove {
    display: block !important;
}
.collapsible.ng-hide-add-active,
.collapsible.ng-hide-remove-active {
    overflow: hidden;
}
.collapsible.ng-hide {
    opacity: 0;
    max-height: 0;
}

Demo: http://plnkr.co/edit/2YgEceZkBRjbnEVds945?p=preview


text:
Q: Some guidance tips as a brand new user to Stack Exchange I'm a brand new user to Stack Exchange and I was wondering if I could get some guidance on how this site works and how to ask questions. I have been told by my friends I need to be clear and understandable when writing, otherwise I will get downvoted and put in "the slaughterhouse".
When I first signed up, there was a page that explained how to write good questions. However, it seemed quite vague and I'm not sure it was massively helpful. Can I have some guidance from you guys with more experience in the Stack Exchange community on the basics of how Stack Exchange works, as well as an explanation of how to write good questions on Stack Exchange?
It would be very much appreciated!

A: There are some links of Stack Exchange in the help center, and other ones.
Okay, let's start with tour which you already read:
https://meta.stackexchange.com/tour
And the whole help center page:
https://meta.stackexchange.com/help
There are some good links there, e.g.
https://meta.stackexchange.com/help/on-topic
https://meta.stackexchange.com/help/dont-ask
https://meta.stackexchange.com/help/how-to-ask

https://meta.stackexchange.com/conduct
https://meta.stackexchange.com/help/whats-meta

https://meta.stackexchange.com/help/how-to-answer
And some other ones.
You can keep learning these and there are some more about how the site works. They are all good.


text:
Q: QWizard behaves weird in QMdiArea I have a QWizard that is a subwindow of a QMdiArea. A few weird things occur, but I assume they are all related, so I'll describe the easiest. Under Windows with an Aero theme, the following code behaves strange:
from PyQt4 import QtGui

def createIntroPage():
    page = QtGui.QWizardPage()
    page.setTitle("Introduction")
    label = QtGui.QLabel("This wizard will help you register your copy of "
    "Super Product Two.")
    label.setWordWrap(True)
    layout = QtGui.QVBoxLayout()
    layout.addWidget(label)
    page.setLayout(layout)
    return page

def createRegistrationPage():
    page = QtGui.QWizardPage()
    page.setTitle("Registration")
    page.setSubTitle("Please fill both fields.")
    nameLabel = QtGui.QLabel("Name:")
    nameLineEdit = QtGui.QLineEdit()
    emailLabel = QtGui.QLabel("Email address:")
    emailLineEdit = QtGui.QLineEdit()
    layout = QtGui.QGridLayout()
    layout.addWidget(nameLabel, 0, 0)
    layout.addWidget(nameLineEdit, 0, 1)
    layout.addWidget(emailLabel, 1, 0)
    layout.addWidget(emailLineEdit, 1, 1)
    page.setLayout(layout)
    return page

def createConclusionPage():
    page = QtGui.QWizardPage()
    page.setTitle("Conclusion")
    label = QtGui.QLabel("You are now successfully registered. Have a nice day!")
    label.setWordWrap(True)
    layout = QtGui.QVBoxLayout()
    layout.addWidget(label)
    page.setLayout(layout)
    return page

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    main = QtGui.QMainWindow()
    main.setWindowTitle('Test MDI Application')
    mdiArea = QtGui.QMdiArea(main)
    main.setCentralWidget(mdiArea)

    wizard = QtGui.QWizard(main)
    wizard.addPage(createIntroPage())
    wizard.addPage(createRegistrationPage())
    wizard.addPage(createConclusionPage())
    wizard.setWindowTitle("Trivial Wizard")

    mdiArea.addSubWindow(wizard)
    wizard.show()
    main.show()
    sys.exit(wizard.exec_())

Notice the buttons are all missing. After resizing, the buttons appear, but cannot be clicked. They can only be activated by tabbing to them and activating them with space.
Am I doing something wrong, or is this a PyQT4 issue?


text:
Q: Jekyll pagination with data files I was looking to try to do pagination with the _data files. Here is the code that I was coming up with but it doesn't work. Trying to make it work for a project I am working on right now for a nonprofit client I have.
{% if page.layout == "events" %}
    {% for events in paginator.events %}

{{ events.title }}

                    {% if events.start %}

                         {{ events.start | date_to_long_string }}

                    {% endif %}

{{ events.summary }}

    {% endfor %}

    {% if paginator.total_pages > 1 %}

            {% if paginator.previous_page %}

            {% endif %}
            {% if paginator.page_trail %}
                {% for trail in paginator.page_trail %}
                {{ trail.num }}
                {% endfor %}
            {% endif %}
            {% if paginator.next_page %}

            {% endif %}

    {% endif %}
{% endif %}

Can someone see if this is a way possible that might have done this? If it is would it be ideal to do it for an events page to show an archive of events or no?


text:
Q: Parcel: unable to marshal value android.graphics.Path I am trying to launch an new activity from my main activity. I have:
    Button butt = new Button(this);
    butt.setText("Colors");
    butt.setBackgroundColor(paintCanvas.currentColor());
    butt.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view)
        {
            Intent intent = new Intent(PaintCanvas.this, PaletteActivity.class);
            startActivity(intent);

        }

    });

This launches the new activity and then immediately throws the error:
10-18 01:41:01.090  28582-28582/com.deekor.fingerpainting E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Parcel: unable to marshal value android.graphics.Path@415c3c68
    at android.os.Parcel.writeValue(Parcel.java:1235)
    at android.os.Parcel.writeList(Parcel.java:622)
    at android.os.Parcel.writeValue(Parcel.java:1195)
    at android.os.Parcel.writeMapInternal(Parcel.java:591)
    at android.os.Bundle.writeToParcel(Bundle.java:1619)
    at android.os.Parcel.writeBundle(Parcel.java:605)
    at android.os.Parcel.writeValue(Parcel.java:1170)
    at android.os.Parcel.writeSparseArray(Parcel.java:662)
    at android.os.Parcel.writeValue(Parcel.java:1198)
    at android.os.Parcel.writeMapInternal(Parcel.java:591)
    at android.os.Bundle.writeToParcel(Bundle.java:1619)
    at android.os.Parcel.writeBundle(Parcel.java:605)
    at android.os.Parcel.writeValue(Parcel.java:1170)
    at android.os.Parcel.writeMapInternal(Parcel.java:591)
    at android.os.Bundle.writeToParcel(Bundle.java:1619)
    at android.os.Parcel.writeBundle(Parcel.java:605)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:2078)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:2874)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

Whats going wrong? One my views uses paths, but why would that affect me stating a new activity?

A: a Path is not serializable. I had to create my own class that implements serializable.

A: The Path class doesn't have anything in it that wouldn't be serializable so you can get away with using the following class instead of Path.
public class SerializablePath extends Path implements Serializable {
}


text:
Q: Is there any solution to handle dataType for TestCaseSource ? [Nunit Framework] Based on https://gigi.nullneuron.net/gigilabs/data-driven-tests-with-nunit/ website. I have try to create a simple testcase which prepare for read data in the future. But I have no idea how to handle Argument and use it properly
I have try to set as a object, but i think this might not be a correct solution
        [TestCaseSource("GetDataString")]
        public void TestMethod2(object configs)
        {

        }

Here is source code
namespace SAP
{
    [TestFixture]
    public class Scenario1
    {

        // This one Give System.ArgumentException
        [TestCaseSource("GetDataString")]
        public void TestMethod(List<Config> configs)
        {
            Console.WriteLine("Config " + configs);

        }
        // This one can handle an Exception
        [TestCaseSource("GetDataString")]
        public void TestMethod2(object configs)
        {

        }

        public static List<Config> GetDataString()
        {
            var datas = new List<Config>();
            datas.Add(new Config("Nick", "Coldson"));
            return datas;
        }
    }

    public  class Config
    {
        public string NickName { get; set; }
        public string Name { get; set; }

        public Config(string nickname, string name)
        {
            NickName = nickname;
            Name = name;
        }

    }

}

Here is error msg

System.ArgumentException : Object of type 'SAP.Config' cannot be
  converted to type 'System.Collections.Generic.List`1[SAP.Config]'.

A: The testcasesource has slightly different definition pattern. Assuming you use nunit 3 it should be:
[TestCaseSource(typeof(MyTestData), nameof(GetDataString))]
public void TestMethod2(List<Config> configs)
{
   ...
}

public class MyTestData
{
    public static IEnumerable GetDataString()
    {
        var datas = new List<Config>();
        datas.Add(new Config("Nick", "Coldson"));

        return new TestCaseData(datas);
    }
}

For more info, check the documentation:
https://github.com/nunit/docs/wiki/TestCaseData

A: Your GetDataString returns a List<Config>.
Meaning, your test method with a [TestCaseSource("GetDataString")] will be executed as many times as many items the list has and your method must match the item type.
//// This one throws System.ArgumentException
//[TestCaseSource("GetDataString")]
//public void TestMethod(List<Config> configs)
//{
//    Console.WriteLine("Config " + configs);
//}

// This one is ok
[TestCaseSource("GetDataString")]
public void TestMethod(Config config)
{
    Console.WriteLine(config);
}

If you need to get List<Config> instances in your test, then your source must return some collection containing list items.


text:
Q: SSIS - Pass value from For Loop Item Enumerator to Executesqltask How to pass variable from For Loop Item Enumerator to Executesqltask

A: assuming you know how to use the for loop, you should go to the "variable mapping" tab and map the result of the loop to packages variables. So if you are looping on a folder to get all the files in it, you could map the index 0 (right column) to a variable called @fileName (left column) so on each iteration the loop will read a file name and store on the @fileName variable