text:
Q: User Class not found in Laravel 5 I have got the following Problem.
I have just upgraded to Laravel 5 from 4.2 but my UserController which I first just copied to the new Controllers folder does not work.
It always tells me that it does not fiend the User Model.
My Code looked like the following when I copied it:
UserController.php
<?php

use App\Transformer\UserTransformer;

class UserController extends ApiController
{
public function index()
{
    App::abort(403, 'This is not allowed');
}

public function show($id)
{
    $user = User::find($id);
    if($user->access_token!=Input::get('access_token')){
        return "It is not allowed to access data from other users";
    }else{
        $result = $this->respondWithItem($user, new UserTransformer);
        return $result;
    }
}

public function getID()
{
    $user = User::where('email', '=', Input::get('email'))->first();
    if($user->access_token!=Input::get('access_token')){
        return "It is not allowed to access data from other users";
    }else{
        $result = $user->id;
        return $result;
    }
}

public function register()
{
    $user = new User;
    $name = Input::get('name');
    $email = Input::get('email');
    $password = Input::get('password');

    if($name != null AND $email != null AND $password != null){
        if(User::where('email', '=', Input::get('email'))->exists()){
            return "A user with this email already exists";
        }else{
            $user->name = $name;
            $user->email = $email;
            $user->password = $password;
            $user->save();
            return "Success";
        }
    }else{
        return "All fields are required";
    }
}

public function login(){
    $user = User::where('email', '=', Input::get('email'))->first();
    if($user != null){
        if($user->password==Input::get('password')){
            $then =$user->time;
            $now = strtotime("now");
            $thenTimestamp = strtotime($then);
            $difference = $now - $thenTimestamp;
            if((empty($user->date) AND empty($user->time))OR($difference >=10800)OR($user->date!=date('d.m.Y'))){
                $user->access_token=self::getGUID();
                $timestamp = time();
                $user->date=date("d.m.Y",$timestamp);
                $timestamp = strtotime("now");
                $user->time=date('H:i', $timestamp);
                $user->save();
            }
            return $user->access_token;
        }
        else
            return "Wrong username or password";
    }else
        return "Wrong username or password";
}

function getGUID(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*100000);
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);
        $uuid =
            substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);
        return $uuid;
    }
}

public function check(){
    $user = User::where('access_token', '=', Input::get('access_token'))->first();
    if($user != null){

    }else
    return "no session";
}
}

I did not have the the Controller namespaced and the User Model just worked out of the box. The UserTransformer does have the User Model included. Here the original copy:
<?php

use App\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
/**
 * Turn this item object into a generic array
 *
 * @return array
 */
public function transform(User $user)
{
    return [
        'id'             => (int) $user->id,
        'name'           => $user->name,
        'email'            => $user->email,
        'phone'         => $user->img,
        'mobile'       => $user->mobile,
        'address'       => $user->address,
    ];
}
}

That is everything that I needed to have the functions to work.
But now in Laravel 5 the UserController does tell me that the User class is not found. I have tried to add lines like this "use App/User" or "use App/Http/Controllers/User" to the UserController. It did not work.
I am not sure why since I have got my Transformer included I do not get any error for this but the User does not work.
I have also tried different use methods to include the User Model into the Transfomer since I though there might be an error but I do not get a working version.
I hope someone can help me.

A: Let's clarify just some things that could be interfering in loading the controller.
The route: by default, laravel comes with a provider called RouteServiceProvider found at app\providers. If you take a look to this file you will find that there is a variable named $namespace. This is very usefull if you want get more "clear" routes at routes.php file. For example, having $namespace = 'App\Http\Controllers' you convert this...
Route::get('welcome', 'App\Http\Controllers\HomeController@welcome');

to this...
Route::get('welcome', 'HomeController@welcome');

So yes, a short choice for write your rules. By default, the value of $namespace is set to {Application Name}\Http\Controllers
The controller: If you laravel installation is working with the RouteServiceProvider then your controller never will be found, because the routes prefix the namespace previously declared. So, which namespace should I use in controllers? there are two options:

*

*Following the conventions of laravel 5 putting your controller at app/Http/Controllers/ folder. Then, declare the namespace as default:
namespace {Application Name}\Http\Controllers;

and setting it at routes.php like:
// weather is a controller
Route::get('foo', 'UserController@index');

// weather is a resource
Route::resource('api-user', 'UserController');

Notice that the namespace structure match the same folder structe where it is resides (Http/Controllers/)

*Delete RouteServiceProvider from providers folder AND delete it from providers array in config/app.php file. Then, you can use "absolute" namespaces like:
namespace {Application Name}\Http\Controllers;

Route::get('foo', 'Myapp\Http\Controllers\UserController@index');

Application name and autoload
did you question yourself why app folder is not added at namespace? Take a look the composer.json file:
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "MyCoolApp\\": "app/"
    }
},

If you note, you will see that there is an alias that points out to app/ folder. So, for app will response to the alias instead of app\Http\Controllers.
I am no expert in this topic, hope somebody give me hand to expand this explanation, but I have read that psr-4 is like a rule that make you match the namespace with the folder structure. As result, if your controller is like...
namespace MyCoolApp\Http\Classes;

The autoload class expects that your controller resides at aapp/Http/Classes/ instead of MyCoolApp/Http/Controllers
That is a reason why a controller could not be found.


text:
Q: Sql Server Deadlock Object IDs are too large I am trying to trace a deadlock that is occurring in our SQL 2005 database (64-bit).  We do not currently have snapshot isolation enabled.
I turned on tf-1204 and received the output below.
From this output I am able to determine that Node 1 is a stored procedure that selects data and only modifies values in #temp tables.
Node 2 is another stored procedure does a simple primary key based update on a single row of data.
What I can't determine is the actual resource that was in contention here.  The Keys of 10:72057594060734464 and 10:72057594038910976 allow me to determine the database, but these object ids cannot be resolved with object_name.  In fact, they should be int values, so I'm not sure where these large numbers are coming from.
In researching the problem I was able to get similar values out of Activity Monitor for Object ID as well.
How do I resolve these object identifiers?
Here is the deadlock tf-1204 output:

2008-12-05 07:48:28.19 spid4s      ----------------------------------
2008-12-05 07:48:28.19 spid4s      Starting deadlock search 634
2008-12-05 07:48:28.19 spid4s      Target Resource Owner:
2008-12-05 07:48:28.19 spid4s       ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980
2008-12-05 07:48:28.19 spid4s      0:Insert new node: Node:1     ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980
2008-12-05 07:48:28.19 spid4s      1:SearchOR Considering new blocker - task: 0000000000EC5198, Worker 00000000C89881C0
2008-12-05 07:48:28.19 spid4s      2:Insert new node: Node:2     ResType:LockOwner Stype:'OR'Xdes:0x00000000808F1A80 Mode: S SPID:79 BatchID:0 ECID:0 TaskProxy:(0x0000000129E82598) Value:0x1063d000
2008-12-05 07:48:28.19 spid4s      3:SearchOR Considering new blocker - task: 0000000000C3FC18, Worker 00000000F847C1C0
2008-12-05 07:48:28.19 spid4s      4:InsertKnown Cycle found between old res owner: [ ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980] and new res owner [ ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980]
2008-12-05 07:48:28.19 spid4s      4:InsertKnown search result: Deadlock found (blocking owner is on a stack)
2008-12-05 07:48:28.19 spid4s      3:SearchOR search result: Deadlock found (cycle on this level or before)
2008-12-05 07:48:28.19 spid4s      1:SearchOR search result: Deadlock found (cycle on this level or before)
2008-12-05 07:48:28.19 spid4s
2008-12-05 07:48:28.19 spid4s      Deadlock cycle was encountered .... verifying cycle
2008-12-05 07:48:28.19 spid4s      0:Insert new node: Node:1     ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980 Cost:(0/1544)
2008-12-05 07:48:28.19 spid4s      1:SearchOR Considering new blocker - task: 0000000000EC5198, Worker 00000000C89881C0
2008-12-05 07:48:28.19 spid4s      2:Insert new node: Node:2     ResType:LockOwner Stype:'OR'Xdes:0x00000000808F1A80 Mode: S SPID:79 BatchID:0 ECID:0 TaskProxy:(0x0000000129E82598) Value:0x1063d000 Cost:(0/0)
2008-12-05 07:48:28.19 spid4s      3:SearchOR Considering new blocker - task: 0000000000C3FC18, Worker 00000000F847C1C0
2008-12-05 07:48:28.19 spid4s      4:InsertKnown Cycle found between old res owner: [ ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980 Cost:(0/1544)] and new res owner [ ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980 Cost:(0/1544)]
2008-12-05 07:48:28.19 spid4s      4:InsertKnown search result: Deadlock found (blocking owner is on a stack)
2008-12-05 07:48:28.19 spid4s      3:SearchOR search result: Deadlock found (cycle on this level or before)
2008-12-05 07:48:28.19 spid4s      1:SearchOR search result: Deadlock found (cycle on this level or before)
2008-12-05 07:48:28.19 spid4s      Deadlock encountered .... Printing deadlock information
2008-12-05 07:48:28.19 spid4s      Wait-for graph
2008-12-05 07:48:28.19 spid4s
2008-12-05 07:48:28.19 spid4s      Node:1

2008-12-05 07:48:28.19 spid4s      KEY: 10:72057594060734464 (c80089667602) CleanCnt:3 Mode:S Flags: 0x0
2008-12-05 07:48:28.19 spid4s       Grant List 1:
2008-12-05 07:48:28.19 spid4s         Owner:0x000000011063CDC0 Mode: S        Flg:0x0 Ref:1 Life:00000000 SPID:79 ECID:0 XactLockInfo: 0x00000000808F1AB8
2008-12-05 07:48:28.19 spid4s         SPID: 79 ECID: 0 Statement Type: INSERT Line #: 220
2008-12-05 07:48:28.19 spid4s         Input Buf: RPC Event: Proc [Database Id = 10 Object Id = 1751794144]
2008-12-05 07:48:28.19 spid4s       Requested By:
2008-12-05 07:48:28.19 spid4s         ResType:LockOwner Stype:'OR'Xdes:0x00000000813B8700 Mode: X SPID:77 BatchID:0 ECID:0 TaskProxy:(0x00000000CE6D8598) Value:0x1043f980 Cost:(0/1544)
2008-12-05 07:48:28.19 spid4s
2008-12-05 07:48:28.19 spid4s      Node:2

2008-12-05 07:48:28.19 spid4s      KEY: 10:72057594038910976 (0c0092f62b82) CleanCnt:2 Mode:X Flags: 0x0
2008-12-05 07:48:28.19 spid4s       Grant List 0:
2008-12-05 07:48:28.19 spid4s         Owner:0x000000011043F300 Mode: X        Flg:0x0 Ref:0 Life:02000000 SPID:77 ECID:0 XactLockInfo: 0x00000000813B8738
2008-12-05 07:48:28.19 spid4s         SPID: 77 ECID: 0 Statement Type: UPDATE Line #: 23
2008-12-05 07:48:28.19 spid4s         Input Buf: RPC Event: Proc [Database Id = 10 Object Id = 1791462302]
2008-12-05 07:48:28.19 spid4s       Requested By:
2008-12-05 07:48:28.19 spid4s         ResType:LockOwner Stype:'OR'Xdes:0x00000000808F1A80 Mode: S SPID:79 BatchID:0 ECID:0 TaskProxy:(0x0000000129E82598) Value:0x1063d000 Cost:(0/0)
2008-12-05 07:48:28.19 spid4s
2008-12-05 07:48:28.19 spid4s      Victim Resource Owner:
2008-12-05 07:48:28.19 spid4s       ResType:LockOwner Stype:'OR'Xdes:0x00000000808F1A80 Mode: S SPID:79 BatchID:0 ECID:0 TaskProxy:(0x0000000129E82598) Value:0x1063d000 Cost:(0/0)
2008-12-05 07:48:28.19 spid4s      End deadlock search 634 ... a deadlock was found.
2008-12-05 07:48:28.19 spid4s      ----------------------------------

A: These IDs actually refer to hobts (Heap Or Binary Tree), found in sys.partitions.  Try the following query inside database 10, and you will find which object and which index is affected.
SELECT hobt_id, object_name(p.[object_id]), index_id
FROM sys.partitions p
WHERE hobt_id = 72057594060734464

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I set Last Modified Date of file after using HandbrakeCLI to convert a file? Running this on OS X Lion.
I'm batch converting several hundred home movies using Handbrake CLI.  I'd like to set the last modified date and created date to that original file.
I'm using the following script:
for f in "$@"; do
  base=${f%.*}
  extension=${f##*.}
  newfile=${base}.m4v
  echo Converting \"$f\" to \"$newfile\"
  /Applications/HandBrakeCLI  -e x264 -b 4000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 --crop 0:0:0:0  -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 -i "$f" -o "$newfile"
done

I execute this script by running:
find . -name "*.avi" -print0 | xargs -0 hbapple.sh

Does anyone have thoughts on how I can set the last modified and creation time of the original file to that of the $newfile?
If I don't figure out how to do this I will have a difficult time knowing when these videos were actually created.
I appreciate any help or pointers

A: The modification date can be set with
touch -m -t 201207010742 whatever.m4v

AFAIK the creation/birth date can't be modified.
To set the modification date based on the creation date of another file you can use stat:
touch -m -t $(stat -f %SB -t %Y%m%d%H%M original-file.mov) new-file-m4v

To apply this to your script, use something like
for f in "$@"
  do
     olddate=$(stat -f %SB -t %Y%m%d%H%M "$f")
     base=${f%.*}
     extension=${f##*.}
     newfile=${base}.m4v
     echo Converting \"$f\" to \"$newfile\"
     /Applications/HandBrakeCLI  -e x264 -b 4000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 --crop 0:0:0:0  -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 -i "$f" -o "$newfile"
     touch -m -t $olddate "$newfile"
  done


text:
Q: How to compute the E(x) given its cdf function? How could I compute the expected value E(x) given that its cdf is,
$F(x) = \dfrac{\exp(x)}{1+\exp(x)}$.
I know the method to derive E(x), as in this post. I still find it very hard to derive the result. Thanks.

A: I prefer to refer to this question.
We have
$$F(x)=\frac{e^x}{e^x+1}\implies  f(x) = \frac{dF(x)}{dx}=\frac{e^x}{\left(e^x+1\right)^2}$$
$$E[X] = \int_{1}^{\infty}  x f(x)\,dx$$
$$I = \int  x f(x)\,dx=\frac{x \,e^x }{e^x+1}-\log \left(e^x+1\right)$$ Just use the bounds.


text:
Q: Add entries together based on key in array PHP As you can see I have a key called dateTime which holds dates. What I need to do is add all the entries together for each date and return the array. So I simply got one dateTime per date with all the entries of that day added together. I do not know the dateTime inputs ahead of time as I have a crawler that constantly inserts data into my database.
How would you go about doing that in the most efficient way? I imagine I would have to do a foreach loop and somehow check if the key value (dateTime) changes from the previous key value. And then create a brand new array that I return
An example of the array is as follows:
array (size=130)

 0 =>
    array (size=2)
      'dateTime' => string '2015-09-01' (length=10)
      'entries' => string '225' (length=3)
  1 =>
    array (size=2)
      'dateTime' => string '2015-09-01' (length=10)
      'entries' => string '218' (length=3)
  2 =>
    array (size=2)
      'dateTime' => string '2015-09-01' (length=10)
      'entries' => string '217' (length=3)
  3 =>
    array (size=2)
      'dateTime' => string '2015-09-01' (length=10)
      'entries' => string '225' (length=3)
  4 =>
    array (size=2)
      'dateTime' => string '2015-09-02' (length=10)
      'entries' => string '231' (length=3)
  5 =>
    array (size=2)
      'dateTime' => string '2015-09-02' (length=10)
      'entries' => string '220' (length=3)
  6 =>
    array (size=2)
      'dateTime' => string '2015-09-03' (length=10)
      'entries' => string '223' (length=3)
  7 =>
    array (size=2)
      'dateTime' => string '2015-09-03' (length=10)
      'entries' => string '237' (length=3)
  8 =>
    array (size=2)
      'dateTime' => string '2015-09-03' (length=10)
      'entries' => string '220' (length=3)

So it returns an array like this
array (size=130)

  0 =>
    array (size=2)
      'dateTime' => string '2015-09-01' (length=10)
      'entries' => string '660' (length=3)
  1 =>
    array (size=2)
      'dateTime' => string '2015-09-02' (length=10)
      'entries' => string '451' (length=3)
  2 =>
    array (size=2)
      'dateTime' => string '2015-09-03' (length=10)
      'entries' => string '680' (length=3)

Edit With the help of you guys, I ended up doing the following to get the right format.
function prepareArrayForGraphDates($array){
$results = [];
$finalResult = [];

foreach ($array as $value) {
    if (!isset($results[$value['dateTime']])) {
        $results[$value['dateTime']] = 0;
    }
    $results[$value['dateTime']] += $value['entries'];
}
$keyNames = array_keys($results);
for ($x = 0; $x < sizeof($results); $x++) {
    $finalResult[$x]['dateTime'] = $keyNames[$x];
   $finalResult[$x]['entries'] = $results[$keyNames[$x]];
}
return $finalResult;
}

A: Use the fact that array keys are unique...
$results = [];
foreach ($array as $value) {
    if (!isset($results[$value['dateTime']])) {
        $results[$value['dateTime']] = 0;
    }
    $results[$value['dateTime']] += $value['entries'];
}

A: You can use an array like a set or a dictionary, using the date as the key.
$data = [
  [
    'datetime'=>'2015-09-02',
    'entries' => 220
  ]
  // ... other entries snipped ...
];

$results = [];
foreach ($data as $date => $entry)
{
      // if the date has already been recorded with an initial value, add to it
      if (array_key_exists($date, $results) {
          $results[$date] += $entry
      } else {
          // the date is new; add it to the results and set its initial value
          $results[$date] = $entry;
      }

}


text:
Q: merge 2 files based on 1,2,3 column matching in 2 files & print specific columns from 2 files. also retain non-pairing rows from both files in output file1
CHR  POS  ID  REF  ALT  D1  D2  D3
3  35863940  rs15689009  T  C,G  NO  NO  YES
11  85123789  rs78018396  G  A,T  NO  YES  YES
9  11234300  rs6512203  G  A,C,T   YES  YES  NO
22  1728499  rs00981837  A  G,T  NO  NO  YES

file2
CHR  POS  ID  REF  ALT  K1  K2
3  35863940  rs15689009  T  C,G  YES  NO
9  11234300  rs6512203  G  A,C,T   YES  NO
11  85123789  rs78018396  G  A,T  YES  YES

Desired output
CHR  POS  ID  REF  ALT  D1  D2  D3 K1  K2
3  35863940  rs15689009  T  C,G  NO  NO  YES  YES  NO
11  85123789  rs78018396  G  A,T  NO  YES  YES  YES  YES
9  11234300  rs6512203  G  A,C,T   YES  YES  NO  YES  NO
22  1728499  rs00981837  A  G,T  NO  NO  YES  -  -  -

I tried
paste file1 file2 | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$14,$15}'

but this doesnt consider order of rows in both files
based on matching values in column 1 , 2, 3 in file1 and file2
column 1st to 8th of file1 and 6th & 7th column of file2 should be in output


text:
Q: Linq many to many query with where clause I have the following problem:
I have some tables "clinic", "doctor", "clinicDoctor" (representing a many to many relatioship), also I have "specialty" and "doctorSpecialty" (representing a many to many relatioship).
I want to make a linq query that find all clinics that have doctors with an especific specialty.
In resume I want to find clinics by specialty id
var clinicLst = (from cli in clinica.Clinic
                                  .Include(x => x.ClinicDoctor) //This is a Collection
                                  .ThenInclude(x => x.IdDoctorNavigation)
                                  .ThenInclude(x => x.DoctorSpecialty) //This is a Collection
                                  .ThenInclude(x => x.IdSpecialtyNavigation)
                                  .Where(cli => (cli.State == true)
                                  && HERE I WANT THE ESPECIALIDAD.ID == ID BUT I DON'T KNOW HOW)
                                  select cli).ToList();

Please any sugestion.
Thanks in advance!!!

A: Your question isn't very clear, but I think you're looking for something like:
var clinicList = await clinica.Clinic.Where(x => x.DoctorSpecialty.Any(s => s.Id == specialtyId)).ToListAsync();

UPDATE
Hence the "your question isn't very clear". Generally, with a many-to-many, especially if you're using EF Core, you'd have set up like:
public class Doctor
{
    ...
    public ICollection<DoctorSpecialty> Specialties { get; set; }
}

public class Specialty
{
    ...
    public ICollection<DoctorSpecialty> Doctors { get; set; }
}

public class DoctorSpecialty
{
    public int DoctorId { get; set; }
    public int SpecialtyId { get; set; }
}

Then, Clinic would have something like:
public ICollection<Doctor> Doctors { get; set; }

Assuming a set up like that, then you'd query via:
context.Clinics.Where(x => x.Doctors.Any(d => d.Specialties.Any(s => s.SpecialtyId == specialtyId)))

A: So every Clinic has zero or more Doctors, and every Doctor works in zero or more Clinics. Apparently you use a framework that implements this many-to-many relation using virtual ICollection, like Entity Framework does.
class Clinic
{
    public int Id {get; set;}  // primary key
    ...                        // other properties

    // every Clinic has zero or more Doctors (many to many):
    public virtual ICollection<Doctor> Doctors {get; set;}
}

Similarly, there is a many to many relationship between Doctors and Specialties:
class Doctor
{
    public int Id {get; set;}  // primary key
    ...                        // other properties

    // every Doctor works in zero or more Clinics (many-to-many):
    public virtual ICollection<Clinic> Clinics {get; set;}

    // every Doctor has zero or more Specialties
    public virtual ICollection<Specialty> Specialties {get; set;}
}

For completeness the Specialty:
class Specialty
{
    public int Id {get; set;}  // primary key
    public string Description {get; set;}
    ...                        // other properties

    // every Specialty belongs to zero or more Doctors (many to many):
    public virtual ICollection<Doctor> Doctors {get; set;}
}

I want to make a linq query that find all clinics that have doctors with an especific specialty.

int specialtyId = ...
var clinicsWithSpecialty = myDbContext.Clinics

    // keep only those Clinics that have at least one Doctor with the desired specialty
    .Where(clinic => clinic.Doctors
        .Where(doctor => doctor.Specialties.Select(specialty => specialty.Id == specialtyId)
        .Any())
    .Select(clinic => new
    {
        // Select the clinic properties you want:
        Id = clinic.Id,
        Name = clinic.Name,
        ...

        // Select the Doctors you want:
        Doctors = clinic.Doctorw.Where(doctor => ...)
            .Select(doctor => new
            {
                // Select the Doctor properties that you want
                Id = doctor.Id,
                ...

                Specialties = doctor.Specialties
                    .Where(specialty => ...)
                    .Select(specialty => new
                    {
                        // Select the specialties that you want
                        ...
                    })
                    .ToList(),
             })
             .ToList(),
     });

For efficiency reasons, don't select any properties that you don't plan to use, especially the foreign keys to your junction tables. If Clinic [10] has 300 Doctors, then every Doctor will have the same value for the foreign key to the junction table. It would be a waste to transfer this value 300 times if you are not using it.

When fetching data, only use Include if you plan to change the fetched data. If you only need to query it, use Select.


text:
Q: select all columns from both tables postgresql function i have a simple sql join query
SELECT a.*,b.*
FROM Orders a
JOIN Customers b ON a.CustomerID=b.CustomerID

which selects all columns from both tables . I need to achieve the same in
Postgresql function,but i am not able to select data from 2nd table
CREATE  FUNCTION get_data (p_pattern VARCHAR,p_year INT)
 RETURNS TABLE (
orders.*,Customers.*
)
AS $$

A: The one problem is that neither function nor views can return the columns with same names (in your example columns CustomerID presented in both tables). And the another one - syntax:

RETURNS TABLE ( column_name column_type [, ...] )

from the official doc, nothing about table_name.*.
Aside of the obvious solution where you specifying the complete list of columns, there is one trick with composite (row, record) types:
CREATE  FUNCTION get_data (p_pattern VARCHAR,p_year INT)
  RETURNS TABLE (order orders, customer customers)
AS $$

Note that you can use table/view names as types in declarations.
And in that case your query could looks like
SELECT a, b
FROM Orders a
JOIN Customers b ON a.CustomerID=b.CustomerID

After that the usage of the function would be:
select
  *, -- two composite columns
  (order).*, -- all columns from table orders
  (customer).*, -- all columns from table customers
  (order).CustomerID -- specific column from specific table
from
  get_data(<parameters here>);

dbfiddle

A: Considering the columns are present on which you are joining, you can do this:
    SELECT * FROM Orders a,Customers b WHERE a.CustomerID=b.CustomerID;

For more see the official docs: https://www.postgresql.org/docs/8.2/static/tutorial-join.html
You can also refer this: https://www.tutorialspoint.com/postgresql/postgresql_using_joins.htm
.It has good examples and references what joins are there in postgre and how to do them.


text:
Q: Generate a UTF-8-pdf from a PHP website
I'm trying to code a website in CakePHP where people fill in their details to apply for our university.
This is in Germany, and we have a lot of applicants, so we have names with Czech accents, German umlauts, etc.
They enter their data in a form which gets saved in a database (also in UTF-8). The site should also generate a .pdf with their name, address etc. I tried using FPDF and the unicode extension UFPDF, but somehow still fail.
Now I'm wondering if I can somehow generate a LaTeX-document and just automatically enter the user's data and compile & return it to the user. LaTeX always worked fine for me with UTF-8.
Oh, I forgot: I don't want to use TCPDF (which apparently supports UTF-8), because it already took 20secs for a Hello-World-document; I'm scared it would strangle the server when 300 students apply at the same time.
If anyone could help me, I would be very thankful.

A: You could do it the LaTeX way, calling exec from PHP and creating the document.
Or you can use TCPDF which is build on FPDF but it has more functionality build in it, and it supports UTF-8.
Hm 20sec for a simple document seems very very long, I've created larger documents with many pictures (20+ pages with 3 images each page) with TCPDF and it's usually very fast, far from 20 sec even for documents of that size.

A: Did you ever try PDFLIB?
The company is located in your country, the product is really very professional. When we used it for a project we never had any problems with unicode support.
(I assume the direct PDF generation this way is way faster and less error-prone than executing tex).


text:
Q: Snowflake ODBC Query Of MS Access Linked Tables I have a business user I am migrating to Snowflake that has many MS Access reporting processes that use MS Access Linked Tables that he is attempting to redirect to Snowflake through an ODBC connection. If his ODBC connection specifies a Database, he can see contents of the linked table.  If he tries to link a table in a different Database, MS Access can find the table in list of objects but cannot open it.  It is like the process to find the table is using the full data dictionary but when you try to link it, it forms a query that lacks the database qualifier.
We have tried most all qualification of including or omitting entries out of the ODBC connection properties including the database. We can think of two work-arounds but neither are ideal because there is a large user community and the reporting is complex and vast.  The two backup options are to create a separate driver for each database or to create views in Snowflake under the same database that can be accessed.
Has anybody else encountered this issue and know a better solution?  Is it the version of the ODBC driver for Snowflake (which I assume is the most current because the user followed a canned set of download directions created by our IT department).


text:
Q: Struggling to get buildozer to work (xubuntu), python 3.8, seems like it miss some dependencies but im not sure well I smh killed by virtual box and I don't remember how I got my first one to work, I installed kivi and buildozer based on kivy.org docs. It dies in the middle of building though, no matter what I try to compile logs are always the same.
[INFO]:    -> running make -j 1 -C /home/herbal/Desk...(and 119 more)
           working: make: Leaving directory '/home/herbal/Des...(and 121 more) Exception in thread background thread for pid 14999:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 1662, in wrap
    fn(*args, **kwargs)
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 2606, in background_thread
    handle_exit_code(exit_code)
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 2304, in fn
    return self.command.handle_command_exit_code(exit_code)
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 877, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_2:

  RAN: /usr/bin/make -j 1 -C /home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build

  STDOUT:
make: Entering directory '/home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build'
make: *** No rule to make target '/home/herbal/Desktop/snake/Makefile.pre.in', needed by 'Makefile.pre'.  Stop.
make: Leaving directory '/home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build'

  STDERR:

Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1260, in <module>
    main()
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
    ToolchainCL()
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 709, in __init__
    getattr(self, command)(args)
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 154, in wrapper_func
    build_dist_from_args(ctx, dist, args)
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 213, in build_dist_from_args
    build_recipes(build_order, python_modules, ctx,
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 577, in build_recipes
    recipe.build_arch(arch)
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/recipes/hostpython3/__init__.py", line 116, in build_arch
    shprint(sh.make, '-j', str(cpu_count()), '-C', build_dir)
  File "/home/herbal/Desktop/snake/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 167, in shprint
    for line in output:
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 925, in next
    self.wait()
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 849, in wait
    self.handle_command_exit_code(exit_code)
  File "/home/herbal/.local/lib/python3.8/site-packages/sh.py", line 877, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_2:

  RAN: /usr/bin/make -j 1 -C /home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build

  STDOUT:
make: Entering directory '/home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build'
make: *** No rule to make target '/home/herbal/Desktop/snake/Makefile.pre.in', needed by 'Makefile.pre'.  Stop.
make: Leaving directory '/home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build'

  STDERR:

# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=conganew --bootstrap=sdl2 --requirements=python3,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/herbal/Desktop/snake/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21
# ENVIRONMENT:
#     SHELL = '/bin/bash'
#     SESSION_MANAGER = 'local/herbal-VirtualBox:@/tmp/.ICE-unix/731,unix/herbal-VirtualBox:/tmp/.ICE-unix/731'
#     WINDOWID = '60817411'
#     QT_ACCESSIBILITY = '1'
#     COLORTERM = 'truecolor'
#     XDG_CONFIG_DIRS = '/etc/xdg/xdg-xubuntu:/etc/xdg:/etc/xdg'
#     XDG_SESSION_PATH = '/org/freedesktop/DisplayManager/Session0'
#     XDG_MENU_PREFIX = 'xfce-'
#     CLUTTER_BACKEND = 'x11'
#     LANGUAGE = 'en_US'
#     LC_ADDRESS = 'pl_PL.UTF-8'
#     LC_NAME = 'pl_PL.UTF-8'
#     SSH_AUTH_SOCK = '/run/user/1000/keyring/ssh'
#     DESKTOP_SESSION = 'xubuntu'
#     LC_MONETARY = 'pl_PL.UTF-8'
#     SSH_AGENT_PID = '816'
#     XDG_SEAT = 'seat0'
#     PWD = '/home/herbal/Desktop/snake#2'
#     LOGNAME = 'herbal'
#     XDG_SESSION_DESKTOP = 'xubuntu'
#     QT_QPA_PLATFORMTHEME = 'gtk2'
#     XDG_SESSION_TYPE = 'x11'
#     GPG_AGENT_INFO = '/run/user/1000/gnupg/S.gpg-agent:0:1'
#     XAUTHORITY = '/home/herbal/.Xauthority'
#     XDG_GREETER_DATA_DIR = '/var/lib/lightdm-data/herbal'
#     GDM_LANG = 'en_US'
#     HOME = '/home/herbal'
#     LC_PAPER = 'pl_PL.UTF-8'
#     LANG = 'en_US.UTF-8'
#     LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:'
#     XDG_CURRENT_DESKTOP = 'XFCE'
#     VTE_VERSION = '6001'
#     XDG_SEAT_PATH = '/org/freedesktop/DisplayManager/Seat0'
#     LESSCLOSE = '/usr/bin/lesspipe %s %s'
#     XDG_SESSION_CLASS = 'user'
#     TERM = 'xterm-256color'
#     LC_IDENTIFICATION = 'pl_PL.UTF-8'
#     GTK_OVERLAY_SCROLLING = '0'
#     LESSOPEN = '| /usr/bin/lesspipe %s'
#     USER = 'herbal'
#     DISPLAY = ':0.0'
#     SHLVL = '1'
#     LC_TELEPHONE = 'pl_PL.UTF-8'
#     LC_MEASUREMENT = 'pl_PL.UTF-8'
#     XDG_VTNR = '7'
#     XDG_SESSION_ID = 'c1'
#     XDG_RUNTIME_DIR = '/run/user/1000'
#     LC_TIME = 'pl_PL.UTF-8'
#     XDG_DATA_DIRS = '/usr/share/xubuntu:/usr/share/xfce4:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/usr/share'
#     PATH = '/home/herbal/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/herbal/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
#     GDMSESSION = 'xubuntu'
#     DBUS_SESSION_BUS_ADDRESS = 'unix:path=/run/user/1000/bus'
#     LC_NUMERIC = 'pl_PL.UTF-8'
#     _ = '/home/herbal/.local/bin/buildozer'
#     PACKAGES_PATH = '/home/herbal/.buildozer/android/packages'
#     ANDROIDSDK = '/home/herbal/.buildozer/android/platform/android-sdk'
#     ANDROIDNDK = '/home/herbal/.buildozer/android/platform/android-ndk-r19c'
#     ANDROIDAPI = '27'
#     ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2

here is the log
I tried both installing from GitHub and via pip, I also tried compiling simpler scripts, I also certain I got it to work before my virtual box died with same exact script.

A: Here are the requirements:
python3,
kivy==2.0.0rc3,
https://github.com/kivymd/KivyMD/archive/master.zip,
sdl2_ttf==2.0.15


text:
Q: Remove all but one occurance of word in a string in python i have a string for example "Free Visual Studio developer offers offers offers offers with everything you need to create apps"
what i want to do is "offers" is occuring 4 times sequentially; i want to keep "offers" just once and remove all the other occurances.
This is just an example string,i have a dataset where such cases are there of same words occuring sequentially more than once,
Please help me a way to remove other such words and keep one word and generate a resulting string

A: You can use regular expressions to find repeating words and remove the extra ones:
>>> import re
>>> s = 'Free Visual Studio developer offers offers offers offers with everything you need to create apps'
>>> re.sub(r'\b(\w+\s)(\1+)', '\\1', s)
'Free Visual Studio developer offers with everything you need to create apps'


text:
Q: Swallowing exception thrown in catch/finally block Usually I come across situations where I have to swallow an exception thrown by the clean up code in the catch/finally block to prevent the original exception being swallowed.
For example:
// Closing a file in Java
public void example1() throws IOException {
    boolean exceptionThrown = false;
    FileWriter out = new FileWriter("test.txt");
    try {
        out.write("example");
    } catch (IOException ex) {
        exceptionThrown = true;
        throw ex;
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            if (!exceptionThrown) throw ex;
            // Else, swallow the exception thrown by the close() method
            // to prevent the original being swallowed.
        }
    }
}

// Rolling back a transaction in .Net
public void example2() {
    using (SqlConnection connection = new SqlConnection(this.connectionString)) {
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction = command.BeginTransaction();
        try {
            // Execute some database statements.
            transaction.Commit();
        } catch {
            try {
                transaction.Rollback();
            } catch {
                // Swallow the exception thrown by the Rollback() method
                // to prevent the original being swallowed.
            }
            throw;
        }
    }
}

Let's assumed that logging any of the exceptions is not an option in the scope of method block, but will be done by the code calling the example1() and example2() methods.
Is swallowing the exceptions thrown by close() and Rollback() methods a good idea? If not, what is a better way of handling the above situations so that the exceptions are not swallowed?

A: You can create a custom Exception type that can hold both exceptions. If you overload the ToString(), you can log both exceptions.
try
{
    transaction.Commit();
}
catch(Exception initialException)
{
    try
    {
        transaction.Rollback();
    }
    catch(Exception rollbackException)
    {
        throw new RollbackException(initialException, rollbackException);
    }

    throw;
}

A: That's exactly why Commons IO has an IOUtils.closeQuietly method.  In most cases what goes wrong during the closing of a file is not that interesting.
Database transactions that have to be rolled back are potentially more interesting, as in that case the function didn't do what it was supposed to do (put stuff in the DB).

A: I'm not a fan of catching and rethrowing an exception.
If you catch it, do something with it - even if it's just logging the exception.
If you can't do anything with it, don't catch it - add a throws clause to the method signature.
Catching an exception tells me that either you can deal with an exceptional situation and have a recovery plan or "the buck stops here" because an exception cannot propagate in that form any farther (e.g., no stack traces back to the user).

A: There's no reason to rollback the transaction in the C# code.  If you close the connection wihtout rolling back the transaction (or committing it) that is equivalent and more efficient...
public void example2() {
  using (SqlConnection connection = new SqlConnection(this.connectionString))
  using (SqlCommand command = connection.CreateCommand())
  using (SqlTransaction transaction = command.BeginTransaction()) {
    // Execute some database statements.
    transaction.Commit();
  }
}

and you are done.
The using statement will ensure (via finally) that the connection is closed regardless of any exceptions and let the raw exception bubble out (with the full/correct stack trace).  If an exception occurs before the call to Commit, the transaction will never commit and will be automatically rolled back when the transaction/connection closes.

A: I believe that an exception should be something you don't expect. If you expect an exception then you should do something with it. So in your first example I think you should probably not bother catching the IOException if you are also stating that your method is going to throw IOException.

A: I would consider rewriting example1 as follows:
// Closing a file in Java
public void example1() throws IOException {
    boolean success = false;
    FileWriter out = new FileWriter("test.txt");
    try {
        out.write("example");
        success = true;
        out.close();
    } finally {
        if (!success) {
            try {
                out.close();
            } catch (IOException ex) {
                // log and swallow.
            }
        }
    }
}

Moving the success = true; to after the out.close(); statement would make the meaning of success a bit clearer ... though it may result in out.close() being called twice.

A: Without knowing all of what your particular circumstance is, you could look into throwing a new exception.  In C#, at least, when throwing a new exception you one of the optional constructors accepts an existing exception as a parameter.  For example:
throw new Exception("This is my new exception.", ex);

The purpose of this is to retain the original exception.
Another option might be the try .. catch .. finally construct.
try {
    // normal code that might throw an exception
  } catch (Exception ex) {
    // handle that first exception
  } finally {
    // handle any cleanup regardless of exception being thrown
  }
In general if my code can handle an exception in a particular try .. catch then I don't re-throw that exception.  If it is important for something further up the call stack to have that exception I will throw a new exception and set the original exception as the inner exception.

A: usually, risky codes are put all in one try-catch block. nested try-catch blocks are not a very good idea, IMO (or just try to avoid nested try-catch blocks as much as possible, unless you really need them).
because the risky codes are exceptional scenario, so putting exceptional codes for exceptional case for even more exceptional case, that's alot of unnecessary work.
for example in example1(), place all risky codes in one try-catch block:
try{
FileWriter out = new FileWriter("test.txt");
out.write("example");
out.close();
} catch(Exception e) {
    //handle exception
}

OR, another good idea is to place several catch(s) for the same try:
try{
    FileWriter out = new FileWriter("test.txt");
    out.write("example");
    out.close();
} catch(FileNotFoundException e) {
        //if IOException, do this..
} catch(IOException e) {
        //if FileNotFound, do this..
} catch(Exception e) {
        //completely general exception, do this..
}


text:
Q: put SELECT COUNT(*) statement result into int variable I have a SELECT COUNT(*) statement in C#/ASP.NET and I want to store the result as an int to use as an IF condition. However I am getting an error in visual studio:

Error:System.Data.SqlClient.SqlException (0x80131904): The data types text and varchar are incompatible in the equal to operator. at System.Data.SqlClient.SqlConnection.

It tells me its occurring at the int temp line. The columns I'm accessing in the database table are of text type.
conn.Open();
String checkEmail = "select count(*) from Players where PlayerEmail= '" + txtEmailLogIn.Text + "'";
SqlCommand com = new SqlCommand(checkEmail, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{

}

A: The problem is in your SQL. You can't use = when comparing TEXT data types, instead you can use LIKE:
String checkEmail = "select count(*) from Players where PlayerEmail LIKE '" + txtEmailLogIn.Text + "'";

Be warned though, that you are opening yourself up to SQL injection attacks when composing SQL strings like this.

A: DavidG's answer above works. However, if you have the opportunity to change the database schema, you could also fix the error by changing the PlayerEmail column from text to varchar(max). The text data type has been deprecated since at least 2005.


text:
Q: Rails: What do model associations tangibly do? I have the following models setup:
clinics
has_many :occupations, through: :clinic_occupations
has_many :clinic_occupations

occupations
has_many :clinic_occupations

clinic_occupations
belongs_to :occupations
belongs_to :clinics

I think the has_many :clinic_occupations in clinics is probably unnecessary, but it's what we have right now so I wanted to include it.  I am trying to only call occupations that have been associated with a clinic, or occupations that have no clinic id at all.  What is the correct way to do this, and what are these model associations tangibly doing?

A:
I think the has_many :clinic_occupations in clinics is probably unnecessary

Nope, it is. In order for any has_many _, through: _ to work, you need to supply another association. That's exactly what through stands for, "an association through an association". Under the hood, this uses JOIN-clauses for "lower" asssociated objects with "higher" ones . Since Rails 3 these can even be nested, producing a JOIN-clause through multiple tables at once.
What it does is create a bunch of methods for your model (reference) with some caching underneath.
Why should you define that association explicitly? Because:

*

*It's safer. Association name may not follow Rails convention and thus no assumptions can be made just with its name. Let's face it, sometimes this happens. More on that below.

*It offers all the features has_many associations have in general. Association may contain details that do not violate conventions (like conditions).

*It's more flexible. This way you can define multiple associations that point to the same class. It's impossible to follow conventions in this case, since one name can only point to one method.

*It's clearer when looking at the model why a single method call queries multiple tables at once.

In fact, you may want to access the join model (ClinicOccupation) directly when speeding up certain queries. There are cases when you already know the needed object's id and want to use it in a query without fetching the entire object first with an extra query.


text:
Q: How to do real time mobile opt-in in marketing cloud integrated with sales cloud? We're capturing User information through web based form and the same is integrated with sales cloud which automatically creates a lead based on information provided. We've marketing cloud integrated only with sales cloud.
Now, I want to send a confirmation sms to user in real time as soon as a lead is created, and for that I need to do mobile opt-in in real time in marketing cloud.
Journey I'm planning for this would be a trigger base journey, i.e. as soon as a new lead is created, that lead contact would enter into the journey. Existing journey builder doesn't provide any option to trigger a mobile opt-in or data import activity into mobile contact list.

*

*How to do real time opt-in in marketing cloud ?

*Can I also do it in sales cloud ? Is there any option available where I can do mobile opt-in in sales cloud and marketing cloud then automatically adds into mobile contact list.

A: There is no configuration between Sales Cloud and Marketing Cloud when it comes to MobileConnect Keyword subscriptions or Status settings.
That being said, Journey Builder does actually allow you to subscribe a Contact to a new MobileConnect keyword and send immediately an SMS to the Contact.
Assuming you have MobileConnect properly set up with your numbers and keywords and have the permission to Contact the client, all you really need to do is create the Journey based on Salesforce Data and configure an SMS event in this Journey.
While configuring the SMS event you select the option Subscribe all Contacts to a Keyword and pick the MobileConnect keyword they will be subscribed to.
Once a Contact in the Journey reaches this step, they will be created in MobileConnect with Active status and have a Opt-In status for the selected Keyword.

*

*Configure Journey Builder for Sending Messages


text:
Q: Getting error making calls with twilio python api Getting this error when I try to make a call with the twilio python api:
Jacob-Mac-mini:downloads kovyjacob$ python3 twilio_call.py
Traceback (most recent call last):
  File "/Users/kovyjacob/Downloads/twilio_call.py", line 11, in <module>
    call = client.calls.create(
  File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/rest/api/v2010/account/call/__init__.py", line 141, in create
    payload = self._version.create(method='POST', uri=self._uri, data=data, )
  File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/base/version.py", line 205, in create
    raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:

POST /Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json

Twilio returned the following information:

Unable to create record: The requested resource /2010-04-01/Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json was not found

More information may be available here:

https://www.twilio.com/docs/errors/20404

I checked the link, but a) I'm not sure what the problem is exactly, and b) it doesn't say how to fix it.
This is the code:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ['AC766eaf7ef8d79de658756223cee446df']
auth_token = ['74ef4743a7a9a748cxxxxxxxxxxxxxxx']
client = Client(account_sid, auth_token)

call = client.calls.create(
                        twiml='<Response><Say>Ahoy, World!</Say></Response>',
                        to='+14372341004',
                        from_='+14243560675'
                    )

print(call.sid)

A: account_sid and auth_token should be passed as strings, not array with string inside.
Twillio Rest Client Source Code
Edit your code to:
account_sid = 'AC766eaf7ef8d79de658756223cee446df'
auth_token = '74ef4743a7a9a748cxxxxxxxxxxxxxxx'


text:
Q: Routing to a specific view based upon a JSON return value in React using React Router Let's say you have a JSON payload returning to a react application from an initial call after authentication to find out what "type" of role the user has and based upon this, they get routed to a specific view in React.  So from JSON I will receive something like this:
{ "is_admin": true }
In React Router, is there a way to test this value and then render the appropriate view? Basically looking at the JSON value and if they are an admin one collection of components are rendered,  if they not an admin, a different collection is rendered.

A: You want to use the router to send admin users to a specific url http://mysite/admin while other users go to http://mysite/user
In order to leverage the react-router , the best you can do here is use the <Redirect /> component with something like that :
{ is_admin ? <Redirect to='/admin' /> : <Redirect to='/user' /> }


text:
Q: How can I use pandas to parse CSV already loaded from somewhere else? I download and scrape a webpage for some data in TSV format. Around the TSV data is HTML that I don't want.
I download the html for the webpage, and scrape out the data I want, using beautifulsoup.
However, I've now got the TSV data in memory.
How can I use this TSV data in memory with pandas? Every method I can find seems to want to read from file or URI rather than from data I've already scraped in.
I don't want to download text, write it to file, and then rescrape it.
#!/usr/bin/env python2

from pandas import pandas as p
from BeautifulSoup import BeautifulSoup
import urllib2

def main():
    url = "URL"
    html = urllib2.urlopen(url)
    soup = BeautifulSoup(html)
    # pre is the tag that the data is within
    tab_sepd_vals = soup.pre.string

    data = p.LOAD_CSV(tab_sepd_vals)
    process(data)

A: If you feed the text/string version of the data into a StringIO.StringIO (or io.StringIO in Python 3.X), you can pass that object to the pandas parser. So your code becomes:
#!/usr/bin/env python2

import pandas as p
from BeautifulSoup import BeautifulSoup
import urllib2
import StringIO

def main():
    url = "URL"
    html = urllib2.urlopen(url)
    soup = BeautifulSoup(html)
    # pre is the tag that the data is within
    tab_sepd_vals = soup.pre.string

    # make the StringIO object
    tsv = StringIO.StringIO(tab_sepd_vals)

    # something like this
    data = p.read_csv(tsv, sep='\t')

    # then what you had
    process(data)

A: Methods like read_csv do two things, they parse the CSV and they construct a DataFrame object - so in your case you might want to construct the DataFrame directly:
>>> import pandas as pd
>>> df = pd.DataFrame([['a', 1], ['b', 2], ['c', 3]])
>>> print(df)
   0  1
0  a  1
1  b  2
2  c  3

The constructor accepts a variety of data structures.


text:
Q: Xcode Crash Error iOS devices are crashing when attempting to retrieve certain datasets.
Xcode log reads:
Warning>: Application 'EventsDev' exited abnormally with signal 6: Abort trap: 6.

What is Abort trap: 6 related to?

A: To see where it crashed, create a new exception breakpoint, and set to 'all exceptions'.


text: Q: Linearly independent linear functionals Let  $ f_1,\ldots,f_n$ be linearly independent linear functionals on a vector space $X$. Show that there are $n$ elements  $x_1,\ldots,x_n$ in $X$ such that the $n\times n$ matrix $[f_i(x_j) ]$ is non-singular.


text:
Q: rails 4 updating object invoke the creation of a related model same action In my crm app there is opportunity model and comment model (polymorphic that can belong to opportunity).
I have status_edit and status_update actions which has a form to change opportunity status.
i would like that action to invoke the creation of a new comment. (there is other ways to create comments that already works well). the opportunity is been updated but new associated comment isn't.
 def status_update
   @opportunity.update(opportunity_params)
   if @opportunity.save
     @comment = @opportunity.comments.new(name: "Status was changed to #{@opportunity.status}", description: "#{@opportunity.status_reason}")
     @comment.save!
     redirect_to opportunity_path(@opportunity)
     ...
 end

server log :
  SQL (1.5ms)  UPDATE "crm_opportunities" SET "status" = ?, "updated_at" = ? WHERE "crm_opportunities"."id" = ?  [["status", 3], ["updated_

at", "2020-02-23 07:07:33.936820"], ["id", 26]]
   (16.6ms)  commit transaction
   (0.2ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/crm_opportunities/26
Completed 302 Found in 45ms (ActiveRecord: 19.4ms)

routes:
  resources :opportunities do
    resources :comments
    member do
      get :status_edit
      patch :status_update
    end
  end

Thank you all!

A: since comments is belongs to Opportunity, you can use build to create new record for comments
below is sample for the creation of comment
 @comment = @opportunity.comments.build(name: "Status was changed to #{@opportunity.status}", description: "#{@opportunity.status_reason}")
 @comment.save

if the above method still fail please check also validation that you set in comment model


text:
Q: Better fit w/ Polyfit I'm trying to fit some data but with the polynomial i can't find a good solution. So, how can I draw a curve like the black one (knowing the type of the curve)?

figure('Units', 'pixels', 'Position', [100 100 500 375]);
hold on;

ydata_s = [1.0e-03 0.5804 0.3916 0.2234 0.1527 0.0697 0];
ydata_m = [0.2765 0.2760 0.2758 0.2757 0.2755 0.2754];
xdata_m = [1 2.5 5 10 50 100];

% Fit with a line.
coeffs = polyfit(xdata_m, ydata_m, 2)
% Define the range where we want the line
xFitting = (0:1:100);
yFitted = polyval(coeffs, xFitting);

hFit = line(xFitting, yFitted);
hE   = errorbar(xdata_m, ydata_m, ydata_s);

set(hFit                          , ...
  'Color'           , [0 .2 .6]    );
set(hE                            , ...
  'LineStyle'       , 'none'      , ...
  'Marker'          , '.'         , ...
  'Color'           , [.8 .3 .3]  );

hTitle  = title ('Precisione / Velocità');
hXLabel = xlabel('Campionamnto [%]');
hYLabel = ylabel('Funzione Obiettivo [€/P]');

xlim([0 100]);

hLegend = legend( ...
  [hE, hFit], ...
  'Data (\mu \pm \sigma)' , ...
  'Fit (\it{x^3})'      , ...
  'location', 'NorthEast' );

set(gca,'XTick',[1 2.5 5 10 50 100]);

A: This is relativity easy if you have the curve fitting toolbox
x = [1 2.5 5 10 50 100];
y = [0.2765 0.2760 0.2758 0.2757 0.2755 0.2754];
plot(x, y, '*');
hold('on');
plot(fit(x', y', 'exp2'));
legend({'Data', 'Fit'})

A two term exponential fit has an r^2 of 0.96


text:
Q: Change user with "su" locally without password for specific user i have a Server with 4 users: a, b, c, admin
I have the plan to enable user a and b to change
to user admin with the command su (without sudo! [Because screen program]) without a password promt.
I had read something about the /etc/sudoers file but nothing which match really with my Problem.
With regards, Tim
Solved :: Bad Idea
Don't create an Account without an password.
It can enable workarounds for users ...

A: You cannot do this with su. It requires a password, and it should. There is likely another approach you need to take if sudo is not an option. Otherwise they could always sudo -c 'su - admin' sort of thing.


text:
Q: Gravity Forms non-empty Total field values not submitted I have created a gravity form and used several Total fields. Although I do not have any Product fields in my form, which the Total field is usually used to display the total of product prices, I used the Total field because I like the way it automatically formats prices and I am setting the values of the Total fields in my form via my own jQuery code. My code updates both the text in the Total field span element and the associated hidden input element.
However, despite these values displaying in the Total fields on the form, when the form is submitted the Total fields' values are not displaying in the form entries or email notifications.
I know my use of the Total field is not strictly in keeping with the intended usage, but I do not know why the field values are missing from the submission entries. Any ideas why and if there is a way to get around the problem?

A: As @richardW8k pointed out, Total field values are recalculated on submission and will override anything submitted from the frontend.
If your custom jQuery code can be replaced by a formula in the Number field, that'd definitely the way to go. If your jQuery code is doing some more complex logic a calculated Number field will have the same issue as the total field. The submitted value will be overridden by the calculated value on submission.
Here's a solution that allows you to use your custom jQuery code to update the value of a read-only Number field styled to look like the Total field.

*

*Add a Number field to your form.

*Mark the field as read-only. There are two ways to do this.
The Easy Way
GF Read Only provides the ability to mark fields as readonly right from the field settings.
The Hard Way
This snippet from Gravity Forms can do the job.
// update '1' to the ID of your form
add_filter( 'gform_pre_render_1', 'add_readonly_script' );
function add_readonly_script( $form ) {
    ?>

    <script type="text/javascript">
        jQuery(document).ready(function(){
            /* apply only to a input with a class of gf_readonly */
            jQuery("li.gf_readonly input").attr("readonly","readonly");
        });
    </script>

    <?php
    return $form;
}

*Target this Number field with your jQuery code to update the price.

*Use our styles to style your Number field like a total field by adding a "gf_total" class to the field's CSS Class Name setting.
/**
 * Gravity Wiz // Gravity Forms // Style Number Fields like Total Field
 *
 * Use "gf_price" and "gf_total" CSS classes via the "CSS Class Name" setting to style your Number fields like a product
 * price (red) or total (green).
 */
.gform_wrapper .gf_price input[type=text],
.gform_wrapper .gf_price input[type=number] {
    border: 0;
    font-size: 1.2em;
    color: #060;
    text-indent: 0;
    padding: 0;
}
.gform_wrapper .gf_total input[type=text],
.gform_wrapper .gf_total input[type=number] {
    color: #060;
}


text:
Q: Firestore basic question: How to avoid N+1 requests on join I would like to know how I could structure my database in order to avoid doing N requests for all the joins I want to do.
Firebase gets quite expensive when you do a lot of requests.
Let's say I have a todo app, 400 todo to display for my whole company.
I want to display them on the home page, and each todo is assigned to a user.
I have two collections:
- Todos
--> id
--> ...
--> user_id

- Users
--> id

Each time a users displays the home page, I will have 401 requests sent to just get the user name assigned to each todo.
A solution could be to keep the username inside each todo, but I would have to updates all todos each time a user is updated.
What is the best solution to minimize the number of requests, knowing I can't load all the users and todo (the database is too big)?

A: An IN/OR logical operator is on the Firestore team's radar, but I don't think it's possible today.
I think Doug's comment is correct, and it can be restated like this: You'll probably have to choose between fast reads (and store user information in each Todo object, which will slow down writes) or fast writes (and increase the number of requests, slowing down reads).
I suspect that it would be better in the long run to just store the relevant User information (first and last name, username, etc) in each Todo object. Changing your user details is probably going to be a fairly rare occurrence, so it's probably more acceptable to make that a longer process.
You could also offload the function that performs the modification to each of the User's Todo objects to a Cloud Function, so the user doesn't have to wait for the process to complete.


text:
Q: Error writing to table using IBPP I have some problem writing to a firebird database using IBPP. I can make queries from tables without problems using the SELECT statement, but whenever I try to write values using IBPP::Set or IBPP::Execute, I get an error.
This is how I connect to my database:
db = IBPP::DatabaseFactory(settings.ServerName, settings.DbName, settings.UserName, settings.Password,
    "WIN1252", "PAGE_SIZE 8192 DEFAULT CHARACTER SET WIN1252");
db->Connect();
IBPP::Transaction tr = IBPP::TransactionFactory(db);
IBPP::Statement st = IBPP::StatementFactory(db, tr);

Then I wanted to set a specific value:
st->Execute("UPDATE T_GEOMODELL SET Distance= 42.0 WHERE (OBJEKT_ID = 1756056);");

I also tried
st->Prepare("SELECT * FROM T_GEOMODELL WHERE OBJEKT_ID = 1756056");
st->Set(6, "41");
st->Execute();

Here I get the error that "this->mOutRow" is "nullptr".
With the Firebird ISQL tool however, the same command
UPDATE T_GEOMODELL SET Distance= 42.0 WHERE (OBJEKT_ID = 1756056);

works without problems.
I am using Visual C++ 2015 under x64.
Thanks in advance for any help!

A: Okay, I found the error - I had to start and commit the transaction using tr->Start(); and tr->Commit();
tr->Start();
st->Execute("UPDATE T_GEOMODELL SET Distance= 42.0 WHERE (OBJEKT_ID = 1756056);");
tr->Commit();


text:
Q: Bootpag stopped working My page was working until recently. No changes have been made to it.
The bootpag won't load now.
When I load the page I get this error in chrome-console:
dashboard.php?dashboard:31 Uncaught TypeError: $(...).bootpag is not a function
    at HTMLDocument.<anonymous> (https://sslhost:8890/user/dashboard.php?dashboard:31:23)
    at j (https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js:2:27295)
    at Object.fireWith [as resolveWith] (https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js:2:28108)
    at Function.ready (https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js:2:29942)
    at HTMLDocument.J (https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js:2:30308)(anonymous function) @ dashboard.php?dashboard:31j @ jquery.min.js:2fireWith @ jquery.min.js:2ready @ jquery.min.js:2J @ jquery.min.js:2

What should I do?


text:
Q: how to change main background color of media elements audio player (black by default) to something lighter? I am using the MediaElement.js Wordpress plugin and am trying to change the main background color of the audio player (which is black by default) to something lighter so it matches my theme better. I tried replacing "background.png" with my own image, but it didn't work. I am currently only using the player for mp3's, so I'm talking about the 30px tall audio player background color. However, it would be nice to know how to change the color for the video player as well for future reference.

A: In the mediaplayerelement.css (or minimized version) change the background attribute of the .mejs-container tag.  I'm only using this for MP3 files like you, so I don't know if this also works for the video player or if something else needs to be updated.
.mejs-container {
    position: relative;
    background: #000;
    font-family: Helvetica, Arial;
}


text:
Q: AWS Cognito: Get Access_token from url fragment after successful login (Python) After going through countless documentation, articles, and videos, I am still lost on how I ultimately use AWS Cognito access keys in order to verify a user is logged in (after logging in and moving around the website) and ultimately, signing out.
I was able to set up Cognito user pools through which users are able to create accounts, sign in, etc.
After a user signs in, they are redirected to the url:
 https://somedomain.com/callback#id_token=[id_token]&#access_token=[access_token]&#expires=[expires]

I cannot access the access_token using python as it is on the client side and not server side (due to being a url fragment). However, from what I understand, I need this access_token in order to use the cognito API for other calls (sign out, etc). How can I extract this access_token fragment from the url? Am I not supposed to access it from the URL but from another source? I appreciate any guidance or feedback as this is my first time using cognito.


text:
Q: php shell_exec() out put to get a text file I'm trying to run rate -c 192.168.122.0/24 command on my Centos computer and write down the output of that command to the text file using shell_exec('rate -c 192.168.122.0/24') command; still no luck!!

A: If you don't need PHP, you can just run that in the shell :
rate -c 192.168.122.0/24 > file.txt

If you have to run it from PHP :
shell_exec('rate -c 192.168.122.0/24 > file.txt');

The ">" character redirect the output of the command to a file.

A: You can also get the output via PHP, and then save it to a text file
    $output = shell_exec('rate -c 192.168.122.0/24');
    $fh = fopen('output.txt','w');
    fwrite($fh,$output);
    fclose($fh);

A: As you forgot to mention, your command provides a non ending output stream. To read the output in real time, you need to use popen.
Example from PHP's website :
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);

You can read the process output just like a file.

A: $path_to_file = 'path/to/your/file';
$write_command = 'rate -c 192.168.122.0/24 >> '.$path_to_file;
shell_exec($write_command);

hopes this helps. :D
And this will direct you to a good way. https://unix.stackexchange.com/a/127529/41966


text:
Q: Any homeomorphism from $D^2$ to $D^2$ maps $\partial D^2$ onto $\partial D^2$ I'm starting to study Algebraic Topology. After doing some problems and studying the theory I've arrived at:

Let $D^2$ be the unit disk in $R^2$, $\partial D^2$ the topological boundary of $D^2$ (i.e. $S^1$, the unit circle) and $f:D^2\to D^2$ an homeomorphism. Then $f(\partial D^2)=\partial D^2$.

This should be true because $D^2-\partial D^2\approx f(D^2-\partial D^2)$ and since $D^2-\partial D^2$ is path connected, $f(D^2-\partial D^2)$ is path connected as well but if some point in the boundary is mapped to the interior of the disk then it seems that $f(D^2-\partial D^2)$ has two path connected components instead of just one.
This might not be true, and if that's the case provide an example. Also try to keep the answers as elementary as possible, assuming only knowledge of point-set topology. I'm also interested in the same problem but in $D^n$.

A: I'm not sure whether this counts as an elementary proof, but you can do it in this way:
Assume there is a point $x$ on the boundary that is mapped into the interior of $D^2$. Then the restriction of $f$ induces a homeomorphism $D^2 \setminus \{x\} \to D^2 \setminus \{f(x)\}$. But $D^2\setminus \{x\}$ is simply connected, while $D^2\setminus \{f(x)\}$ is not.
The more general case can be found in this thread.


text:
Q: How can i get that value in html from one page to another page I want to check password field value after submiting the form by post method.
How can I get that value in HTML page using javascript
Example:
<form method="post" action="check.html">
  <input type="Password" value="" name="pwd">
  <input type="Submit" value="Submit" name="Submit">
</form>

I want the value of "pwd" in check.html to check the authorisation.

A: you can try this alos
page1.php
<form method="POST" action="page2.php">
    <input type="text" name="field" value="Enter value here" />
</form>

page2.php
<form method="POST">
    <input type="text" name="field" value="<?php echo($_POST['field']) ?>" />
</form>

also you can do this with cookies also but using cookies is not a good option i guess.
another option you can use
file1.html
<Form name="frmDefault" action="file2.html" method="get">

Item1: <Input Type="text" name="txtItem1">

Item2: <Input Type="text" name="txtItem2">

<Input type="submit">

</Form>

file2.html

A:

  <form id='authfrm' method='post'>
   <input type='text' id='nick' />
   <input type='password' id='pwd' />
   <input type='button' onclick='doSubmit();' />
  </form>

but remember, you can't access any values from html page. you need do assign action="check.php" or some other script engine.

A: You cannot get at a posted variable in an html page unless your check.html is not really an html page, but a server processed page with a rewrite rule to hide it is not really html
Some servers will not even allow you to post to html.
To get at the variable in javascript, you will need to GET the page - this will show the password in plain text in the url of the page.
I think you want to completely rethink your approach and password protect the directory where your page is in, and use at least basic authentication to get at it depending on how secret you want it to be. If you just want your aunt to not see your page, then set a cookie in the form and check it in check.html

A: There is an existing post about it
For GET, there is a trick able to do it as below
var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

// display responses
var response = "";
for (var key in $_GET) {
    response += key + ": " + $_GET[key] + ";";
}
alert(response);


text:
Q: How to convert an integer value into floating point in java? I am getting an integer value in my android application.I want to convert it into floating point number which is in this format

"0.xyF"

.I tried lot of methods.I know its simple but i am confused.Please help.
I am passing a value from one activity to another using putExtra.So in the second activity i have to convert it to float for setting the value as verticalMargin for my dialog window.I used this line for getting the value in second activity.
int data = getIntent().getIntExtra("value", 7);

This is used for setting the vertical margin.
wlp.verticalMargin = "the converted floating point number";

A: If i is the integer value, then try:
float f=i;
while(f>=1.0f)
    f/=10.0f;

A: You question still isn't clear. If you're asking how to convert an integer value that represents a percentage from 0 to 100 into a floating point value, then it would be fpVal = intVal / 100.0;

A: In your first activity store your integer value in string like this
String margin = "0."+int_value;

then pass this string to second activity.
In the second activity get that string from extra and convert it to float.
float float_value = Float.parseFloat(margin);

A: If you just want a simple conversion of an integer into a floating point number with the same exact value (e.g. 7 --> 7.0), then you can just cast it: fpVal = (float) intVal;


text:
Q: Xamarin - .aar Java Binding - The name '[method name]' does not exist in the current context I am trying to create binding for Facebook Notification .aar library.
However I am getting compile errors:

Severity  Code    Description Project File    Line    Suppression State
  Error CS0103  The name 'CreateAsset' does not exist in the current
  context   FBNotifications C:\Users\jakub\documents\visual studio
  2015\Projects\FBNotifications\FBNotifications\obj\Release\generated\src\Com.Facebook.Notifications.Internal.Asset.Handlers.BitmapAssetHandler.cs  344 Active
Severity  Code    Description Project File    Line    Suppression State
  Error CS0103  The name 'CreateView' does not exist in the current
  context   FBNotifications C:\Users\jakub\documents\visual studio
  2015\Projects\FBNotifications\FBNotifications\obj\Release\generated\src\Com.Facebook.Notifications.Internal.Asset.Handlers.BitmapAssetHandler.cs  350 Active

The methods that have the problem are following:

// This method is explicitly implemented as a member of an instantiated Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler
        global::Java.Lang.Object global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler.CreateAsset (global::Org.Json.JSONObject p0, global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetCache p1)
        {
            return global::Java.Interop.JavaObjectExtensions.JavaCast<Java.Lang.Object>(CreateAsset (p0, p1));
        }

        // This method is explicitly implemented as a member of an instantiated Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler
        global::Android.Views.View global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler.CreateView (global::Java.Lang.Object p0, global::Android.Content.Context p1)
        {
            return CreateView (global::Java.Interop.JavaObjectExtensions.JavaCast<global::Com.Facebook.Notifications.Internal.Asset.Handlers.BitmapAssetHandler.BitmapAsset>(p0), p1);
        }

I can see that the code issue can be fixed like this:
// This method is explicitly implemented as a member of an instantiated Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler
        global::Java.Lang.Object global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler.CreateAsset (global::Org.Json.JSONObject p0, global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetCache p1)
        {
            return global::Java.Interop.JavaObjectExtensions.JavaCast<Java.Lang.Object>(((AssetManager.IAssetHandler)this).CreateAsset (p0, p1));
        }

    // This method is explicitly implemented as a member of an instantiated Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler
    global::Android.Views.View global::Com.Facebook.Notifications.Internal.Asset.AssetManager.IAssetHandler.CreateView (global::Java.Lang.Object p0, global::Android.Content.Context p1)
    {
        return ((AssetManager.IAssetHandler)this).CreateView (global::Java.Interop.JavaObjectExtensions.JavaCast<global::Com.Facebook.Notifications.Internal.Asset.Handlers.BitmapAssetHandler.BitmapAsset>(p0), p1);
    }

I thought that creating a partial class for BitmapAssetHandler and putting there the corrected method while removing it in Metadata.xml would fix it but it doesn't seem like it.
<remove-node path="/api/package[@name='com.facebook.notifications.internal.asset.handlers']/class[@name='BitmapAssetHandler']/method[@name='CreateAsset']" />
  <remove-node path="/api/package[@name='com.facebook.notifications.internal.asset.handlers']/class[@name='BitmapAssetHandler']/method[@name='CreateView']" />

If I do that then I get error that the methods exist twice (somehow they do not get removed from the generated code). I hope it's not too complex of a problem. Is my approach correct? Or is there something else needed to be done to be able to get it working.

A: remove-node element does the trick.
<remove-node path="/api/package[@name='com.facebook.notifications.internal.asset.handlers']/class[@name='BitmapAssetHandler']" />


text:
Q: Google Cloud SQL - OS environment not set to Google App Engine I am attempting to connected to a Google Cloud SQL instance in python and have gone through google's tutorial: https://cloud.google.com/appengine/docs/python/cloud-sql/
I am essentially cloning google's tutorial code and for some reason this line isn't working right for me:
if (os.getenv('SERVER_SOFTWARE') and
  os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):

This if statement is not being entered and I'm not sure why - it is then defaulting to accessing a local database based on the else statement. How is the os server_software environment set? I'm new to all of this but basically because that is not getting set, I am not able to access my google cloud sql instance. How do I make sure this if statement is entered?

A: SERVER_SOFTWARE is an environment variable that is automatically set by GAE. It could either be something like Google App Engine/x.x.xx when deployed or Development/x.x when running locally.
Basically the section of the code you're referring to checks whether your app is deployed and is running on GAE servers and if so - it will connect to a Google Cloud SQL instance, otherwise, if your app is running locally, it will attempt to connect to a local mysql instance.
It's done that way because you wouldn't normally want to mess with your production (deployed) data while developing & testing locally as many thing could go wrong.
Since you're stating that the if statement is not being entered - it's safe to assume that you are trying to run the program locally but are expecting it to connect to a Google Cloud SQL instance, for that, the next few lines in the example you provided are explaining how to do it:
db = MySQLdb.connect(host='127.0.0.1', port=3306, db='guestbook', user='root', charset='utf8')
# Alternatively, connect to a Google Cloud SQL instance using:
# db = MySQLdb.connect(host='ip-address-of-google-cloud-sql-instance', port=3306, user='root', charset='utf8')

so what you need to do is comment out the first line (the one it attempts to connect to a localhost mysql server) and uncomment the one where it connects to the Google Cloud SQL instance (note that you will have to update several parameters that reflect the configuration that you have, i.e. the host parameter and possible others).


text:
Q: Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List>
I'm trying to return List<QuestionsAndChoices> in getAllQuestions() method but I'm getting this error
Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<int, HowWellDoYouKnowMeAPI.Models.models.QuestionsAndChoices>>' to 'System.Collections.Generic.List<HowWellDoYouKnowMeAPI.Models.models.QuestionsAndChoices>

GetAllQuestions
public List<QuestionsAndChoices> getAllQuestions()
{
    List<QuestionsAndChoices> questionsAndChoices1 = context.quizQuestionAndChoices.
        Join(context.quizQuestions, QandC => QandC.QuizQuestions.QuizQuestionsId, qustions => qustions.QuizQuestionsId, (QandC, qustions) =>
            new
            {
                QandC,
                qustions
            }).
            Join(context.quizChoices, QandC1 => QandC1.QandC.QuizChoicesId, choices => choices.QuizChoicesId, (QandC1, choices) =>
            new QuestionsAndChoices
            {
                QuestionId = QandC1.qustions.QuizQuestionsId,
                Question = QandC1.qustions.Questions,
                Choices = choices,
             }).GroupBy(e => e.QuestionId).ToList();

    return questionsAndChoices1;
}

QuestionsAndChoices class
public class QuestionsAndChoices
    {
        public int QuestionId { get; set; }
        public string Question { get; set; }
         public List<QuizChoices> Choices { get; set; }
    }

QuizQuestionAndChoices class
public class QuizQuestionAndChoices
{
    public int QuizQuestionAndChoicesID { get; set; }
    public int QuizChoicesId { get; set; }
    public int QuizQuestionsId { get; set; }
    public QuizChoices quizChoices { get; set; }
    public QuizQuestions QuizQuestions { get; set; }
}

quizQuestions class
 public class QuizQuestions
 {
     public int QuizQuestionsId { get; set; }
     public string Questions { get; set; }
     public List<QuizzerQCdetails> quizzerQCdetails { get; set; }
     public List<QuizQuestionAndChoices> QuizQuestionAndChoices { get; set; }
 }

QuizChoices class
public class QuizChoices
{
    public int QuizChoicesId { get; set; }
    public string Choice { get; set; }
    public List<QuizzerQCdetails> quizzerQCdetails { get; set; }
    public List<QuizQuestionAndChoices> quizQuestionAndChoices { get; set;
}

I expect output like this
{
    "questionId":1,
    "question":"q1",
    "choices":{
        {
        "quizChoicesId":1,
        "choice":"1c1",
        "quizzerQCdetails":null,
        "quizQuestionAndChoices":null
        },
        {
        "quizChoicesId":2,
        "choice":"1c2",
        "quizzerQCdetails":null,
        "quizQuestionAndChoices":null
        }
    }
}

but am getting this output
@IbraHimM.Nada I have gone trough that code but I get output like this
{
"questionId":1,
"question":"q1",
"choices":{
        {
        "quizChoicesId":1,
        "choice":"1c1",
        "quizzerQCdetails":null,
        "quizQuestionAndChoices":null
        }
    }
}
,
{
"questionId":1,
"question":"q1",
"choices":{
        {
        "quizChoicesId":2,
        "choice":"1c2",
        "quizzerQCdetails":null,
        "quizQuestionAndChoices":null
        }
    }
}

A: Try following :
List<QuestionsAndChoices> questionsAndChoices1 = (
    from qandc in context.quizQuestionAndChoices
    join quest in context.quizQuestions on qandc.QuizQuestionsId equals quest.QuizQuestionsId
    join answers in context.quizChoices on qandc.QuizChoicesId equals answers.QuizChoicesId
    select new { question = quest.Questions, answers = answers })
  .GroupBy(x => x.question)
  .Select(x => new QuestionsAndChoices()
    {
      Question = x.Key,
      Choices = x.Select(y => y.answers).ToList()
    }).ToList();


text:
Q: Google Api PHP Client Library I am trying to use the Google API PHP Client library for Google Analytic v3.
I am able to run the simple app I wrote at home, but when I try at the office it doesn't work. When I run the program I am asked to authorize the php app to my google account. After allowing access I get
Google_IOException: HTTP Error: (0) couldn't connect to host in C:\wamp\www\google\GoogleClientApi\io\Google_CurlIO.php on line 128
It is necessary to connect to a proxy server at my organization. Does anyone know how to use oauth 2 and the php client library to connect to a proxy server.
thanks
Below is the code from my php client.
session_start();
require_once dirname(__FILE__).'/GoogleClientApi/Google_Client.php';
require_once dirname(__FILE__).'/GoogleClientApi/contrib/Google_AnalyticsService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
//$client->setClientId(''); omitted for privacy
//$client->setClientSecret(''); omitted for privacy
$client->setRedirectUri($scriptUri);
//$client->setDeveloperKey(''); // API key omitted for privacy

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token     and store it in session
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

echo 'Hello, world.';

A: Just to add (Since I wasn't able to find any results in google for this) if you want to avoid having to edit the library itself you can specify the additional curl params via the $client object. The code to do so looks roughly like this.
$client = new Google_Client();
$client->getIo()->setOptions(array(
    CURLOPT_PROXY => 'myproxy.mywebsite.com',
    CURLOPT_PROXYPORT => 8909
));

A: You have to configure proxy settings in curl. Check Google_CurlIO.php for a line that calls curl_exec($ch).
You may need to add something beforehand similar to:
curl_setopt($ch, CURLOPT_PROXY, 'your-proxy-server');

A: Update for v2.0.0
$client = new Google_Client();
$httpClient = $client->getHttpClient();
$httpClient->setDefaultOption("proxy", "http://{$proxyUser}:{$proxyPass}@{$proxyAddress}:{$proxyPort}");

A: Update for version 2.2.0
The library uses Guzzle which reads the environnement variables to automatically setup (or not) a proxy (see GuzzleHttp\Client class) line 177:
    if ($proxy = getenv('HTTPS_PROXY')) {
        $defaults['proxy']['https'] = $proxy;
    }

I assume you need a HTTPS proxy since Google OAuth won't work over simple HTTP.
Just add
putenv('HTTPS_PROXY=myproxy.mywebsite.com:8909');

and it works by itself.


text:
Q: How to properly display weather station JSON data on Leaflet map from Synoptic API? I'm trying to display a map of weather stations in Alaska from a MesoWest (now Synoptic) API with their temperature and wind speed on a Leaflet map. I've seen some examples online but they're all very old and result in errors.
Here is what I have in my .js:
var map = L.map('map').setView([64.666, -147.101], 8);
var basemap = L.tileLayer.provider('Stamen.Terrain').addTo(map);

var mesoMarkersGroup=new L.LayerGroup();
$.getJSON('https://api.synopticdata.com/v2/stations/latest?&token=[MY TOKEN]&within=1440&obtimezone=utc&output=json&units=temp|f,speed|mph&state=ak&country=us&status=active&vars=air_temp,wind_speed&varsoperator=and', function (data) {
    L.geoJson(data).addTo(map);
});
map.addLayer(mesoMarkersGroup);

The link should return raw .JSON data.
Here is a snippet of some of what the link shows if I limit it to one station:
{"UNITS":{"wind_speed":"Miles\/hour","air_temp":"Fahrenheit"},"QC_SUMMARY":{"QC_CHECKS_APPLIED":["sl_range_check"],"TOTAL_OBSERVATIONS_FLAGGED":0.0,"PERCENT_OF_TOTAL_OBSERVATIONS_FLAGGED":0.0},"STATION":[{"STATUS":"ACTIVE","MNET_ID":"1","PERIOD_OF_RECORD":{"start":"2002-11-05T00:00:00Z","end":"2021-12-09T07:15:00Z"},"ELEVATION":"433","NAME":"Fairbanks, Fairbanks International Airport","DISTANCE":0.0,"STID":"PAFA","SENSOR_VARIABLES":{"wind_speed":{"wind_speed_value_1":{"period_of_record":{"start":"","end":""}}},"air_temp":{"air_temp_value_1":{"period_of_record":{"start":"","end":""}}}},"ELEV_DEM":"419.9","LONGITUDE":"-147.87611","STATE":"AK","OBSERVATIONS":{"wind_speed_value_1":{"date_time":"2021-12-09T07:53:00Z","value":0.0},"air_temp_value_1":{"date_time":"2021-12-09T07:53:00Z","value":10.94}},"RESTRICTED":false,"QC_FLAGGED":false,"LATITUDE":"64.80389","TIMEZONE":"America\/Anchorage","ID":"4620"}],"SUMMARY":{"DATA_QUERY_TIME":"1.08480453491 ms","RESPONSE_CODE":1,"RESPONSE_MESSAGE":"OK","METADATA_RESPONSE_TIME":"152.322053909 ms","DATA_PARSING_TIME":"0.256776809692 ms","TOTAL_DATA_TIME":"1.34587287903 ms","NUMBER_OF_OBJECTS":1}}

I just want a dot on the map that shows wind and temperature :(

A: As I mentioned above, it is enough to add the appropriate parameter to the api output=geojson call. Below is the use of api:

var map = L.map("map").setView([0, 0], 13);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);

fetch("https://api.synopticdata.com/v2/stations/latest?radius=KHOU,50&limit=10&output=geojson&vars=air_temp&within=100&token=70c1dfd9b68d4511a0a8283cc6f0f972")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    const jsonLayer = L.geoJSON(data);
    jsonLayer.addTo(map);
    map.fitBounds(jsonLayer.getBounds(), {padding: [50, 50]});
  });
*,
:after,
:before {
  margin: 0;
  box-sizing: border-box;
}

html,
body,
#map {
  height: 100%;
}

body {
  margin: 0;
  min-height: 100%;
  overflow-x: hidden;
  padding: 0;
}
<link href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" rel="stylesheet"/>