text:
Q: Exchanging data between two Microservices I am facing this problem and would like to review my approach to it here.

*

*A Client sends an HTTP request to  Service A and is expecting an answer.

*Service A is connected to DB A. When it receives a request from Client, it should save it in DB A and forward it to Service B. If it already exists, it should return a failure.

*Service B is connected to DB B. When it receives a request from Service A, it should save it in DB B. If it already exists, it should return a failure which is propagated back to the Client
How can one design such a system so that:

*

*The Client does not block forever

*DB A and DB B DO NOT contain duplicated data

*Both services conform to a Microservices architecture (i.e., some downtime is expected).

One way i thought would be good to design it is to split the Client request into two: one to post the data without expecting an answer, and another request to query the data in question if it was successfully inserted. This avoids blocking the client. Both Services would need to have a queue.
Am i overlooking something fundamental in the design?
Many thanks in advance

A: For this kind of requirement, it will be better to have the client receive an intermediate response rather than returning the final answer. For this to work, I would make a client request processed asynchronously.
In simple terms, Service A and Service B act as consumers listening to queues QueueA and QueueB respectively on a message broker service (ActiveMQ, RabitMQ, etc) There will be another service called API service that listens to client requests. This service will also have its own DB maintaining status of tasks (DB API). Service A and Service B will also have access to DB API.
With this design in place, here is how a request is processed when it is submitted by the client:

*

*API Service will create a task ID in DB API. The task status will be In Progress. Then it will post a request to QueueA. The task ID is retuned as an immediate response.

*Service A will consume the message, processes it. If the request is processed successfully, the quest is forwarded to QueueB. It will update the DB API against the task ID.

*Service B listening to QueueB consumes the message and processes it. If it fails, the failure is updated against the DB API against the task ID in DB API as the final result.

Based on the task updates done by Service A and Service B, the status of the task will either be Done or Error. The client that is polling for the job to complete, will then get the final result as response.


text:
Q: large sql resultsets in java How can I fetch large resultset in java? I have about 140,000 rows with 3 columns.

A: There's no special way to retrieve a large result set; this can be done the same as any other database query via JDBC.
The key is in how the results are handled. 140,000 small records is not too many, but if holding them all in application memory at once is a problem, consider whether they can be processed "streamwise". That is, use the information needed from each record, then discard the record before retrieving the next. This way, the memory requirement doesn't depend on the number of records in the result set.

A: (using a java.sql.Connection to your DB):
Statement st = cnxn.createStatement();
ResultSet rs = st.executeQuery("SELECT column1,column2,your_mom FROM some_table");

while(rs.next()){
  Object ob1 =  rs.getObject(1);
  Object ob2 =  rs.getObject(2);
  Ho ob3 =  rs.getHo(3);
  doStuffWithRow(ob1,ob2,ob3);
}

Unless your DBMS is pathetically useless, results will be read from disk/memory as requested, and won't sit in your memory or anything crazy like that.  Using the primitives-based ResultSet.getXXX methods is faster than getObject, but I didn't feel like specifying column types.
Just be patient and let 'er chug. Oh, and stay the heck away from ORM here.

A: If you're using PostgreSQL, you'll need to setup the Connection and the Statement as follows:
Connection cnxn = ...;
cnxn.setAutoCommit(false);
Statement stmnt = cnxn.createStatement();
stmnt.setFetchSize(1);

Otherwise your query is liable to try & load everything into memory.
Thanks to http://abhirama.wordpress.com/2009/01/07/postgresql-jdbc-and-large-result-sets/ for documenting that.

A: i would avoid loading such a data set with any kind of complex abstraction. this sounds like a "batch job" style application.
i would recommend using raw jdbc and map it to a very compact representation, without bloat with only 3 colums this should be fairly easy to hold in memory, if the strings? are not overly big.
avoid loading 140k rows with a tool such as hibernate. it is a great tool, but you might run into memory issues if you hold that many entities in the hibernate 1st and 2nd level caches.

A: I recommend a batch style fetch instead of loading everything.  There are performance considerations at the database end when executing a query with a big result set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: laravel why i cant use releationshiop for data get with join here is my controller:
 $homeTeamFacts = DB::table('match_facts')
            ->where('match_id', $match->id)
            ->join('players', 'match_facts.player_id', '=', 'players.id')
            ->where('players.team_id', '=', $homeTeamId)
            ->get();

and here is data collection i get:
Illuminate\Support\Collection {#1311 ▼
  #items: array:4 [▼
    0 => {#1325 ▼
      +"id": 2
      +"match_id": "1"
      +"player_id": "2"
      +"minutes": 90
      +"goals": null
      +"yellowCard": 1
      +"redCard": 0
      +"bench": 0
      +"created_at": "2021-01-08 11:12:59"
      +"updated_at": "2021-01-08 11:12:59"
      +"team_id": "1"
      +"position": "Gynėjas"
      +"photo": null
      +"name": "Tomas"
      +"surname": "Tomaitis"
      +"birth_date": null
      +"city": null
      +"height": null
      +"weight": null
    }
    1 => {#1332 ▶}
    2 => {#1323 ▶}
    3 => {#1333 ▶}
  ]
}

the problem is when i'm trying to get player name in view with "{{$fact -> player-> name}}"
when i get an error like this "Undefined property: stdClass::$player (View:..... "
But when i get data like this:
$MatchFacts = Match_fact::where('match_id', $match->id)
        ->get();

there are no problems and releationship works fine.
Is any options to make releationships work on my mentioned problem?

A: This is because you are doing the query through the query builder directly instead of using Eloquent. That way, the results are not being hydrated as Match_fact instances but common stdClass ones. So, there's no player relationship defined on those.
To solve this, try to query your data using Eloquent and relationship instead
$MatchFacts = Match_fact::with('player')
        ->where('match_id', $match->id)
        ->get();

If you have defined the player relationship on Match_fact properly, then you should be able to do this:
@foreach($MatchFacts as $fact)
  {{ $fact->player->name }}
@endforeach

A: In your case you are using a query builder for retrieve your data from DB DB::table('match_facts')
You can get player name using query builder, just add select players.name to your select() method
$homeTeamFacts = DB::table('match_facts')
    ->where('match_id', $match->id)
    ->join('players', 'match_facts.player_id', '=', 'players.id')
    ->where('players.team_id', '=', $homeTeamId)
    ->select('match_facts.*', 'players.name  as player_name')
    ->get();

and now you can access the player name using $fact->player_name
But in my opinion using Models and relations is the better option for your purposes

A: I think when you join more than one table means the result will be  not an actual instance of that model will be just a collection of data that's why the relationship does not work , you can get the name of player by add  select in which you will specify the columns do you can add even the name of the player as the column selected so in a collection of data will be a name of the player also as player_name
 $homeTeamFacts = DB::table('match_facts')->select([                DB::raw('players.name as player_name'),])

        ->where('match_id', $match->id)
        ->join('players', 'match_facts.player_id', '=', 'players.id')
        ->where('players.team_id', '=', $homeTeamId)
        ->get();


text:
Q: Recovering NTFS drive with safecopy Several days ago, I dropped my USB external hard disk. As a result, I cannot read some of the files. I would like to recover it, and now I am using safecopy. I used the following command,
sudo safecopy /dev/sdb1 data.img --stage1

However, at around 93%, then there is a message something like "cannot read from source".
Then I tried to mount this partially recovered image, but failed. What are the things I can do more to recover the data?
==================================================================
I have tried to use
sudo safecopy /dev/sdb data.img --stage1

Now, it is done. Then, I
fdisk -lu data.img

It produces this result,
Disk data.img: 310.8 GB, 310798626816 bytes
255 heads, 63 sectors/track, 37785 cylinders, total 607028568 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xb1bec32c

   Device Boot      Start         End      Blocks   Id  System
data.img1              63   625137344   312568641    7  HPFS/NTFS/exFAT

Then, I tried to mount with
sudo mount -o loop,offset=32256 -t ntfs data.img /mnt/temp

but failed with this output
Failed to read last sector (625137281): Invalid argument
HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,
   or it was not setup correctly (e.g. by not using mdadm --build ...),
   or a wrong device is tried to be mounted,
   or the partition table is corrupt (partition is smaller than NTFS),
   or the NTFS boot sector is corrupt (NTFS size is not valid).
Failed to mount '/dev/loop0': Invalid argument
The device '/dev/loop0' doesn't seem to have a valid NTFS.
Maybe the wrong device is used? Or the whole disk instead of a
partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?

How should I do to recover the data from here?

A: First, you may want to try safecopy --stage2 and safecopy --stage3 as well, to try to extract a little more from the disk.
If your copy is partial, you have a damaged filesystem. Run fsck on it (e.g. fsck -y copy-of-data.img) to attempt to repair. Note that for NTFS, you'll need a recent version of NTFS-3g. Repairing means turning the filesystem into a valid filesystem, it may well lose some of the data. So do this on a copy of the image. Then mount the image and try to recover files from it: sudo mount -o loop copy-of-data.img /mnt. Note that if fsck finds some data that it's unable to relate to a file name, it'll store it under the lost+found directory.
Sometimes, when fsck runs, it discards data because that data doesn't seem to belong to any file. A different approach for data recovery is to look for fragments on the disk that look like useful data. This works especially well for file formats that have a recognizable header, such as pictures. So try running carving tools on the copy of the disk image where you haven't run fsck. See How to recover data from a bad SD card? If these carving tools aren't easily available on your system, try the Testdisk live CD.


text:
Q: Run Apache-beam pipeline job on existing google cloud VM I am creating a python apache-beam pipeline that has google cloud SQL ingestion, so when I am deploying the pipeline, a new VM is created automatically which has no access to my google cloud SQL instance, so my job is getting failed each time. showing below error log in job logs

So I am looking for an apache-beam pipeline option with python, if I can pass any argument name as a worker(VM) name or public IP of existing VM so that job will be automatically run over the existing VM that has access to my google cloud SQL VM
So far I have checked this https://cloud.google.com/dataflow/docs/reference/pipeline-options it does not have any worker name argument
Please help me out
Thanks

A: Probably, Dataflow workers do not have access to your Google Cloud SQL instance. Please look into Dataflow security and permissions regarding setting up correct access for Dataflow VMs. Specifically, you need to make sure that the Worker service account has access to the Cloud SQL instance.


text:
Q: How I can insert birth date in MySQL with php? I'm trying to insert a birth date in MySQL with php, but it displays 00-00-0000,
In html I have three dropdowns with Month, Date and Year, and in MySQL the column is name: birthdate, Type: DATE. I'm trying to insert with the below PHP script, but I can not.
Please see the script below:
if (isset($_POST['first']) && isset($_POST['last']) && isset($_POST['email']) && isset($_POST['password'])) {
  if (!empty($_POST['first']) && !empty($_POST['last']) && !empty($_POST['password'])) {
    $user = new User();
    $user - > id['id'];
    $user - > firstname = $_POST['first'];
    $user - > lastname = $_POST['last'];
    $user - > email = $_POST['email'];
    $user - > password = $_POST['password'];
    $month = $_POST['month'];
    $dt = $_POST['dt'];
    $year = $_POST['year'];
    $user - > birthdate = $date_value = "$month/$dt/$year";
    if ($user - > Create()) {
      header("Location:profile.php");
    } else {
      echo "User already exist!";
    }
  }
}

A: In PHP you use . to concatenate strings, try:
$Date = $year . "/" . $month.  "/" . $dt;

$newformat = date('Y-m-d',$Date);

Your code should be
$user -> birthdate = $newformat;

A: Try your birthdate like below
 $month = date('m', strtotime($month));
   /* or you can directly covert like this also $month = date('m', strtotime($_POST['month'])); */
    $date_value = $year. "-" .$month . "-".$dt;
    $user->birthdate = date('Y-m-d',strtotime($date_value));

Here i have convert your date in Y-m-d format as MySQL date datatype accept this format  You can find more about strtotime on this link


text:
Q: O que é o "stdafx.h" e qual sua importância? Ao criar um projeto C++ no Visual Studio, ele traz uma linha automaticamente no arquivo principal:
#include "stdafx.h"

Como estou no início do estudo da linguagem, vendo alguns "olá mundo", não encontrei essa linha nos exemplos.
Ao retirar essa linha, recebo o seguinte erro

error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?

Qual é a finalidade dessa linha?

A: Por definição "Stdafx.h" é um cabeçalho pré-compilado.
Pré-compilado (uma vez compilado não é necessário compilá-lo novamente).
Cabeçalho pré-compilado stdafx.h é basicamente usado no Microsoft Visual Studio para permitir que o compilador conheça os arquivos que são compilados e não há necessidade de compilá-lo a partir do zero.
Por exemplo:
Se você estiver incluindo os arquivos de cabeçalho do Windows abaixo
Código:
#include <windows.h>
#include <tchar.h>

int main() {  //your code return 0; }

O compilador sempre compilará esses arquivos de cabeçalho do zero.
Mas se você incluir #include "stdafx.h" antes que isso inclua, então o compilador irá encontrar os arquivos de cabeçalho compilado do stdafx.h e não compilado a partir do zero. Mas se o compilador não encontrar quaisquer arquivos de cabeçalho compilado do stdafx.h, em seguida, primeiro ele compila os arquivos e, em seguida, armazena sua versão compilada em stdafx.h. Para que possa ser usado para a compilação da próxima vez.
Código:
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>

int main() { //your code  return 0; }

Quais são os seus benefícios:

*

*Reduz o tempo de compilação.

*Reduz o processamento desnecessário.

Portanto a conclusão:

Usar #include "stdafx.h" onde você está realmente usando os outros
  arquivos de cabeçalho (como arquivos de cabeçalho do Windows). Caso
  contrário, não há necessidade de usar stdafx.h. E isso não
  significa que você irá removê-lo de seu projeto, mas você pode
  desativar este cabeçalho pré-compilado de configurações do projeto,
  selecionando o arquivo (em que você não precisa deste stdafx.h) e
  vá para propriedades dele e encontrar sob a opção "C ++ ->
  Precompiled Header e selecione Use Precompiled Header to...".

É isso aí. Espero que tenha entendido.

A: Por falta de um mecanismo melhor é uma bela gambiarra para indicar que os cabeçalhos a serem usados já possuem uma versão compilada e não precisa compilá-los novamente. Coloca esta linha e o compilador sabe que pode usar os pré compilados.
Os headers são códigos que são necessários para uso das bibliotecas contendo estruturas, macros e assinaturas de funções. Eles são inclusos no seu código e tudo é compilado. Demora para fazer isto até porque costuma ter vários deles e alguns são bem grandes. Só que em geral eles não são alterados e a compilação deles toda vez que compila o seu código é um desperdício.
Tem como desabilitar isso no Visual Studio, mas a compilação ficará mais lenta.
Coloquei no GitHub para referência futura.


text:
Q: How to type props for components that are nested in a HOC in Flow? I came across that wrapping a component in a HOC doesn't return any type annotations.
Short example:
components/Button/index.js
// @flow

import * as React from 'react'
import { withRouter } from 'react-router-dom'
import styled from 'styled-components'

const Wrapper = styled.button`
  background-color: transparent;
`

type Props = {
  children?: React.Node,
  history: Object,
  target: String
}

const Button = (props: Props) => {
  return <Wrapper onClick={() => { if (props.target) props.history.push(props.target) }}>{props.children}</Wrapper>
}

export default withRouter(Button)

But VS Code doesn't give any information about my Button component when using this in another component:

That's how it should look:

So how do I have to write those type annotations?
Update 1
So that's my current solution, based on the comments and some research (intersection of types):
// @flow

import * as React from 'react'
import { RouterHistory, withRouter } from 'react-router-dom'
import styled from 'styled-components'

import theme from 'themes/default'

type ButtonProps = {
  children: React.Node,
  target: string,
}

type Props = ButtonProps & RouterHistory

const Wrapper = styled.button`
  background-color: transparent;
`

const Button = ({ children, history, target }: Props) => (
  <Wrapper onClick={() => { history.push(target)}}>{children}</Wrapper>
)

const enhanced: typeof Button = withRouter(Button)
export default enhanced

I'm sure there are better solutions, but without the typed export, VS Code won't show any hints except import Button.

A: I guess the type of Props is wrong. With the type definition from flow-typed, ContextRouter is the type of the additional props that are provided by withRouter HOC.
import type { ContextRouter } from 'react-router';

type Props = ButtonProps & ContextRouter;

I made an example on REPL.
Alternative Approach
HOC is hard to type in general because flow needs to subtract history, etc. from the props of Button. An alternative is "render props" pattern. It's much easier for flow to type-check because it doesn't require the subtraction.
Fortunately, withRouter is just a thin wrapper around Route component, which takes a render prop.
If you use Route, you can directly use ButtonProps and it's easier for flow to understand.
type ButtonProps = {
  children: React.Node,
  target: string,
}

const Button = ({ children, target }: ButtonProps) => (
  <Route
    render={({ history }) => (
      <button onClick={() => { history.push(target) }}>{children}</button>
    )}
  />
)

export default Button

I also made a working example with render prop with REPL.


text:
Q: Как решить задачи в E-olymp c помощью php? Есть такой замечательный сайт: https://www.e-olymp.com/ru/problems/21
Решил я порешать задачи, но столкнулся с проблемой, что не правильные ответы, но на машине всё правильно работает. Подозреваю что дело в записи в файл. Как работать с такими компиляторами ?
Код моей задачи:
<?php
    function readFiles($dir) {
        return file($dir, FILE_IGNORE_NEW_LINES);
    }

    $dir = __DIR__ . '/input.txt';
    $outputFile = __DIR__ . '/output.txt';
    $firstLine = explode(' ', readFiles($dir)[0]);
    $countExpires = $firstLine[0];
    $percent = $firstLine[1];
    $expiresArr = explode(' ', readFiles($dir)[1]);
    while(count($expiresArr) !== 1) {
        for ($i = 0; $i < round(count($expiresArr) / 2, 0, PHP_ROUND_HALF_DOWN); $i++) {
            var_dump($expiresArr);
            echo '
';
            $expiresArr[] = ($expiresArr[$i] + $expiresArr[$i + 1]) * (1 - ($percent / 100));
            $expiresArr = array_diff_key($expiresArr, [$i, $i + 1]);
            array_values($expiresArr);
            sort($expiresArr, SORT_NUMERIC);
            var_dump($expiresArr);
            echo '
';
        }
    }
    file_put_contents($outputFile, number_format($expiresArr[0],2, '.', '') . "\n");
?>

A: Для начала ознакомиться со справкой. Обычно там пишут как с чем работать с примерами кода.

На данный момент система поддерживает 3 языка и 6 разных копиляторов: Borland Delphi 7.0, Free Pascal, Gnu C++, Java Developement Kit, Microsoft Visual С++ 6.0, Microsoft Visual C++ 9.0.

A: Если вы поставили галочку Решение использует файлы для чтения и записи, то ответ надо писать в файл. А не выводить через echo как это сделано у вас.


text:
Q: How can I portably implement row-wise binding of arbitrary resultsets in ODBC while avoiding alignment issues? I have a class which takes an SQL query, executes it, then binds every column in the resultset as SQL_C_WCHAR using row-wise binding.
right now the way I do it is to allocate a vector of char, and determine the pointers to give SQLBindColumn as follows:

*

*buffer for column 1 = &vec[0]

*buffer for length indicator of column 1 = &vec[0] + (sizeof(SQLWCHAR) * length of column 1)

*buffer for column 2 = &vec[0] + (sizeof(SQLWCHAR) * length of
column 1) + sizeof(length indicator)

*buffer for length indicator of column 2 = &vec[0] + (sizeof(SQLWCHAR) * length of column 1) + sizeof(length indicator) + (sizeof(SQLWCHAR) * length of column 2)

and so on
this is causing some alignment issues (on SPARC). I know I need to add some padding, but I don't know how to calculate how much portably.

A: The way I ended up dealing with it was to actually put the length indicators and the wchars in seperate, correctly typed, buffers. They don't actually have to live in the same buffer since all that ODBC does is add the 'struct size' to each address each time it wants to go the the next set.
I figured out the alignment needed for WCHAR and SQLLEN by allocating two small arrays on the stack and subtracting pointers between adjacent cells. Then I took the LCM of both of the alignments, and added padding to the buffers so each set would occupy a multiple of that space. The I fed ODBC this as a phony 'struct size'.

A: Row-wise binding is a pain in the backside. However, I thought the indicators (assuming you mean StrLen_or_IndPtr argument) can be specified in a separate array of SQLINTEGER/SQLLEN (depending on how new your ODBC is). Look for something like SQL_DESC_INDICATOR_PTR and there is another one for the length. You can set these separately from the data by setting fields in the descriptor. If you do this you will avoid alignment issues and keep your row data separate from the indicator/length.
Update: http://msdn.microsoft.com/en-us/library/ms711730(v=vs.85).aspx
Update2: Just ensure the integer values (like you indicator) are correctly aligned on a 4 byte boundary or whatever Sparc requires.


text:
Q: how do you detect an inactive session for a chat script in PHP? so i'm writing something similar to a chat app and need a way to detect when a user is no longer active. essentially i need to let OTHER users of the app know that user X logged out if they left the page or closed their browser.  Any way for a server-side script to figure this out aside from "i got no requests from user X in 15 mins so i'll assume he's out?"

A: Just as they said in the links in the comments you need to use AJAX. The easiest way to do this (in my opinion) is with JQuery, here is an example below:
$(document).ready(function(){
    window.setInterval(function(){
        initiateSessionCheck();
    5000);

    function initiateSessionCheck() {
        $.ajax({
            type : 'POST',
            url : 'sessioncheck.php',
            success : function(data){
                //success
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                //error do something they are no longer active
            }
        });

    }
});

Now in your sessioncheck.php file you'll want to do this
session_start();

if (!$_SESSION) { //you could check a session variable explicitly like $_SESSION['user_id'] != ''
    $return['error'] = true;
} else {
    $return['error'] = false;
}

echo json_encode($return);

It's basic but it should do the trick!


text:
Q: Facebook Redirect Uri Not Return And Stuck On White Page I try to make fb sharer its posted well but after that not return on my redirect uri url
and stuck on this fb page
https://web.facebook.com/dialog/return/close?_rdc=1&rdr#=_
here is my share code
<a href="https://www.facebook.com/sharer/sharer.php?app_id=423436984657946&u=<?=$_IM['siteurl'];?>/sview/<?=$qf['url'];?>/<?=$_SESSION['FBID'];?>&picture=<?=$a_img;?>&title=<?=$a_title;?>&description=<?=$a_desc;?>&redirect_uri=<?=$a_return;?>"><button type="button" style="background: blue;border:2px solid blue;" ="" > শেয়ার করুন</button>

and if u need to read full code I submit that too below
  <?php
        require_once __DIR__ . '/config.php';
        $helper = $fb->getRedirectLoginHelper();
        try {
        $accessToken = $helper->getAccessToken();
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage(); exit;
        }
         catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit;
        }
        if (isset($accessToken)) {
        $_SESSION['access_token'] = (string) $accessToken;
        }
        if(isset($_GET['app'])){
        $aid=$_GET['app'];
        $app=$idb->prepare("SELECT * FROM allapps WHERE url=?");
        $app->bind_param("s",$aid);
        $app->execute();
        $a_r=$app->get_result();
        $naf=$a_r->fetch_assoc();
        $views=$naf['views']+1;
        $v=$idb->prepare("UPDATE allapps SET views=? WHERE id=?");
        $v->bind_param("ss",$views,$naf['id']);
        $v->execute();
        if($a_r->num_rows<1){   igo($_IM["siteurl"]."/404.php");
        }
        $title=$naf['title'];
        }
        include "header.php";

        if(!isset($_SESSION['FBID'])){
        echo "Login First";
        exit();
        } ?>

        <?php
        if(isset($_GET['app'])) {
        $gid=$_GET['app'];
        $guser=$_SESSION['FNAME'].", ";
        $q=$idb->prepare("SELECT * FROM apps_text WHERE url=? ORDER BY rand()");
        $q->bind_param("s",$gid);
        $q->execute();
        $qr=$q->get_result();
        $qf=$qr->fetch_assoc();
        $text1=$qf['text'];
        $fbid=$_SESSION['FBID'];
        $gpropic=$_SESSION['propic'];
        if(file_exists("apps-f/".$qf['url'].".php")){
        include ("apps-f/".$qf['url'].".php");
        $a_title=$naf['title'];
        $a_desc=$naf['title']." - দেখতে এখানে ক্লিক করুন" ;
        $a_img=$_IM['siteurl']."/images/generated/".$naf["url"]."-".$fbid.".jpg";
        $a_return=$_IM['siteurl']."/".$gid."";
        }                               else {
        echo "Not Found!";
        }
        }
        echo '';
        include 'ads.php';
        echo '';
        ?>

        <button type="button" onClick="window.location.reload()" >রিফ্রেশ</button>

        <a href="https://www.facebook.com/sharer/sharer.php?app_id=423436984657946&u=<?=$_IM['siteurl'];?>/sview/<?=$qf['url'];?>/<?=$_SESSION['FBID'];?>&picture=<?=$a_img;?>&title=<?=$a_title;?>&description=<?=$a_desc;?>&redirect_uri=<?=$a_return;?>"><button type="button" style="background: blue;border:2px solid blue;" ="" > শেয়ার করুন</button>

            <?php echo ''; include 'ads.php'; echo ''; ?>

        <?php include 'ads.php'; ?>

All Apps

        <?php
        $aapp=$idb->prepare("SELECT * FROM allapps ORDER BY id DESC");
        $aapp->execute();
        $ar=$aapp->get_result();
        while($af=$ar->fetch_assoc()){                  ?>

        <?php
        if(isset($_SESSION['access_token'])){
        $nu="";
        } else {
        $nu=".php"; }
        ?>
        <a href="<?=$_IM['siteurl'];?>/<?=$af['url'].$nu;?>">
        <img src="<?=$_IM['siteurl'];?>/<?=$af['img'];?>" alt="<?=$af['title'];?>" class="img-responsive" />

<?=$af['title'];?>

        <?php
        }?>

            <?php include "right_content.php";?>

        <?php include "footer.php"; ?>


text:
Q: Simple psql count query I am very new to postgresql and would like to generate some summary data from our table
We have a simple message board - table name messages which has an element ctg_uid. Each ctg_uid corresponds to a category name in the table categories.
Here are the categories select * from categories ORDER by ctg_uid ASC;
 ctg_uid |    ctg_category    | ctg_creator_uid
---------+--------------------+-----------------
       1 | general            |               1
       2 | faults             |               1
       3 | computing          |               1
       4 | teaching           |               2
       5 | QIS-FEEDBACK       |               3
       6 | QIS-PHYS-FEEDBACK  |               3
       7 | SOP-?-CHANGE       |               3
       8 | agenda items       |               7
      10 | Acq & Process      |               2
      12 | physics-jobs       |               3
      13 | Tech meeting items |              12
      16 | incident-forms     |               3
      17 | ERRORS             |               3
      19 | Files              |              10
      21 | QIS-CAR            |               3
      22 | doses              |               4
      24 | admin              |               3
      25 | audit              |               3
      26 | For Sale           |               4
      31 | URGENT-REPORTS     |               4
      34 | dt-jobs            |               3
      35 | JOBS               |               3
      36 | IN-PATIENTS        |               4
      37 | Ordering           |               4
      38 | dep-meetings       |               4
      39 | reporting          |               4

What I would like to do is for all messages on our messages is count the frequency of each category
I can do it on a category by category basis
SELECT count(msg_ctg_uid) FROM messages where msg_ctg_uid='13';
However is it possible to do this in a one liner?
The following gives the the category and ctg_uid for each message
SELECT ctg_category, msg_ctg_uid FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);
but SELECT ctg_category, count(msg_ctg_uid) FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);
gives me the error ERROR:  column "categories.ctg_category" must appear in the GROUP BY clause or be used in an aggregate function
How do I aggregate the frequency of each category ?

A: You're missing the group by clause:
SELECT ctg_category, count(msg_ctg_uid)
FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);
GROUP BY ctg_category

this means you want the count per ctg_category


text: Q: Cluster Analysis Assumptions and diagnostics I have a question. I am conducting a study using cluster analysis. My number of observations is less than the number of variables which means my matrix in n<p. Is it true that I am violating cluster analysis assumptions? Do I have to reduce my variables?


text:
Q: How does stream analytics query windowing work and how do I avoid double rows? I have a query in stream analytics to count the requests per hour. Therefore I have a group by cause and I got the message "a window is expected". So I added a tumblingwindow, but I do not understand how it is working.
group by
    datetimefromparts(year(r.starttime), month(r.starttime), day(r.starttime), datepart(hh, r.starttime),0,0,0),
    r.tags,
    r.IsMobile,
    tumblingwindow(hh, 1)

When I choose hh I got these 11 results:
requestdate                 tags    ismobilecount   summary
2016-10-03T21:00:00.000Z    A       0       6       2016-10-03T21:00:00.000ZA06
2016-10-03T21:00:00.000Z    B       0       1       2016-10-03T21:00:00.000ZB01
2016-10-03T22:00:00.000Z    A       0       20      2016-10-03T22:00:00.000ZA020
2016-10-03T21:00:00.000Z    B       0       1       2016-10-03T21:00:00.000ZB01
2016-10-03T22:00:00.000Z    B       0       14      2016-10-03T22:00:00.000ZB014
2016-10-03T21:00:00.000Z    A       1       2       2016-10-03T21:00:00.000ZA12
2016-10-03T21:00:00.000Z    B       1       1       2016-10-03T21:00:00.000ZB11
2016-10-03T21:00:00.000Z    B       1       1       2016-10-03T21:00:00.000ZB11
2016-10-03T21:00:00.000Z    A       1       1       2016-10-03T21:00:00.000ZA11
2016-10-03T22:00:00.000Z    A       1       15      2016-10-03T22:00:00.000ZA115
2016-10-03T22:00:00.000Z    B       1       22      2016-10-03T22:00:00.000ZB122

But when I choose dd (tumblingwindow(hh, 1)) I got these results:
requestdate                  tags ismobile  count   summary
2016-10-16T21:00:00.0000000Z    B       1       45      2016-10-16T21:00:00.0000000ZB145
2016-10-16T22:00:00.0000000Z    A       0       51      2016-10-16T22:00:00.0000000ZA051
2016-10-16T22:00:00.0000000Z    A       1       49      2016-10-16T22:00:00.0000000ZA149
2016-10-16T22:00:00.0000000Z    B       0       41      2016-10-16T22:00:00.0000000ZB041
2016-10-16T22:00:00.0000000Z    B       1       39      2016-10-16T22:00:00.0000000ZB139
2016-10-16T23:00:00.0000000Z    A       0       3       2016-10-16T23:00:00.0000000ZA03
2016-10-16T23:00:00.0000000Z    A       0       39      2016-10-16T23:00:00.0000000ZA039
2016-10-16T23:00:00.0000000Z    A       1       2       2016-10-16T23:00:00.0000000ZA12
2016-10-16T23:00:00.0000000Z    A       1       38      2016-10-16T23:00:00.0000000ZA138
2016-10-16T23:00:00.0000000Z    B       0       1       2016-10-16T23:00:00.0000000ZB01
2016-10-16T23:00:00.0000000Z    B       0       46      2016-10-16T23:00:00.0000000ZB046
2016-10-16T23:00:00.0000000Z    B       1       29      2016-10-16T23:00:00.0000000ZB129
2016-10-16T23:00:00.0000000Z    B       1       4       2016-10-16T23:00:00.0000000ZB14
2016-10-17T00:00:00.0000000Z    A       0       42      2016-10-17T00:00:00.0000000ZA042
2016-10-17T00:00:00.0000000Z    A       1       36      2016-10-17T00:00:00.0000000ZA136
2016-10-17T00:00:00.0000000Z    B       0       39      2016-10-17T00:00:00.0000000ZB039
2016-10-17T00:00:00.0000000Z    B       1       45      2016-10-17T00:00:00.0000000ZB145
2016-10-17T01:00:00.0000000Z    A       0       41      2016-10-17T01:00:00.0000000ZA041

When I run my job for some days, I got 8 rows for 23:00:00h every day.
But I am expecting only 4 rows for every hour. How can I solve that? Can someone explain me how this is working and how to solve this problem?

A: I believe it's due to your Tags always having A and B. This looks like it is expected behavior, since every hour you have an A and B. You will get the same thing with IsMobile when there are more than one distinct value in the hourly group.
So, based on Tags and IsMobile both having two possible choices every hour, you could have up to four rows per hour if there were the following events in that hour:
Tag: A, IsMobile: 0
Tag: A, IsMobile: 1
Tag: B, IsMobile: 0
Tag: B, IsMobile: 1


text:
Q: JSP form clientside validation in Spring without JS I am trying to input form details into database using a JSP file, Spring, Tomcat, MS Access. I am not supposed to use Maven and JavaScript.
When I did this before using JSP and servlets, the pattern feature of HTML5 using regex patterns worked fine for my client side validation. As for eg, for Login Id,
   <input type="text" name="uid"
            pattern="/^[A-Za-z0-9]+(?:[_][A-Za-z0-9]+)*$/" required>

worked fine.
Now that I'm learning spring and trying to use the form tag, I am doing
    <form:input type="text" path="uid" />

which works fine, but I need the pattern validator for client side without using JavaScript.
Now whenever I try to add the pattern feature to this, like
    <form:input type="text" name="uid"
            pattern="/^[A-Za-z0-9]+(?:[_][A-Za-z0-9]+)*$/" required/>

it reports an error which goes :
    type Exception report
    message /UserForm.jsp (line: 18, column: 61) equal symbol expected
    description The server encountered an internal error that prevented it from fulfilling this request.

Where am i going wrong?
I know I'll have to implement validator interface before I save the data into the database, I will get to it eventually. As of now, any help with this is highly appreciated.
I am new to spring, so it would be very kind of helpers to provide answers with explanation accompanying the workaround/solution code for the same.Thanks in advance.

A: In case of JSP and Spring you should validate the form fields on the controller class and show errors on the form with additional error-fields:
<form:input path="user" id="userInput" />
<form:errors path="user" cssClass="error" />

In the controller class you validate your fields and if there are no errors you could save your data to the database otherwise you show errors on the form.
@PostMapping("/saveUser")
public String saveUser(@ModelAttribute("user") @Validated User user,
    BindingResult result, Model model) {

  //custom validation
  //validator.validate(user, result);

  if (result.hasErrors()) {
     //if any errors, return back to fill out the form again
     return "userForm";
  }

  //save to DB and return success page
  return "success";
}

Validation could be standard and\or custom. There are a lot of good tutorials on the internet about Spring validation.

A: perhaps you have to change
<form:input type="text" name="uid" pattern="/^[A-Za-z0-9]+(?:[_][A-Za-z0-9]+)*$/" required/>

to
<form:input type="text" name="uid" pattern="/^[A-Za-z0-9]+(?:[_][A-Za-z0-9]+)*$/" required="required"/>

change required to required="required"


text:
Q: Prevent gulp-htmllint from skipping invalid html files I'm using gulp-htmllint to check files with html fragments. However, to my surprise, it skips files with invalid markup. I'd love to get "as good as possible" linting, but at the very least I want it to fail / report an error on invalid html.
Here's a repro. First the gulpfile.js (requires appropriate npm install commands beforehand):
var gulp = require("gulp"),
    gutil = require('gulp-util'),
    htmllint = require("gulp-htmllint"),
    path = require('path');

gulp.task("default", [], function() {
    return gulp.src("src/*.html")
        .pipe(htmllint({}, reporter));
});

function reporter(filepath, issues) {
    var filename = path.basename(filepath);
    if (issues.length > 0) {
        issues.forEach(function (issue) {
            gutil.log(gutil.colors.cyan('[lintHtml] ') + gutil.colors.white(filename + ' [' + issue.line + ',' + issue.column + ']: ') + gutil.colors.red('(' + issue.code + ') ' + issue.msg));
        });
        process.exitCode = 1;
    }
}

The reporter is based off the example on the package's home page.
With this src/fragment.html file:
Test 1.
Test 2.

I'll nicely get:

[08:04:06] Using gulpfile ~\myapp\gulpfile.js
[08:04:06] Starting 'default'...
[08:04:06] [lintHtml] fragment.html [1,6]: (E001) the `style` attribute is banned
[08:04:06] [lintHtml] fragment.html [2,6]: (E001) the `style` attribute is banned
[08:04:06] Finished 'default' after 38 ms

But, if I make the html file invalid like so:
<span style="color: red;"Test 1.
Test 2.

I get:

[08:05:06] Using gulpfile ~\myapp\gulpfile.js
[08:05:06] Starting 'default'...
[08:05:06] Finished 'default' after 25 ms

As if there's nothing wrong.
How do I get the process to report errors and fail when my fragment has such a problem?
PS. I ended up cross-posting to Github as an issue too.

A: There's no way to do this without changes to gulp-htmllint itself. If you look at the source you see that it only provides a success handler to the htmllint promise:
lint.then(function(issues) {
    issues.forEach(function(issue) {
        issue.msg = issue.msg || htmllint.messages.renderIssue(issue);
    });
    reporter(file.path, issues);
});

To output cases where the linting process fails because of invalid html, it would have to provide a reject handler as well:
lint.then(function(issues) {
    issues.forEach(function(issue) {
        issue.msg = issue.msg || htmllint.messages.renderIssue(issue);
    });
    reporter(file.path, issues);
}).catch(function(error) {
    //do something useful here
    console.log(file.path + ': ' + error.toString());
});

That means you have two options:

*

*Fork the project on github and implement this yourself

*Find another gulp plugin that does this (maybe gulp-htmlhint or gulp-html5-lint?)


text:
Q: Multiword RegEx containing '/' is not correctly finding the term Hey there I'm trying to write a multi-word RegEx that uses word boundaries. The string I'm searching is as follows (this is only a test string):
const regString = "/gamma/ truck?timer!doctor\\face"
Here is my regular expression:
const testReg2 = new RegExp("\\b\/gamma/|truck|\\?|face\\b", "gi");
For whatever reason the console posts ['truck', '?', 'face'] but it refuses to find '/gamma/' which is puzzling because const testReg = new RegExp("/gamma/"); does find '/gamma/'.

const regString = "/gamma/ truck?timer!doctor\\face"
const testReg2 = new RegExp("\\b\/gamma/|truck|\\?|face\\b", "gi");

console.log(regString.match(testReg2))

A: The issue is in using \b\/gamma and expecting it to match "/gamma" (same for the closing \b).
The Word Boundary \b in order to work it should be followed (or preceded, depending on where it's used) by at least one (or more) Word characters. Which is not — due to the non-word / character.
To visualize, let's spread those characters:
# Regex: \bxyz

/ g a m m a
 ^--------- \b points here. Match: `gamma`

# Regex: \b\/xyz

/ g a m m a
\b points nowhere. Match: none since `/` is a non-word char

Either: remove the \/ since that's already a specific character prefix / suffix, or...
If you really need to make sure the exact existance and sequence of those characters /gamma/, than don't use \b for the /gamma/ case.
\/gamma\/|\b(truck|\?|face)\b

Example on Regex101.com

const regString = "/gamma/ truck?timer!doctor\\face"

console.log(regString.match(/\/gamma\/|\b(truck|\?|face)\b/gi))

A: There are two ways to make this work, a) using word boundaries with words that start/end with word chars only (when the words are know beforehand, it is the easiest way), or b) using adaptive dynamic word boundaries (this is good if your "word" list is dynamic, or user-defined).
Here is Option 1:

const regString = "/gamma/ truck?timer!doctor\\face"
const testReg2 = /\/gamma\/|\?|\b(?:truck|face)\b/gi;
console.log(regString.match(testReg2))

So, here, ? and /gamma/ are NOT checked if they are whole words or not, since they start/end with non-word chars.
Now, Option 2:

const regString = "/gamma/ truck?timer!doctor\\face";
const words = ["/gamma/", "?", "truck", "face"];
const testReg2 = new RegExp("(?!\\B\\w)(?:" + words.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|") + ")(?<!\\w\\B)", "gi");
console.log(regString.match(testReg2));

This solution requires the lookbehind support, but it makes sure the whole word check is applied only in case there are word chars at the start/end of the word (also, all special chars are escaped appropriately).

A: According to this answer

[...] at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_])

Your string doesn't start with [0-9A-Za-z_] hence not match


text:
Q: How to save model form Data(User input of multiple users) into the database or dict in Django I am trying to set up a Website for Employee Scheduling with Django. I am new to Web development, therefore I run into some problems, scince I have the feeling the Web handles things differently. I need to pass information to a solver using pyomo.
For this employees should be able to pass information about their availability through a model form.
The employee has to be able to submit his input by clicking in the shift button in the day row. When he is logged in.

e.g:
Day1 : [S1] [S2] [S3] [S4] [S5] [S6]
Day2 : [S1] [S2] [S3] [S4] [S5] [S6]
Day3 : [S1] [S2] [S3] [S4] [S5] [S6]
The data in the database should look like this
Employee               Shift      Day    Available

Username                S1         D1        0
Username                S2         D1        1
Username x              Si         Dk        0

For the solver the information has to be in a dict like this:
Available ={("Username", "S1", "D1"): 0, ("Username", "S2", "D1"): 1, ("Username x", "Si ", "Dk"): 0}

0 means that the employee is not available on that shift on that day  and 1 means he is. The x stands for the next user.
In this example the employee clicked on [S2] in the Day 1 row. So the model should automatically paste the day and the employee name. So I would have to be able to link the button to it's related day and the model has to get the logged in user name.
Right now I get my data from a csv and transform it into a dict using pandas.
Is there any way to save the passed information as a csv or a dict into a database?

A: you can use Bulk Create and create a function that adds the data after reading it from the .csv file


text:
Q: How to count all the clicked radio buttons when clicking submit then the scores will go to the database How to count all the clicked radio buttons when clicking submit then the scores will go to the database
then score modal will fetch the score that's in the database. how to do that it is said that I should use
JQuery, should i really use it?
The value of the 4 radio buttons is 3 wrongs and 1 correct how to count all the radio buttons with correct value when it is clicked.
The HTML,JS and PHP is below
<?php
$Ans1 = $_POST['1'];
$Ans2 = $_POST['2'];
$Ans3 = $_POST['3'];
$Ans4 = $_POST['4'];
$Ans5 = $_POST['5'];
$Ans6 = $_POST['6'];
$Ans7 = $_POST['7'];
$Ans8 = $_POST['8'];
$Ans9 = $_POST['9'];
$Ans10 = $_POST['10'];

$Ans1 = $_POST['1'];

$INSERT = "INSERT Into scores(score) values (?)" ;

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'I have 27 years'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$Quest1 = $row[0];

?>
<?php

$sql = "SELECT * FROM questions WHERE B = 'I have 27 years'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1a = $row[1];
$RDO2a = $row[3];
$RDO3a = $row[2];
$RDO4a = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'By Taxi' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$Quest2 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'By Taxi' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1b = $row[1];
$RDO2b = $row[2];
$RDO3b = $row[3];
$RDO4b = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'At least 7 years' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest3 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'At least 7 years' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1c = $row[1];
$RDO2c = $row[2];
$RDO3c = $row[3];
$RDO4c = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'some' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest4 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'some' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1d = $row[1];
$RDO2d = $row[2];
$RDO3d = $row[3];
$RDO4d = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'goes to' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest5 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'goes to' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1e = $row[1];
$RDO2e = $row[2];
$RDO3e = $row[3];
$RDO4e = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'in Wednesdays' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest6 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'in Wednesdays' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1f = $row[1];
$RDO2f = $row[2];
$RDO3f = $row[3];
$RDO4f = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'Do you like?' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest7 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'Do you like?' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1g = $row[1];
$RDO2g = $row[2];
$RDO3g = $row[3];
$RDO4g = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'one white' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest8 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'one white' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1h = $row[1];
$RDO2h = $row[2];
$RDO3h= $row[3];
$RDO4h = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'has' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest9 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'has' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1i = $row[1];
$RDO2i = $row[2];
$RDO3i= $row[3];
$RDO4i = $row[4];

?>

<?php

$sql = "SELECT QUESTIONS FROM questions WHERE B = 'brothers or sisters' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$Quest10 = $row[0];

?>

<?php

$sql = "SELECT * FROM questions WHERE B = 'brothers or sisters' ";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$RDO1j = $row[1];
$RDO2j = $row[2];
$RDO3j= $row[3];
$RDO4j = $row[4];

?>

 COLLEGE ENTRANCE EXAMINATION

  INSTRUCTION: Choose the right answer from the multiple choices.

 ENGLISH

 <?php echo "1." . $Quest1; ?>

  <?php echo $RDO1a; ?>
         <input type="radio" name="1">

  <?php echo $RDO3a; ?>
    <input type="radio" name="1">

  <?php echo $RDO2a; ?>
         <input type="radio" name="1">

  <?php echo $RDO4a; ?>
    <input type="radio" name="1">

 <?php echo "2." . $Quest2; ?>

   <?php echo $RDO1b; ?>
        <input type = "radio" name="2">

   <?php echo $RDO2b; ?>
            <input type = "radio" name="2">

   <?php echo $RDO3b; ?>
            <input type = "radio" name="2">

   <?php echo $RDO4b; ?>
            <input type = "radio" name="2">

 <?php echo "3." . $Quest3; ?>

  <?php echo $RDO1c; ?>
        <input type = "radio" name="3">

  <?php echo $RDO2c; ?>
        <input type = "radio" name="3">

   <?php echo $RDO3c; ?>
        <input type = "radio" name="3">

   <?php echo $RDO4c; ?>
        <input type = "radio" name="3">

 <?php echo "4." . $Quest4; ?>

  <?php echo $RDO1d; ?>
        <input type = "radio" name="4">

  <?php echo $RDO2d; ?>
        <input type = "radio" name="4">

 <?php echo $RDO3d; ?>
        <input type = "radio" name="4">

  <?php echo $RDO4d; ?>
        <input type = "radio" name="4">

 <?php echo "5." . $Quest5; ?>

  <?php echo $RDO1e; ?>
        <input type = "radio" name="5">

  <?php echo $RDO2e; ?>
        <input type = "radio" name="5">

  <?php echo $RDO3e; ?>
        <input type = "radio" name="5">

  <?php echo $RDO4e; ?>
        <input type = "radio" name="5">

 <?php echo "6." . $Quest6; ?>

  <?php echo $RDO1f; ?>
        <input type = "radio" name="6">

  <?php echo $RDO2f; ?>
        <input type = "radio" name="6">

  <?php echo $RDO3f; ?>
        <input type = "radio" name="6">

  <?php echo $RDO4f; ?>
        <input type = "radio" name="6">

 <?php echo "7." . $Quest7; ?>

  <?php echo $RDO1g; ?>
        <input type = "radio" name="7">

  <?php echo $RDO2g; ?>
        <input type = "radio" name="7">

  <?php echo $RDO3g; ?>
        <input type = "radio" name="7">

  <?php echo $RDO4g; ?>
        <input type = "radio" name="7">

 <?php echo "8." . $Quest8; ?>

  <?php echo $RDO1h; ?>
        <input type = "radio" name="8">

  <?php echo $RDO2h; ?>
        <input type = "radio" name="8">

  <?php echo $RDO3h; ?>
        <input type = "radio" name="8">

  <?php echo $RDO4h; ?>
        <input type = "radio" name="8">

<?php echo "9." . $Quest9; ?>

   <?php echo $RDO1i; ?>
        <input type = "radio" name="9">

   <?php echo $RDO2i; ?>
        <input type = "radio" name="9">

  <?php echo $RDO3i; ?>
        <input type = "radio" name="9">

   <?php echo $RDO4i; ?>
        <input type = "radio" name="9">

 <?php echo "10." . $Quest10; ?>

  <?php echo $RDO1j; ?>
        <input type = "radio" name="10">

  <?php echo $RDO2j; ?>
        <input type = "radio" name="10">

  <?php echo $RDO3j; ?>
        <input type = "radio" name="10">

  <?php echo $RDO4j; ?>
        <input type = "radio" name="10">

<?php

$sql = "SELECT QUESTIONS FROM questionsmath WHERE B = '-5'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

$Quest1M = $row[0];

?>

A: You should post only the code that matters to the question. Posting the complete php/js code will only distract us and prevent people from finding the problem and helping.
Saying that, and as I pointed out in my comment to your question, if you don't mind letting javascript "know" which answers are correct and which are wrong, then you can just simply give the correct answers a class, like correct and later when the form is submitted, you can do a count of all radio buttons that were checked and are marked as correct behind the scenes.
I am not sure why you would want to do it on the client side, since the HTML markup code can be inspected, and people can know which answers are correct. But if that is not a concern to you, then here is one way to achieve it:

document.getElementById("btn-check").addEventListener("click", function() {
  let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length;
  console.log("Correct Answers: " + numberOfCorrectAnswers);
});
.question {
  display: block;
  color: navy;
  background-color: #def;
}

What is the sum of 11+33?

  <input class='wrong' type='radio' name='q1' />45

  <input class='correct' type='radio' name='q1' />44

  <input class='wrong' type='radio' name='q1' />47

  <input class='wrong' type='radio' name='q1' />42

What is the sum of 3+5?

  <input class='wrong' type='radio' name='q2' />2

  <input class='wrong' type='radio' name='q2' />4

  <input class='wrong' type='radio' name='q2' />6

  <input class='correct' type='radio' name='q2' />8

<button id='btn-check'>Check Number of Correct Answers</button>


text:
Q: How to connect to dashdb with node.js httpRequest How can we connect to Dash DB using HTTP/Request module of node.js and execute R-script code. I am able to do it using Node-RED but like to do it programmatically. Right now I am getting this error:
0530 [App/0] ERR Potentially unhandled rejection [2] Error: EACCES, mkdir '/home/nol'
0530 [App/0] OUT STATUS: 500
0530 [App/0] OUT HEADERS: {""content-type":"text/html; charset=UTF-8","set-cookie":Path=/; Secure; HttpOnly"],"connection":"Close", ""}
0530 [App/0] OUT BODY:
0530 [App/0] OUT An internal error has occurred. The application may still be initializing or the URL used is invalid. Check the URL and try again. For more information, view the server log files.

Below is my code :
  var options = {
  hostname: 'bluemix05.bluforcloud.com',
  host:'50.97.93.115',
  port: 8443,
  path: ':/console/blushiftservices/BluShiftHttp.do',
  method: 'POST',
  username: 'xxxxxxxxx',
  password: 'xxxxxxxxx',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization' : 'Basic ' + new Buffer(username + ':' + password).toString('base64')
  }
};
var postData = querystring.stringify({
  'msg' : 'cmd=RScriptRunScript&command=library\(ibmdbR\)\ncon <- idaConnect(\"BLUDB\",\"\",\"\")\nidaInit(con)\nSUB_NUM <- c\(0877777777\)\nPAST_YR_AVG <- c\(300\)\nTestUsageTable1<- data.frame \(SUB_NUM,PAST_YR_AVG,stringsAsFactors=FALSE\)\nsqlSave\(con, TestUsageTable1, rownames=FALSE,safer=FALSE,append=TRUE\)&profileName=BLUDB'
});
var req = http.request(options, function (res) {
                             console.log('STATUS: ' + res.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(res.headers));
                             res.setEncoding('utf8');
                             res.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                               loggererror.info('STATUS: ' + res.statusCode);
                           });

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
  loggererror.info('Status: ' + e.message);
});

req.write(postData);
req.end();

A: I modified the code and made it more similar to the node-red http code (make sure you update your username, password and url to match your dashDB instance before testing the code):
var https = require("follow-redirects").https;
var urllib = require("url");

var options = urllib.parse('https://awh-yp-small03.services.dal.bluemix.net:8443/console/blushiftservices/BluShiftHttp.do');
options.method = 'POST';
options.headers = {"content-type": "application/x-www-form-urlencoded"};
options.auth = '<username>:<password>';

var postData = 'cmd=RScriptRunScript&command=library\(ibmdbR\)\ncon <- idaConnect(\"BLUDB\",\"\",\"\")\nidaInit(con)\nSUB_NUM <- c\(0877777777\)\nPAST_YR_AVG <- c\(300\)\nTestUsageTable1<- data.frame \(SUB_NUM,PAST_YR_AVG,stringsAsFactors=FALSE\)\nsqlSave\(con, TestUsageTable1, rownames=FALSE,safer=FALSE,append=TRUE\)&profileName=BLUDB';

var req = https.request(options, function (res) {
                             console.log('STATUS: ' + res.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(res.headers));
                             res.setEncoding('utf8');
                             res.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                               //loggererror.info('STATUS: ' + res.statusCode);
                           });

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
  //loggererror.info('Status: ' + e.message);
});

req.write(postData);
req.end();

My result is this:
STATUS: 200
HEADERS: {"x-powered-by":"Servlet/3.0","content-type":"text/json; charset=UTF-8","content-language":"en-US","content-length":"857","set-cookie":["dsweb11082=0000Pv6OYa62mRxurvYa6c2_5of:31d3d6bb-82d3-44ca-8db8-ac929c09de05; Path=/; Secure; HttpOnly"],"connection":"Close","date":"Wed, 14 Oct 2015 22:11:27 GMT","server":"WebSphere Application Server","expires":"Thu, 01 Dec 1994 16:00:00 GMT","cache-control":"no-cache=\"set-cookie, set-cookie2\""}
BODY:
{"message":"","cmd":"RScriptRunScript","errorMessageCode":"","items":"{\"RModelOutput\":\"\",\"filename\":[],\"workingDirectory\":\"\\\/opt\\\/ibm\\\/dsserver\\\/Config\\\/RModels\\\/Pv6OYa62mRxurvYa6c2_5of\\\/1444860685812\",\"RModelError\":\"Loading required package: RODBC\\nLoading required package: ibmdbR\\nLoading required package: methods\\nLoading required package: MASS\\nLoading required package: grDevices\\nLoading required package: graphics\\nLoading required package: stats\\nLoading required package: utils\\nLoading required package: Matrix\\nLoading required package:
BODY:  arules\\n\\nAttaching package: \\u2018arules\\u2019\\n\\nThe following objects are masked from \\u2018package:base\\u2019:\\n\\n    %in%, write\\n\\nLoading required package: rpart\\nWarning message:\\nclosing unused RODBC handle 1 \\n\"}","resultcode":"success"}


text:
Q: JavaScript on body overflow? I created a contextmenu in my Website, that shows up on right click.
In that contextmenu I've got some submenus that will aply on the right site of the menu.
The problem is now that if you call up the contextmenu on the right side of the page, there isn't enough space left to display the submenus, and the browser adds a horizontal scrollbar.
Is there any JavaScript command or else where you can change the position of the submenus in the CSS, if there isn't enough space left in the browser?

A: a draft of what you can do can be found live on JsBin
You can easily get the position of the mouse and check it again the document width.
code uses jQuery for simplicity.
$(document).mousemove(function(e){

  var CONTEXT_MENU_WIDTH = 200,
      pos = 'RIGHT';
  if( ($(document).width() - CONTEXT_MENU_WIDTH) < e.pageX )
    pos = 'LEFT';

  $('#status').html(e.pageX +', '+ e.pageY);
  $('#position span').html(pos);

});

Edited
just added a simple vertical line to help with the position.
CONTEXT_MENU_WIDTH variable should be the area width that you want the context menu change position.


text:
Q: From six randomly generated values (1-6) in a array , some code that would run to see how many match in value and which ones match This is for an intro to comp sci class that I am taking, we have to input a number that will be that number of times a die is rolled. Then we are supposed to record how many times that each number is rolled. I am fine up to that point, the problem part is now we have to see if one number was rolled more times that the others, and if there are ties for the most rolled.
Ie.
(user inputs --> 5) die is rolled 5 time. 1 is rolled 2 times, 2 is rolled 1 time, 3 is tolled 2 times.
The computer would print out: "There was a tie for most times rolled between 1 and 3, they were both rolled 2 times.
Any Feedback would be greatly appreciated, thank you!

A: The first time you go through the dice values, find the maximum number of times a value has been rolled. If 1 has been rolled 3 times, 2 has been 4 times, and 3 has been rolled 2 times, then the maximum would be 4.
Now we go through the dice values again, and if the current value has been rolled the same amount as the maximum we previously calculated, that means that this value was rolled the most.
An example: 1 was rolled 3 times, 2 was rolled 3 times, 3 was rolled 4 times, 4 was rolled 7 times, 5 was rolled 7 times.
We first go through the values and find the maximum number of times a value has been rolled, which in this case is 7 times.
Next, we go through the values again, and see which values are equal to that maximum. Values 4 and 5 have both been rolled 7 times. Therefore, 4 and 5 are the maximum, and you would output that they are tied.

A: After generating your array of random numbers, you should go through it and tally the number of times each number was rolled in another array.  Then, you can go through this new array and find the max number(s) to display to the user.  Here's my example:
        int numRolls;
        // get user input for number of rolls
        // ...

        int[] diceRolls = new int[numRolls];
        // generate your rolls here, each element in diceRolls represents a roll
        // ...

        // tally number of times each roll occurs in array
        int[] timesRolled = new int[6];

        for (int i = 0; i < numRolls; i++) {
            timesRolled[diceRolls[i] - 1]++;
        }

        // find the max of timesRolled
        int maxPos = 0;
        for (int i = 1; i < 6; i ++) {
            if (timesRolled[i] > timesRolled[maxPos]) {
                maxPos = i;
            }
        }

        System.out.println("The number rolled the most was " + (maxPos + 1) +
                " which was rolled " + timesRolled[maxPos] + " times.");

This code does not handle ties.
Also, unless it is required by the assignment, there is no reason for you to be storing each individual die roll.  Instead, you could generate a roll, then directly add 1 to its corresponding position in timesRolled, then generate the next roll, add 1 to that roll's counter... and so on.
EDIT:  I see now that I misread which part you needed help with.  As for handling ties, there's a couple ways to do it.  I would build a results string that was something like "The number(s) rolled the most were: " and then add to that the highest number, and any numbers that it tied with.  That way you don't need to store the tying numbers, you can just build the string as you check for ties.


text:
Q: How to print memory address of a defined constant in C++ Code:
#include <cstdlib>
#include <iostream>
#define PI 3.14159

using namespace std;

int main(int argc, char** argv) {
    cout<<"Address of PI:"<<&PI<<endl;
    return 0;
}

Here is the output:
main.cpp: In function int main(int, char**)':
main.cpp:20: error: non-lvalue in unary&'
make[2]: * [build/Debug/Cygwin-Windows/main.o] Error 1
make[1]:  [.build-conf] Error 2
make: ** [.build-impl] Error 2
So why can't I see the memory address of PI here?
Thank you.

A: Macros are never allocated a memory. Before the code is compiled, the compiler does a text search in the file and replace all Macros with their value. Also this is a text search, so the text gets replaced. So PI gets replaced by 3.14 in your code before compiling it. As a result, the memory operator throws an error because it cannot get the value of 3.14 as it is not a variable. Hope it helps :)

A: You cannot take the address of a numeric literal. You could for a  variable, though:
// #define PI 3.14159
static const double PI = 3.14159;

A: In your code, PI does not have a memory address. Since it's a preprocessor macro, its value gets substituted everywhere PI appears in your program.
If you turned it into a variable, you'd be able to take its address:
const double PI = 3.1415926;

A: The preprocessor will replace PI by 3.14159 everywhere in your code. Hence, the number does not reside in memory.


text:
Q: Why's Remote Desktop missing? I live Toronto. I have family in China and New York. We must remotely access each's desktop. All have Windows 10.
TeamViewer falsely blocked us for commercial use. We requested Unblock, but no answer yet. I'm having issues with AnyDesk and will post later.
Anyhow pls see screen shot beneath from 0.51.

A: By default, Windows Home edition doesn't support the remote desktop feature. It's available only in the Pro and Enterprise edition.
How to check if your system supports remote desktop:

*

*Press the Windows key + I to open the Settings app, click on
System and choose the "Remote Desktop" page.

*On the right pane, you can see if the remote desktop settings are available. If
it's not available, you can click the suggested link on that page to
upgrade your Windows 10 edition.


text:
Q: Ubuntu 20.04 wouldn't connect to wifi after latest update. Reinstall 18.04 and still won't work Recently while I was running ATP - upgrade on my machine the internet stopped working for one specific Network.
Every other network connects normally. I have tried a taco-bell wifi and a hospital wifi, both worked normally.
This happened during one of the first "apt-get upgrade"s i did after updating from 18.04.5 to 20.04.
I have tried downgrading to 18.04 doing a reinstall of my ubuntu partition from the same live usb stick i installed with initially.
My machine is an HP inspiron-5755 with Intel Dual Band Wireless AC 3160
I have (with a phone app) determined that the router is manufactured by Ruckus.
The output of nmcli is as follows
colin@colin-Inspiron-5755:~$ nmcli
wlp3s0: connected to CROSSLAND 1
"Intel wireless 3160 (Dual Band Wireless AC 3160)"
wifi (iwlwifi), E4:02:9B:1C:FD:36, hw, mtu 1500
ip4 default
Inet4 172.17.19.128/16
route4 0.0.0.0/0
route4 172.17.0.0/16
route4 169.254.0.0/16
inet6 fe80::6e7a:9089:875e:6ded/64
route6 ff00::/8
route6 fe80::/64

enp2s0: unavailable
"Realtek RTL810xE PCI Express Fast Ethernet Controller"
ethernet (r8169),28:F1:0E:46:05:00, hw, mtu 1500

"lo"
loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536
DNS configuration;
servers: 4.2.2.1
domains: globalsuite.net
Lines 1-23

colin@colin-Inspiron-5755:~$ lscpi -knn | grep net -A3; rfkill list
03:00.0 network controller [0280]: intel corporation wireless 3160 [8086:8470] (rev 83)
Subsystem: Intel corporation dual band wireless AC 3160 [8086:8470]
Kernel driver in use: iwlwifi
Colonel modules: iwlwifi
0: dell-rbtn: wireless LAN
Soft blocked: no
Hard blocked: no
1: phy0: wireless LAN
Soft blocked: no
Hard blocked: no
2: hci0: Bluetooth
Soft blocked: no
Hard blocked: no

A: It seemed to be some sort of error on their part where I was unable to reach the Wi-Fi login page. The support for the hotel I was staying at was able to ping my computer, and get me manually connected.


text:
Q: Regex Search In Files using Java What I ask here should be pretty common but my intent is to figure out the best possible way to do it.

*

*I have a list of files(say n) within a directory - all of which have
been categorized by extensions.

*I have a csv file containing Regex patterns(say m) which I want to look for in all those files of a particular type.

*I want to have a final output wherein I have a Regex pattern, file name,
line and line number listed.

Here are the few questions I have about how I should approach this:

*

*Is there a way where I could avoid m*n operations?

*What's faster - reading the files, buffering content and storing each line in say in an array before a search for all regex expressions or should I be taking a regex pattern, read the file line by line and search as I parse without using up memory?

*I figure that read/write operations are the most taxing - hence, I want to have 'n+1' reads(files, csv) and just a single write at the very end. Is my assumption and approach here correct?

*Arrays, Lists, hashmaps, something else - any suggestion on what would be the best way to have the task done? I think parsing files would be the key to efficiency?

*Any particular 'uncommon' Java APIs that I can make use of which reduce the code significantly?

I appreciate any insight/help with respect to this question.
.

A: Write a simple working solution first, then optimize it.  That said, I think you might be able to do something like:

*

*Construct a composite regex from each of the individual regexes that you're searching for.  If they don't use capturing patterns, I suspect you could just do something like "(regex1)|(regex2)|(regex3)" and that'd be valid.  I'm not positive, though -- I've never been clear on how regex capturing groups work in when they're in different | branches.

*Use Pattern.compile(regexString) to precompile the regex so it's not rebuilt more than once.

*Use Guava's Files.toString(File, Charset) to just slurp each file all at once.  If you're that keen on doing it line-by-line, use Files.readLines(File, Charset) to get a List<String>.  You might even use the full-blown callback-based Files.readLines(File, Charset, LineProcessor) to avoid having the whole file in memory at once.

*Use the compiled Pattern to match against the target file -- you'll probably need to use the Matcher to identify where exactly the match was, and which pattern was matched.


text:
Q: How to get Ember component object inside promise success or error call back? I have pass two callback function success and error on promise returned from ajax call using then method. Now i am unable to get Ember component object inside success/error method.
import Ember from 'ember';

export default Ember.Component.extend({
    data:null,
    issueType:'',
    description:null,
    prepareSubmitRaiseIssueModal:function(){
        var data = this.get('data');
        this.set('ticket.category',data.category);
        this.set('ticket.name',this.get('session.currentUser.first_name'));
        this.set('ticket.phone',this.get('session.currentUser.phone'));
        this.set('ticket.groupId',data.groupId);
        this.set('ticket.ownerId',this.get('session.currentUser.id'));
        this.set('ticket.oyoId',this.get('session.currentOwnerHotelOyoId'));
        this.set('ticket.ticketRaisedBy','owner');
        this.set('ticket.bookingId',data.bookingId);
        this.set('ticket.subType',data.subType);
        this.set('ticket.subSubIssue',data.subSubIssue);
        this.set('ticket.email',this.get('ticket.oyoId')+'@oyoproperties.com');
        this.set('ticket.subject',this.get('ticket.oyoId')+' : '+this.get('ticket.category'));
        this.set('ticket.description',this.get('description'));
    },
    success:function(){
        console.log(this.get('description'));
    },
    error:function(){
        console.log(this.get('description'));
    },
    actions :{
        submitIssue:function(){
            this.prepareSubmitRaiseIssueModal();
            this.get('ticket').submitRaiseIssue().then(this.success,this.error);
            //this.send('closeRaiseIssueModal');
        },
        closeRaiseIssueModal:function(){
            this.sendAction('closeRaiseIssueModal');
        }
    }
});

i am able to get Ember component object if instead of passing named function i pass anonymous function.
submitIssue:function(){
            var self = this;
            this.prepareSubmitRaiseIssueModal();
            this.get('ticket').submitRaiseIssue().then(function(response){
                console.log(self.get('description'));
            },
            function(err){
                console.log(self.get('description'));
            });
            //this.send('closeRaiseIssueModal');
        },

is there any way i can get the Ember component object's reference for former case??

A: Wow speaking of a spaghetti.
prepareSubmitRaiseIssueModal:function(){
        var data = this.get('data');
        this.set('ticket.category',data.category);
        this.set('ticket.name',this.get('session.currentUser.first_name'));
        this.set('ticket.phone',this.get('session.currentUser.phone'));
        this.set('ticket.groupId',data.groupId);
        this.set('ticket.ownerId',this.get('session.currentUser.id'));
        this.set('ticket.oyoId',this.get('session.currentOwnerHotelOyoId'));
        this.set('ticket.ticketRaisedBy','owner');
        this.set('ticket.bookingId',data.bookingId);
        this.set('ticket.subType',data.subType);
        this.set('ticket.subSubIssue',data.subSubIssue);
        this.set('ticket.email',this.get('ticket.oyoId')+'@oyoproperties.com');
        this.set('ticket.subject',this.get('ticket.oyoId')+' : '+this.get('ticket.category'));
        this.set('ticket.description',this.get('description'));
    },

How about
prepareSubmitRaiseIssueModal:function(){
        var data = this.get('data');
        var ticket = this.get('ticket')
        ticket.setProperties({
           'category': data.category,
           'name': ...
        })

    },

And to pass reference's you can either use
promise.then(function() {
     this.mysuccess();
}.bind(this), function() {
     this.myerror();
}.bind(this))

const self = this;
promise.then(function() {
    self.blah();
});

promise.then(result => {
    this.blah();
})

In your case I would write a utility JS file for displaying notifications.
And handle success for each promise personally and let errors be handled in a general error method.
utils/notifications.js
function reportError(error) {
    displayNotification('error', getErrorMessage(error));
}

import reportError from 'utils/notifications';

export default Ember.Controller.extend({
....
promise.then(result => {
   // Do custom stuff with result;
}, reportError);
....
});

And promise within a promise
return promise1.then(x => {
   return promise2.then(x2 => {
       return promise3 ... etc
   })
}).catch(reportError); // Single hook needed but u need to return promises


text:
Q: Synchronizing copied repository with GIT repository I have copied repository from my team member and I want to synchronize with GIT repository.
Please keep in mind that I am new to GIT and I only have URLs of the repository where I need to synchronize. I need help to connect my repository with GIT repository. I have not imported any repository and I have just copied that. I will be able to push or pull or merge etc. only if my project is synchronized with remote repository. Please let me know that how can I synchronize. Thanks

A: It's unclear from your question whether you are trying to simply keep two copies of the same repository synchronized or something else.
If it's the first, then what you want to do it a git clone. Your changes should be git commit, to get remote changes you should git pull and to push your changes to your co-worker's repository, you should git push.
Depending on your operating system, there are different front-ends for Git. I gave you the command-line version. I saw you tagged your questions with the eclipse tag, which suggests you are trying to do this inside Eclipse. In that case, you might find EGit useful. See the EGit User Guide here.
If all this sounds too complex for you, you should first Read The Manual - that is, check out the Getting Started chapter of the Git Documentation.

A: I found the solution. I had to go in team-> share projects. then "create a new repository location" and paste the url of git repository. then team->share project-> git and add the repository. Now my copied repository is linked/connected with my git repository and I am able to synchronize my repository.


text:
Q: handling height of the image which is set as a background using :before pseudo element using jquery I have created one navigation bar using bootstrap and jquery. In my navigation   bar their is one background image, which is left to the logo.I am facing problem during mobile view,the problem is:In mobile,on click of hamburger icon,when navigation menu get collapse and expand,that same time i need to increase and decrease height of that background image which is left to the logo.
below is link jsfiddle link:https://jsfiddle.net/gbhopale/utb6adyp/3/
HTML Code:

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mydiv">

      </button>

Register

          Account

            Update Provider Information
            Register New Provider
            Reset Password
            Update Account Information

Home

About

Contact

 Logoff


text:
Q: what is the good way to sync and test the application server deployed on aws, using git? I am currently new to aws, usually I use putty as the console to debug the program, and use winscp to upload the new code to the server, but using winscp to update the server is kind of inefficient, I want to know if there is a easy, fast way allowing me to sync the code to the testing server deployed in the amazon instance.
something comes to my mind, is probably the git, I don't know how to do it in both sides, that once I update the repository locally to git server, the git server will automatically update the code to my testing server on aws
or if you have a better way than git

A: Once you push the code to your git or github repo, you need to ssh to your server and pull the code. To achieve that, first generate the ssh key in your aws instance follow [this][1] instructions. Once your initial test says okay, then git clone your application to the desired path. Once you clone it update the app with the latest using git pull command.


text:
Q: Cannot retrieve correct checkbox value after it is clicked with jQuery I have a checkbox. I have assigned a click-event to the checkbox. In the method that is called I want to see if the checkbox is checked or not. The expected result is that if the checkbox is not checked and I click it, in the method the checked value should be "true" and vice versa. I can't get this result with my code. I always get "false" as checked. How can I solve this?
Am I using the wrong event?
I use jQuery 1.8.2
My code:
$(document).ready(function () {
  $(".UpdateCheckboxInstant").change(UpdateInstant);
});

function UpdateInstant() {
  //var checked = $(".UpdateCheckboxInstant").is(":checked");
  var checked = $(this).is(":checked");
  alert(checked); // this always says "false" :(
}

A: Take a look at this on jsFiddle. I think it actually works for me.
<input type="checkbox" class="UpdateCheckboxInstant" />

$(document).ready(function () {
  $(".UpdateCheckboxInstant").change(UpdateInstant);
});
function UpdateInstant() {
  //var checked = $(".UpdateCheckboxInstant").is(":checked");
  var checked = $(this).is(":checked");
  alert(checked);
}


text:
Q: How to handle a variable amount of buttons clicked? I have a pretty basic problem with button clicks in VB.Net I cannot seem to figure out.
First, I am creating a variable amount of buttons and adding them to the parent form.
Private Sub CreateUIObjects()
    For i As Integer = 1 To NumberOfButtons
        Dim button As Button = New Button()
        Me.Controls.Add(button)
    Next
End Sub

I know it is possible to handle a fixed amount of buttons clicked with the following code
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Handles Button1.Click, Button2.Click, Button3.Click '... And so on
        Dim b As Button = CType(sender, Button)

End Sub

But what do I do with not 3, but a variable amount of buttons?

A: You can use something like this
AddHandler Button1.Click, AddressOf Button_Click

take a look http://msdn.microsoft.com/en-us/library/ms172877.aspx

A: Some code to experiment with
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    CreateUIObjects(3)
End Sub

Dim myButtonNames As String = "foobar"
Private Sub myButtonsClick(sender As Object, e As EventArgs)
    Dim b As Button = DirectCast(sender, Button)
    Debug.WriteLine(b.Name)
End Sub

Private Sub CreateUIObjects(NumberOfButtons As Integer)
    Static ct As Integer = 0
    For i As Integer = 1 To NumberOfButtons
        ct += 1
        Dim btn As Button = New Button()
        btn.Name = myButtonNames & ct.ToString
        btn.Text = btn.Name
        btn.Location = New Point(ct * 20, ct * 20)
        AddHandler btn.Click, AddressOf myButtonsClick
        Me.Controls.Add(btn)
    Next
End Sub


text:
Q: prove that the following sequence converges to infinity given the inductive sequence $a_1 = 1$; $a_{n+1} = a_n+\frac{1}{a_n}$ I had to prove that $lim_{n\to\infty}a_n \to \infty$.
I proved it by the following way, but I'm not sure I did everything ok so I would appreciate your feedback.
At first, I prove $(a_n)$ is monotonically increasing by induction, in short I assume $a_{n+1} >a_n$ and prove that also $a_{n+2} >a_{n+1}$ as following:
$a_{n+2} = a_{n+1} + \frac{1}{a_{n+1}} = a_{n} + \frac{1}{a_{n}}+\frac{1}{a_{n+1}} \ge a_{n} + \frac{1}{a_{n}} = a_{n+1}$ as needed, thus monotonically increasing.
Secondly, I would like to show that $(a_n)$ converges to +$\infty$. So I have to show that for every $0<M\in R$ exists N such that for every natural n>N, $a_n>M$. =====> I choose N = $a_n$ = M, So I get $a_{n+1} = a_n + \frac{1}{a_n} = M + \frac{1}{M} > M$ as needed.
In conclusion, I get that $(a_n)$ is monotonically increasing and unbounded from above, thus it converges to +$\infty$
by the way I'm 100% sure the thing I did with N=an = M is wrong, or at least semantically is wrong..

A: $N=a_n=M$ does not make sense, really. When reading, I have no idea what you did.
You have $M$, and you want to find $N$. The value of $N$ must be defined only in terms of $M$, and if you set $N=M$, you must prove that $a_N>M$, and you did not prove that.
My advice to solving the problem is different:
You already know that $a_n$ is increasing, meaning that it either converges or diverges to $\infty$. Now, assume that it converges, and find a contradiction. Do this by proving that all candidates for a limit are wrong.
Another hint:
Remember, if $a_{n+1} = a_n + \frac1{a_n}$, then what happens if you sent $n\to\infty$ on both sides?


text:
Q: AEM 6.1 classic UI dialog to touch UI dialog customization in JS for Multifield I am working on converting classic UI dialog to touch UI dialog in AEM 6.1.
I have a multifield dialog which is working fine in classic UI, I want to customize the js to convert it to touch UI. But

*

*The multifield is not storing the values from the JS. Instead, it is displaying empty values.

*Also, the Article Heading field in the dialog is a required field and dialog shouldn't be exit if it is empty, but the required functionality is not working with the touch UI.

I tried the following JS but couldn't understand what the problem is.
(function ($, $document) {
    "use strict";

    var _ = window._, Class = window.Class;

    ACS.TouchUI.MultiCompositeMultiField = new Class({
        toString: 'AARP Composite Multifield Store as Multi Value Field',
        extend: ACS.TouchUI.Widget,
        MULTI_VALUE_STORE: "MULTI_STORE",
        isMulti: false,

        getMultiFieldNames: function(){
            var cmf = this, mNames = {}, mName, $multifield, $template,
                $multiTemplates = $(".js-coral-Multifield-input-template");

            $multiTemplates.each(function (i, template) {
                $template = $(template);
                $multifield = $($template.html());
                if(!cmf.isMultiValueStore($multifield.data(cmf.ACS_COMMONS_NESTED))){
                    return;
                }
                this.isMulti = true;
                mName = $multifield.data("name").substring(2);
                mNames[mName] = $template.closest(".coral-Multifield");

            });

            return mNames;
        },

        buildMultiField: function(data, $multifield, mName){
            var cmf = this;

            if(_.isEmpty(mName) || _.isEmpty(data)){
                return;
            }

            _.each(data, function(value, key){
                if(key === "jcr:primaryType"){
                    return;
                }
                var currentElements = $multifield.find("li.coral-Multifield-input").length;

                if( Object.prototype.toString.call( value ) === '[object Array]' ) {
                    var numberOfElements = value.length;
                    if (numberOfElements > currentElements) {
                        var newNum = numberOfElements - currentElements;
                        currentElements = numberOfElements;
                        for (var i=0; i< newNum; i++) {
                            $multifield.find(".js-coral-Multifield-add").click();
                        }
                    }
                    var elementParts = {
                    key: key,
                    container: mName
                    };
                    _.each(value, function(fValue, index) {
                        var $field = $multifield.find("[name='./"+mName+"/" + this.key + "']").eq(index);

                        if(_.isEmpty($field)){
                            return;
                        }
                        cmf.setWidgetValue($field, fValue);
                    }, elementParts);
                } else {
                    if (currentElements === 0) {
                        $multifield.find(".js-coral-Multifield-add").click();
                    }
                    var $field = $multifield.find("[name='./"+mName+"/" + key + "']");

                    if(_.isEmpty($field)){
                        return;
                    }
                    cmf.setWidgetValue($field, value);
                }

            }, mName);
        },

        addDataInFields: function () {
            var cmf = this, mNames = cmf.getMultiFieldNames(),
                $form = $("form.cq-dialog"),
                actionUrl = $form.attr("action") + ".infinity.json";

            $.ajax(actionUrl).done(postProcess);

            function postProcess(data){
                _.each(mNames, function($multifield, mName){
                    cmf.buildMultiField(data[mName], $multifield, mName);
                });

                $document.trigger("touchui-composite-multifield-nodestore-ready", mNames);
            }
        },

        getMultiValueStoreMultifields: function(){
            return $("[" + this.DATA_ACS_COMMONS_NESTED + "='" + this.MULTI_VALUE_STORE + "']");
        },

        isMultiValueStore: function(name){
            return (name === this.MULTI_VALUE_STORE);
        },

        collectDataFromFields: function(){
            if (!this.isMulti) {
                return;
            }

            var $multifields = this.getMultiValueStoreMultifields();

            if(_.isEmpty($multifields)){
                return;
            }

            var $form = $("form.cq-dialog"), $fields,
                cmf = this;

            $multifields.each(function(counter, multifield){
                $fields = $(multifield).children().children(cmf.CFFW);

                $fields.each(function (j, field) {
                    fillValue($form, $(multifield).data("name"), $(field).find("[name]"), (counter + 1));
                });
            });

            function fillValue($form, fieldSetName, $field, counter){
                var name = $field.attr("name"), value;

                if (!name) {
                    return;
                }

                //strip ./
                if (name.indexOf("./") === 0) {
                    name = name.substring(2);
                }

                value = $field.val();

                if (cmf.isCheckbox($field)) {
                    value = $field.prop("checked") ? $field.val() : "";
                }

                //remove the field, so that individual values are not POSTed
                $field.remove();
                $('<input />').attr('type', 'hidden')
                    .attr('name', fieldSetName +"/" + name+"["+counter+"]")
                    .attr('value', value)
                    .appendTo($form);
            }
        }
    });

    $document.ready(function () {
        var compositeMultiField = new ACS.TouchUI.MultiCompositeMultiField();

        $document.on("dialog-ready", function(){
            compositeMultiField.addDataInFields();
        });

        $document.on("click", ".cq-dialog-submit", function(){
            compositeMultiField.collectDataFromFields();
        });
    });
}(jQuery, jQuery(document)));


text:
Q: Proving $\lim_{x \rightarrow 2} \sqrt[3]{x} = \sqrt[3]{2} $ using $\epsilon - \delta$ definition I'm trying to use the $\epsilon$ - $\delta$ definition to show that  $\lim_{x \rightarrow 2}  \sqrt[3]{x} =  \sqrt[3]{2}$ .
$\forall \epsilon>0,  \exists \delta >0$ s.t. if $0< | x-2 |  < \delta$  then  $|  \sqrt[3]{x}  - \sqrt[3]{2} | < \epsilon$.
I'm not at all sure how to do this but...
 $\sqrt[3]{2}-\epsilon < \sqrt[3]{x} < \epsilon+\sqrt[3]{2}$
$\Rightarrow$ $(\sqrt[3]{2}-\epsilon)^3 <x< (\epsilon+\sqrt[3]{2})^3$
and $2-\delta < x < \delta + 2$.
But now i'm stuck. If i say that $2-\delta = (\sqrt[3]{2}-\epsilon)$ and $\delta + 2 = (\epsilon+\sqrt[3]{2})^3$, then $\delta$ could be $2-(\epsilon+\sqrt[3]{2})^3$ or $(\epsilon+\sqrt[3]{2})^3 -2$...... How do i know which is the smaller of the two?
Also this felt like a very complicated way to prove this. Is there any way to make $|  \sqrt[3]{x}  - \sqrt[3]{2} |$ seem more like | x-2 |???

A: lemma:${a^3}-{b^3}=(a-b)(a^2+ab+b^2)$
now, let$a^3=x,b^3=2$,then,we have $x-2=(\sqrt[3]{x}-\sqrt[3]{2})(x^\frac{2}{3}+\sqrt[3]{2x}+2^\frac{2}{3})$,
thus,$\sqrt[3]{x}-\sqrt[3]{2}=\frac{x-2}{x^\frac{2}{3}+\sqrt[3]{2x}+2^\frac{2}{3}}$.
using  $\epsilon-\delta$ definition as below,
for all $\epsilon>0$,exists $\delta>0$ , such that if  $0<|x-2|<\delta$,let$\delta=1/2$ ,$|\sqrt[3]{x}-\sqrt[3]{2}|=|\frac{x-2}{x^\frac{2}{3}+\sqrt[3]{2x}+2^\frac{2}{3}}|<\frac{|x-2|}{2^\frac{2}{3}}<\frac{\delta}{2^\frac{2}{3}}<\epsilon$. it is trivial to find that $\delta=min{\{2^\frac{-2}{3}\epsilon,1/2}\}$ is satisfied.


text:
Q: How to make current cell in column C according to value of the cell in A This is very confusing to explain so please excuse if I don't explain well enough.
In column A have Person name.
in Column C is where formula goes.
if cell A2:A10 start with letter Q then c2:c10 will be = E2:E10

if cell A11:A20 start with letter B then c11:c20 will be = G2:G10

QData & Bdata is random column Lenth
I tried writting 1 line formula but it didn't work.
in c2  and drag formula down
=if(left(a2,1)="Q",O2,if(left(a2,1)="B",P2,"mORE IF COND"))

A: If I understand the input correctly - you need smth like this:
=IF(LEFT(A2,1)="Q",INDIRECT("O"&ROW(A2)),IF(LEFT(A2,1)="B",INDIRECT("P"&ROW(A2)),A2))

Please add instead of A2 any output you like if cells in A match neither "Q" nor "B".
EDITED Update as per changed reqs:
=IF(LEFT(A2,1)="Q",INDIRECT("O"&ROW(A2)),IF(LEFT(A2,1)="B",INDIRECT("P"&(1+COUNTIF($A$2:A2,"Boy"))),A2))

Sample file: https://www.dropbox.com/s/izrjcvgix752klw/QueenBoyIF.xlsx