text:
Q: Implementing load balancing on any Linux distro I am thinking of implementing a load balancing solution for personal use.
What I want to do, is to maximize data throughput over mobile phone Internet connections. Let me be clear:
I have data plan in my mobile phone and my family have their respective data plans in their phones, too. If I can connect up to 4 phones in one (desktop) PC (through USB preferably) then I will achieve (theoretically) a faster Internet connection than any one of the 4 phones can achieve (if I connect them to a PC).
That desktop computer will then act as a router for an intranet.
If the above has a sound basis (I could be wrong - don't know the technologies involved in great detail), I need a how to to implement that.
I have seen that the tool for the job is ipvs (right?) but no how to.
Distro-wise the job can be done in any distro, but I know that connecting an Android phone with Ubuntu works plug and play.
So If I can do it in Ubuntu, it will probably be faster than compiling everything from strach.
Is there a relative how to? Is there a distro perhaps that does load balancing, and identifies USB internet connections on the fly?

A: It could be possible - ispunity is a project that load balances your internet connection.  It's written in Ruby.  They've got it running on a Raspberry Pi, so it should run on any reasonable distro.
The only difference between theirs and your scenario is that they used Ethernet whereas you're proposing to use 3G.  I suppose much of your success (or failure) depends on how your 4 mobile phones present their Internet on USB.
As Rasberry Pi usually runs a variant of Debian, then maybe start with that or Ubuntu.

A: To balance outgoing connections all you need is standard iptables and some policy routing. This does get a bit complex with 4 connections as you will need to reconfigure and rebalance the links as connections come and go.
The raw iptables setup is

*

*Create a routing table for each connection
ip rule add fwmark 10 table PHONE0 prio 33000
ip rule add fwmark 11 table PHONE1 prio 33000
ip rule add fwmark 12 table PHONE2 prio 33000
ip rule add fwmark 13 table PHONE3 prio 33000

*Add the default gateway for each connection to each table (the gateway IP will vary depending on each phones provider/setup)
ip route add default via 192.168.1.2 table PHONE0
ip route add default via 192.168.9.1 table PHONE1
ip route add default via 192.168.13.2 table PHONE2
ip route add default via 192.168.7.9 table PHONE3

*Randomly mark any unmarked flows, which will route the flow via a specific connection. OUTPUT is used for local processes. Use PREROUTING if you are forwarding traffic for other clients)
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark
iptables -t mangle -A OUTPUT -m mark ! --mark 0 -j ACCEPT
iptables -t mangle -A OUTPUT -j MARK --set-mark 10
iptables -t mangle -A OUTPUT -m statistic --mode random --probability 0.25 -j MARK --set-mark 11
iptables -t mangle -A OUTPUT -m statistic --mode random --probability 0.25 -j MARK --set-mark 12
iptables -t mangle -A OUTPUT -m statistic --mode random --probability 0.25 -j MARK --set-mark 13
iptables -t mangle -A OUTPUT -j CONNMARK --save-mark

*NAT for each of the connections (the interface will need to be whatever you phone connection appears to the system as)
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o ppp1 -j MASQUERADE
iptables -t nat -A POSTROUTING -o ppp2 -j MASQUERADE
iptables -t nat -A POSTROUTING -o ppp3 -j MASQUERADE

Note that a single TCP or UDP connection will see no speed up as it will still be going over a single link. You have to use multiple concurrent connections (at least 4) to make use of the extra bandwidth. Most browsers do this under the hood when requesting multiple objects. Some download managers allow you to use multiple connections for a single file.
As garethTheRed suggests, ispunity adds some of the "glue" on top of this iptables setup to loop through a list of connections, check that the gateway is responding, re balance if something is wrong etc.  It's "sticky session" management looks to be additional setup per port on top of it's base "round robin" load balancing of connections. Another solution is Net-ISP-Balance, a Perl script and library that automates the iptables and routing table configuration, monitors the ISP status, alerts you to problems, and reconfigures the routing in case one or more ISPs become inacessible.
Also note that having requests come from multiple IP's can break some services that are based on consistent IP lookups and you may need to add additional rules for those services to tie them to a connection. You won't see any speedup on single connections, only when you are doing 4 things at once, which most browsers will try to do anyway.
ipvs is more for creating a virtual service addresses for things you host so the service can be failed over between multiple hosts.

A: dispatch-proxy
Using dispatch-proxy one can combine many Wi-Fi networks/Ethernet/3G/4G connections and have access to them as one big, high-bandwidth, load balanced connection. Do note that to make use of higher-connection speed, user must use a threaded download manager which will open multiple connections to dispatch-proxy and it will effectively fetch them using multiple interfaces resulting in combined, faster download speeds.
instruction to install for mac, also works for linux.
ISP unity
ISPUnity is an opensource rubygem/software based multiple internet load balancer and failover.
For mobile internet I recommend dispatch-proxy as you don't configure any setting as in ISP unity.
this link comment about a patched linux kernel for inbuilt load balancing you may have a look.


text:
Q: Open and Execute a Music.mp3 and the Code Program in C using Ubuntu GCC Hellow, guys... I'm creating a game and I want to add a music to play in BG.
I tried system("mpg123 ./bgm/1.mpe") inside the code, but, this program will run the music until the end... so, the user needs to wait for the end...
I need to play a music simultaneously while user plays the Program. Any ideas?
I thought about opening the song in a new process with gnome-terminal -e but I could not.
THE GAME IS A SIMPLE TERMINAL GAME LIKE SNAKE OR ANYTHING ELSE

redpajama_set_name: RedPajamaStackExchange


text:
Q: Giving QML a QSharedPointer or a std::unique_ptr? According to the docs, "When data is transferred from C++ to QML, the ownership of the data always remains with C++. The exception to this rule is when a QObject is returned from an explicit C++ method call: in this case, the QML engine assumes ownership of the object, unless the ownership of the object has explicitly been set to remain with C++ by invoking QQmlEngine::setObjectOwnership() with QQmlEngine::CppOwnership specified."
As a C++ programmer, whenever I see a function return a raw pointer, I shudder. Why return a Foo* when you could return a std::unique_ptr<Foo> or at least a std::shared_ptr<Foo> or a QSharedPointer<Foo>? It seems like this functionality isn't built in. Obviously QML should be allowed to take a std::unique_ptr<Foo>. Is taking a QSharedPointer<Foo> really not supported? Is there some work-around?
Maybe something like this (inspired by http://doc.qt.io/qt-5/qtqml-cppintegration-data.html#value-types)?
template <typename T>
class QSharedNotNullPointerWrapper {
{
    Q_GADGET
    Q_PROPERTY(T& value READ value WRITE setValue)
public:
    QSharedNotNullPointerWrapper(const QSharedPointer<T>& ptr)
        : m_ptr(ptr) {
        Q_ASSERT(m_ptr); // Not-null
    }
    operator QSharedPointer<T>&() { return m_ptr; }
    const T& value() const { return *m_ptr; }
          T& value()       { return *m_ptr; }
    void setValue(const T &val) { *m_ptr = val; }
private:
    QSharedPointer<T> m_ptr;
};

#define DECLARE_SHARED_PINTER_METATYPE(NAME, T) \
  using NAME = QSharedNotNullPointerWrapper<T>; \
  Q_DECLARE_METATYPE(NAME)

If something like that works, then I could do
DECLARE_SHARED_PINTER_METATYPE(MyFooPtr, Foo)

and then have a function return a MyFooPtr and safely hand it to QML or to C++.


text:
Q: Combine and sort 2 arrays This question was asked somewhere else, but I just wanted to check if what I did was applicable given the rspec circumstances:

Write a method that takes two sorted arrays and produces the sorted array that combines both.

Restrictions:

*

*Do not call sort anywhere.

*Do not in any way modify the two arrays given to you.

*Do not circumvent (2) by cloning or duplicating the two arrays, only to modify the copies.

Hint: you will probably need indices into the two arrays.
combine_arrays([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]

Can you just combine the two arrays into a single array and then run a typical bubble sort?
def combine_arrays(arr1,arr2)
  final = arr1 + arr2
  sorted = true
  while sorted do
    sorted = false
    (0..final.length - 2).each do |x|
      if final[x] > final[x+1]
        final[x], final[x+1] = final[x+1], final[x]
        sorted = true
      end
    end
  end
  final
end

p combine_arrays([1,3,5],[2,4,6]) => [1, 2, 3, 4, 5, 6]

A: Here is a variant which relies solely on Ruby's enumerators.  The result is short and sweet.
# merge two sorted arrays into a sorted combined array
def merge(a1, a2)
  [].tap do |combined|
    e1, e2 = a1.each, a2.each
    # The following three loops terminate appropriately because
    #    StopIteration acts as a break for Kernel#loop.
    # First, keep appending smaller element until one of
    #    the enumerators run out of data
    loop { combined << (e1.peek <= e2.peek ? e1 : e2).next }
    # At this point, one of these enumerators is "empty" and will
    #    break immediately. The other appends all remaining data.
    loop { combined << e1.next }
    loop { combined << e2.next }
  end
end

The first loop keeps grabbing the minimum of the two enumerator values until one of the enumerators runs out of values.  The second loop then appends all remaining (which may be none) values from the first array's enumerator, the third loop does the same for the second array's enumerator, and tap hands back the resulting array.

A: Sure, you can do that but you are overlooking a real gimmee - the two arrays you are given will already be sorted.
def combine_arrays(A1, A2)
    retVal = Array.CreateInstance(System::Int32, A1.Length + A2.Length - 1)
    i = 0
    j = 0
    while i < A1.Length | j < A2.Length
        if i < A1.Length and self.A1(i) < self.A2(j) then
            self.retVal(i + j) = self.A1(i)
            i += 1
        else
            self.retVal(i + j) = self.A2(j)
            j += 1
        end
    end
    return retVal
end

A: This is based on the same logic as Dale M's post, but in proper ruby:
def combine_arrays(arr1,arr2)
  [].tap do |out|
    i1 = i2 = 0
    while i1 < arr1.size || i2 < arr2.size
      v1 = arr1[i1]
      v2 = arr2[i2]
      if v1 && (!v2 || v1 < v2)
        out << v1
        i1 += 1
      else
        out << v2
        i2 += 1
      end
    end
  end
end

combine_arrays([1,3,5], [2,4,6])

A: Take a look at this one:
def merge(arr1, arr2)
  arr2.each { |n| arr1 = insert_into_place(arr1, n) }
  arr1.empty? ? arr2 : arr1
end

def insert_into_place(array, number)
  return [] if array.empty?
  group = array.group_by { |n| n >= number }
  bigger = group[true]
  smaller = group[false]
  if bigger.nil?
    number > smaller.last ? smaller << number : smaller.unshift(number)
  else
    (smaller << number) + bigger
  end
end


text:
Q: Database-first EF7-7.0.0-rc1-final dnx ef dbcontext scaffold command fails I am using this command:
dnx ef dbcontext scaffold "Server=webuat08,1433,Database=Store;user
id=user_here;password=password_here" EntityFramework.MicrosoftSqlServer

The database "Store" exists. But I am getting the following error:
Unable to identify the primary key for table 'dbo.spt_fallback_db'.
Unable to generate entity type for table 'dbo.spt_fallback_db'.
Unable to identify the primary key for table 'dbo.spt_fallback_dev'.
Unable to generate entity type for table 'dbo.spt_fallback_dev'.
Unable to identify the primary key for table 'dbo.spt_fallback_usg'.
Unable to generate entity type for table 'dbo.spt_fallback_usg'.
Could not find type mapping for column
'dbo.MSreplication_options.optname'     with data type 'sysname'. Skipping column.
Unable to identify the primary key for table 'dbo.MSreplication_options'.
Unable to generate entity type for table 'dbo.MSreplication_options'.
Unable to identify the primary key for table 'dbo.spt_monitor'.
Unable to generate entity type for table 'dbo.spt_monitor'.
Done

If I change the name of the Database in the command to a DB that doesn't exist I still get the same error.  Any ideas?

A: You need to put the primary key in your tables


text:
Q: I want to estimate the incremental increase in turnover for an extra product option For example:
A shop sells sandwiches.  They find that if they sell $3$ types of sandwiches they sell more than they would if they only sold $2$ types of sandwiches.  However the increase in turnover between $2$ and $3$ is much greater than the increase in turnover between $99$ types of sandwiches and $100$ types.
What is the mathematical function for this and how would I calculate it please?
Thanks in advance

A: There is no way to calculate it.  You can collect real data (say from other sandwich shops) and create a model, but without that you can't say anything.


text:
Q: Avoiding angular dependency injection with use of global object I inherited some code that is using a global object to to store angular services. These services get attached to the global object in the run function of the angular module. My question is, can this lead to trouble down the road? What sort of trouble does this cause for testing? Passing around services like this seems a lot easier than injecting all of the services in each controller so I see why this is done. What are other arguments for not doing this? Here is some code to illustrate what I am talking about:
// vars
var globalObject =
{
    ng: {},
};

// Setup module
var myModule = angular.module("myModule", []);
myModule.config(doStuff);
myModule.run(setUpGlobals);

// Setup app globals
function setUpGlobals(ngRootScope, ngHttp, ngTimeout)
{
    globalObject.rootScope = ngRootScope;

    // angular services
    globalObject.ng.http = ngHttp;
    globalObject.ng.Timeout = ngTimeout;
}
setUpGlobals.$inject = ['$rootScope', '$http', '$timeout'];

A: This makes testing nightmaraish. Dependency Injection is great, because it means you can do some atomic tests, by mocking out the services you don't need. In a simple, non-convulted example, imagine a service that makes API calls via http, if you DI it in, your test can mock out the http and just fake a return, letting you test only the bits of code you want, and saving you from having a test that relies on the API, or worse a test suit that uses up your API calls. With the provider in the global scope, that's much more difficult to achieve.
Just one reason, i'm sure there are many others.

A: Modules and DI were introduced in Angular exactly to avoid relying on globals and improve modularity.
This is naive approach that only works if there is a single module and a single application instance. It will fail if there are several modules that can be used separately (including tests). It will produce awful bugs if there is more than one application instance on the page (for example, if Angular is used for non-SPA applications).
A monolith module hurts testability. Even if it is used like that, some options will be unavailable, e.g. injecting spied or stubbed services in $controller(...) - because a controller relies on globals.
setUpGlobals results in eager service instantiation. This may not be a problem for core services but will be a problem for services that don't need to be instantiated right now.
Less important concern is code size in minified application. ng.$rootScope can be minified to a.$rootScope but not any further. Annotated function should mention '$rootScope' string once, but $rootScope variable name can be minified to a. There will be improvements if a service is used more than once inside a function.
There's a lot of reasons why global variables are bad. Some of them won't be applicable in this case, other ones will.


text:
Q: Launch .net-assembly in its own process, pass it an object I am writing a VSTA 20151 enabled app.
In it, I need to load an assembly, access a well-known method (a constructor, not that it matters), invoke it, and pass it a COM object (wrapped up so it is a .net object naturally).
This works fine.  Now, in order to enable debugging, I need the process that the assembly is loaded from be different than the one that interacts with the VSTA subsystem.  The application interacts with the VSTA subsystem; which means I need the assembly to be loaded in a distinct process.
Is there a simple way to load a .net assembly in a separate process, passing it a com object (or a .net object wrapping the com object) to a well-known entry point?
The complex method would involve creating a custom .exe loader that loads the assembly, use IPC to get ahold of the COM interface, wrap it up and pass it to the assembly.  Then use IPC to return any error messages.  Not certain what kind of IPC I should use.  But there are a lot of moving parts here (the two IPC systems, the loader), and I'd hope there would be an easy way to do it without them.
I looked at System.Diagnostic.Process.Start, but it doesn't seem able to "open an assembly as a process and pass it this .net object" among the options.
Apartments (and similar) probably won't work, as the separate process is needed so that a debugger can attach to the VSTA "script" process and pause/advance it without locking up the VSTA "hosting" process (which in the docs says it can lead to deadlocks).
The application is mixed managed/unmanaged, if that matters.  Most of the managed component is C#, most of the unmanaged is C++, and most of the interface is C++/cli.

1 VSTA 2015 is a Microsoft solution to allow on-the-fly editing of a "script-like" environment of a .net language, where the Visual Studio IDE workflow is integrated with the application workflow.  Note that this is different than pre-VSTA 2012 in fundamental ways: pre-VSTA 2012 information or answers are unlikely to be useful here.


text:
Q: How to use .css() method with array? I need to apply style to all elements of class.
const history_cells = $(".history-cell");

for (var i = 0; i < history_cells.length; i++) {
    history_cells[i].css({"opacity": "1"});
}

But have

Uncaught TypeError: history_cells[i].css is not a function.

Where am I wrong?

A: jQuery handles collections of elements just as it would with a single element, so going
$(".history-cell").css({"opacity": "1"})

does the job.
On the other hand, I strongly recommend not to use inline styles. Rather do this:
$(".history-cell").addClass('opaque');

and add this class in your CSS:
.opaque { opacity: 1; }

A: This is a foreach loop syntax in jquery better than for loop

$(".a").each(function(i,e) {
   $(this).html(i);
});

A: You can get rid of the error in this simple way
$(history_cells[i]).css({"opacity": "1"});

However, you can also do it like below instead
$(".history-cell").css({"opacity": "1"});

A: Change little
const history_cells = $(".history-cell");

for (var i = 0; i < history_cells.length; i++) {
    $(history_cells[i]).css({"opacity": "1"});
}

A: You can use class using jquery 2 types.
First you can create CSS class then apply it.
$('your input').addClass('class Name');

For Ex:
$('.history-cell').addClass('opacity');

Second You can apply it directly using following:
$('your input').css({"your need(backgroundcolor, font or etc)":"value(color,size px or %)"});

For Ex:
$('.history-cell').css({"opacity": "1"});

Apply style using loop:
$(".history-cell").each(function(){
    $(this).css("opacity", "1");
    //Or use direct class is better
    $(this).addClass('opacity');
});


text:
Q: Database migration We are migrating a client's own database schema to our own (both SQL-Server). Most of the mappings from their schema to ours have been indentified and rules been agreed on if the columns don't exactly align (default values etc.)
Previously, depending on who was assigned the task, this has been done either with a mixture of sql scripts or one-off vb apps.
I was thinking there must be a application (commercial or otherwise) where you can assign these mappings/rules and have it stream the data across.  Surely the setting up and configuration of this tool would be less than the creation of ad-hoc scripts...
Is there an app? Apart from the obvious 'be careful' any tips to mitigate the stress of a non-DBA porting one schema to another?

A: You can use database migrations in your code.
There are several .net data migration libraries that were inspired by ruby migrations. They define database changes in code.

Migrations allows a developer to manage rollout, and rollback, of database schema changes in a controlled and consistent manner.

Look at these:

*

*SubSonic migrations

*Rails Migrations for .NET

*RikMigrations

*Migrator.Net

*MachineMigrations

A: I use an Open Source ETL (extract/transform/load) tool called Talend Open Studio for tasks like this.
In short, Talend Open Studio (TOS) is a GUI code-generation tool, in which you plug in different components to import, munge, and export data--and the resulting code is portable Java or Perl. There are plenty of components to help you make decisions about non-standard data (or you could always add your own Java or Perl routines for the most complex parts).
TOS has proved to be well worth the time I initially invested in it... so I would definitely recommend it.

A: Not really. Problem is that whatever app you would have would be more a frameowrk anyway. Schema transfers, by definition, are partially tricky to do. And a tool doing half of the stuff is nearly useless - that is easy to do in SQL anyway ;)

A: I do this sort of thing every day. because of the custom nature of our software, i usually one-off the whole thing. about 70% of the time, i use ms access as an intermediary (the rest of the time, i write code to do it). i load the source data into ms access, massage it and then move it into our sql server tables. access is very well suited for this type of work. the main thing to be careful about is your keys and duplicate restrictions. i'm sure there are off-the-shelf apps to do data migration, for my use, however, i need more control and ms access allows me to reuse some portions of the data import while maintaining the ability to customize everything.
best regards,
don

A: Try SQL Data Examiner.
This tool allows comparing/synchronizing sql-query results, so you can write appropriate queries to both databases and compare/synchronize results returned by these queries.


text:
Q: Include only var from one php file to another I have one variable in url.php.
I want to access it in multiple other files. I tried to include url.php in all those files. But there is one issue.
<?php
 include 'url.php';   //include url.php
 echo "My id is : $myid";
?>
<!DOCTYPE html>

//somecontent

url.php has html code including buttons, div etc. All of them get included when I include url.php.
How can I include only php variable and skip other html code from url.php.
url.php looks like this:
<?php
$myid=$_POST['myid'];
echo "myID is :
";
echo $myid;
?>

  //some othe html stuff

A: You can put some condition there like isset().
<?php
 if(isset($_POST['myid']))
  {
   $myid=$_POST['myid'];
   echo "myID is :
";
   echo $myid;
  }
 else{
?>

    //some othe html stuff

 <?php } ?>

A: The Other solution is you can save the variable in session and later you can retrieve the value in other pages also.
url.php
<?php
$myid=$_POST['myid'];
session_start();
$_SESSION['my_id']=$myid;
?>

You can use the variable like this.
useMyId.php``
<?
session_start();
$var=$_SESSION['my_id'];

echo "Here is the variable".$var;
?>

A: You can not do this. The only way is to remove the HTML and include that somewhere else. A call to include is opening the file then running eval on the content. If it contains vital UI parts of your site you should reconsider your design pattern.

A: you could declare a variable in every php file before including the url.php.
like this:
$uservar = 1;
then in your url.php put the html block in an if statement
if($usevar != 1){
HTML-BlOCK
}


text:
Q: API Request in ReactiveSwift I am beginner in ReactiveSwift. I create weather app and my request does not work.
func fetchCurrentWeather() -> SignalProducer<TodayWeatherData?, DownloadError> {
    guard let unwrappedURL = url else { return SignalProducer.empty }

    return URLSession.shared.reactive
        .data(with: URLRequest(url: unwrappedURL))
        .retry(upTo: 2)
        .flatMapError { error in
            print("Error = \(error.localizedDescription)")
            return SignalProducer.empty
        }
        .map { (data, response) -> TodayWeatherData? in
            do {
                let weatherArray = try JSONDecoder().decode(TodayWeatherData.self, from: data)
                return weatherArray
            } catch (let error) {
                print("\(error)")
                return nil
            }
        }
        .observe(on: UIScheduler())
}

self.weatherFetcher.fetchCurrentWeather().map { weather in

}

Map block is not called. What should i change in this request or in parsing method ?

A: You have to start your SignalProducer.
self.weatherFetcher.fetchCurrentWeather().startWithResult({ result in
    switch result {
       case .success(let weather): //use the result value
       case .failed(let error): //handle the error
    }

})

you also have

*

*startWithFailed()

*startWithValues()

*startWithCompleted()

*start()

in all cases, you have to "start" cold signals in order to make them work.


text:
Q: Haskell records setter export Is there any way to export record "getter" but not "setter"?
Example.
Assume we have M1.hs
module M1(customCtor, field1) where
  data DType = DCtor { field1 :: Int }
  customCtor = DCtor { field1 = 1 }

and M2.hs
import M1
modified = customCtor{ field1 = 3 }  -- how to prevent this?
main = putStrLn . show . field1 $ modified

I fould like to be able run field1 getter in M2.hs but not to update record outside of M1.
If it is possible, could you point me to relevant part of Haskell documentation?
If it is not, can you explain why?

A: One fairly easy option is to define a synonym and export that:
module M1(customCtor, getField1) where

data DType = DCtor { field1 :: Int }
customCtor = DCtor { field1 = 1 }

getField1 = field1

Here, getField1 is a "getter" function (type: DType -> Int) that gets field1 but doesn't have the additional status of being a record field for updates.


text:
Q: Cant validate a list of values for duplicates using Python and Cerberus I am fairly new to Python and Cerberus.
I have a requirement where I need to validate a list for any empty Strings or duplicates. Below is what I did:
import cerberus

myschema = {'uid': {'type': 'list', 'schema': {'type': 'string', 'required' : True}}}

cerberus.rules_set_registry.add('myschema', myschema)
newval = Validator(myschema)

test = {'uid' : {'10000', '10001', '10002', '10003', '10004', '10005'}}
newval.validate(test)

The output is always 'False' for some reason.
Alternatively, I tried the 'oneof' of-rules and came up with the below:
from cerberus import Validator
document = {'column_name' : ['BLAH', 'SEX', 'DOMAIN', 'DOMAIN']}

schema = {'column_name' : {'oneof' : [{'type': 'list', 'contains' : ['DOMAIN']}]} }
v = Validator(schema)
v.validate(document, schema)

The above always return True. I was hoping the 'oneof' can validate duplicates and the aforementioned is the right way.
Can anyone here please correct me if I am wrong.!
Thanks in advance,
Nix

A: test = {'uid' : {'10000', '10001', '10002', '10003', '10004', '10005'}}
This is not a valid representation of list in json. The following is
test = {'uid' : ['10000', '10001', '10002', '10003', '10004', '10005']}
That is why Cerberus returns false. You could use print(newval.errors) to print all the errors for that json object.
As for oneOf, Cerberus will validate that your items in the list will meet exactly one of the constraints mentioned in the constraint list. It doesn't check the relationship between the elements.

A: Alright.
I couldn't find an answer with Cerberus validator to check duplicates in a list.
I checked Json Schema where it is really easy. Below is the code:
from jsonschema import validate

schema = { "type": "array", "uniqueItems": True}

mylist  = ['1000', '1001', '1010', '1011', '1100', '1101', '1110', '1000']

# Returns None if validated; else a validation error
validate(instance = mylist, schema = schema)

In Cerberus, validation returns a True if validated right; else False. Whereas, Json Schema returns a None (in Python) if validated right else, throws a validation error as given below:
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
<ipython-input-1-efa3c7f0da39> in <module>
      5 mylist  = ['1000', '1001', '1010', '1011', '1100', '1101', '1110', '1000']
      6
----> 7 ans = validate(instance = mylist, schema = schema)
      8 if(ans == None): print('Validated as True')

~/Library/Python/3.8/lib/python/site-packages/jsonschema/validators.py in validate(instance, schema, cls, *args, **kwargs)
    932     error = exceptions.best_match(validator.iter_errors(instance))
    933     if error is not None:
--> 934         raise error
    935
    936

ValidationError: ['1000', '1001', '1010', '1011', '1100', '1101', '1110', '1000'] has non-unique elements

Failed validating 'uniqueItems' in schema:
    {'type': 'array', 'uniqueItems': True}

On instance:
    ['1000', '1001', '1010', '1011', '1100', '1101', '1110', '1000']


text:
Q: Issue with UIDocumentMenuViewController I have implemented UIDocumentMenuViewController in my application with below code
_importMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:[MingleUtils allowedUTIs] inMode:UIDocumentPickerModeImport];
_importMenu.delegate = self;
 [self presentViewController:_importMenu animated:YES completion:nil];

It is working but picker is taking time to appear and sometimes getting error "couldnt comunicate with helper application"
Can anyone help me in this?


text:
Q: Angular search array value from input I need to search the name which i need to take the value of search from input and search in array. I need to take the input of name and search it in array and show only that name data.
Also attach the data console . in array there is member_name i need to take input and show only that member_name data only.
This is how im taking input

         Search Name
               <input type="search"
               class="form-control" placeholder="Search Name">

How the data is showing in .html

                              STATUS
                              Name
                              Patient Name
                              Claimed Amount
                              Company
                              Submitted By

                                    Submitted
                                    Settled
                                    Rejected
                                    Approved
                                    Objection claim

                                {{x.member_name}}

                              {{x.patient_name}}
                              {{x.claimed_value}}

                                  Airlink Communication
                                  Ascertia (Pvt) Ltd
                                  Frontier Works Organization
                                 Ebryx (pvt) Ltd
                                  HY Enterprises (Pvt) Limited
                                 Naimat Saleem trust NST (US GROUP)
                                 Samad Rubber Works (Pvt) Ltd
                                Sundry Clients
                                TIMEXPERTS (PRIVATE) Limited
                                US Apparel & Textile (Pvt) Limited
                                US Denim Mills (Pvt) Limited

                              {{x.submitted_at || 'not-defined'}}

A: By using Angular's Pipe:
HTML Code:
<input type="text" class="form-control" [(ngModel)]="searchText" placeholder="Search item" name="search"
        autocomplete="off">

                STATUS
                Name
                Patient Name
                Claimed Amount
                Company
                Submitted By

                    Submitted
                    Settled
                    Rejected
                    Approved
                    Objection claim

                                {{x.member_name}}

                    {{x.patient_name}}
                    {{x.claimed_value}}

                        Airlink Communication
                        Ascertia (Pvt) Ltd
                        Frontier Works Organization
                        Ebryx (pvt) Ltd
                        HY Enterprises (Pvt) Limited
                        Naimat Saleem trust NST (US GROUP)
                        Samad Rubber Works (Pvt) Ltd
                        Sundry Clients
                        TIMEXPERTS (PRIVATE) Limited
                        US Apparel & Textile (Pvt) Limited
                        US Denim Mills (Pvt) Limited

                    {{x.submitted_at || 'not-defined'}}

Filter Component
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'userFilter'
})
export class FilterPipeForUserSearch implements PipeTransform {
    transform(items: any[], searchText: string): any[] {
        if (!items || !searchText) return items;
        searchText = searchText.toLowerCase();
 return items.filter(it => {
            return it.productId==searchText;
        });
    }

}

To Filter with the all the fields Use following filter Component
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filterForUser'
})
export class FilterPipeForUserSearch implements PipeTransform {
    transform(items: any[], searchText: string): any[] {
        if (!items || !searchText) return items;
        searchText = searchText.toLowerCase();
            return items.filter((data) => this.matchValue(data,searchText));
    }
    matchValue(data, value) {
        return Object.keys(data).map((key) => {
           return new RegExp(value, 'gi').test(data[key]);
        }).some(result => result);
      }
}

to show results, when user will type anything in search box only
 if (!items || !searchText) return [];

NOTE: Please declare FilterPipeForUserSearch in app / any other Module

A: I have done it by very short method its solve my problem .
 <input type="text" class="form-control" [(ngModel)]="userFilter.member_name"
  placeholder="Search name" name="search">

               {{x.member_name

 userFilter: any = { member_name:'', status:'', company_id: ''};


text:
Q: Is there a way to find a single occurence of a digit in a vector and ignore duplicates in R? I have an array of numbers and I'd like to find the index of a specific digit ONLY when it's occuring alone, NOT when it's occuring in a sequence of the same digit.
For example:
a <- c(1,2,4,5,5,8,1,2,8,8,8,4,3)

I would like to find the index of the SINGLE 8 occuring at index 6, I'm not interested in any of the other digits, nor in the sequence of 8's occuring at index 9-11.
Is there a clever way to do this in R?

A: An option would be rle.  Apply the rle on the vector, create a logical index based on the values and lengths, and then wrap with which on the replicated logical vector
which(with(rle(a), rep(values == 8 & lengths == 1, lengths)))
#[1] 6


text:
Q: how to create a VS2015 project inside a specific directory with a specific projectname? Not sure how to describe my question and ok here it goes:
We already have some existing projects created and under TFS source control.
A typical project is then stored locally as:
SomeDir\SomeNameSpace.SomeName\ProjectName\
then the csproj and sln file inside that directory will be named: SomeNameSpace.SomeName.ProjectName
Now when I want to create that same setup using Visual Studio it goes horribly wrong:
I have tried all possible options on creating a project and either it creates an extra SomeNameSpace.SomeName.ProjectName folder extra under the ProjectName directory and puts the sln and csproj inside that dir or I can create a Project under the proper ProjectName dir only then the name of the sln and csproj files will be ProjectName.snl/csproj which is neither what I want.
Renaming them of course would be the logical thing to do, however, doing that causes the sln to go corrupt. When I try to reopen it will throw a Save as DevEnv.sln in my face and that is not what I want.
Edit: Of course I have renamed inside the sln and csproj file which neither led me to the solution
So how can I create a new VS2015 solution that will nicely sit under
    \SomeDir\SomeNamespace.SomeName\ProjectName\ with
    SomeNameSpace.SomeName.ProjectName.sln and
    SomeNameSpace.SomeName.ProjectName.csproj as it's name?
What am I missing, that it seems impossible to achive this in a simple manner?

A: Create the Project from the New Project VS Window. The settings you need are:

*

*Name: ProjectName

*Do NOT create directory for solution

This should create the csproj and sln files in the appropriate directory.
From here, right clic on the project in Solution Explorer -> Rename -> SomeNameSpace.SomeName.ProjectName
This way, the solution reference will be updated too.
Now, rename the solution too, from Solution Explorer.
File menu, Save All. This saves both the project AND the solution.
And I think that's it.

A: You should in your new project window have it look like this

Please note the highlighted aria is unticked

A: Ok we have figured it out.
The solution as posted by A. Chiesa was almost right.
The solution, projects and namespaces need to be set.
 - Rename the Solution within the "Solution Explorer" for example name it "NameSpace.SomeName.ProjectName"
 - Rename the Project within the "Solution Explorer" for example also name it "NameSpace.SomeName.ProjectName"
 - Go to the project properties and rename within Application the "Assembly name:"  for example also name it "NameSpace.SomeName.ProjectName"
 - Go to the project properties and rename within Application the "Default namespace:"  for example also name it "NameSpace.SomeName.ProjectName"
Then if you are lucky, you can use Resharper to rename the namespace for all files throughout your project or you have to do it manually (depending on files count can be a very tedious job to do).
That should do it.
Thanks everyone for your input and advice.
Best regard,
Ed


text:
Q: override preferredStatusBarStyle in UIViewConrtoller extension I'd like to override preferredStatusBarStyle in an extension of UIViewController like this:
extension UIViewController {
    open override var preferredStatusBarStyle: UIStatusBarStyle {
      return .lightContent
    }
}

The compiler throws this error Getter for 'preferredStatusBarStyle' with Objective-C selector 'preferredStatusBarStyle' conflicts with method 'preferredStatusBarStyle()' with the same Objective-C selector
Applying the same override to UINavigationController instead of UIViewController works; but preferredStatusBarStyle is a var that is inherited by UIViewController.
-> Why is it possible to apply this extension to UINavigationController but not to UIViewController

A: You can't override (re-declare implementation of) already implemented properties this way via extensions in Swift on a class which introduces the property.
You should definitely create a UIViewController subclass and use it app-wide instead.
There's an option, however. You can override this using Objective-C by providing an extending category, similar thing applied to UIFont answered here: Is there a way to change default font for your application. However, it's not completely safe to do so and you should expect unicorns to come when not careful enough.


text:
Q: CodeIgniter 404 not found controller I know the question has been asked many times but I really can't solve the issue.
My default controller is working, but if I want to access another controller I will have the 404 issue.
My controller file name has the upper case as Utilisateur.php,
So I'm trying to access the Controller function inscription by inscription
Here is my config:
$config['base_url'] = 'http://localhost:63342/WeBusy/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

Here is my rooting:
$route['default_controller'] = 'accueil';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

And finally the controler:
class Utilisateur extends CI_Controller {

    public function inscription(){
        $data = array('header' => 'HeaderAccueil.php', 'body' => 'utilisateur/AjoutUtilForm.php');
        $this->load->view('StructureHtml.php', $data);
    }

Thanks

A: Give complete path to your anchor
inscription

But the best practice is to give dynamic url like using url helper or constants.
For Example if use url helper function your anchor path is like.
<a href="<?php echo site_url(); ?>Utilisateur/inscription">inscription

Don't forget to load url helper in your autoload file or your class constructor.

A: I found the issues,
So I needed to create a .htaccess file in the root of the applicaiton in order to remove the index.php AND this still doesn't work with phpstorm, maybe there is something to configure but it is working smoothly on EasyPhp :)

A: *

*Check your controller filename, should be Utilisateur.php (ucfirst).

*Check if your mod_rewrite works:

*

*http://localhost:63342/WeBusy/index.php?q=utilisateur/inscription

*add new method index() {die('test');} to your Utilisateur controller and change $route['default_controller'] = 'accueil'; to: $route['default_controller'] = 'utilisateur';


text:
Q: VBA / Minor HTML / Javascript: Click a tricky hidden checkbox in a report I get a report daily for work and I use excel to make a command button to open IE, navigate to the report page, fill in the date and time details and then stop so I can click these two checkboxes I need to tick. I would love for it to be able to check the two checkboxes automatically. Here's the HTML:

                            <input type="hidden" name="NavigationCorrector$ScrollPosition" id="NavigationCorrector_ScrollPosition"><input type="hidden" name="NavigationCorrector$ViewState" id="NavigationCorrector_ViewState"><input type="hidden" name="NavigationCorrector$PageState" id="NavigationCorrector_PageState">

                                <input type="hidden" name="NavigationCorrector$NewViewState" id="NavigationCorrector_NewViewState">

                            &nbsp;Your browser does not support scripts or has been configured not to allow scripts.

                                    Report Viewer Configuration Error

The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file.  Add <add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, ReportingServicesWebUserInterface, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /> to the system.web/httpHandlers section of the web.config file, or add <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, ReportingServicesWebUserInterface, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /> to the system.webServer/handlers section for Internet Information Services 7 or later.

<input type="hidden" name="ctl31$ctl03$ctl00" id="ctl31_ctl03_ctl00"><input type="hidden" name="ctl31$ctl03$ctl01" id="ctl31_ctl03_ctl01"><input type="text" name="ctl31$ctl10" id="ctl31_ctl10"><input type="hidden" name="ctl31$ctl11" id="ctl31_ctl11" value="quirks">

                                        	Loading...

                                            Cancel

<input type="hidden" name="ctl31$AsyncWait$HiddenCancelField" id="ctl31_AsyncWait_HiddenCancelField" value="False">

                                                            Show Start Date From:

                                                                <input name="ctl31$ctl04$ctl03$txtValue" type="text" size="30" id="ctl31_ctl04_ctl03_txtValue" class="null">

		Show End Date To:

                                                                <input name="ctl31$ctl04$ctl05$txtValue" type="text" size="30" id="ctl31_ctl04_ctl05_txtValue" class="null">

                                                            Show Start Hour From:

                                                                <select name="ctl31$ctl04$ctl07$ddValue" id="ctl31_ctl04_ctl07_ddValue" style="width: 117px;">

                                                                    <option value="1">00</option>
                                                                    <option value="2">01</option>
                                                                    <option value="3">02</option>
                                                                    <option value="4">03</option>
                                                                    <option value="5">04</option>
                                                                    <option value="6">05</option>
                                                                    <option value="7">06</option>
                                                                    <option value="8">07</option>
                                                                    <option selected="selected" value="9">08</option>
                                                                    <option value="10">09</option>
                                                                    <option value="11">10</option>
                                                                    <option value="12">11</option>
                                                                    <option value="13">12</option>
                                                                    <option value="14">13</option>
                                                                    <option value="15">14</option>
                                                                    <option value="16">15</option>
                                                                    <option value="17">16</option>
                                                                    <option value="18">17</option>
                                                                    <option value="19">18</option>
                                                                    <option value="20">19</option>
                                                                    <option value="21">20</option>
                                                                    <option value="22">21</option>
                                                                    <option value="23">22</option>
                                                                    <option value="24">23</option>

                                                                </select>

		Show Start Hour To:

                                                                <select name="ctl31$ctl04$ctl09$ddValue" id="ctl31_ctl04_ctl09_ddValue" style="width: 117px;">

                                                                    <option value="1">00</option>
                                                                    <option value="2">01</option>
                                                                    <option value="3">02</option>
                                                                    <option value="4">03</option>
                                                                    <option value="5">04</option>
                                                                    <option value="6">05</option>
                                                                    <option value="7">06</option>
                                                                    <option value="8">07</option>
                                                                    <option value="9">08</option>
                                                                    <option value="10">09</option>
                                                                    <option value="11">10</option>
                                                                    <option value="12">11</option>
                                                                    <option value="13">12</option>
                                                                    <option value="14">13</option>
                                                                    <option value="15">14</option>
                                                                    <option value="16">15</option>
                                                                    <option value="17">16</option>
                                                                    <option value="18">17</option>
                                                                    <option value="19">18</option>
                                                                    <option value="20">19</option>
                                                                    <option value="21">20</option>
                                                                    <option value="22">21</option>
                                                                    <option value="23">22</option>
                                                                    <option selected="selected" value="24">23</option>

                                                                </select>

                                                            Media Type:

                                                                    <input name="ctl31$ctl04$ctl11$txtValue" type="text" size="28" readonly="readonly" id="ctl31_ctl04_ctl11_txtValue" class="null"><input src="/ReportManager/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.50.4339.0&Name=Microsoft.Reporting.WebForms.Icons.MultiValueSelect.gif" name="ctl31$ctl04$ctl11$ddDropDownButton" type="image" id="ctl31_ctl04_ctl11_ddDropDownButton" alt="Select a value" title="Select a value" style="vertical-align:top;cursor:pointer;">

                                                            <input type="submit" name="ctl31$ctl04$ctl00" value="View Report" id="ctl31_ctl04_ctl00">

                                        <input type="hidden" name="ctl31$ctl04$ctl11$divDropDown$HiddenIndices" id="ctl31_ctl04_ctl11_divDropDown_HiddenIndices" value="">

                                        <input type="image" name="ctl31$ToggleParam$img" id="ctl31_ToggleParam_img" title="Show / Hide Parameters" src="/ReportManager/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.50.4339.0&Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapse.png" alt="Show / Hide Parameters" align="middle" onclick="void(0);" style="border-width:0px;cursor:pointer;"><input type="hidden" name="ctl31$ToggleParam$store" id="ctl31_ToggleParam_store"><input type="hidden" name="ctl31$ToggleParam$collapse" id="ctl31_ToggleParam_collapse" value="false">

                                            <input type="hidden" name="ctl31$ctl08$ClientClickedId" id="ctl31_ctl08_ClientClickedId">

                                        <input type="image" name="ctl31$ctl07$img" id="ctl31_ctl07_img" title="Show / Hide Document Map" src="/ReportManager/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.50.4339.0&Name=Microsoft.Reporting.WebForms.Icons.SplitterVertCollapse.png" alt="Show / Hide Document Map" align="top" onclick="void(0);" style="border-width:0px;cursor:pointer;"><input type="hidden" name="ctl31$ctl07$store" id="ctl31_ctl07_store"><input type="hidden" name="ctl31$ctl07$collapse" id="ctl31_ctl07_collapse" value="false">

                                                <input type="hidden" name="ctl31$ctl09$VisibilityState$ctl00" value="None">

<input type="hidden" name="ctl31$ctl09$ScrollPosition" id="ctl31_ctl09_ScrollPosition">

                                                <input type="hidden" name="ctl31$ctl09$ReportControl$ctl02"><input type="hidden" name="ctl31$ctl09$ReportControl$ctl03"><input type="hidden" name="ctl31$ctl09$ReportControl$ctl04" id="ctl31_ctl09_ReportControl_ctl04" value="100">

The checkboxes I would like to click are as follows:
 <input id="ctl31_ctl04_ctl11_divDropDown_ctl03" type="checkbox" name="ctl31$ctl04$ctl11$divDropDown$ctl03" onclick="$get('ctl31_ctl04_ctl11').control.OnValidValueClick(this, 'ctl31_ctl04_ctl11_divDropDown_ctl00');">

and
 <input id="ctl31_ctl04_ctl11_divDropDown_ctl04" type="checkbox" name="ctl31$ctl04$ctl11$divDropDown$ctl04" onclick="$get('ctl31_ctl04_ctl11').control.OnValidValueClick(this, 'ctl31_ctl04_ctl11_divDropDown_ctl00');">

However, they are hidden inside a dropdown
 <input src="/ReportManager/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.50.4339.0&Name=Microsoft.Reporting.WebForms.Icons.MultiValueSelect.gif" name="ctl31$ctl04$ctl11$ddDropDownButton" type="image" id="ctl31_ctl04_ctl11_ddDropDownButton" alt="Select a value" title="Select a value" style="vertical-align:top;cursor:pointer;">

Inside a table

...Which is inside at least three or four tables and divs. Is there an easy way to click it / set the value to TRUE?
Here's the VBA I'm using that's not working, you can see I'm attempting a couple of different methods in it:
    Dim oCheckBox1 As Object
    Set oCheckBox1 = IE.document.getElementById("ctl31_ctl04_ctl11_divDropDown_ctl03")

    Dim oCheckBox2 As Object
    Set oCheckBox2 = IE.document.getElementById("ctl31_ctl04_ctl11_divDropDown_ctl04")

HWNDSrc = IE.HWND
'Set IE as Active Window
SetForegroundWindow HWNDSrc

        oCheckBox1.Click , True
        Call IE.document.parentWindow.execScript("$get('ctl31_ctl04_ctl11').control.OnValidValueClick(this, 'ctl31_ctl04_ctl11_divDropDown_ctl00');", "JavaScript")
        oCheckBox1.Checked = True
        oCheckBox1.Value = True

        oCheckBox2.Click , True
        Call IE.document.parentWindow.execScript("$get('ctl31_ctl04_ctl11').control.OnValidValueClick(this, 'ctl31_ctl04_ctl11_divDropDown_ctl00');", "JavaScript")
        oCheckBox2.Checked = True
        oCheckBox2.Value = True
        Dim oMediaType As Object
        Set oMediaType = IE.document.getElementById("ctl31_ctl04_ctl11_txtValue")
        oMediaType.Value = "[RESULT THAT COMES FROM CLICKING THE CHECKBOXES, REDACTED FOR PRIVACY]"

...then I click the "VIew Report" button
Any help?

A: As requested here is the answer. The element you are trying to click has an Event that is called by what appears to be JavaScript.
The page code:
onclick="$get('ctl31_ctl04_ctl11').control.OnValidValueClick(this, 'ctl31_ctl04_ctl11_divDropDown_ctl00');
You need to call that event in order to execute the code on the page that powers that button.
The simplified code is:
 oCheckBox1.Click
 oCheckBox1.FireEvent("OnClick")


text:
Q: how to display uploaded json file from local system on html page using angularjs I would like to print the json values on my html page(this file is uploaded from my local system). I can able to read the file and able to get the json data format in one variable, but I am facing issueson displaying the those values on my view page.
app.js:
mainApp.controller('MainCtrl',['$scope', '$rootScope', '$location', function($scope, $rootScope, $location){
....

 $scope.loadFile = function(){

var input, file, fr;

file = input.files[0];

fr = new FileReader();

fr.readAsText(file);

var imagelines, newArrImage;

fr.onload = function (e){

 $scope.imagelines = e.target.result;//total data in json format (Ex: [{"name":"imageurl","value":"Image1.nii"},{"name":"3d","value":"3d0"},{"name":"sliceX","value":"sliceX0"},{"name":"sliceY","value":"sliceY0"},{"name":"sliceZ","value":"sliceZ0"}])

$scope.newArr = JSON.parse($scope.imagelines);

angular.forEach($scope.newArrImage, function(data){

console.log("Data VALUES: "+data.value);//here I can get he values, like: (Ex: Image1.nii, 3d0, sliceX0, sliceY0, sliceZ0)

 });

}

}

...

}]);

html:

 {{data.value}}

Please help me where I am doing wrong to display those .json values on my html page. Thanks in advance.

A: Can you please check jsfiddle demo
http://jsfiddle.net/uvzLxn5g/

<input type='file' /><input type="button" ng-click='loadFile()'     value="Uplaod"/>
{{ dataItems }}

I did some modification like assumption that data is getting in controller so please read.

A: Try to change the newArr in Li tags to this value imagelines

      {{ data.value }}

"$scope.imagelines" already have the data of the .json file


text:
Q: Using AdMob, InMobi...is it possible for a publisher to restrict ads from selected advertisers only in the mobile App? As in, if publisher wants that ads from selected advertisers only should be shown in the app, how can this be achieved through Google AdMob, InMobi...

A: Most ad networks (Admob and InMobi for certain) allow whitelisting of advertisers or, blocking advertisers. That said, it will result in significant no-fills which in turn will result in lower revenues.
A better option might be to block all and only allow certain categories though this will also result in lower fill.


text:
Q: Optimisation issue in R Question relating to optim function in R
I have the following code so far and need to know to input my values of X and T. X is a vector of 10 values and T is vector of 10*2 values relating to the means and variances. I want the output to be in the format of one new value for alpha, mean1, mean2, var1, and var2. Not sure how to get the input data in properly.
I want to run all values of X in this function but only the first row of T (10 values) and im not sure how to do this for T. I have a different function for the 2nd row.
R <-runif(10, 0, 1)
S <-1-R
T <-t(cbind(R,S))

X <- runif(10, 25, 35)

Data1 <- function(xy) {
  alpha <- xy[1]
  mean1 <- xy[2]
  mean2 <- xy[3]
  var1 <- xy[4]
  var2 <- xy[5]

  -sum(0.5*(((X)-mean1)/var1)^2+alpha*mean1+log(2.5*var1)+log(exp(-alpha*mean1)+exp(-alpha*mean2))*(T))
}
starting_values <- c(0.3, 28, 38, 4, 3)
optim(starting_values, Data1, lower=c(0, 0, 0, 0, 0), method='L-BFGS-B')

also getting the following error code:
Error in optim(starting_values, Data1, lower = c(0, 0, 0, 0, 0), method = "L-BFGS-B") :
  L-BFGS-B needs finite values of 'fn'

Cheers for any help.
EDIT
second function for inclusion
0.5*((y1-mean2)/var2)^2+alpha*mean2+log(2.5*var2)+ log(exp(-alpha*mean1)+exp(-alpha*mean2)))*T

Ok so to explain as clearly as possible what i want to do. The first function in the original post above takes all 10 values of X one at a time and should take the first row of T data (labelled R here) and im not sure how to do this.
The second function detailed above should again take all 10 values of X in succession and then the second row of data from T (labelled as S below)
all this is then summed together. The five unknown parameters are thusly estimated.

T

       [,1]      [,2]      [,3]       [,4]      [,5]        [,6]      [,7]      [,8]      [,9]     [,10]
R 0.1477715 0.3055021 0.2963543 0.04149945 0.8342484 0.996865333 0.1592568 0.4623762 0.8000778 0.6979342
S 0.8522285 0.6944979 0.7036457 0.95850055 0.1657516 0.003134667 0.8407432 0.5376238 0.1999222 0.3020658

Edit2
im not getting the same values as ben, even with running the same seed. I have checked that i have all the packages installed and it would appear i do. Im not getting the same final answers and im also unable to call an individual item of opt2$par. Instead of providing reams of output, i will provide the first few lines and the last few.
0.3 28 38 4 3 -74.97014 -120.7212
Loading required package: BB
Loading required package: quadprog
Loading required package: ucminf
Loading required package: Rcgmin
Loading required package: Rvmmin

Attaching package: 'Rvmmin'

The following object(s) are masked from 'package:optimx':

    optansout

Loading required package: minqa
Loading required package: Rcpp
0.3 28 38 4 3 -74.97014 -120.7212
0.9501 28 38 4 3 -176.3368 -265.9074
1.9001 28 38 4 3 -324.7782 -478.4652
0.9501 28.95 38 4 3 -179.9994 -260.8711
0.9501 28 38.95 4 3 -176.3366 -283.0445
0.9501 28 38 4.95 3 -176.7836 -265.9074
0.9501 28 38 4 3.95 -176.3368 -254.6188

.................
16.32409 27.86113 38.54337 3.940143 2.504167 -2566.194 -3826.233
16.32409 27.86113 38.54337 3.940044 2.504167 -2566.194 -3826.233
16.32409 27.86113 38.54337 3.940093 2.504199 -2566.194 -3826.232
16.32409 27.86113 38.54337 3.940093 2.504136 -2566.194 -3826.234
> opt2$par
$par
[1] 16.324085 27.861134 38.543373  3.940093  2.504167

> opt2$par["mean1"]
$<NA>
NULL

A: A first crack:  I used your code above.  I added set.seed(101) at the beginning for reproducibility.
Reformatted the function slightly for clarity, but without changing anything significant, and added a cat() statement for debugging purposes:
Data1 <- function(xy) {
    alpha <- xy[1]; mean1 <- xy[2]; mean2 <- xy[3]
    var1 <- xy[4]; var2 <- xy[5]

    r1 <- -sum(0.5*((X-mean1)/var1)^2+
           alpha*mean1+
           log(2.5*var1)+
           log(exp(-alpha*mean1)+
               exp(-alpha*mean2))*T[1,])
    r2 <- -sum(0.5*((X-mean2)/var2)^2+
           alpha*mean2+
           log(2.5*var2)+
           log(exp(-alpha*mean1)+exp(-alpha*mean2))*T[2,])

    cat(xy,r1,r2,"\n")
   r1+r2
}

A slightly compressed version, that (1) takes advantage of with to make the function cleaner; (2) uses R's replication and vector-recycling capabilities
Data2 <- function(xy) {
    with(as.list(xy),
    {
       mmat <- rep(c(mean1,mean2),each=ncol(T))
       vmat <- rep(c(var1,var2),each=ncol(T))
       -sum(0.5*((X-mmat)/vmat)^2+
          alpha*mmat+
          log(2.5*vmat)+
          log(exp(-alpha*mean1)+exp(-alpha*mean2))*T)
    })
}

Now we need a named vector of starting values:
 starting_values <- c(alpha=0.3, mean1=28, mean2=38, var1=4, var2=3)

Check that the results match:
 Data1(starting_values) ##  [1] -195.6913
 Data2(starting_values) ##  [1] -195.6913

This fails (but gives us information on how it fails):
 optim(par=starting_values, Data1, lower=rep(1e-4,5), method='L-BFGS-B',
     control=list(trace=6))

It produces a lot of output, ending with:
##  21.29998 27.97361 37.98915 4.011199 3.001 -6014.225
## 21.29998 27.97361 37.98915 4.011199 2.999 -6014.225
## 85.29991 27.89318 37.95606 4.04533 3 Inf
## Error in optim(par = starting_values, Data1, lower = rep(1e-04, 5),
##    method = "L-BFGS-B",  :
##     L-BFGS-B needs finite values of 'fn'

This at least tells you where things went wrong.  I would now try evaluating your expression piece-by-piece to see which bit overflowed.
As a commenter (Justin) in the chat room said,

your third term log(exp(...) + exp(...)) goes to -Inf very quickly
  since alpha, mean1 and mean2 are unbounded. exp(-large number * large
  number) ~ 0

For further debugging, you can:

*

*try to rearrange the evaluation of your function to avoid overflows

*set upper bounds on some of the parameters to avoid overflows

*have the function test and return very large values rather than Inf in appropriate cases

Unfortunately, L-BFGS-B is more fragile than some of the other optimizers, and doesn't allow non-finite values.
Next I tried the bobyqa optimizer from the optimx package, which allows bounds and handles non-finite values (and is a derivative-free method, which in general tend to be slightly slower but more robust than the derivative-based methods): it seems to work OK, although I don't know if the answers are sensible or not.
library(optimx)
opt2 <- optimx(par=starting_values,
      Data1, lower=rep(1e-4,5), method='bobyqa')
opt3 <- optimx(par=starting_values,
      Data2, lower=rep(1e-4,5), method='bobyqa')

Looks OK (provided this is a sensible answer, which I don't know).
> opt2$par
$par
    alpha     mean1     mean2      var1      var2
16.330752 27.815324 38.497483  3.894179  2.447219

> opt3$par
$par
    alpha     mean1     mean2      var1      var2
16.330900 27.820813 38.491290  3.887975  2.456052

Note that the answers are slightly different (by about 0.5% in the case of var2), which suggests that the fit may be slightly unstable/the surface may be quite flat.  (Data1 and Data2 are supposed to give identical answers, and do so for the starting values, but I guess the order of operations makes them give very slightly different answers for some inputs -- or I screwed up somewhere ...)
To extract an individual component from this fit, e.g. mean1, use vector indexing:
opt3$par["mean1"]  ## 27.820813


text:
Q: symfony doctrine type datetime expected format y-m-d h:i:s I have a problem in symfony when I try to select some items from database with doctrine.
I run this:
$allOrders = $em->getRepository('MyBundle:Dieta')->findBy(array('diet_status'=>'active'));
var_dump($allOrders);

And I get the following error:

Could not convert database value "2014-03-03" to Doctrine Type
  datetime. Expected format: Y-m-d H:i:s

When I insert the date in the database i do it like this:
$format = 'd/m/Y';
$date = \DateTime::createFromFormat($format, $_POST['dietStartDate']);
$dietStartDate = $date->format('Y-m-d H:i:s');
$dietStartDate = new \Datetime($dietStartDate);

$timestamp = strtotime(str_replace('/', '-', $_POST['dietStartDate']));
$timestamp7 = strtotime('+7 days', $timestamp);
$datetime = date("Y-m-d H:i:s", $timestamp7);
$dietDateEnd = new \Datetime($datetime);

The $dietStartDate and $dietDateEnd are inserted in a datetime column in database. In the doctrine.yml I have it also declared as datetime.
Any ideas ?

A: From the value "2014-03-03", it seems that your database column type is date but not datetime.
Run php app/console doctrine:schema:update to check whether there are changes.

A: i have the same issue and i have resolve it by adding the code bellow
the problem is getted because postgres register microseconde when it's different to 0 this produce the isse
use Doctrine\DBAL\Types\Type;

Type::overrideType('datetime', 'Doctrine\DBAL\Types\VarDateTimeType');
Type::overrideType('datetimetz', 'Doctrine\DBAL\Types\VarDateTimeType');
Type::overrideType('time', 'Doctrine\DBAL\Types\VarDateTimeType');

Type::overrideType('datetime_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType');
Type::overrideType('datetimetz_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType');
Type::overrideType('time_immutable', 'Doctrine\DBAL\Types\VarDateTimeImmutableType');

you can read more here
https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/known-vendor-issues.html


text:
Q: Importing py-files from a VS Python project into C# IronPython. How to get imports to work? I just started accessing py-files from C# via IronPython and for simple files it worked very well. However, accessing py-files that were used in a Visual Studio Python project is not quite as easy, because the pyproj-file configures imports and requirements and I am having difficulties replicating all of that with IronPython.
I basically want to access everything the Python software can do by invoking its modules from C# with IronPython. Does anyone know what the proper approach to do that is?
I tried just adding everything inside of "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Lib" to my search path, including subdirectories. I successfully gathered all the paths and added them to the engine. I tested it by accessing a few MS shared modules and I don't get the "No module named XYZ" error, but mostly a generic "token error" instead, so putting the paths into the engine must've worked at least.
But what else do I have to do to get the software to work? Am I merely missing some further include paths or is there something else I'm missing, too?
edit: I just found a comment in this answer saying that IronPython isn't compatible with Python 3.x yet, and said comment responded to someone complaining about token errors similar to what I've been seeing. So I guess IronPython is out, then? I'm too much of a newbie to know whether for sure, e.g. there might be ways to make it compatible? I don't know.


text:
Q: DataSet in Java Web Service Client from C# Web Service I'm a novice in both Java and C#, so please bear with me.
I've made a Web Service in C# with the .Net Framework that is connected to one table in my MSSQL Server database. I've made a Java Application in Eclipse with a Web Service Client that is connected to the Web Service in Visual Studio with a SoapProxy through localhost.
The problem is that the webmethod I've made in C# is returning the Library table from MSSQL as a DataSet which I have no idea how to call as a method and print in the console of my Java Client.
Is there any better way going about the webmethod to get my table from MSSQL to VisualStudio and then printing it in my Eclipse Console?
Java Web Service Client
http://imgur.com/a/oCGzy
C# Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WSDB : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public DataSet getBooks()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString =  "server=.;database=Library;user=sa;password=1234";
        SqlDataAdapter da = new SqlDataAdapter("select * from Library", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;

    }

}

What should the code in my Java Web Service Client look like to call and print this DataSet in the console the easiest most basic way? (formatting doesn't have to be pretty)
Update
I tried a different approach with a new WebMethod, connecting to my database with ADO.Net Entity Framework.
But I'm  still clueless how to call and print the method in my Java Web Client, any suggestions?
[WebMethod]
    public Library GetLibInfo(string booknr)
    {
        return libEnt.Libraries.Single(x=> x.booknr == booknr);
    }

A: I'm not a c# programmer but from what I read about Dataset I see that is a stateful object, you should only return serializable objects from a WS.
So put your result into a simple array and return that.
Anyway you should call somethink like this:
you should have something like this:
WSDBLocator service = new WSDBLocator();

GetBooksReponseGetBookResults res = service.getGetBooks();

SomeKindOfCollection col = res.someMethod();
for(SomeKindOfObject o : col){
   System.out.print(o.getProperty1());
   System.out.print(",");
   System.out.print(o.getProperty2());
   System.out.print(",");
   System.out.printLn(o.getProperty3());
}

A: If formatting isn't an issue you can just import the data from your DataTable into an object array and return it.
[WebMethod]
    public object[] javaCustomer()
    {
        connectCronus();  //changes the ConnectionString
        int count = 0;
        cmd = new SqlCommand("select [Name],[City] from [CRONUS Sverige AB$Customer];");
        dt = returnDataTable();
        object[] ar = new string[dt.Rows.Count];
        foreach (DataRow row in dt.Rows)
        {
            ar[count] = row["Name"].ToString() + "\t" + row["City"].ToString();
            count++;
        }
        return ar;
    }

Then it's just a matter of printing it in your java client.
for(Object o : proxy.javaEmployee()){
        System.out.println(o);
}


text:
Q: No errors but PowerShell code not working No errors in this script, but I am scratching my head because I have checked the csv data and the first and last names match up just fine (so no error should be written to the log). Yet, instead of skipping the writing to the log, it always does. So, I had to Comment out the Continue line or the script won't finish.
Also, I want to enable a user object if the re-hire date is 8 days in the future from todays date, but this also appears to not work (no obvious errors to me). Can someone please check my logic? This is not the full script, just the areas where I can't find any issues. Thanks
`$CSVLine = "C:\scripts\adp\Test ADP Import spec.csv"
$ErrorLog = "C:\scripts\adp\ADPProcessErrors.csv"
[xml]$DivLocFile = Get-Content -Path "C:\Scripts\adp\DivLocData.xml"
$DocumentRoot = $DivLocFile.DocumentElement
$UserLocationCode = @{}
$a = Get-Date

ForEach ($row in (Import-Csv $CSVLine)) {

    #Skips over Terminiated employees
If ($CSVLine.EmployeeStatus -eq "Terminated") { Continue }
    #Gets the user's First and Last name
    $User = Get-ADUser -LDAPFilter ("(sAMAccountName=" + $Row.sAMAccountName + ")") -Properties *

    If ($User -eq $Null) {
        #If there is no First and Last name this will throw an error and go on to the next record.
        ($Row.sAMAccountName + ",AD Object Not Found") | Out-File -FilePath $ErrorLog -Append

        Continue
         }
        #Checks whether First or Last names don't match
        If (($User.givenName -ne $CSVLine.'First Name') -or ($User.sn -ne $CSVLine.'Last Name')) {

        ($Row.sAMAccountName + ",givenName and sn property mismatch") | Out-File -FilePath $ErrorLog -Append

        #Continue
         }
        #Enables a disabled user if they have a hire date 8 days in advance of today's date.
        If (($CSVLine.'Date of hire/rehire' -gt ($a)) -and ($CSVLine.'Date of hire/rehire') -le ($a.AddDays(8)) -and (!($User.Enabled)))  {

        (Set-ADUser -Enabled $True -Identity $User)
        ("SID:" + $Row.sAMAccountName + ", User:[" + $User.givenName + " " + $User.sn + "] Re-Hire date is in range. Account enabled.") | Out-File -FilePath $ErrorLog -Append
        }`

A: Looks like a lot of your IF statements are using $CSVLine where it looks like they should instead be using $row


text:
Q: Retrofit query params I'm trying to configure a request to http: //where.yahooapis.com/v1/places.q(name_here);count=50?....
Not the best solution, I guess, but I tried
@GET("/v1/{location}")
Places getLocations(@Path("location") String locationName);

and pass there
getLocations("places.q(" + locationName + ");count=50");

But it still doesn't work as the string (); is translated into %28%29%3B.
Can you suggest any solutions? It would be better to dinamycally modify only the name_here part, something like
@GET("/v1/places.q({location});count=50)

If it is not possible how do I have to pass symbols (); so that they are converted correctly?

A: I just tried
@GET("/v1/places.q({location});count=50")
Places getLocations(@Path("location") String name)

a bit later and it works fine. I thought it will insert something like "/" or modify it, but it does exectly what I need.


text:
Q: Are "smell like" and "smell of" the same? Is there any difference between smell like and smell of?
I came across this sentence in the Cambridge Advanced Learner's Dictionary:

My hands smell like (US) / of (UK) onion.

But I'm not really sure about it because in the Longman Advanced American Dictionary, I came across smell of.
Does the usage have anything to do with whether the smell is of a real thing or something similar?
Like when you say "My hands smell of onion", it means that you have touched an onion and that's why your hands smell, and when you say "The food smells like rotten meat" it means that the smell of the food is similar to that of rotten meat, though there might be no meat in it?

A:
Like when you say "My hands smell of onion", it means that you have touched an onion and that's why your hands smell, and when you say "The food smells like rotten meat" it means that the smell of the food is similar to that of rotten meat, though there might be no meat in it?

My interpretation is that smell of implies causality.  You have touched something, and therefore your hands "smell of it": they smell because of it.
Of course, when something causes a smell, that smell is typically similar to the smell of the thing itself.  If you touch onions, your hands smell like onions, of course (because, I assume, some chemical from the onion rubs off on your hand).
The distinction is more clear in metaphor.  You can "smell of" failure, or of desperation, or of fear.  Those things can cause you to literally smell (because of sweat or hygiene issues), or they can just make you an object of distaste, as if you smelled bad, but no one believes that abstract concepts like "desperation" have an odor to resemble.
Smell like is much more literal.  One thing smells like another thing, because of happenstance, chemistry, or some other reason.

A: In the US, you'd rarely hear anyone say that something smelled "of" anything. Right or wrong, (or inaccurate) we say, "like."

A: I disagree that smell like / smell of is a transatlantic divide.  Though Americans might be less inclined to use smell of, the primary consideration is that smell of is more specific in its applicability.
For example, organic compounds developed in the aging process of a wine may impart a strawberry-like aroma, even though grapes were the only ingredient.  In that case, it would be acceptable to say

This wine smells like strawberry.

However, it would be highly questionable to say

This wine smells of strawberry.

since there are no real strawberries involved.
The same distinction would apply for synthetic flavours.

A: Your final paragraph precisely states common usage here, at the bottom of the world & at the edge of the empire, in New Zealand. I cannot vouch for the accuracy of the 'Cambridge Advanced Learner's Dictionary' on its home turf, but, here, the distinction they make is incorrect.
Either term might be used, depending on context.
You said

"...when you say "My hands smell of onion", it means that you have touched an onion and that's why your hands smell,
  ·
  and when you say "The food smells like rotten meat" it means that the smell of the food is similar to that of rotten meat, though there might be no meat in it?!

That is the common usage here.  ie:
"Smell of ..." means that they have some of the material on them so that "smelling your hands" returns the smell of the attached material.
"Smell like ..." means that the smell is reminiscent of the smell of the cited material, even though none is present.
Pedantry:
It would be possible, and generally felt to be valid,  to say " ... smells like ..." when the smell was caused by the material mentioned but you were unaware of what caused the smell.
eg saying  "My cup smells like liniment" when the cup had, unbeknown to you, previously been used to contain liniment, would be valid (As xxx usually DOES smell LIKE xxx).
Advanced Pedantry:
However, the converse - "This cup smells of Aniseed" when it contained Ouzo liquor, which has an Aniseed like smell, would be incorrect usage, based on a misapprehension by the smeller. This distinction would be understood by many but few would be pedantic enough to care if such a mistake was made.
eg "This cup smells of Aniseed"
might be replied to with "'It's Ouzo", without the felt need (usually) to explain that it can't smell of it because "it ain't it".

Added:
It's evident from various added comments (Oldbag, Steve Jessop and others) that

*

*US usage tends to be "smells like xxx" regardless of whether it is actually xxx being smelt or something that is known not to be xxx but has the same or a similar smell, Whereas ...

*UK (and New Zealand) usage is to differentiate between 'actually xxx' and 'similar characteristics to those of xxx'.
So, the Cambridge Advanced Learner's Dictionary appears to be correct in its [US] assertion but not general enough in its [UK] assertion.
However, Sharaman says that "Longman Advanced American Dictionary"mentions "smell of" but Oldbag's answer and Steve Jessop's related comment indicate that "smell of" is not common US usage.

Sharaman asks if "taste" follows the same "rules" as "smell".
In NZ "taste" follows the same 'rules' as "smell".
This would tend to apply to a number of sense or perception based terms although the usage becomes "forced" in some cases.
eg "made of wood" would be used but "made like wood" would feel too 'strained' and would  probably be rendered "made to look like wood" or "made to seem like wood" or even "made to seem like it was made of wood." [I decided that, in this example, the use of wood would make the example (just slightly) more entertaining and thus, just possibly, more memorable, with the added benefit of also making it more confusing :-)].

Tongue twister from my youth:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
This was always a deep mystery to me as, in New Zealand, we do not have Marmota monax,  groundhogs, woodchucks, whistle-pigs, land-beavers, nor any members of the Sciuridae family, nor ground squirrels or marmots  or in fact native rodents of any sort.

A: My grammatical opinion (as an American who lives in Europe) is this:
If I have chopped up an onion, and I want to convey to someone that I can still smell the residue of onion on my fingers, I would say:

"My fingers still have the fragrance (or "odor" -- depending on whether or not you find the scent of onions appealing or off-putting) of onions!!"

In this sentence, I would use "of".
However -- I would also say, in a similar context:

"Even though I have washed my hands several times, they still smell like the onions I chopped earlier."

I feel as though the usage of "of" and "like" are almost interchangeable, and the intent of the statement is the determining factor.
For instance:

If Evan and Emma went to a bar, and Evan was drinking but I know that he doesn't smoke, I would tell Evan that his breath smelled of alcohol and his clothes smelled like Cigarette smoke.

However, if Emma was the designated driver and I knew she wasn't drinking or smoking, I would would say:

"you definitely smell like you've been in a bar!"

instead of saying:

"you smell of a bar!"

In actuality, Emma was engaged in the action of hanging out at a bar, without participating in drinking or smoking, yet she smelled as though she had partaken in both.
I am not entirely sure which phrase is grammatically correct,  simply because the acceptance of lazy speech is becoming more and more popular due to social media. My opinion is formed based on location, colloquialisms and vernacular.
...annnnnd...on that note...I am convinced that the importance of grammar and syntax is becoming extinct.


text:
Q: If I don't choose to prestige, can I still gain experience? After reaching level 80 and earning enough XP to prestige (81?), what happens if I chose not to prestige? Do I continue to rack up or accumulate XP (that can be seen when I eventually prestige) or am I stagnant at the max XP cap for the first set of ranks? I understand that guns will continue to level and that I can unlock titles and such, which is partly why I'm holding off leveling, I am close to finishing a challenge on the MK14 and don't want to lose my progress.

A: No, you do not gain additional XP, and any XP you gain over the amount needed to get to "prestige rank" or level 81, is lost.  You can gain weapon XP, but know that your weapon XP will completely reset every time you prestige, even if you choose to unlock that weapon via a prestige token.
If you're close to finishing a big challenge, you might hold off on prestige mode, but all you'll be doing if you wait and finish is unlocking a new title and/or emblem at best.  You can generally tell if a challenge will unlock a title or emblem by looking at the appropriate challenge in the Barracks.  Challenges that will unlock new titles or emblems at the next level have a small title or emblem icon with a "lock" over it.  The other rewards from challenges (generally just XP) will not carry over to your new prestige.
Emblems and titles are really the only things that carry over from prestige to prestige.  Most challenges will also reset, and you could do them again, but you won't unlock anything new.  Notice also that there is a special set of challenges/emblems that can only be unlocked after the first time you prestige.  Some of these are "lifetime" challenges that do not reset on additional prestiges.


text:
Q: How to create a overlay layout upon a listview I have a listview that will be filled with AsyncTask and at the bottom edge of the app I need to show a fixed overlay layout like this:

But I can't figure it out how I can do this in xml?
This is my present layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   <!-- Probably I need to do something here  -->

</LinearLayout>

A: As Daniel has suggested, use a RelativeLayout because it allows stacking of components(same with FrameLayout and SurfaceView). The following code will give you the layout you are looking for:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<RelativeLayout
   android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/transparentBlack"
    android:layout_alignParentBottom="true" >

   <TextView
       android:id="@+id/textView2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/textView1"
       android:layout_alignParentRight="true"
       android:layout_marginRight="20dp"
       android:text="Medium Text"
       android:textColor="@color/white"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_centerVertical="true"
       android:layout_marginLeft="40dp"
       android:text="Large Text"
       android:textAppearance="?android:attr/textAppearanceLarge"
       android:textColor="@color/white" />

   </RelativeLayout>

</RelativeLayout>

In the code above, the color hex values used for transparentBlack is #95000000 and white is #ffffff.
Here is an excellent tutorial on the basics of UI design in android: Android User Interface Design: Layout Basics.

A: Change the parent layout to RelativeLayout or FrameLayout and position the fixed view at the same level of the ListView (but after the ListView)
Something like:
---> RelativeLayout
    --> ListView
    --> Any view as the fixed view

You can then align the fixed view to the bottom of the wrapping RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ListView
       android:id="@+id/list"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

   <!-- Here you should position the fixed view  -->
</RelativeLayout>


text:
Q: c# Insert multiple records based on time span using entity I am writing a task scheduling app and have most of it done. I want to update the app now to handle tasks that are 8 Hours or more.
What I am trying to do is. If I add a task for 20 hours on Tuesday from 9:00 AM, I want my method to create multiple entities/records and insert in the DB (8 Hrs, 8 Hrs and 4 Hrs in this case, with all details the same except the start and end time.)
public PartialViewResult Add(FormCollection collection)
{
    try
    {
        using(var _dbContext = new myContext())
        {
             string _UserName = collection["UserName"].ToString();
             string _TaskName = collection["TaskName"].ToString();

             DateTime _dtTaskStart = new DateTime();
             DateTime.TryParse(collection["dtTaskStart"], out _dtTaskStart);

             DateTime _dtTaskEnd = new DateTime();
             DateTime.TryParse(collection["dtTaskEnd"], out _dtTaskEnd);

             List<Task> _Tasks = new List<Task>();

             //total task hrs
             Double _TotalTaskHrs = (_dtTaskEnd - _dtTaskStart).TotalHours;

             if(_TotalTaskHrs  > 8)
             {
                 /*1. Here want to get an array that gives me the split hours 8,8,4*/
                 /*2. Once I get 8,8,4 (This can be stored as an array) from which I can tell I have to create 3 entries */
                 /*3. Copy values from form collection to all three entries*/
                 /*4. Add all tasks to the list*/

                 _dbContext.Tasks.Attach(/*Created entity*/);
                 _dbContext.SaveChanges();
             }
         }
     }
     catch(Exception Ex)
     {

     }
 }

I am not sure if this is the correct approach.


text:
Q: Clojure: finding sequential items from a sequence In a Clojure program, I have a sequence of numbers:
(2 3 4 6 8 1)

I want to find the longest sub-sequence where the items are sequential:
(2 3 4)

I am assuming that it will involve (take-while ...) or (reduce ...).
Any ideas?
Clarification: I need the longest initial list of sequential items. Much easier, I'm sure. Thanks for the solutions to the more difficult problem I initially posed.

A: Taking into account the OP's comment on the question -- which completely changes the game! -- this can be written very simply:
(let [doubletons (partition 2 1 [1 2 3 5 6])
      increment? (fn increment? [[x y]]
                   (== (inc x) y))]
  (cons (ffirst doubletons)
        (map second (take-while increment? doubletons))))

;; returns (1 2 3)

Note that this is actually lazy. I expect it not to hold onto the head of doubletons thanks to locals clearing. Another version:
(cons (first [1 2 3 5 6])
      (map second (take-while increment? (partition 2 1 [1 2 3 5 6]))))

The original version of the question is more fun, though! :-) A super-simple solution to that could be built using the above, but of course that would be significantly less performant than using reduce. I'll see if I have anything substantially different from zmila's and dnolen's solutions -- and yet still reasonably performant -- to add to that part of this thread later. (Not very likely, I guess.)

A: Answer to original:
(defn conj-if-sequential
  ([] [])
  ([a] a)
  ([a b] (let [a (if (vector? a) a [a])]
           (if (= (inc (last a)) b)
             (conj a b)
             a))))

(reduce conj-if-sequential [2 3 4 6 8 1])

A more generic solution for those interested:
(defn sequential-seqs
  ([] [])
  ([a] a)
  ([a b] (let [n (last (last a))]
           (if (and n (= (inc n) b))
             (update-in a [(dec (count a))] conj b)
             (conj a [b])))))

(defn largest
  ([] nil)
  ([a] a)
  ([a b] (if (> (count b) (count a)) b a)))

(reduce largest (reduce sequential-seqs [] [2 3 4 6 8 1 4 5 6 7 8 9 13]))

I think this is much better.

A: (defn find-max-seq [lst]
  (let [[f & r] lst,
        longest-seq (fn [a b] (if (> (count a) (count b)) a b)),
        [last-seq max-seq] (reduce
                             (fn [ [[prev-num & _ :as cur-seq] max-seq] cur-num ]
                               (if (== (inc prev-num) cur-num)
                                 [(conj cur-seq cur-num) max-seq]
                                 [(list cur-num) (longest-seq cur-seq max-seq)]
                                 ))
                             [(list f) ()]
                             r)]
    (reverse (longest-seq last-seq max-seq))))

(find-max-seq '(2 3 4 6 8 1))  ; ==> (2 3 4)
(find-max-seq '(3 2 3 4 6 8 9 10 11)) ; ==> (8 9 10 11)

A: If you are only interested in the longest initial sequence, it's a 1-liner:
(defn longest-initial-sequence [[x :as s]]
  (take-while identity (map #(#{%1} %2) s (iterate inc x))))