text:
Q: MVC4 App Targets .NET 4.0 but seems to Require .NET 4.5 to Run OK, so I asked a question here that describes how I have arrived at this conclusion. I have looked around the web and have found similar issues but not one that gives me the answer or that gets me close enough for me to be able to make the leap to pull it altogether. The MVC 4 application that I developed in Visual Studio 2012 targets the .NET 4.0 framework as our production server can not presently be upgraded to .NET 4.5. In VS 2012 and on my local IIS the application runs perfectly. However, when I deployed it to our staging server, which only had .NET 4.0, it would not run completely, although it did display the Login page. It would not, however, display the Register or the Forgot Login pages.
Things I have tried:

*

*running aspnet_regiis.exe -ir, although it was not necessary as we already have ASP.NET 4 apps running - [desperation]

*Removing and adding in web.config, UrlRoutingModule-4.0

*Ensured all dll's targeted .NET 4.0

*... will list more when I return to work tomorrow

In my continued troubleshooting efforts, I was able to determine that after the user logged in and was authenticated, the only error that was thrown was one stating that it could not locate my error page which existed in the Error directory. After remedying this, it only displayed the error page with no other usable information other than that an error occurred in my Account-Login method. I also checked SQL Server and noticed that the test user's LastLogon field was being updated which verified my connection for SQL and EF5. At this point I added logging and was able to determine that the user was in fact authenticated but the code in the BaseController which was responsible for routing authenticated users to the Home/Index page never seemed to fire (see the full code here).
After exhausting several hours trying to isolate the faulty code, on a whim, I installed .NET 4.5 to the staging server and Lo and Behold, it worked as intended. Could I be using something that is intended for .NET 4.5? The only additional plugins I am using are:

*

*TwitterBootstrapMVC

*Grid.MVC

*Entity Framework 5.0

*... will list more when I return to work tomorrow

and several other JQuery plugins, neither of which require .NET 4.5. I would be more than appreciative if someone could guide me onto the right path to help  solve this challenge. I know you guys here, like me, love a challenge. Let's see if anyone can figure this one out before I do.

The only use of an obstacle is to be overcome. All that an obstacle does with brave men is, not to frighten them, but to challenge them.

                                                                      ~ Woodrow Wilson

A: OK, I discovered what was going wrong. For some of my Controllers, I needed an additional parameter and I did not want to use QueryString so I added an additional url parameter to my RouteConfig:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}/{xid}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, xid = UrlParameter.Optional }
);

Haven't had much time to research why this would work in 4.5 and not 4.0 but when I find it, I will post an explanation or a link to an explanation here, just in case someone finds themselves in a similar pickle. And if anyone reading cares to expound on this, please feel free.


text:
Q: How come multiplying this unit vector by another is a rotation? I was reading a book about rotations today and in the introduction there are two complex vectors $\langle 1,1 \rangle = [1,1]$ and $\langle 0,1\rangle = [0,1]$. I initially thought the columns of one didn't match the rows of the other because it doesn't show that computation. The result of multiplying $\langle 1,1 \rangle$ by $\langle 0,1\rangle$ rotates $\langle 1,1 \rangle$ by the other vector's argument $\pi/2$ to $\langle -1,1\rangle$.
I've checked the cross product of the vectors and it doesn't look like it exists, because there are no entries to compute the determinant of the remaining column with after removing the first or second entry.
More specifically I thought if these are vectors that are row matrices with a row for each dimension they would be the row vectors $[1 , 1]$ and $[0,1]$. I was sure they can be multiplied but the columns and rows do not match so what do I do different?

A: One can represent complex numbers $a+bi$ as vectors in the plane $[a,b]$.  It works nicely for addition because complex addition is componentwise as is our usual addition of vectors.  Complex multiplication is completely different from any vector product we are used to.  We can just define the multiplication of two of these vectors as $[a,b]\cdot[c,d]=[ac-bd,ad+bc]$  This matches the usual multiplication of complex numbers.  Normally in two dimensions there is no vector multiplication that results in a vector.

A: You can treat the complex numbers as the vector space $\mathbb{R}^2$ (i.e. the Cartesian plane) with the complex number $a + ib$ being equated with the vector $(a, b)$. However, $\mathbb{R}^2$ does not come with its own multiplication operation - like any vector space, you can add vectors to each other, and you can multiply vectors by real numbers, but $(a, b) \times (c, d)$ has no intrinsic definition.
There are, in fact, multiple options for a multiplication operation on $\mathbb{R}^2$ depending on what properties you want to have - for example, $(a, b) \times (c, d) = (ac, bd)$ is a valid choice under some circumstances (and makes sense if you map the vectors to diagonal 2x2 matrices).
In our case, though, the aim is to make complex arithmetic a smooth extension of real arithmetic, and in particular we know that $i^2 = -1$ so in vector form it means we're stuck with having $(0, 1) \times (0, 1) = (-1, 0)$. As it turns out, the way to do this is to define multiplication as $(a, b) \times (c, d) = (ac - bd, ad + bc)$. It doesn't relate to matrix multiplication at all.
Except ...
We can also write vectors in $\mathbb{C} = \mathbb{R}^2$ in polar coordinates, i.e. in terms of their distance from the origin and counterclockwise from the positive $x$-axis, which gives us $x + iy = (x, y) = (r \cos \theta, r \sin \theta) = r \cos \theta + i \sin \theta = r\ \mathrm{cis}\ \theta$. In this notation, you can show that $r\ \mathrm{cis}\ \theta \times s\ \mathrm{cis}\ \psi = rs\ \mathrm{cis}\ (\theta + \psi)$ - i.e. complex multiplication multiplies the vector lengths and adds the angles.
And, as it happens, there is a way to do vector rotation using matrices, and we can steal that to give a matrix representation for our complex numbers. If we write:
$$x + iy \sim \begin{bmatrix} x & y \\
-y & x \end{bmatrix}$$
then it turns out that this 2x2 matrix representation gives us both complex addition and multiplication using the standard matrix operations.
In all of these cases, though, it can be useful to write the "vector that's actually a complex number" differently to "just a normal real-valued 2-dimensional vector" so that it's clear that we have this extra multiplication operation available to us, which is why we may use the square or angle brackets.

A: You can identify the vector $\langle a,b\rangle$ (the position vector of a point $(a,b)$ in the plane) as the complex number $a+bi$ in the Argand plane. Multiplying by $\langle\cos\theta,\sin\theta\rangle$, ie, $\cos\theta+i\sin\theta$ then gives a counter-clockwise rotation by angle $\theta$. As such, multiplying by $\langle 0,1\rangle=\langle\cos\frac\pi 2,\sin\frac\pi 2\rangle$ gives a counter-clockwise rotation by $\dfrac\pi 2$ radians, ie, $90^\circ$
The operations are defined as how it is defined for $\Bbb C$ when it is constructed from $\Bbb R^2$ by,
$$\langle a,b\rangle+\langle c,d\rangle=\langle a+c,b+d\rangle\\ \lambda\langle a,b\rangle=\langle\lambda a,\lambda b\rangle\quad\text{for scalar }\lambda\in\Bbb R\\\langle a,b\rangle\cdot\langle c,d\rangle=\langle ac-bd,ad+bc\rangle$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to shard a mongodb collection with existing index. Getting "couldn't find valid index for shard key" I have a collection with the following index...
{
    "feedId" : 1,
    "timekey" : 1,
    "entity.samplingRate" : 1,
    "endTimekey" : 1,
    "geo" : "2dsphere"
}

and I'm trying to shard the collection using the following shard key...
{
    "feedId": 1,
    "timekey": 1,
    "entity.samplingRate": 1
}

which is giving me the following error...
{
    "ok" : 0,
    "errmsg" : "couldn't find valid index for shard key",
    "code" : 96,
    ...
}

Why doesn't this work? Is it because "geo" is a "2dsphere" index? Or is it because of the "." in "entity.samplingRate"? It is not an index on an array (i.e "entity" is a subobject, not an array). Is there something else going on here?


text:
Q: Non-static method App\User::getallreferrals() should not be called statically am trying to call functions inside my model in my controller but i get this error.

(1/1) ErrorException Non-static method App\User::getallreferrals() should not be called statically. in HomeController.php (line 37)

this is my model.

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Auth;

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'first_name','last_name','other_name','user_name','number2','email', 'password', 'number','bank_name','acct_number','acct_name', 'next_kin', 'next_kin_no', 'transaction_details', 'entry_matrix','referral_id', 'referred_by','first_downline_id', 'second_downline_id'
];

/**
 * The attributes that should be hidden for arrays. `1
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

public function scopeGetallreferrals($query)
{
    return $query->where('referred_by', Auth::user()->referral_id)->pluck('referral_id');
}

public function scopeGetallreferralsobject($query)
{
    return $query->where('referred_by', Auth::user()->referral_id)->get();
}

public function scopeGetallreferrals2genobject($query)
{
    $referrals = $this->getallreferrals();
    return $query->where('referred_by', $referrals)->get();
}

public function scopeGetallreferrals2gen($query)
{
    $referrals = $this->getallreferrals();
    return $query->where('referred_by', $referrals)->pluck('referral_id');

}

public function scopeGetallreferrals3gen($query){
    $referrals2gen = $this->getallreferrals3gen();
    return $query->where('referred_by', $referrals2gen)->pluck('referral_id');

}

public function scopeGetcaptain($query)
{
    return $query->where('referral_id', Auth::user()->referred_by)->pluck('referred_by');
}

public function scopeGetallcaptain2gen($query)
{
    $captain = $this->getcaptain();
    return $query->where('referral_id', $captain)->pluck('referral_id');

}

public function  scopeGetallcaptain3gen($query){
    $captain2gen = $this->getcaptain2gen();
    return $query->where('referred_by', $captain2gen)->pluck('referral_id');

}

public function  scopeGetallreferralsbyID($query, $id){
    return $this->getallreferrals()->where('id', $id);
}

public function  scopeGetallreferrals2genbyID($query, $id){
    return $this->getallreferrals2gen()->where('id', $id);
}

public function  scopeGetallreferrals3genbyID($query, $id){
    return $this->getallreferrals3gen()->where('id', $id);
}

}
then my controller.
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\DateTime;
use App\User;
use Auth;
use Session;

class HomeController extends Controller
{
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */

public function index()
{
    $captain = User::getcaptain();
    $referrals = User::getallreferrals();

    return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}

Please what am i not doing right? I have been on this project for a while now.
my migrations
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('other_name');
        $table->string('user_name');
        $table->string('number');
        $table->string('number2');
        $table->string('bank_name');
        $table->string('acct_number');
        $table->string('acct_name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('next_kin');
        $table->string('next_kin_no');
        $table->string('entry_matrix');
        $table->string('transaction_details')->nullable();
        $table->integer('isconfirmed')->default(0);
        $table->string('total_earned')->nullable();
        $table->string('total_paid')->nullable();
        $table->string('type_account')->nullable();
        $table->integer('stage')->default(0);
        $table->string('referral_id')->unique();
        $table->string('referred_by')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('users');
}

}

A: As it is saying the getallreferrals method is not static, but you are trying to call it with :, which means static.
It should be something like
use a Scope for this in User model
public function scopeGetallreferrals($query, $user)
{
    return $query->where('referred_by', $user->referral_id);
}

and in controller
public function __construct(User $user)
{
    $this->middleware('auth');
    $this->user = Auth:user();
}

public function index()
{
    $captain = $this->user->getcaptain();
    $referrals = $this->user->getallreferrals($this->user)->pluck('referral_id');

    return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}


text:
Q: How to edit remote files on an Apache server with Android application I need my app to be able to go to a specified URL and access a file, then insert text at a specific line of said file.  Is this at all possible?  I greatly appreciate your help and responses,  Thanks.

A: Sure, just configure mod_dav so you get put support on the apache side. Then use a GET to pull down the file, edit it locally, and use PUT to send it back. Obviously, this will not work well from a concurrency standpoint, but it's fine for the basic text editor type workflow.
Alternatively, you could write server side code to actually edit the file on the server side.


text:
Q: Functions type converting How can I convert func add (a, b int) int to func(...interface{}) interace{} type ?
Any ideas about implementing generic functions using the reflect package ?

A: As JimB said, you can't cast in Go and you cannot convert functions just like that but by using closures, you can rapidly wrap your function:
func add(a, b int) int {
    return a + b;
}

wrap := func(args ...interface{}) interface{} {
    return interface{} (add(args[0].(int), args[1].(int)))
}

Note that wrap will panic if you give it arguments that are not of type int. If you want to avoid that you can slightly modify wrap:
wrap := func(args ...interface{}) (interface{}, error) {
    a, k := args[0].(int)
    b, l := args[1].(int)
    if !k || !l {
        return nil, errors.New("Arguments must be of type int")
    }
    return add(a,b), nil
}

If you'd like to do different things with wrap, depending on it's arguments types you can do so by using a type switch:
func addInts(a, b int) int {
    return a + b;
}

func addFloat64s(a, b float64) float64 {
    return a + b;
}

wrap := func(args ...interface{}) interface{} {
    switch args[0].(type) {
    case int: return interface{}(addInts(args[0].(int), args[1].(int)))
    case float64: return interface{}(addFloat64s(args[0].(float64), args[1].(float64)))
    }
}

Note that this last version of wrap makes the assumption that all given parameters will have the same type and at least 2 arguments are given.

A: There is no "casting" is go (well, using the "unsafe" package kind of is like casting).
You cannot convert function types like this, since they have different layouts in memory. Generic-like functions can be made through the reflect package, though with significant overhead. See http://golang.org/pkg/reflect/#example_MakeFunc for an example.
For most use cases of generic functions, you're probably better off accepting an interface, and using type assertions or switches (http://golang.org/ref/spec#Type_switches), rather than the reflection library.


text:
Q: SQL Array aggregation in Haskell + Squeal I'm using an SQL library called Squeal in Haskell.
What's the correct way to aggregate multiple text rows into one array in Squeal library?
Say I got a very simple Schema with just one table containing a column 'keyword' (of PG text type) + associated types:

import           Squeal.PostgreSQL
import qualified GHC.Generics                  as GHC
import qualified Generics.SOP                  as SOP

type Constraints = '["pk_keywords"  ::: 'PrimaryKey '["id"]]
type Columns
  = '["id" ::: 'Def :=> 'NotNull 'PGint8, "keyword" ::: 'NoDef :=> 'NotNull 'PGtext]
type Table = 'Table (Constraints :=> KColumns)
type Schema = '["keywords" ::: Table]
type Schemas = '["public" ::: Schema]

newtype Keywords = Keywords {unKeywords ::  [Text]} deriving (GHC.Generic)
instance SOP.Generic Keywords
instance SOP.HasDatatypeInfo Keywords
type instance PG Keywords = 'PGvararray ( 'NotNull 'PGtext)

This is the part I need help with:
I'm trying an aggregation query like this:
keywords :: Query_ Schemas () Keywords
keywords =
  select_ ((arrayAgg (All #keyword)) `as` #fromOnly) (from (table #keywords))

However, I keep getting an error:
* Couldn't match type 'NotNull (PG [Text])
                 with 'Null ('PGvararray ty0)
    arising from a use of `as'

From what I understand, arrayAgg can produce NULL so I need to provide a default of empty array [] somehow with fromNull from here:
https://hackage.haskell.org/package/squeal-postgresql-0.5.1.0/docs/Squeal-PostgreSQL-Expression-Null.html#v:fromNull
But I don't quite know how to provide that.
What about the value type mismatch (PG [Text] vs 'PGvararray ty0)? How to solve that?

A: For the record, the library's author provided a solution as follows:
keywords :: Query_ Schemas () (Only (VarArray [Text]))
keywords = select_
  (fromNull (array [] & inferredtype) (arrayAgg (All #keyword)) `as` #fromOnly)
  (from (table #keywords) & groupBy Nil)

The key factors here are:

*

*Provide a default empty array with fromNull (array [] & inferredtype) .... This way we can avoid using Maybe in the return type

*Provide grouping with groupBy Nil

*Choose either Distinct or All rows in arrayAgg

*Finally, the return type should be VarArray x


text:
Q: Array Search Method Php $contacts = array(
    array("name"=>"Samatha Perera", "Email"=>"smatha@gmail.com", "Telephone"=>array("office"=>"0112233789","personal"=>"0718256385","home"=>"0112843425")),
    array( "name"=>"Charith Fernando", "Email"=>"charith@gmail.com", "Telephone"=>array("office"=> "0112656457","personal"=>"0718456723","home"=>"0112334466"))
);

From this array I need to search by name, email, phone number via HTML form. I have done the form and search coding part but it doesn't work.
Search code:
if(isset($_POST['submit'])){

        function search_name($id, $array){
            foreach($array as $key => $val){
                while($val['name'] === $name){
                    echo "".$array['id']."	";
                }
            }
            return "wrong";
        }
        $name = $_POST['val-box'];
        $id= search_name($name,$contacts);
    }

A: $name is sent to the function as the $id argument so
i think you mean this:
while($val['name'] === $name){

to
while($val['name'] === $id){

A: Is this what you're looking for? (you had some minor typos and mistakes.) (I removed the post from the code to test it locally, but you can easily add that code again).
$contacts = array(
    array("name"=>"Samatha Perera", "Email"=>"smatha@gmail.com", "Telephone"=>array("office"=>"0112233789","personal"=>"0718256385","home"=>"0112843425")),
    array( "name"=>"Charith Fernando", "Email"=>"charith@gmail.com", "Telephone"=>array("office"=> "0112656457","personal"=>"0718456723","home"=>"0112334466"))
);
function search_name($id, $array){
    foreach($array as $key => $val){
        if($val['name'] == $id){
            echo "".$val['name']."	" .
                 "".$val['Email']."	" .
                 "".$val['Telephone']['office'] . "	" .
                 "".$val['Telephone']['personal'] . "	" .
                 "".$val['Telephone']['home'] . "	";
        }
    }
    echo "wrong";
}

$name = 'Samatha Perera';
$id= search_name($name,$contacts);

A: $contact = array(
            array("name"=>"Samantha Perera",
                  "email"=>"samantha@gmail.com",
                  "telephone"=>
                                array("office"=>"0112233789",
                                      "personal"=>"0718256385",
                                       "home"=>"0112843425")),
            array("name"=>"Charith Fernando",
                  "email"=>"charith@gmail.com",
                  "telephone"=>
                                array("office"=>"0112656457",
                                      "personal"=>"0718456723",
                                       "home"=>"0112334466")),
            array("name"=>"Malith Wijekoon",
                  "email"=>"malith@hotmail.com",
                  "telephone"=>
                                array("office"=>"0332301311",
                                      "personal"=>"077456453",
                                      "home"=>"0112556677")),
            array("name"=>"Sanath Perera",
                  "email"=>"sanath@yahoo.com",
                  "telephone"=>
                                array("office"=>"0112201654",
                                      "personal"=>"0757277365",
                                      "home"=>"0312867725")),
            array("name"=>"Gihnan Indran",
                  "email"=>"gihan@gmail.com",
                  "telephone"=>
                                array("office"=>"032222526",
                                      "personal"=>"0778856385",
                                      "home"=>"0322243426")),
            );

     function searchValue($type, $value, $array) {
           foreach ($array as $key => $val) {
    //echo $val[$type]. "=== ".$value."
";
    if($type != 'tp'){
       if ($val[$type] === $value) {
           return $key;
       }
    }else{

if ($val['telephone']['office'] === $value || $val['telephone']['personal'] === $value || $val['telephone']['home'] === $value) {
           return $key;
       }
    }
      }
          return null;
     }

       if(isset($_POST['btn_search'])){
$text = isset($_POST['search_val'])?$_POST['search_val']:null;
$type = isset($_POST['search'])?$_POST['search']:null;
$result =  searchValue($type,$text, $contact);

$data ='';
$data .= "

Name	Email	                                 Telephone
";
$data  .= "
".$contact[$result]['name']."	".$contact[$result]['email']."	Office :".$contact[$result]['telephone']['office']."
Personal :".$contact[$result]['telephone']['personal']."
Home :".$contact[$result]['telephone']['home']."
";
$data  .= "
";

   }

this is the html part.

<form name="form1" action="<?php $_SERVER['PHP_SELF']?>" method="POST">
        Search Contacts

Search By
<select name="search">
             <option value="name" <?php echo(isset($_POST['search'])&&($_POST['search']=="name")?"selected":null); ?>>Name</option>
            <option value="email" <?php echo(isset($_POST['search'])&&($_POST['search']=="email")?"selected":null); ?>>Email</option>
            <option value="tp" <?php echo(isset($_POST['search'])&&($_POST['search']=="tp")?"selected":null); ?>>Telephone</option>
    </select>

    Search Value
  <input type="text" name="search_val" id="search_val" value="<?php echo        (isset($_POST['search_val'])?$_POST['search_val']:null) ?>">
     <button type="submit" name="btn_search">Search</button>

       <?php
          if(isset($data )){echo $data ;}
        ?>

    </form>


text:
Q: Write field update logic in before or after trigger I have to perform below logic to update opportunity status based on opportunity's Account's trial__c field on insert of opportunity.
For(Opportunity opp : trigger.new)
     {
       If(opp.Account.trial__c == 'service')
       {
         opp.status__c  = 'Closed';

       }

     }

however trigger.new doesnt contain related object field so we will need to query it from opportunity and for that we would need id. So above logic cannot be performed in before trigger of opprotunity and doing this logic in after trigger of opportunity wont be best practice as we will be updating field of opportunity record in opportunity after trigger.
What can be the best way to implement this functionality.

A: Field updates should always go in the before context. Putting them after requires further DML, which has a host of complications. If you need to query for related records, you can query those tables by Id instead.
Set<Id> accountIds = new Set<Id>();
for (Opportunity record : trigger.new)
    accountIds.add(record.AccountId);
Map<Id, Account> accounts = new Map<Id, Account([
    SELECT Trial__c FROM Account WHERE Id IN :accountIds
]);
for (Opportunity record : trigger.new)
{
    if (accounts.get(record.AccountId)?.Trial__c == 'Some Value')
    {
        // logic here
    }
}

You may also want to look into some best practices like Trigger Handler pattern, and Filter Layer as well.


text:
Q: Split list into two dependent on condition and return value from larger list I have a list as following:
 mylist = [0.254, 0.754, 0.152, 0.981, 0.614]

My list contains numbers that are less than or equal to 0.5 and numbers greater than 0.5.
I want to choose the most frequent category determined by how many are <= 0.5 versus how many are > 0.5.
For example, in the above list, since there are more numbers greater than 0.5 than less than 0.5, 3 versus 2, I want to return one of these numbers as the output, for example 0.754.

A: You can filter out two lists from the original and then return the most frequent of the larger list
l1 = list(filter(lambda x: x > .5, l))
l2 = list(filter(lambda x: x < .5, l))
if len(l1) > len(l2):
    print(max(set(l1), key = l1.count))
else:
    print(max(set(l2), key = l2.count))

0.754

A: Just go over the list, and append to the desired list.
Keeping it simple as possible:
mylist = [0.254,0.754,0.152,0.981,0.614]

above = []
below = []
for num in mylist:
    if num > 0.5:
        above.append(num)
    else:
        below.append(num)
if len(above) > len(below):
    print(above[0])
elif len(below) != 0:
    print(below[0])

output:
0.754

A: import random
random_value = None
my_list = [0.254,0.754,0.152,0.981,0.614]
small_list = [elem for elem in my_list if elem < 0.5]
large_list = [elem for elem in my_list if elem > 0.5]
try:
    if len(small_list) == len(large_list):
        random_value = random.choice(small_list)
    if len(small_list) < len(large_list):
        random_value = random.choice(small_list)
    else:
        random_value = random.choice(large_last)
    print(random_value)
except IndexError as e:
    print("something went wrong got two empty lists")

A: You can approach this problem by first determining the most common category; for example via collections.Counter. Then feed this into a generator comprehension and extract the first in-scope value.
The algorithm will have linear time complexity.
from collections import Counter

L = [0.254, 0.754, 0.152, 0.981, 0.614]
flag = Counter(i > 0.5 for i in L).most_common(1)[0]

L_filtered = (i for i in L if ((i > 0.5) if flag else (i <= 0.5)))
sample = next(iter(L_filtered))  # 0.754


text:
Q: FIle upload code FIle Exist Validation Code in MVC 4 Here is my Controller for file upload :
[HttpPost]
        public ActionResult Create(AdulLiteracyTeachers adulliteracyteachers, HttpPostedFileBase[] files)
        {
            foreach (HttpPostedFileBase file in files)
            {
                string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/"), System.IO.Path.GetFileName(file.FileName));
                file.SaveAs(path);
                adulliteracyteachers.Image = file.FileName;
            }
            if (ModelState.IsValid)
            {

                db.AdulLiteracyTeachers.Add(adulliteracyteachers);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.DistID = new SelectList(db.Districts, "DistID", "DistName", adulliteracyteachers.DistID);
            return View(adulliteracyteachers);
        }

How Can I put the Check If file already exists upload another ?

A: suppose in View:
<input type="file" id="FileUpload" name="FileUpload"/>

you need to do that in action:
string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/"), System.IO.Path.GetFileName(file.FileName));

if (System.IO.File.Exists(path))
{
    //Other code

this.ModelState.AddModelError("FileUpload", "File Already exists");

return View(adulliteracyteachers);
}

else
{
 // upload and save in db
}


text:
Q: what is difference between settings_data.json and settings_schema.json in shopify What is The difference between settings_data.json and settings_schema.json file in shopify, i can set theme settings by  both, but i will use which one for when exactly? I am giving an example in below where is displayed Setting_schema.json file and Setting_data.json file both but i can understand both are creating same functionality in admin section. But What is the difference between then. Why shopify theme used two type settings json file?
/**Here is Setting_schema.json file :**/

[
  {
    "name": "theme_info",
    "theme_name": "Minimal",
    "theme_author": "Shopify",
    "theme_version": "1.0",
    "theme_documentation_url": "https:\/\/docs.shopify.com\/manual\/more\/official-shopify-themes\/minimal",
    "theme_support_url": "https:\/\/support.shopify.com\/"
  },
  {
    "name": "Layout",
    "settings": [
      {
        "type": "checkbox",
        "id": "enable_wide_layout",
        "label": "Enable wide layout"
      }
    ]
  },
  {
    "name": "Colors",
    "settings": [
      {
        "type": "header",
        "content": "Background"
      },
      {
        "type": "checkbox",
        "id": "theme_bg_image",
        "label": "Use theme background"
      },
      {
        "type": "image_picker",
        "id": "bg_custom",
        "label": "Custom image"
      },
      {
        "type": "radio",
        "id": "bg_image_display",
        "label": "Image display",
        "options": [
          {
            "value": "tile",
            "label": "Tile"
          },
          {
            "value": "stretch",
            "label": "Stretch"
          }
        ]
      },
      {

like this...
/**And Here is Schema_data.json code:**/

{
  "current": {
    "enable_wide_layout": false,
    "theme_bg_image": false,
    "bg_custom": "",
    "bg_image_display": "tile",
    "color_topbar_bg": "#eeeeee",
    "color_body_bg": "#ffffff",
    "color_footer_bg": "#eeeeee",
    "color_borders": "#dddddd",
    "color_primary": "#ab094b",
    "color_button_primary_text": "#ffffff",
    "color_secondary": "#767676",
    "color_button_secondary_text": "#ffffff",
    "color_topbar_text": "#a8003e",
    "color_header_text": "#595556",
    "color_body_text": "#5b5252",
    "color_footer_text": "#555555",
    "color_footer_social_link": "#555555",
    "type_base_family": "'HelveticaNeue', 'Helvetica Neue', Helvetica, Arial, sans-serif",
    "type_base_size": "16px",
    "type_header_family": "Google_PT+Serif_700_serif",
    "type_header_size": "36px",
    "type_accent_family": "Google_Lato_400_sans",
    "type_accent_size": "16px",
    "type_accent_transform": false,
    "type_accent_spacing": false,
    "favicon": "shopify:\/\/shop_images\/color_transparent_500px_81b18ab4-183c-480f-ba6a-529b0e9e665c.png",
    "social_twitter_link": "",
    "social_facebook_link": "",
    "social_pinterest_link": "",
    "social_google_plus_link": "",
    "social_instagram_link": "",
    "social_snapchat_link": "",
    "social_tumblr_link": "",
    "social_youtube_link": "",
    "social_vimeo_link": "",
    "social_fancy_link": "",
    "social_rss_link": "",
    "share_facebook": true,
    "share_twitter": true,
    "share_pinterest": true,
    "social_sharing_style": "normal",
    "checkout_header_image": "",
    "checkout_logo_image": "shopify:\/\/shop_images\/color_transparent_500px_e0d779f9-b33c-47b1-bb14-fb8fde7411d7.png",
    "checkout_logo_position": "left",
    "checkout_logo_size": "medium",
    "checkout_body_background_image": "",...........

like this as a example
I can see both outputting theme setting option in admin panel Then what is difference between those?
What is The difference between settings_data.json and settings_schema.json file in shopify, i can set theme settings by  both, but i will use which one for when exactly? I am giving an example in below where is displayed Setting_schema.json file and Setting_data.json file both but i can understand both are creating same functionality in admin section. But What is the difference between then. Why shopify theme used two type settings json file?

A: The schema file is here for generating/creating/editing options for your theme which will be displayed in theme interface for user. It is the one you use to create options (setting all parameters such ID, type, label, etc...).
The data file is recording all option values. It's sort of database in JSON.  It might be used to modify an option value or a theme preset directly in the theme without using user interface.
Schema manages keys and data stores values set by user.

A: From Shopify post: link
settings_schema.json vs. settings_data.json
The settings_schema.json file controls the organization and options available to a merchant in the theme editor. It's used to create and edit the theme settings available for a merchant within a theme. The theme settings follow the specified file format outlined by the Shopify documentation.
The settings_data.json file stores the theme settings data saved from the theme editor. It can also include 'theme styles', also known as presets. If presets are defined, it enables a merchant to choose a theme style which is predetermined by a theme developer. The theme style then sets specific values for the keys defined in the settings_schema.json file.


text:
Q: Understanding recursion in a function that converts list of Maybe a to Maybe [a] While learning Haskell I came across this flipMaybe function:
flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe [] = Just []
flipMaybe (Nothing:xs) = Nothing
flipMaybe (Just x:xs) = case flipMaybe xs of
    Nothing -> Nothing
    Just ls  -> Just (x:ls)

I can't wrap my head around the last line. What is ls here? How does the recursion work here? Or in another words, can someone show me how this function solves flipMaybe [Just 1, Just 2, Just 3]? (step by step)

A:
I can't wrap my head around the last line. What is ls here?

If the recursive call on the tail of the list return a Just ls, then ls is the list wrapped in the Just. So if flipMaybe [Just 3] is called, this will return a Just [3], and thus ls is [3].
This is used to prepend the list with xs. If we thus evaluate flipMaybe [Just 1, Just 2], then we first inspect the first item, if that is a Nothing, we return Nothing: we do not care about the rest of the list, we know that the outcome will be a Nothing, if it is a Just …, we should check what flipMaybe [Just 2] will return. If it returns a Nothing, then we thus return Nothing, since then it means there is a Nothing in the tail of the list. If it is a Just ls, then we return a Just (x : ls), we thus prepend the item of the list to the outcome of the recursive call.
If the list thus looks like [Just 2, Nothing, Just 3], then we first investigate Just 2, since it is not Nothing, we make a recursive call with flipMaybe [Nothing, Just 3]. Since that list starts with a Nothing, Nothing is returned from the flipMaybe [Nothing, Just 3], and thus we return Nothing for flipMaybe [Just 2, Nothing, Just 3].


text:
Q: What language could let us get the defined parameter name and passed parameter name? For example, I defined a method:
def hello(String name) {
    println("Hello " + name)
}

I want to the the name of argument in runtime:
def hello(String name) {
     println("The name of the parameter of this method is: " + getParamName())
     // getParamName() will be `name` here
}

And, I expect to get the passed name of the parameter:
def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}

String user1 = "someone"
hello(user1)

It will print:
Passed parameter name:  user1

Notice, here is user1, the variable name!
I know this is difficult, since java/groovy/scala can't do it. But I think it's a very useful feature(especially for web-framework design). Is there a language can do it?

A: You can't get the name of an argument in general because the argument may not be a named variable. Given this:
def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}

What would it output here:
hello("a literal")
hello("an " + "expression")

Given that, there are some languages that let you access the raw AST of the passed argument. Macros in Lisp, Io, and Ioke all let you define functions that will take a chunk of unevaluated code as the argument, which you can then inspect.

A: *

*Python

There is the inspect module and one of the many functions there will get you the name and default value of arguments of a function.
inspect.getargspec(func)

*

*C#

Here's a good example from another SO question using anonymous types and reflection Resolving a parameter name at runtime

*

*Javascript

And here's a way to do it in Javascript using RegEx (another SO question, that also mentions the Python way) Inspect the names/values of arguments in the definition/execution of a JavaScript function


text:
Q: не увеличивается точность нейросети на тестовом наборе точность на тренировочном наборе нормально увеличивается, а вот на тестовом никак, использовал dropout и l2 регуляризацию - не помогло. Также менял количество слоев и нейронов в каждом, не помогает. даных для обучения больше достать не получается.
набор даных можно скачать по ссылке: https://drive.google.com/file/d/1WrfFHJ7SfS-d9eRuiVvq_gSDSVNgcO1p/view?usp=sharing
ниже одна из многих вариаций которую я пробовал(максимально сократил, но она рабочая, и воспроизводит проблему)
import numpy as np
import h5py
import keras
import matplotlib.pyplot as plt
import random
import os
import tensorflow as tf

def load_data(name):
    train_dataset = h5py.File('datasets/' + name + '.h5', "r")
    train_x = np.array(train_dataset["train_x"][:])
    train_y = np.array(train_dataset["train_y"][:])
    train_y = train_y.reshape((1, train_y.shape[0]))
    return train_x,train_y

def Normalize(train_x):
    max = 0
    for i in train_x:
        for j in i:
            if j > max:
                max = j
    train_x = train_x / max
    return train_x

train_x,train_y = load_data('train_data')
train_x = Normalize(train_x)
train_x = train_x.reshape(train_x.shape[0],-1)
train_y = train_y.T

seed = 13
l2_k = 0.1
dropout_k = 0.3

np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
tf.random.set_seed(seed)

input = keras.layers.Input(shape = train_x.shape[1])

layer1 = keras.layers.Dropout(dropout_k,seed=seed)(keras.layers.Dense(1300,activation=keras.layers.LeakyReLU(0.1), kernel_initializer=keras.initializers.TruncatedNormal(seed=seed))(input))
layer2 = keras.layers.Dropout(dropout_k,seed=seed)(keras.layers.Dense(700,activation=keras.layers.LeakyReLU(0.1), kernel_initializer=keras.initializers.TruncatedNormal(seed=seed))(layer1))
layer3 = keras.layers.Dropout(dropout_k,seed=seed)(keras.layers.Dense(300,activation=keras.layers.LeakyReLU(0.1), kernel_initializer=keras.initializers.TruncatedNormal(seed=seed))(layer2))
layer4 = keras.layers.Dropout(dropout_k,seed=seed)(keras.layers.Dense(70,activation=keras.layers.LeakyReLU(0.1), kernel_initializer=keras.initializers.TruncatedNormal(seed=seed))(layer3))

output =  keras.layers.Dropout(0,seed=seed)(keras.layers.Dense(1, activation='sigmoid', kernel_initializer=keras.initializers.TruncatedNormal(seed=seed))(layer4))

model = keras.Model(inputs=input, outputs=output)
model.compile(loss=keras.losses.BinaryCrossentropy(), optimizer=keras.optimizers.Adam(0.01), metrics=[keras.metrics.BinaryAccuracy()])
hist = model.fit(train_x, train_y, epochs=30,validation_split = 0.2, batch_size=256)

plt.plot(hist.history['binary_accuracy'], label = 'train accuracy')
plt.plot(hist.history['val_binary_accuracy'], label = 'test accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()


text:
Q: shinyWidgets::prettyRadioButtons() The alignment of Choices on Radio Button #484 require('BBmisc')
lib('shiny')
lib('shinythemes')
lib('shinydashboard')
lib('shinydashboardPlus')
lib('dashboardthemes')
lib('shinyWidgets')
lib('shinyjs')
lib('memoise')
if(!require('XML')) devtools::install_github('omegahat/XML')
lib('XML')

### creating custom logo object
logo <- shinyDashboardLogoDIY(
  boldText = 'ξηg',
  mainText = 'Lιαη Ημ',
  textSize = 16,
  badgeText = ' ®γσ',
  badgeTextColor = 'white',
  badgeTextSize = 2,
  badgeBackColor = "#40E0D0",
  badgeBorderRadius = 3)

alignCenter <- memoise(function(el) {
  htmltools::tagAppendAttributes(el, style="width:500vw;height:100vh;background-color:#fff;display:flex;align-items:center;justify-content:center;")
})

ui <- shinyUI(
  shinydashboardPlus::dashboardPage(#skin = 'midnight',
    header = shinydashboardPlus::dashboardHeader(title = logo),

    sidebar = shinydashboardPlus::dashboardSidebar(
      minified = TRUE, collapsed = FALSE,
      sidebarMenu(
        id = 'tabs',
        menuItem('®Studio ☁', tabName = 'menu',
                 ## https://getbootstrap.com/docs/3.4/components/#glyphicons
                ## https://fontawesome.com/icons
                icon = icon('fa-brand fa-linux'), startExpanded = TRUE,
                menuSubItem(' Home', tabName = 'home'),
                menuSubItem(' ENGLISH', tabName = 'en'),
                menuSubItem(' 简体中文', tabName = 'cn'),
                menuSubItem(' 繁体中文', tabName = 'tw'),
                menuSubItem(' 日本語', tabName = 'jp'),
                menuSubItem(' 한국어', tabName = 'kr'),
                menuSubItem(' Deutsch', tabName = 'de'),
                menuSubItem(' français', tabName = 'fr'),
                menuSubItem(' Italiano', tabName = 'it'))#,
        #menuItem('Appendices', icon = icon('th'), tabName = 'append',
        #         menuSubItem('Author', tabName = 'author'))
        )),

    body = dashboardBody(
      shinyDashboardThemes(theme = 'blue_gradient'),
      tabItems(
        tabItem(tabName = 'home', h2('®Studio ☁', align = 'center'), alignCenter(
          #shinydashboardPlus::box(
                  prettyRadioButtons(
            inputId = 'rb', label = NULL,
            choices = c(' ENGLISH' = 'en',
                        ' 简体中文' = 'cn',
                        ' 繁体中文' = 'tw',
                        ' 日本語' = 'jp',
                        ' 한국어' = 'kr',
                        ' Deutsch' = 'de',
                        ' Français' = 'fr',
                        ' Italiano' = 'it'),
            shape = 'curve', animation = 'pulse',
            selected = character(0), status = 'primary',
            thick = TRUE, width = '100%', bigger = TRUE,
            icon = icon('registered')))
          ),
        tabItem(tabName = 'en', h2(' ENGLISH', align = 'center'),
                tags$iframe(src = 'http://rpubs.com/englianhu/ryo-en',
                            height = 800, width = '100%', frameborder = 0)#,
                #HTML(readLines('www/ryo-en.html')),
                #fluidPage(includeHTML('www/ryo-en.html'))
                ),
        tabItem(tabName = 'cn', h2(' 简体中文', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-cn',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-cn.html')),
                fluidPage(includeHTML('www/ryo-cn.html'))),
        tabItem(tabName = 'tw', h2(' 繁体中文', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-tw',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-tw.html')),
                fluidPage(includeHTML('www/ryo-tw.html'))),
        tabItem(tabName = 'jp', h2(' 日本語', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-jp',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-jp.html')),
                fluidPage(includeHTML('www/ryo-jp.html'))),
        tabItem(tabName = 'kr', h2(' 한국어', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-kr',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-kr.html')),
                #fluidPage(includeHTML('www/ryo-kr.html'))
                ),
        tabItem(tabName = 'de', h2(' Deutsch', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-de',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-de.html')),
                #fluidPage(includeHTML('www/ryo-de.html'))
                ),
        tabItem(tabName = 'fr', h2(' Français', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-fr',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-fr.html')),
                #fluidPage(includeHTML('www/ryo-fr.html'))
                ),
        tabItem(tabName = 'it', h2(' Italiano', align = 'center'),
                #tags$iframe(src = 'https://rpubs.com/englianhu/ryo-fr',
                #            height = 800, width = '100%', frameborder = 0),
                #HTML(readLines('www/ryo-fr.html')),
                #fluidPage(includeHTML('www/ryo-fr.html'))
                ))),

  footer = shinydashboardPlus::dashboardFooter(
    p('Powered by - Copyright® Intellectual Property Rights of ',
      tags$a(href='https://www.scibrokes.com', target = '_blank',
             tags$img(height = '20px', alt = 'scibrokes', #align='right',
                      src='www/Scibrokes.png')),
      HTML("Sςιβrοκεrs Trαdιηg®"))),
  title = 'DashboardPage'))

#shinyApp(server = server, ui = ui)

ui.R as above

require('BBmisc')
lib('shiny')
lib('shinythemes')
lib('shinydashboard')
lib('shinydashboardPlus')
lib('dashboardthemes')
lib('shinyWidgets')
lib('shinyjs')
lib('memoise')
if(!require('XML')) devtools::install_github('omegahat/XML')
lib('XML')

server <- shinyServer(function(input, output, session) {

  #observeEvent(input$rb, {
  #       newtab <- switch(input$tabs,
  #                        "en" = "en",
  #                        "cn" = "cn",
  #                        "tw" = "tw",
  #                        "jp" = "jp")
  #       updateTabItems(session, "tabs", newtab)
  #    })

  #output$cv_page <- renderUI({
  #
  #  page = switch(input$rb,
  #                en = 'www/ryo-en.html',
  #                cn = 'www/ryo-cn.html',
  #                tw = 'www/ryo-tw.html',
  #                jp = 'www/ryo-jp.html')
  #
    #HTML(markdown::markdownToHTML('ryo-en.md'))
    #HTML(rmarkdown::render(knit('ryo-en.Rmd')))
  #  includeHTML(page)
  #})

  #observeEvent(input$rb, {
  #  newtab <- switch(input$tabs,
  #                   "home" = "home",
  #                   "en" = "en",
  #                   "cn" = "cn",
  #                   "tw" = "tw",
  #                   "jp" = "jp",
  #                   "author" = "author")
  #  updateTabItems(session, "tabs", newtab)
  #})

  observeEvent(input$rb == 'en', {
    updateTabItems(session, "tabs", selected = "en")
  })

  observeEvent(input$rb == 'cn', {
    updateTabItems(session, "tabs", selected = "cn")
  })

  observeEvent(input$rb == 'tw', {
    updateTabItems(session, "tabs", selected = "tw")
  })

  observeEvent(input$rb == 'jp', {
    updateTabItems(session, "tabs", selected = "jp")
  })

  #output$ryo_en <- renderUI({
  #  #HTML(markdown::markdownToHTML('ryo-en.md'))
  #  #HTML(rmarkdown::render(knit('ryo-en.Rmd')))
  #  includeHTML("ryo-en.html")
  #})

  #output$ryo_cn <- renderUI({
  #  #HTML(markdown::markdownToHTML('ryo-en.md'))
  #  #HTML(rmarkdown::render(knit('ryo-en.Rmd')))
  #  includeHTML("ryo-cn.html")
  #})

  #output$ryo_tw <- renderUI({
  #  #HTML(markdown::markdownToHTML('ryo-en.md'))
  #  #HTML(rmarkdown::render(knit('ryo-en.Rmd')))
  #  includeHTML("ryo-tw.html")
  #})

  #output$ryo_jp <- renderUI({
  #  #HTML(markdown::markdownToHTML('ryo-en.md'))
  #  #HTML(rmarkdown::render(knit('ryo-en.Rmd')))
  #  includeHTML("ryo-jp.html")
  #})

  #observeEvent(input$rb, {
  #  updateTabItems(session, input$rb,
  #                    selected = input$rb)
  #})

  #observeEvent(input$rb, {
    #tbs <- c('en', 'cn', 'tw', 'jp', 'kr', 'de', 'fr', 'it')
  #  newtab <- switch(input$tabs,
  #                   'en' = 'en',
  #                   'cn' = 'cn',
  #                   'tw' = 'tw',
  #                   'jp' = 'jp',
  #                   'kr' = 'kr',
  #                     'de' = 'de',
  #                   'fr' = 'fr',
  #                   'it' = 'it')
  #  updateTabItems(session, 'tabs', newtab)#, selected = input$rb)
  #})

  #observeEvent(input$rb, {
  #  updatePrettyRadioButtons(
  #    session = session,
  #    inputId = 'rb',
  #    choices = c('en', 'cn', 'tw', 'jp', 'kr', 'de', 'fr', 'it'),
  #    prettyOptions = list(animation = 'pulse', status = 'info',
  #                         shape = 'curve', status = 'primary',
  #                         thick = TRUE, width = '100%',
  #                         bigger = TRUE, icon = icon('registered')))
  #}, ignoreInit = TRUE)

})

#shinyApp(server = server, ui = ui)

server.R as above
Try to use shinyWidgets::prettyRadioButtons() but wonder why the alignment doesn't working fine? Below shows the problem.

Current output as above, the choices do not align same line with radio buttons
Just wonder how to make it work as normal as shows below? I do appreciate if somebody take a look.

Expected output as above, the choices do align same line with radio buttons

Expected output as above will be BEST, the choices do align same line with radio buttons with stepwise effect (animated bounce-in or fly-in will be wonderful)

Source of Question:

*

*GitHub: The alignment of Choices on Radio Button #484

*shinyWidgets::prettyRadioButtons() and shinydashboard::updateTabItems()


text:
Q: How to configure PCI Express hard ip in Stratix IV? I want to use PCI Express for my upcoming project. So before working for my project I want to do some basic exprements with PCI express. I tried PCI Express reference for stratic IV and it was succesful. As a next step I want to either modify the design or to do someting by my own.
PCI Express hard ip is there in stratix IV, how I can configure it to do some basic experiment (simplest)?


text:
Q: Mongodb : can't find a table mapping for namespace database.collection I am trying to develop an android application withAndroid Studio in java and to insert data from a text entered in the application into the mongodb database, however, although the connection is carried out without problem the logs return me "Error:FUNCTION_EXECUTION_ERROR(realm::app::ServiceError:14): can't find a table mapping for namespace db.collec". I do however have a collection named collec in a db database.
Here is my code in java, do you know what is causing this
public void onClick(View v) {
    User user = app.currentUser();
    mongoClient = user.getMongoClient("mongodb-atlas");
    mongoDatabase = mongoClient.getDatabase("db");
    MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collec");

    mongoCollection.insertOne(new Document("userid",user.getId()).append("data",dataEditText.getText().toString())).getAsync(result -> {
        if(result.isSuccess())
        {
            Log.v("Data","Data Inserted Successfully");
        }
        else
        {
            Log.v("Data","Error:"+result.getError().toString());
        }
    });

The error seems to be the same as here but I don't understand the resolution.
MongoDB Realm Functions on React Native


text:
Q: PostgreSQL import file In PostgreSQL and bash(linux), are there ways to directly import a file from the filesystem like
[execute.sh]
pgsql .... -f insert.txt
[insert.txt]
insert into table(id,file) values(1,import('/path/to/file'))
There seems to be no import function, bytea_import as well, lo_import would save int and I don't know how to get the file back (these files are in small sizes so using lo_import seems not appropriate)
And can how do I move the insert.txt statement to PostgreSQL?

A: I'm not sure what you're after, but if you have script with SQL-statements, for example the insert statements that you mention, you can run psql and then run the script from within psql. For example:
postgres@server:~$ psql dbname
psql (8.4.1)
Type "help" for help.

dbname=# \i /tmp/queries.sql

This will run the statements in /tmp/queries.sql.
Hope this was what you asked for.

A: In case of more detailed parameters:
$ psql -h [host] -p [port] -d [databaseName] -U [user] -f [/absolute/path/to/file]

A: The manual has some examples:
testdb=> \set content '''' `cat my_file.txt` ''''
testdb=> INSERT INTO my_table VALUES (:content);

See http://www.postgresql.org/docs/8.4/interactive/app-psql.html


text:
Q: Tweenlite in multiple objects I tried to move cards to my  users they are three members here i have nine cards here my code below.I have used tweenlite to move first three cards moved successfully then rest of cards how can i move to users.
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;

 click_mc.addEventListener(MouseEvent.CLICK, UserOne);

function UserOne(evt:MouseEvent):void
{

    TweenMax.to(joker_mc, .5, { x:598.25, y:164.45 , onComplete:UserTwo} );
}

function UserTwo():void
{
    TweenLite.to(king_mc, .5, { x:316.50, y:267.90, onComplete:UserThree} );

}

function UserThree():void
{
    TweenLite.to(queen_mc, .5, { x:39, y:172} );

}

Anyone knows Please Elaborate this one.

A: There's no need to create separate code for each of the cards, they are all alike. Create an Array with card + x + y entries, and work with the entries.
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;

var currentEntry:int = -1;
var aList:Array =
[
    {card:joker_mc, x:598.25, y:164.45},
    {card:king_mc,  x:316.50, y:267.90},
    {card:queen_mc, x:39, y:172},

    // ...
    // and so on
];

click_mc.addEventListener(MouseEvent.CLICK, onClick);

function onClick(e:MouseEvent):void
{
    // Unsubscribe to avoid the mess with second click.
    click_mc.removeEventListener(MouseEvent.CLICK, onClick);

    // Start process.
    moveNext();
}

function moveNext():void
{
    currentEntry++;

    // Stop the process if all the cards have been moved.
    if (currentEntry >= aList.length) return;

    // Get the entry.
    var anEntry:Object = aList[currentEntry];

    // Move the card.
    TweenLite.to(anEntry['card'], .5, {x:anEntry['x'], y:anEntry['y'], onComplete:moveNext});
}


text:
Q: Displaying map in a Fragment I have a master class which creates two fragment classes.  One of them is MapDisplay().java
I want to display a map in this class.  Here is my code for MapDisplay()
public class MapDisplay extends Fragment implements OnMapClickListener{
    private GoogleMap googlemap;
    LatLng GAN = new LatLng(34.4305556,74.9250000);

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.maplayout, container, false);

        try
        {
            if(googlemap==null)
            {
                 googlemap=
            ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map2)).getMap();
            googlemap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            googlemap.setMyLocationEnabled(true);
            googlemap.getUiSettings().setMyLocationButtonEnabled(true);
            googlemap.getUiSettings().setZoomControlsEnabled(false);

            }
            if(googlemap!=null)
            {

            Marker m = googlemap.addMarker(new MarkerOptions().position(GAN).title("Gangbal"));
            m.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
            googlemap.moveCamera(CameraUpdateFactory.newLatLngZoom(GAN, 15));
            googlemap.animateCamera(CameraUpdateFactory.zoomTo(10),2000,null);
            googlemap.setOnMapClickListener(this);
            }
            else
            {
                Toast.makeText(getActivity(), "WELL! HELLO THERE", Toast.LENGTH_LONG).show();
            }
        } catch(Exception e)
        {
            e.printStackTrace();
        }
        return rootView;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        Bundle args1 = new Bundle();
        args1.putParcelable("LOCATION", GAN);
        Intent a = new Intent(getActivity(),FullScreenMap.class);
        a.putExtra("bundle", args1);
        a.putExtra("title", "Gangbal");
        startActivity(a);

    }
}

And here's my XML layout file maplayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</RelativeLayout>

This class however, doesn't display the map I want to.  Just a world map with no markers.  Also clicking on this map doesn't work.
I'm creating the MapDisplay() fragment class in another class
    FragmentPagerAdapter tabadapter = new TabAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.tabpager);
pager.setAdapter(tabadapter);

    class TabAdapter extends FragmentPagerAdapter{
public TabAdapter(FragmentManager fm){
    super(fm);
}

@Override
     public Fragment getItem(int m) {
    switch(m)
    {
    case 0:
        return new MapDisplay();
    case 1:
        return new Description();
    }
    return null;
}

    @Override
    public CharSequence getPageTitle(int position) {
        return CONTENT[position % CONTENT.length];
    }

    @Override
    public int getCount() {
      return CONTENT.length;
    }

}
So I guess MapDisplay() should extend Fragment, right??
What am I doing wrong?  Please help!

A: You need to use a MapView or your fragment should extend MapFragment.
http://developer.android.com/reference/com/google/android/gms/maps/MapView.html
So have the below in maplayout.xml
<?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" >

<com.google.android.gms.maps.MapView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    />

</RelativeLayout>

In Fragment
View rootView = inflater.inflate(R.layout.maplayout, container, false);
MapView  mapView = (MapView) rootView.findViewById(R.id.map);
GoogleMap map = mapView.getMap();

You also need to check the availability of google play services which is not shown here.
Note:
Users of this class (MapView) must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class. In particular, you must forward on the following methods:
onCreate(Bundle)
onResume()
onPause()
onDestroy()
onSaveInstanceState()
onLowMemory()

You can check the answer @
Android - android.view.InflateException: Binary XML file line #8: Error inflating class fragment


text:
Q: Warning: Creating default object from empty value header.php on line 327 In my wordpress website showing  warning in top like this Warning: Creating default object from empty value in /home/innappsy/public_html/ramufilms/wp-content/themes/rockit/header.php on line 327
i checked the code but not able to get because im new to the wordpress  pls tell me how to resolve this.
<?php
 if(is_front_page() or is_home()){
     $show_slider = "";
     $cs_home_page_slider = get_option("cs_home_page_slider");
     if ( $cs_home_page_slider <> "" ) {
    $xmlObject = new SimpleXMLElement($cs_home_page_slider);
        $show_slider = $xmlObject->show_slider;
        $node->slider_type = $xmlObject->slider_type;
        $node->slider = $xmlObject->slider_id;
     }
   ?>


text:
Q: How to illustrate two circuits drawn in circuitikz as figures one next to the other? In fact, I want to display two circuits drawn by circuitikz as figures. I have read in a post that the same procedure to follow is the same as with figures. However when I tried it, an error was displayed. Here is the code :
\documentclass[review]{elsarticle}
\usepackage{graphicx}
\usepackage{amssymb,amsmath,nccmath}
\usepackage{cclicenses}
\usepackage{makecell}
\usepackage[straightvoltages]{circuitikz}
\usetikzlibrary{arrows}
\usepackage{lscape,array}
\usepackage{subcaption}
\usepackage{caption}

\begin{document}
\begin{figure}[!ht]
\begin{subfigure}
\centering
\captionsetup{justification=centering}
\begin{circuitikz}[scale=0.6][american voltages]
\draw

(0,0) to [open,v>=${v}_{ds}$] (0,4)
to [short, *- ,i=${i}_{ds}$] (0.5,4)
to [/tikz/circuitikz/bipoles/length=1cm,R, l=$R_s$] (2,4)
to [/tikz/circuitikz/bipoles/length=1cm,L, l=$X_s$] (4,4)
to [/tikz/circuitikz/bipoles/length=1cm,european voltage source,
l_=${\omega}_s {\phi}_{qs}$] (4.5,4)
(4.5,4) to [short, -] (5,4)
(5,4) to [/tikz/circuitikz/bipoles/length=1cm,L, l_=$X_m$] (5,0)

(5,4) to [/tikz/circuitikz/bipoles/length=1cm,european voltage source,
l_=${\omega}_r {\phi}_{qr}$] (6.5,4)
to [/tikz/circuitikz/bipoles/length=1cm,L, l=$X_r$] (7.5,4)
to [/tikz/circuitikz/bipoles/length=1cm,R, l=$R_r$] (9.8,4)
to [short, -* ,i<=${i}_{dr}$] (10,4)
(10,0) to [open, v>=${v}_{dr}$] (10,4)
(0,0) to [short, *-*] (10,0);
\end{circuitikz}
\caption{fig1}
\end{subfigure}
\begin{subfigure}
\centering
\captionsetup{justification=centering}
\begin{circuitikz}[scale=0.6][american voltages]
\draw

(0,0) to [open,v>=${v}_{qs}$] (0,4)
 to [short, *- ,i=${i}_{qs}$] (0.5,4)
 to [R, l=$R_s$] (2,4)
 to [L, l=$X_s$] (4,4)
 to [european voltage source, l_=${\omega}_s {\phi}_{ds}$] (4.5,4)
 (4.5,4) to [short, -] (5,4)
 (5,4) to [L, l_=$X_m$] (5,0)

 (5,4) to [european voltage source, l_=${\omega}_r {\phi}_{dr}$] (6.5,4)
 to [L, l=$X_r$] (7.5,4)
 to [R, l=$R_r$] (9.8,4)
 to [short, -* ,i<=${i}_{qr}$] (10,4)
 (10,0) to [open, v>=${v}_{qr}$] (10,4)
 (0,0) to [short, *-*] (10,0);
 \end{circuitikz}
 \caption{fig2}
 \end{subfigure}
 \caption{FIG3}
 \end{figure}
 \end{document}

Thank you in advance

A: you have more issues in your question and reported in your comments above:

*

*use of subfigure environment. correct syntax is:

\documentclass[review]{elsarticle}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}
\captionsetup{justification=centering}

\begin{document}
    \begin{figure}[ht]
\begin{subfigure}[t]{0.48\linewidth}
    \includegraphics[width=\linewidth]{example-image-a}
\caption{first circuit}
\end{subfigure}
    \hfill
\begin{subfigure}[t]{0.48\linewidth}
    \includegraphics[width=\linewidth]{example-image-b}
\caption{second circuit}
\end{subfigure}
\caption{FIG3}
\label{fig:fig3}
    \end{figure}
\end{document}

*use of your circuit drawings. i suspect, that this your question was dedicated to this problem, so i wonder why you not use received answer (meanwhile is see that one has been deleted). this answer solve your problems (regarding scaling). please accept it (by clicking on check mark at top left side of answer), that it become clear, what you will use in your drawings in future and that we know, what we should to improve.

*if you have new problem with your circuitikz picture, please don't hesitate to ask new question. comments are not right place for this, since they are not well visible to wide audience here (i'm not only one who is /little/ familiar with circuitikz), so more people can help you.


text:
Q: CSS3 rotate animation not working (jsFiddle) I am trying to get a <div> element to rotate constantly on the spot using CSS3. I have a jsFiddle all set up with the HTML and CSS3 but it's not doing a thing. Any help?
http://jsfiddle.net/8FUK8/
Please note I am testing in Chrome and therefore only using the -webkit- prefix at the moment.

A: do the same thing for keyframe change @keyframes to @-webkit-keyframes

A: I answered a similar question recently. Here's a jsfiddle for your convenience. You can fine-tune the styles to fit your needs, but the rotation styles will be left intact.

A: You should use animation and @keyframes compatibility selectors. for example
-moz-animation:1s foo infinite alternate;
-ms-animation:1s foo infinite alternate;
-webkit-animation:1s foo infinite alternate;

@-moz-keyframes foo {}

@-ms-keyframes foo {}

@-webkit-keyframes foo {}


text:
Q: Connecting Server-Client i am new to socket programming.Every time i run the client program it says "Could not connect to server". Can anyone tell me where i am making a mistake.
Any help would be much appreciated.
this is client.c
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
int host_socket=0;
struct sockaddr_in host_addr,serv_addr;
char sendbuffer[1024];
char recvbuffer[1024];

host_socket = socket(AF_INET,SOCK_STREAM,0);
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(5000);
host_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(host_socket,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
    printf("could not connect to server !!");
    return -1;
}
strcpy(sendbuffer,"127.0.0.1");

send(host_socket,sendbuffer,strlen(sendbuffer),0);

recv(host_socket,recvbuffer,sizeof(recvbuffer),0);
fputs(recvbuffer,stdout);

return 0;
    }

and this is server.c
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
int serv_socket=0;
struct sockaddr_in serv_addr,host_addr;
char recvbuffer[1024];
char sendbuffer[1024];
socklen_t add_len;

serv_socket = socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

bind(serv_socket,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

if(listen(serv_socket,10)<0)
{printf("no listening");}

add_len = sizeof(host_addr);
accept(serv_socket,(struct sockaddr*)&host_addr,&add_len);
recv(serv_socket,recvbuffer,sizeof(recvbuffer),0);
strcpy(sendbuffer,recvbuffer);
send(serv_socket,sendbuffer,sizeof(sendbuffer),0);

return 0;
 }

A: host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(5000);
host_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(host_socket,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
    printf("could not connect to server !!");
    return -1;
}

You put the server parameters in host_addr, but your connect call uses the uninitialized serv_addr.


text:
Q: Difference docker repository vs Ubuntu package As of today (2019-03-20), both the current docker website, and the Ubuntu package have version

18.09.2

https://stackoverflow.com/questions/50427996/difference-installing-docker-from-ubuntu-repository-and-official-docker-reposito mentions that the Docker repo package might be newer, which is currently not the case.
Are there any reasons to use the Docker repository if you just want a stable install? Are there any differences between these? (Otherwise, it seems easier to avoid another repository, another trusted GPG key etc).

A: Versions might be the same now but you can expect it to be a game of catch-up
Depending on what docker releases and how complex porting those features are into  Ubuntu ecosystem you will surely end up with a release being older
at some point using the Ubuntu docker version
What version you end up using depends on whats best for your needs.

*

*Ubuntu: More stable

*Docker: New features faster


text:
Q: Preventing react-redux from re-rendering whole page when state changes I am reading several articles about how to prevent react-redux from re-rendering the whole page, when only one little thing changes.
One article suggests that instead of wrapping all into one big container (as in figure 1 here) wrapping all into smaller containers (as in figure 2 here). If something changes in Container 2, only Component 2 and Component 3 are getting re-rendered. Component 1 would not re-render.
Figure1

Figure2

I have following questions:

*

*If I wrap everything in smaller containers, I would need "several" global states, for each container one (as indicated with the pseudo-code on the bottom of the figure). Is that common practice?

*If it is ok to have "several" global states and I would need in some property from Container1 in Container2, I would need to connect that with two global states. To me that feels like it could get messy very quick. Where does what come from?

*When and where would I use the react method shouldComponentUpdate()? Using the Big Container approach how would I differ which Component should be rerendered?! If implemented in the Components, they would not be "dump" anymore, because they need to access the global state in order to decide whether to re-render or not. I would not be able to reuse Components because every Component has its own special case when to rerender and when not. I am not sure where and when to use shouldComponentUpdate()
Please note that I am pretty new to this and might have made wrong assumptions etc. I basically want to know how not to re-render the whole page, when only one thing needs to be updated. The results from asking google differ a lot.

A: Your second approach is the way to go, though your definition of a global state is a bit misleading.
Basically, you want to have exactly one "global state". This is what is referred to as "store". All components that need to receive parts of the store are connected to it using react-redux' connect function.
Now, connect(...) is actually a HOC which wraps your component and passes only defined parts of the store to it. This way, the component (and its' children) only re-render when its' defined props change.
Don't be afraid to use connect() more often. You just have to be careful what parts of the store you pass to the container and this is exactly where performance can become an issue.
This should answer your first question. The second one is a question of design. Design in terms of how your app and maybe also in terms of how your datasource is structured. As said before, you want to have a minimum of props passed to a component so it doesn't re-render when other parts of the store change.
For the third question, you first have to understand that 'dumb components' can, of course, receive props from their parent components/containers. Dumb just means that they don't get to decide whether a re-render should happen or not. Dumb components are there to present/display data and that's it.
Let's say you have a really simple store:
const store = {
  posts: {
    all: [],
    isFetching: false,
    err: {},
  }
}

And you connect your container to it like this:
function mapStateToProps(store) {
  return {
    posts: store.posts.all,
    isFetching: store.posts.isFetching,
    err: store.posts.err,
  };
}
@connect(mapStateToProps)

And this container has three dumb components it can use:

*

*A posts component, which receives all posts and displays them using another dumb child (pseudoCode, you get the point):
 function posts = (posts) => {
   posts.map((post, id) => (
     <otherDumbComponent post={post} key={id} />
   ));
 }

*One to display just a spinner while isFetching

*One to display the error if there's one.

Now, if only isFetching has changed, only the second component will re-render and that's it. Oh, and shouldComponentUpdate() is something you probably don't want to use, because, well.. there are many good blog posts about it.


text:
Q: Rounding floats in processing.org Is there any way to round a float to the nearest decimal place in processing?
For example
float x = 1.0000001
float y = 1.1000000001

float a = x + y
round(a)

a = 2.10

The standard round() in processing rounds to the nearest whole number, but I need to have the decimals in place. I can't find a function that does what I'm looking for. I have some floats with over a hundred decimal places so I need to trim them down, if its possible.

A: Here is a function that is more processing-centric:
float fixDec(float n, int d) {
  return Float.parseFloat(String.format("%." + d + "f", n));
}

and to test it:
float x = 1.0000001;
float y = 1.1000000001;
x = fixDec(x, 2);
y = fixDec(y, 2);
float a = x + y;
round(a);

this is probably not the most efficient algorithm, but it works.

A: I am not familiar with processing. However, the common way to round to a fixed number of decimal places given a round-to-integer function is:
a = round(a * PowerOf10) * InversePowerOf10

Thus, for one digit after the decimal point, you might use:
a = round(a * 10) * .1

There are some caveats and comments:

*

*This does not work in binary floating point. It is impossible because numbers like .1 cannot be represented exactly in binary floating point. If may be close enough, depending on your needs and whether you take appropriate care.

*It may be fine in decimal floating point, but decimal floating point is rare. If processing implements decimal floating point, you may be all set.

*I used multiplication for both operations because multiplication is typically faster than division. However, it may be preferable to use division in certain situations: a = round(a * PowerOf10) / PowerOf10. (Notably, in binary floating point, this avoids the extra rounding error in calculating the inverse of PowerOf10.)

*If processing provides extended precision binary floating point, the result may be close enough for your purposes even though it is not exact.

*If you want to format a number for display rather than further calculation, look for string formatting functions instead of numerical rounding functions. Converting a number to a decimal numeral in a string can be done exactly even in binary floating point.

A:
Floats are not precise, so avoid adding small values (such as 0.0001)
  may not always increment because of rounding error. If you want to
  increment a value in small intervals, use an int, and divide by a
  float value before using it.

http://processing.org/reference/float.html
int i = 10001000;
int j = 11000001;

float a = round((i + j)/pow(10,5));

a /= 100;

println(a);

2.1


text:
Q: boost::asio::local::stream_protocol::iostream does not work? Referencing an old (from 2008) discussion:
There is a compile error when trying to use boost::asio::local::stream_protocol::iostream
There was no solution on the discussion forum and I've run into the same problem, it seems.
Has there been a fix or solution for the compile error? How can I use
boost::asio::local::stream_protocol::iostream?

A: The class stream_protocol defines no inner resolver_query type. That member type is needed for the connect function. The connect function is called inside the constructor with parameters of basic_socket_iostream. It seems to me, that the stream_protocol was not meant to act as a iostream. If you look into the stream_protocol header you even see an #if !defined(BOOST_NO_IOSTREAM) around the inner iostream type. So try to use endpoint, socket or acceptor instead.
EDIT:
If you used a string, try connecting to an stream_protocol::endpoint instead. Using something different than an stream_protocol::endpoint will result definitely in this error. If this doesn't help first construct the object and after after that, use the connect method to connect to an endpoint.
EDIT: For examples of how to use stream_local try the official example.

A: This bug was reported on the boost trac webiste. Chris closed it as invalid and suggested using the existing boost::asio::local::stream_protocol examples.

A: Why you don't ask in the referred forum, where they are with this issue? You can also look at the Trac system for pending issues. If you don't find the issue, make a new one. In this way you contribute to improving Boost.


text:
Q: javadoc MyClass.java formatting errors I'm trying to create an HTML interface for my class, but I've got some errors related with < and > format I think. I'm on Fedora 28 with java 1.8.0_191.
I wrote javadoc MyStringVector.java and get these errors:
MyStringVector.java:53: error: malformed HTML
       if 0 <= index <= size(), insert the item specified in the location
MyStringVector.java:57: error: malformed HTML
       if index < 0 o index > size() returns without do nothing
MyStringVector.java:107: error: malformed HTML
      if 0 <= index < size(), removes the element at the specified index,
MyStringVector.java:189: error: malformed HTML
      if index < 0 o index >=size() returns null.
If its a formatting problem, what escape sequence I have to use? Thanks!

A: Just escape the > and < characters like this :
  if 0 <= index <= size()

or
  if index < 0 o index > size()

And so on for all the symbols that are reserved for xml/html formatting.


text:
Q: Overriding javascript function on different page This is new to me, and I don't know how to handle it.
The page has a logo that uses transitions to change its size and color and is triggered by this on the bottom of the HTML:
document.onload="initialize()"
setInterval(function(){
    setTimeout(function(){
        $('#path1').css('transform','scale(.95)');
        $('#path2').css('transform','scale(.95)');
        $('#path2').css('fill','#F7A700');
    }, 2000);
$('#path1').css('transform','scale(1.05)');
    $('#path2').css('transform','scale(1.00)');
    $('#path2').css('fill','#FFCF55');
}, 4000);

This starts the transition and changes the color of the svg path in coordination. On a separate script page there is a function that determines the current page slider and I need to change the css fill on #path2 for a specific page. I've tried if...else statements, moving the setInterval() function to the same page, etc, but nothing is letting me override the fill color in the setInterval() function.
REVISION: Its included in the html and there is a separate js page with all of the other functions. So I thought maybe it had something to do with that but now I'm understanding it is running on an infinite loop so any changes I try to make are going to be overridden. Its a logo that is a svg with multiple paths and on the homepage slide one path needs to be white and everything else stay the same for all other pages slides. There is only one page of html and the content slides on a slider. Not sure if I explained it any better. I'm working with existing code done by someone else so I'm trying to work with what I've been given but maybe there is a better solution to run this? maybe through css? I need it to load on window or document load and run infinitely but need to be able to modify the css on it. I have to use css transforms to set it up.

A: The interval is setup to run forever. If you set the color from another script, the interval will just overwrite the color the next time the interval runs. One option is to stop the interval when setting the color from the other script. You would need a variable to hold the interval id.
var timer = null;

You would need to save the interval id when starting the interval.
timer = setInterval(function(){
    setTimeout(function(){
        $('#path1').css('transform','scale(.75)');
        $('#path2').css('transform','scale(.75)');
        $('#path2').css('fill','#F7A700');
    }, 2000);
    $('#path1').css('transform','scale(1.50)');
    $('#path2').css('transform','scale(1.50)');
    $('#path2').css('fill','#FFCF55');
}, 4000);

In your other script, stop the interval when setting the color.
if (timer) {
    clearInterval(timer);
    timer = null;
}
$('#path2').css('fill','#00FF00');

Edit:
Another possible option is to use boolean flags to stop parts of the animation. This would allow you to stop the fill animation but continue with the reest of the animation. You would need a boolean flag to indicate whether or not the fill should be animated. Initialize the flag to true.
var animateFill = true;

Use the flag to determine if interval should animate the fill attribute.
setInterval(function(){
    setTimeout(function(){
        $('#path1').css('transform','scale(.75)');
        $('#path2').css('transform','scale(.75)');
        if (animateFill){
            $('#path2').css('fill','#F7A700');
        }
    }, 2000);
    $('#path1').css('transform','scale(1.50)');
    $('#path2').css('transform','scale(1.50)');
    if (animateFill) {
        $('#path2').css('fill','#FFCF55');
    }
}, 4000);

In your other script, set the flag to false when setting the fill color.
animateFill = false;
$('#path2').css('fill','#00FF00');

If you later need to restart the animation of the fill color then set the flag back to true.
animateFill = true;


text:
Q: Calling .NET method from PowerShell with boolean parameter I'm trying to import XML node from one document to the other. I'm calling ImportNode method on XmlDocument with two parameters - node and boolean parameter.
...
$connectionString = $anotherWebConfig.SelectSingleNode("//add[@name='ConnectionString']")
$WebConfig.ImportNode($connectionString, $True)
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($connectionString)

but I'm getting an error
Exception calling "AppendChild" with "1" argument(s): "The node to be inserted is from a different document context."

I know that there must be something wrong with the import. I tried to change $True parameter to 1, 0, 10 and also remove it but it still doesn't help. It was surprising to me that even if I call this method with invalid arguments, it will pass without any exception.
What's the proper way to call .NET method from powershell with boolean parameter?

A: You seem to have misdiagnosed the issue here - it's not the boolean argument that's the problem, but the fact that you try to Append the original node, rather than the imported node:
$WebConfig.ImportNode($connectionString, $True) # <-- great effort to import node
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($connectionString)
#                                                                      ^
#                                                                      |
#                                                       Yet still appending the original

Assign the imported node (returned from ImportNode()) to a variable, and reference that as an argument to AppendChild() instead:
$ImportedNode = $WebConfig.ImportNode($connectionString, $True)
$WebConfig.SelectSingleNode("//connectionStrings").AppendChild($ImportedNode)


text:
Q: New Line in File Writer From Existing Multi-Lined String I am trying to output a multi-line string to a file using FileWriter. How can I make it recognize the lines and automatically use "output.newLine"?
Example String
static String test = "This \n" + "is \n" + "a \n" + "sample \n" + "string."

public static void testMethod (String test){
FileWriter fileWriter = new FileWriter ("output.txt", true)
BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);

bufferedWriter.write (test);
bufferedWriter.close ();
}

A: Use text.split("\n") to create multiple lines and write them separately.

A: You can replace \n with the platform new line with.
bufferedWriter.write(test.replaceAll("\n", System,getProperty("line.separator"));


text:
Q: How do I have several views watch a Singleton's data? I've set up a Singleton class. Several view controllers will be getting data from the singleton for their views. The data is periodically updated.
How would I set up the app so that the view controllers watch the singleton to see if there are changes in data... or the singleton sends a message to a view if there is new data relevant to that view?

A: You can use NSNotificationCenter to post notifications whenever the singleton's data changes (such as setter methods) and have any associated views register to receive the notifications.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

A: Create a protocol with some methods and add those listeners (they have to implement the protocol) to an array. If you change something inside your singleton, just call an all listeners this method.
For example:
@protocoll SingletonListenerProtocol
- (void)singleton:(Singleton*)singleton didChangeValueX:(NSString*)newValue;
@end

-------------------

@implementation Singleton
- (void)setValueX:(NSString*)newX {
  valueX = newX;
  for(id<SingletonListenerProtocol> listener in listeners) {
    [listener singleton:self didChangeValueX:newX];
  }
}
@end

A: I would use key-value observing. It's built in, so it's easy to take advantage of.

*

*If your data source class already uses properties, you're all set. Here is an example of one which does:
@interface Source : NSObject {}
@property (nonatomic, retain) NSString *value;
@end

@implementation Source
@synthesize value;
@end

If it does not, you only need to define a couple of specially-named methods to make it work:
- (NSDictionary*)someValue;
- (void)setSomeValue: (NSDictionary*)newValue;

(where someValue is the name of your property, and NSDictionary* is its type. setSomeValue does not need to be a public method).
If a property is computed (so that it's not appropriate to have a setter for it), you can trigger KVO notifications manually like this:
[self willChangeValueForKey:@"someValue"];
// Do work with changes the effective value of someValue
[self didChangeValueForKey:@"someValue"];

*Then, any object may subscribe to notifications when a key changes, like this:
@implementation Observer
- (id)initWithSource: (Source *)source
{
    if ([super init]) {
        _source = source;
        [_source addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"New value: %@", [change objectForKey:NSKeyValueChangeNewKey]);
}
- (void)dealloc
{
    [_source removeObserver:self forKeyPath:@"value"];
    [super dealloc];
}
@end

Your observer must implement a observeValueForKeyPath:ofObject:change:context: method, which will be called when any observed key changes on any observed object. You can tell what changed by looking at the arguments passed at ofObject: and KeyPath:.

*Change some values! Here's how the process would work with these example classes:
Source *source = [Source new];
[(Observer*)[Observer alloc] initWithSource: source];
source.value = @"foo";

You'll see this on the console, logged by observer:
New value: foo
The Key Value Coding and Key Value Observing programming guides are pretty good. I would also take a look at the NSKeyValueObserving protocol reference.


text:
Q: Type 'System.Web.UI.WebControls.GridView' does not have a public property named 'script' This is my aspx code. Simply, it has a gridview that I want to add some javascipt code.
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="MainForm.aspx.cs"
Inherits="GUI_MainForm" EnableSessionState="True" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="Server">

    <asp:Label runat="server" ID="label1"></asp:Label>

    <asp:GridView ID="gridviewFriend" Width="200px" runat="server" BorderStyle="None" ShowHeader="False" OnRowDataBound ="gridviewFriendRowDataBound">

    </asp:GridView>

</asp:Content>

I don't know why when I insert some javascript code, it shows error:

Type System.Web.UI.WebControls.GridView does not have a public
  property named script

.

A: You're putting your Javascript inside the GridView server tag. Move it outside and adjust it to something like this:
<asp:GridView ID="gridviewFriend" Width="200px" runat="server" BorderStyle="None" ShowHeader="False" OnRowDataBound ="gridviewFriendRowDataBound">
</asp:GridView>

Or better yet, toss it all together and add this CSS to your stylesheet:
#gridviewFriend tr {
    background-color: "fff";
}

#gridviewFriend tr:hover {
    background-color: "#c8e4b6";
}

#gridviewFriend tr:hover > td:nth-child(2) {
    background-color: "green";
}

A: Please remove the script tag and do this in your RowDataBound event.
protected void gridviewFriendRowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#c8e4b6';");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#fff';");
    }
}

Framework is your friend!

A: You are doing it the wrong way. Try doing it the way this article describes.
http://www.aspsnippets.com/Articles/How-to-change-GridView-Row-Color-on-Mouseover-in-ASPNet.aspx
You need to place the script tag in your  section of the page, or in your case the "HeadContent" section, like this:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">

</asp:Content>


text:
Q: Knex.js: How to create table, insert data, get select query results, then return The following snippet creates the database file, creates the table, inserts the data, queries and outputs it, but then it just hangs.
I need it to return the query result, output to console, then end the process.
What am I missing?
const knex = require('knex')({
    client: 'sqlite3',
    // debug: true,
    connection: {
    filename: "example.db"
    },
    useNullAsDefault: true
});

const data = [
    {
        col1: "one",
        col2: "two",
        col3: "three"
    },
    {
        col1: "a",
        col2: "b",
        col3: "c"
    },
    {
        col1: "1",
        col2: "2",
        col3: "3"
    }
];

knex.schema.createTable('myTable', table => {
    table.increments();
    table.string("col1");
    table.string("col2");
    table.string("col3");
})
.then(function(){
    return knex('myTable').insert(data);
})
.then(function(){
    return knex('myTable').select();
})
.then(console.log);

A: It appears that adding a knex.destroy() call helps; it does resolve the promise, but I"m not sure if it is the correct approach.
knex.schema.createTable('myTable', table => {
    table.increments();
    table.string("col1");
    table.string("col2");
    table.string("col3");
})
.then(function(){
    return knex('myTable').insert(data);
})
.then(function(){
    return knex('myTable').select();
})
.finally(function(queryResult){
    knex.destroy();
    return queryResult;
})
.catch(console.error);


text:
Q: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessaging; After integrating moengage sdk in android I'm facing this issue
implementation("com.moengage:moe-android-sdk:12.2.02")

Update
After adding dependency "firebase-messaging" to build-gradle I'm receiving new error
 java.lang.AbstractMethodError: abstract method "void com.moengage.core.internal.inapp.InAppHandler.onResume(android.app.Activity)"
        at com.moengage.core.internal.inapp.InAppManager.onResume$core_release(InAppManager.kt:102)
        at com.moengage.core.internal.lifecycle.LifecycleManager.onActivityResumed$core_release(LifecycleManager.kt:147)
        at com.moengage.core.internal.lifecycle.GlobalActivityLifecycleObserver.onActivityResumed(GlobalActivityLifecycleObserver.kt:40)
        at android.app.Application.dispatchActivityResumed(Application.java:438)
        at android.app.Activity.dispatchActivityResumed(Activity.java:1445)
        at android.app.Activity.onResume(Activity.java:1984)
        at androidx.fragment.app.FragmentActivity.onResume(FragmentActivity.java:434)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1456)


text:
Q: What is the difference between the different padding types on iOS? On iOS, the Certificate, Key, and Trust Services API contains the following padding types:

*

*kSecPaddingNone

*kSecPaddingPKCS1

*kSecPaddingPKCS1MD2

*kSecPaddingPKCS1MD5

*kSecPaddingPKCS1SHA1
A user on the Apple CDSA mailing list says that "kSecPaddingPKCS1 [...] is the same as PKCS #1 1.5". The Certificate, Key, and Trust Services Reference annotates the latter three padding types (kSecPaddingPKCS1MD2, kSecPaddingPKCS1MD5, and kSecPaddingPKCS1SAH) with "Standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation".

*

*What is the difference to kSecPaddingPKCS1?

*Is kSecPaddingPKCS1 just the raw padding of the underlying RSA operation according to RFC 3447?

*When signing a SHA-256, SHA-384, or SHA-512 digest with SecKeyRawSign(), does a developer need to use kSecPaddingPKCS1 and perform the ASN.1 padding herself? Is the ASN.1 padding necessary or can it be omitted?

Any hint that points me in the right direction is highly appreciated.

A: PKCS#1 contains two "paddings" for signatures with RSA, the "new" one (called PSS, added in version 2.1) and the "old" one (renamed "v1.5" since it was already in version 1.5 of PKCS#1). We are talking about the v1.5 padding.
When some data is signed, it is first hashed with a suitable hash function (e.g. SHA-1), then the hash value (20 bytes if using SHA-1) is wrapped into two successive layers:

*

*The hash value is encoded into an ASN.1-based structure which also specifies which hash function was used. In practice, if the hash value is H, then the first wrapping results in the sequence of bytes A || H where "||" is concatenation, and "A" is a header which is specific to the hash function (typically 15 to 20 bytes).

*The "A || H" is expanded with some extra bytes:
0x00 0x01 0xFF 0xFF ... 0xFF 0x00 || A || H
The number of bytes of value 0xFF is adjusted to that the total size equals the size of the RSA modulus (i.e. 128 bytes for a 1024-bit RSA key).
The second step is what PKCS#1 calls "type 1 padding".
kSecPaddingPKCS1 means that the function performs only the second step: it assumes that the input data is already the proper "A || H". Note that SSL/TLS (up to version 1.1) uses a signature variant which requires this mode (there's no "A", but there are two hash functions). With kSecPaddingPKCS1SHA1, the signature function expects the hash value as input, and adds the "A" header itself.
For a proper, standards-compliant signature which can be verified by third-party implementations, the "A" header must be added at some point. You can add it yourself and use kSecPaddingPKCS1, or use kSecpaddingPKCS1SHA1 and let the engine add it itself, which is probably less error-prone.
(As of 2011, use of SHA-1 is not recommended; you'd better switch to SHA-256 or SHA-512. Also, the API you are trying to use seem to be quite low-level, and the whole thing suspiciously looks as if you are tying to implement your own cryptographic protocol instead of using an existing library or framework.)


text:
Q: Accelerating expansion of a gas The his thermodynamics book, Zemansky refers to an example in which a gas in a piston is expanding for which the piston is accelerating.

It is obvious that no equation of state exists for the states traversed by a system that is not in mechanical and thermal equilibrium, since such states cannot be described in terms of thermodynamic coordinates referring to the system as a whole. For example, if a gas cylinder were to expand and to impart to a piston an accelerated motion, the gas might have, at any moment, a definite volume and temperature, but the corresponding pressure, calculated from an equation of state, would not apply to the system as a whole. The pressure would not be a thermodynamic coordinate, because it would depend not only on the velocity and acceleration of the piston but would also vary from point to point.

Extracted from "Heat and Thermodynamics" by Zemansky and Dittman, page 32.
He goes on to state that the pressure is not a thermodynamic coordinate in this case.
How is it possible to state that pressure is not a thermodynamic variable in case of an accelerating expansion of a gas ?

A: The behavior of a gas experiencing a rapid expansion (or compression) is fundamentally very different from that of the same gas under static conditions (i.e., at thermodynamic equilibrium), even if the piston velocity is not high enough to be comparable to the speed of sound.  Because of the viscous character of gases, the behavior depends not only on amount of the volume change that occurs, but also on the rate at which the volume is changing (i.e., dV/dt).  For example, a crude approximation to the force F exerted by the gas on the piston face (where the gas is doing work) is given by the equation:
$$\frac{F}{A}=\frac{nRT}{V}-\frac{k(T)}{V}\frac{dV}{dt}\tag{1}$$where k(T) is a temperature-dependent gas physical property proportional to the gas viscosity.  Note that, if the rate of change of volume approaches zero, the thermodynamic equilibrium behavior of the gas is recovered.  Note also that, although Eqn. 1 has been written for the specific case of an ideal gas, the same basic principle applies for non-ideal gas equations of state.


text:
Q: Prove there is a deterministic sequence for which $\frac{X_n}{c_n}\overset{a.s.}{\to}0$. Prove that for any sequence $X_1,X_2,\dots$ of random variables there exists a deterministic sequence $c_1,c_2,\dots$ of real numbers for which $\frac{X_n}{c_n}\overset{a.s.}{\to}0$.
So far my idea has been to try to use the Borel-Cantelli lemma to show this. I want to show that there is a sequence such that
$$
P\left(\frac{X_n}{c_n}\geq\frac1n\right)\leq\frac1{n^2},
$$
and then I could use Borel-Cantelli to finish off from here. The problem is that I'm not sure how to show that this sequence exists without having any assumptions on the random variables $X_1,X_2,\dots$ Does this require that I assume the random variables are finite? Any help would be appreciated.