text:
Q: Documentation errors tag I have a method in a class where I am triggering an error.
/**
 * Get info
 * @return string|FALSE Info
 */
public function getInfo()
{
    if ($this->info) {
        return $this->info;
    }

    trigger_error('Missing info', E_USER_WARNING);
    return FALSE;
}

I do not want to throw an exception here, as I really want/need this code to continue running. Elsewhere, I log this error, and logging error is out of the scope of this class.
But how do I document this? For an exception I would use:
/**
 * @throws Exception
 */

Is there something similar for errors? I really want other developers to easily know what is going on in my code.

A: There is no phpdoc tag for errors.
trigger_error() returns bool, so your method isn't returning or throwing anything. Execution will resume unless your error handler prevents that, so using @return or @throws would be misusing them, and probably confusing to anyone reading your code.

I would use a different approach.
This is how I would do it:
/**
 * Has info
 *
 * @return bool Whether info is available
 */
public function hasInfo()
{
    return (bool) $this->info; // or use isset() or whatever you need
}

/**
 * Get info
 *
 * @throws Exception
 * @return string The info string
 */
public function getInfo()
{
    if (! $this->hasInfo()) {
        throw new Exception('Missing info');
    }

    return $this->info;
}

And then from your other code, you can do:
if ($object->hasInfo()) {
    $info = $object->getInfo();
} else {
    // no info!
}

I would also catch the Exceptions at the root of my codebase:
try {
    MyApp::run();
}
catch(Exception $e) {
    // handle error, eg. display fatal error message
}

A: I agree with others that I would change my coding approach here, but addressing your direct question -- I would perhaps use the @internal tag to explain the things you're wanting developers to be aware of.  Granted, when you run phpDocumentor against this code, @internal tags won't appear in your generated docs unless you use the --parse-private runtime option... this is because internal-info-for-devs is presumed to be off limits to consumers / API-interested readers, just like "@access private" items are.


text:
Q: How do I remove function added to clicked element, when I click outside of it? I have a funcition that adds mousewheel horizontal scrolling to selected div.
I want to add this function to the element when I click on it, and remove it when I click outside of it. Not sure how to do it though, adding functionality works fine, but I can't figure out how to remove this function if I click outside the div (so even if mouse is within the div, horizontal scrolling won't take place).
Here's my jquery:
$mainDiv.on('click', function() {

    $(this).find($scrollableContainer).horizontal();

});

Function responsive for horizontal scroll (mousewheel plugin):
$.fn.horizontal = function() {

    $(this).mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * 40);
        e.preventDefault();
    });

};

In other words, what I'm trying to achieve is: if user clicks on $mainDiv - add horizontal() function to $scrollableContainer, but if user then clicks outside $mainDiv, remove horizontal() function from $scrollableContainer. I did try clicking on the body but that didn't work:
$('body').on('click', function() {
    $(this).find($scrollableContainer).off();
});

Anyone can help please?

A: First modify the plugin
$.fn.horizontal = function(didgeridoo) {

    this[didgeridoo]('mousewheel', fn);

    function fn(e, delta) {
        this.scrollLeft -= (delta * 40);
        e.preventDefault();
    }

};

then to activate
$mainDiv.on('click', function() {

    $(this).find($scrollableContainer).horizontal('on');

});

and deactivate
$(document).on('click', function() {
    $(this).find($scrollableContainer).horizontal('off');
});

It is rather strange to use a variable in find, unless that variable holds a selector as a string ?
Note that there is no delta as a second argument, and that the mousewheel event is non-standard, and according to MDN shouldn't be used? Are you using another plugin to provide non-standard functionality ?
There are however deltaX and deltaY properties of the event in Chrome and IE, they can be accessed like this
function fn(e) {
    e.preventDefault();

    var delta = e.originalEvent.deltaX;
    this.scrollLeft -= (delta * 40);
}

And MDN has a polyfill that should work cross-browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any words or expressions to describe this situation I am interested in someone at my workplace and want to concentrate on tasks,but unconsciously take a glance at the person again and again. Is there any word to describe the situation? It would not be close to the following words that i came up with such as "concern"or"she has been on my mind".
Much appreciated if you could give me an example and best choice word.

A: This question is not about English. It's about love. :)
I'm thinking of an expression, not a word, to describe how you feel:

"Can't take my eyes off you"

There's even a song you can hum or whistle when you think about that person.

A: Depends who's describing the "interest":

*

*The verb charm describes a subjective or individually pleasing interest, as from beauty or charisma.

*Nouns and phrases like daydreaming, mooning over, or making eyes at describes how a businesslike supervisor might regard such interest.

*Verbs like bother, annoy, disturb or perturb might describe the subject's own reluctant interest.

A: I wonder if you are distracted by the person in your office? This word can have a positive or negative connotation depending on the context - see my two examples below.
1). Negative use of distracted:
I am distracted at work because, like a reflex reaction, I often find myself glancing at my colleague to make sure that she is working and not playing games on her mobile phone.
2). Positive use of distracted:
I am distracted at work because our new member of staff is such a lively and attractive person that I find myself quite unable to stop glancing at her.
Distracted: "Unable to think about or pay attention to something: unable to concentrate". (Merriam-Webster)


text:
Q: How to call the setTimeout? I am being given the below mentioned code and asked to print the console after 3 seconds - B and C after A.
I tried
  setTimeout(main(),3000);

But I get no output.
function sleep(){

}

function main(){

console.log('A');

// call after 3 sec
console.log('B');

// call after 3 sec
console.log('C');

}
}

A: setTimeout(main , 3000);

remove function call '( )'
How setTimeout works:
You specify the function (as a first argument) to be called after your timeout (second argument: 3000)

A: Generally you should pass the function by name to the setTimeout function without calling it.
setTimeout(main,3000);

A: setTimeout(main(), 3000) will execute main immediately because you put the () after it. Just use the name. setTimeout(main, 3000)
Also, you'll want to put your timeout on the two specific log statements you want to call later, not the whole function, or you could also log A outside of the main function and then call the main function after the timeout.

function main() {

  console.log('A');

  // call after 3 sec
  setTimeout(() => {
    console.log('B');
    console.log('C');
  }, 3000);

}

main();

A: You are calling the function in the first parameter of setTimeout. It is supposed to be a callback function(function definition). Just copy the code of the main function inside the setTimeout function and it will work.
The setTimeout Function is used usually with two parameters.

*

*The callback function

*Time in milliseconds

The callback function is called after a given time (second param).
This is how it is called:
const callbackFunction = () =>{
   console.log("Inside callback");
}

setTimeout(callbackFunction, 2000);

OR simply
setTimeout(() =>{
   console.log("Inside callback");
}, 2000);

Output (after 2 secs)
Inside callback

A: try this
    setTimeout(main,3000);

  function main(a){

      console.log('A');

      setTimeout(function(){
        console.log('B');

        setTimeout(function(){
          console.log('C');
        }, 3000);

      }, 3000);

  }

A: Above output could also be reproduced using async-await:

function sleep(time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("");
    }, time);
  });
}

async function main() {
  await sleep(0);
  console.log('A');

  // call after 3 sec
  await sleep(3000);
  console.log('B');

  // call after 3 sec
  await sleep(3000);
  console.log('C');

}
main();


text:
Q: Generate CREATE TABLE statement from arbitrary SQL query Is there script/procedure/function that can generate a CREATE TABLE statement from an arbitrary SQL query?
When building procedures, I'd like to have a quick way to generate a temporary table, rather than having to review the table definitions of all of the tables referenced in the query.
Simple example:
SELECT p.pat_id, pat_name,
       enc_id, admsn_time, disch_time
FROM   patient p
INNER JOIN encounter e ON p.pat_id=e.pat_id
WHERE  admsn_time >= '01/01/2014'

Would generate (columns' data definition is retrieved from the system table):
-- randomly-generated table name
CREATE TABLE #random_name (
  PAT_ID      VARCHAR(18) NOT NULL,
  PAT_NAME    VARCHAR(200),
  ENC_ID      NUMERIC(18,0) NOT NULL,
  ADMSN_TIME  DATE,
  DISCH_TIME  DATE
)

SSMS workflow:

*

*select the text

*right click, select Generate CREATE TABLE statement (function/script/proc called; result placed on clipboard)

*place cursor in desired location

*paste

A: This is a bit of a hack, but you could try selecting into a table (see line #3):
SELECT p.pat_id, pat_name,
   enc_id, admsn_time, disch_time
INTO delete_me
FROM   patient p
INNER JOIN encounter e ON p.pat_id=e.pat_id
WHERE  admsn_time >= '01/01/2014'

Then you can highlight the delete_me table in SSMS, right-click, and generate the CREATE TABLE script.
Finally, you'd want to DROP TABLE delete_me to clean up.

A: use
SELECT p.pat_id, pat_name,
       enc_id, admsn_time, disch_time
into #randomtable
FROM   patient p
INNER JOIN encounter e ON p.pat_id=e.pat_id
WHERE  admsn_time >= '01/01/2014'

and your table will be created when you execute the statement.

A: First of all, I would make a stored procedure of the query. (It keeps me from forgetting it later)
Secondly, I would write a query to generate the table for me:
DECLARE @CREATE_TABLE_QUERY NVARCHAR(MAX) = N'';

SELECT
    @CREATE_TABLE_QUERY += ', ' + name + ' ' + UPPER(system_type_name) + CHAR(13) + CHAR(10) + CHAR(9)

FROM
    sys.dm_exec_describe_first_result_set('YOUR_PROCEDURE_NAME_HERE', NULL, 1);

SELECT
    @CREATE_TABLE_QUERY = N'CREATE TABLE TABLE_NAME_HERE(' + CHAR(13) + CHAR(10) + CHAR(9) + STUFF(@CREATE_TABLE_QUERY, 1, 1, N'') + ');';

PRINT @CREATE_TABLE_QUERY;

Note: Replace 'YOUR_PROCEDURE_NAME_HERE' with the name of your own stored procedure.
Note: Replace TABLE_NAME_HERE with the table name of your choice.
The above will generate something like this:
CREATE TABLE TABLE_NAME_HERE(
     WeekName VARCHAR(40)
    , Line Name VARCHAR(50)
    , TheDate DATETIME
    , ReceivedAll INT
    , Answered INT
    , Abandoned INT
    , Call Length INT
    , WaitTimeAnswer INT
    , WaitTimeAbandon INT
    , PeriodName VARCHAR(10)
    , Week SMALLINT
    , Period SMALLINT
    , Year SMALLINT
    , WeekInPeriod SMALLINT
    , NumWeeksInPeriod SMALLINT
    , WeekendDate DATETIME
    , CRCOperative VARCHAR(100)
    , CallType VARCHAR(20)
    , Charge Time INT
    , SourceNumber VARCHAR(80)
    , DestinationNumber VARCHAR(80)
    , CallStart DATETIME
    , Out of Hours VARCHAR(12)
    , IsWorkingDay BIT
    );


text:
Q: Windows 8.1 store apps architecture I'm wondering if this architecture is possible for an Windows Store application.
To resume briefly, i have a main apps which contain components (those can have view/ViewModel...). Those components are accessible via an hub in the main project. To ensures maintainability, i'd like to order my components as subprojects of my solution. I'd like to be able to debug through subproject.
Here is an example :

*

*Solution

*

*MainProject (hub)

*subProject1 (hubtile1)

*

*views

*viewModels

*subProject2 (hubtile2)

*

*views

*viewModels

... and so on.
The question is : how to achieve that ?
Is it possible to include a subproject as view with viewmodel linked in ? in that way i (or other) could dev each subproject separately.
If it's possible will my subProject would be able to discuss with each other (like subProject1 wants to share some infos with subProject2) ?
Thanks in advance for any hint :-)

A: I would not create a project for every single hub. It's not best practise and will slow down Visual Studio. I saw such a project...
I would suggest a structure like:
BusinessLogic (project)
DataAccess (project)
UI (project)
  Assets
  Controls
  Pages
  Styles
  UserControls
  ViewModels
With this approach you'll also preventing to have too many namespaces.


text:
Q: how to unhide the letters in this game? it's a guess-the-letter game something like hangman. it generates a random word in the length of 4 or 5 it's the user's choice and after that, it displays it like this ^^^^ for 4 letters for example. each time user can guess a letter if it's not right I display a message and says it but if it's right has to display that it is right and display the word something for example like this ^a^^. the letter has to be exactly in the position of the original word. can someone help me with the part where the letter that is guessed is right? How shoul i code that this format ^^^^ be forexample like ^a^^ if the letter guessed is right?
# Choosing the words
if result2 == 4:
    word = choice(word4)
else:
    word = choice(word5)
guess_list = []  # List of guess letters
sec_word = []  # the list for formatting the random word
for i in range(len(word)):
    sec_word.append("*")  # To format the random word into ****
while result1 > 0:  # Start of the guessing game on the condition that guess left is greater than 0
    print("word is:", "".join(sec_word))  # Displaying the word
    # Displaying the remaining guess number
    print("Guess remaining:", num_guess)
    print("Previous guess:", guess)  # Showing the previous guest
    guess = input("Please guess a letter: ")
    guess_list.append(guess)  # Add the guess letters to a list
    if guess.lower() == "stop" or guess.lower() == "exit":
        print("Game Ends!")
        break  # Letting user end the game at anytime
    if guess not in guess_list:
        if guess in word:  # if the user guess correct letter
            print(guess, "is in the word")
        else:  # if the user guess wrong letter
            print("Sorry! letter entered is not present in the word!")
    else:
        # If a letter is already in list
        print("You have already guessed that letter, Try another letter")
    result1 -= 1  # After each guess the remaining guess time drops 1 time

and output of the code is supposed to be something like this
Word is: ****
Guesses remaining: 6
Previous Guesses:
Choose a letter to guess: a
'a' is NOT in the word! Try again!
Word is: ****
Guesses remaining: 5
Previous Guesses: a
Choose a letter to guess: b
'b' is in the word!
Word is: b***
Guesses remaining: 4
Previous Guesses: a
Choose a letter to guess: l
'l' is in the word!
Word is: bl**
Guesses remaining: 3
Previous Guesses: a
Choose a letter to guess: a
'a' is NOT in the word and has been guessed before.
Guesses remaining: 3
Choose another letter to guess: e
'e' is in the word!
Word is: bl*e
Guesses remaining: 2
Previous Guesses: a
Choose a letter to guess: exit

A: I think this base code will work for this,
Note: You need to find index of all occurrences if character is present more than twice in word ( ex: pool ) here o is occurring twice, so you can loop over the base method to replace both occurrences
original_word = 'avatar'
masked_word = '*' * len(original_word)

i = 4 # this is index of character

if(i == 0):
    masked_word = original_word[0] + masked_word[1:]
elif(i == len(original_word)-1):
    masked_word = masked_word[:i] + original_word[i]
else:
    masked_word = masked_word[:i] + original_word[i] + masked_word[i+1:]

print(masked_word)


text:
Q: need some assistance with a perfect number exercise in C# (this isn't homework, just an exercise in the book I'm using)

"An integer is said to be a perfect number if its factors, including
  one (but not the number itself), sum to the number. For example, 6 is
  a perfect number, because 6 = 1 + 2 + 3. Write method Perfect that
  determines whether parameter value is a perfect number. Use this
  method in an app that determines and displays all the perfect numbers
  between 2 and 1000. Display the factors of each perfect number to
  confirm that the number is indeed perfect."

The problem is that it is displaying the perfect numbers twice instead of once. Why is it doing this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Perfect_Numbers2
{
class Program
{
static bool IsItPerfect(int value)
{
    int x = 0;

    bool IsPerfect = false;

    List<int> myList = new List<int>();

    for (int i = value; i == value; i++)
    {
        for (int j = 1; j < i; j++)
        {
            if (i % j == 0)  // if the remainder of i divided by j is zero, then j     is a factor of i
            {
                myList.Add(j); //add j to the list

            }

    }
        x = myList.Sum();
        // test if the sum of the factors equals the number itself (in which     case it is a perfect number)
        if (x == i)
        {
            IsPerfect = true;

            foreach (int z in myList)
            {
                Console.Write("{0} ",z);

            }

            Console.WriteLine(".  {0} is a perfect number", i);
        }

    }
    return IsPerfect;
}

static void Main(string[] args)
{
    bool IsItAPerfectNum = false;

    for (int i = 2; i < 1001; i++)
    {
        IsItAPerfectNum = IsItPerfect(i);

        if (IsItPerfect(i) == true)
        {

            Console.ReadKey(true);
        }

    }
}
}
}

A: You're calling IsItPerfect twice, which causes it to evaluate the code in that method twice. That method writes the number to the console, so it's displaying the number twice.
You could rewrite the code as follows, which would eliminate the issue and prevent you from executing the same logic twice:
static void Main(string[] args)
{
    for (int i = 2; i < 1001; i++)
    {
        bool IsItAPerfectNum = IsItPerfect(i);

        if (IsItAPerfectNum)
        {
            Console.WriteLine("{0} is a perfect number", i);
            Console.ReadKey(true);
        }
    }
}

And of course, remove the corresponding Console.WriteLine from your ItIsPerfect method.

A: You are calling IsItPerfect(i) twice, and it contains a Console.WriteLine().  You need to remove the IsItPerfect(i) before the if. I'd also recommend removing the UI from your method altogether - its bad practice.


text:
Q: Best Practices for RSpec expect raise_error I have some code for RSpec.
My (or not my) Class can (or not) call specific exception.
Ex, Class::Foo::Bar::TimeOutError.
I want check it.
describe :describe_description do
  before :all do
    object = Class.new
    # method can be call Class::Foo::Bar::TimeOutError
    object.method
  end
  it :exception do
    expect {}.to_not raise_error Class::Foo::Bar::TimeOutError
  end
end

This code worked, but RSpec write a Warning:

WARNING: Using expect { }.not_to raise_error(SpecificErrorClass) risks false positives, since literally any other error would cause the expectation to pass, including those raised by Ruby (e.g. NoMethodError, NameError and ArgumentError), meaning the code you are intending to test may not even get reached. Instead consider using expect {}.not_to raise_error or expect { }.to raise_error(DifferentSpecificErrorClass). This message can be suppressed by setting: RSpec::Expectations.configuration.on_potential_false_positives = :nothing.

How can I fix my code so that the RSpec works correctly and does not issue warnings?

A: No, there isn't a way to apply expect {}.to_not raise_error in the spec without this warning (that's the whole point of adding this warning).
It doesn't make sense logically because you don't need to explicitly check a type of error is not raised.
Scenario 1. The code executes successfully (i.e no errors at all). Then a passing test itself implies there's no Class::Foo::Bar::TimeOutError thrown.
Scenario 2. Another type of error is thrown. Then expect {}.to_not raise_error Class::Foo::Bar::TimeOutError isn't testing anything, it still just passes which creates false positive.
Scenario 3. If you really want to use it, suppress with the setting on_potential_false_positives then the test will continue without the warning. If it passes, then this has no difference with the scenario which makes expect {}.to_not raise_error redundant anyway.

A: For a future-proof solution I recommend setting
RSpec::Expectations.configuration.on_potential_false_positives = :raise

And fixing any offending examples from
expect { some_call }.to not_raise_error(SomeErrorClass)

to
expect { some_call }.to not_raise_error
# OR
expect { some_call }.to raise_error(SomeOtherErrorClass)


text:
Q: Redshift: Total Row Count for all tables for a particular user We use Periscope which charges(I think) by the total number of rows that are present in the tables that we give it access to.
My question is: Given a user periscope, how do I obtain the total count of rows in the tables that the user periscope has access to?
E.g. if the user periscope can only access two tables: t1 with count 8 and t2 with count 2, the total count should be 10.
I got all the tables with this answer(excluding 'pg_tables' and 'information_schema') but I don't know how to go about next:
SELECT CAST(schemaname as varchar), CAST(  objectname as varchar)
FROM
    (
    SELECT
        schemaname
        ,objectname
        ,usename
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AS sel
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AS ins
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'update') AS upd
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'delete') AS del
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'references') AS ref
    FROM
        (
        SELECT schemaname, 't' AS obj_type, tablename AS objectname, schemaname + '.' + tablename AS fullobj FROM pg_tables
        WHERE schemaname not in ('pg_internal')
        UNION
        SELECT schemaname, 'v' AS obj_type, viewname AS objectname, schemaname + '.' + viewname AS fullobj FROM pg_views
        WHERE schemaname not in ('pg_internal')
        ) AS objs
        ,(SELECT * FROM pg_user) AS usrs
    ORDER BY fullobj
    )
WHERE (sel = true or ins = true or upd = true or del = true or ref = true)
and usename = 'periscope'
and schemaname not in ('information_schema', 'pg_catalog');

If you have an elegant solution, please let me know!

A: This should give you what you need:
SELECT SUM(b.reltuples)
FROM
(
    SELECT
        schemaname
        ,objectname
        ,usename
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AS sel
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AS ins
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'update') AS upd
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'delete') AS del
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'references') AS ref
    FROM
    (
        SELECT schemaname, 't' AS obj_type, tablename AS objectname, schemaname + '.' + tablename AS fullobj FROM pg_tables
        WHERE schemaname not in ('pg_internal')
        UNION
        SELECT schemaname, 'v' AS obj_type, viewname AS objectname, schemaname + '.' + viewname AS fullobj FROM pg_views
        WHERE schemaname not in ('pg_internal')
        ) AS objs
        ,(SELECT * FROM pg_user) AS usrs
    ORDER BY fullobj
) as a
JOIN
(
    SELECT
        nspname AS schemaname,relname,reltuples
    FROM pg_class C
    LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
    ORDER BY reltuples DESC
) as b
ON (a.schemaname = b.schemaname AND a.objectname = b.relname)
WHERE (sel = true or ins = true or upd = true or del = true or ref = true)
and usename = 'periscope'
and a.schemaname not in ('information_schema', 'pg_catalog');


text:
Q: Karaf - Error rendering Swagger API due "org.apache.camel.model.cloud" doesnt contain ObjectFactory.class or jaxb.index I am trying to build camel-rest dsl with KARAF, but the swagger seemed isn't work.
javax.xml.bind.JAXBException: "org.apache.camel.model.cloud" doesnt contain ObjectFactory.class or jaxb.index
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:260) ~[jaxb-runtime-2.3.3.jar:2.3.3]
    at com.sun.xml.bind.v2.JAXBContextFactory.createContext(JAXBContextFactory.java:48) ~[jaxb-runtime-2.3.3.jar:2.3.3]
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:302) ~[?:?]
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:478) ~[?:?]
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:435) ~[?:?]
    at org.apache.camel.xml.jaxb.DefaultModelJAXBContextFactory.newJAXBContext(DefaultModelJAXBContextFactory.java:39) ~[?:?]
    at org.apache.camel.xml.jaxb.DefaultModelJAXBContextFactory.newJAXBContext(DefaultModelJAXBContextFactory.java:29) ~[?:?]
    at org.apache.camel.xml.jaxb.JaxbModelToXMLDumper.getJAXBContext(JaxbModelToXMLDumper.java:195) ~[?:?]
    at org.apache.camel.xml.jaxb.JaxbModelToXMLDumper.dumpModelAsXml(JaxbModelToXMLDumper.java:69) ~[?:?]
    at org.apache.camel.swagger.RestSwaggerSupport.getRestDefinitions(RestSwaggerSupport.java:152) ~[!/:3.5.0]
    at org.apache.camel.swagger.RestSwaggerSupport.renderResourceListing(RestSwaggerSupport.java:232) ~[!/:3.5.0]
    at org.apache.camel.swagger.RestSwaggerProcessor.process(RestSwaggerProcessor.java:120) [!/:3.5.0]

It is just a normal rest configuration
   restConfiguration()
                // Use the 'servlet' component.
                .component("jetty")
                .host("localhost").port(8080)
                // Allow Camel to try to marshal/unmarshal between Java objects and JSON
                .bindingMode(RestBindingMode.auto)
                .dataFormatProperty("prettyPrint", "true")
                .dataFormatProperty("mustBeJAXBElement", "false")
                .apiContextPath("api-doc")
                .apiProperty("api.title", "User API")
                .apiProperty("api.version", "1.0.0")
                .enableCORS(true);

   rest().path("/api")
                .consumes("application/json")
                .produces("application/json")
                .get()
                .outType(ResponseType.class)
                       .description("Get Response").type(ResponseType.class)
                       .param().name("ab").type(RestParamType.path).description("blah").endParam()
   ...

pom.xml
 <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>osgi.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>osgi.cmpn</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.karaf</groupId>
            <artifactId>camel-core-osgi</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-swagger-java</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <!-- JSON support -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jackson</artifactId>
            <version>${camel.version}</version>
        </dependency>

    </dependencies>

Calling as rest dsl service is working fine, but swagger API is not working, the camel-core-engine did have the jaxb.index file. I can't find any reason why felix cannot find it, or felix didn't include this file?

A: Looks like this will be fixed in https://issues.apache.org/jira/browse/CAMEL-16040 .  I don't think this impacts blueprint users but as Claus mentions in the comment if you create your own camel context you'll need a camel release that includes this fix.


text:
Q: ngFor weird different behavior I'm try get the first asset from a list of Posts. This list came from a web api.
import { Component, OnInit } from '@angular/core';
import { BlogPostService } from '../services/blog-post.service';
import { BlogPost } from '../modules/blog-post';

@Component({
  selector: 'af-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

      blogPosts: BlogPost[];
      skip: number;
      showPrevious = false;
      constructor(private blogService: BlogPostService) { }

      ngOnInit() {
        this.skip = 0;
        this.getPosts(this.skip);
      }

      getPosts(skip: number) {
        this.skip = skip;

        this.blogService.getBlogPosts(skip).subscribe(dt => this.blogPosts = dt});
      }
      getAssetById(id: string) {
        console.log('id:', id);
      }
    }

the strange behavior happens on the front end side. blogPosts is a list of 4 but just 2 haven images.
if I try just print the values like this:

        {{ post.fields.images && post.fields.images[0].sys.id}}

The result is 4 divs and just 2 with ids. It is what I'm expecting.

        {{ post.fields.images && getAssetById(post.fields.images[0].sys.id) }}

but in this case, console logs 4 times. It logs the post that images exist and repeats the value for that not exists.

A: In development mode, Angular runs change detection twice to ensure that the model has stabilized after the first pass. If not, you would see an error (something like "Expression has changed after it was checked..."). So you are seeing the result of Angular calling your function twice for each element that has an image.
If you run in production mode, your function will be called only once for each element that has an image.
Check out this post for more details.


text:
Q: Function headers this is more of a confusing question problem where i dont really understand what the question wants me to put down as an answer.
Question:
Write function headers for the functions described below:
(i) The function check has two parameters. The first parameter should be an integer number and the second parameter a floating point number. The function returns no value.
Thats just the first one since all im really looking for is maybe an example of some kind for what i should put down as an answer. If anyone can help me out with this it would be wonderful.
Thanks!

A: void check(int, float);
(Normally I'd give the parameters names to help indicate semantics, but we aren't given enough information here.)


text:
Q: Google Cloud: prevent users from syncing to other instances I want an instance having a local user with the purpose of running and owning a service on that instance. I have tried creating it with a simple
adduser <username>

as well as following,
https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#instance-only, according to the following
instance_a='<instance_a>'

ssh-keygen -t rsa -C "test_ssh_key"
gcloud compute instances add-metadata $instance_a --metadata-from-file ssh-keys=test_ssh_key.pub
gcloud compute ssh $instance_a --ssh-key-file='test_ssh_key'

However, in both cases, the created user is automatically synced to all other running instance in the project. Also, in the second case, I'm able to ssh into a second instance even though the documentation says it's for a single instance, despite the ssh key not showing up with
gcloud compute instances describe $instance_a

Note that ssh with the newly created key works using both gcloud compute ssh and regular ssh.
Does anyone know how to properly either create a truly local user on an instance or alternatively turn off the service syncing users having no ssh login?

A: You can't do this using Google managed SSH keys (when you use gcloud compute ssh)
Using instance level SSH will work (as you are doing), just make sure to remove any project level metadata for the same user.
Also make sure the new user is completely limited by
A) Make sure the user does not have IAM permissions to use google managed SSH
B) Limit the scopes of the default service account on the instance to ensure users are not using that to bypass the security measures you have in place.


text:
Q: Why doesn't this conditional expression generate a SyntaxError? When "if" is combined with "or", which one Python prioritize first:
for example:
if a == b or c

is it (a == b) or c  or is it a == (b or c).
I assume the correct logical form should be the former one but I accidentally used:
if gender == "m' or "M"

and to my surprise, it did not generate any errors and did the purpose.

A: From the documentation:

The following table summarizes the operator precedence in Python, from
  lowest precedence (least binding) to highest precedence (most
  binding).
lambda
if – else
or
and
not x
in, not in, is, is not, <, <=, >, >=, !=, ==
...

So, to answer your question,
a == b or c

Is equivalent to
(a == b) or (c)

The code if gender == "m" or "M" will work like this: Is gender == 'm"? If yes, the result is True. Otherwise, test the "truthiness" of "M". Is "M" "true"? If it is, the result is true. To understand how this works, you should know that all objects have a truthiness associated to it. All non-zero integers, non-empty strings and data structures are True. 0, 0.0, '', None, False, [], {} and set() are all False.
For more details, visit How do I test one variable against multiple values?


text:
Q: Reading/Setting socket header information [Node.js] I am currently working on a project that involves a few layers of TCP communication. For the purpose of this project, most of the TCP communication that needs to be implemented is user validation and forwarding streams to their corresponding endpoints. One problem I keep running into is that there is no way to access any header information from incoming sockets that I know of or can find in the net documentation.
I have found similar questions with no results on this. I've also found a node module that can make connections with raw sockets, but making connections is only half the battle here.
Is there another module, native or not, that solves this? Or is there a way to access the necessary layer through the net implementation?
Edit 1 (for clarity):
I'm trying to make a router for multiple RTMP servers. Connections will come in, and depending on header information like the path and query string, they either be rejected because their credentials were invalid, or they will be forwarded to the relevant server.
I am using node-media-server as my server base. For the router, there currently isn't much code, because what I want to do and implement relies on this.
const testNet = net.createServer((socket)=>{

    /*
     *  TODO: validate credentials given by socket, reject if invalid
     */

    /*
     *  TODO: Create ID for socket and create a header that
     *        reflects this new id and the new endpoint
     */

    let newConnection = net.createConnection({port:1937, host:host}, () => {
        newConnection.on('end', () => {
            socket.end();
            newConnection.end();
        });
    });
    socket.pipe(newConnection);
    newConnection.pipe(socket);
    socket.on('end', () => {
        newConnection.end();
        socket.end();
    });
}).listen(1935,host,()

I'm still learning the bridge between RTMP and TCP, so I understand if there are still some missing gaps with what I've presented. I hope that this was enough information to clear up what I want to do, and what I want to know.


text:
Q: matlab inline function with special handling for zero I have a function that has a singularity at zero. The resulting value should be at that point 1.
However I fails to understand how to create an inline function that has a special treatment for values of x and y at x or y = 0.
The function could for example be
f = @(x,y) ( 1./x + 1./y );

A: To answer your question with a counter-question: why do you want it to be inline?
As a general rule, keep inline functions simple. If more functionality is needed, use a dedicated function:
function val = f(x,y)

    if ~all(size(x)==size(y))
        error('sizes must match');

    val = zeros(size(x));

    zero_x = x==0;
    zero_y = y==0;

    not_zero = ~zero_x & ~zero_y;
    zero = ~not_zero;

    val(not_zero) = 1./x(not_zero) + 1./y(not_zero);
    val(zero) = 1;

end

Having said that, there are of course ways to do it inline (see other answers).
But as you indicated, your actual function is more complex, so...why inline?

A: As dirty trick you could replace x with x + (x==0)
Then if x equals zero you would have 0+1 in the denominator.

In some cases you could also abuse operators that "short circuit".
Like ~isfinite(f(x)) || f(x)

A: Create the following iif.m function file, residing in your working folder, or even as a subfunction if you're using it in other functions (scripts of course can not contain subfunctions):
function val = iif(expr, truepart, falsepart)
    if isscalar(truepart)
        truepart=truepart(ones(size(expr)));
    end
    if isscalar(falsepart)
       falsepart=falsepart(ones(size(expr)));
    end
    val = arrayfun(@iif_scalar, expr, truepart, falsepart);
end
function val = iif_scalar(expr,truepart,falsepart)
    if expr
        val = truepart;
    else
        val = falsepart;
    end
end

and use it as follows:
f = @(x,y) iif(x==0 | y==0, 1, 1./x + 1./y );

I kept the iif function as general as possible, you can use it on vectors, scalars, mixed scalar and vectors, or even matrices. For example, in the above I used 2 vectors and a scalar:
iif( ...
     x==0 | y==0 ,... % expression if x or y are 0 => vector
     1 , ...          % scalar obviously
     1./x + 1./y ...  % function of x and y => vector
   )

A: I think this is roughly what most people would want in this case.
1+sum([repmat(nan,~**0**,1) 0])

ans =
   NaN
1+sum([repmat(nan,~**1**,1) 0])

ans =
   1
Now generalizing:
zero2nanElseNum_inline = @(x) x*(1+sum([repmat(nan,~x,1) 0]))

zero2nanElseNum_inline(0)

ans =
   NaN
zero2nanElseNum_inline(10)

ans =
   10
zero2nanElseNum_inline(1)

ans =
   1

For the specific case at hand, you could simply take the code snippet:
sum([repmat(nan,~**0**,1) 0])

feed it in to isnan:
isnan(sum([repmat(nan,~**0**,1) 0]))

and add the result to your original number.


text:
Q: Estimating biomass in mangroves in google earth engine I am working on a project estimating biomass production and carbon storage in mangrove forests.
I looked upon examples estimating biomass production using NPP and GPP such as https://mygeoblog.com/2016/10/19/biomass-production-from-npp/ and https://mygeoblog.com/2016/10/18/measuring-carbon-storage-from-space/ .
These examples are using Modis MOD17A3H.006: Net Primary Production Yearly L4 Global 500 m and MYD17A2H.006: Gross Primary Productivity 8-Day L4 Global 500 m  data.
But these products are lacking data in mangroves sites (I am focussing on Sundarbans and some other mangrove sites in India). Of which I think the reason is that wetlands are assigned fill values https://lpdaac.usgs.gov/dataset_discovery/modis/modis_products_table/mod17a2h_v006 and https://lpdaac.usgs.gov/dataset_discovery/modis/modis_products_table/mod17a3h_v006 .
Can anyone guide me what dataset would be best for mangroves? Can you guide with examples and algorithm to use?


text:
Q: Error Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING I get this error:

"Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '(' in [wordpress dir]/wp-content/themes/[my-theme]/functions.php on line 14"

And line 14 is just a simple use command...
Line 13-15:
add_action('headway_setup_child_theme', array('HeadwaySchematic', 'init'), 1);
use mfbcaptheme\mobilebrowsertheme;
require_once 'mobilebrowsertheme.php';

This is on a client's site and it works just fine on my test site....Not sure what would cause this error.

A: Make sure they are running PHP 5.3 or later. If they are running an earlier version they won't have support for namespaces.


text:
Q: Json web token generation in angular4 or javascript How can I generate JSon web token for a user who just login into the application in angular2/4 application

A: generating a token is a back-end side job and angularJs should just store it and send it to server to validate user data and basically generating it in front-end isn't a good idea cos you'r key will get in people's hand and they can generate tokens with it that server will validate it as True and it will make problems and error's for application.

A: You can't generate web token from client side. Please use https://jwt.io/ to use it in your own server side language and use https://github.com/auth0/angular2-jwt this library to consume it.

A: Actually there are number of way by using you can create JSON web token for your app, for example using btoa approach , or using jwt.io etc.

But Why to generate JSON web token ?

Generally JSON web token should be generated from back end side and which is safe also, so don't try this on client side.


text:
Q: website made from replit is not displaying text properly I am having some problems making the website mobile friendly. the text starts coming up all weird and not in alignment at all. Any suggestions as to what I can add to make the text normal again.
website coded in html, js, python
On pc
On phone
This is happening in some other webpages too
The code block regarding this:

    {%block content%}
    {%include 'navbar.html'%}
    {%endblock%}

    <form method="POST" action="{{url_for('test_results')}}">

A test to help you explore careers

Are you ...?

        {%for i in are_you%}
        {%for j in are_you[i]%}

<input type="checkbox" name="{{i}}">{{j}}

        {%endfor%}
        {%endfor%}

Can you ...?

        {%for i in can_you%}
        {%for j in can_you[i]%}

<input type="checkbox" name="{{i}}">

A: Your website is not responsive. If you don't want to make the code responsive by yourself, you can use CSS libraries like bootstrap to do the heavy work for you.


text:
Q: Using javascript, is there any way to remove characters from inside an element while leaving the other objects inside that div untouched? I have a div that contains text and an anchor tag.

    some text here

    more text

I'd like to remove the characters "more text" from inside the div, but I can't just replace the html of the header div because there's javascript that's already been attached to the button that I can't reattach if I were to replace the contents of the div entirely. Is there any way I could just strip out specific words or characters but leave the rest of the elements untouched?
Thanks!
Edit: using jQuery is an acceptable option.


text:
Q: DataTable.Load returning 'Cannot convert string to int' when using parameters I am trying to execute a SQL statement that simply returns the value of a parameter.
In the below example, my command is 'Select txtName = ?' and I add a single string parameter with a value of 'test':
OdbcCommand command = CreateCommand(query, controls);
command.Connection = _OdbcConnection;
OdbcDataReader reader = command.ExecuteReader();
ExtendedDataTable Results = new ExtendedDataTable();
Results.Load(reader);
return Results;

When this attempts to load the results into the Results table, I receive an error "Cannot convert 'test' to a int".
I have also confirmed from the DataTable.GetSchemaTable() command that it does think my value is of type int16, which it obviously is not.
If I run the below statement instead, it works perfectly fine, so I know my parameter is working
Select txtName = 'test' where ? = 'test'

If it helps, the OdbcCommand is connecting to a SQL Anywhere 11 database. Also, the ExtendedDataTable type is basically just a DataTable (nothing special that should impact types).


text:
Q: How to toggle jqGrid display using jQuery? We have two jqGrid grids - we only want to display one at a time based on a user's input.
Each grid, when displayed, should appear on the screen at the same location.
What is the easiest way to achieve this?
Currently we just have our HTML set up with

 and then we create the grid with $("#list").jqGrid({....

A: jqGrid create some divs over table and pager elemetes. The id of the div which contain all the jqGrid elements is a div with id="gbox_list" in your case.
So to hide the grid you cane use $("#gbox_list").hide(); and to show it back: $("#gbox_list").show();. If you want to use another toggle effectes which you needs, but with the same $("#gbox_list") object.

A: HTML:
Toggle

JQuery:
$("a#click1").click(function() {
    $("table#list1").toggle();
    $("table#list2").toggle();
});

PS. I am wondering whether jqGrid will work on items that have display: none and are thus effectively removed from the DOM; if it doesnt work out you might want to adapt the toggle() function to use the visibility property instead.
$("table.list").toggle(
    function() {
        $(this).css({"visibility": "hidden"});
    },
    function() {
        $(this).css({"visibility: "visible"});
    }
);


text:
Q: Bigquery sql: Replace keys of json to a new values present in a column I have two tables in Big Query as shown: table_1 has id, properties in json format, collection columns repectively.
table_2 has collection, property_key, property_name columns
I want to replace the json keys in properties column from table_1 with property_name from table_2
condition: where tabe_1.collection = table_2.collection and also property_key in table_2 contains the actual json_key's
Table_1:

id
properties
collection

workflow:623a776f04f1527a7bc2b3ed
{"counterpartyName_string":{"type":"string","value":"XYZ"},"signerc_string":{"type":"string","value":"xyz_a"},"signer3_email":{"type":"email","value":"cyz@gmail.com"},"custome54_string":{"type":"string","value":"No (default answer)"},"paperSource_string":{"type":"string","value":"Our paper"},"acceptanceType_string":{"type":"string","value":"eSignature"},"agreementDate":{"type":"date","value":"2018-04-02"},"workflowId":{"type":"string","value":"123"},"workflowCreatedDate":{"type":"date","value":"2018-03-23"},"workflowUpdatedDate":{"type":"date","value":"2022-04-02T15:16:24.688Z"},"workflowCreator":{"type":"string","value":"6008"},"workflowOwner":{"type":"string","value":"6008"},"workflowConfigurationVersionNumber":{"type":"number","value":12.0}}
57b4c959e899aa130069e4e0

52523e7b-0a19-4551-be43-5c1d124beea0
{"amendment":{"type":"boolean","value":false},"10vs25term":{"type":"string","value":"10 Term"},"counterpartyAddress":{"type":"string","value":"USA"},"agreementDate":{"type":"date","value":"2018-11-05"},"contractType":{"type":"string","value":"ABC"},"contactForNotice":{"type":"string","value":"UMC"},"statementOfWork":{"type":"boolean","value":false},"mastercardEntity":{"type":"string","value":"Master"},"folder":{"type":"string","value":"NDA"},"importBatch":{"type":"string","value":"Sale"},"counterpartyName":{"type":"string","value":"Gra"},"documentID":{"type":"string","value":"115"},"region":{"type":"string","value":"United States"},"effectiveDate":{"type":"date","value":"2018-11-05"}}
5db09e5d9c32aaa121bf4ca1

Table_2:

collection
property_key
property_name

57b4c959e899aa130069e4e0
counterpartyName_string
Counterparty Name

57b4c959e899aa130069e4e0
signerc_string
Counterparty Signer Name

57b4c959e899aa130069e4e0
signer3_email
Counterparty Signer Email

57b4c959e899aa130069e4e0
custome54_string
Equipment

5db09e5d9c32aaa121bf4ca1
amendment
Amendment

5db09e5d9c32aaa121bf4ca1
10vs25term
10 vs 25 Term

5db09e5d9c32aaa121bf4ca1
counterpartyAddress
Counterparty Address

5db09e5d9c32aaa121bf4ca1
agreementDate
Agreement Date

I wanted the result table be like a new column with changed properties field from table_1 as shown
Result_table:

id
properties
collection
renamed_properties

workflow:623a776f04f1527a7bc2b3ed
{"counterpartyName_string":{"type":"string","value":"XYZ"},"signerc_string":{"type":"string","value":"xyz_a"},"signer3_email":{"type":"email","value":"cyz@gmail.com"},"custome54_string":{"type":"string","value":"No (default answer)"},"paperSource_string":{"type":"string","value":"Our paper"},"acceptanceType_string":{"type":"string","value":"eSignature"},"agreementDate":{"type":"date","value":"2018-04-02"},"workflowId":{"type":"string","value":"123"},"workflowCreatedDate":{"type":"date","value":"2018-03-23"},"workflowUpdatedDate":{"type":"date","value":"2022-04-02T15:16:24.688Z"},"workflowCreator":{"type":"string","value":"6008"},"workflowOwner":{"type":"string","value":"6008"},"workflowConfigurationVersionNumber":{"type":"number","value":12.0}}
57b4c959e899aa130069e4e0
{"Counterparty Name":{"type":"string","value":"XYZ"},"Counterparty Signer Name":{"type":"string","value":"xyz_a"},"Counterparty Signer Email":{"type":"email","value":"cyz@gmail.com"},"Equipment":{"type":"string","value":"No (default answer)"},"Paper Source":{"type":"string","value":"Our paper"},"Acceptance Type":{"type":"string","value":"eSignature"},"Agreement Date":{"type":"date","value":"2018-04-02"},"Workflow Id":{"type":"string","value":"123"},"Workflow Created Date":{"type":"date","value":"2018-03-23"},"Workflow Updated Date":{"type":"date","value":"2022-04-02T15:16:24.688Z"},"Workflow Creator":{"type":"string","value":"6008"},"Workflow Owner":{"type":"string","value":"6008"},"Workflow Configuration Version Number":{"type":"number","value":12.0}}

52523e7b-0a19-4551-be43-5c1d124beea0
{"amendment":{"type":"boolean","value":false},"10vs25term":{"type":"string","value":"10 Term"},"counterpartyAddress":{"type":"string","value":"USA"},"agreementDate":{"type":"date","value":"2018-11-05"},"contractType":{"type":"string","value":"ABC"},"contactForNotice":{"type":"string","value":"UMC"},"statementOfWork":{"type":"boolean","value":false},"mastercardEntity":{"type":"string","value":"Master"},"folder":{"type":"string","value":"NDA"},"importBatch":{"type":"string","value":"Sale"},"counterpartyName":{"type":"string","value":"Gra"},"documentID":{"type":"string","value":"115"},"region":{"type":"string","value":"United States"},"effectiveDate":{"type":"date","value":"2018-11-05"}}
5db09e5d9c32aaa121bf4ca1
{"Amendment":{"type":"boolean","value":false},"10 vs 25 Term":{"type":"string","value":"10 Term"},"Counterparty Address":{"type":"string","value":"USA"},"Agreement Date":{"type":"date","value":"2018-11-05"},"Contract Type":{"type":"string","value":"ABC"},"Contact For Notice":{"type":"string","value":"UMC"},"Statement Of Work":{"type":"boolean","value":false},"Mastercard Entity":{"type":"string","value":"Master"},"Folder":{"type":"string","value":"NDA"},"Import Batch":{"type":"string","value":"Sale"},"Counterparty Name":{"type":"string","value":"Gra"},"Document ID":{"type":"string","value":"115"},"Region":{"type":"string","value":"United States"},"Effective Date":{"type":"date","value":"2018-11-05"}}

Can someone guide me the correct way to solve this in BigQuery using sql or sqludf's

A: Consider below approach
select id, collection,
  '{' || string_agg(renamed_property, ',' order by offset) || '}' renamed_properties
from (
  select id, collection, property, offset,
    array_agg(replace(property, property_key, property_name) order by regexp_contains(property, property_key) desc limit 1)[offset(0)] renamed_property
  from table_1 t1,
  unnest(regexp_extract_all(properties, r'"[^"]+":{"type":"[^"]+","value":[^}]+}')) as property with offset
  left join table_2 t2
  using (collection)
  group by id, collection, property, offset
)
group by id, collection

if applied to sample data in y our question - output is


text:
Q: Checking if username is valid using jQuery plugin I am using the jQuery validation plugin to validate forms. I have a username field that I need validated. So far this is what I have:
$(".personal_form").validate({
        errorElement: 'div',
        rules: {
            username: {
                required: true,
                maxlength: 15,
                remote: {
                    url: "usernameChecker.php",
                        type: "post",
                        data: {
                          username: function() {
                            return $( "#username" ).val();
                            },
                        },
                    },
            },

        },

        messages: {

            username: {
                required: "Please enter a username",
                maxlength: "Your username should not exceed 15 characters.",
                remote: "This username is taken."
            },

        },

        });

I want to make it so that if someone enters an invalid username it'll show an error. For example, if someone entered special characters : "!@#$%^&*()_+=~`-" it'll show an error. Valid usernames are usernames that have letters or numbers. How can I do this?

A: Create a custom validation rule that checks for the user name as per your rules like:
jQuery.validator.addMethod("alphanumeric", function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9 ]+$/.test(value);
    });

and add it with your validations

A: You can pattern attribute at <input type="text"> element with RegExp \w+|d\+ to match word or digit characters, <label> element, css :focus, :invalid, :after

#username:focus:invalid + label[for="username"]:after {
  content: "input must contain only letters and numbers";
  color:red;
}
<input type="text"
       pattern="\w+|d\+"
       id="username"
       placeholder="input letters and numbers" />
<label for="username"></label>

A: Add this in :
$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var check = false;
        return this.optional(element) || regexp.test(value);
    },
    "Please provide a valid username."
);

$(".personal_form").validate({
    errorElement: 'div',
    rules: {
        username: {
            required: true,
            maxlength: 15,
            regex: /^[a-zA-Z0-9 ]+$/,
            remote: {
                url: "usernameChecker.php",
                    type: "post",
                    data: {
                      username: function() {
                        return $( "#username" ).val();
                        },
                    },
                },
        },

    },

    messages: {

        username: {
            required: "Please enter a username",
            maxlength: "Your username should not exceed 15 characters.",
            remote: "This username is taken."
        },

    },

});

A: Use jQuery.validator.addMethod( name, method [, message ] ) for custom validation on form fields.
https://jqueryvalidation.org/jQuery.validator.addMethod/


text:
Q: Проблема с автоматическим добавлением слеша в url
Nginx + PHP-FPM

Конфиг вирт. хоста:
listen 80;

server_name test.local;
root        /home/httpdocs/test.local/www;
index index.php index.html index.htm;

access_log  /home/httpdocs/test.local/log/access.log;
error_log   /home/httpdocs/test.local/log/error.log;

location / {
    try_files $uri $uri/ /index.php?$args;
    rewrite ^/(.*)/$ /$1 permanent;
}

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php-fpm/php5-fpm.sock;
    fastcgi_index index.php;

    fastcgi_param DOCUMENT_ROOT /home/httpdocs/test.local/www/;
    fastcgi_param SCRIPT_FILENAME /home/httpdocs/test.local/www/$fastcgi_script_name;
    fastcgi_param PATH_TRANSLATED /home/httpdocs/test.local/www/$fastcgi_script_name;

    include fastcgi_params;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_param REQUEST_METHOD $request_method;
    fastcgi_param CONTENT_TYPE $content_type;
    fastcgi_param CONTENT_LENGTH $content_length;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
}

location ~ /\.(ht|svn|git) {
        deny  all;
}

при открытии url: test.local в браузере, происходит автоматический редирект на test.local/ (добавляет в конце слеш), вот это проблема!
Подскажите, как решить?
p.s.: Хотя при test.local/post/ автоматически редиректит на test.local/post (убирает в конце слеш), что правильно. Т.е. проблема возникает, именно когда в url только имя хоста.

A: При открытии test.local никакого редиректа не происходит. Ваш браузер на самом деле отправляет запрос на http://test.local/, просто в некоторых случаях браузер для вашего удобства не отображает в адресной строке http:// в начале и / (если путь состоит из одного лишь /) в конце. Видимо, в вашем браузере для доменов вида example.local и example.ru правила скрытия единственного слеша отличаются.
Как правильно сказал @AlexeyTen, после домена всегда должен быть указан путь, состоящий хотя бы из слеша, пустого пути не бывает.


text:
Q: Bernoulli and Categorical Naive Bayes in scikit-learn Is sklearn.naive_bayes.CategoricalNB the same as sklearn.naive_bayes.BernoulliNB, but with one hot encoding in the columns?
Couldn't quite guess from documentation, and CategoricalNB has that one extra parameter alpha whose purpose I don't understand.

A: The categorical distribution is the Bernoulli distribution, generalized to more than two categories. Stated another way, the Bernoulli distribution is a special case of the categorical distribution, with exactly 2 categories.
In the Bernoulli model, each feature is assumed to have exactly 2 categories, often denoted as 1 and 0 or True and False. In the categorical model, each feature is assumed to have at least 2 categories, and each feature may have a different total number of categories.
One-hot encoding is unrelated to either model. It is a technique for encoding a categorical variable in a numerical matrix. It has no bearing on the actual distribution used to model that categorical variable, although it is natural to model categorical variables using the categorical distribution.
The "alpha" parameter is called the Laplace smoothing parameter. I will not go into detail about it here, because that is better suited for CrossValidated, e.g. https://stats.stackexchange.com/q/192233/36229. From a computational perspective, it exists in order to prevent "poisoning" the calculations with 0s, which propagate multiplicatively throughout the model. This is a practical concern that arises whenever some combination of class label and feature category is not present in your data set. It's fine to leave it at the default value of 1.


text:
Q: R - plot map with ggmap using geom column I would like to plot a map from a data.frame using ggmap. I have been doing this, but now I does not have Lat and Long columns, I only have a geom column of the type:

010600002009720000010000000103000000010000000F000000CCF9D5AF2F192441B50537EDB57D5C414C5355FBFB182441576427D7B57D5C41CAFB6C77F6182441486FA487B67D5C41FFCF78B5F3182441515E507AB77D5C417E830DE2EE182441792B1B71BB7D5C416C8E8A92EF182441E3BBD679BC7D5C4181276139F91824410F92806CBD7D5C415E7F30833419244118812C5FBE7D5C415144FBEB401924415D3E0D33BE7D5C410970EFAD431924412876AFAEBD7D5C41E585E90E45192441E3BBD679BC7D5C41BFDF4F204719244106AFBB14B87D5C41D1D4D26F4619244103B2C3B3B67D5C41622E018B3F192441CEE9652FB67D5C41CCF9D5AF2F192441B50537EDB57D5C41

Is it possible to use the geom column as a argument in the ggmap() function? or is it possible to transform a geom column in Lat / Long columns so than I can use the following code?
ggmap(map)+geom_polygon(data, aes(lon, lat))


text:
Q: is error value incorrect for output neurons? I use the fully connected neural network for image recognition "mnist".
My network has 784 input neurons, one hidden layer of neurons consists of 1569 neurons, an output layer consists of 10 ones.
I have two questions:

*

*I use sigmoid and formula for error error = output * (1 - output) * (target - output). The problem is that if the output neuron is 1, and the required value is 0, that error = 0, but it's wrong, is n't?

*Is it right to use sigmoid if weighted sum of neurons in the hidden layer becomes too large as the result is 1? What values to initialize the weights?

A: Normally, I experienced good results with initializing weights in a random range of something like 0.01 to 0.5.
To 1: As far as I know the local error for output layer normally is expectedOutput - currentOutput, because this simplified statement never fails and has enough accuracy. After this, for fully-connected layers, you use backpropagation to adjust weights of hidden layers. See Yann Lecuns work for efficient: Efficient Backprop
To 2: To prevent to have an input of 1 to your output layer because the sum of the hiddens layer is too big and sigmoid delivers 1 for a huge amount of epochs you could do a simple, easy, efficient hack: always divide the input of each output layers neuron with the amount of neurons in the parent (hidden) layer, therefore your input is always in the interval [-1.0, 1.0] before the sigmoid transfer function is used. In most cases this trick reduces the amount of epochs needed to train the network drastically.

A: Ok Its suggested you initialize your weights randomly. Typically its suggested you  choose initial weights of a neural network from the range ((−1/√d),(1√d)), where d is the number of inputs to a given neuron.
And error is always Actual output-Current Output. The formula you mentioned has to do with one of the steps of BPN algorithm in the hidden layer weight adjustment. I would suggest to reduce the number of hidden nodes in your model. Its a general advice to have the number of hidden nodes less then the number of inputs.
And sigmoid function is fine for your task.


text:
Q: Greedy Algorithm to Determine 3 Best Quantile Points for Quantile Regression I ran a Quantile Regression algorithm on a multimodal data point and have successfully generated a reasonable model with sufficient accuracy. However, the challenge I have is I had to hand pick the quantile points. I have to replicate this experience against multiple products.
The first image shows the quantiles I hand-picked. However, I'd like to automate the process so the machine can return to me the three best points. The source from which I picked my quantiles is from the table below which shows the average Mean Absolute Error (MAE) of the quantile columns at each 0.05 quantile/percentile. I basically started from the left most column, and gradually select the quantile points that yield the smallest average MAE.
I'm familiar with the Greedy Algorithms that looks through one list and yields a maximum/minimum solution by slicing a list/array and highlighting the first and last index. However, in multi-dimensional space like the table below, how can such algorithm be utilized?
In summary, the goal is to find three quantile points with the minimum average MAE to represent the observation. What approach can be used to solve this problem?
High-level overview of how I created the table below:
# Setup Flow
quantiles = np.arange(0.05,1.0,0.05)
predictions = {}

# Run Regression
from statsmodels.regression.quantile_regression import QuantReg

X_ = general_linear_model_preprocessor.fit(df_btb)
X_columns = X_.get_feature_names_out()
X = pd.DataFrame(X_.transform(df_set['product_train']), columns=X_columns, index=df_set['product_train'].index)
mod = QuantReg(df_set['product_train']['btb_total'],X)

# Go through each quantile and generate a regression model
for quantile in quantiles:
    res = mod.fit(q=quantile, kernel='epa')
    X_test = pd.DataFrame(X_.transform(df_set['product_test']), columns=X_columns, index=df_set['product_test'].index)
    predictions["{:.2f}".format(quantile)] = res.predict(X_test)

# Record the actual data into a new DataFrame
# and concatenate with quantile results

df_y = df_set['product_test']['btb_total'].copy()

for quantile in quantiles:
    df_y_hat = pd.DataFrame(predictions["{:.2f}".format(quantile)], columns=["{:.2f}".format(quantile)], index=df_y.index)
    df_y = pd.concat([df_y,df_y_hat], axis=1)

# Sort
df_y_sort = df_y.sort_values(by=[y_variable])

# Generate table to measure MAE
df_mae = np.abs(df_y_sort.drop(columns=['btb_total']).sub(df_y_sort['btb_total'], axis=0))

# Split into 0.05 quantiles
df_mae_split = np.array_split(df_mae, len(quantiles)+1)

# Aggregator
mae_aggregator = list()

# Loop and measure MAE
for df_sub in df_mae_split:
    mae_aggregator.append(df_sub.mean(axis=0).values.ravel())

pd.DataFrame(mae_aggregator, columns=df_mae.columns)


text:
Q: Is there any boto3 function/API available to copy snapshot from one AWS account to other AWS account? I have a requirement from my client to copy the EBS snapshots from one AWS account to another AWS account. I am using python and boto3 SDK to implement this.

A: Assuming that you want to copy EBS snapshots: check out this answer: Copying AWS Snapshots using boto3
relevant docs: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.copy_snapshot


text:
Q: Laravel Eloquent - method to obtain 'grandchildren' where grandparent_id matches I have the following relationship:
Tool:
-----
id
name
description

Competency:
-----------
id
name
description
tool_id

Indicator:
----------
id
name
description
competency_id

I'm trying to obtain all the indicators (i.e. grandchildren) which fall directly under a specified tool. The relationships are that tools has many competencies, and competencies has many indicators.
My (pseudo) code so far is:
hasManyThrough('Indicator', 'Competency', 'tool_id', 'competency_id')->where('tool_id', '=', 1)->get();

I think I'm going down the right lines, but having trouble getting the code right.

A: Get indicators for the indicated competency.
$indicatorsOfCompetency = Indicator::where("competendy_id", $yourCompetencyID)->get();

or, depends of your laravel relationships names:
$competency = Competency::find($yourCompetencyID);

$indicatorsOfCompetency = $competency->indicators()->select(["id","field1","field2"]);

Get indicators when his competency it's related to the indicated tool.
// Note: Depending of your Laravel version, could be "lists" or "pluck" function.
$competencyIDS = Competency::where("tool_id", $yourToolID)->lists("id");

$indicators = Indicator::whereIn("competency_id", $competencyIDS);

or more eloquent, using whereHas():
$indicators = Indicator::whereHas("competency", function($qCompetency) use ($yourToolID){
    $qCompetency->whereHas("tools", function($qTool) use($yourToolID){
        $qTool->where("id", $yourToolID);
    });
});


text:
Q: Libgdx slider - drawables are drawn the wrong size I am drawing a slider with Libgdx using the following code:
    Pixmap pix = new Pixmap(200, 50, Pixmap.Format.RGBA8888);
    pix.setColor(Color.BLACK);
    pix.fill();
    skin.add("sliderBackS", new Texture(pix));

    Pixmap pix1 = new Pixmap(10, 70, Pixmap.Format.RGBA8888);
    pix1.setColor(Color.RED);
    pix1.fill();
    skin.add("knobS", new Texture(pix1));

    Slider.SliderStyle sliderStyle = new Slider.SliderStyle();
    sliderStyle.disabledBackground = skin.newDrawable("sliderBackS");
    sliderStyle.disabledKnob = skin.newDrawable("knobS");
    sliderStyle.background = skin.newDrawable("sliderBackS");
    sliderStyle.knob = skin.newDrawable("knobS");

    skin.add("sunSlider", sliderStyle);
    sunlightSlider = new Slider(0, 100, 1, false, sliderStyle);
    stage.addActor(sunlightSlider);

    sunlightSlider.setBounds(300, 300, 100, 10);

    sunlightSlider.setDisabled(true);
    sunlightSlider.setDebug(true);

And then else where:
    stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
    stage.draw();

But for some reason the pixmaps in the slider seem to be drawn at their actual size. This can be seen in the following picture (the green line is what it should be, from the debug):

For some reason the width seems to be constrained by sunlightSlider.setBounds(300, 300, 100, 10); but the height does not.
I know that I could choose the pixmap size to what ever I need, but I want to use an image from file. If I use a big image, then it overflows the bounds similarly.
I want it to look like it is above, but constrained to the green rectangle.
What am I doing wrong?

A: A TextureRegionDrawable, which is what you've created with your newDrawable calls, by default has a minimum size that matches its original pixel dimensions. The minimum size of the Drawable prevents the Slider widget from drawing it as small as it would like to fit it into its own bounds. So you can reduce the minimum size:
sliderStyle.disabledBackground = skin.newDrawable("sliderBackS");
sliderStyle.disabledBackground.setMinWidth(0);
sliderStyle.disabledBackground.setMinHeight(0);
// and so on for other new drawables.

I'm not sure what your long term plans are, but typically you want all your skin's images to be part of a single Texture object so the SpriteBatch doesn't have to flush itself many times to draw your whole scene.
If for some reason you're not doing that, you can at least make all these solid color drawables use the same texture. It can simply be a one-pixel white texture that is shared by everything. Also, make sure you are disposing of the pixmap you use to create a texture, or you are leaking memory!
Pixmap pix = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
pix.setColor(Color.WHITE);
pix.fill();
Texture tex = new Texture(pix);
pix.dispose();
skin.add(tex, "white");

Drawable blackDrawable = skin.newDrawable("white", Color.BLACK);
Drawable redDrawable = skin.newDrawable("white", Color.RED);

Slider.SliderStyle sliderStyle = new Slider.SliderStyle();
sliderStyle.disabledBackground = blackDrawable;
sliderStyle.disabledKnob = redDrawable;
sliderStyle.background = blackDrawable;
sliderStyle.knob = redDrawable;

Since you passed your Texture object to the Skin, the Skin will dispose of it when the Skin is disposed. Don't forget to dispose of the Skin in the dipose() method.


text:
Q: Accessing Django Templates after modifing the Django layout structure I re-organized Django,the following way:
config
 - settings
     - base.py
     - local.py
 urls.py
 wsgi.py

also apps:
- apps(level0)
  - acc(level_1)
   - users(level_2)
     - templates
       - users
    - acc_control(level_2)
  -att(level_1)
    - notes (level_2)
    - notifications (level_2)
  - mark(level_1)
- config (level0)
- templates(level0)

Some apps are directly in apps folder, ex mark, others are in other subfolders, ex users
   BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]

My issue is regarding templates access, because I receive the following error:
\apps\acc\users\templates\users\templates\users\detail.html (Source does not exist)

is repeating the internal folder;
In the View the template is set as:
 template_name = 'users/templates/users/detail.html'

I tried also:
 template_name = '/users/detail.html'

A: You don't need the users/templates/ prefix when you set template_name. As long as you have 'APP_DIRS': True in your TEMPLATES setting, the app directories loader will check the templates directory for every installed app, including users/templates
template_name = 'users/detail.html'


text:
Q: Euler's formula $e^{i\pi} = -1$ I need some help to verify this, basically I need to use the rule:
$$\exp(-x) = \frac{1}{\exp(x)}$$
to verify that
$$e^{i\pi} = -1$$
Except I'm not sure how to do it, I mean I know of the trigonometric identity of $$e^{i\pi} = \cos(\pi) + i\sin(\pi)$$, how do we get $-1$?

A: Note that

*

*$\cos(\pi)=-1$

*$\sin(\pi)=0$

Then:
$$e^{i\pi} = \cos(\pi) + i\sin(\pi)=-1+i\cdot 0$$


text:
Q: Rspec target a specific link in xpath where link text is a piece of data I'm a bit new to this but I'm trying to get rspec to click on a link.
I've replaced the 'Show' link on an index pager with a link which is the name of the item.
i.e. My view has this
     <%= link_to task.name, task_path(task) %>

My rspec file had a reference
    find(:xpath, "(//a[text()= 'Show'])[1]").click

which I want to turn into something like
    find(:xpath, "(//a[text()= @task1.name])[1]").click

That should pick up the correct task in the list so I can follow it with
    it { should have_content(@client.name) }
    it { should have_content(@task1.name) }
    it { should have_content(@task1.description) }

Unfortunately I can't work out how to put that @task.name in so that it doesn't break.
Any ideas?
Update:
    Failure/Error: find(:xpath, "(//a[text()= @task1.name])[1]").click
    Capybara::ElementNotFound:
    Unable to find xpath "(//a[text()= @task1.name])[1]"
    # ./spec/requests/task_pages_spec.rb:123:in `block (4 levels) in <top (required)>'

A: Please try your xpath this way,you missed the Ruby's string interpolation:
find(:xpath, "//a[text()= \"#{@task1.name}\"][1]").click

I tried to produce a similar example :-
require 'nokogiri'

doc = Nokogiri::HTML::Document.parse <<-eotl

foo

foo

bar

eotl

doc.class # => Nokogiri::HTML::Document

class Person
  attr_accessor :name
end

ram = Person.new
ram.name="foo"
ram.name # => "foo"
doc.search("//div/p[text()= \"#{ram.name}\"]").to_a.size
# => 2

A: This was much easier than I thought....
    click_link @task1.name

Think I might need to go and cry in the corner for a bit having spent hours trying to work that one out...


text:
Q: How can I get safari to pre-load js / css assets? I've been trying to get Safari to start pre-loading assets while a page is loading but nothing seems to work. Chrome and Firefox seem to do it just fine though.
The setup is simple enough. A script renders the following html with a 2s pause in the middle. The first part of the response has been flushed out and streamed to the browser. This is confirmed by Firefox and Chrome's ability to start fetching the js early.

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="preload" href="http://localhost:8888/js.js" as="script" />
    <script href="http://localhost:8888/js.js"/>

</head>
<!-- here the script rendering the HTML would actually pause
    for 2s before rendering the rest of the document -->
<!-- the first part of the response has been
    flushed and sent to the browser already -->
<body>
</body>
</html>

Fetching the JS file also has a 2s delay added to it. This makes things easy to visualize in browser timelines.
Note that Chrome & Firefox will start loading the JS early even if no <link preload> is present. They seem to just start parsing the HTML as soon as they get a bit of it and download any js they encounter along the way.
On Firefox I get the following waterfall:

On Chrome I get about the same:

On Safari however all I ever can get is:

Which clearly shows Safari not trying to asynchronously load the script and instead waiting for the full html response to be received.
What am I missing? Does safari just not do any asset pre-loading at all?

A: At the moment, Safari doesn't support <link rel=preload>, which explains the waterfall you're seeing. The good news is that Jen Simmons, one of their Web Evangelists, has asked on Twitter what developers would use it for if it existed.


text:
Q: List of Abbreviations like bibliography in biblatex-sbl SBLHS2 makes the list of abbreviations different than the bibliography for entries depending on whether the abbreviation is for the author or the title. This means that the abbreviation list looks different than the bibliography for certain entries.
Here is a MWE with two entries from SBLHS2.
\documentclass[letterpaper,12pt]{book}
\usepackage{polyglossia}
\setmainlanguage[variant=us]{english}
\usepackage[english=american]{csquotes}

\begin{filecontents}[overwrite]{customstyles.dbx}
  \DeclareDatamodelEntrytypes{tdict}
\end{filecontents}

\usepackage[style=sbl,citepages=omit,fullbibrefs=true,sblfootnotes=false,citereset=chapter]{biblatex}

\begin{filecontents}[overwrite]{temp.bib}

@book{BDF,
   author = {F. Blass and A. Debrunner},
   title = {A Greek Grammar of the New Testament and Other Early Christian Literature},
   subtitle = {A Translation and Revision of the Ninth-Renth German Edition Incorporating
      Supplementary Notes of A. Debrunner},
   shorthand = {BDF},
   editor = {Robert W. Funk},
   editortype = {reviser},
   translator = {Robert W. Funk},
   publisher = {The University of Chucago Press},
   address = {Chicago},
   year = {1961}
}

@mvlexicon{TLNT,
   title = {Theological Lexicon of the New Testament},
   shorthand = {TLNT},
   shorttitle = {TLNT},
   volumes = {3},
   author = {Ceslas Spicq},
   translator = {James D. Ernest},
   publisher = {Hendrickson Publishers},
   date = {1994},
   address = {Peabody, MA},
}

\end{filecontents}

\addbibresource{temp.bib}

\usepackage{xparse}

\begin{document}

\null\vfill

\printbiblist{abbreviations}
Cite BDF.\footcite[1]{BDF} Cite TLNT.\footcite[2]{TLNT}

\clearpage
\printbibliography%
\end{document}

Here is the result:

Basically, it looks like SBLHS2 always puts the thing abbreviated first in the entry in the list of abbreviations, author/editor or title. biblatex-sbl is doing just like SBLHS2 requests (an example of TLNT in the bibliography is given in 6.3.6 in SBLHS2 and looks just like this).
My style guide is slightly different, in that the entries in the list of abbreviation should look just like a bibliography entry. How can I make the entry in the abbreviation list look just like a bibliography entry?

A: Good news. I think this can be adjusted pretty easily. It's controlled with a toggle, which we can just remove from the abbreviations driver:
\usepackage{xpatch}
\xpatchbibdriver{abbreviations}
  {\toggletrue{blx@abbrevcite}}
  {}
  {}
  {}

MWE
\documentclass{article}
\begin{filecontents}[overwrite]{\jobname.bib}
@book{BDF,
  author = {F. Blass and A. Debrunner},
  title = {A Greek Grammar of the New Testament and Other Early Christian Literature},
  subtitle = {A Translation and Revision of the Ninth-Renth German Edition Incorporating
     Supplementary Notes of A. Debrunner},
  shorthand = {BDF},
  editor = {Robert W. Funk},
  editortype = {reviser},
  translator = {Robert W. Funk},
  publisher = {The University of Chucago Press},
  address = {Chicago},
  year = {1961}
}
@mvlexicon{TLNT,
  title = {Theological Lexicon of the New Testament},
  shorthand = {TLNT},
  shorttitle = {TLNT},
  volumes = {3},
  author = {Ceslas Spicq},
  translator = {James D. Ernest},
  publisher = {Hendrickson Publishers},
  date = {1994},
  address = {Peabody, MA},
}
\end{filecontents}
\usepackage{polyglossia}
\setmainlanguage[variant=us]{english}
\usepackage[english=american]{csquotes}
\usepackage[style=sbl,citepages=omit,fullbibrefs=true,sblfootnotes=false]{biblatex}
\addbibresource{\jobname.bib}
\usepackage{xpatch}
\xpatchbibdriver{abbreviations}
  {\toggletrue{blx@abbrevcite}}
  {}
  {}
  {}
\begin{document}
\null\vfill
\printbiblist{abbreviations}
Cite BDF.\footcite[1]{BDF} Cite TLNT.\footcite[2]{TLNT}
\printbibliography
\end{document}


text:
Q: SWFObject like setup for Unity Is there a SWFObject type setup for embedding Unity content and having a fallback HTML content (with a link to install the plugin)?
The JS included with Unity only allows for a button they've created.

A: Here's the official guide
Basically, for non-IE browsers, you check that the plugin's installed using javascript, and for IE, you use VisualBasic scripting. Their code isn't terribly pretty (all those document.write calls - ugh!) but it's robust.
You can always take their code, clean it up and wrap it in a nicer package. I know I did (but for a client, so I can't give you the code - sorry)


text:
Q: Problema con return Javascript Siempre he tenido poca claridad en como 'recoger' o 'captar' el valor del return, sé que es con expresiones funcionales, pero cómo ?
Mi intento:

var calc = document.getElementById('gosqrt');
calc.addEventListener("click", maths);

function maths() {

  var b = document.getElementById("sqrt").value;
  //alert(Math.sqrt(b));
    return Math.sqrt(b);

}

var um = maths();

document.write(um);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input type="text" id="sqrt" placeholder="Square root"/>
  <input type="button" id="gosqrt" value="Calcular"/>
</body>
</html>

A: Analisis
Si observamos el codigo, podemos encontrarnos con la siguiente linea:
calc.addEventListener("click", maths);

Esta le asigna un listener al elemento calc, pero ¿Que quiere decir esto?
Cuando se haga clic al elemento calc, este ejecutara una funcion.
¿Donde esta el problema?
El problema viene a darse en el hecho, en que no estamos guardando el resultado retornado de esa funcion en ninguna parte.
Tenemos esta linea:
var um = maths();
document.write(um);

Simplemente ejecuta la funcion maths(), y listo, el valor retornado de la funcion maths() se asigna a la variable um y se imprime el valor...No pasa nada mas.
¿Porque no nos funciona el boton?
Solo hemos asignado el listener, mas no hemos asignado el resultado de la funcion a algun elemento.
¿Como podriamos solucionarlo?
Una solucion podria ser esta:

/* Asignamos el listener */
var calc = document.getElementById('gosqrt');
calc.addEventListener("click", botonPresionado);

/* Creamos una variable que contendra el resultado */
var resultado;

/**
 * Funcion maths()
 * Calcula la raiz cuadrada
 */
function calcularRaiz() {
  var b = document.getElementById("sqrt").value;
  return Math.sqrt(b);
}

/**
 * Funcion botonPresionado()
 * Funcion a ejecutar cuando se presione el boton
 */
function botonPresionado() {
  resultado = calcularRaiz();
  alert(resultado);
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input type="text" id="sqrt" placeholder="Square root"/>
  <input type="button" id="gosqrt" value="Calcular"/>
</body>
</html>

¿Que hemos hecho aca?
Creamos una variable global, llamada resultado y en ella guardamos el resultado de la funcion calcularRaiz() (anterior maths()), y ejecutamos un alert(), para mostrar el resultado de la operacion.


text:
Q: Get facebook data as list (python) *this uses a python wrapper to access facebook's graph API
So, I am trying to get a list of document IDs in a facebook group
I am able to get the ids, but they come in as a 2-item dictionary.
All of the ids are on one of the dictionary items in this format:
u'data':[{u'id': u'11111111111111'}, {u'id': u'22222222222}....]

and so on
Is there a way to either
a) have the data come in as a list and not a dictionary
b) convert this dictionary item into a list of IDs
code...
graph=facebook.GraphAPI(token)
IdDict = graph.get_object("xxNameOfGroupxx/docs", fields='id')
print type(idDict)
print len(idDict)

<type 'dict'>
2

A: a = []
b= {1:'one', 2:'two}
a.append(b.copy())
print(a) --> [{1: 'one', 2: 'two'}]
print(type(a)) --> <class 'list'>


text:
Q: Is there a way to import all databases into one database with Mysqldump? I want to gather automatically all my databases into one with Mysqldump, is there a way to do it ?
For example what I want is to move all the tables from DB1, DB2 and DB3 into DB4 (DB4 can already contain some tables or can be created during the import, it doesn't matter to me).
I tried mysqldump -uroot -p --all-databases > dump.sql
Then import it with mysql -uroot -p allInOne < dump.sql
But the resulting database is only filled with it's own data.

A: I think you will have to do the databases individually but with:
mysqldump -uroot -p DB1 > dump.sql

This will not include the Database name and Use in the dump so you can re-import into the new database.
If you really have a lot of databases then not sure if any of the other options will help :https://dev.mysql.com/doc/refman/5.5/en/mysqldump.html
Might be worth exploring:
mysqldump -uroot -p --all-databases --tables > dump.sql


text:
Q: Get Distinct row from table A based upon a value from table B I need help adjusting the below proc to have the ability to return a result from the organization table when doing a search from the service table. The organization can have several services listed in the services table keyed off of the organization_id. one org, many services.
The current proc in place was used to search for the organization and return that row OR it would return all organizations if all the fields are blank. I want to change it so that I can still maintain that but have it return the organization if a service is searched for.
SELECT
    organization_id,
    organization_nm,
    contact_nm,
    phone_nr,
    email_ad,
    last_upd_dt,
    update_frequency_cd
FROM ORGANIZATION
WHERE
    organization_id = CASE
        WHEN @organization_id = 0 THEN organization_id
        WHEN @organization_id IS NULL THEN organization_id
        ELSE @organization_id END
    AND organization_nm LIKE CASE
        WHEN @organization_nm IS NULL THEN organization_nm
        ELSE '%' + @organization_nm + '%' END
    AND update_frequency_cd = CASE
        WHEN @update_frequency_cd = 'x' THEN update_frequency_cd
        ELSE @update_frequency_cd END
    AND operator_id = CASE
        WHEN @operator_id = 0 THEN operator_id
        WHEN @operator_id IS NULL THEN operator_id
        ELSE @operator_id END
ORDER BY organization_nm

I did this inner join and it get's me the results I want, but I am at a loss on how to incorporate it into the proc. I've been trying many ways to get it to work but did not want to muck up my question with those attempts. Any help making the two pieces fit would be much appreciated OR if I can be schooled on the proper/easier way to make this work.
Here is the inner join I did that gets me the results I am looking for when searching for just a service.
SELECT
    org.organization_id,
    org.organization_nm,
    org.contact_nm,
    org.phone_nr,
    org.email_ad,
    org.last_upd_dt,
    org.update_frequency_cd,
    service_nm
FROM dbo.ORGANIZATION AS Org
INNER JOIN
(
SELECT organization_id AS orgId, service_nm
FROM dbo.RECYCLE_SERVICE
WHERE service_nm = 'my service'
) AS serv
ON  Org.organization_id = serv.orgId

A: Note - User community needs to acknowledge original posts...when editing others answers
Try:
SELECT
    org.organization_id,
    org.organization_nm,
    org.contact_nm,
    org.phone_nr,
    org.email_ad,
    org.last_upd_dt,
    org.update_frequency_cd,
    service_nm
FROM dbo.ORGANIZATION AS Org
INNER JOIN
(
SELECT organization_id AS orgId, service_nm
FROM dbo.RECYCLE_SERVICE
WHERE service_nm = 'my service'
) AS serv
ON  Org.organization_id = serv.orgId
WHERE
    organization_id = CASE
        WHEN @organization_id = 0 THEN organization_id
        WHEN @organization_id IS NULL THEN organization_id
        ELSE @organization_id END
    AND organization_nm LIKE CASE
        WHEN @organization_nm IS NULL THEN organization_nm
        ELSE '%' + @organization_nm + '%' END
    AND update_frequency_cd = CASE
        WHEN @update_frequency_cd = 'x' THEN update_frequency_cd
        ELSE @update_frequency_cd END
    AND operator_id = CASE
        WHEN @operator_id = 0 THEN operator_id
        WHEN @operator_id IS NULL THEN operator_id
        ELSE @operator_id END
ORDER BY organization_nm


text:
Q: Azure durable function calls prioritization I have an Azure durable function (HttpTrigger -> orchestrator -> activity) which is called from 2 sources - automated and manually. When called automatically, multiple calls are queued and then executed. When calling the function manually, the manual call is also queued and will be executed at some time in the future (after all queued automated calls are executed). What I would like to do is to prioritize the manual call in such a way that it is the next to be processed, so it has a higher priority than the automated calls.
Is there a way to do this?