Q: Flutter animations: how to keep position of parent widget I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?
I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });

These are the circles:
Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!

A: Output:

Full code:
Column(
  children: <Widget>[
    Container(
      margin: EdgeInsets.only(top: 16.0),
      child: Center(
        child: Text(
          'Circles',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ),
    Container(
      height: 200,
      margin: EdgeInsets.only(top: 8.0),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          ),
          Spacer(),
          AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return GestureDetector(
                onTap: () {
                  _animationController.forward();
                },
                child: Container(
                  width: MediaQuery.of(context).size.width * _animation.value,
                  height: MediaQuery.of(context).size.height * _animation.value,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
                ),
              );
            },
          ),
          Spacer(),
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          )
        ],
      ),
    ),
  ],
);

A: first i suggest you delete mainAxisSize: MainAxisSize.min, if that didn't work, try to wrap the animated builder with a container and give it the same proprities as those


Q: Кнопка отправки данных Mysql Суть проблемы заключается в кнопке. Как должна работать она? Кнопка должна быть не активна,до тех пор,пока пользователь не выполнит капчу.После того,как капча была выполнена,кнопка должна быть активна и после нажатия пользователю зачислялся +1 пойнт на баланс. Но кнопка не работает вообще.Ничего не происходит.Почему? Непонятно.Прошу помощи!
Код кнопки:
    <form action="pay" method="post">

      <input name="moneycaptcha_code" id="moneycaptcha_code" type="hidden" value="">
    </form>

    <input type="submit" value="Отправить данные" name="moneycaptchabottom" id="moneycaptchasubmit" title="Вам необходимо правильно ответить на капчу"></>

Код,который должен выполняться после нажатия на кнопку:
   <?php

   if(!isset($Functions)){
     die("Error! 404");
   }

   $user = $Functions->getUser();
   $payment = '1';

   if(isset($_POST['moneycaptchabottom']) {
     $result = $Functions->giveMoney($user,$payment);
   }

   if (isset($_POST['moneycaptcha_code'])) {
     $handle = curl_init();
     curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($handle, CURLOPT_URL, "https://moneycaptcha.ru/valid.php?code=$_POST[moneycaptcha_code]");
     curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
     $status = curl_exec($handle);
     if ( $status === false ) echo "
" . curl_error($handle);
       curl_close($handle);
       $xml = simplexml_load_string($status);

       if ($xml->code == "1"){ //Здесь обработчик клиента}
     }//Конец обработчик клиента
   }

A: Кнопка не внутри тэга формы. Если так надо что бы кнопка была вне формы, то нужно указать id формы, и проставить его в параметр в form кнопки.


Q: How to send a message or event into Server Unity3D? I am learning about Networking in Unity. I am confused on how can I send a message or event from client to server. I have these script already that successfully connect my client to server.
This is my server script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class ServerNetwork : MonoBehaviour {

    void Start()
    {
        SetupServer();
    }

    // Create a server and listen on a port
    public void SetupServer()
    {

        NetworkServer.Listen(4444);
        NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected);
        Debug.Log("Server is running");
    }

    void OnClientConnected(NetworkMessage netMsg)
    {
        Debug.Log("Client connected");
        Debug.Log(netMsg.msgType);
    }
}

This is my client Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class ClientNetwork : MonoBehaviour {

    NetworkClient myClient;
    public bool isClientConnected = false;

    void Start()
    {
        SetupClient();
    }

    // Create a client and connect to the server port
    public void SetupClient()
    {
        myClient = new NetworkClient();
        myClient.RegisterHandler(MsgType.Connect, OnConnected);
        myClient.Connect("127.0.0.1", 4444);
        isClientConnected = true;
    }

    // client function
    public void OnConnected(NetworkMessage netMsg)
    {
        Debug.Log("Connected to server");
    }
}

The Server Script is attached to "NetworkManager" Object on ServerScene
The Client Script is attached to "NetworkManager" Object on ClientScene
I have build ClientScene alone to run as a client, and running ServerScene inside editor
With these script, I can already connect the client into the server. From this, how can I communicate from client to server ?
the purpose here is to send real time score into the server from client every second.
Thank You

A: You have to use [SyncVars] Attribute. In short what it does is it synchronize a variable from client to the server. Here is a simple example from Unity3d Documentation.
[SyncVar]
int health;

public void TakeDamage(int amount)
{
    if (!isServer)
        return;

    health -= amount;
}

another way to do this is by using custom WebSocket implementation for Unity3D. There a few very good ones in GitHub.Also please take a look at the documentation Unity3d


Q: Correctly get access to nested object in JavaScript I have the JS-object, that in Chrome's console looks as folllow:
data: Object
 comparisonType: "IN"
 dateValue: ""
 numericalValue: 0
 screeningCriterionId: "-4"
 screeningField.displayName: "Prop1"
 screeningField.fieldName: "Prop2"
 screeningField.groupName: "Prop3"
 screeningField.type: "MULTI"
 value: null

And I need to read the  screeningField.displayName: "Prop1"  from this object , but
trying to execute in console this  myObject.screeningField.displayName I'm getting the error:

TypeError: Cannot read property 'displayName' of undefined

How to solve my problem ?

A: Apparently the dot is actually included in the key name, try:
myObject['screeningField.displayName']


Q: How do i efficiently use redux in react making request to backend server? I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. The problem is that the request is reaching the back end and also i have been having trouble handling the axios returned promise.
Here is my action transaction.js function:
import axios from "axios";

export const CREATE_TRANSACTION = "CREATE_TRANSACTION";
export const VIEW_TRANSACTION = "VIEW_TRANSACTION";
export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION";
export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS";
export const DELETE_TRANSACTION = "DELETE+TRANSACTION";
export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA";

const ROOT_URL = "http://127.0.0.1:8000/api/";

export const getTransactionList = () => (dispatch) => {
  axios
    .get(`${ROOT_URL}transactions/`, {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((response) => {
      dispatch({ type: LIST_TRANSACTIONS, payload: response.data });
      console.log(response.data);
    });
};

Here is my reducer transactions.js function:
import { LIST_TRANSACTIONS } from "../actions/transaction";

export function TransactionReducer(state = {}, action) {
  switch (action.type) {
    case LIST_TRANSACTIONS:
      return action.payload;
    default:
      return state;
  }
}

My store.js:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 })
  : compose;

const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(applyMiddleware(thunk))
);

export default store;

Trying to display data using useSelector()
import React, { useEffect } from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { useSelector, useDispatch } from "react-redux";
import { getTransactionList } from "../../actions/transaction";

export default function TransactionList() {
  const dispatch = useDispatch();
  const data = useSelector((state) => state.transactions);
  console.log(data);
  useEffect(() => {
    dispatch(getTransactionList());
  }, [dispatch]);

  return (
    <TableContainer component={Paper} sx={{ boxShadow: "none" }}>

Lastly my index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      {" "}
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();

Please any help would be greatly appreciated, REMINDER I AM NEW TO USING THESE TECHNOLOGIES. Any further information required can be provided.

A: I see a more or less correct setup. The only part I think is missing is when you do this:
const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(applyMiddleware(thunk))
);

Where is your rootReducer? I mean, I'm missing your root reducer code with something like that:
import { combineReducers } from 'redux';
import { TransactionReducer } from 'your/path/TransactionReducer';
import { fooReducer } from 'your/path/fooReducer';
import { barReducer } from 'your/path/barReducer';

export const rootReducer = combineReducers({
  transactions: TransactionReducer,
  foo: fooReducer,
  bar: barReducer,
});

It isn't it?


Q: How to remove customAnimations from childFragmentManager Android The code to apply custom animations is this, though when I pass childFragmentManager to a bottom sheet dialog fragment the same animations are applied which is not even overridding.
.childFragmentManager
        .beginTransaction()
        .setCustomAnimations(
            enter,
            exit,
            popEnter,
            popExit
        )
        .replace(R.id.fl_fragment_container, fragment, tag)
        .setReorderingAllowed(true)
        .apply {
            if (shouldAddToBackStack)
                addToBackStack(tag)
        }
        .commit()

A: You can disable the animation from BottomSheetDialogFragment
 override fun onResume() {
        super.onResume()
        // Disable dialog window animations for this instance
        dialog?.window?.setWindowAnimations(-1)
    }


Q: Como listar uma query sem saber o que vai ser retornado? Nesse exemplo eu defini alguns atributos a serem mostrados, mas no jogo eu não sei quais devo mostrar porque o usuário é quem vai fazer a consulta.
<?php
   while ($row = mysql_fetch_array($qry_result)){?>

     <?= $row[id_funcionario]?>
     <?= $row[end_funcionario]?>
     <?= $row[nome_funcionario]?>

<?php } ?>

Como eu faço pra listar essa $qry_result na tabela sem saber o que vai ser retornado?
Exemplo: No meu Jogo de SQL tem um campo onde o usuário digita a instrução SQL. Ele pode digitar por exemplo select * from funcionarios. Como eu mostro as informações na tabela sem saber o que ele vai digitar?

A: Pra mostrar os resultados, basta isso:
<?php
   while ( $row = mysql_fetch_array($qry_result, MYSQL_NUM) ) {
      echo '
';
      foreach($row as $item) {
         echo '';
         echo htmlentities( $item );
         echo '	';
      }
      echo "
\n";
   }
?>

Lembrando que você precisa limitar os privilégios de acesso do usuário, senão ele vai fazer muito mais do que dar SELECT onde você imagina. Dá pra pensar desde um DROP TABLE até uma consulta à sua tabela de senhas.
Versão com títulos:
<?php
   $primeira = true;
   while ( $row = mysql_fetch_array($qry_result, MYSQL_ASSOC) ) {
      if ($primeira ) {
         echo '
';
         foreach($row as $titulo => $item) {
            echo '';
            echo htmlentities( $titulo );
            echo '	';
         }
         echo '
';
         $primeira = false;
      }
      echo '
';
      foreach($row as $item) {
         echo '';
         echo htmlentities( $item );
         echo '	';
      }
      echo "
\n";
   }
?>


Q: Keyboard layout related issue I run on Ubuntu 14.04. I have an issue related to the keyboard layout in GUI mode. I managed to fix it in the GUI by using: setxkbmap -layout us [1] and adding it to the ~/.bashrc. That works fine. However, the problem is that when I log to the text-mode terminal I receive an error - Cannot display "default display". This is not surprising because this command does not work in text mode. The question is: where should I put [1] and have no error in text mode terminal?

A: Issue is solved. Added script to ~/.bashrc:
if [ "$TERM" = "xterm" ]; then
   setxkbmap -layout "us"
fi


Q: How to Generate Scripts For All Triggers in Database Using Microsoft SQL Server Management Studio I'd like to generate an SQL Script that contains the SQL to create all of the triggers that exist in our database.  The triggers were added directly via the SSMS query pane so, there is currently no source other than the trigger on the database itself.
I have already tried the method where you right-click the database, select Tasks->Generate Scripts and used the "Script Entire Database and All Objects" option.  While this does create a SQL script for the tables and constraints, it does not generate SQL for the triggers.
I also understand that I can right click on each trigger in the database and select the Generate SQL Script option but, there is currently 46 tables under audit (For Insert, Update, and Delete).
Rather manually generate an insert, update, and delete trigger script for each of the 46 tables, is there an easier way to do this?  Or, should I start clicking, copying, and pasting?

A: I know the answer has been accepted already, but want to provide another solution for cases when for some reason SSMS wizard is not able to generate script for triggers (in my case it was MSSQL2008R2)
This solution is based on idea from dana above, but uses 'sql_modules' instead to provide the full code of the trigger if it exceeds 4000 chars (restriction of 'text' column of 'syscomments' view)
select [definition],'GO' from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
 where obj.type ='TR'

Right click on the results grid and then "Save results as..." saves to file with formatting preserved

A: To script all triggers you can define the stored procedure:
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Procedure:
--   [dbo].[SYS_ScriptAllTriggers]
--
-- Parameter:
--   @ScriptMode bit
--     possible values:
--     0 - Script ALTER only
--     1 - Script CREATE only
--     2 - Script DROP + CREATE

ALTER PROCEDURE [dbo].[SYS_ScriptAllTriggers]
    @ScriptMode int = 0
AS
BEGIN

    DECLARE @script TABLE (script varchar(max), id int identity (1,1))

    DECLARE
        @SQL VARCHAR(8000),
        @Text            NVARCHAR(4000),
        @BlankSpaceAdded INT,
        @BasePos         INT,
        @CurrentPos      INT,
        @TextLength      INT,
        @LineId          INT,
        @MaxID           INT,
        @AddOnLen        INT,
        @LFCR            INT,
        @DefinedLength   INT,
        @SyscomText      NVARCHAR(4000),
        @Line            NVARCHAR(1000),
        @UserName        SYSNAME,
        @ObjID           INT,
        @OldTrigID       INT;

    SET NOCOUNT ON;
    SET @DefinedLength = 1000;
    SET @BlankSpaceAdded = 0;

    SET @ScriptMode = ISNULL(@ScriptMode, 0);

    -- This Part Validated the Input parameters
    DECLARE @Triggers TABLE (username SYSNAME NOT NULL, trigname SYSNAME NOT NULL, objid INT NOT NULL);
    DECLARE @TrigText TABLE (objid INT NOT NULL, lineid INT NOT NULL, linetext NVARCHAR(1000) NULL);

    INSERT INTO
        @Triggers (username, trigname, objid)
    SELECT DISTINCT
        OBJECT_SCHEMA_NAME(B.id), B.name, B.id
    FROM
        dbo.sysobjects B, dbo.syscomments C
    WHERE
        B.type = 'TR' AND B.id = C.id AND C.encrypted = 0;

    IF EXISTS(SELECT C.* FROM syscomments C, sysobjects O WHERE O.id = C.id AND O.type = 'TR' AND C.encrypted = 1)
    BEGIN

        insert into @script select '/*';
        insert into @script select 'The following encrypted triggers were found';
        insert into @script select 'The procedure could not write the script for it';

        insert into
            @script
        SELECT DISTINCT
            '[' + OBJECT_SCHEMA_NAME(B.id) + '].[' + B.name + ']' --, B.id
        FROM
            dbo.sysobjects B, dbo.syscomments C
        WHERE
            B.type = 'TR' AND B.id = C.id AND C.encrypted = 1;

        insert into @script select '*/';
    END;

    DECLARE ms_crs_syscom CURSOR LOCAL forward_only FOR
    SELECT
        T.objid, C.text
    FROM
        @Triggers T, dbo.syscomments C
    WHERE
        T.objid = C.id
    ORDER  BY T.objid,
        C.colid
    FOR READ ONLY;

    SELECT @LFCR = 2;
    SELECT @LineId = 1;

    OPEN ms_crs_syscom;

    SET @OldTrigID = -1;

    FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;

    WHILE @@fetch_status = 0
    BEGIN

        SELECT @BasePos = 1;
        SELECT @CurrentPos = 1;
        SELECT @TextLength = LEN(@SyscomText);

        IF @ObjID <> @OldTrigID
        BEGIN
            SET @LineID = 1;
            SET @OldTrigID = @ObjID;
        END;

        WHILE @CurrentPos != 0
        BEGIN
            --Looking for end of line followed by carriage return
            SELECT @CurrentPos = CHARINDEX(CHAR(13) + CHAR(10), @SyscomText, @BasePos);

            --If carriage return found
            IF @CurrentPos != 0
            BEGIN

                WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @CurrentPos - @BasePos + @LFCR ) > @DefinedLength
                BEGIN
                    SELECT @AddOnLen = @DefinedLength - (ISNULL(LEN(@Line), 0) + @BlankSpaceAdded );

                    INSERT
                        @TrigText
                    VALUES
                        ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                    SELECT
                        @Line = NULL,
                        @LineId = @LineId + 1,
                        @BasePos = @BasePos + @AddOnLen,
                        @BlankSpaceAdded = 0;
                END;

                SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @CurrentPos - @BasePos + @LFCR), N'');

                SELECT @BasePos = @CurrentPos + 2;

                INSERT
                    @TrigText
                VALUES
                    ( @ObjID, @LineId, @Line );

                SELECT @LineId = @LineId + 1;

                SELECT @Line = NULL;
            END;
            ELSE
            --else carriage return not found
            BEGIN
                IF @BasePos <= @TextLength
                BEGIN
                    /*If new value for @Lines length will be > then the
                    **defined length
                    */
                    WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @TextLength - @BasePos + 1 ) > @DefinedLength
                    BEGIN
                        SELECT @AddOnLen = @DefinedLength - ( ISNULL(LEN(@Line), 0 ) + @BlankSpaceAdded );

                        INSERT
                            @TrigText
                        VALUES
                            ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                        SELECT
                            @Line = NULL,
                            @LineId = @LineId + 1,
                            @BasePos = @BasePos + @AddOnLen,
                            @BlankSpaceAdded = 0;
                    END;

                    SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @TextLength - @BasePos+1 ), N'');

                    IF LEN(@Line) < @DefinedLength AND CHARINDEX(' ', @SyscomText, @TextLength + 1) > 0
                    BEGIN
                        SELECT
                            @Line = @Line + ' ',
                            @BlankSpaceAdded = 1;
                    END;
                END;
            END;
        END;

        FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;
    END;

    IF @Line IS NOT NULL
        INSERT
            @TrigText
        VALUES
            ( @ObjID, @LineId, @Line );

    CLOSE ms_crs_syscom;

    insert into @script select '-- You should run this result under dbo if your triggers belong to multiple users';
    insert into @script select '';

    IF @ScriptMode = 2
    BEGIN

        insert into @script select '-- Dropping the Triggers';
        insert into @script select '';

        insert into @script
        SELECT
            'IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(''[' + username + '].[' + trigname + ']'')'
            + ' AND ObjectProperty(OBJECT_ID(''[' + username + '].[' + trigname + ']''), ''ISTRIGGER'') = 1)'
            + ' DROP TRIGGER [' + username + '].[' + trigname +']' + CHAR(13) + CHAR(10)
            + 'GO' + CHAR(13) + CHAR(10)
        FROM
            @Triggers;
    END;

    IF @ScriptMode = 0
    BEGIN
        update
            @TrigText
        set
            linetext = replace(linetext, 'CREATE TRIGGER', 'ALTER TRIGGER')
        WHERE
            upper(left(replace(ltrim(linetext), char(9), ''), 14)) = 'CREATE TRIGGER'
    END

    insert into @script select '----------------------------------------------';
    insert into @script select '-- Creation of Triggers';
    insert into @script select '';
    insert into @script select '';

    DECLARE ms_users CURSOR LOCAL forward_only FOR
    SELECT
        T.username,
        T.objid,
        MAX(D.lineid)
    FROM
        @Triggers T,
        @TrigText D
    WHERE
        T.objid = D.objid
    GROUP BY
        T.username,
        T.objid
    FOR READ ONLY;

    OPEN ms_users;

    FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;

    WHILE @@fetch_status = 0
    BEGIN

        insert into @script select 'setuser N''' + @UserName + '''' + CHAR(13) + CHAR(10);

        insert into @script
        SELECT
            '-- Text of the Trigger' =
            CASE lineid
                WHEN 1 THEN 'GO' + CHAR(13) + CHAR(10) + linetext
                WHEN @MaxID THEN linetext + 'GO'
                ELSE linetext
            END
        FROM
            @TrigText
        WHERE
            objid = @ObjID
        ORDER
            BY lineid;

        insert into @script select 'setuser';

        FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;
    END;

    CLOSE ms_users;

    insert into @script select 'GO';
    insert into @script select '------End ------';

    DEALLOCATE ms_crs_syscom;
    DEALLOCATE ms_users;

    select script from @script order by id

END

How to execute it:
SET nocount ON
DECLARE @return_value INT

EXEC @return_value = [dbo].[SYS_ScriptAllTriggers] @InclDrop = 1
SELECT 'Return Value' = @return_value

GO

A: How about this?
select text from syscomments where text like '%CREATE TRIGGER%'
EDIT - per jj's comment below, syscomments is deprecated and will be removed in the future.  Please use either the wizard-based or script-based solutions listed above moving forward :)

A: Database-> Tasks-> Generate Scripts -> Next -> Next
On Choose Script Options UI, under Table/View Options Heading, set Script Triggers to True.

A: Using my own version with the combination of answer found in here and other post(can't find the original quetion.
select OBJECT_NAME(parent_obj) AS table_name,sysobj.name AS trigger_name,
[definition],'GO'
from sys.sql_modules m
inner join sysobjects sysobj on sysobj.id=m.object_id
INNER JOIN sys.tables t ON sysobj.parent_obj = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE sysobj.type = 'TR' and sysobj.name like 'NAME_OF_TRIGGER'
order by sysobj.name


Q: Ineligible app Submission to Facebook What features does my canvas app need, in order to submit the application on the App Center?
Facebook gave me this response:

Ineligible Submission
Your app does not have high enough ratings and
  user engagement to be eligible for the App Center at this time.

A: Are you trying to get your App into Facebook App center? In your case, it seems that you don't have enough users to do so. Facebook review process states that "Once your app has enough high user ratings and engagement, you can be submit your App Details Page for App Center listing...", it means that you need to run your App for a while.
Per your question (but I don't think that that's your real issue), the eligibility requirements are (see the same link above):
Eligibility Requirements
These apps are eligible for the App Center when they reach high user engagement and user ratings:
A canvas page app with Login Dialog.
A mobile apps built for iOS or Android and uses Facebook Login SDK for iOS or Facebook Login SDK for Android (More)
A app that is a website and uses Facebook Login
These apps are not currently eligible for App Center:
A Page Tab app
A Desktop web game off of Facebook.com


Q: iOS Swift Getting Lazy Map Collection Values I am trying to get the value for "alert" but not having very much luck.
LazyMapCollection<Dictionary<AnyHashable, Any>, AnyHashable>(_base: [AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1475009164, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("aps"): {
    alert = "test message";
}, AnyHashable("google.c.a.c_id"): 9039575328704479116, AnyHashable("gcm.message_id"): 0:1475009164740581%df6f7f01df6f7f01], _transform: (Function))

This is the code is a using but it does not work correctly
if (userInfo["aps"] != nil) {
                    let msg = (userInfo["alert"] as? String)!
                    let alert1 = UIAlertController(title: "Notification", message: msg, preferredStyle: .alert)
                    alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
                    }))
                    self.window?.rootViewController?.present(alert1, animated: true, completion: nil)
                    completionHandler(.newData)
                }

I am trying to display a local notification with the message of the value alert.  Any ideas would be appreciated. Thank you

A: This is my working solution
if (userInfo["aps"] != nil) {
                    if let notification = userInfo["aps"] as? NSDictionary,
                        let alert = notification["alert"] as? String {
                        let alert1 = UIAlertController(title: "Notification", message: alert, preferredStyle: .alert)
                        alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
                        }))
                        self.window?.rootViewController?.present(alert1, animated: true, completion: nil)
                        completionHandler(.newData)

                    }
                }


Q: Unknown error communicating between PHP and Actionscript I've got a problem that's either insanely simple or complex, it's up to you to find out. I've been working on trying to incorporate the URL Loader class into the beginners graphics program - Stencyl. I am fluent in HTML, CSS and PHP but actionscript is completely new to me so I really could use with a hand. Here's what I've got:
There are 4 files hosted on my domain:
Webpage.html
Stylesheet.css
RequestData.php
FlashDoc.swf
The html and css code is simple, no problems there and the swf file embed in the html document. The flash file is a simple form with a text field, submit button and two dynamic text fields. The code goes as follows:
// Btn listener
submit_btn.addEventListener(MouseEvent.CLICK, btnDown);
// Btn Down function
function btnDown(event:MouseEvent):void {

// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("http://www.mywebsite.com/config_flash.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);

variables.uname = uname_txt.text;
variables.sendRequest = "parse";
// Send the data to the php file
varLoader.load(varSend);

// When the data comes back from PHP we display it here
function completeHandler(event:Event):void{

var phpVar1 = event.target.data.var1;
var phpVar2 = event.target.data.var2;

result1_txt.text = phpVar1;
result2_txt.text = phpVar2;

}

}

I then have a small PHP file with this code:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
// Access the value of the dynamic text field variable sent from flash
$uname = $_POST['uname'];
// Print  two vars back to flash, you can also use "echo" in place of print
print "var1=My name is $uname...";
print "&var2=...$uname is my name.";

}

?>

This is, for some reason, not working. The result is just two blank text fields and being an actionscript noob, I have no idea what is up. Any help would be greatly appreciated. Thank you for your time.

A: The answer to your issue is both simple and surprising, if you're not used to AS3.
In AS3, the flash.* classes tend to, when a setter is used, make and store a copy of the passed object.
Since they store a copy, any modification on the original instance after the setter isn't applied on the copy, and thus is ignored.
It is the case of, for example, DisplayObject.filters, ContextMenu.customItems or URLRequest.data.
In your code, you are setting varSend.data = variables before filling variables. You should do the reverse :
variables.uname = uname_txt.text;
variables.sendRequest = "parse";
varSend.data = variables;
// Send the data to the php file
varLoader.load(varSend);

Only some classes do that, and even then, they usually don't do it with all of their setters.


Q: Struggling to get .fadeIn jQuery to work on a homepage image transition script I'm unsure if fadeIn is even the right transition (newbie), but I'm basically trying to have a crossfade between homepage images that change every 3 seconds. The changing is working successfully, but I don't know how to get them to fade. Currently there is just an abrupt switch. Here is my code:
    var images = ["image-link1", "image-link2"];
$(function () {
    var i = 0;
    document.getElementById("homeImage").src = images[i];
    setInterval(function () {
        if (i == images.length) {
            i = 0;
        }
        else {
            document.getElementById("homeImage").src = images[i];
            $(this).fadeIn("slow");
            i++;
        }
    }, 3000);
});

I'm using ASP.NET MVC. Thanks!

A: You have to fade out before that,  you can add fadeOut before changing the elememt's background and then add fadeIn when the background has changed

A: The steps will be

*

*Show an image.

*Fade out the current image.

*After finished fading out, change the url to a new image.

*Fade in to show the new image.

Working solution:

 $(function () {
    var i = 0;
    document.getElementById("homeImage").src = images[i];
    setInterval(function () {
        if (i == images.length - 1) {
            i = 0;
        }
        else {
            $('#homeImage').fadeOut("slow", function() {
                document.getElementById("homeImage").src = images[i];
                $('#homeImage').fadeIn("slow");
            });
            i++;
        }
    }, 3000);
});

A: <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Williams Marketing Studio</title>
    <link rel="stylesheet" href="~/Content/newstyle.css">
    @RenderSection("metatags", required: false)
    @Scripts.Render("~/bundles/modernizr")

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Services", "Index", "Services")

@Html.ActionLink("Categories", "Index", "Categories")

@Html.ActionLink("Contact", "Contact", "Home")

                @using (Html.BeginForm("Index", "Services", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {

                        @Html.TextBox("Search", null, new { @class = "form-input", @placeHolder = "Search Services" })
                        <button type="submit" class="button">Search</button>

                }

            @RenderBody()

                Copyright ©@DateTime.Now.Year

                Williams Marketing Studio
                W3C Validator API
                CSS Validator

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Services", "Index", "Services")

@Html.ActionLink("Categories", "Index", "Categories")

@Html.ActionLink("Contact", "Contact", "Home")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)


Q: How can I set an input mask property to a text filed of access database so that it will add leading zeros? I have a table field of text data type. I want to set an input mask property so that it add leading zeros to make 12 digits number. say, Input: 1256
it will automatically converted as 000000001256
how can I do this?

A: No need to use input mask .. use textbox and use format() function when store the text
Dim MyStr as String = format(val(txtNumber.Text),"000000000000")


Q: How to reload a shiny app when CSV file changes I have a shiny app which generates a distance matrix. It reads a database saved in a csv file, load as a data.frame and then it calculates the distance matrix.
This app runs in a host and is used in the same network by other pc using options(shiny.host = '0.0.0.0') and options(shiny.port = 5050).
The main problem is that when the csv is upload, the new information is not available for the shiny app due to the csv is already read, and the people that is using this app through browser is not able to stop and run again the shiny app in the rstudio to reread the csv data.base.
Is it possible to reload automatically the app when the csv is modified? Any suggestions? Thanks in advance.


Q: Firebase 3 permission denied after first-time sign-in with Google, works after second time I have a Google sign-in implemented according to instructions:
https://firebase.google.com/docs/auth/android/google-signin#authenticate_with_firebase
Authentication and sign-in work fine, the user is authenticated and signed-in and the listener is called:
mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
        }

However, when trying to read from a user node/path having a standard security rule:
  "users": {
     "$user_id": {
       ".read": "auth !== null && auth.uid === $user_id",
       ".write": "auth !== null"
     }
  }

with the following code triggered later manually:
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
userRef.child(uid).addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot data) {
                 ...
            }
            @Override
            public void onCancelled(DatabaseError error) {
                Log.w(TAG, "fb sync onCancelled: " + error.getMessage());
            }
        });

onCancelled is called with "permission denied". The uid is correct, equals to the user ID as returned by firebaseAuth.getCurrentUser().getUid()
Now the important part is that everything works fine if I sign-out and sign-in again, or if I terminate and re-launch the app. So I guess something must be wrong with the FirebaseAuth state after the initial sign-in, or maybe I miss something again..?
Tested with firebase-*:9.0.2 and play-services-auth:9.0.2 as well as 9.2.0.

A: My observations with Firebase realtime database.

It caches data on server side before adding to database (for a few milliseconds).

Result:

Read operations are few milliseconds faster than write operations.

*

*What's happening with your request:

*

*It reaches server and asks for data which is still not available in realtime database.

*Why that so:

*

*because its cached and still to be added to realtime database.

*all this caching and adding data to realtime database takes only milliseconds of time, but its significant when you immediately invoke data after adding because your Get Data request has reached the server before the node is created.

*That's why it shows permission denied.

*When this does not happen:

*

*When your device is using low speed internet connectivity, your request reaches Firebase server with a delay of 1-3 seconds, this happens naturally. So this problem will not arise there.

*What to do now:

*

*Just introduce a delay of 2-3 seconds before requesting data for the first time.

*This gives the whole operation of authentication, node creation and adding data enough time to complete.

*Everything will be smooth from there.

A: Thanks to the suggestion from Mr Frank I've managed to pinpoint the culprit. The problem occurs when the user signs in with Google while being already signed in anonymously (which I didn't take into account). So a workaround would be to sign out the anonymous user (FirebaseAuth.getInstance().sign_out()) before trying to sign in with Google, although I believe it's still undesired behavior, because it makes linking accounts problematic.
Here's an example to reproduce the problem:
public class TestAuthGoogle extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    static private final String TAG = TestAuthGoogle.class.getSimpleName();
    private GoogleApiClient mGoogleApiClient;
    public static final int RC_SIGN_IN = 9001;
    private Handler mHandler = new Handler();

    @Override
    public void onStart() {
        super.onStart();

        signInAnonymously();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                signInGoogle();
            }
        },5000);
    }

    void signInAnonymously() {
        FirebaseAuth.getInstance().signInAnonymously()
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInAnonymously", task.getException());
                        }
                    }
                });
    }

    void signInGoogle() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.my_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(TestAuthGoogle.this)
                .enableAutoManage(TestAuthGoogle.this, TestAuthGoogle.this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
                Log.d(TAG,"Authenticated");
            } else {
                Log.d(TAG,"Authentication failed");
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        FirebaseAuth.getInstance().signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
                        if (task.isSuccessful()) {
                            Log.d(TAG,"Signed in");
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    readFromDatabase();
                                }
                            },5000);
                        } else {
                            Log.w(TAG, "signInWithCredential: " + task.getException().getMessage());
                        }
                    }
                });
    }

    void readFromDatabase() {
        Log.d(TAG,"read from db");
        DatabaseReference uRef = FirebaseDatabase.getInstance().getReference("users");
        uRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot data) {
                        Log.d(TAG, "fb onDataChange: " + data.getValue());
                    }
                    @Override
                    public void onCancelled(DatabaseError error) {
                        Log.w(TAG, "fb onCancelled: " + error.getMessage());
                    }
                });
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG,"onConnectionFailed");
    }

}


Q: Rails i18n Attributes Not Working via JSON API We have a RoR 4.2.5.1 API server and an AngularJS frontend.
I'm trying get the internationalism working and have setup my en.yml as so
en:
  activerecord:
    attributes:
      nas:
        calledstationid: 'AP Mac'
    errors:
      models:
        nas:
          attributes:
            calledstationid:
              blank:
              invalid:
              taken: "has already been added to a location"

When I create 'nas' with a taken calledstationid, I'm expecting "AP Mac has already been added to a location".
Instead I get, "calledstationid..."
def create
  @nas = Nas.new(
    calledstationid: params[:box][:calledstationid]
  )
  respond_to do |format|
    if @nas.save
      format.json { render template: 'api/v1/boxes/show.json.jbuilder', status: 201 }
    else
      @errors = @nas.errors
      format.json { render template: 'api/v1/shared/index.json.jbuilder', status: 422 }
    end
  end
end

When I use the bang, I can see the calledstationid is replaced with ap mac in the logs.
So... my question is, why is the field name not being updated in the @nas.errors object? And how can I get this to work for multiple locales.
-- EDIT --
The error object:
@messages={:calledstationid=>["has already been added to a location"]}>

A: You have 2 options to solve this.
First:
Edit your yaml file and replace the message with the below :
"%{attribute} has already been added to a location"

Second:
What you are getting is standard and correct output as per the current YAML configuration. But to get what you are looking for, without changing the YAML, need to use ActiveModel::Errors#full_messages.Because this method prepends the attribute name to the error message.


Q: Android XML layout checkbox "onclick" method bind to a function not found in MainActivity Is it possible in Android to bind the "onclick" method from a checkbox to a function defined in a java class file directly in the XML file?
something like this
//XML layout File

....

 <CheckBox
     android:id="@+id/checkbox_1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/testString"
     android:textColor="@color/testcolor"
     android:onClick="onClickCheckbox_1_do"/>

...

public class TestClass{
     ...
     public void onClickCheckbox_1_do(View view) {
        //DoStuff
     }

}

Thanks!

A: Yes, you can. I just did. Write this code in your layout file:
<CheckBox
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="click"/>

And in your activity:
public void click(View view)
{
}

A: Yes! it's possible.
To define the click event handler for a checkbox, you should add android:onClick attribute to the  element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
   1. Be public
   2. Return void, and
   3. Define a View as its only parameter (this will be the View that was clicked)
Below is the code examples: xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/meat"
    android:onClick="onCheckboxClicked"/>
<CheckBox android:id="@+id/checkbox_cheese"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cheese"
    android:onClick="onCheckboxClicked"/>
</LinearLayout>

The activity method should look as follows:
  public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();

// Check which checkbox was clicked
switch(view.getId()) {
    case R.id.checkbox_meat:
        if (checked)
            // Put some meat on the sandwich
        else
            // Remove the meat
        break;
    case R.id.checkbox_cheese:
        if (checked)
            // Cheese me
        else
            // I'm lactose intolerant
        break;
    // TODO: Veggie sandwich
  }
}

I hope you find this helpful.


Q: Taking screenshots of multiple browser tabs My browser has 10-20 tabs open and I should go through and take a screenshot of each tab.
Can this be automated somehow?
I am using Internet Explorer but solutions for other browsers are also welcome.

A: Greenshot can take full page screenshots of browser tabs. It scrolls the page down and stitches the pieces together automatically.
Right-click its tray icon » Capture Internet Explorer from list » All open tabs are listed there

You might want to automate these repeating clicks by using TestComplete or AutoHotkey


Q: Query on Optional fields with QueryDSL I've had some trouble trying to figure out how QueryDSL is working with Java 8 Optional attributes.
I have configured QueryDSL, and queries like tests?field=valueare working on the String attributes. But as some of the getters of my class have Optional return types, the QTest class that is generated contains SimplePath<Optional<String>> instead of a simple StringPath for a String attribute. See below :
Test.class
@QueryEntity
@Document(collection = "test")
public class Test {

  private String field;

  private String optionalField;

  Test(String field, String optionalField) {
    this.field = field;
    this.optionalField = optionalField;
  }

  public String getField() {
    return field;
  }

  public Optional<String> getOptionalField() {
    return Optional.ofNullable(optionalField);
  }
}

Generated QTest.class
@Generated("com.querydsl.codegen.EntitySerializer")
public class QTest extends EntityPathBase<Test> {

    private static final long serialVersionUID = -609090735L;

    public static final QTest test = new QTest("test");

    public final StringPath field = createString("field");

    public final ComparablePath<java.util.UUID> id = createComparable("id", java.util.UUID.class);

    public final SimplePath<java.util.Optional<String>> optionalField = createSimple("optionalField", java.util.Optional.class);
}

The object in the database is such :
{
    "field":"value",
    "optionalField":"optionalValue"
}

The controller :
@RestController
@RequestMapping("/tests")
public class TestController {

  private final TestService testService;

  @Inject
  public TestController (final TestService testService) {
    this.testService = testService;
  }

  @GetMapping()
  public ResponseEntity<Page<Test>> getAllWithPredicate(Pageable pageable,
      @QuerydslPredicate(root = Test.class) Predicate predicate) {
    return new ResponseEntity<>(this.testService.getAllTestsWithPredicate(pageable, predicate), HttpStatus.OK);
  }

  @PostMapping
  public ResponseEntity<Test> createTest(@RequestBody Test test) {
    return new ResponseEntity<>(this.testService.createTest(test), HttpStatus.CREATED);
  }
}

Service :
@Service
public class TestService {

  private final TestRepository testRepository;

  @Inject
  public TestService(final TestRepository repo) {
    this.testRepository = repo;
  }

  public Page<Test> getAllTestsWithPredicate(Pageable pageable, Predicate predicate) {
    return this.testRepository.findAll(predicate, pageable);
  }

  public Test createTest(Test test) {
    Test savedTest = testRepository.save(test);
    return savedTest;
  }
}

And the repository :
@Repository
public interface TestRepository extends JpaRepository<Test, String>, QuerydslPredicateExecutor<Test>, QuerydslBinderCustomizer<QTest> {

  @Override
  default public void customize(QuerydslBindings bindings, QTest root) {
    bindings.bind(String.class).first((StringPath path, String value) -> path.containsIgnoreCase(value));
  }
}

So, first of all I wanted to process a containsIgnoreCase on both of my fields. This containsIgnoreCase is perfectly working on the normal field.
But when it comes to the Optional, with this request : tests?optionalField=optionalValue I got this error message :
java.lang.ClassCastException: com.querydsl.core.types.dsl.SimplePath cannot be cast to com.querydsl.core.types.dsl.StringPath
    at org.springframework.data.querydsl.binding.QuerydslBindings$MultiValueBindingAdapter.bind(QuerydslBindings.java:506) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.invokeBinding(QuerydslPredicateBuilder.java:139) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.getPredicate(QuerydslPredicateBuilder.java:113) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
...

That seems to be a normal behavior because of the QTest type generated for this field (SimplePath<Optional<String>> instead of StringPath), but the fact is that I can't find any working way to deal with this optionalField.
So my questions are :
Can QueryDSL work with Optional<String> values ? And if so, how am I supposed to query on these fields ?
Thank you for your help ! :)


Q: Como mostrar los datos de una base de datos en una tabla en html y php Soy nuevo en esto de php y html y quiero mostrar los datos en una tabla personalizada por bootstrap, este es mi codigo

<?php

// Conectando, seleccionando la base de datos

$link = mysql_connect('localhost', 'root', 'usbw')

    or die('No se pudo conectar: ' . mysql_error());

mysql_select_db('hotel') or die('No se pudo seleccionar la base de datos');

// Realizar una consulta MySQL
$query = 'SELECT id, nombre, apellido, telefono, dias, habitaciones FROM registro';

$result = mysql_query($query) or die('Consulta fallida: ' . mysql_error());

?>

   ID
   NOMBRE
   APELLIDO
   TELEFONO
   ESTADIA
   HABITACION

<?php while ($row = mysql_fetch_array($result)){?>
 <?php $row['id'] ?>
    <?php $row['nombre'] ?>
    <?php $row['apellido'] ?>
    <?php $row['telefono'] ?>
    <?php $row['dias'] ?>
    <?php $row['habitaciones'] ?>

<?php} ?>

A: Recuerda que el formato html. para tu documento de acuero con lo que quieres hacer con bootstrap.
Te recomiendo leer la documentación de php http://php.net/manual/es/pdo.connections.php, y ademas tratar de separar el código php de html por buenas practicas.

<!DOCTYPE html>

  <title>Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<?php
// Te recomiendo utilizar esta conección, la que utilizas ya no es la recomendada.
$link = new PDO('mysql:host=localhost;dbname=hotel', 'root', ''); // el campo vaciío es para la password.

?>

   ID
   NOMBRE
   APELLIDO

<?php foreach ($link->query('SELECT * from registros') as $row){ // aca puedes hacer la consulta e iterarla con each. ?>

 <?php echo $row['id'] // aca te faltaba poner los echo para que se muestre el valor de la variable.  ?>
    <?php echo $row['nombre'] ?>
    <?php echo $row['apellido'] ?>

<?php
 }
?>

Espero serte de ayuda.
Saludos!!!


Q: PHP Curl Proxy, how to define $_FILES['foo']['name'] I'm using CURL to make a PHP Proxy that forward a multipart form.
The form have an input type="file".
The proxy receive the following data:
array
  'foo' =>
    array
      'name' => string 'wt.jpg' (length=6)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/tmp/phpoIvraK' (length=14)
      'error' => int 0
      'size' => int 7427

So I'm expecting the page at the end to receive the same array (except for the tmp_name)
Right now I receive this:
'foo' =>
   array
     'name' => 'phpoIvraK'
     'type' => 'image/jpeg'
     'tmp_name' => '/tmp/php5ZhCwy'
     'error' => 0
     'size' => 7427

As you can see, the name is now the tmp_name that the proxy is receiving, so the original filename is lost.
Here's the PHP Code:
$arrFields = $_POST;
foreach($_FILES as $k => $file)
    $arrFields[$k] = '@' . $file['tmp_name'] . ';type=' . $file['type'];

curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields);

Ps.: I know I could make a new variable, but the goal here is to respect the variable format, and make the usage of the proxy as transparent as possible for the person that'll use it.
Is it me or the only solution would be to rename the tmp file in the /tmp before resending it ? That looks a bit silly to me ...
$arrFields = $_POST;
foreach($_FILES as $k => $file){
    move_uploaded_file($file['tmp_name'], $file['name']);
    $arrFields[$k] = '@' . $file['name'] . ';type=' . $file['type'];
}
curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields);

A: I think you shouldn't use the tmp file but instead store the file with it's real name somewhere, pass it to the POSTFIELDS param and after executing remove it. That seems to easiest way to me. curl doesn't care about the original request, it just does what you tell it to do and that is ... send the temp file over.

A: Faced similar situation and this is how I solved it
Pass the actual file name along with the request
$arrInputs["uploadvia"]     = 'curl';
$arrInputs["actualfilename"]= $_FILES["upfile1"]["name"];
$arrInputs["upfile1"]       = "@".$_FILES["upfile1"]["tmp_name"].";type=".$_FILES["upfile1"]["type"].";";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrInputs);

And at the other end, put this block
if($_POST['uploadvia'] == "curl")
{
     $_FILES["upfile1"]["name"] = $_REQUEST['actualfilename'];
}


Q: What is the time complexity of an algorithm with the setTimeout function? Given the following sorting algorithm, what is the time complexity of the sort?
function sort(arr) {
  arr.forEach(i => {
    setTimeout(() => console.log(i), i)
  })
}

const n = [100, 1000000, 10000, 3600000, 3, 5, 0, 1, 9];
sort(n);

Output:
0
1
3
5
9
100
10000
3600000 // After 1 hour


Q: Clojure: Rename and select keys from map with one iteration In Clojure, I want to both rename-keys and select-keys from a map.
The simple way of doing is with:
(-> m
    (rename-keys new-names)
    (select-keys (vals new-names)))

But this will itetate over the entire map twice.
Is there a way to do it with one iteration?

A: Sure, there is a way to do it with a single iteration.
You could do it using reduce-kv function:
(reduce-kv #(assoc %1 %3 (get m %2)) {} new-names)

or just a for loop:
(into {} (for [[k v] new-names] [v (get m k)]))

If you want a really simple piece of code, you could use fmap function from algo.generic library:
(fmap m (map-invert new-names))


Q: Why the string is always empty? I try to use LINQ to read XML file. However, the string which store the value of selected attribute is always empty.
Here is the code:
        string output = "";
        XDocument loaded = XDocument.Load(@"d:\input.xml");

        var ta = from tmp in loaded.Descendants("NewDataSet.Table")
                select tmp.Element("E1");

        foreach (string ss in ta)
        {
            ouput += ss;

        }

The output string is always empty. But the ss string has correct value.
What is the problem?
I've no idea how to add xml file with style. So i have to update the xml file as image. :(

A: Now that you have shown your XML, here's how to fix your code:
var ta = from tmp in loaded.Descendants("Table")
         select tmp.Element("E1");

You do not use . in XML as you do in C# to navigate the XML tree. You could also navigate a XML tree using XPath:
var ta = from tmp in loaded.XPathSelectElements("NewDataSet/Table/E1")
         select tmp;

Also I would recommend you to use a StringBuilder instead of string concatenations for this output variable:
var ta = from tmp in loaded.Descendants("Table")
         select tmp.Element("E1");

var builder = new StringBuilder();
foreach (string ss in ta)
{
    builder.Append(ss);
}
string output = builder.ToString();

A: var ta = from tmp in loaded.Descendants("Table")
select tmp.Element("E1");


Q: Android приложение перестало работать Написал приложение, которое принимает JSON с сервера и результат выводит в RecyclerView. Изначально все работало корректно, но через некоторое время стало зависать на ProgressBar в Android 5.0. На эмуляторе Android studio все работает отлично (эмулятор Android 7.1.1). Зависает в фоновом потоке при десериализации JSON.
MainActivity.java
public class MainActivity extends AppCompatActivity {

Context context;
ProgressBar progressBar;
RecyclerView filmView;
Activity main;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    main = this;
    context=this;
    setContentView(R.layout.activity_main);
    filmView = (RecyclerView) findViewById(R.id.FilmsList);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(ProgressBar.VISIBLE);

        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.start();
}

/**
 * Класс для обработки Json
 */
public class MyThread extends Thread{
    private final long date=System.currentTimeMillis()/1000L;
    private final String FILMS_URL ="http://example.com"
    private String resultJson;
    private JSONObject jsonObject;
    private JSONArray js;
    Adapter adapter;
    private Films[] films;
    InputStream inputStream;
    @Override
    public void run(){
        try {
            URL url = new URL(FILMS_URL);
            URLConnection http = url.openConnection();
            inputStream = http.getInputStream();
            http.connect();
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultJson = buffer.toString();
        }
        catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            jsonObject = new JSONObject(resultJson);
            js = jsonObject.getJSONArray("results");
            films =new Gson().fromJson(js.toString(), Films[].class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        filmView.post(new Runnable() {
            @Override
            public void run() {

                filmView.addItemDecoration(new SpacesItemDecoration(50));
                filmView.setHasFixedSize(true);
                adapter = new Adapter(main, context, films);
                LinearLayoutManager llm = new LinearLayoutManager(main);
                llm.setOrientation(LinearLayoutManager.VERTICAL);
                filmView.setLayoutManager(llm);
                filmView.setAdapter(adapter);

                /**
                 * Обработка нажатий
                 */
                filmView.addOnItemTouchListener(
                        new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {

                            @Override
                            public void onItemClick(View view, int position) {
                                Intent intent = new Intent(MainActivity.this, FilmDetails.class);
                                String filmString;
                                GsonBuilder gsonBuilder=new GsonBuilder();
                                gsonBuilder.registerTypeAdapter(Films.class, new MyTypeAdapter());
                                gsonBuilder.setPrettyPrinting();
                                Gson gson=gsonBuilder.create();
                                filmString =gson.toJson(films[position]);
                                intent.putExtra("films", filmString);       //передаём объект как json-строку
                                startActivity(intent);
                            }
                        })
                );
            }
        });
    }
}

public void onProgressClick(View view){
    Toast toast=Toast.makeText(this, "loading...", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM, 0, 0);
    toast.show();
}
}

в логи пишет это
01-13 13:45:31.464 1353-1360/com.example.sharafievp.myfilm W/art: Suspending          all threads took: 53.907ms
01-13 13:45:33.422 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 5.432ms
01-13 13:45:35.849 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 9256(454KB) AllocSpace objects, 3(47KB)      LOS objects, 21% free, 2017KB/2MB, paused 4.327ms total 312.016ms
01-13 13:45:35.876 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 24.495ms
01-13 13:45:35.953 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 34.178ms
01-13 13:45:36.939 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 5.087ms
01-13 13:45:38.017 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 90.718ms
01-13 13:45:39.033 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 106.362ms
01-13 13:45:39.123 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 5725(315KB) AllocSpace objects, 1(16KB)   LOS objects, 13% free, 2MB/2MB, paused 3.789ms total 499.241ms
01-13 13:45:39.565 1353-1360/com.example.sharafievp.myfilm W/art: Suspending   all threads took: 140.064ms
01-13 13:45:39.734 1353-1365/com.example.sharafievp.myfilm I/art: Background partial concurrent mark sweep GC freed 8075(378KB) AllocSpace objects, 0(0B) LOS      objects, 39% free, 2MB/3MB, paused 2.541ms total 374.222ms
01-13 13:45:39.756 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 22.256ms
01-13 13:45:41.457 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 10.842ms
01-13 13:45:42.026 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 21.661ms
01-13 13:45:42.306 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 26452(1138KB) AllocSpace objects, 0(0B)   LOS objects, 38% free, 2MB/3MB, paused 3.173ms total 350.458ms
01-13 13:45:42.340 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 32.739ms
01-13 13:45:42.478 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 45.701ms
01-13 13:45:42.941 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 7.528ms
01-13 13:45:43.441 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 9.983ms
01-13 13:45:43.967 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 15.002ms
01-13 13:45:44.441 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 5.679ms
01-13 13:45:45.017 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 78.054ms
01-13 13:45:45.227 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 30991(1278KB) AllocSpace objects, 0(0B) LOS objects, 33% free, 2MB/3MB, paused 4.014ms total 530.324ms
01-13 13:45:45.248 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 20.060ms
01-13 13:45:46.952 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 6.040ms
01-13 13:45:47.519 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 24262(1051KB) AllocSpace objects, 0(0B) LOS objects, 33% free, 2MB/3MB, paused 28.907ms total 413.226ms
01-13 13:45:47.522 1353-1364/com.example.sharafievp.myfilm I/art: WaitForGcToComplete blocked for 276.630ms for cause HeapTrim
01-13 13:45:47.621 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 93.925ms
01-13 13:45:47.952 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 6.986ms
01-13 13:45:48.445 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 5.285ms
01-13 13:45:49.451 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 7.622ms
01-13 13:45:49.977 1353-1360/com.example.sharafievp.myfilm W/art: Suspending all threads took: 33.428ms
01-13 13:45:50.156 1353-1365/com.example.sharafievp.myfilm W/art: Suspending all threads took: 5.254ms
01-13 13:45:50.407 1353-1365/com.example.sharafievp.myfilm I/art: Background sticky concurrent mark sweep GC freed 27212(1124KB) AllocSpace objects, 0(0B) LOS objects, 31% free, 2MB/3MB, paused 11.058ms total 474.047ms

на english форумах пишут что проблема связана не с кодом, а с Android 5.0.
Пользуюсь библиотекой Gson

A: filmView.setHasFixedSize(true);

Нужен только в том случае, если у вас все ячейки одинаковой высоты.
Если у вас высота зависит от контента, просто удалите эту строчку, в противном случае, это может вызывать лаги

A: В общем ни одна из библиотек обработки JSON у меня не работает на Android 5.0. Написал собственный класс для обработки, используя стандартную библиотеку org.json. Теперь приложение не зависает.


Q: How to control colors assigned to data groups? Code:
mtcars %>% group_by(cyl,am) %>% ggvis(~mpg, fill = ~factor(cyl)) %>% layer_densities()

The code above plots density graphs for each group of "cyl" and assigns different colors according to three levels of cyl: (4,6,8). But I don't have control over what color is assigned to each group.
How can I assign specific colors e.g. "red", "green", and "yellow" to each group?

A: You can add the following to your ggvis function
... %>% scale_ordinal("fill", range = c("red", "green", "yellow"))


Q: Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address in Xcode How can I fix the issue?

W0721 13:54:19.105928 1 commandlineflags.cc:1503] Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address

A: This problem occurs because your code try to using non-existing pointer in cocoa pods. You may using framework that using cocoa pods and install needed pods on the main project.
The solution is to make cocoa pods version similar in both framework and project , run pod update from the terminal in both  framework and project or specify every pod version to be same in both
Example
framework pod file :
pod 'GooglePlaces' '~> 3.1.0'

project pod file :
pod 'GooglePlaces' '~> 3.1.0'

I hope this solve your problem.

A: I've seen this error when I had a UITableView in a view controller and:

*

*I connected the DataSource and Delegate for table view in the Storyboard.

*I did NOT declare the UIViewController as UITableViewDelegate and UITableViewDataSource.

I usually assign delegate/datasource in code (which would have given me a warning).


Q: Check if numpy array is in list of numpy arrays I have a list of numpy arrays and a single numpy array. I want to check if that single array is a member of the list.
I suppose there exist a method and I haven't searched properly... This is what I came up with:
def inList(array, list):
    for element in list:
        if np.array_equal(element, array):
            return True
    return False

Is this implementation correct? Is there any ready function for this?

A: lets say you have an array like this:
a= [array([ 1, 24,  4, 5]), array([ 22,   4, 123]), array([11,  1,  1])]
#convert all subarrays to list
a= [ list(item) for item in a ]

no you can check for a sublist like this:
In [80]: [1,22,4] in a
Out[80]: False

In [81]: [1,24,4,5] in a
Out[81]: True

A: Using the verb is when talking about python is a bit ambiguous. This example covers all the cases I could think of:
from __future__ import print_function
from numpy import array, array_equal, allclose

myarr0 = array([1, 0])
myarr1 = array([3.4499999, 3.2])
mylistarr = [array([1, 2, 3]), array([1, 0]), array([3.45, 3.2])]

#test for identity:
def is_arr_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem is myarr), False)

print(is_arr_in_list(mylistarr[2], mylistarr)) #->True
print(is_arr_in_list(myarr0, mylistarr)) #->False
#myarr0 is equal to mylistarr[1], but it is not the same object!

#test for exact equality
def arreq_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if array_equal(elem, myarr)), False)

print(arreq_in_list(myarr0, mylistarr)) # -> True
print(arreq_in_list(myarr1, mylistarr)) # -> False

#test for approximate equality (for floating point types)
def arreqclose_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem.size == myarr.size and allclose(elem, myarr)), False)

print(arreqclose_in_list(myarr1, mylistarr)) #-> True

PS:do NOT use list for a variable name, as it is a reserved keyword, and often leads to subtle errors. Similarly, do not use array.

A: There is a much simpler way without the need to loop using np.all(). It only works when all the arrays within the list of arrays have the same shape:
list_np_arrays = np.array([[1., 1.], [1., 2.]])
array_to_check = np.array([1., 2.])

is_in_list = np.any(np.all(array_to_check == list_np_arrays, axis=1))

The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check.


Q: JSONP works in jQuery but not in mootools I'm trying to convert my code to Mootools (I like the coding paradigm better).
I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):
Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :
var url = http://localhost:3000/
Server:
var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});

jQuery:
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});

Mootools:
var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();

I've tried adding these headers to no avail.:
'Accept': 'application/json',
'Content-Type': 'application/json'

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

A: What does URL look like?  jQuery figures out it's a JSONP request by adding ?callback= or ?foo= to the url.  Request.JSONP instead uses an option callbackKey.
There's no method option for JSONP (in any library), since it's just injecting a script tag.
var myRequest = new Request.JSONP({
  url: url,
  callbackKey: 'callback'
  onComplete: function(data){}
}).send();

I have a feeling, however, you aren't using JSONP, but rather XHR with JSON.  If that's the case, use Request.JSON, not Request.JSONP.

Edit
Since it sounds, from the comments on this answer, that you're not using JSONP, just do this:
new Request.JSON({
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

Edit 2
To change the request headers just add them as an option:
new Request.JSON({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  },
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

A: You had a syntax error in your code.
var myRequest = new Request.JSONP({
    url: url,
    method: 'get',
    onComplete: function(data){}
});
myRequest.send();

Also, the response should be wrapped with callback function, example: http://jsfiddle.net/zalun/yVbYQ/

A: Your ajax call should be like this
          $.ajax({
                type: "GET",
                url: "http://localhost:17370/SampleService.asmx/HelloWorld",
                data: "{}",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                dataType: "jsonp",
               async:false,
                success:function(data,status){
                    alert(data);

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " +
                    XMLHttpRequest + " | " + textStatus + " | " +
                    errorThrown);
                }
            });

Your server side method should not return simple string it should return response in jsonp format for that you need to follow this blog:
http://msrtechnical.blogspot.in/


Q: sort data from mysql table using php Can you help me how to sort my data from MySQL table ?
I want to sort is by using the table head :
<?php
    if(isset($_POST['search'])) {
        $valueTosearch = $_POST['searchvalue'];
        $query = "SELECT * FROM `admin` WHERE CONCAT(`id`, `name`, `gender`, `user_group`, `date_registered`) LIKE '%".$valueTosearch."%'";
        $search_result = filterTable($query);
    } else {
        $query = "SELECT * FROM `admin`";
        $search_result = filterTable($query);
    }

    function filterTable($query)
    {
        include('config/dbconnect.php');
        $filter_result = mysqli_query($con, $query);
        return $filter_result;
    }
?>

<form method='post' action=''>

<input type = 'text' name = 'searchvalue' placeholder="search by name">

                <input id='gradient' class='search-btn' type = 'hidden' name = 'search' value = 'search'>

                        name
                        sex
                        user group
                        date register

                <?php while($row = mysqli_fetch_array($search_result)): ?>

                        <?php echo $row['name']; ?>
                        <?php echo $row['gender']; ?>
                        <?php echo $row['user_group']; ?>
                        <?php echo $row['date_registered']; ?>

                <?php endwhile; ?>

</form>

A: Why don't you use order by clause:
SELECT * FROM table ORDER BY column;
Order By Reference

A: You can modified your query as below for sorting:
sql > select * from
 order by <column name>;

default sorting is ascending order  else for descending you can do like
sql > select * from
 order by <column name> desc;

A: If you could use JQuery, it's very simple, you have just to add the following javascript code:
$( document ).ready(function() {
    $("#responsive_table").DataTable({
      ordering: true,
      searching: true
    });
});

for a complete example see the following code:

<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>

      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">

    <form method='post' action=''>

                            name
                            sex
                            user group
                            date register

                            HERE
                            Your
                            data
                            loaded

                            via
                            PHP
                            loop
                            bye

            </form>


Q: Android get data from gmail, attachment is json What I want: Get data from json in gmail attachment.
Description: Open Gmail, click attachment which is json file. Json file handle data which I need to procesing.
In Manifest I declarated
<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="application/json"/>
                <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Next i use
Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_VIEW)){
intent.getData <- I suppose from here i can get my infomation
        }

But intent.getData only return Uri, and I read someone i must use ContentResolver, InputStream and something else to for example write my data from json to string. If some can explain how it works on example I will appreciate it.

A: Ok i have it
if (intent.getAction().equals(Intent.ACTION_VIEW)) {
            Toast.makeText(this, "work", Toast.LENGTH_SHORT).show();
            Uri data = intent.getData();
//            ContentResolver contentResolver = getContentResolver();
            String text = getStringFromShare(data);
            Log.d("sasas", "onCreate: sometext");
        }
    }

    private String getStringFromShare(Uri data) {
        String text = null;
        try {

            ContentResolver cr = getApplicationContext().getContentResolver();
            InputStream is = cr.openInputStream(data);
            if (is != null) {

                StringBuffer buf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String str;
                if (is != null) {
                    while ((str = reader.readLine()) != null) {
                        buf.append(str);
                    }
                }
                is.close();
                text = buf.toString();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }


Q: При попытке сделать .exe файл выдает ошибку cannot find existing pyqt5 plugin directories Хочу с помощью pyinstaller переделать свой код в exe файл, но выдает ошибку cannot find existing pyqt5 plugin directories
:\Program Files\Crestiki\Project>pyinstaller test.py

79 INFO: Python: 3.7.7
80 INFO: Platform: Windows-10-10.0.18362-SP0
80 INFO: wrote C:\Program Files\Crestiki\Project\test.spec
82 INFO: UPX is not available.
84 INFO: Extending PYTHONPATH with paths
['C:\\Program Files\\Crestiki\\Project', 'C:\\Program Files\\Crestiki\\Project']
127 INFO: checking Analysis
127 INFO: Building Analysis because Analysis-00.toc is non existent
127 INFO: Initializing module dependency graph...
129 INFO: Caching module graph hooks...
140 INFO: Analyzing base_library.zip ...
2672 INFO: Processing pre-find module path hook distutils from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-distutils.py'.
2673 INFO: distutils: retargeting to non-venv dir 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib'
4985 INFO: Caching module dependency graph...
5098 INFO: running Analysis Analysis-00.toc
5100 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\ильсаф\appdata\local\programs\python\python37\python.exe
5167 INFO: Analyzing C:\Program Files\Crestiki\Project\test.py
5209 INFO: Processing module hooks...
5209 INFO: Loading module hook 'hook-distutils.py' from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
5211 INFO: Loading module hook 'hook-encodings.py' from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
5297 INFO: Loading module hook 'hook-PyQt5.py' from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
5503 WARNING: Hidden import "sip" not found!
5503 INFO: Loading module hook 'hook-PyQt5.QtCore.py' from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
5575 WARNING: Unable to find Qt5 translations C:/users/èëüñàô/appdata/local/programs/python/python37/lib/site-packages/PyQt5/Qt/translations\qtbase_*.qm. These translations were not packaged.
5575 INFO: Loading module hook 'hook-PyQt5.QtGui.py' from 'c:\\users\\ильсаф\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
Traceback (most recent call last):
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Ильсаф\AppData\Local\Programs\Python\Python37\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\__main__.py", line 114, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\building\build_main.py", line 711, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\building\build_main.py", line 658, in build
    exec(code, spec_namespace)
  File "C:\Program Files\Crestiki\Project\test.spec", line 17, in <module>
    noarchive=False)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\building\build_main.py", line 236, in __init__
    self.__postinit__()
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\building\datastruct.py", line 160, in __postinit__
    self.assemble()
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\building\build_main.py", line 413, in assemble
    self.graph.process_post_graph_hooks()
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\depend\analysis.py", line 359, in process_post_graph_hooks
    module_hook.post_graph()
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\depend\imphook.py", line 420, in post_graph
    self._load_hook_module()
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\depend\imphook.py", line 387, in _load_hook_module
    self.hook_module_name, self.hook_filename)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\compat.py", line 588, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 407, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 907, in load_module
  File "<frozen importlib._bootstrap_external>", line 732, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\hooks\hook-PyQt5.QtGui.py", line 13, in <module>
    hiddenimports, binaries, datas = add_qt5_dependencies(__file__)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 538, in add_qt5_dependencies
    more_binaries = qt_plugins_binaries(plugin, namespace=namespace)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 146, in qt_plugins_binaries
    pdir = qt_plugins_dir(namespace=namespace)
  File "c:\users\ильсаф\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 131, in qt_plugins_dir
    """.format(namespace, ", ".join(paths)))
Exception:
            Cannot find existing PyQt5 plugin directories
            Paths checked: C:/users/èëüñàô/appdata/local/programs/python/python37/lib/site-packages/PyQt5/Qt/plugins``

A: Я бы посоветовал Вам переставить питон в папку с коротким путем c:\python37 например. И обязательно без кириллицы в пути к файлам.


Q: How to load a STL vector with a constant If I have a vector<double> that has already been resized to be 1200, what is the best way to load that vector with the same value in each slot? The value is not known at compile time.
Right now I just use a loop through all 1200 slots and set each slot equal to the value. I was wondering if this was the best way to do this.

A: You can use std::vector constructor

explicit vector (size_type n, const value_type& val = value_type(),
                   const allocator_type& alloc = allocator_type());

next way
vector<double> myVector;
double value = 1.;
myVector = vector<double>(1200, value);

alternative is std::fill, which will avoid memory allocation
std::fill(begin(myVector), end(myVector), value);

A: You could use loop unrolling:
std::vector<double> my_vector(1200);
for (int i = 0; i < 300; i += 4)
{
    my_vector[i + 0] = value;
    my_vector[i + 1] = value;
    my_vector[i + 2] = value;
    my_vector[i + 3] = value;
}

I suggest playing around with the number of assignments in the loop.  The idea here is to reduce the overhead of incrementing and branching (do more data operations).


Q: JSF PrimeFaces datatable filtering I 'record' objects and I put them in a datatable. A record has a boolean value 'Ignored', my idea is to make a filter so that it either shows all ignored records or everything. Here is my code:
<p:column headerText="Status" filterMatchMode="equals" filterBy="#{record.ignored}">
    <f:facet name="filter">
      <p:selectOneButton onchange="PF('logTable').filter()">
        <f:converter converterId="javax.faces.Boolean" />
        <f:selectItem itemLabel="All" itemValue="" />
        <f:selectItem itemLabel="Ignored" itemValue="#{record.ignored}" />
      </p:selectOneButton>
    </f:facet>
    <h:outputText value="#{record.status}" />
</p:column>

For some reason it is not working properly which i could not find, after searching for some examples online.

A: The item value for this item
<f:selectItem itemLabel="Ignored" itemValue="#{record.ignored}" />

should be either true or false since that is the condition that will be check during the filtering of the records
<f:selectItem itemLabel="Ignored" itemValue="true" />


Q: Splash with 9 patch ruins next activity I have a splash screen with my company's logo in the center of it with a little progress bar under it.
I launch the splash as the first activity, and before that happens I display an image of the splash (without the progress bar, just the logo) using the app's theme background.
I placed a 9 patch image of the in the app's theme android:windowBackground, and when the extension of that file is .9.png - the splash activity is displayed on the top left corner of the screen in a smaller size.
Changing the extension to .png makes the splash display correctly over the whole screen, but of course my first image is stretch horribly ,because it's much smaller than the screen.
Exmaple:
This is the logo

The picture below is how the app looks when the splash has been loaded and I am using the .9.png extension

The picture below is how the app looks when the splash has been loaded and I am using the .png extension

The pic above is how I want the splash to look, but without the .9.png extension the app looks like this (picture below) before the splash loads

Anybody experienced this issue? Couldn't find it online.
Thanks for the help.

A: Solved the issue. Instead of changing the app's theme's windowBackground to my 9patch image, I added a new theme with the 9patch background and attached it to my first activity.
So the basic rule is, don't put a 9patch image in the app's theme background. Place it in the first activity's theme instead.
Source for this solution: https://developer.appcelerator.com/question/149184/9-patch-splash-screen-initial-window-does-not-fill-screen


Q: Accessing App Store Data Is there a way to access app logo, category, price and other app store information using the app store url.
Want my app to be able to access app store information from the apps url.
Is this possible?

A: You can use the iTunes Search API: http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
This page can help you better understand how the iTunes Search API works: http://www.phponwebsites.com/2015/03/get-app-details-from-apple-itunes-using-php.html