text:
Q: GetILGenerator method is not supported by MethodBuilder I am trying to generate generic method via Reflection API. Here is function which I want to create:
public List<T> CreateList<T>()
{
    return new List<T>();
}

Here is program, which should create assembly with DemoType class, which will contain mentioned CreateList method, generated dynamically:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

class GenericMethodBuilder
{
    public static void Main()
    {
        var asmName = new AssemblyName("DemoMethodBuilder1");
        var demoAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);

        var demoModule = demoAssembly.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");
        var demoType = demoModule.DefineType("DemoType", TypeAttributes.Public);

        var create_list_method = demoType.DefineMethod("CreateList", MethodAttributes.Public | MethodAttributes.Static);

        var TInput = create_list_method.DefineGenericParameters(new string[] { "TInput" })[0];
        var t_list_type = typeof(List<>).MakeGenericType(TInput);

        create_list_method.SetParameters(Type.EmptyTypes);
        create_list_method.SetReturnType(t_list_type);

        var ilgen = create_list_method.GetILGenerator();

        ilgen.Emit(OpCodes.Newobj, t_list_type.GetConstructors()[0]);
        ilgen.Emit(OpCodes.Ret);

        Type dt = demoType.CreateType();
        demoAssembly.Save(asmName.Name + ".dll");
    }
}

But during execution create_list_method.GetILGenerator() I receive NotSupportedException at with message:

Additional information: Specified method is not supported.

What's wrong with this method? I checked out docs, and it seems like ok.

A: The received exception is:

[System.NotSupportedException: Specified method is not supported.]
     at System.Reflection.Emit.TypeBuilderInstantiation.GetConstructors(BindingFlags bindingAttr)
     at GenericMethodBuilder.Main() :line 26

at the GetConstructor call.
This happens because you try to get the constructor of a not yet constructable type List<TInput>.
The way to go is to use the magic of the static TypeBuilder.GetConstructor-method to create a appropriate representation of the generics type constructor:
ilgen.Emit(OpCodes.Newobj, TypeBuilder.GetConstructor(t_list_type, typeof(List<>).GetConstructors()[0]));
The msdn entry for TypeBuilder.GetConstructor provides a quite extensive explanation as well as examples.


text:
Q: Excel Count/Sum Based on Multiple Criteria for Same Row I have a relatively simple problem which I am getting stumped on - perhaps it is this brain fog from Covid. I'll try my best to explain the problem.
Here is a simulated dataset:
    A   B   C   D   E   F   G   H   I   J   K   L   M   N
1   X1  X2  X3  Y1  Y2  Y3  X1  X2  X3  X1  X2  X3  Ct  St
2   1   2   0.2             0   2   0.5 1   2   0.1 2   0.3
3   1   2   0.3             1   1   0.2             1   0.3
4   1   2   0.6 1   2   0.1                         1   0.6
5   1   2   1.1                 2   0.7 1       0.5 1   1.1

A-N reflects the column names while the first column (1-5) reflects the row names in Excel.
Each column has been labelled as either X (e.g., male) and Y (e.g., female). There are three characteristics for male (X1, X2, X3) and three characteristics for female (Y1, Y2, Y3). We can think of adjacent columns as belonging to a trait (e.g., X1, X2, and X3 in columns A, B and C form a set of male characteristics for trait 1; X1, X2, and X3 in columns G, H and I form a set of similar characteristics but for trait 2, etc.).
For each row, I would like to calculate a count total (Ct, see column M) and sum total (St, see column N) based on a set of conditions.
Count total: Count the number of male (X) traits that feature a "1" for X1 and "2" for X2, giving a 'count total'.
Sum total: Sum the X3 values over male (X) traits that feature a "2" for X2, giving a 'sum total'.
I have manually calculated the count totals and sum totals for each column to make these definitions clearer. In row 1, there are two traits that fulfil the count total criteria (Ct = 2), whereby their X1 values = 1 and X2 values = 2. Notice that while the X2 value in column H qualifies (X2 = 2), X1 in column G is not equal to 1, so it is not counted. Furthermore, we only sum the X3 values for traits 1 and 2 (e.g., X3 in Column C and X3 in Column L), giving us a total of 0.3 (0.2 + 0.1).
The formulae should ignore sets of values that qualify but are for female traits (e.g., see row 3) and should work across missing values (e.g., in col J, row 4, X1 is missing, so it cannot be counted, even if X2 in col K row 4 features a qualifying value of 2).
I hope that makes sense.
My instinct was to use a SUMPRODUCT formula, but I am struggling to integrate the two conditions, e.g., for each row:
=SUMPRODUCT(((A1:L1="X1")*(A2:L2=1))*((A1:L1="X2")*(A2:L2=2)))

Any guidance would be much appreciated.

A: I haven't checked this thoroughly, but suggest for Ct
=SUMPRODUCT((A$1:J$1="X1")*(A2:J2=1)*(B$1:K$1="X2")*(B2:K2=2))

and for St
=SUMPRODUCT((A$1:J$1="X1")*(A2:J2=1)*(B$1:K$1="X2")*(B2:K2=2)*(C$1:L$1="X3")*C2:L2)

copied down.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find Text, Insert Rows then Copy & Paste after changing specific Text I have a data of rows and columns and I would like my macro to find certain text (Location) in one column and upon finding the location create 2 or more rows and copy the data of the found Location row but change the Location by an increment of 1.  For example if it finds a value in Location Column London then copy the whole row to the 2 new inserted rows but change the London text with London1 and London 2 and so on.  Please help.
code
sub Insert_CopyPaste()

    Dim LastRow As Long
    With Sheets("Sheet2")
        .Activate
        LastRow = .Range("C6000").End(xlUp).Row
        For i = 2 To LastRow
            If (InStr(1, .Range("c" & i).Value, "03M-EX", vbTextCompare) > 0) Then
                .Range("a" & i).EntireRow.Copy
                .Range("a" & i + 1).EntireRow.Insert
                .Range("a" & i + 1).PasteSpecial xlPasteValues
            End If
        Next
    End With
    Exit Sub

End Sub

A: I'm sure this is what you're after. If it's not clear I can explain.
sub Insert_CopyPaste()

    Dim LastRow As Long, i as long, txt as string
    txt = "03M-EX" 'set text to search
    With Sheets("Sheet2")

        LastRow = .Range("C6000").End(xlUp).Row
        while i <= lastrow

            If .Range("c" & i).Value = txt Then

                .Range("a" & i).EntireRow.Copy
                .Range("a" & i + 1).EntireRow.Insert
                .Range("a" & i + 1).PasteSpecial xlPasteValues
                .Range("c" & i + 1).value = txt & "1" 'add 1 to text

                i = i + 1 'skip newly added row
                lastrow = lastrow + 2 'increase last row reference by 2

                .Range("a" & i).EntireRow.Copy
                .Range("a" & i + 1).EntireRow.Insert
                .Range("a" & i + 1).PasteSpecial xlPasteValuesxlPasteValues
                .Range("c" & i + 1).value = txt & "2"

            End If

            i = i + 1 'goto next row to check

        loop
    End With
End Sub


text:
Q: Server values for Visitor IP - which to check in this usecase? there are other questions on this subject, but I am interested in a specific usecase.
I'm the author of a country geolocation plugin that's worked fine for years. A prob has been posted (probably IP address related); but I've had no response to a request for additional info.
Currently the plugin ONLY gets the IP address from $_SERVER['REMOTE_ADDR'] because:

*

*it shouldn't matter whether it contains the visitors "real" IP address or that of their proxy, as in most legitimate cases they would be the same country.

*responses to other StackOverflow qns stated $_SERVER['REMOTE_ADDR'] is the only "reliable & safe" value.

However, when using a reverse proxy (NGINX) a server's "REMOTE_ADDR" may (incorrectly?) contain localhost/server-side IP.
In such cases can I be confident that $_SERVER['HTTP_X_REAL_IP'] will contain visitor IP/their proxy?
Bearing in mind my comment on proxy servers, should I modify the plugin to first attempt to get IP address from:

*

*i: 'HTTP_X_REAL_IP' then ii. 'REMOTE_ADDR'

or do I need to extend further? e.g.

*

*i. first csv in 'HTTP_CLIENT_IP';  ii. first csv in 'HTTP_X_FORWARDED_FOR'; iii. 'HTTP_X_REAL_IP'; iv. 'REMOTE_ADDR'

I assume the additional checks and validation would have no noticeable speed impact on visitors to anyone's server?
clarification after deceze answer (thanks):

"exploitation by default"

It's not used for security, it tailors content based on visitor country. If someone spoofs an address they will just get content e.g. an advert, intended for another country. Poisoning: the internet relies on input forms; I can't see how IP validating an environment variable is as complicated or risky as validating comment form input.
N.B. if you are using IP address to block/allow by country even $_SERVER['REMOTE_ADDR'] is not reliable. When I checked a host it contained the "middle man" address for requests via anon proxy or VPN (try with Opera). Transparent proxy could be identified, but only by additionally checking the "spoofable" env variables.

A: If PHP operates behind a proxy, then it's entirely up to the proxy configuration whether and how the actual origin address is being passed. You cannot possibly foresee all possible variable names people are going to use, and you should not try to get the value from any arbitrary HTTP headers since that may lead to exploitation by default. You'll have to require the server admin/user of your plugin to explicitly configure where your plugin is supposed to get the remote IP from. You can only safely default to $_SERVER['REMOTE_ADDR'], anything else must be explicitly configured based on the particular setup.


text:
Q: How does nestjs pubsub.publish serializes the object? I'm using:nestjs, graphql(with subscription), mongodb,typegoose.
When I try to use a scalable graphql subscription, I chose to use the lib graphql-redis-subscription. The problem is here:
When I use built-in pubsub
built-in
pubsub.publish('name':{name: mongodbObject})

This mongodbObject returned will automatically add an id field (string for _id) whenever I need it. I guess this has something to do with pubsub serializer or my app serializer pipe.
redisPubSub
redisPubSub.publish('name':{name: mongodbObject})

This mongodbObject will not return id, which makes my front end throw errors. But it does provide a serializer option to change the way it works.
How to get the serializer of nestjs-graphql-subscription?

A: It seems to not be related to the graphql-redis-subscriptions. As you can see in this PubSub loc, it's just doing a JSON.stringify if you not pass a custom serializer in options.
I found some related github issues (here and here), but no solutions.
Waiting for a proper solution, I'm transforming myself the objects:
  @Subscription(() => [ProfileAnswer], {
    resolve: ({ profileAnswers }: Record<string, any>) =>
      profileAnswers.map(({ _id, occuredAt, ...item }) => ({
        id: _id,
        occuredAt: new Date(occuredAt),
        ...item,
      })),
  })
  @UseGuards(AccountAuthGuard)
  @UseGuards(GqlAuthGuard)
  profileAnswers(@Args('uuid') uuid: string): AsyncIterator<ProfileAnswer[]> {
    // Subscribe only to own answers
    return this.pubSub.asyncIterator<ProfileAnswer[]>(`${uuid}.answers`);
  }


text:
Q: How to use LINQ to get data from an XML file? I have xml files which look like this:
<?xml version="1.0" encoding="utf-8"?>
<record id="177" restricted="false">
    <type>record type</type>
    <startdate>2000-10-10</startdate>
    <enddate>2014-02-01</enddate>
    <titles>
        <title xml:lang="en" type="main">Main title</title>
        <!-- only one title element with type main -->
        <title xml:lang="de" type="official">German title</title>
        <!-- can have more titles of type official -->
    </titles>
    <description>description of the record</description>
    <categories>
        <category id="122">
            <name>category name</name>
            <description>category description</description>
        </category>
        <!-- can have more categories -->
    </categories>
    <tags>
        <tag id="5434">
            <name>tag name</name>
            <description>tag description</description>
        </tag>
        <!-- can have more tags -->
    </tags>
</record>

How do I select the data from these xml files using LINQ, or should I use something else?

A: You can load xml into XDocument objects using either the Load() method
for files, or the Parse() method for strings:
var doc = XDocument.Load("your-file.xml");
// OR
var doc = XDocument.Parse(yourXmlString);

Then you can access the data using LINQ:
var titles =
    from title in doc.XPathSelectElements("//title")
    where title.Attribute("type").Value == "official"
    select title.Value;

A: Was searching for examples of Xmlserializer and found this: How to Deserialize XML document
So why not to try. I did Ctrl+C and Edit -> Paste Special -> Paste XML As Classes in Visual Studio 2013 and... Whoa I got all the classes generated. One condition target framework must be 4.5 and this function is available from Visual Studio 2012+ (as stated in that post)


text:
Q: How to merge two tables in SQL SERVER? I have the following two tables T1 and T2.
Table T1
Id   Value1

1    2
2    1
3    2

Table T2
Id   Value2

1    3
2    1
4    1

I need a SQL SERVER query to return the following
Id   Value1   Value2
1    2        3
2    1        1
3    2        0
4    0        1

Thanks in advance!!

A: You can achieve this by FULL OUTER JOIN with ISNULL
Execution with given sample data:
DECLARE @Table1 TABLE (Id INT, Value1 INT)
INSERT INTO @Table1 VALUES (1, 2), (2, 1), (3, 2)

DECLARE @Table2 TABLE (Id INT, Value2 INT)
INSERT INTO @Table2 VALUES (1, 3), (2, 1), (4, 1)

SELECT ISNULL(T1.Id, T2.Id) AS Id,
       ISNULL(T1.Value1, 0) AS Value1,
       ISNULL(T2.Value2, 0) AS Value2
FROM @Table1 T1
FULL OUTER JOIN @Table2 T2 ON T2.Id = T1.Id

Result:
Id   Value1   Value2
1    2        3
2    1        1
3    2        0
4    0        1

A: FYI - Merge means something different in SQL Server.
I would suggest if you have a table which contains a list of all possible Id values, I would select everything from that and have two left outer joins to T1 and T2.
Assuming there isn't one, with only what is provided, it sounds like you want a full outer join.
Something like this should work:
SELECT Id = COALESCE(T1.Id, T2.Id),
       Value1 = COALESCE(T1.Value1, 0),
       Value2 = COALESCE(T2.Value2, 0)
FROM   T1
       FULL OUTER JOIN T2
                    ON T1.ID = T2.ID

A: That's a basic FULL OUTER JOIN:
SELECT coalesce(t1.id,t2.id) as [ID],
       coalesce(t1.value1,0) as Value1,
       coalesce(t2.value2,0) as Value2
FROM t1
FULL OUTER JOIN t2
 ON(t1.id = t2.id)

This will join both table together, and will keep the record from both tables even when there is no match.
The COALESCE() is used to replace null values, because of the full join.

A: Please try this. Its working fine with SQL Server 2012.
--Create two temp tables
    CREATE TABLE #temp1
    (Id int,Value1 int)

    CREATE TABLE #temp2
    (Id int,Value2 int)
--Insert Values to two tables
    INSERT INTO #temp1
    (Id,Value1)
    VALUES
    (1,2),(2,1),(3,3)

    INSERT INTO #temp2
    (Id,Value2)
    VALUES
    (1,3),(2,1),(4,1)
--Query which gives desired output
    SELECT
        ID = COALESCE(#temp1.Id, #temp2.Id),
        Value1 = COALESCE(#temp1.Value1, 0),
        Value2 = COALESCE(#temp2.Value2, 0)
    FROM
        #temp1 FULL JOIN #temp2 ON #temp1.Id = #temp2.Id

A: Here is the general syntax for full join.
SELECT column-names
  FROM Table1 FULL OUTER JOIN Table2
    ON column-name1 = column-name2
 WHERE condition


text:
Q: show/hide attachments Is there a way to show/hide attachments in my case images on a post.
What I want is to mark an image as "hidden" and then only show it to the admin and hide hidden images from a normal user I know how to use wp_query and get_posts to get attachments also how to check if user is an admin just want to know if there is somewhere a  field or table where I can store a flag that the attachment is hidden or if there is any "best practice" for this.
Essentially I have an post with attached images and I display a gallery of the images on a page as a custom post type and I want is to show the "hidden" images to the admin but not to a user lower then admin. Atm. I am using:
$args = array(
'order'         => 'ASC',
'orderby'       => 'menu_order ID',
'post_type'     => 'attachment',
'post_parent'   => $post->ID,
'post_mime_type' => 'image',
'post_status'   => null,
// Change the number of images to show in the gallery below
'numberposts'   => 999,
);
$attachments = get_posts($args);

To retrieve the attachments
I tried  wp_delete_attachment witch confuses me because according to *WP documentation: * function wp_delete_attachment( $post_id, $force_delete = false )  it has a parameter that does not permanently delete the attachment

bool   $force_delete: Whether to bypass trash and force deletion.
  Defaults to false.

but when I used it as: wp_delete_attachment( $item,false );

$item being the id for the attachment

it deleted the image from the uploads folder. If the wp_delete_attachment function works as intended I would like to know how to query the deleted attachments that are bound to the post. So that the admin user has a chance to "restore" the image
Hope someone can help.


text:
Q: Long running scheduled tasks in .net core and aws I was wondering what would be the recommended way to host a long running scheduled task in AWS.
Currently we have an EC2 instance (windows) in charge of triggering our app every few hours. This task will take between 1-3 hours depending on the number of items to process.

*

*Lambda does not seem to be appropriate since my task is too long

*Found this topic about Hangfire Scheduled Jobs in .NET Core 2 Web app hosted in AWS. Seems good but outside of AWS.

Any suggestions?
Thx
Seb

A: I would recommend AWS Step Functions. Very easy to implement. Part of the AWS Serverless Platform.
AWS Step Functions

AWS Step Functions makes it easy to coordinate the components of
  distributed applications and microservices using visual workflows.
  Building applications from individual components that each perform a
  discrete function lets you scale and change applications quickly. Step
  Functions is a reliable way to coordinate components and step through
  the functions of your application. Step Functions provides a graphical
  console to arrange and visualize the components of your application as
  a series of steps. This makes it simple to build and run multistep
  applications. Step Functions automatically triggers and tracks each
  step, and retries when there are errors, so your application executes
  in order and as expected. Step Functions logs the state of each step,
  so when things do go wrong, you can diagnose and debug problems
  quickly. You can change and add steps without even writing code, so
  you can easily evolve your application and innovate faster.

A: Using AWS Lambda with Scheduled Events would let you create an AWS Lambda that will respond to a scheduled event. This Lambda could then trigger your app. Your app doesn't need to be in a Lambda itself.


text:
Q: biblatex: Inconsistent behavior of `citetitle` (quotation marks vs. italic)
*

*Observation: It seems like the \citetitle command formats the title differently depending on the entry type.

*MWE: In the example below, an article is formatted as "Title" (I assume \enquote{Title}) and report is formatted as \textit{Title}.

*Question: (1) Is this intended? (2) Can I force (in a clean non-hacky way) the same formatting (I prefer "Title" or \enquote{Title})?

\documentclass{article}
\usepackage{biblatex}

% See https://ctan.org/tex-archive/macros/latex/contrib/biblatex/doc/examples
\addbibresource{biblatex-examples.bib}

\begin{document}
\begin{description}
\item[Article] \citetitle{baez/article} % @article{baez/article,
\item[(Tech)Report] \citetitle{padhye} % @report{padhye,
\end{description}
\printbibliography
\end{document}

Related

*

*Suppress quotes or other markup in \citetitle

*Remove quotes from inbook reference title with biblatex

*Remove Quotation Marks from Style (Thanks to user moewe for this reference.)

A:
It seems like the \citetitle command formats the title differently depending on the entry type.

Indeed. From there to the "inconsistent" in the title, it is a step though... I haven't done the setup, but to me it seems that it is different for each entry type precisely to be consistent with how the title is formatted elsewhere (bibliography, etc.).
But, as usual, with biblatex you can have it your way. The starred version of \DeclareFieldFormat* allows you to override all type-specific settings for a particular format:
\documentclass{article}
\usepackage{biblatex}

\addbibresource{biblatex-examples.bib}

\DeclareFieldFormat*{citetitle}{\mkbibquote{#1\isdot}}

\begin{document}
\begin{description}
\item[Article] \citetitle{baez/article} % @article{baez/article,
\item[(Tech)Report] \citetitle{padhye} % @report{padhye,
\end{description}
\printbibliography
\end{document}


text:
Q: How can I import a component based on the current url? I'd like to import different CSS depending on which page I'm on. The HTML will stay the same. What do I need to do to access the current location?
I was thinking I could put an if statement in the constructor and import the CSS there, but I'm not sure that will work.
EDIT: you can't import from within the constructor, so is there a way to do a conditional import?
Here's my code:
import React from 'react'
import Link from 'gatsby-link'

class Menu extends React.Component {

    constructor(props) {
        super(props)

        //how do I get myCurrentLocation?
        if(myCurrentLocation == '/') {
            import menuStyle from '../page-assets/global/styles/menu/_home-page.sass'
        } else {
            import menuStyle from '../page-assets/global/styles/menu/_regular-page.sass'
        }
    }

    render (){
        return (

                <Link to="/work-ive-done/" className="menu-item">

                        Work

                        ive done

                </Link>

                //other menu items ...

        )
    }
}

export default Menu;

A: gatsby-link is a wrapper for react-router-dom Link, so you should be able to access your route by using this.props.match.path.
otherwise:
You can access your current url using window.location.href
https://developer.mozilla.org/en-US/docs/Web/API/Window/location

A: In Gatsby v2, the page components will be able to access their location through the following:

*

*for class components: this.props.location.pathname

*for functional components: props.location.pathname
For function components, ensure props are being passed through their params. e.g.
const IndexPage = (props) => (
  <Layout>

This works {props.location.pathname}

  </Layout>
)

For anywhere else, you can use @reach/router's Location component (credits: jlengstorf)
import React from 'react';
import { Location } from '@reach/router';

export default () => (
  <Location>
    {({ navigate, location }) => /* ... */}
  </Location>
);

Here's a codesandbox showing the above. Also credits jlengstorf .


text:
Q: Cannot do "split" in chrome's console I am trying to get links from one page. Here's a simple code to get all links from certain dom element.
var $ = jQuery;
var page = $("#main .entry p");
var rez = [];

for(var i=0; i<page.length;i++) {
    var title = $(page[i]).find("a").text();
    var info = $(page[i]).text();
    var page_url = $(page[i]).find("a").attr("href");
    rez.push({
        title: title,
        page_url: page_url,
        info: info
    });
}

I am using this code in Chrome browser's console.
Everything works ok. rez array is populated, and I can veryfy it by something like console.table(rez).
Now I am trying to strip certain part from urls collected in previous step by using split
for(var i=0; i<rez.length;i++) {
    console.log(rez[i].page_url); // <- this works
    console.log(rez[i].page_url.split("http://something...")[1] ); // <- this fails
}

Important note! I am doing it all in one step by copying entire code (rez populating code and rez iterating in order to make split).
And I am getting this error in console:
VM7064:18 Uncaught TypeError: Cannot read property 'split' of undefined
    at <anonymous>:18:29

Why??

A: The split() function is used to split a string into an array of substrings. In split function as parameter you have to put a separator for example:
"http://something...like-this.com/blablabla".split("/");
This will return you an array ["http:", "", "something...like-this.com", "blablabla"]
In your case you try to split by some text "http://something..." and to get the second element of the array [1]. This will return you undefined in all your cases.


text:
Q: как получить новый массив объектов из массива JS? Есть массивы:
products = [
   {id:1, name:'product1', price:100},
   {id:2, name:'product2', price:200},
   {id:4, name:'product3', price:300},
   {id:5, name:'product1', price:400},
   {id:6, name:'product2', price:500},
   {id:7, name:'product3', price:600},
];
ids_products_in_cart = [2, 5, 7];

Нужно создать новый массив с элементами id в ids_products_in_cart, используя products, и изменить его, чтобы получилось:
var newArray = [
   {id:2, name:'product2', quantity_in_cart:1},
   {id:5, name:'product5', quantity_in_cart:1},
   {id:7, name:'product3', quantity_in_cart:1},
]

A:

const products = [
   {id:1, name:'product1', price:100},
   {id:2, name:'product2', price:200},
   {id:4, name:'product3', price:300},
   {id:5, name:'product1', price:400},
   {id:6, name:'product2', price:500},
   {id:7, name:'product3', price:600},
];
const ids_products_in_cart = [2, 5, 7];

const result = ids_products_in_cart.reduce((res, id) => {
  const item = res.find((_) => _.id === id);
  item ? item.quantity_in_cart++ : res.push({ id, name: products.find((_) => _.id === id).name, quantity_in_cart: 1 });
  return res;
}, []);

console.log(result);

A: const newArray = products.filter(product => ids_products_in_cart.includes(product.id));


text:
Q: How to replace characters automatically in excel I need to make replacement of characters such "á" "é" "í" "ó" "ú" for "a" "e" "i" "o" "u" , and "-" "," "." for just a space (many of these at once).
Is there a macro or something that could do this in an entire worksheet (on a regular basis)?
Thanks for your help.
Regards.

A: The easiest way
Select all your data (Ctrl + A)
Press Ctrl + H
Find what: á
Replace with: a
Replace all.
The other symbols in the same way


text:
Q: cannot communicate with server: Post http://localhost/v2/snaps/discord: dial unix /run/snapd.socket: connect: connection refused I want to install discord via snap (Linux package format), but i get the following error:
cannot communicate with server: Post http://localhost/v2/snaps/discord: dial unix /run/snapd.socket: connect: connection refused

Don't know why ...

A: Unmask it:
sudo systemctl unmask snapd.service

Enable it:
sudo systemctl enable snapd.service

Start it:
sudo systemctl start snapd.service

A: Maybe you don't have the snad service running
To start it onetimes do:
sudo systemctl start snapd

To enable that it always start with your system do:
sudo systemctl enable snapd

A: I've been having the same issue for some time now.
I solved the issue by uninstalling snap and then reinstalling it:
$ sudo apt autoremove --purge snapd
$ sudo apt install snapd

A: This issue came to me because i changed permission to 777
I searched every where and I find only this solution is best
sudo apt-get purge snapd
sudo apt-get install snapd

A: This issue came when i was trying to install spotify on my kali machine using snap "snapd"
so this issue can be solved with the following commands on the terminal
Firstly install snap **$ sudo apt install snapd**
or remove it by **$ sudo apt autoremove --purge snapd**  then install it again
Then enter the following commands
$ sudo systemctl enable snapd`
$ sudo systemctl start snapd
$ sudo snap install spotify

you should be able to download spotify on your kali/ubuntu Machine


text:
Q: htaccess & Symfony, one single route leads to 404, but works with app_dev.php I have an admin area where I login as described here.
This form works in dev enviroment, but when I switch to production the /admin route returns a 404.
The Controller (404 when not using app_dev.php):
/**
 * @Route("/admin", name="mainPage")
 */
public function indexAction(Request $request)
{
    return $this->render('admin/index.html.twig', array());
}

My .htaccess in /web (removed comments for readability)
DirectoryIndex app.php
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^ %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /app.php/
    </IfModule>
</IfModule>

And finally, my 000-default.conf
DocumentRoot /var/www/html/web

<Directory /var/www/html/web>
    AllowOverride All
    Allow from All
</Directory>

Where is the error? The /admin/login route shows the login form. After the login I am moved to admin/ (with 404), but when I enter another address manually that is protected it works (e.g. admin/setup/prices) as I am actually logged in.
Changing the route from /admin to /admin/start for example does not change anything.
If you need the security.yml:
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:

encoders:
  Symfony\Component\Security\Core\User\User: plaintext
  AppBundle\Entity\User: bcrypt

# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
    in_memory:
        memory: ~
    our_db_provider:
        entity:
            class: AppBundle:User
            property: username

access_control:
    - { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: ROLE_ADMIN }
firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        # activate different ways to authenticate

        http_basic: ~
        # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

        provider: our_db_provider

        form_login:
            login_path: login_route
            check_path: login_check
            csrf_token_generator: security.csrf.token_manager
            use_referer: true
        logout:
            path:   logout_route
            target: mainPage
        # http://symfony.com/doc/current/cookbook/security/form_login_setup.html

UPDATE
I see now that /admin is actually called but get 301 to /admin/
So I think the issue is with this line from the htaccess:
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

Changing the route in the controller to /admin/ does not help though.

A: In prod env', maybe you can share us your production logs about the error?
Else, did you tried to make a specific fire rules?
firewalls:
    login_firewall:
        pattern:   ^/login$
        anonymous: ~
    secured_area:
        pattern:    ^/
        form_login: ~


text:
Q: Error when running Hive Can any one suggest me why the following error is occurring and how to resolve it??
Not only the below command, running any command related to Hive is returning the same..
hive> show databases;
FAILED: Error in metadata: MetaException(message:Got exception: org.apache.thrif
t.transport.TTransportException java.net.SocketException: Connection reset by pe
er: socket write error)
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTa
sk

A: Check out your hive-site.xml. It is possible your javax.jdo.option.ConnectionURL, the URL for the Hive metastore, isn't right.


text:
Q: Evaluation Metrics for Generative Adversarial Networks I'm using GANs on non image data, and I'm looking for some qualitative metrics to measure the quality of the generated samples.
I can't use Inception Score (IS) or similar metrics that uses inception model because I'm not working on images.
Is there any metrics which are clearly explained ?


text:
Q: Updating state array of objects from api call Hy, let me explain my problem, i have a state of tag called tag_data :
const  [tagData, setTagData] = useState([
    { key: '1', label: 'Music', active: 0 },
    { key: '2', label: 'Sport', active: 0 },
    { key: '3', label: 'Dance', active: 0 },
    { key: '4', label: 'Cook', active: 0},
    { key: '5', label: 'Video Games', active: 0},
    { key: '6', label: 'Travel', active: 0 },
    { key: '7', label: 'Picture', active: 0 },
    { key: '8', label: 'Animals', active: 0 },
    { key: '9', label: 'Coding', active: 0},
    { key: '10', label: 'Party', active: 0},
])

I do a api call for get ACTIVE tag from my user :
useEffect(() => {
   const fetchData = async () => {
       setLoad(true)
       try {
           const result = await axios.post('/user/activetag')
           console.log(result.data.active_tag)
            setTagData({
                   // update
            })
       } catch (error) {
           console.log(error)
       }
       setLoad(false)
   }
   fetchData()
}, [])

Then the result store the active tags like this :
active_tag: Array(5)
0: {tag_id: 1, label: "Music"}
1: {tag_id: 2, label: "Sport"}
2: {tag_id: 3, label: "Dance"}
3: {tag_id: 4, label: "Cook"}
4: {tag_id: 5, label: "Video Games"}

I would like to update the tagData state and put active to 1 where the tag_id is equal to the key of tagData state, any idea ?
Full code :
import React, {useState, useEffect} from "react";
import { makeStyles } from '@material-ui/core/styles';
import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
import DoneIcon from '@material-ui/icons/Done';
import axios from 'axios'
import Loading from '../../../../Loading/Loading'

const useStyles = makeStyles((theme) => ({
  // style
 })
export default function TagUser(){
const classes = useStyles();
const [load, setLoad] = useState(false)
const  [tagData, setTagData] = useState([
    { key: '1', label: 'Music', active: 0 },
    { key: '2', label: 'Sport', active: 0 },
    { key: '3', label: 'Dance', active: 0 },
    { key: '4', label: 'Cook', active: 0},
    { key: '5', label: 'Video Games', active: 0},
    { key: '6', label: 'Travel', active: 0 },
    { key: '7', label: 'Picture', active: 0 },
    { key: '8', label: 'Animals', active: 0 },
    { key: '9', label: 'Coding', active: 0},
    { key: '10', label: 'Party', active: 0},
])

useEffect(() => {
   const fetchData = async () => {
       setLoad(true)
       try {
           const result = await axios.post('/user/activetag')
           console.log(result.data)
           setTagData({
                   // update
            })
        } catch (error) {
           console.log(error)
       }
       setLoad(false)
   }
   fetchData()
}, [])

const handleDelete = (key) => {
    //delete
}
const handleSubmit = (key) => {
    //submit
}

if(load){
    return <Loading/>
} else {
return(
    <Paper variant="outlined" square component="span" className={classes.root}>
       {
           tagData.map((data) => {
               if (data.active === 0) {
                   return (

                           <Chip
                               variant="outlined"
                               color="secondary"
                               label={data.label}
                               className={classes.chip}
                               onDelete={() => handleSubmit(data.key)}
                               deleteIcon={<DoneIcon />}
                           />

                   )
               } else {
                   return (

                           <Chip
                               color="secondary"
                               label={data.label}
                               className={classes.chip}
                               onDelete={() => handleDelete(data.key)}
                           />

                   )
               }
           })
       }
   </Paper>
  )
 }
}

A: Disclosure: I am the author of the suspense-service library used in this answer.
If you're open to using a 3rd-party library, it can significantly simplify your data-fetching logic. You won't need a load state, or a useEffect(), the component will only render when the list is ready:
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
import DoneIcon from '@material-ui/icons/Done';
import axios from 'axios';
import { createService, useService } from 'suspense-service';
import Loading from '../../../../Loading/Loading';

const defaultTags = [
  { key: '1', label: 'Music', active: 0 },
  { key: '2', label: 'Sport', active: 0 },
  { key: '3', label: 'Dance', active: 0 },
  { key: '4', label: 'Cook', active: 0},
  { key: '5', label: 'Video Games', active: 0},
  { key: '6', label: 'Travel', active: 0 },
  { key: '7', label: 'Picture', active: 0 },
  { key: '8', label: 'Animals', active: 0 },
  { key: '9', label: 'Coding', active: 0},
  { key: '10', label: 'Party', active: 0},
];

const UserActiveTags = createService(async (allTags) => {
  try {
    const result = await axios.post('/user/activetag');

    console.log(result.data.active_tag);

    const activeTags = result.data.active_tag.map((tag) => tag.tag_id);
    const activeTagsSet = new Set(activeTags);

    return allTags.map((tag) => ({
      ...tag,
      active: activeTagsSet.has(tag.key) ? 1 : 0
    }));
  } catch (error) {
    console.log(error);
    return allTags;
  }
});

export default function TagUser() {
  return (
    <UserActiveTags.Provider request={defaultTags} fallback={<Loading />}>
      <TagList />
    </UserActiveTags.Provider>
  );
}

const useStyles = makeStyles((theme) => ({
  // style
}));

function TagList() {
  const { root, chip } = useStyles();
  const tagData = useService(UserActiveTags);

  const handleDelete = (key) => {
    //delete
  };
  const handleSubmit = (key) => {
    //submit
  };

  const tagList = tagData.map(({ active, key, label }) => {
    const props = active === 0
      ? { variant: 'outlined', onDelete: () => handleSubmit(key), deleteIcon: <DoneIcon /> }
      : { variant: 'default', onDelete: () => handleDelete(key) };

    return (

        <Chip
          color="secondary"
          label={label}
          className={chip}
          {...props}
        />

    );
  });

  return (
    <Paper variant="outlined" square={true} component="span" className={root}>
      {tagList}
    </Paper>
  );
}

If you need tagData to be stateful, then
const tagData = useService(UserActiveTags);

needs to be updated to this:
const initialTagData = useService(UserActiveTags);
const [tagData, setTagData] = useState(initialTagData);

useEffect(() => {
  setTagData(initialTagData);
}, [initialTagData]);

A: I think you could something like this,
In your useEffect(),
const result = await axios.post('/user/activetag');
const filteredTags = tagData.map((e) => {
    const checkActive = result.data.some(i => i.tag_id == e.key);
    if(checkActive){
      const temp = {...e};
      temp.active = 1;
      return temp;
    }
   return e;
});

setTagData(filteredTags);

Hope that works!


text:
Q: No option for recording conference in JITSI I install jitsi on my server (Debian 10.3). The server is located behind nat. jitsi works well. But in my conference no option for recording and translating the conference
image

A: You have to enable the recording and Livestream option in config.js. Normally that file location is /etc/jitsi/meet/<DOMAIN>-config.js. After that, you have to manually enable these two options.


text:
Q: liquibase is putting single quote around all values of a csv line for the insert sql statement This is what I have in the csv file:
CONTACT_TYP_CD,CONTACT_TYP_DESC,CREATE_DATE,CREATE_USER,UPDATE_DATE,UPDATE_USER
"ALL","Contact to be used for all communications","2014-03-14 00:00:00","CS_MAIN",null,null

This is how I load this file through liquibase:
<loadData file="src/main/resources/METAINF/install/seed_data/seed_contact_type.csv"
        tableName="CONTACT_TYPE">
</loadData>

This is what liquibase uses to insert the data into oracle:
liquibase.exception.DatabaseException: Error executing SQL INSERT INTO CONTACT_TYPE (CONTACT_TYP_CD,CONTACT_TYP_DESC,CREATE_DATE,CREATE_USER,UPDATE_DATE,UPDATE_USER) VALUES ('"LL","Contact to be used for all communications","2014-03-14 00:00:00","CS_MAIN",null,null'): ORA-00947: not enough values

Can someone tell me what I am doing wrong? Thank you

A: Try removing the double quotes from your csv file, and define columns types, see the following test case as an example:
changeSet source
csv file
Another solution might be to enclose also the column titles in quotes, as seen here

A: you need to add the xml escape for double quote in the quotechar
quotchar="""

A: Your Problem here is the separator, not the quote. Liquibase seems to use semikolons by default, so you have to specify separator=",". Otherwise the whole line is considered a single value.


text:
Q: Show Firebase HTML-formatted text inside TextView I have a Text Editor inside my app, formatting watherver I want into HTML. But I've got a problem when retrieving this from the server (Firestore), because it's showing the whole text+codes, like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis non arcu porttitor, laoreet arcu et, egestas justo.
Mauris non pharetra augue, id maximus tellus. Vivamus in sapien nisi.

So this is what is loading inside the TextView, instead of formatted text like it should be. Does anyone knows how to fix it? Thank you in advance!

A: You can use Html.fromHtml. It will format your text (html) to display.
val message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis non arcu porttitor, laoreet arcu et, egestas justo.
Mauris non pharetra augue, id maximus tellus. Vivamus in sapien nisi."

binding.tvMessage.text =
            Html.fromHtml(message, Html.FROM_HTML_MODE_COMPACT)

UPDATE:
You are doing it wrong way.
txtPostDesc.setText(Html.fromHtml(postDescription, Html.FROM_HTML_MODE_COMPACT));


text:
Q: Git Graphical log is not working I am pretty new to git and I am trying to create a graphical log from an given example in git with this code:
git config --global alias.graphlog log --graph --full-history --all --color \ --pretty=format:'%x1b[33m%h%x09%C(blue)(%ar)%C(reset)%x09%x1b[32m%d%x1b[0m%x20%s%x20%C(dim white)-%x20%an%C(reset)'

...currently I am not yet understanding all the given parameters in the example.
Is it a git setting issue or something which is wrong with the example code?

A: you are trying to do 2 things here :
- edit your configuration file
- display the logs
If you just try your command to view the logs it works well :
git log --graph --full-history --all --color --pretty=format:'%x1b[33m%h%x09%C(blue)(%ar)%C(reset)%x09%x1b[32m%d%x1b[0m%x20%s%x20%C(dim white)-%x20%an%C(reset)'

Then to use the alias git graphlog you should do :
git config --global alias.graphlog '!git log --graph --full-history --all --color --pretty=format:"%x1b[33m%h%x09%C(blue)(%ar)%C(reset)%x09%x1b[32m%d%x1b[0m%x20%s%x20%C(dim white)-%x20%an%C(reset)"'

That will add the command git graphlog to your config file .gitconfig but in your example you were missing the quotes and the ! before git, also I had to remove the \ in the middle of your command.


text:
Q: Timeout error after MySQL 8 upgrade on Laravel My Laravel 7 project uses MySQL 7 and we are trying to upgrade it to MySQL 8.
But after upgrading, we got a time-out issue when writing data on our most important table using the usual Model::create([]) method and we really don't understand why.
Has anybody experienced such an error with Laravel when moving from MySQL 7 to MySQL 8?
Thanks!


text:
Q: How do I use FileReader.onload multiple times on a page? I have a page that has multiple inputs for single file upload. Kind of like this:

    <input id="inputField1" type="file"></input>

    <input id="inputField2" type="file"></input>

    <input id="inputField3" type="file"></input>

<button type="button" onclick="uploadFiles()">Upload</button>

Inside uploadFiles(), I first create an array of each file in the input fields:
var files = [];
for (var i = 1; i <= 3; i++) {
    var element = document.getElementById("inputField" + i);
    var file = element.files[0];
    files.push(file);
}

Then I attempt to call FileReader's onLoad event for each file in the "files" array:
for (var i = 0, f; f= files[i]; i++) {
    var fileName = f.name;
    console.log("out: " + fileName);
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}

addItem() is a function that works.
When I run this, only the last item in the "files" array is uploaded.
If inputField1 has a file named file1.jpg, inputField2 has a file named file2.jpg, etc, I would get the following in the console:
out: file1.jpg
out: file2.jpg
out: file3.jpg
in: file3.jpg
in: file3.jpg
in: file3.jpg

I feel like I am missing something truly fundamental with how to use FileReader. Any help would be appreciated. Thank you!

A: <button type="button" onclick="uploadFiles(readF)">Upload</button>

function uploadFiles(){
    var files = [];
    for (var i = 1; i <= 3; i++) {
        var element = document.getElementById("inputField" + i);
        var file = element.files[0];
        files.push(file);
    }
    for (var i = 0, f; f= files[i]; i++) {
        console.log("out: " + fileName);
        readF(f);
    }
}
function readF(f){
    var reader = new FileReader();
    reader.onload = function (e) {
        var fileName = f.name;
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}

A: It looks like the problem was with the "var fileName = f.name;" being outside the onload. I think the e.target.result would have been correct in the original example. The output would also be dependent on execution order of things. If the browser called each onload directly after readAsArrayBuffer, the out:  would like right, but it looks like your case, it was running the loop all 3 times and then calling all the onloads.
So it looks like the simplest fix to original code would have been to change:
for (var i = 0, f; f= files[i]; i++) {
    var fileName = f.name;
    console.log("out: " + fileName);
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}

TO
for (var i = 0, f; f= files[i]; i++) {
    console.log("out: " + fileName);
    var reader = new FileReader();
    reader.onload = function (e) {
        var fileName = f.name;
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}

Or if possible reference the file name from "e.target".


text:
Q: Uniform random variables and optimal strategy This comes from Fivethirtyeight's riddler weekly challenge...

Toddler poker is played by two players. Each is dealt a "card," which
  is actually a number randomly chosen uniformly from the interval
  [0,1]. (It could be 0.1, or 0.9234781, or 1/π, and so on.) The game
  starts with each player anteing a buck. Player A can then either
  "call," in which case both numbers are shown and the player with the
  higher number wins the two bucks on the table, or "raise," betting one
  more dollar. If A raises, B then has the option to either "call" by
  matching A's second dollar, after which the higher number wins the $4
  on the table, or "fold," in which case A wins but B is out only his
  original buck. No other plays are made.
What is the optimal strategy for each player? Under those strategies,
  how much is a game of toddler poker worth to Player A?

My thinking is that you want to maximize some expected payoff.  Since the 'cards' are uniform random numbers, the probability that player A's card is larger than player B's card is equivalent to the probability that $A-B>0$.  The difference of two uniformly distributed random numbers is triangularly distributed, and so $Z := A-B$.
In the first turn, player A can either call or raise.  If he calls, his expected payoff should be
$$E_A = \$1 P(Z) - \$1 P(1-Z)$$
A bucks if he has the larger number, and he loses his ante if not.  If he decides to raise then his expected payout is
$$E_A = \$2 P(Z) - \$1 P(1-Z)$$
A similar argument holds for player B.  Do you think I am on the right track?  What is my stopping criteria?  A hint would be lovely, or if you want you can throw down your solution.

A: I think this problem is more related to game theory(math/econ). Anyway, you have to figure out the Bayesian Nash Equilibrium to see how this game plays out.
Assume that both players are risk-neutral, i.e. they only care about the expected win. Let $\sigma_A$ and $\sigma_B$ be the strategies of $A$ and $B$. From the structure of the game, the strategies are functions of each card values.
The Bayesian Nash Equilibrium $(\sigma_A^*,\sigma_B^*)$ is defined as
$$\sigma_A^* = \arg\max_{\sigma_A} E_{X_B}[\pi_A(\sigma_A,\sigma_B^*)]$$
$$\sigma_B^* = \arg\max_{\sigma_B} E_{X_A}[\pi_B(\sigma_A^*,\sigma_B)]$$
where $\pi_A$ and $\pi_B$ are payoff function given opponents' type and strategy. In equilibrium, nobody has incentive to deviate from their strategies given that their opponents play the equilibrium strategy.
First, note that strategies can be characterized by a simple function that maps $[0,1]$ to $[0,1]$ where the range is the probability of choosing Raise($R$) for $A$ and the probability of choosing Call($C$) for $B$ given that $A$ raised. Note that $B$ has nothing to decide given $A$ called. So let's simply notate them by $P_A(x_A)$ and $P_B(x_B)$. (That's right. We are considering not just pure strategies, but also mixed strategies.)
Second, let's work out through $B$'s problem given $P_A(x_A)$. Given $x_B$ and that $A$ raised, $B$ maximizes
$$E_{X_A}[\pi_B(P_A(x_A),P_B(x_B))]=P_B(x_B)(2P[x_A<x_B|A\ raised]-2P[x_A>x_B|A\ raised])-(1-P_B(x_B))$$with respect to $P_B(x_B)$. By definition of $P_A$, $$P[A\ raise|x_A<x_B]= \int_0^{x_B}P_A(t)dt$$ Thus, by Bayes rule, $$P[x_A<x_B|A\ raise] = \frac{\int_0^{x_B}P_A(t)dt}{\int_0^{1}P_A(t)dt}$$ Plugging in the above expression, we have
$$E_{X_A}[\pi_B(P_A(x_A),P_B(x_B))] = P_B(x_B)[\frac{3\int_0^{x_B}P_A(t)dt-\int_{x_B}^1 P_A(t)dt}{\int_0^1 P_A(t)dt}]-1$$ and we conclude that the optimal $P_B(x_B)=1$ if $3\int_0^{x_B}P_A(t)dt-\int_{x_B}^1 P_A(t)dt>0$ and $0$ otherwise. Since the expression is monotone increasing in $x_B$, we know that the strategy must be characterized by a threshold $t_B$, where $B$ calls if $x_B>t_B$ and folds otherwise.
Given this, let's work on $A$'s problem which becomes a lot simpler with the threshold characterization of $B$'s strategy. Given $x_A$, $A$'s problem is to maximize
$$E_{X_B}[\pi_A(P_A(x_A),t_B)] = P_A(x_A)(2P[x_B<x_A,x_B>t_B]-2P[x_B>x_A,x_B>t_B]+P[x_B<t_B])+(1-P_A(x_A))(2x_A-1)$$
It is easy to see that $P[x_B<x_A,x_B>t_B]=\max(x_A-t_B,0)$ and $P[x_B>x_A,x_B>t_B] = 1-\max(x_A,t_B)$. So we have
$$E_{X_B}[\pi_A(P_A(x_A),t_B)] = P_A(x_A)[4\max(x_A,t_B)-2t_B-2+t_B-2x_A+1]+(2x_A-1)$$ We have two cases to consider. First $x_A>t_B$. We have $P_A(x_A)=1$ if $x_A>\frac{t_B+1}{2}$. Second, $x_A<t_B$. We have $P_A(x_A)=1$ if $x_A<\frac{3t_B-1}{2}$. Note that the inequality $\frac{3t_B-1}{2}\le t_B \le \frac{t_B+1}{2}$ holds for $t_B\in [0,1]$. So the optimal strategy for $A$ is twofold as our intuition suggests. If he has small enough number, he would just raise to get lucky in case $B$ folds. If he has large enough number, he would also raise to get more out of his value. We conclude that
$$P_A^*(x_B|t_B)=0 \quad \forall\frac{3t_B-1}{2}\le x_B \le \frac{t_B+1}{2}$$ and 1 otherwise.
Now let's get back to $B$'s problem of setting his $t_B$. We know that
$$3\int_0^{t_B}P_A(t)dt=\int_{t_B}^1 P_A(t)dt$$ must hold. Plugging in the above result, we have
$$3\frac{3t_B-1}{2}=(1-\frac{2t_B+1}{2})$$ and we finally get $t^*_B=\frac{2}{5}$.
So we conclude that in the Bayesian Nash equilibrium, $B$'s strategy is Call if $x_B>\frac{2}{5}$  and fold otherwise given that $A$ raised. And $A$'s strategy is Raise if $x_A < \frac{1}{10}$ or $x_A>\frac{7}{10}$, and Call otherwise. Expected values of each player can be easily calculated by drawing partitions on $X_A-X_B$ plane by each player's strategy. You can simply multiply the area and payoffs to get the expected values for each player. My calculation shows that the value is $\frac{1}{10}$ for player $A$ and $-\frac{1}{10}$ for $B$ as the game is zero-sum.

Payoff at A = (-2,2), B = (-1,1), C = (1,-1), D = (2,-2). Area of A = $\frac{21}{200}$, B = $\frac{36}{100}$, C = $\frac{40}{100}$, D = $\frac{27}{200}$.
Intuitively, $A$ gets some advantage with the right to choose whether to raise or call. However, the game will be played much differently if $B$ is able to raise upon $A$'s call.


text:
Q: Default TabItem Background Color I want to set the background color of a TabItem Header (TabItem.Background) if certain content is not set in the tab.  To accomplish this, I have a Brush property in my ViewModel that is bound to the Background property of the TabItem.  However, I'm not sure how to get/create the default TabItem background brush.
public Brush TabItemBrush
{
    get
    {
        return IsContentSet ? DefaultTabItemBrush : Brushes.LightSkyBlue;
    }
}

<TabItem Header="Some Header" Background="{Binding TabItemBrush, Mode=OneWay}">

I would like the DefaultTabItemBrush brush to match the other TabItems so if the Theme changes all the TabItems will still look the same.
Is the default brush available in SystemColors?
Using C# / .NET 3.5

A: I ended up using the solution from In WPF, how do I get the current theme's button background?
Then in my code looks something like:
public Brush TabItemBrush
{
    get
    {
        return IsContentSet ?  (Brush)UIUtilities.GetValueFromStyle(typeof(TabItem), Control.BackgroundProperty) : Brushes.LightSkyBlue;
    }
}

<TabItem Header="Some Header" Background="{Binding TabItemBrush, Mode=OneWay}">

When IsContentSet == true it will use the default brush and when false some other brush in this case LightSKyBlue


text:
Q: How can I transfer data via bluetooth from an iOS device to a Mac? I want to be able to transfer basic information (strings and such) from an iOS device to a Mac, and vice versa, via apps installed on each device. I've been trying to get bluetooth on the iOS device, but it seems to only want to connect to other iOS devices.

A: Bluetooth access on the ios is very limited. As a matter of fact you can only access it through the GameKit.
http://developer.apple.com/library/ios/#DOCUMENTATION/NetworkingInternet/Conceptual/GameKit_Guide/Introduction/Introduction.html
So if you want to share information with a Mac you would have to make the mac appear as an iOS device. I however ignore how you could do this.


text:
Q: How to add a mouselistener to images which are inserted using graph.drawimage()?     public class buttonActionStart implements ActionListener {      // overwritten ActionListener

        public void actionPerformed (ActionEvent e){
        JFrame window2 = new JFrame("Main Game"); //create empty frame

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window2.setSize(screenSize.width,screenSize.height);
        window2.add(new JPanel(){

        public void paintComponent(Graphics graph){
            super.paintComponent(graph);

            Board board = new Board();

            graph.drawString(board.sqaures[1].getName(),440,560);
            graph.drawString(board.sqaures[2].getName(),335,560);
            graph.drawString(board.sqaures[3].getName(),225,560);
            graph.drawString(board.sqaures[4].getName(),145,560);
            graph.drawString(board.sqaures[5].getName(),30,560);
            graph.drawString(board.sqaures[6].getName(),25,460);
            graph.drawString(board.sqaures[7].getName(),25,360);
            graph.drawString(board.sqaures[8].getName(),35,260);
            graph.drawString(board.sqaures[9].getName(),25,160);
            graph.drawString(board.sqaures[10].getName(),25,60);
            graph.drawString(board.sqaures[11].getName(),140,60);
            graph.drawString(board.sqaures[12].getName(),240,60);
            graph.drawString(board.sqaures[13].getName(),340,60);
            graph.drawString(board.sqaures[14].getName(),440,60);
            graph.drawString(board.sqaures[15].getName(),530,60);
            graph.drawString(board.sqaures[16].getName(),550,160);
            graph.drawString(board.sqaures[17].getName(),545,260);
            graph.drawString(board.sqaures[18].getName(),540,360);
            graph.drawString(board.sqaures[19].getName(),550,460);

            for (int i = 0; i < 6; i++)
                graph.drawRect(10 + (i*100),10,100,100);
            for (int j = 0; j < 4; j++)
                graph.drawRect(10,110 + (j*100),100,100);
            for (int k = 0; k < 4; k++)
                graph.drawRect(510,110 + (k*100),100,100);
            for (int l = 0; l < 6; l++)
                graph.drawRect(10 + (l*100),510,100,100);

            InputStream resource = UI.class.getResourceAsStream("player1.png");
            Image player1Image = null;
            try{
                player1Image = ImageIO.read(resource);
            }catch (IOException e){
                e.printStackTrace();
            }

            resource = UI.class.getResourceAsStream("player2.png");
            Image player2Image = null;
            try{
                player2Image = ImageIO.read(resource);
            }catch (IOException e){
                e.printStackTrace();
            }

            resource = UI.class.getResourceAsStream("player3.png");
            Image player3Image = null;
            try{
                player3Image = ImageIO.read(resource);
            }catch (IOException e){
                e.printStackTrace();
            }

            resource = UI.class.getResourceAsStream("player4.png");
            Image player4Image = null;
            try{
                player4Image = ImageIO.read(resource);
            }catch (IOException e){
                e.printStackTrace();
            }

            graph.drawImage(player1Image, 511, 511, null);
            graph.drawImage(player2Image, 585, 510, null);
            graph.drawImage(player3Image, 511, 585, null);
            graph.drawImage(player4Image, 585, 585, null);
            }
        });
        window2.setVisible(true);
    }
}

I am developing a kind of board game and these four images will serve as the player icon. I want the player to click the image which is assigned to them manually, then click somewhere else on the screen and the image will be "updated" to that position.
The "square" and board" will be my self-defined class.
I got another window which will have a "start" button and triggering the above graphic to be drawn on a new window.
I do found a lot of people suggesting to add image using JLabel and add the JLabel to the JFrame but I found that the image will cover my graphic.

A: Two options:

*

*Do as suggested and use a JLabel. By saying "the image will cover my graphics", you probably mean that transparent parts of the image will not show the background. If so, call JLabel.setOpaque(false).

*Add a MouseListener to the component for which you implement the paintComponent() method (probably a JFrame implementation). You will then get mouse events whenever the user clicks into the component. In the listener implementation, you then have to manually check whether the coordinates fall into the area of one of the images.

Generally speaking, for a game I would prefer option 2: You use a blank canvas and draw your game scene into the canvas. User interactions are then managed by a general game logic object which delegates to game objects such as 'player', 'NPC', etc., based on the coordinates / pressed keys / etc.


text:
Q: I am getting a URI Redirect error for an Azure Application even though the URIs match I am building my first Azure application and am getting this error when I try to authenticate
AADSTS50011: The redirect URI 'http://127.0.0.1:5000/getAToken' specified in the request does not match the redirect URIs configured for the application
When I go into Azure and look at the redirect URI this is what the value is set to:
http://localhost:5000/getAToken
The app is running locally on http://127.0.0.1:5000
What am I missing here? The URIs match exactly right? So why am I getting this error?

A: The redirect URI is matched as a string, not as a DNS-resolved URL. That means that localhost does not equal 127.0.0.1 in this case.
As Gaurav said you would have to use the same value in both places — either localhost or 127.0.0.0, but it has to be the same string value.
It doesn't matter how you access your app, you can still access it through localhost or 127.0.0.1. The thing that matters is the value that you send in the redirect_uri parameter. So, if in Azure you have the value http://localhost:5000/getAToken then send http://localhost:5000/getAToken in the redirect_uri parameter.


text:
Q: .gif marker google maps I have in my code this
var map;
  function initialize() {
    var mapDiv = document.getElementById('map-canvas');
    map = new google.maps.Map(mapDiv, {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);

  }

  function addMarkers() {
    var iconoMarca = "/assets/giftRayo.gif");
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    for (var i = 0; i < 10; i++) {
      var latLng = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),
                                          southWest.lng() + lngSpan * Math.random());
      var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        icon: iconoMarca
      });
    }
  }

but the marker doesn't appear and if I use a png or jpeg it works. What am I doing wrong?? Do the gif animations have another treatment?

A: As a standard, the markers use something called optimized rendering that always renders the markers as static. To see animated gifs you need to set optimized = false on your marker. The code for generating your marker would then be:
var marker = new google.maps.Marker({
    position: latLng,
    map: map,
    icon: iconoMarca,
    optimized: false
  });

This should solve your problem.
Ps.:
You seem to have a small bug in your code:
var iconoMarca = "/assets/giftRayo.gif");

You should remove the ).


text:
Q: Object as a data member in Objective C From what I have experienced it seems as if objects cannot be shared data members in objective c. I know you can init a pointer and alloc the object in each method but I cannot seem to figure out how one can say define a NSMutableString as a data member and allow all of the methods to use and modify its data as in c++. Is this true or am I missing something?

A: To define an instance variable (member), edit your .h file:
@interface MyClass : NSObject {
    // ivars go here
    NSObject *member;
}
// methods go here
@end

Then, in your .m file, from any instance method (one which begins with -), you can access this variable.
- (void)doThingWithIvar {
    [member doThing];
}

If you want to access the variable from outside the object itself, you'll need accessors. You can do this easily with Obj-C properties:
@interface MyClass : NSObject {
    // ivars go here
    NSObject *member;
}
// methods go here
@property (nonatomic, retain) NSObject *member;
@end

And in the .m:
@implementation MyClass
@synthesize member;
// ...
@end

The @synthesize line creates getter/setter methods for the ivar. Then you can use property syntax:
MyClass *thing = ...;
NSLog(@"%@", thing.member); // getting
thing.member = obj; // setting

(Note that I specified (retain) for the @property; if your member isn't an Objective-C object you won't want that. And if your property's class has a mutable counterpart, you'll want (copy) instead.)

A: It sounds like you want to synthesize (create getter/setter methods) a property for a member variable.   I just found this cheat sheet, go down to the section called, "Properties", should give a quick overview.
Other than that Apple's documentation should give you more info.


text:
Q: easy-autocomplete not working after internationalization (i18n) Since I internationalized my app with i18n, easy-autocomplete return the following error:
ActionController::UnknownFormat (MainController#search is missing a template for this request format and variant.

request.formats: ["application/json"]
request.variant: []):

Is anybody familiar with this ? what should I add/modify please ?


text:
Q: Ruby Thread & Mutex : why does my code failed to fetch JSON in sequence? I wrote a crawler which uses 8 threads to download JSON from the Internet:
#encoding: utf-8
require 'net/http'
require 'sqlite3'
require 'zlib'
require 'json'
require 'thread'

$mutex = Mutex.new # Lock of database and $cnt
$cntMutex = Mutex.new # Lock of $threadCnt
$threadCnt = 0 # number of running threads
$cnt = 0 # number of lines in this COMMIT to database

db = SQLite3::Database.new "price.db"
db.results_as_hash = true
STDOUT.sync = true
start = 10000000
def fetch(http, url, timeout = 10)
    # ...
end

def parsePrice( i, db)
        ss = fetch(Net::HTTP.start('p.3.cn',80), 'http://p.3.cn/prices/get?skuid=J_'+i.to_s)
        doc = JSON.parse(ss)[0]
        puts "processing "+i.to_s
        STDOUT.flush
        begin
                $mutex.synchronize {
                        $cnt = $cnt+1
                        db.execute("insert into prices (id, price) VALUES (?,?)", [i,doc["p"].to_f])
                        if $cnt > 20
                                db.execute('COMMIT')
                                db.execute('BEGIN')
                                $cnt = 0
                        end
                }
        rescue SQLite3::ConstraintException
                warn("duplicate id: "+i.to_s)
                $cntMutex.synchronize {
                        $threadCnt -= 1;
                }
                Thread.terminate
        rescue NoMethodError
                warn("Matching failed")
        rescue
                raise
        ensure
        end

        $cntMutex.synchronize {
                $threadCnt -= 1;
        }
end

puts "will now start from " + start.to_s()
db.execute("BEGIN")

Thread.new {
        for ii in start..12000000 do

                sleep 0.1 while $threadCnt > 7

                $cntMutex.synchronize {
                        $threadCnt += 1;
                }
                Thread.new {
                        parsePrice( ii, db)
                }

        end
        db.execute('COMMIT')
} . join

Then I created a database named price.db:
sqlite3 > create table prices (id INT PRIMATY KEY, price REAL);

To make my code thread-safe, db, $cnt, $threadCnt are all protected by $mutex or $cntMutex.
However, when I tried to run this script, the following messages were printed:
[lz@lz crawl]$ ruby priceCrawler.rb
will now start from 10000000
http://p.3.cn/prices/get?skuid=J_10000008http://p.3.cn/prices/get?skuid=J_10000008
http://p.3.cn/prices/get?skuid=J_10000008http://p.3.cn/prices/get?skuid=J_10000002http://p.3.cn/prices/get?skuid=J_10000008
http://p.3.cn/prices/get?skuid=J_10000008

http://p.3.cn/prices/get?skuid=J_10000002http://p.3.cn/prices/get?skuid=J_10000002

processing 10000002
processing 10000002processing 10000008processing 10000008processing 10000002

duplicate id: 10000002

duplicate id: 10000002processing 10000008
processing 10000008duplicate id: 10000008

duplicate id: 10000008processing 10000008
duplicate id: 10000008

It seems that this script skipped some id and called parsePrice with the same id more than once.
So why did this error occur? Any help would be appreciated.

A: It seems to me that your thread scheduling is wrong. I have modified your code to illustrates some possible race conditions you were triggering.
re 'net/http'
require 'sqlite3'
require 'zlib'
require 'json'
require 'thread'

$mutex = Mutex.new # Lock of database and $cnt
$cntMutex = Mutex.new # Lock of $threadCnt
$threadCnt = 0 # number of running threads
$cnt = 0 # number of lines in this COMMIT to database

db = SQLite3::Database.new "price.db"
db.results_as_hash = true
STDOUT.sync = true
start = 10000000
def fetch(http, url, timeout = 10)
  # ...
end

def parsePrice(i, db)
  must_terminate = false

  ss = fetch(Net::HTTP.start('p.3.cn',80), "http://p.3.cn/prices/get?skuid=J_#{i}")
  doc = JSON.parse(ss)[0]
  puts "processing #{i}"
  STDOUT.flush
  begin
    $mutex.synchronize {
      $cnt = $cnt+1
      db.execute("insert into prices (id, price) VALUES (?,?)", [i,doc["p"].to_f])
      if $cnt > 20
        db.execute('COMMIT')
        db.execute('BEGIN')
        $cnt = 0
      end
    }
  rescue SQLite3::ConstraintException
    warn("duplicate id: #{i}")
    must_terminate = true
  rescue NoMethodError
    warn("Matching failed")
  rescue
    # Raising here does not prevent ensure from running.
    # It will raise after we decrement $threadCnt on
    # ensure clause.
    raise
  ensure
    $cntMutex.synchronize {
      $threadCnt -= 1;
    }
  end

  Thread.terminate if must_terminate
end

puts "will now start from #{start}"

# This begin makes no sense for me.
db.execute("BEGIN")

for ii in start..12000000 do
  should_redo = false

  # Instead of sleeping, we acquire the lock and check
  # if we can create another thread. If we can't, we just
  # release the lock and retry latter (using for-redo).
  $cntMutex.synchronize{
    if $threadCnt <= 7
      $threadCnt += 1;
      Thread.new { parsePrice(ii, db) }
    else
      # We use this flag since we don't know for sure redo's
      # behavior inside a lock.
      should_redo = true
    end

  }

  # Will redo this iteration if we can't create the thread.
  if should_redo
    # Mitigate busy waiting a bit.
    sleep(0.1)
    redo
  end
end

# This commit makes no sense to me.
db.execute('COMMIT')

Thread.list.each { |t| t.join }

Also, most databases already implement locks themselves. You can probably remove the mutex that locks the database. And another advice is that you be more consistent with your commits. You have a lot of scattered begins and commits in the code. I suggest that you either make the operation and then commit or use a commit buffer and then commit everything in a single place.
The race condition, it seems you were not being careful enough when dealing with $threadCnt. The implementation I gave you makes more sense to me, but I have not tested it.
The redo in the main loop is a form of busy waiting, which is bad for performance. You can and you should put a sleep clause there. But it is essential that you maintain the $threadCnt checking and updating inside the lock. The way you implemented it before did not ensure the check and updating was an atomic operation.


text:
Q: Poltergeist and Capybara can't open page by its url, returns about_blank I am using Capybara 1.1.4 with poltergeist as PhantomJS driver. When I run this code on ruby:
visit('some_url')

I get 'about_blank'. It happens when I open specific dev environment. With other sites' urls it works great. Maybe someone knows how to fix it?

A: Is 'some_url' in other domain? If yes, Capybara (and Cucumber) have several limitations to test other domains, even subdomains. I mean, it will not work without workarounds.


text:
Q: Array size blows up I have a snippet of code that creates an array clusterUniqueMarkers that stores all the unique objects in the array clusterMarkers.
Problem: With the help of console.log(clusterUniqueMarkers.length); I can see that the size of that array blows up! When the code is executed, the browser CPU & memory usage shoots up and crashes. What could have caused the problem?
JS Code
// MarkerClusterer click handler
google.maps.event.addListenerOnce(mc, "clusterclick", function (cluster) {

    // Find number of unique LatLng in clusters
    var clusterMarkers = mc.getMarkers();
    var clusterUniqueMarkers = [];
    for(var j = 0; j < clusterMarkers.length; j++) {

        if(clusterUniqueMarkers.length == 0){
            // Adding first unique marker
            clusterUniqueMarker = new Object();
            clusterUniqueMarker.lat = mc.getMarkers()[j].position.lat();
            clusterUniqueMarker.lng = mc.getMarkers()[j].position.lng();
            clusterUniqueMarkers.push(clusterUniqueMarker);
        } else {
            // At least 1 unique marker
            var clusterUniqueMarkersLength = clusterUniqueMarkers.length;   // prevent infinite loop when clusterUniqueMarkers.length keeps increasing
            console.log(clusterUniqueMarkers.length);
            console.log(clusterUniqueMarkersLength);
            console.log('j: ' + j);
            for(var k = 0; k < clusterUniqueMarkersLength; k++) {
                // If marker is unique
                if(clusterUniqueMarkers[k].lat != mc.getMarkers()[j].position.lat() && clusterUniqueMarkers[k].lng != mc.getMarkers()[j].position.lat()) {
                    clusterUniqueMarker = new Object();
                    clusterUniqueMarker.lat = mc.getMarkers()[j].position.lat();
                    clusterUniqueMarker.lng = mc.getMarkers()[j].position.lng();
                    clusterUniqueMarkers.push(clusterUniqueMarker);
                }
            }
        }

    }
    console.log(clusterMarkers);
    console.log(clusterUniqueMarkers);
});

A: Your logic is wrong. You're iterating through all the elements in clusterMarkers, and doing this:
If the unique list is empty, add the current element as a unique one.
If the unique list is not empty, iterate through the unique list, and if the current element doesn't match the current unique element, add it as a unique one. What you want to do is say "if the current element doesn't equal any of the unique ones, add it as a unique one", which this code will achieve:
for(var k = 0; k < clusterUniqueMarkersLength; k++) {
    // If marker is unique
    var unique = true;
    if(clusterUniqueMarkers[k].lat == clusterMarkers[j].position.lat() && clusterUniqueMarkers[k].lng == clusterMarkers[j].position.lat()) {
        // if the element in clusterMarkers is equal to an element already in clusterUniqueMarkers
        // it can't be unique
        unique = false;
    }
}
if(unique) {
    clusterUniqueMarker = new Object();
    clusterUniqueMarker.lat = mc.getMarkers()[j].position.lat();
    clusterUniqueMarker.lng = mc.getMarkers()[j].position.lng();
    clusterUniqueMarkers.push(clusterUniqueMarker);
}


text:
Q: Cant make Tinymce edit iframe to work with tabbifier Im trying to get tinymce edit iframe to work with this wonderfull tabbifier:
http://www.barelyfitz.com/projects/tabber
I have successfully installed both of them and they work great.
In my example I have tested the following:

*

*Load a tinymce component and save the following code inside the tinymce iframe with the HTML option:
test

*The result is saved perfectly after refreshing with F5 and this code is saved in the database:

test

tinymce is working perfecly.
The next test I have made is with tabber:

*

*Edit the tinymce component box and saved the following code with the HTML option:

        test firsttab

        test secondtab

*

*The code is perfectly saved in the database, and the result is perfectly loaded in the output view, showing two tabs, each one of them with its content.

*The problem is while trying to edit the content again with tinymce, the tabs are not shown. The content is perfectly loaded in the tinymce iframe, without the tabs. Its shown as below:
test firsttab
test secondtab
The HTML code inside it is good, it has the proper tabbifier html code saved before.
The problem maybe is that the iframe of tinymce is not able to load or interpret the javascript of tabber.js and its not showing the tabs.
I have tested loading the javascript of tabber.js inside the tinymce iframe with this code, and seems to load it but the tabs are not still shown:

I have also checked that /js/tabber.js is the correct path. And saw at firebug that its loading it.
The two alert messages are displayed, so it seems to load it, but the tabs inside the tinymce edit iframe are still not shown.
Any help is welcome, thank you so much.

A: The tinymce ScriptLoader does not load a script inside the iframe. It provide a way to load a script in the main window after the tinymce initialization. This is very confusing as not documented.
But you definitelty can load a script inside the iframe. Here is the magic :
tinymce.init( { setup : function( ed ) {
    ed.on('init', function (args) {
        // get the iframe DOM
        var doc = args.target.contentDocument || args.target.contentWindow.document;

        // inject script into the DOM
        var s = doc.createElement('script');
        s.type = 'text/javascript';
        s.src = '/js/tabber.js';
        doc.getElementsByTagName('head')[0].appendChild(s);
    });
});

A: Several browsers have problems with spaces and tabs on paragraph start.
A workaround for spaces is to code them onSave as protected spaces if they are at the beginning. The solution for tabs is to use another character with similar behaviour and replace them when saving. It is necessary to recode the content when reloaded from databse into the editor.


text:
Q: Action when clicking on an option in a select menu I am programming a website with a map and a side panel, where I want some action to happend I chose an option in a select-menu.
This is my code:
<select id="optionList" onchange="display_div(document.getElementById('optionList').value);">
  <option selected="selected">Chose league</option>
  <option value="PL">Premier League</option>
  <option value="CH">Championship</option>
  <option value="L1">League 1</option>
  <option value="L2">League 2</option>
</select>

  <select id="plTeamList" onchange="display_div2(document.getElementById('plTeamList').value);">
    <option selected="selected">Chose team</option>
    <option value="MUN">Manchester United</option>
    <option value="CHE">Chelsea</option>
    <option value="BOU">Bournemouth</option>
    <option value="NEW">Newcastle</option>
  </select>

 ....

where I have a script with what happens when you choose Manchester United from the menu (it is plotting some popups in the map):
 function clickOnMUN() {
   var info = whichteam("MU"); // Finner ut hvilket lag som spiller, og info om stadion
   var marker = L.marker([info.substring(0, 5), info.substring(5, 10)]).addTo(map);

   marker.bindPopup(info.substring(10));
 }

This code is oddly not doing the script when I chose an option in the team-list.
The display_div-functions are only showing the options.

A: The only issue I see is the second "display_div" call... it says "display_div2" maybe a typo... but if it is the same as the first and only show the hidden div, removing the 2 should solve part of the problem. Also it could improve the code if you use some listeners for the clicks events instead of placing the function call inside the html tag. But this could be a version of your current code:

function display_div( theDiv ) {
 console.log ( theDiv );
 $('#'+theDiv).css("display", "block" );
}

function clickOnTeamList(targ) {

 $('#status').html("clicked a team " + targ );
}
p {
font-family: verdana;
font-size:12px;
color: blue;
}

<select id="optionList" onchange="display_div(document.getElementById('optionList').value)">
  <option selected="selected">Chose league </option>
  <option value="PL">Premier League • only option active</option>
  <option value="CH">Championship</option>
  <option value="L1">League 1</option>
  <option value="L2">League 2</option>
</select>

  <select id="plTeamList" onchange="display_div(document.getElementById('plTeamList').value);">
    <option selected="selected">Chose team</option>
    <option value="MUN">Manchester United</option>
    <option value="CHE">Chelsea</option>
    <option value="BOU">Bournemouth</option>
    <option value="NEW">Newcastle</option>
  </select>

Team: Manchester United

Team: Chelsea

Team: Bournemouth

Team: Newcastle

___


text:
Q: What are the semantics of overlapping objects in C? Consider the following struct:
struct s {
  int a, b;
};

Typically1, this struct will have size 8 and alignment 4.
What if we create two struct s objects (more precisely, we write into allocated storage two such objects), with the second object overlapping the first?
char *storage = malloc(3 * sizeof(struct s));
struct s *o1 = (struct s *)storage; // offset 0
struct s *o2 = (struct s *)(storage + alignof(struct s)); // offset 4

// now, o2 points half way into o1
*o1 = (struct s){1, 2};
*o2 = (struct s){3, 4};

printf("o2.a=%d\n", o2->a);
printf("o2.b=%d\n", o2->b);
printf("o1.a=%d\n", o1->a);
printf("o1.b=%d\n", o1->b);

Is anything about this program undefined behavior? If so, where does it become undefined? If it is not UB, is it guaranteed to always print the following:
o2.a=3
o2.b=4
o1.a=1
o1.b=3

In particular, I want to know what happens to the object pointed to by o1 when o2, which overlaps it, is written. Is it still allowed to access the unclobbered part (o1->a)? Is accessing the clobbered part o1->b simply the same as accessing o2->a?
How does effective type apply here? The rules are clear enough when you are talking about non-overlapping objects and pointers that point to the same location as the last store, but when you start talking about the effective type of portions of objects or overlapping objects it is less clear.
Would anything change if the the second write was of a different type? If the members were say int and short rather than two ints?
Here's a godbolt if you want to play with it there.

1 This answer applies to platforms where this isn't the case too: e.g., some might have size 4 and alignment 2. On a platform where the size and alignment were the same, this question wouldn't apply since aligned, overlapping objects would be impossible, but I'm not sure if there is any platform like that.

A: Basically this is all grey area in the standard; the strict aliasing rule specifies basic cases and leaves the reader (and compiler vendors) to fill in the details.
There have been efforts to write a better rule but so far they haven't resulted in any normative text and I'm not sure what the status of this is for C2x.
As mentioned in my answer to your previous question, the most common interpretation is that p->q means (*p).q and the effective type applies to all of *p, even though we then go on to apply .q .
Under this interpretation, printf("o1.a=%d\n", o1->a); would cause undefined behaviour as the effective type of the location *o1 is not s (since part of it has been overwritten).
The rationale for this interpretation can be seen in a function like:
void f(s* s1, s* s2)
{
    s2->a = 5;
    s1->b = 6;
    printf("%d\n", s2->a);
}

With this interpretation the last line could be optimised to puts("5"); , but without it, the compiler would have to consider that the function call may have been f(o1, o2); and therefore lose all benefits that are purportedly provided by the strict aliasing rule.
A similar argument applies to two unrelated struct types that both happen to have an int member at different offset.


text:
Q: Reserve space between elements I have a set of  elements placed one after another. If user clicks an element, 1px width border is set to it. As result other img elements are shifted.
How can I reserve 1px width space around every img element?

A: Either use margin (MDN)
margin: 1px;

or set the border-color (MDN) to transparent and just switch the color
border-color: transparent;

A: when you add the border you can add margin: -1px; to the element too (make sure you reverse the process properly when taking the border off)
Alternatively give all border: 1px solid transparent (think they all support that these days) then you just need change the border colour. You could tinker with border-color: rgba(222,0,0,0); and then rgba(222,0,0,1) for the active element, where a is the transparency. However, rgba is not very well supported in IE atm.


text:
Q: Mocha async hooks not running? I am always getting page as being undefined in this structure. It seems none of mocha's hooks are running. I tried adding async to the top level describe, I tried adding done statements. I even tried using Promise.then.catch. All with no luck.
const should = require('chai').should()
const puppeteer = require('puppeteer')

const puppeteerConfig = {
    headless: true,
    args: ['--no-sandbox', '--disable-translate', '--disable-extensions', '--disable-sync']
}

var browser
var page

describe('...', function() {

    before(async function() {
        browser = await puppeteer.launch(puppeteerConfig)
    })

    after(async function() {
        await browser.close()
    })

    beforeEach(async function() {
        page = await browser.newPage()
    })

    afterEach(async function() {
        await page.close()
    })

    describe('...', async function() {
        before(async function() {
            console.log(page) // undefined
        }
    })
})

A: Thanks to @Akshendra Pratap, that gist showed why that before failed. What I did was create a top level function:
async function genHTML(page) {
    return await page.$(...)
}

Then called that inside the first describe's beforeEach(). This solved it, very odd design that mocha would call the upper then lower before's, before calling the upper beforeEach...


text:
Q: what's a c++ equivalent of a generic? suppose i'm implementing a polymorphic tree data structure that can take on data of any type...
Tree<Int> or Tree<String> or Tree<Object>

but I'm implementing it in C++....how would I specify that the tree can contain an arbitrary type similar to generics in Java
also is there an equivalent of Java's Object object in C++ in which all objects in C++ inherits Object

A: The nearest equivalent of Java's generic is template in C++. Its not equivalent as such, if strictly speaking. But that is what you've in C++. So to suit your need, you've to work a little bit so that you can write equivalent code in C++.
Here're few links to some  articles that compare C++ template with Java generics:

*

*Java Generics and C++ Templates (at Dr Dobbs)

*Generics in C#, Java, and C++ (at artima.com)

A: If your goal is to have a single container that can contain anything, you could make the container's value type be Boost Any.  But it sounds like what you're looking for is a homogenous container, and the template answers here make sense for that.

A: In C++, you use templates, in the form
template <typename T>
    class Tree {
        TreeNode<T> Root
        ...
    };

Templates aren't identical to generics, they offer a bit more flexibility (and more ability to shoot yourself in the foot). You can't constrain a template type parameter to be a subclass of a certain type for example. And C++ doesn't have strong type checking inside the template, which is where it can be easy to make a mess.

A: What you're looking for are C++ templates.
You can declare a templated class like:
template<class TType>
class AClass
{
private:
    TType *somePointer;
};

Classes do not derive from a common base in C++, like they do in languages like C# and Java.  The closest you'll get is a void*, but that throws all type-safety out the door and I wouldn't recommend it.

A: You are using the language of generics: Tree<Int> or Tree<String> aren't supposed to hold objects of any type; they specifically hold integers or strings. Only Tree<Object> would be able to hold "any" type, but C++ doesn't have a concept equivalent to "object". You might be able to hold "any" type in your tree using Boost.Any although I haven't used it myself.
Use C++ templates to hold a specific type:
template<typename T>
class Tree {
    ...
};

Usage:
Tree<int> treeOfInts;

A: Templates.
http://www.cplusplus.com/doc/tutorial/templates/

A: Ok, naive attempt at java's generics would be Tree<void*>. That's not very good and many people will replace that with the following:
class TreeBase { };
class TreeInt : public TreeBase { int i; };

And then use Tree<TreeBase*>. This lets you specify which types will be compatible with it. It's equivalent of the java's Object thing.
Yet another layer would be to have Tree<Node> n; with just simple struct Node { TreeBase *b; };
But since we're talking about trees, c++ has considerably better way to do that, since it's directly supported via the c++ classes:
class TreeNode { virtual ~TreeNode() { } };
class MyIntTreeNode : public TreeNode {
public:
    MyTreeNode(int i) : i(i) { }
    int i;
};
class MyStringTreeNode : public TreeNode {
public:
   MyStringTreeNode(string s) : s(s) { }
   string s;
};
class MyArrayTreeNode : public TreeNode {
public:
   MyArrayTreeNode(std::vector<TreeNode*> v) : v(v) { }
   std::vector<TreeNode*> v;
};

Creating the tree couldnt be easier, once necessary types are available:
int main() {
  MyIntTreeNode n1(10);
  MyStringTreeNode n2("abc");
  std::vector<TreeNode*> v;
  v.push_back(&n1);
  v.push_back(&n2);
  MyArrayTreeNode n3(v);
  algo(n3);
  }

This approach has the advantage that every treenode can have different behaviour. The downside is that it's slightly verbose.


text:
Q: openWithCompletionHandler prob in 5.1 sim I'm puzzled.  I'm finding that the UIDocument method openWithCompletionHandler works in the iOS 5 and IOS 6 sims, but not in the one for iOS 5.1.
Any thoughts on how I work around this?  Is it just one of those things where the sim falls down but the real environment doesn't?
Thanks.
Steve

A: I see something similar. In openWithCompletionHandler the completion handler is never called. In saveToURL, the app freezes completely. As for you this only happens in the 5.1 simulator. 5.0 and now 6.1 are fine.


text:
Q: your FFI declaration needs a type signature Sometimes I face to weird issue, consider following examples:
This compiles:
renderFrame :: Frame -> Fay ()
renderFrame frame = do
     stack <- getStack
     if length stack > 0
           then (do
                   let e = head stack
                   traceEventCoord e)
           else (do return ())
     reqFrame renderFrame
     emptyStack
     where traceEventCoord :: Event -> Fay ()
           traceEventCoord e = do
               eX <- pageX e
               eY <- pageY e
               let str = show eX ++ " x " ++ show eY
               trace <- elById "trace"
               if isNull trace
                   then return ()
                   else elSetHtml (fromNullable trace) str

pageX :: Event -> Fay Int
pageX = ffi "%1['pageX']"

pageY :: Event -> Fay Int
pageY = ffi "%1['pageY']"

So does it:
getParentGroups :: Fragment -> Fay [Fragment]
getParentGroups f = do
    p <- getParent f
    nn <- nodeName (fromNullable p)
    return [fromNullable p]

getParent :: Fragment -> Fay (Nullable Fragment)
getParent = ffi "%1.parent()"
nodeName :: Fragment -> Fay String
nodeName = ffi "%1.node.nodeName"

But if I put auxiliary functions within where block I have compilation error:

fay: your FFI declaration needs a type signature pageX = ffi "%1['pageX']"
fay: your FFI declaration needs a type signature: getParent = ffi "%1.parent()"

E.g.
-- ...
where traceEventCoord :: Event -> Fay ()
      traceEventCoord e = do
          eX <- pageX e
          eY <- pageY e
          let str = show eX ++ " x " ++ show eY
          trace <- elById "trace"
          if isNull trace
              then return ()
              else elSetHtml (fromNullable trace) str
       pageX :: Event -> Fay Int
       pageX = ffi "%1['pageX']"
       pageY :: Event -> Fay Int
       pageY = ffi "%1['pageY']"

and
getParentGroups f = do
    p <- getParent f
    nn <- nodeName (fromNullable p)
    return [fromNullable p]
    where
        getParent :: Fragment -> Fay (Nullable Fragment)
        getParent = ffi "%1.parent()"
        nodeName :: Fragment -> Fay String
        nodeName = ffi "%1.node.nodeName"

Notice, that traceEventCoords in first example do not invokes this issue.
Is it a bug?
P.S. Second example is a just an example and final code would be refactored a bit, but it holds for demonstrative purpose.

A: Update: This has been implemented and released in fay 0.19
Sorry for the delay! Jetlag got me :(
I think this just hasn't been implemented yet. Initially ffi was only supported on the top level, then ffi expressions were added which need the type signature next to the expression ffi "alert('foo')" :: Fay (). I don't think anyone ever got around to doing it for where statements as well.


text:
Q: Google map api v3: find multiple paths using DistanceMatrixService I am using Google map api for finding distance between two points with the help of DistanceMatrixService(). In the success callback of getDistanceMatrix(), I can get the distance between two points. There could be multiple paths between two points but I always get the length of shortest path. How could I get all path distances? Please refer the code below:
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
    origins: [--some origins--],
    destinations: [--some destinations--],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
}, function (response, status) {
        for (var i = 0, length = response.rows[0].elements.length; i < length; i++) {
            if (response.rows[0].elements[i].status == 'NOT_FOUND') {
                alert('Source or destination address could not be found.');
                return;
            }

            var distance = response.rows[0].elements[i].distance.text;
            var duration = response.rows[0].elements[i].duration.text;
        }
});

In above code, the array response.rows[0].elements always turns out to have length one. It should have more that one objects if there are multiple paths between source and destination. How to achieve that? Thanks in advance.

A: The DistanceMatrix doesn't allow for multiple routes, it always calculates the shortest/best  distance.
If you need alternate routes and only have a single origin and destination, user the DirectionsService, set provideRouteAlternatives to true.
from the documentation:

provideRouteAlternatives (optional) when set to true specifies that the Directions service may provide more than one route alternative in the response. Note that providing route alternatives may increase the response time from the server.


text:
Q: Java for intermediate .NET Developer I am a .NET Developer with about 5 years of web development experience using Microsoft technologies starting with classic ASP to ASP .NET 3.5.
I do have a little background in Java as well and can write/understand Java code very easily. I am looking for resources (online, books) that are compatible with my .NET experience. I am only interested in web development in Java and want to start at intermediate level even if it may require me to look up some details.
What path or resources would you recommend for intermediate .NET web developers to gain equivalent proficiency in Java web development tools?

A: *

*Get an IDE: IntelliJ (my preference), Eclipse, Netbeans;

*Get an application server: Glassfish (my preference; either v2 or v3 Prelude), JBoss or, if you're feeling adventurous, SpringSource dm server;

*Get a JDK eg 6u11;

*Get a copy of Spring 2.5.6 (or 3.0M2 if you're feeling adventurous);

*Get a copy of the Spring reference documentation;

Put the pieces together.

A: Get yourself a copy of eclipse, and just start reading other people's code, and reading some java docs. The Java website has all the docs online, and they're one of the best language specs I've seen.
Really, if you know C# pretty well, Java should be a cake walk. The languages are pretty similar, so you just need to get to know the different frameworks.

A: Probably the most helpful book in regards to learning Java's web development framework, Java Server Faces:
Core JSF
- Great examples and explainations throughout on the whole process of using the JSF Framework.
And of course for anyone new to Java I would recommend:
Effective Java
- Covers various design patterns and practices.

A: In my experience that official Java exams are better than the .Net equivalents, so it may be worth starting there?

A: Search for a servlet/JSP tutorial (Good, albeit a little old, example here).
You'll get basic knowledge of Java web application development.

A: Whatever your level is, JSF for Nonbelievers is the best introduction to JSP/JSF.

A: I'd check out Bitter Java.
It's a book that shows you the wrong way to do things, why it's wrong, and then it shows you the right way.
It pretty much falls in line with the evolution of the j2ee framework. Started with servlets, then moved into jsps, then command pattern, etc.