Q: Dynamically creating javascript file in Rails 3.1 I am attempting to create a plug and play shopping cart in Rails 3.1 that allows users to add a shopping cart to their site by just adding a link to a javascript file.  The items for sale are input on my end and stored in this js file and rendered with jquery templates.  I currently have an action that renders the corresponding js, but I was wondering if there was a way to create a new minified js file for each site and link to this file in each site instead of the show action that renders the js.
For example, for store#1, I would like to create and save a js file called store1.js and serve that file instead of calling the show.js action that creates the javascipt array for the jquery templates every time.

A: You could try using action caching to have it only render the action once. Then you can utilize cache sweepers to invalidate the cached js when you make any updates that would change the information in the js.
I think that really might be your best option. Your going to go through a lot more trouble trying to get precompiled dynamic JS like that, especially if the content has a tendency to change at all.


Q: Can a virus "attach" to an executable? My understanding is that a virus is an executable - and thus it needs to be executed to do anything. When you execute a virus (program), the process will be able to do whatever malicious thing it is supposed to.
I've been reading an answer, and this part:

Virus, on the other hand, need an executable image to spread within a
  system. They will spread to other executables within the same computer
  (they will attach themselves to those executables which become
  infected and able to spread the virus). And they spread to other
  computers as these executables are passed to them by any means
  (download, on a CD or floppy disk) and executed.

Spread to other executables? So if a virus spreads into my Photoshop executable, running Photoshop in the future will effectively execute the virus code? Essentially rendering my Photoshop program into a virus on itself?
I have never seen this sort of behaviour before - if it is true? (If yes I'll ask at SO how)

A: Yes, viruses can attach themselves onto an executable. Maybe they wrap around the original application, or they just attach themself to some jmp location, but as you said you might be better off asking at SO how to do that.

A: yes it is true. I have seen tools (ProRat I guess) which can merge virus code to EXEs but I have no Idea how to do it programmatically.

A: Both guys (SMR and private_meta) are right. I would like to only append, that some .exe's won't run, if they are corrupted by some kind of injection (which is particulary virus code injected) or strange pieces of code - they will provide application error and crash.
However, not all .exe's are so "smart"...


Q: How to sort the array How to sort array by preserving key
 $arr = array(strong text
    'a' => array('date' => time() - 1000),
    'b' => array('date' => time() - 2000),
    'c' => array('date' => time() - 3000),
);

I want to sort according to the time().

A: function cmp($a, $b)
{
   if($a["date"] == $b["date"]) return 0;

   return($a["date"] >  $b["date"]) ? 1 : -1;
}

usort($array, "cmp");

A: There is a couple of PHP functions that sort arrays - you can see the overview here: http://php.net/manual/en/array.sorting.php
As you want to neither by key nor value, but by some custom logic of yours, you need to use one of the functions starting with u. Ouf of those 3 functions, 2 can be used to sort by value: usort and uasort. The difference between them is that while the first one doesn't preserve the key-value associations, the second one does, which makes uasort the function you need.
uasort takes 2 parameters - an array to be sorted and a callback, that for 2 given elements should return -1, 0 or 1 if the first element is smaller, equal or larger than the second.
In your case, this will work:
print_r($arr);

uasort($arr, function($e1, $e2) {
  if ($e1['date'] == $e2['date']) {
    return 0;
  }
  return ($e1['date'] < $e2['date']) ? -1 : 1;
});

print_r($arr);

Notice: make sure you don't assign the result of uasort to your $arr - the return value of this function is not the sorted array, but a boolean saying if sorting succeeded.


Q: Can I use jQuery to toggle 'reversed' on an ordered list? I'm working with ten
's.
All sections have a header
 followed by an ordered list
.
Only two sections have a sort inside their header.
I wish to use those sort-span's to toggle (reverse) the order of only those two lists.

Section with a list appearing in ascending alphabetical order:

artists sort

Hockney, David

Matisse, Henri

Picasso, Pablo

Artists

*

*Hockney, David

*Matisse, Henri

*Picasso, Pablo

Section with a 'reversed' list appearing in descending alphabetical order:
Note: I have simply added "reversed" to the
 ordered list.

artists sort

03. Hockney, David

02. Matisse, Henri

01. Picasso, Pablo

Artists

*

*Picasso, Pablo

*Matisse, Henri

*Hockney, David

What I am having trouble with is figuring out how to (use jQuery to) toggle 'reversed' to the
 as it's not a .class or .id...
As I only have basic understanding of jQuery, and honestly wouldn't know where to start, I was hoping to ask around here if this is even possible, and if so, how best to approach this?

This all I've got so far, am I on the right track?
$('section span').on('click', function(e) {
    e.preventDefault();
    $(this).closest('ol').toggle().append("reversed");
});

$('section span').on('click', function(e) {
    e.preventDefault();
    $(this).closest('ol').toggle().append("reversed");
});

artists sort

Hockney, David

Matisse, Henri

Picasso, Pablo

A: Added a working example, let me know in case HTML structure is change.

$('section span').on('click', function(e) {
   var OlObj = $(this).parent('h1').next('ol');
   OlObj.append( OlObj.find('li').get().reverse());
});

artists sort

Hockney, David

Matisse, Henri

Picasso, Pablo


Q: AngularJS submit on blur and blur on keypress I want to submit some data to the server when a input field is blurred. The User should also be able to blur the input field by pressing enter.
Unfortunately this results in the following: $rootScope:inprog: $apply already in progress error.
Plunkr - thanks in advance!

A: You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/
Provide details event handle related blur,focus,keydow,keyup,keypress
<input ui-event="{ blur : 'blurCallback()' }">
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

A: Here's what's happening:

*

*You press enter

*ng-keydown triggers (digest begins)

*You call target.blur()

*ng-blur triggers and attempts to start another digest cycle

*Angular complains

The blur is executed synchronously and immediately triggers the handler without finishing the first digest.
In my opinion, this is not a problem with your code, but rather an Angular bug. I've been trying to think of a better solution, but I can only find:
app.controller('BlurCtrl', function($scope, $timeout) {
  $scope.blurModel = "I'm the value"

    $scope.blurOnEnter = function( $event ) {
      if ( $event.keyCode != 13 )
        return

      // this will finish the current digest before triggering the blur
      $timeout(function () { $event.target.blur() }, 0, false);
    }

    $scope.onBlur = function() {
    $scope.result = this.blurModel
    }
})

A: Here is a small directive :
    .directive('ngEnterBlur', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress blur", function (event) {
            if(event.which === 13 || event.type === "blur") {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnterBlur);
                });

                event.preventDefault();
            }
        });
    };
})


Q: Trying to learn boost::intrusive Q2 if I uncomment these
//BaseList   baselist;
//MemberList memberlist;

outside the loop and comment out the ones inside the loop it crashes. I need to be able to have the baselist (and memberlist) outside any loop. How is this achieved?
Edit

The actual problem I am trying to solve in it's simplest form is this.
I want to have a std::vector of MyClass, call it AllThingsBunchedTogether.
  I also want to have a std::vector of BaseList, call it AllThingsSpreadOut.
So

*

*AllThingsBunchedTogether might contain (just the anInt1 part for the sake of compactness): 1,2,1,10,2,3,4,4,5,9,10,10.

*AllThingsSpreadOut might contain (zero not used for now) at [1] 1,1 at [2] 2,2 at [3] 3 at [4] 4,4 at [5] 5 at [9] 9 at [10] 10,10,10.

  Note that the numbers themselves aren't be stored in the BaseList, but e.g., the MyClass(1, "John").
At [1] it could be "Mike", "John", at [2] it could be "Mike", "Dagobart" at [3]
  "John" ... at [10] "John" "Mike" "Dagobart" etc so that there no duplicates in
  any of the BaseList at AllThingsSpreadOut[i] since each MyClass in each
  BaseList hashes to a different value (anInt1 + Name).
In essence, anInt1 tells where the MyClass lives in AllThingsSpreadOut, but anInt1 + name guarantees uniqueness within each BaseList.
So the idea is that AllThingsSpreadOut is a vector of BaseList where at each BaseList at vector location is a list of similar things.
Then, when I remove things from AllThingsBunchedTogether (not by a clear, but by a search to remove some items like in the code below IsMarkedToDelete), they will automatically disappear from the corresponding AllThingsSpreadOut.
AllThingsSpreadOut acts as a sort for AllThingsBunchedTogether, with intrusive semantics. AllThingsBunchedTogether allows superfast access through [].

End Edit
#include <vector>
#include <iostream>

#include <boost/intrusive/list.hpp>

using namespace boost::intrusive;

class MyClass : public list_base_hook<link_mode<auto_unlink>> // This is a derivation hook
{
public:
    std::string name;
    bool bIsMarkedToDelete;
    int anInt1;
public:
    list_member_hook<link_mode<auto_unlink>> member_hook_; // This is a member hook

    MyClass(std::string n, int i) : name(n), anInt1(i), bIsMarkedToDelete(false) {}
};

bool IsMarkedToDelete(const MyClass &o)
{
    return o.bIsMarkedToDelete;
}

//Define a list that will store MyClass using the public base hook
typedef list<MyClass, constant_time_size<false>> BaseList;

// Define a list that will store MyClass using the public member hook
typedef list<MyClass,
        member_hook<MyClass, list_member_hook<link_mode<auto_unlink>>, &MyClass::member_hook_>,
        constant_time_size<false> > MemberList;

int main()
{
    bool done = false;
    std::vector<MyClass> values;

    std::string names[] = {"John", "Mike", "Dagobart"};

    //BaseList   baselist;
    //MemberList memberlist;

    int i = 0;
    while(!done)
    {
        // Create several MyClass objects, each one with a different value

        for (int j = 0; j < 11; ++j)
            values.emplace_back(names[j % 3], j);

        BaseList   baselist;
        MemberList memberlist;

        // Now insert them in t-he reverse order in the base hook list
        for (auto& e : values)
        {
            baselist.push_front(e);
            memberlist.push_back(e);
        }

        // Now test lists
        auto rbit(baselist.rbegin());
        auto mit(memberlist.begin());
        auto it(values.begin()), itend(values.end());

        // Test the objects inserted in the base hook list
        for (; it != itend; ++it, ++rbit)
        {
            if (&*rbit != &*it)
                return 1;
        }
        // Test the objects inserted in the member hook list
        for (it = values.begin(); it != itend; ++it, ++mit)
        {
            if (&*mit != &*it)
                return 1;
        }
# if 0
        for(auto& e : values)
            std::cout << e.anInt1 << "\n";

        for(auto& e : baselist)
            std::cout << e.anInt1 << "\n";

        for(auto& e : memberlist)
            std::cout << e.anInt1 << "\n";

#endif // 0

        if(2 == i)
        {
            for(auto& e: values)
                std::cout << e.name << "\n";

            for(auto& e: values)
            {
                if("Mike" == e.name)
                    e.bIsMarkedToDelete = true;
            }

            values.erase(
                std::remove_if(values.begin(), values.end(), IsMarkedToDelete), values.end());
        }

        if(i++ > 3)
        {
            values.clear();
            done = true;
        }

        std::cout << "\n";
        std::cout << values.size()     << "\n";
        std::cout << baselist.size()   << "\n";
        std::cout << memberlist.size() << "\n";
    }
}

A: I've seen it late, but anyways, here goes:

*

*What you describe matches exactly the implementation of an intrusive hash table of MyClass elements, where

*

*anInt1 is the hash (the bucket identifier) for an element

*the bucket lists are implemented as linked lists

*equality is defined as equality of (anInt1, Name)

So really, your program could just be:
Live On Coliru
std::unordered_set<MyClass> values {
    { "John",      0 }, { "Mike",      1 }, { "Dagobart",  2 },
    { "John",      3 }, { "Mike",      4 }, { "Dagobart",  5 },
    { "John",      6 }, { "Mike",      7 }, { "Dagobart",  8 },
    { "John",      9 }, { "Mike",     10 },
};

for(int i = 0; i<=3; ++i) {
    if(2 == i) {
        for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
        for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);

        for(auto it=begin(values); it!=end(values);) {
            if (it->bIsMarkedToDelete) it = values.erase(it);
            else ++it;
        }
    }

    std::cout << "i=" << i << ", values.size(): " << values.size() << "\n";
}
values.clear();
std::cout << "Done\n";

*if you really wanted contiguous storage, I can only assume you wanted this for performance

*

*you do not want to use pointers instead of objects, since that simply negates the memory layout ("AllThingsBunchedTogether") benefits and you'd be better of with the unordered_set or unodered_map as above

*you do not want to use auto_unlink mode, since it cripples performance (by doing uncontrolled deletion triggers, by inhibiting constant-time size() and by creating thread safety issues)

*instead, you should employ the above stratagy, but with boost::intrusive::unordered_set instead see http://www.boost.org/doc/libs/1_57_0/doc/html/intrusive/unordered_set_unordered_multiset.html
Here, again, is a proof-of-concept:
Live On Coliru
#include <vector>
#include <iostream>
#include <boost/intrusive/unordered_set.hpp>
#include <vector>
//#include <functional>
//#include <algorithm>

namespace bic = boost::intrusive;

struct MyClass : bic::unordered_set_base_hook<bic::link_mode<bic::auto_unlink>>
{
    std::string name;
    int anInt1;
    mutable bool bIsMarkedToDelete;

    MyClass(std::string name, int i) : name(name), anInt1(i), bIsMarkedToDelete(false) {}

    bool operator==(MyClass const& o) const { return anInt1 == o.anInt1 && name == o.name; }

    struct hasher { size_t operator()(MyClass const& o) const { return o.anInt1; } };
};

typedef bic::unordered_set<MyClass, bic::hash<MyClass::hasher>, bic::constant_time_size<false> > HashTable;

int main() {

    std::vector<MyClass> values {
        MyClass { "John", 0 }, MyClass { "Mike",  1 }, MyClass { "Dagobart", 2 },
        MyClass { "John", 3 }, MyClass { "Mike",  4 }, MyClass { "Dagobart", 5 },
        MyClass { "John", 6 }, MyClass { "Mike",  7 }, MyClass { "Dagobart", 8 },
        MyClass { "John", 9 }, MyClass { "Mike", 10 },
    };

    HashTable::bucket_type buckets[100];
    HashTable hashtable(values.begin(), values.end(), HashTable::bucket_traits(buckets, 100));

    for(int i = 0; i<=3; ++i) {
        if(2 == i) {
            for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
            for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);

            values.erase(std::remove_if(begin(values), end(values), std::mem_fn(&MyClass::bIsMarkedToDelete)));
        }

        std::cout << "i=" << i << ", values.size():    " << values.size()    << "\n";
        std::cout << "i=" << i << ", hashtable.size(): " << hashtable.size() << "\n";
    }
    values.clear();
    std::cout << "Done\n";
}

A: Here's the error message, which you omitted:
Assertion `node_algorithms::inited(to_insert)' failed.

From this we can understand that an element is being inserted twice.  This isn't valid with intrusive containers in general.
When you have your lists inside the loop, they are destroyed and recreated each time.  But when they are outside, you never clear them, and you also never clear values, so this sequence occurs:

*

*Add 11 elements to values.

*Add all values to the lists.

*Add 11 elements to values; it still has the previous 11 so now 22 elements.

*Add all values to the lists.  Crash on the first one, because it is already in a list.

One solution is to add values.clear() at the top of the while(!done) loop.


Q: How to block incoming calls from unknown numbers programmatically? I want to create an app that blocks all numbers that are not in contacts.
I have read this  but it is not perfect.
How to do this? Thanks for reading

A: This is one way to use it. First, you have to use ITelephony in your project. I will give you an example to use it in below link. Second, you have to insert code to start service when you restart phone as follows:
in AndroidManifest File :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Change this to :
@Override
public void onReceive(Context context, Intent intent) {
    Intent serviceIntent = new Intent(context,BackgroundService.class);
    startService(serviceIntent);
    }

The sample code at https://github.com/Levon-Petrosyan/Call_redirect_and_reject


Q: Binding to ToolTip.IsOpen reports 'false' the first the ToolTip is opened Currently I am trying to bind the IsOpen property of a ToolTip to a property of my backing view model. Additionally The binding mode is set to 'OneWayToSource'.
This is the Style that is applied to a TreeViewItem and contains the ToolTip definition:
<Style TargetType="TreeViewItem">
    <Setter Property="ToolTip">
        <Setter.Value>
            <ToolTip IsOpen="{Binding IsToolTipOpen, Mode=OneWayToSource}">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Name}"/>
                    <TextBlock Text="{Binding CurrentValue, StringFormat={}Value: {0}}"/>
                    <TextBlock Text="{Binding UnitName, StringFormat={}Unit: {0}}"
                               Visibility="{Binding HasUnit, Converter={StaticResource BooleanToVisibilityConverter}}"/>
                </StackPanel>
            </ToolTip>
        </Setter.Value>
    </Setter>
</Style>

Here is the code for the property that it is binding to:
public bool IsToolTipOpen
{
    get
    {
       return mIsToolTipOpen;
    }
    set
    {
        PegasusContext.Current.LogMessage( new PegasusMessage( string.Format( "IsTooltipOpen: {0}", value ), LogLevel.Debug ) );

        if( mIsToolTipOpen == value ) return;
        mIsToolTipOpen = value;

        if( mIsToolTipOpen )
        {
            BackingIO.BeginWatching();
        }
        else
        {
            BackingIO.StopWatching();
        }
    }
}

When the ToolTip is opened for the first time, it will invoke the IsToolTipOpen property setting it's value to false. Additionally when the ToolTip closes, it will set the value of IsToolTipOpen to false...again. Every subsequent time, the value will get set as expected. After opening the first ToolTip, it will perform strange behavior on other items with the ToolTip attached. For instance it will set the IsToolTipOpen property to true and then back to false almost immediately. Again every subsequent time the ToolTip is opened, it works normally.
Here is report from the logging code you can see on the first line of my IsToolTipOpen property set method (with some additional comments I handwrote in):
TreeViewItem A:
IsTooltipOpen: False <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True  <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed

TreeViewItem B:
IsTooltipOpen: True <-- ToolTip Open
IsTooltipOpen: False <-- ToolTip Open, occured at the same time as the previous entry.
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed

So I was curious if anyone had any idea what was going on? and possible solutions?

A: It appears that the events are working as intended with the ToolTip class. So I created an attached property to fix the problem I was having.
I have a attached property to enable the registration of events:
public static readonly DependencyProperty EnableWatchProperty = DependencyProperty.RegisterAttached(
        "EnableWatch",
        typeof( bool ),
        typeof( ToolTipFix ),
        new PropertyMetadata( default( bool ), OnEnableWatchPropertyChanged ) );

    private static void OnEnableWatchPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        var toolTip = d as ToolTip;
        if( toolTip == null ) return;

        var newValue = (bool) e.NewValue;

        if( newValue )
        {
            toolTip.Opened += OnTooltipOpened;
            toolTip.Closed += OnTooltipClosed;
        }
        else
        {
            toolTip.Opened -= OnTooltipOpened;
            toolTip.Closed -= OnTooltipClosed;
        }
    }

I also have an attached property that can be binded to, and it indicates the current state of the ToolTip:
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.RegisterAttached(
        "IsOpen",
        typeof( bool ),
        typeof( ToolTipFix ),
        new PropertyMetadata( default( bool ) ) );

The event handlers just set the IsOpen property to true or false depending on the event that was invoked.
Here is how I used the the attached property in XAML:
<ToolTip local:ToolTipFix.EnableWatch="True"
         local:ToolTipFix.IsOpen="{Binding IsToolTipOpen, Mode=OneWayToSource}">
    ...
</ToolTip>

If anyone has another solution, or reason for this problem, I would very much appreciate it.

A: This was confusing the heck out of me, and I couldn't help but poke at it for while to try and understand what's going on. I'm not entirely sure I arrived at a complete understanding, but I'm further than when I started =D
I replicated your behaviour for a very simple ToolTip in a Grid, I had a good look at events and the ToolTipService and got nowhere, then started using WPF Snoop (no affiliation) to examine the DataContext on the ToolTip when the application was first started.
Seemingly, the ToolTip has no DataContext. As soon as you open it for the first time.

The ToolTip inherits the DataContext.

So what I assume is happening (this is where I'm hazy), is that when you first mouse over the ToolTip, the DataContext has not yet been correctly bound, so your get/set can't fire correctly; the reason you see any messages at all is a result of the behaviour of the OneWayToSource binding mode explained here: OneWayToSource Binding seems broken in .NET 4.0.
If you choose TwoWay binding, you'll notice the ToolTip doesn't open at all the first time round, but will function correctly after the late binding of the DataContext.
The reason the ToolTip does this, is a result of the way it's implemented, and the possible sharing of ToolTips that can occur; it doesn't live within the visual tree:

A tooltip (and everything in it) is not part of the visual tree - it is not in a parent-child relationship with the Image, but rather in a property-value relationship.
When a tooltip is actually displayed, WPF does some special work to propagate the values of inheritable properties from the placement-target into the tooltip,

So, I think that's sounding plausible, but is there anything you could actually do about it?
Well, some people have wanted to bind the ToolTip to things on the visual tree, and given the difficulties faced in locating the parent objects, a few workarounds have arisen (I cameacross these while looking for a solution:
http://blogs.msdn.com/b/tom_mathews/archive/2006/11/06/binding-a-tooltip-in-xaml.aspx
Getting a tooltip in a user control to show databound text and stay open
Both rely on a neat property of the ToolTip, PlacementTarget, which "Gets or sets the UIElement relative to which the ToolTip is positioned when it opens. MSDN.
So, in summary, to get the IsOpen property to bind and behave correctly, I did this in my mockup:
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow"
    DataContext="{Binding RelativeSource={RelativeSource Self}}" Background="#FF95CAFF"
    >
<Grid>
    <TextBlock Text="{Binding Path=TestObject.Name}">
        <TextBlock.ToolTip>
            <ToolTip IsOpen="{Binding DataContext.TestObject.IsToolTipOpen}"
                DataContext="{Binding Path=PlacementTarget,
                    RelativeSource={RelativeSource Self}}" >
                <StackPanel Orientation="Vertical">
                    <!-- Show me what the `DataContext` is -->
                    <TextBlock Text="{Binding Path=DataContext}" />
                </StackPanel>
            </ToolTip>
        </TextBlock.ToolTip>
    </TextBlock>
</Grid>

Context found on program load.

In this case, the DataContext is WpfApplication1.MainWindow, and I'm binding to a property on that I'm using for testing, called TestObject. You would probably have to fiddle with the syntax a little bit to locate your desired `DataContext item in your template (it might be easier to do it the way you've already done it depending on your structure).
If I've said anything drastically incorrect, let me know.


Q: how to maintain status of failed file I am new in java .I am developing an app in java to transfer a large number of files to server.The requirement is to check the status of failed file and store somewhere and transfer those files later.The application should be maintain a daemon process.
Thanks and Regard
sanjeet

A: The better option for large number of files transfer is to use ftp protocol. For that you need an ftp server. And, using org.apache.commons.net.ftp.FTPClient you may upload files in to the server (and also various file management).
The storeFile(String, InputStream) method of org.apache.commons.net.ftp.FTPClient can give the file upload status, i.e. if the file is uploaded successfully it will return true otherwise false.
Please refer this link for a sample program.


Q: PostgreSQL function to return text array with two elements I am trying to return a text array with two elements using postgresql function.  But the output seems to generate one element.
Here's result from pgAdmin query:  Here, it does seem like the result array with two elements
select "address_pts".usp_etl_gis_get_cname_bd_ext(3)
ALLEGHANY,POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))

But in Python when I call the function, I see the output array length as only 1.
(partial python code)
pg_cur.execute("SELECT \"VA\".address_pts.usp_etl_gis_get_cname_bd_ext(3)")
for rec in pg_cur:
   print(len(rec))
-- output = 1

for rec in pg_cur:
   print(rec[0])
-- ouput: ['ALLEGHANY', 'POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))']

 it generates an error for below code:
 for rec in pg_cur:
   print(rec[1])

-- Here is the function --
-- postgresql 9.6

CREATE OR REPLACE FUNCTION address_pts.usp_etl_gis_get_cname_bd_ext(
_cid integer
  )
RETURNS TEXT[]
LANGUAGE 'plpgsql'
COST 100.0
VOLATILE NOT LEAKPROOF
AS $function$

DECLARE cname TEXT;
DECLARE cbd_ext TEXT;
DECLARE outarr TEXT[];

BEGIN
IF (_cid NOT BETWEEN 1 and 100) THEN
    RAISE EXCEPTION '%s IS NOT A VALID COUNTY ID. ENTER A COUNTY BETWEEN 1..100', _cid;
END IF;

select upper(rtrim(ltrim(replace(name10,' ','_'))))
into cname
from "jurisdictions"."CB_TIGER_2010"
WHERE county_id = _cid;

/*
#Returns the float4 minimum bounding box for the supplied geometry,
#as a geometry. The polygon is defined by the corner points of the
#bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)).
#(PostGIS will add a ZMIN/ZMAX coordinate as well).
*/

SELECT ST_AsText(ST_Envelope(geom))
INTO cbd_ext
from "jurisdictions"."CB_TIGER_2010"
where county_id = _cid;

outarr[0] := cname::text;
outarr[1] := cbd_ext::text;

RETURN outarr;

END;

$function$;

questions:

*

*Is postgresql function resulting in array of length 1 or 2?

*If len is 1, how can split the result? for example:
['ALLEGHANY','POLYGON((1308185.614362,...))']
Thank you

A: If you are happy to split the string once you are in Python, you can try with regex and the module re:
# Python3
import re
p = re.compile(r"\['(.*)','(.*)']")
res = p.search("['ALLEGHANY','POLYGON((1308185.614362,...))']")

print(res.group(1)) # 'ALLEGHANY'
print(res.group(2)) # 'POLYGON((1308185.614362,...))'


Q: Coding a family tree style app I want to code up an app. ( for my own learning) that helps build a family tree. So I want the user to add the users grandparents, parents etc. to this app. and I want to be able to maintain this data. I am wondering what components would go into this. Here's what I am thinking:
- A database - that has all the info.
- front end ( iOS app) that pulls data from this database.
Questions:
- Is a database the right way to go ?
- Any recommendations on the database to use ?
- Any code samples/recommendations on the approach to take ?
I want to make sure the system is scalable and hopefully build a WEB fronted in addition to an app fronted.
Any thoughts from the more experienced coders on how you would approach this problem ?


Q: how can i assign a randomly generated integer to a string in C? i'm trying to make a slot machine type thing and i wanted to assign the randomly generated numbers to certain symbols like 1 = cherry, 2 = bell and so on so i could print out the results in symbol form at the end.
i tried putting the symbols as strings in an array and assigning the numbers to the elements in the array in each slot functions but it didn't work out... is there a way to do this?
here's the code i've written so far, minus the array attempts. any suggestions would be helpful! :D
EDIT: here's an example of what i've tried doing on one of the slots but it keeps saying i need a cast to assign the integer from a pointer (i've tried searching online but idk how to do this)
char * slotOne(int randOne, const char *symbols[])
{
    randOne = rand() % 4 + 1;

    if (randOne = 1)
    {
        randOne = *symbols;
    }
    if (randOne = 2)
    {
        randOne = *(symbols+1);
    }
    if (randOne = 3)
    {
        randOne = *(symbols+2);
    }
    else
    {
        randOne = *(symbols+3);
    }
    return randOne;

}

this is the part of my main function where i've tried declaring the string array:
int main()
{
    int x, one, two, three;
    const char *symbols[4] = {"bell", "orange", "cherry", "horseshoe"};

    srand(time(NULL));

    one = slotOne(x);
    two = slotTwo(x);
    three = slotThree(x);

    printf("%s - %s - %s\n", one, two, three);

    //...

}

not sure if %s or %c is the right type too...

A: At least these problems:

Code is assigning = when it should compare ==.
// if (randOne = 1)
if (randOne == 1)

The last if () { ... } else { ... } will cause one of the 2 blocks to execute.  OP wants an  if () { ... } else if () { ... } else { ... } tree.
// Problem code
if (randOne = 3) {
    randOne = *(symbols+2);
} else {
    randOne = *(symbols+3);
}

Suggest
if (randOne == 1) {
    randOne = *symbols;
} else if (randOne == 2) {
    randOne = *(symbols+1);
} else if (randOne == 3) {
    randOne = *(symbols+2);
} else {
    randOne = *(symbols+3);
}

Also research switch.
switch (randOne) {
  case 1:
    randOne = *symbols;
    break;
  case 2:
    randOne = *(symbols+1);
    break;
  case 3:
    randOne = *(symbols+2);
    break;
  default:
    randOne = *(symbols+3);
    break;
}

Or consider a coded solution:
randOne = *(symbols+(randOne-1));

But code needs to return a pointer to a string not an int and has no need to pass in randOne as a parameter.
const char * slotOne(const char *symbols[]) {
    int randOne = rand() % 4;
    return symbols[randOne];
}

Calling code also needs to adjust to receive a const char *, not an int.
// int one;
// one = slotOne(x);
const char *one = slotOne(symbols);


Q: Unknown error in XPath One of our web application, which has been running in our production environment for a long time, most recently it is running into an weird error when there is a high volume of transactions. We couldn't figure out what is exactly the root cause of the problem, but we found some similar issues in the previous version, WebSphere 6, related to a bug in Xalan version used by the app server. Our application server actually is WebSphere 7, which is supposed to have it fixed, besides it's not using Xalan under the hood anymore. Our application doesn't have Xalan jar embedded too.
To have it fixed we just restart the application itself.
One important note is that the Document is being cached (docs.get(tableName)) and reused to execute the XPath evaluation. We did it to avoid the cost of parsing the Document every time.
The app code is
        Document doc = null;
        try {
            doc = docs.get(tableName);

            if (doc == null)
                return null;

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();
            XPathExpression expr = xpath.compile(toUpper(xPathQuery));
            Object result = expr.evaluate(doc, XPathConstants.NODESET);

            return (NodeList) result;
        } catch (XPathExpressionException e) {
            logger.error("Error executing XPath", e);
        }

And the error stack is here
javax.xml.transform.TransformerException: Unknown error in XPath.
at java.lang.Throwable.<init>(Throwable.java:67)
at javax.xml.transform.TransformerException.<init>(Unknown Source)
at org.apache.xpath.XPath.execute(Unknown Source)
at org.apache.xpath.jaxp.XPathExpressionImpl.evaluate(Unknown Source)
Caused by: java.lang.NullPointerException
at org.apache.xerces.dom.ElementNSImpl.getPrefix(Unknown Source)
at org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.processNamespacesAndAttributes(Unknown Source)
at org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.nextNode(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBase._nextsib(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBase.getNextSibling(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$ChildTraverser.next(Unknown Source)
at org.apache.xpath.axes.AxesWalker.getNextNode(Unknown Source)
at org.apache.xpath.axes.AxesWalker.nextNode(Unknown Source)
at org.apache.xpath.axes.WalkingIterator.nextNode(Unknown Source)
at org.apache.xpath.axes.NodeSequence.nextNode(Unknown Source)
at org.apache.xpath.axes.NodeSequence.runTo(Unknown Source)
at org.apache.xpath.axes.NodeSequence.setRoot(Unknown Source)
at org.apache.xpath.axes.LocPathIterator.execute(Unknown Source)
... 16 more

This is the similar issue what I mentioned.
http://www-01.ibm.com/support/docview.wss?uid=swg1PK42574
Thakns.

A: Many people don't realise that the DOM is not thread-safe (even if you are only doing reads). If you are caching a DOM object, make sure you synchronize all access to it.
Frankly, this makes DOM unsuited to this kind of application. I know I'm biased, but I would suggest switching to Saxon, whose native tree implementation is not only far faster than DOM, but also thread-safe. One user recently tweeted about getting a 100x performance improvement when they made this switch.


Q: What is the status of the Born Rule in axiomatic QM? While physicists have tried multiple times and failed to derive the Born Rule (for example: https://arxiv.org/pdf/quant-ph/0409144.pdf). I was wondering what axiomatic Quantum Mechanics had to say about this? Is it fundamentally impossible to derive the Born Rule or is there hope?
Here's a link of great discussion in the same spirit:
https://www.math.columbia.edu/~woit/wordpress/?p=10533&cpage=1
In fact here we have someone summarising good reasons/books to believe that it indeed may be possible:  http://www.johnboccio.com/research/quantum/notes/bell.pdf
I suspect Lubos Motl was something of the opinion the measurement that should be a separate fundamental axiom. If so, I suspect it becomes a problem of showing: there is no non-redundant axiom when the Born Rule is included?
https://motls.blogspot.com/2018/09/woit-and-probability-in-quantum.html


Q: Session Time out problem Dear All
I have a website hosted on the cloud server and I have added
sessionState mode ="InProc" timeout="1440" />
in the web.config file. But the session gets timed out in 1-2 minutes.
I think the web.config settings should override the IIS settings.But it's not working. Is there solution for this?
thanks in advance
Anoop George Thomas

A: With InProc (in-memory) session state, you will lose session if any of the following conditions occur:

*

*IIS worker process restarts

*User is transferred to another worker process on the same webserver, or another webserver

*IIS restarts

I would verify that you are not seeing any strange restart behavior on IIS, or if you are bouncing around in your cloud environment.

A: If your using Forms authentication this has a timeout as well.
<authentication mode="Forms">
       <forms timeout="20"/>
</authentication>


Q: Correct way to pass data from one view to another in django? Currently Im trying to build an app using Django that pull data from fitbit. Im in the process of getting the Oauth2.0 connection to work.
So I generated a authorization url from a bunch of user inputs: fitbit url, fitbit api, fitbit client id, fitbit client secret and redirect url. Once the link is generated and visited, fitbit returns with an access code in the URL like: https://localhost:8000/?code=#=
Im able to extract the access code, but Im not sure what is the correct way to obtain the previous user input data in the newly redirected view. One way I can think of is saving the first user inputs into a DB and then pulling it out when redirected with the new access code. But Im not sure what other options are available and what the standard way of doing this is.
Im still new to django, so any help is appreciated.
Thanks!

A: you can pass in URL query params if data is not sensitive otherwise you can use session value.


Q: Check if any type of user is signed in I'm using devise and have set up helper methods to check if any type of user is signed in. I have player and coach user types and current_player and current_coach are devise methods that exist.
Here is my application_controller:
helper_method :current_account, :account_signed_in?

def current_account
  if @current_player
    @current_account = current_player
  elsif @current_coach
    @current_account = current_coach
  end
end

def account_signed_in?
  current_account != nil
end

The player and coach models are submodels of the user model.
class Player < User
end
class Coach < User
end

This works (but only if there is a current_player):
def current_account
@current_account = current_player
end

If I remove the @ from current_player and current_coach I get an error:
wrong number of arguments (given 10, expected 2)

A: current_account stays nil because neither your if condition nor your elsif condition are true. It means that @current_player and @current_coach are nil (or false)


Q: Markov inequality example If I have $x_1, x_2,\ldots, x_n$ independent NON-identically distributed Bernoulli random variables, how do I show that:
$$\mathrm{Pr}\left(\sum_{i=1}^nx_i>\beta\mu\right)\le e^{-g(\beta)\mu}$$
where $$\beta>1$$$$\mu=E\left(\sum_{i=1}^nx_i\right)$$$$g(\beta)=\beta\times \ln(\beta)-\beta+1$$?  I believe this can be accomplished using the Markov inequality (because that's what we've been covering), but I'm still not sure how to apply it.

A: In markov's inequality, Note that
$$P(\sum_{i=1}^n x_i > \beta \mu) = P(\beta^{\sum_{i=1}^n x_i} > \beta^{\beta \mu})$$
Now apply markov inequality to rhs to get
$$\leq \frac{E[\beta^{\sum_{i=1}^n x_i}]}{\beta^{\beta \mu}} = \frac{\prod_{i=1}^nE[\beta^{x_i}]}{\beta^{\beta \mu}}=\frac{\prod_{i=1}^nE[\beta^{x_i}]}{e^{(\beta \ln \beta) \mu}}$$
Now $E[\beta^{x_i}] = 1 + p_i(\beta-1)$ where $p_i$ is the mean of the i'th bernoulli random variable. Now you observe
$$\prod_{i=1}^nE[\beta^{x_i}] = \prod_{i=1}^n(1 + p_i(\beta-1)) \leq \prod_{i=1}^n e^{p_i(\beta-1)}$$
$$= e^{(\beta - 1)\sum_{i=1}^n p_i} = e^{(\beta - 1)\mu}$$
Putting it all together, we get
$$P(\sum_{i=1}^n x_i > \beta \mu) \leq e^{(-\beta \ln \beta +\beta -1)\mu} = e^{-g(\beta)\mu}$$
QED


Q: App crashes after adding the AdSupport.framework Hi I get this error on startup:
dyld: Library not loaded: /System/Library/Frameworks/AdSupport.framework/AdSupport
  Referenced from: /Users/owner12/Library/Application Support/iPhone Simulator/5.1/Applications/823A0485-7443-4206-B9F5-A84C03DBFB89/BusinessPlan.app/BusinessPlan
  Reason: image not found

I added that framework to the Target --> Build Phases --> Link Binary With Libraries.
The strange thing is that this framework started appearing in my project in the navigator in the main area where the files are, and not in the project/Frameworks.
Would anyone know how to fix this?  Thanks!
Also, I added some params to the Build Settings under "Other Linker Flags" and they appear like this:

But really they were supposed to appear like this:
-all_load *
-ObjC

Could that be the reason for the error?

A: " Referenced from: /Users/owner12/Library/Application Support/iPhone Simulator/5.1/" - isn't AdSupport available only in iOS 6.0 and later?


Q: IQueryable return type with Lambda statements i am facing problem with the return type for this function and not really getting anywhere near solving can someone help me with this?
here goes the function,
public IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>> GetDiscussion_categoriesWithBoards()
{
    return GetDiscussion_categories().Select(c =>
        new
        {
            Category = c,
            Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
        }).ToDictionary(i => i.Category, i => i.Boards.ToList());
}

this is the other function that works which is used in the above function that doen't work,
public IQueryable<discussion_board> GetDiscussion_boardsByCategory(int CategoryID)
{
    return this.ObjectContext.discussion_boards.Where(e => e.CategoryID == CategoryID);
}
public IQueryable<discussion_category> GetDiscussion_categories()
{
    return this.ObjectContext.discussion_categories;
}

I need this to be the return type:
IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>>

thank you friends!

A: Since you're calling ToDictionary(), your method returns a Dictionary<>, not an IQueryable<>:
public Dictionary<discussion_category, List<discussion_board>>
GetDiscussion_categoriesWithBoards()
{
    // ...
}

If you absolutely want to return an IQueryable<> you can write something like:
public IQueryable<Dictionary<discussion_category, List<discussion_board>>>
GetDiscussion_categoriesWithBoards()
{
    return new[] {
        GetDiscussion_categories().Select(c => new {
            Category = c,
            Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
        }).ToDictionary(i => i.Category, i => i.Boards.ToList())
    }.AsQueryable();
}

A: The return type will be:
System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>

as the return type of ToDictionary is Dictionary object and not a Iqueryable of Dictionary

A: Seems that this function will return:
Dictionary<Category, List<Board>>

A: I found the answer :)
public IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>> GetDiscussion_categoriesWithBoards()
{
    return (GetDiscussion_categories().Select(c =>
        new
        {
            Category = c,
            Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
        }).ToDictionary(i => i.Category, i => i.Boards.ToList())).AsQueryable() as IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>>;
}

this is the solution :)
thank you for all your help your questions and answers lead me to solve this :)

A: Are you asking what is the return type of the lambda? It looks to be a Dictionary<Category,List<Board>>


Q: Consecutive Order Numbers - Quickbooks and similar accounting services One constraint I'm dealing with on a project is for all order numbers to be consecutive in nature.
Current: 1000, 1001, 1003, 1004, 1008, 1010
Desired: 1000, 1001, 1002, 1003, 1004, 1005
Problem Statement
Accounting systems can only record sales receipts and invoices in consecutive numbers. If a non-consecutive number comes through, the accounting system is forced to rewrite the number to a consecutive number.
When that happens, Magento and the accounting system are no longer synced by transaction number. I have a clear understanding of why Magento does not store consecutive order numbers - due to sales quotes being created before order is transacted.
Requirements & Question
The requirement is to keep some form of sync between Magento and the accounting system. That means a transaction number or another identifier.
Questions

*

*Is there a way to maintain consecutive order numbers in Magento without breaking the core?

*Is there another common identifier that can be used between the accounting system and Magento if the transaction numbers don't sync up?

A: Magento is not intended to have consecutive order numbers. This is what accounting systems are for. Not every order in Magento necessarily is going to have an invoice. For example there are orders which ...

*

*never get paid (pre payment)

*get cancelled in an early state

*may be splitted in multiple invoices

*are changed on request

Invoice numbers need to be consecutive, not order numbers. As a result there is no other way to logically get them in an uninterrupted order. Use an accounting system and keep the references.

A: I am using shipping and Quickbooks integration software from Teapplix.  They support using ebay Sales Order number or Magento sales order number as Quickbooks sales receipt number.  For Magento orders, they just needed to do a customization for me on my teapplix account.


Q: send multiple responses to client via nodejs i am using nodejs and i want to send back multiple responses to client.And my code is below
//addwork
var agenda = require('../../schedules/job-schedule.js')(config.db);

    exports.addwork = function(req, res) {

        var work = new Work(req.body);
        work.user = req.user._id;
        var user=req.user;
     work.save(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {

                console.log('created work....'+work);
                console.log('dateeeeeeeeeeeee'+work.created);
                console.log('calling agenda job now, user is: '+ JSON.stringify(req.user));
                    console.log('supervisor-------------------------'+JSON.stringify(user.supervisor));
                agenda.now('Work_To_Supervisior_Notify', {supervisor:user.supervisor,title:work.title,details:work.details});

    res.jsonp(work);
                    res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'});

            }
        });
    };`

//job-schedule.js
var Agenda = require("agenda");
    var emailJob = require('./jobs/email-job.js');
module.exports = function(agendaDb) {

    var agenda = new Agenda({db: { address: agendaDb}});

    emailJob.sendWorkToSupervisiorEmail(agenda);

    agenda.start();
    return agenda;
}

//email-job.js
   exports.sendWorkToSupervisiorEmail = function(agenda){
        agenda.define('Work_To_Supervisior_Notify',{priority: 'high', concurrency: 10}, function(job, done){
            console.log('Send works to supervisior ' + JSON.stringify(job.attrs.data.supervisor)+' ,title '+job.attrs.data.title+' ,details '+job.attrs.data.details);
            var smtpTransport = nodemailer.createTransport(config.mailer.options);
                var mailOptions = {
                    to: job.attrs.data.supervisor,
                    from: config.mailer.from,
                    subject: 'work done by user',
                    html: 'work title : '+job.attrs.data.title+'
work details : '+job.attrs.data.details+''
                };

                    smtpTransport.sendMail(mailOptions, function(err) {
                    if (!err) {
                        console.log('An email has been sent to ' + job.attrs.data.supervisor + ' with further instructions.');
                    res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'});

                    }
                });

            done();
        })

    }

Here i want response either from agenda or from res.send() message in addwork function
If i use res.send in addwork function it shows ERROR as "can't set headers after they sent".And if i use res.send message in sendWorkToSupervisiorEmail() it show ERROR as "there is no method send".I am new to nodejs please help me with solution

A: A http request only gets a single http response. Using http, you only get one response. Some options for you:
1) Wait for everything to finish before replying. Make sure each part creates a result, success or failure, and send the multiple responses at once. You would need some control flow library such as async or Promises to make sure everything responded at the same time. A good choice if all parts will happen "quickly", not good if your user is waiting "too long" for a response. (Those terms were in quotes, because they are application dependent).
2) Create some scheme where the first response tells how many other responses to wait for. Then you'd have a different HTTP request asking for the first additional message, and when that returns to your client, ask for the second additional message, and so on. This is a lot of coordination though, as you'd have to cache responses, or even try again if they were not done yet. Using a memory cache like redis (or similar) could fulfill the need to holding responses until ready, with a non-existent meaning 'not ready'
3) Use an eventing protocol, such as WebSockets, that can push messages from the server. This is a good choice, especially if you don't know how long some events would occur after the trigger. (You would not want to stall a HTTP request for tens of seconds waiting for 3 parts to complete - user will get bored, or quit, or re-submit.). Definitely check out the Primus library for this option. It can even serve the client-side script, which makes integration quick and easy.


Q: How do I update application versioning, are there conventions to follow, are there tools? I do not know why I feel insecure of the things that I am about to do, and I always seek for some advice in the community before doing my move.
Have you used bower and/or npm, they have this cli commands: bower init or npm init that initiates creation of bower.json or package.json files respectively. And now it asks me for a version number. FOllowing semver.org tells me that during development 0.y.z is the way to go. Now after doing npm init, how do you update the version number? by manually editing the package.json? and doing a commit?


Q: Unexpected response from the server. The file may have been uploaded successfully. Check in the Media Library or reload the page. Wordpress media When I try to upload an mp4 file with 84mb. It gives me this error
"Unexpected response from the server. The file may have been uploaded successfully. Check in the Media Library or reload the page."
SSL is activated

A: You may need to adjust the values to higher numbers for larger files.
Try doing following steps:
Open Cpanel -> File manager
Click search and type 'php.ini' -> Right click this file and choose edit.
change value of following
memory_limit
post_max_size
upload_max_filesize

Adjust the values to higher numbers for larger files. Save and try again uploading.

A: I also had this problem
First you need to install a file manager plugin. Open file manager, search for a file with the name: .htaccess
Edit this file, at the bottom add the following:
php_value upload_max_filesize 1000M
php_value post_max_size       2000M
php_value memory_limit        3000M
php_value max_execution_time  180
php_value max_input_time      180

Save and close
Try uploading again, in my case worked.
I followed the instructions from this video:
https://www.youtube.com/watch?v=TnI_h-QjrWo


Q: Why doesn't InputStream fill the array fully? Dude, I'm using following code to read up a large file(2MB or more) and do some business with data.
I have to read 128Byte for each data read call.
At the first I used this code(no problem,works good).
InputStream is;//= something...
int read=-1;
byte[] buff=new byte[128];
while(true){
 for(int idx=0;idx<128;idx++){
  read=is.read(); if(read==-1){return;}//end of stream
  buff[idx]=(byte)read;
 }
 process_data(buff);
}

Then I tried this code which the problems got appeared(Error! weird responses sometimes)
InputStream is;//= something...
int read=-1;
byte[] buff=new byte[128];
while(true){
 //ERROR! java doesn't read 128 bytes while it's available
 if((read=is.read(buff,0,128))==128){process_data(buff);}else{return;}
}

The above code doesn't work all the time, I'm sure that number of data is available, but reads(read) 127 or 125, or 123, sometimes. what is the problem?
I also found a code for this to use DataInputStream#readFully(buff:byte[]):void which works too, but I'm just wondered why the seconds solution doesn't fill the array data while the data is available.
Thanks buddy.

A: Consulting the javadoc for FileInputStream (I'm assuming since you're reading from file):

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

The key here is that the method only blocks until some data is available. The returned value gives you how many bytes was actually read. The reason you may be reading less than 128 bytes could be due to a slow drive/implementation-defined behavior.
For a proper read sequence, you should check that read() does not equal -1 (End of stream) and write to a buffer until the correct amount of data has been read.
Example of a proper implementation of your code:
InputStream is; // = something...

int read;
int read_total;

byte[] buf = new byte[128];

// Infinite loop
while(true){
    read_total = 0;

    // Repeatedly perform reads until break or end of stream, offsetting at last read position in array
    while((read = is.read(buf, read_total, buf.length - offset)) != -1){
        // Gets the amount read and adds it to a read_total variable.
        read_total = read_total + read;

        // Break if it read_total is buffer length (128)
        if(read_total == buf.length){
            break;
        }
    }

    if(read_total != buf.length){
        // Incomplete read before 128 bytes
    }else{
        process_data(buf);
    }
}

Edit:
Don't try to use available() as an indicator of data availability (sounds weird I know), again the javadoc:

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

The key there is estimate, don't work with estimates.

A: Since the accepted answer was provided a new option has become available. Starting with Java 9, the InputStream class has two methods named readNBytes that eliminate the need for the programmer to write a read loop, for example your method could look like
public static void some_method( ) throws IOException  {
    InputStream is = new FileInputStream(args[1]);
    byte[] buff = new byte[128];
    while (true) {
        int numRead = is.readNBytes(buff, 0, buff.length);
        if (numRead == 0) {
            break;
        }
        // The last read before end-of-stream may read fewer than 128 bytes.
        process_data(buff, numRead);
    }
}

or the slightly simpler
public static void some_method( ) throws IOException  {
    InputStream is = new FileInputStream(args[1]);
    while (true) {
        byte[] buff = is.readNBytes(128);
        if (buff.length == 0) {
            break;
        }
        // The last read before end-of-stream may read fewer than 128 bytes.
        process_data(buff);
    }
}


Q: Extract elements of multiple sublists in a list and transform to multiple dataframes Hello Dear Community,
Following this post,
I am searching how to create multiple data frames from a list that contains multiple sublists with different names
So, from a list called tier.col  I would like to create a function tier2col that returns to multiple data.frames (as much as there is sublist in my list) containing specific elements of the sublist.
I get how to do this manually as so :
phones <- data.frame(tier.col$phones$xmin[-1,3], tier.col$phones$xmax[-1,3], tier.col$phones$text[3])

But in reality "phones" changes in multiple names, so I would need a more generic approach to sublists:
x <- data.frame(tier.col$x$xmin[-1,3], tier.col$x$xmax[-1,3], tier.col$x$text[3])

The function would act as so :
tier2col <- function(list.x) {
  for all sublist in my list
  select tier.col$sublist$xmin[-1,3], tier.col$sublist$xmax[-1,3], tier.col$sublist$text[3]
  and compile them in a dataframe
}

I know that I can call all the xmin & xmax & text by this :
lapply(tier.col[c(1:length(names(tier.col)))], "[", 1)
lapply(tier.col[c(1:length(names(tier.col)))], "[", 2)
lapply(tier.col[c(1:length(names(tier.col)))], "[", 3)
But I don't know how to get pass this or how to use mapply on this kind of datastructure.
I would have like something like tier.col$c(names(tier.col)$xmin to work, but evidently, that is not the proper way to do it.
Can someone help me to compute this in an efficient way?
Stucture of tier.col:
List of 17
 $ phones        :List of 3
  ..$ xmin:'data.frame':    2506 obs. of  3 variables:
  .. ..$ num.row: num [1:2506] 11 15 19 23 27 31 35 39 43 47 ...
  .. ..$ object : chr [1:2506] "xmin" "xmin" "xmin" "xmin" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 20 20 21 22 23 24 26 27 28 29 ...
  ..$ xmax:'data.frame':    2506 obs. of  3 variables:
  .. ..$ num.row: num [1:2506] 12 16 20 24 28 32 36 40 44 48 ...
  .. ..$ object : chr [1:2506] "xmax" "xmax" "xmax" "xmax" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 2414 21 22 23 24 26 27 28 29 30 ...
  ..$ text:'data.frame':    2505 obs. of  3 variables:
  .. ..$ num.row: num [1:2505] 17 21 25 29 33 37 41 45 49 53 ...
  .. ..$ object : chr [1:2505] "text" "text" "text" "text" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 11 4397 4434 3697 4025 3697 3832 4127 3992 4397 ...
 $ syll          :List of 3
  ..$ xmin:'data.frame':    1147 obs. of  3 variables:
  .. ..$ num.row: num [1:1147] 10037 10041 10045 10049 10053 ...
  .. ..$ object : chr [1:1147] "xmin" "xmin" "xmin" "xmin" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 20 20 21 24 27 30 33 35 37 40 ...
  ..$ xmax:'data.frame':    1147 obs. of  3 variables:
  .. ..$ num.row: num [1:1147] 10038 10042 10046 10050 10054 ...
  .. ..$ object : chr [1:1147] "xmax" "xmax" "xmax" "xmax" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 2414 21 24 27 30 33 35 37 40 43 ...
  ..$ text:'data.frame':    1146 obs. of  3 variables:
  .. ..$ num.row: num [1:1146] 10043 10047 10051 10055 10059 ...
  .. ..$ object : chr [1:1146] "text" "text" "text" "text" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 11 4431 4028 3879 4430 4442 4405 3783 4159 4327 ...
 $ delivery      :List of 3
  ..$ xmin:'data.frame':    1147 obs. of  3 variables:
  .. ..$ num.row: num [1:1147] 14627 14631 14635 14639 14643 ...
  .. ..$ object : chr [1:1147] "xmin" "xmin" "xmin" "xmin" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 20 20 21 24 27 30 33 35 37 40 ...
  ..$ xmax:'data.frame':    1147 obs. of  3 variables:
  .. ..$ num.row: num [1:1147] 14628 14632 14636 14640 14644 ...
  .. ..$ object : chr [1:1147] "xmax" "xmax" "xmax" "xmax" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 2414 21 24 27 30 33 35 37 40 43 ...
  ..$ text:'data.frame':    1146 obs. of  3 variables:
  .. ..$ num.row: num [1:1146] 14633 14637 14641 14645 14649 ...
  .. ..$ object : chr [1:1146] "text" "text" "text" "text" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 11 2 2 2 2 2 2 2 2 2 ...
 $ link          :List of 3
  ..$ xmin:'data.frame':    807 obs. of  3 variables:
  .. ..$ num.row: num [1:807] 19217 19221 19225 19229 19233 ...
  .. ..$ object : chr [1:807] "xmin" "xmin" "xmin" "xmin" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 20 20 21 27 30 34 37 40 45 1642 ...
  ..$ xmax:'data.frame':    807 obs. of  3 variables:
  .. ..$ num.row: num [1:807] 19218 19222 19226 19230 19234 ...
  .. ..$ object : chr [1:807] "xmax" "xmax" "xmax" "xmax" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 2414 21 27 30 34 37 40 45 1642 1651 ...
  ..$ text:'data.frame':    806 obs. of  3 variables:
  .. ..$ num.row: num [1:806] 19223 19227 19231 19235 19239 ...
  .. ..$ object : chr [1:806] "text" "text" "text" "text" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 11 2 2 4025 2 2 2 4025 2 4025 ...
 $ words         :List of 3
  ..$ xmin:'data.frame':    807 obs. of  3 variables:
  .. ..$ num.row: num [1:807] 22447 22451 22455 22459 22463 ...
  .. ..$ object : chr [1:807] "xmin" "xmin" "xmin" "xmin" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 20 20 21 27 30 34 37 40 45 1642 ...
  ..$ xmax:'data.frame':    807 obs. of  3 variables:
  .. ..$ num.row: num [1:807] 22448 22452 22456 22460 22464 ...
  .. ..$ object : chr [1:807] "xmax" "xmax" "xmax" "xmax" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 2414 21 27 30 34 37 40 45 1642 1651 ...
  ..$ text:'data.frame':    806 obs. of  3 variables:
  .. ..$ num.row: num [1:806] 22453 22457 22461 22465 22469 ...
  .. ..$ object : chr [1:806] "text" "text" "text" "text" ...
  .. ..$ value  : Factor w/ 4466 levels "","  ","  n ",..: 11 4424 3881 4429 3745 3781 4160 4054 3983 4229 ...

Don't hesitate to tell if something is not clear/missing,
Thanks a lot,

A: If you know how to process one item (phones), then just generalize that into a function so you can run it to the whole list via lapply:
process.one <- function(x)
    data.frame(xmin = x$xmin[-1,3], xmax = x$xmax[-1,3], text = x$text[3])

out <- lapply(tier.col, process.one)

At this point, out is a list of data.frames. It is recommended you keep it that way, but if what you really wanted are data.frames to be added to an environment (e.g. the global environment) then you can do so with list2env:
list2env(out, envir = .GlobalEnv)


Q: How do you figure out the Big-Oh of a function if all you are given is the function? I'm currently covering Big-Oh and proofs by Big-Oh. I think I understand the proofs using Big-Oh, but I am struggling to understand how you figure out the Big-Oh of a function. We went through it during lectures but it's the one thing that I've revisited multiple times and I still don't understand.
The example that we went through is this: what is the Big-Oh of f(n) = n^2 + n?
The first step that my lecturer did is convert the function into this:
f(n) = n^2 * (1 + 1/n). I understand why n^2 has gone outside (as it is the faster growing term between itself and n) but i'm struggling to understand how the (1 + 1/n) is created.
After this, the following is done f(n) is O(n^2 * 1 ) = O(n^2) which I understand.
I'm not sure if this is something that a lot of people generally follow or if it's something just specific to my lecturer, but i'd appreciate any advice.
Sorry for my bad formatting, i'm not sure how to make the equations look nice.


Q: CSS : Is there a way to know if GPU is being used? I know some CSS properties, on some browsers, on some OS, can trigger GPU acceleration.
Is there a way to see, somewhere within the browsers' debugging tools, if the GPU is actually being used or not ?


Q: Break string in Javax.Swing.JTextArea without escape characters Is there a way to automatically break a string entered into JTextArea (in package javax.swing), for example via the keyboard, into a readable form, without the need for escape characters, i.e. \n and \r ?
Edit2:
With the help of @matt, I realized that the correct question is about word warp and therefore the answer is the answer function
mytextArea.setLineWrap(true);

A: Breaking a string onto a newline without actually adding a character is a word wrap.
JTextArea has word wrap.
mytextArea.setLineWrap(true);


Q: Kafka producer unable to connect to broker via Internet. Works well if in local network as broker. Telnet connectivity working from internet I have a Kafka broker running on a computer on my home network. When I connect my java producer (on another computer) to this broker from the same wifi network, it works absolutely well and is able to post messages without any issues.
As next steps for my application, I have exposed my computer and Kafka's 9092 port over internet. I have also opened all firewall on my system for this port. And when I do telnet/nc connection attempt from any other network, it connects well. The Kafka host also shows the connection made in the netstat output.
 telnet DNSHOSTNAME 9092
Trying MYIP...
Connected to DNSHOSTNAME.
Escape character is '^]'.

But from this external network, when I use my exact same kafka java producer to send to my home computer from this outside network, it always fails with the following error. I also do not see any connection attempts or errors in the Kafka logs related to this.
    Error while producing message to topic :TP1-0@-1
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for TP1-0: 30005 ms has passed since batch creation plus linger time

Another interesting point is that, I have other apps - RabbitMQ and Tomcat also on the same machine as Kafka with the same firewall and router rules. My same java app is able to publish to them over TCP and HTTP from the internet connection. It's only Kafka which is not working.
Provided that the telnet and nc connections are connecting well, I think this is not a firewall or network routing problem. That leaves me only with the producer code, given below. Is there some type of setting to be applied on Kafka Broker or Kafka Producer side for them to be able to connect over the internet? Same issue with consumer code. It can't connect from internet.
Producer code:
   public static void main(String[] args){

       Properties props = new Properties();
       //props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "DNSHOSTNAME:9092");
       props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "MYEXTERNALIP:9092");

       props.put(ProducerConfig.ACKS_CONFIG, "all");
       props.put(ProducerConfig.RETRIES_CONFIG, 0);
       props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
       props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

       Producer<String, String> producer = new KafkaProducer<String, String>(props);
       TestCallback callback = new TestCallback();
       Random rnd = new Random();

           ProducerRecord<String, String> data = new ProducerRecord<String, String>("TP1", "s2", "TEST DATA" );
           producer.send(data, callback);
       producer.close();
   }

   private static class TestCallback implements Callback {
       @Override
       public void onCompletion(RecordMetadata recordMetadata, Exception e) {
           if (e != null) {
               System.out.println("Error while producing message to topic :" + recordMetadata);
               e.printStackTrace();
           } else {
               String message = String.format("sent message to topic:%s partition:%s  offset:%s", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
               System.out.println(message);
           }
       }
   }

Troubleshooting steps done:

*

*Deployed Kafka on 3 different computers, 2 windows and 1 mac. Same results. Works well from the same network, not when they are on internet. Telnet works with each kafka computer from internet/outside network.

*Tried 3 different external networks, one being my cell phone's hot spot.

*Tried other softwares as well on kafka machine, as mentioned above and they work fine.

*Completely disabled the system firewall just to ensure there is no firewall issue, but no luck.

Can someone please help me here on this thread?
Thanks in advance !

A: The problem you're describing can be solved by "advertising" an address for each broker over the internet via advertised.listeners
telnet and nc check that port is open (listeners config), but cannot check that the brokers bootstrap correctly back to the client, you can instead use kafkacat -L -b <bootstrap> for that, which will return a list of brokers in the cluster, and connecting to each of those should be possible from where you want to run the client
If you have multiple brokers behind your single WAN address, they'll have to advertise / forward separate ports for full connectivity

Alternative solutions include the Kafka REST Proxy
In either case, adding SSL to the connection should be done


Q: Interactive Legend onclick or mouseover - D3js I've been looking for a way to have my legend control my chart animation (similar to NVD3 examples). I've run into a problem though - nested selections.
var legend = svg.append("g")
    .attr("class", "legend")
    .attr("transform", "translate(70,10)")
    ;

var legendRect = legend.selectAll('rect').data(colors);

legendRect.enter()
   .append("rect")
   .attr("x", w - 65)
   .attr("width", 10)
   .attr("height", 10)
   .attr("y", function(d, i) {
       return i * 20;
   })
   .style("stroke", function(d) {
       return d[1];
   })
   .style("fill", function(d) {
       return d[1];
   });

I'm using a bit of a hack to do my animation. Basically setting style to display: none.
I want to be able to click on the rectangles and call the function. But putting a mouseover or onclick within legendRect doesn't work. The bars to animate are not children of the legend. How can I call the function, or chain my function to my legend?
function updateBars(opts) {
var gbars = svg.selectAll("rect.global");
var lbars = svg.selectAll("rect.local");
if (opts === "global") {
    gbars.style("display", "block") ;
    lbars.style("display", "none");
    gbars.transition()
        .duration(500)
        .attr("width", xScale.rangeBand());
};
if (opts === "local") {
    lbars.style("display", "block")
    ;
    gbars.style("display", "none");
    lbars.transition()
        .duration(500)
        .attr("x", 1 / -xScale.rangeBand())
        .attr("width", xScale.rangeBand());
};
}

My other obstacle is changing the fill color on click. I want it to almost imitate a checkbox, so clicking (to deselect) would turn the fill white. I tried something similar as .on("click",(".style" ("fill", "white"))). But that is incorrect.
Here is my fiddle. For some reason, the function isn't updating things on Fiddle. It works on my localhost though. Not sure the problem with that.

A: I'm not completely sure I understand you correctly, but if your first question is how to change element X when clicking on element Y, you need something along the lines of:
legendRect.on("click", function() {
  gbars.transition()
    .duration(500)
    .style("display", "block")
    // etc...
}

As for changing the fill on click, try:
gbars.on("click", function() {
  d3.select(this)
    .attr("fill", "white");
}


Q: C++ warning: Not all control paths return a value Well, I have some warnings that cause my program to crash, when I enter size 3.
Not all control paths return a value.
I am trying to solve N matrix, input, output and some operations. I store first column
 _vec[0:size-1],last column _vec[size : (size*2)-1]

and diagonal
 _vec[size*2 : size*3-2]

of matrix in 1-dimensional array. The size of array is size of matrix * 3 -2.  The problem occurs when I overload () operators:
int _size = (_vec.size() +2) /3;
// when I switch from vector size to normal matrix size. f.e vector size: 7,
// my matrix size is 3.

int Matrix::operator()(int i, int j) const
    {
        int _size = (_vec.size() +2) /3;
        if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
        if (i != j && j != 0 && j != _size - 1) return 0;
        else {
            if (j == 0)
            {
                return _vec[i];
            }
            else if (j == _size - 1)
            {
                return _vec[_size + i];
            }
            else if (i == j && j != 0 && j != _size - 1)
            {
                return _vec[(_size * 2) + i];
            }
        }
    }

    int& Matrix::operator()(int i, int j)
    {
        int _size = (_vec.size() +2) /3;
        if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
        if (i != j && j != 0 && j != _size - 1) throw NULLPART;
        else {
            if (j == 0)
            {
                return _vec[i];
            }
            else if (j == _size - 1)
            {
                return _vec[_size + i];
            }
            else if (i == j && j != 0 && j != _size - 1)
            {
                return _vec[(_size * 2) + i];
            }
        }
    }

A: Change the code like below for second function as well.
int Matrix::operator()(int i, int j) const
{
    int _size = (_vec.size() + 2) / 3;
    if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
    if (i != j && j != 0 && j != _size - 1) return 0;
    else {
        if (j == 0)
        {
            return _vec[i];
        }
        else if (j == _size - 1)
        {
            return _vec[_size + i];
        }
        else if (i == j && j != 0 && j != _size - 1)
        {
            return _vec[(_size * 2) + i];
        }
    }
    return 0; // added this line
}

A: It requires some analysis to prove that all cases return.
And it seems your compiler doesn't do the full analysis
int Matrix::operator()(int i, int j) const
{
    int _size = (_vec.size() + 2) /3;
    if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
    if (i != j && j != 0 && j != _size - 1) return 0;
    else {
        if (j == 0)
        {
            return _vec[i];
        }
        else if (j == _size - 1)
        {
            return _vec[_size + i];
        }
        else if (i == j && j != 0 && j != _size - 1)
        {
            return _vec[(_size * 2) + i];
        }
        else
        {
             // No return here.
             // But is this case reachable?
             // yes, for (i, j) respecting:
             //    (0 <= i && i < _size) && (0 <= j && j < _size)
             //    && ((i == j) || (j == 0) || (j == _size - 1)) // #2
             //    && (j != 0) && (j != _size - 1)               // #1
             //    && (i != j || j == 0 || j == _size - 1)       // #3
             // which after simplification results indeed in false.
             // #1 simplifies #2 to (i == j) and #3 to (i != j)
        }
    }
}

On the other part, that means that you do useless "tests" that you can remove (and so please the compiler):
int Matrix::operator()(int i, int j) const
{
    int _size = (_vec.size() + 2) /3;
    if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
    if (i != j && j != 0 && j != _size - 1) return 0;
    else {
        if (j == 0)
        {
            return _vec[i];
        }
        else if (j == _size - 1)
        {
            return _vec[_size + i];
        }
        else // We have necessary (i == j && j != 0 && j != _size - 1)
        {
            return _vec[(_size * 2) + i];
        }
    }
}


Q: Error in running RMIC via Ant using wsejbdeploy taskdef I get the following exception when trying to generate RMIC using Ant task.
[wsejbdeploy] Error generating RMI code: RMIC command failed on project: .... with message:
[wsejbdeploy] error: The IBM RMIC version 0x1500 does not match the IBM runtime version 0x1600.

Please let me know how to fix this.
I am trying this using the WebSphere 6.1 server that comes bundled with RAD7.5.
This works fine when we use IDE to generate the EAR, and fails only when we use our custom Ant build file.

A: The error means that JAVA_HOME in your shell used to invoke Ant is different from the Java that was included with the embedded WebSphere Application Server.  Try using the WAS_HOME/bin/ws_ant script, or set JAVA_HOME to WAS_HOME/java/.

A: The error
Cannot run RMIC because it is not installed. Expected location of RMIC is the following:
will some times confuse. enable the "Capture RMIC verbose output to the workspace .log file.
and see what the exact error your getting. This option will be available in properties > EJBDeployment.
In My case it throwing error due to huge number of jars in class path.It got resolved after shortening the class path jar location.


Q: Rails - 3 nested models in one view I'm struggling with grasping the fundamentals behind writing model methods, which is I think what I need to do to get this to work. Basically, I have a project view that's showing project_todos that belong to that project. Then nested under that I have project_todo_comments that belong to a project_todo. All in one view.
I've set up the associations so that project has_many project_todos, project_todo belongs_to project and has_many project_todo_comments. Then of course project_todo_comment belongs_to project_todo.
In the projects controller, I'm doing this:
  def show
    @project = Project.find(params[:id])

    # Display the form to create a new todo
    @project_todo = ProjectTodo.new

    # Create the instance variable to display the loop in the view
    @todos = @project.project_todos

    # Display the form to create a new comment
    @project_todo_comment = ProjectTodoComment.new

     # Create the instance variable to display the loop in the view
    @comments = @project.project_todo_comments

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @project }
    end
  end

So this is working to the point where I can add todos on a project and display them, and I can also add comments to project todos and display them too, all in that same view. BUT, I'm having difficulties getting the comments to display ONLY with the todos that they're associated with. Right now, when I add a comment on any todo, every single todo then displays that comment.
In the view, here's where I'm displaying the project_todos and nesting the form to add a comment, then displaying the comments:
 <% @todos.each do |todo| %>

<%= todo.title %>

    <%= form_for(@project_todo_comment) do |f| %>
        <%= f.hidden_field :project_todo_id, :value => @project_todo.id %>
        <%= f.hidden_field :project_id, :value => @project.id %>
        <%= f.text_area :comment %>
        <%= f.submit 'Add Comment' %>
    <% end %>

    <% @comments.each do |comment| %>
        <%= comment.comment %>
    <% end %>

  <% end %>

I've been told that I need to write a model method to get this to work, but I'm still trying to understand those. Could anyone just reassure that I do in fact need to write a model method, and point me in a direction to learn about them? Thanks!

A: In your controller you get all of the comments, but in an actual todo item you just want the comments for that item. This can be done with: todo.project_todo_comments
The easiest way to solve:
- <% @comments.each do |comment| %>
-   <%= comment.comment %>
- <% end %>

+ <% todo.project_todo_comments.each do |comment| %>
+   <%= comment.comment %>
+ <% end %>

You can remove the line from your controller:
- @comments = @project.project_todo_comments

However in your form (where you create a comment) you use the wrong ID for the todo item:
- <%= f.hidden_field :project_todo_id, :value => @project_todo.id %>
+ <%= f.hidden_field :project_todo_id, :value => todo.id %>

By the way, I would just name those models:
Todo and Comment, there is no point using that long modelnames. You define those associations in the start of your model, so if someone would read it, he/she would see it instantly.
For example see myself, I knew what was the purpose of your models still misused the namings, cause of too long classnames.


Q: Why isn't transition for my input forms working? I have tried to add transitions to my input forms but it doesn't work. I've read a lot of stack overflow posts but they haven't worked for me. A person said that it's because input has display: none but even after changing it, it still didn't work. I tried to be more specific when using transition but that didn't work. So I'm not sure how to fix this issue. The transition applies to the button but not to the input forms.
https://codepen.io/i-am-programming/pen/gOmydqv
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>

      Home
      About
      Store
      Contact Us

Log In

      <input type="text" placeholder="Username" class="username info" />
      <input type="password" placeholder="Password" class="pass info" />
      <input type="button" class="button" value="Submit" />

* {
  margin: 0;
  padding: 0;
  font-size: 25px;
  font-family: "Montserrat", sans-serif;
}

body {
  background: url("images/background.jpeg");
  background-size: cover;
}

a {
  text-decoration: none;
  margin-right: 30px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 8px;
  transition: 0.3s ease;
}

nav {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

a:hover {
  color: black;
  background-color: rgba(255, 255, 255, 0.7);
}

.container {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 450px;
  background-color: rgba(0, 0, 0, 0.7);
  align-items: center;
}

.login {
  color: white;
  margin-top: 50px;
  font-size: 45px;
}

input {
  outline: none;
  padding: 5px;
  transition: 0.3s;
}

input:hover {
  width: 400px;
}

.username {
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.pass {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.button {
  width: 150px;
  margin-top: 250px;
}

A: I think you are missing transition property in the input, it will be like this:
input {
  height: 30px;
  width: 300px;
  outline: none;
  transition: all 0.5s ease;
}

input:hover {
  width: 500px;
}

Read more of the CSS transition

A: Firstly your code in text and link are different. Secondly you can't use transition on display cause it's not animatable. You cna use opacity and visibility instead of display. If we come to our question..
You want to get bigger input place when user get hover it right? So in your example your input does not has any width and when you hover it you want to get a transition. For this you need to add a width value to your input so it will know where the change began and what you want at the end. Meanwhile the time you passed is your time attribute on your transition. So
input {
  height: 30px;
  width: 300px;
  outline: none;
   transition: 0.3s;
}

input:hover {
  width: 400px;
}

It will know that when user hover on it, it will grow to 400px from 300px in 0.3s. That's it. Hope you get it.

A: It's because you didn't specify the width of your input


Q: can not use http.begin() in HTTPClient Arduino Library to open my IP i have an esp32 cam with 192.168.1.54:8082 IP.
i want use from http.begin ("http://192.168.1.54:8082"); in  HTTPClient Arduino Library that not working while when i am using "http://192.168.1.54:8082" in a browser working fine.
any help can be useful.
#include <HTTPClient.h>

HTTPClient http;

http.begin("192.168.1.54:8082"); //Not Working Here (but in a browser 192.168.1.54:8082 works fine)
int httpCode = http.GET();
if (httpCode > 0) {
  String payload = http.getString();
  Serial.println(httpCode);
  Serial.println(payload);
}
else {
  Serial.println("Error on HTTP request");
}
http.end();

A: The API for http.begin(url) assumed standard port of 80 or 443 is used. In order to use port 8082, you need to pass in the port as function argument like this:
http.begin("192.168.1.54", 8082);


Q: Netsuite PHP Toolkit - Limit returned fields in Saved Search I'm working on an integration for Netsuite. When I return my saved search, there are 300+ fields returned for the searchRowBasic property. I'll include a var_dump below.
My source code is from Magento 2, so the factory methods are out of scope, but you can assume they create a new instance of the class (which i'll note).
I'm also using the composer package for netsuite to utilize namespaces rather than Netsuite's official package that is one file with 1600 classes and no namespaces (seriously).
/** @var Netsuite\Classes\ItemSearchAdvanced $searchRecord */
$searchRecord = $this->itemSearchAdvancedFactory->create();
/** @var Netsuite\Classes\SearchRow $searchRow */
$searchRow = $this->itemSearchRowFactory->create();
/** @var Netsuite\Classes\SearchRowBasic $searchRowBasic */
$searchRowBasic = $this->itemSearchRowBasicFactory->create();

/** @var Netsuite\Classes\SearchRequest */
$request = $this->searchRequestFactory->create();
$searchRecord->savedSearchId = 190;
$request->searchRecord = $searchRecord;

/** @var Netsuite\NetsuiteService $netsuiteService */
// Loaded with authentication values.
$netsuiteService = $this->getNetsuiteService();
$netsuiteService->setSearchPreferences(false, 1000);

// Submit the request - returns successful response.
$searchResponse = $netsuiteService->search($request);

My Request returns a successful response (:thumbsup:)
The problem is that I want to use 4 variables in the entire response, but there are hundreds of indexes in the array that are unused. My biggest concern is that Netsuite is querying these during the response, my secondary concern is returning multiple KB's of data that I won't use within my response for larger requests.
I have tried this, to unset the parameters, hoping that if I undeclared them, Netsuite would ignore them in the response, but I had no luck.
protected function getSearchRecord(): ItemSearchAdvanced
{
    $searchRecord = $this->itemSearchAdvancedFactory->create();
    $searchRow = $this->itemSearchRowFactory->create();
    $searchRowBasic = $this->itemSearchRowBasicFactory->create();

    $i = 0;
    $fields = $searchRowBasic::$paramtypesmap;
    foreach ($fields as $name => $type) {
        // use only the first 10 just to see if only these 10 will be used.
        // no such luck.
        if ($i > 10) {
            unset($searchRowBasic::$paramtypesmap[$name]);
            unset($searchRowBasic->$name);
        }

        $i++;
    }

    $searchRow->basic = $searchRowBasic;
    $searchRecord->columns = $searchRow;

    return $searchRecord;
}

Question:
I know the fields I want to return before I make the request. How can I specify those fields to only return the data I need, not all the data available?
Here is a var_dump of the response to see the format. I truncated the data a good amount, if anyone needs more I can easily provide it, but I think there is enough info provided currently.
class NetSuite\Classes\SearchResponse#2452 (1) {
    public $searchResult =>
    class NetSuite\Classes\SearchResult#2449 (8) {
        public $status =>
        class NetSuite\Classes\Status#2447 (2) {
        public $statusDetail =>
        NULL
        public $isSuccess =>
        bool(true)
        }
        public $totalRecords =>
        int(1)
        public $pageSize =>
        int(1000)
        public $totalPages =>
        int(1)
        public $pageIndex =>
        int(1)
        public $searchId =>
        string(60) "<requst_id_with_personal_data>"
        public $recordList =>
        NULL
        public $searchRowList =>
        class NetSuite\Classes\SearchRowList#2475 (1) {
        public $searchRow =>
        array(1) {
            [0] =>
            class NetSuite\Classes\ItemSearchRow#2476 (23) {
            public $basic =>
            class NetSuite\Classes\ItemSearchRowBasic#2477 (322) {
                public $accBookRevRecForecastRule =>
                NULL
                public $accountingBook =>
                NULL
                public $accountingBookAmortization =>
                NULL
                public $accountingBookCreatePlansOn =>
                NULL
                public $accountingBookRevRecRule =>
                NULL
                public $accountingBookRevRecSchedule =>
                NULL
                public $allowedShippingMethod =>
                NULL
                public $alternateDemandSourceItem =>
                NULL
                public $assetAccount =>
                NULL
                public $atpLeadTime =>
                NULL

                (more elements)...
            }
            public $assemblyItemBillOfMaterialsJoin =>
            NULL
            public $binNumberJoin =>
            NULL
            public $binOnHandJoin =>
            NULL
            public $correlatedItemJoin =>
            NULL
            public $effectiveRevisionJoin =>
            NULL
            public $fileJoin =>
            NULL
            public $inventoryDetailJoin =>
            NULL
            public $inventoryLocationJoin =>
            NULL
            public $inventoryNumberJoin =>
            NULL

            (more elements)...
            }
        }
        }
    }
}

A: After searching through the XML response from the server, it looks like Netsuite was responding with only the columns declared in my saved search as I wanted. The other null values I was receiving were initialized as default values when the response object was initialized.


Q: Use X,Y coordinates to plot points inside a circle Is there a way in javascript to plot x,y coordinates so they fall into a circle rather than a square?
For example if I have the following code:
  circleRadius = 100;
  context.drawImage(img_elem, dx, dy, dw, dh);

I need to figure out a combination of x,y values that would fall inside a 100 pixel circle.
Thanks!

A: *

*choose an x at random between -100 and 100

*a circle is defined by x^2 + y^2 = r^2, which in your case equals 100^2 = 10000

*From this equation you can get that y^2 = 10000 - x^2 , therefore the points with a chosen x and y = +/-sqrt(10000 - x^2) will lye on the circle.

*choose an y at random between the two coordinates found at point 3

*You're set!

EDIT:
In JS:
var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;

Another edit: a jsFiddle Example

A: If you want equidistributed coordinates you better go for
var radius = 100
var center_x = 0
var center_y = 0

// ensure that p(r) ~ r instead of p(r) ~ constant
var r = radius*Math.sqrt(Math.random(1))
var angle = Math.sqrt(2*Math.PI)

// compute desired coordinates
var x = center_x + r*Math.cos(angle);
var y = center_y + r*Math.sin(angle);

If you want more points close to the middle then use
var r = radius*Math.random(1)

instead.

A: not sure what you mean for javascript but
x = R*cos(theta) and y = R*sin(theta) are the Cartesian points for a circle. R is the radius of course and theta is the angle which goes from 0 to 2*Pi.

A: I'm posting this as a solution because this question was the only relevant result in google.
My question/problem was how to add cartesian coordinates inside a circle where x and y would not exceed r.
Examples:

*

*plot: (45,75) inside a circle with a radius of 100 (this would normally fall inside the circle, but not the correct position)

*plot: (100,100) inside a circle with a radius of 100 (this would normally fall outside the circle

Solution
// The scale of the graph to determine position of plot
// I.E. If the graph visually uses 300px but the values only goto 100
var scale = 100;

// The actual px radius of the circle / width of the graph
var radiusGraph = 300;

// Plot the values on a cartesian plane / graph image
var xCart = xVal * radiusGraph;
var yCart = yVal * radiusGraph;

// Get the absolute values for comparison
var xCartAbs = Math.abs( xCart );
var yCartAbs = Math.abs( yCart );

// Get the radius of the cartesian plot
var radiusCart = Math.sqrt( xCart * xCart + yCart * yCart );

// Compare to decide which value is closer to the limit
// Once we know, calculate the largest possible radius with the graphs limit.
// r^2 = x^2 + y^2
if ( xCartAbs > yCartAbs ) { // Less than 45°
    diff = scale / xCartAbs;
    radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( yCartAbs * diff, 2) );
} else if ( yCartAbs > xCartAbs ) { // Greater than 45°
    diff = scale / yCartAbs;
    radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( xCartAbs * diff, 2) );
} else { // 45°
    radiusMaximum = Math.sqrt( 2 * ( radiusGraph * radiusGraph ) );
}

// Get the percent of the maximum radius that the cartesian plot is at
var radiusDiff = radiusCart / radiusMaximum;
var radiusAdjusted = radiusGraph * radiusDiff;

// Calculate the angle of the cartesian plot
var theta = Math.atan2( yCart, xCart );

// Get the new x,y plot inside the circle using the adjust radius from above
var xCoord = radiusAdjusted * Math.cos( theta );
var yCoord = radiusAdjusted * Math.sin( theta );

A: Not sure if this is correct JavaScript code, but something like this:
for (x = -r; x < r; x++) {
  for (y = -r; x < r; y++) {
    if ((x * x + y * y) < (r * r)) {
      // This x/y coordinate is inside the circle.
      // Use <= if you want to count points _on_ the circle, too.
    }
  }
}


Q: Styling buttons for Microsoft Outlook I am currently setting up my first newsletter i Mailchimp. After checking the newsletter in different email clients I can see that my "buttons" does not look right in Outlook.
Below is my code for the button;

Shop Now

This gives me the following result in most email clients;

Although when i look in Outlook the text is not vertical centered and without rounded corners;

How can i make the button in Outlook look the same as in the other email clients?

A: ...I would suggest setting the line-height the same as the font-size and playing with the link's padding to get the same result. I am certain that this is causing the issue.


Q: Dart code acts differently in my Flutter application. List' is not a subtype of type 'List> When I run this in a "Dart" main, everything works, and I get a List of attendees.  However, when I call it within my Flutter application, I get the error:
flutter: type 'List' is not a subtype of type 'List>'
I have been round and round with the "not a subtype" error in Dart, and I finally was able to get all of the casts correct for my json data that is coming from a REST interface.
Can someone tell me, why is it bombing in Flutter but not in Dart?  How do I resolve this?
Future<List<Attendee>> callLogin() async {
return http.get(
        "http://www.somesite.com")
    .then((response) {
  try {
    List<Attendee> l = new List();
    final List<Map<String, dynamic>> responseJson =
        json.decode(response.body)['attendees'];
    responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
    return l;
  } catch (e) {
    print(e);  // Just print the error, for SO
  }
});

}
class Attendee {
  String nameFirst;
  String nameLast;
  String company;
  ...
factory Attendee.fromJson(Map<String, dynamic> json) {
  return new Attendee(
    nameLast: json['nameLast'],
    nameFirst: json['tnameFirst'],
    company: json['company'],
    city: json['city'],
    state: json['state'],
    country: json['country'],
  );
}

class AttendeeSearch extends StatefulWidget {
  AttendeeSearch({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _AttendeeSearchPageState createState() => new
  _AttendeeSearchPageState();
}

class _AttendeeSearchPageState extends State<AttendeeSearch> {

  String search;

  final _suggestions = new List<Attendee>();
  final _smallerFont = const TextStyle(fontSize: 12.0);
  final formKey = new GlobalKey<FormState>();

  void _submit() {
    final form = formKey.currentState;
    if (form.validate()) {
      form.save();
    }
    AttendeeSummaryRequest asr = new AttendeeSummaryRequest();
    setState(() {
      asr.callLogin().then((item) { // Calling WebService
      setState(() {
        _suggestions.addAll(item);
      });
    });
  });
}

A: For anyone who hits this issue, I did the following...
Future<List<Attendee>> callLogin() async {
return http.get(
    "http://www.somesite.com")
.then((response) {
  try {
    List<Attendee> l = new List();

//  final Map<String, dynamic> responseJson = // REPLACED
    final dynamic responseJson =              // <<== REMOVED CAST to Map<String, dynamic>
                                              //
        json.decode(response.body)['attendees'];
    responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
    return l;
  } catch (e) {
    print(e);  // Just print the error, for SO
  }
});

Normally I don't attempt to answer my own questions.  And, in this case I still do not have a true answer why Flutter acts differently than running the code from the Dart main.  I am running them both from Android Studio.  So, I would assume that Dart, in both cases would be the same version.  But, that is where I am looking next.  I will post if I have more information.