text:
Q: expo-auth-session/providers/google not working on standalone app: invalid_scheme I hope that someone can help me with the following issue which I've been struggling with for a while.
I am trying to use expo-auth-session/providers/google for Google Auth on Android in Expo SDK 39.
I have followed the guide here but everything I do ends up with a google message:

Error 400: invalid_request Invalid parameter value for redirect_uri:
Invalid scheme: com.my_domain.myapp:/oauthredirect

And I just can not understand what am I doing wrong.
I need to mention the fact that in the Expo Client the login/signup works perfectly with the exact same code.
I checked the credentials an infinite amount of times and what bothers me is that it works in the expo client but not on the standalone app so I am sure it's something related to the google config but I don't know what.
Here is my app.json:
{
  "expo": {
    ...
    "scheme": "myapp",
    "platforms": [
      "ios",
      "android"
    ],
    ...
    "android": {
      "package": "com.my_domain.myapp",
      ...
    }
  }
}

And my integration:
import React, { useState } from 'react';
import * as WebBrowser from "expo-web-browser";
import * as Google from 'expo-auth-session/providers/google';
import PillButton from '../UI/PillButton';

const SignupCmp = props => {
    const [browserOpen, setBrowserOpen] = useState(null);

    const [request, response, promptAsync] = Google.useAuthRequest({
        expoClientId: '123-myuniqueid.apps.googleusercontent.com',
        androidClientId: '123-myuniqueid.apps.googleusercontent.com'
    });

    useEffect(() => {
        WebBrowser.warmUpAsync().then(r => console.log('warmed'));

        return () => {
            WebBrowser.coolDownAsync().then(r => console.log('cooled'));
        };
    }, []);

    useEffect(() => {
        if (response?.type === 'success') {
            const { authentication } = response;
            // console.log(authentication);
        }
    }, [response]);

    const handleBrowserOpen = async (url) => {
        let result = await WebBrowser.openBrowserAsync(url );
        setBrowserOpen(result);
    }

    return (
        <View>
            <PillButton
                disabled={!request}
                title={I18n.t('authScreens.signupWithGoogle')}
                type="solid"
                onPress={() => { promptAsync().then(async val => {

                  props.googleAuth(val.authentication.accessToken);
                }) }}
            />
        </View>
    );
};

export default SignupCmp;

I really need help on this one since I am out of ideas.
UPDATE
I updated the redirectUri property in the useAuthRequest as it follows:
const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: '123-myuniqueid.apps.googleusercontent.com',
    androidClientId: '1234-myuniqueid.apps.googleusercontent.com',
    redirectUri: AuthSession.makeRedirectUri({
      native: 'myapp:/oauthredirect',
      useProxy: true
    }),
    scopes: [
      'profile',
      'email'
    ]
  }, {});

And now the message has changed to
Invalid parameter value for redirect_uri: Missing authority: myapp:/oauthredirect
The login in the expo client still works as it should.
I tried creating a new API key in the Google Console and tried different settings there but nothing seems to have worked.
I could really do with some help.
Thank you!

A: I ended up using import * as GoogleSignIn from 'expo-google-sign-in'; instead of the import * as Google from 'expo-auth-session/providers/google';
It seems this is the only way I can get it to work properly.

A: Make sure you're not running your expo with an offline tag
"expo start --offline" ---- this is wrong
instead start it with "expo start"....... that was how i solved my issue on android
// code goes like these
    import * as Google from 'expo-auth-session/providers/google';

    const [request, response, promptAsync] = Google.useAuthRequest({
             expoClientId: 'xxxxxxxx', //get this from google console

    });

     useEffect(() => {
     if (response?.type === 'success') {
       const { authentication } = response;
       // an access token will be returned in the authentication object
           getGoogleUser(authentication.accessToken)
      }
     }, [response]);

     const getGoogleUser = async (accessToken) => {
       try{
         let gUserReq = await
           axios.get('https://www.googleapis.com/oauth2/v2/userinfo',
           {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
           }
         );

    console.log(gUserReq.data)
}
catch(error){
    console.log('GoogleUserReq error: ', error);
}

}


text:
Q: View does not manage to observe all property changes in ViewModel
*

*Case:

There is a View which contains CustomRichTextBox.
public static readonly DependencyProperty NewOutputLogItemProperty = DependencyProperty.Register("NewOutputLogItem",
            typeof(OutputLog ), typeof(CustomRichTextBox), new FrameworkPropertyMetadata(null, OnNewOutputLogAdded));

public OutputLog NewOutputLogItem
{
    get { return (OutputLog )GetValue(NewOutputLogItemProperty ); }

    set { SetValue(NewOutputLogItemProperty , value); }
}

private static void OnNewOutputLogAdded(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    var richBox = (CustomRichTextBox)obj;

    var outputLog = (OutputLog )args.NewValue;

    richBox.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
    {
        var mainParagraph = richBox.Document.Blocks.FirstBlock as Paragraph;

        if (mainParagraph != null)
        {

                mainParagraph.Inlines.AddRange(outputLog.GetInlines());
        }
    }));
}

There is also ViewModel which via MVVM light Messenger receives messages and set that property View binds to.
public void ProcessNotificationMessage(OutputLog message)
{
    NewOutputLog = message;
}

Unfortunately I observed that some messages are not depicted if ProcessNotificationMessage works too fast and as a result View misses single messages.
Do you have any idea how to ensure it to work properly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS - setting text of UITextView throws EXC_BAD_ACCESS I have a UITextView which I have created programmatically in the following code:
NSLog(@"creating the first blurb");
blurb = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
[blurb setText:total];
blurb.backgroundColor = [UIColor redColor];

where blurb is defined as a UITextView in the @interface.
Here's where I'm having the problem:
total is an NSString that is defined to get the text from a .txt file from a specified domain.
It is mutated as:
 NSString *url = @"https://sites.google.com/site/paloaltoapps/tbnappsource-password-blackr3d/Updates.txt";
 NSURL *urlRequest = [NSURL URLWithString:url];
 total = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:nil];

However, when I run the code, I get an instance of EXC_BAD_ACCESS thrown at the setText: line of the top code block.
I have tried printing total out using an NSLog statement, and that seems to work just fine.
Can anyone see what I'm doing wrong? Thanks.

A: try this... May be it lose reference......
total = [[NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:nil]copy];

A: Why not trying to create an NSString and assign the text to that. And then you can try to print the NSString and see if that works. Just a suggestion.


text:
Q: Mostrar el nombre de todos los usuarios de mi database
hola, lo que necesito es mostrar el nombre de los usuarios que tengo en mi Database, pero no logro hacerlo, me podrían ayudar por favor.
cada un esta referenciado por la clave del usuario, muchas gracias.
 database = FirebaseDatabase.getInstance();
    addU = database.getReference(bdreference.userRefence);
    addU.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            key= dataSnapshot.getKey();
            nombre=dataSnapshot.child(key).child("nombre").getValue(String.class);
                Log.i("nombre",nombre);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

A: Lo suyo es que te mires la documentación sobre como recuperar datos. Básicamente lo que tienes que hacer es recuperar la tabla users, y dentro de ella iterar sus filas e ir jugando con los campos que tiene:
mDatabase.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();
            String nombre = map.get("nombre");

            // hacer algo con el NOMBRE

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
});

A: Como dice el compañero arriba, para obtener el dato del usuario es facil, solo que te falta agregar el getUid para obtener el usuario, en donde dice child("users") es la ramificacion de donde viene, digamos que es la clave que engloba todos los Users ID , si no lo tienes le sacas la parte de child("users") y debes declarar un mAuth para identificar el usuario que quieres obtener el nombre. Ahora, si necesitas recuperar solo esos tres , te recomiendo concatenar los addValueEventListener con distintos dataSnapShot.
 mDatabase.child("users").child(mAuth.getCurrentUser.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

      String NombreUsuario=dataSnapshot.getValue().toString();
                    Log.e("Nombre de usuario", "" + NombreUsuario);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

Espero te sirva


text:
Q: Рационально ли использование фреймфорка при разработке одностраничника на PHP? Добрый день!
Недавно освоил PHP. Сейчас есть заказ на разработку лендинга.
Рационально ли было бы применять какой-либо фреймворк, вроде Yii или Symfony.
Или все пишется спокойно на обычном PHP

A: Все зависит от задач, которые хочется решить на стороне бэкэнда. Скорее всего, вам хватит всего функционала фреймворка. Я работал с Yii и знаю, что в нем уже есть масса хэлперов, позволяющих формировать красиво даты, суммы и прочее. Так же, имеется функционал защиты от csrf и инъекций.
Я не вижу ничего плохого в том, что в одностраничнике кто-то использует фреймворк для экономии времени на разработку и тестирование. Как минимум, вы не потратите время на создание базовой структуры, фильтры и валидаторы входящих данных (заполнение форм).
Если использовать кэширование при наличии выборки из sql, то можно легко и быстро сэкономить ресурсы.
Однако, нет никакого смысла в использовании фреймворка, если вы пишете на серверной стороне только какой-нибудь render('template') и больше ничего.


text:
Q: what are the new BI Capabilities sharepoint 2016 has compared to sharepoint 2013 what are the new BI Capabilities sharepoint 2016 has compared to sharepoint 2013
as the prospect of Performancepoint services,excel services and sql server side.

A: One thing i know.Excel Service is now not part of SharePoint 2016 core rather it is now part of Office Online server.
Read this
https://blogs.office.com/2016/11/21/updates-for-excel-services-and-bi-in-sharepoint-2016-on-premises/
Also read this for feature comparison:
http://www.epcgroup.net/business-intelligence-capabilities-SharePoint%202013.php
http://sharepointpromag.com/sharepoint/sharepoint-2016-and-sql-2016-business-intelligence


text:
Q: Need to use apply or broadcasting and masking to iterate over a DataFrame I have a data frame that I need to iterate over. I want to use either apply or broadcasting and masking. This is the pseudocode I am trying to improve upon.
2 The algorithm
Algorithm 1: The algorithm
initialize the population (of size n) uniformly randomly, obeying the bounds;
while a pre-determined number of iterations is not complete do
set the random parameters (two independent parameters for each of the d
variables); find the best and the worst vectors in the population;
for each vector in the population do create a new vector using the
current vector, the best vector, the worst vector, and the random
parameters;
if the new vector is at least as good as the current vector then
current vector = new vector;
This is the code I have so far.
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.uniform(-5.0, 10.0, size = (20, 5)), columns = list('ABCDE'))
pd.set_option('display.max_columns', 500)

df

#while portion of pseudocode
f_func = np.square(df).sum(axis=1)
final_func = np.square(f_func)
xti_best = final_func.idxmin()
xti_worst = final_func.idxmax()
print(final_func)
print(df.head())
print(df.tail())

*#for loop of pseudocode
#for row in df.iterrows():
#implement equation from assignment
#define in array math
#xi_new = row.to_numpy() + np.random.uniform(0, 1, size = (1, 5)) * (df.iloc[xti_best].values - np.absolute(row.to_numpy())) - np.random.uniform(0, 1, size = (1, 5)) * (df.iloc[xti_worst].values - np.absolute(row.to_numpy()))
#print(xi_new)*

    df2 = df.apply(lambda row: 0 if row == 0 else row + np.random.uniform(0, 1, size = (1, 5)) * (df.iloc[xti_best].values - np.absolute(axis = 1)))
    print(df2)

The formula I am trying to use for xi_new is:
#xi_new = xi_current + random value between 0,1(xti_best -abs(xi_current)) - random value(xti_worst - abs(xi_current))

A: I'm not sure I'm implementing your formula correctly, but hopefully this helps
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.uniform(-5.0, 10.0, size = (20, 5)), columns = list('ABCDE'))

#while portion of pseudocode
f_func = np.square(df).sum(axis=1)
final_func = np.square(f_func)
xti_best_idx = final_func.idxmin()
xti_worst_idx = final_func.idxmax()

xti_best = df.loc[xti_best_idx]
xti_worst = df.loc[xti_worst_idx]

#Calculate random values for the whole df for the two different areas where you need randomness
nrows,ncols = df.shape
r1 = np.random.uniform(0, 1, size = (nrows, ncols))
r2 = np.random.uniform(0, 1, size = (nrows, ncols))

#xi_new = xi_current + random value between 0,1(xti_best -abs(xi_current)) - random value(xti_worst - abs(xi_current))
df= df+r1*xti_best.sub(df.abs())-r2*xti_worst.sub(df.abs())

df


text:
Q: Show that for complete and right-continuous filtration, and $\sigma = \tau$ a.s. with $\tau$ stopping time, then $\sigma$ stopping time I am trying to solve the following exercise:

Let $\mathcal F = \{ F(t) \}_{t\in [0,T]}$ be a complete and right-continuous filtration, $\tau$ a stopping time for $\mathcal F$ and $\sigma$ a random variable
  with $\tau = \sigma$ almost sure. Show that $\sigma$ is a stopping time.

Now according to my script, a filtration is complete if for every $t \in [0,T]$
$$
 N \in \mathcal F(t) \mbox{ whenever } N \in \mathcal A \mbox{ with } P(N) = 0
$$
where $(\Omega, \mathcal A, P)$ is the surrounding probability space.
But this tells nothing about the completeness of $(\Omega, \mathcal A, P)$, so we cannot conclude that the probability spaces $(\Omega, \mathcal F(t), P)$ for $t \in [0,T]$ are complete. If they would be, then simply by
$$
 \{ \sigma \le t \} = ( \{ \tau \le t \} \cap \{ \tau = \sigma \} ) \cup
                      ( \{ \sigma \le t \} \cap \{\tau \ne \sigma\})
$$
with $P(\tau \ne \sigma) = 0$ this would give $\{\sigma\le t\} \in \mathcal F(t)$. But in this reasoning the right-continuity does not enters, which wonders me, so either
i) the definition of completeness is incomplete, i.e. they forgot to mention that $(\Omega, \mathcal A, P)$ is complete or that the space $(\Omega, \mathcal F(t), P)$ should be complete (this is quite close to that definition from wikipedia), but then right-continuity does not matters here as I see it, or
ii) the definitions are right, but then I do not see how right-continuity of the filtration implies that the particular subsets $\{\sigma \le t\}\cap \{\sigma\ne \tau\}$ of the nullset $\{\sigma\ne\tau\}$ are themselve in $\mathcal F(t)$ for each $t$?
So, what do you think, is i) or ii) right; and then how to apply right-continuity?

A: In the common use of the term, a filtration $\{\mathcal F(t)\}_{t\ge 0}$ is "complete" provided (i) the probability space $(\Omega,\mathcal A,P)$ is complete (in the usual sense), and (ii) $\mathcal F(0)\supset\{N\in\mathcal A: P(N)=0\}$.
As you surmise, right continuity is not needed for the assertion about $\sigma$ to be true.


text:
Q: Rotation through any angle θ They say that rotation of any point $(x,y)$ through any angle $\theta$ is given by $(x \cos\theta, y \sin\theta)$. Can anybody tell how was this derived? Please post here or send me by email.

A: Since rotations of $\Bbb R^2$ are $\Bbb R$ linear transformations, they can be described by $2\times 2$ matrices over $\Bbb R$. Furthermore, the action of the transformation is completely determined by what it does to the unit vectors $[1,0]$ and $[0,1]$.
In the following, you can take $\theta\in [0,\pi/2]$ as an illustration, although it is valid for any $\theta$.
Taking the line segment between $[0,0]$ and $[1,0]$ and rotating it by $\theta$ radians you get a slanted line segment. Drop a perpendicular to the $x$-axis, and you have a right triangle whose angle on the origin is $\theta$. Clearly the coordinates that $[1,0]$ was rotated to is $[\cos(\theta),\sin(\theta)]$.
Similarly, look at where the line segment between $[0,0]$ and $[0,1]$ goes. It will be a slanted line in the third quadrant (for our "small" theta), and it makes an angle of $\theta$ with the $y$ axis. Dropping a perpendicular towards the $y$-axis and performing a little trigonometry you get that the coordinates of $[0,1]$ must be $[-\sin(\theta),\cos(\theta)]$.
So: what would the transformation matrix $A$ have to look like?
Well, we know that $[1,0]A=[\cos(\theta),\sin(\theta)]$ and that $[0,1]A=[-\sin(\theta),\cos(\theta)]$, so that tells us what the rows of $A$ are:
$$
A=\begin{bmatrix}\cos(\theta)&\sin(\theta)\\ -\sin(\theta)&\cos(\theta)\end{bmatrix}
$$
Finally, then we know that this formula applies to anything in the span of $[1,0]$ and $[0,1]$, not just those two vectors. Rotating $[x,y]$ is acheived by matrix multiplication:
$$
[x,y]A=[x,y]\begin{bmatrix}\cos(\theta)&\sin(\theta)\\ -\sin(\theta)&\cos(\theta)\end{bmatrix}=[x\cos(\theta)-y\sin(\theta),x\sin(\theta)+y\cos(\theta)]
$$

A: I arrived at the end formula $[x\cdot\cos(\theta)−y\cdot\sin(\theta),x\cdot\sin(\theta)+y\cdot\cos(\theta)]$ using the unit circle, multiplied by some radius $r$. Any point on the circle is $(r\cdot\cos\theta, r\cdot\sin\theta)$.  Rotate further through any other angle A and the new coordinates are $(r\cdot\cos(\theta+A), r\cdot\sin(\theta+A))$.
Using the formulas for $\sin(u+v)$ and $\cos(u+v)$ you can expand those expressions.  Substitute $x$ for $r\cdot\cos \theta$ and $y$ for $r\cdot\sin \theta$ and you'll get the same thing (in terms of $A$, the angle rotated through).


text:
Q: Hibernate-validator: How do I interpolate messages with variables containing format "${...}"? I have a hibernate-validation message that interpolates a value ${value}.
Issue is, that the value variable itself is a string of the form "${ohno}". I'd like my final interpolated message to replace ${value} with this literal string "${ohno}" but instead it seems to attempt some sort of recursive interpolation which produces the error "Cannot find property ohno".
I can't really thing of a way to "escape" this string in the message template. Perhaps I can escape it in the string itself before I pass it to the annotation but I'd rather not have to do that (I use this string as a literal elsewhere).
Does anyone know of a work around? Or perhaps I should open up a ticket with hibernate-validator...

A: There is really no work around except escaping {,},\ and $ are meta characters which need to be escaped in Bean Validation. See Message Interpolation in the spec. See also HV-934 in the Validator issue tracker.
Now, if you really do not want to interpolate according to the Bean Validation specification, you can write your on MessageInterpolator and make sure that it gets picked up during Validator initialization. Basically you need a validation.xml pointing out your custom interpolator. Check the docs, there are several examples how to do it.


text:
Q: Random variable (What is the meaning of a $g(X)$ ?) I am readin Ross's "A first course in probability" and I got to the chapter that talks about random variables.
I am tryng to understand the exact meaning of something of the form $g(X)$ where g is a real valued function and X is a r.v.
I can't figure the "form" of g, that is, I don't understand what to write in $g: ?\to ??$.
I saw an example that made me think $g:\mathbb{R}\to\mathbb{R}$, is this correct ?

A: Some textbooks have the following framework. If $(\Omega,\mathscr{M},\mu)$ is a probability space and $X:\Omega\to\mathbb{R}$ is a r.v. (i.e., $\mu$-measurable function) and $g:\mathbb{R}\to\mathbb{R}$ (e.g. a continuous function), then $g(X):\Omega\to\mathbb{R}$ is a r.v. which is attained by the composition of $X$ and $g$, i.e. $g\circ X$.


text:
Q: Chronicle Map Callbacks Hi I am a new user of Chronicle Products and till now documentation/usage looks pretty smooth.
Though I have a question when Map data is shared across JVM's on the same host does consumer JVM waiting on the data receive any sort of callback or signal when the data arrives or do we need to implement custom callback mechanism.
Thoughts?

A: Thank you for you question about Chronicle Software products.
There is no callback/notification mechanism in the use-case you describe.
Maps shared between multiple JVMs on the same host 'communicate' using shared memory, not any kind of eventing mechanism. When you write to map A from JVM 1, if JVM 2 also has a reference to map A (i.e. a Map instance created from the same backing file), then it will see the update automatically, because the two map instances are sharing the same region of mapped memory.
I hope this answers your question.
Best Regards,
Terry


text:
Q: Form Validation using a boolean flag Angular 8 In HTML I have a (change)="limitUser($event)" function. In typescript I have a for loop which runs through each element and checks if the value is less than 10. If it exceeds 10 it sets the inValid = true.
In HTMl all my form fields set the value as true. I want only the form field with value greater than 10 to be set as true.
HTML Code:

p.name{{i}}
<input type="text" class="form-control" (change)="limitUser($event)" name="p.name{{i}}" [(ngModel)]="p.usage" id="p.name">

Please enter number smaller than 10

In typescript:
limitUser(event){
for (let i = 0; i < this.data.length; i ++) {
if (this.data[i].usage = 0 || this.data[i].usage = null || this.data[i].usage = ""){
this.data[i].usage = 0;
}
if (this.data[i].usage > 10){
this.inValid = true;
}

But inValid = true is applied to all the dynamic form fields. How can I put it only on the field whose value is larger than 10.

A: Well, inValid is one boolean variable and you're expecting it to hold the validity for every applicable field.
Either have a separate variable for every field, or create a method that checks the validity for each field. Let's go with the second approach:
So, your HTML code should look like this (update the *ngIf directive):

 p.name{{i}}
 <input type="text" class="form-control" name="p.name{{i}}" (change)="limitUser($event)" [(ngModel)]="p.usage" id="p.name">

  Please enter number smaller than 10

And add a new method in your TS, as well as modify limitUser():
isInvalid(index) {
 return this.data[index].usage > 10;
}

limitUser(event) {
 for (let i = 0; i < this.data.length; i ++) {
  // btw, use === to compare; == means loosely compare and = means assign
  // or just append ! to check for falsy values, like:
  if (!this.data[i].usage){
   this.data[i].usage = 0;
  }
 }
}

You can reuse your inValid variable to check the overall validity of the form, or just remove it.
UPDATE:
To disable the submit button when everything is disabled:
Modify your submit button to include a [disabled] attribute in the HTML:
...
<button type="submit" [disabled]="isFormInvalid">
...

And in the TS:
get isFormInvalid() {
 return this.data.some(datum => datum.usage > 10);
}


text:
Q: How to submit a Modal Dialog with Diactionaries ViewModel by JSon
I am trying to submit a modal dialog and get the result on back page after modal is gone.
my ViewModel----
public class InsertPoStep3
  {
    public Dictionary<int, string> FixedCategoryList { get; set; }
    public string Description { get; set; }
    public Dictionary<int, string> FixedDateRangeList { get; set; }
  }

that viewmodel will submit with dictionaries to the Controller ActionResult if i press the Submit button
Controller ActionResult------
public ActionResult CreateCategory(InsertPoStep3 insertPoStep3)
    {
        // foreach (var data in formCollection)
        // {

        var fixedCategory = insertPoStep3.FixedCategoryList.Values;
        //var description = formCollection[formCollection.Count - 1];
        var category = new Category
        {
            //CategoryId = _db.Categories.Count() + 1,
            //CategoryDescription = description,
            FixedCategoryId = Convert.ToInt32(fixedCategory),

        };
        //_db.Categories.Add(category);
       // _db.SaveChanges();

        /* for(int i=1;i<formCollection.Count-1;i++)
         {
             _db.DateRanges.Add(new DateRange
                                    {
                                        CategoryId = category.CategoryId,
                                        FixedDateRangeId =     Convert.ToInt32(formCollection[i])

                                    });
         }

         _db.SaveChanges();*/

        return Json(insertPoStep3);
    }

There are too many comments... actually i dont know how to get data from viewmodel with dictionary....
My Modal Dialog JavaScript-------
<script type="text/javascript">
$(function () {

    $("#InsertCategoryAnchor").click(function () {

        $("#form-dialog").load("/InsertPo/CreateCategory");
        $("#form-dialog").dialog({
            modal: true,

            height:500,

            width: 700,
            closeOnEscape: true,
            resizable: false,
            draggable: true,

            title: "Insert a Category",

            close: function(){
                $(this).dialog("destroy");
            },

            buttons: {
                Submit: function () {
                    var value = $("#myfrom").serialize();

                    $.ajax({
                        url: "/InsertPo/CreateCategory",
                        type: "POST",
                        data: value,
                        success: function (student) {
                            alert("Yes");

                            $(this).dialog('close');
                        }
                    });

                },
                Cancel: function () {
                    $(this).dialog("destroy");
                }
            }
        });
    });
   });

   </script>

How the actual code will be??? Please anyone answer step by step... i am in a fix.... the codes and scenerios are here... but it doesn't work.... JSon and Dictionaries....

A: You're making this too difficult. ASP.NET MVC has built-in ajax functionality. What you want to do is have your buttons on your main page link to partial views. If the user clicks a button, a modal will pop up that will load your partial view. In the partial view, use an Ajax.BeginForm() to handle your postback to the server. Its really that simple. I know because I just created a bunch of pages that use modal popups for inserting and updating view models.


text:
Q: CSP (Content-Security-Policy) not recognizing url origin I am trying to get nicEditor to work on my site, however I am having trouble with the CSP(Content-Security-Protocols).
I downloaded nicEditor locally and have no problems initializing it.
However when trying to upload images it gives me this error:

Refused to connect to 'https://api.imgur(.)com/3/image' because it
  violates the following Content Security Policy directive: "default-src
  'self'". Note that 'connect-src' was not explicitly set, so
  'default-src' is used as a fallback.

This is the metadata tag I am currently using. I only added https://api.imgur(.)com/3/image to default-src for debuging.
<meta http-equiv="Content-Security-Policy" content="default-src https://api.imgur.com 'self' 'unsafe-eval' ; connect-src https://api.imgur.com;  script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';">

From my understanding this should whitelist content and connections to imgur api but that is not happening. any ideas?


text:
Q: Partial Fraction with Unknown Constants I'm having trouble doing the partial fraction decomposition here due to the unknown constants. I need to break down $$x(s)=\frac{F_0\omega}{(s^2+\omega^2)(s^2-\omega_0^2)}$$
where $F_0, \omega,$ and $\omega_0$ are all constants.

A: HINT:
$$\frac{1}{(s^2+\omega^2)(s^2-\omega_0^2)}=\frac{A}{s+i\omega}+\frac{B}{s-i\omega}+\frac{C}{s+\omega_0}+\frac{D}{s-\omega_0}$$
Then, as an example, we can find $A$ as the limit
$$A=\lim_{s\to -i\omega}\frac{(s+i\omega)}{(s^2+\omega^2)(s^2-\omega_0^2)}=\lim_{s\to -i\omega}\frac{1}{(s-i\omega)(s^2-\omega_0^2)}=\frac{1}{i2\omega(\omega^2+\omega_0^2)}$$

A: You do it the same way as if they were numbers.  First $s^2-\omega_0^2=(s-\omega)(s+\omega)$ so write
$$\frac{F_0\omega}{(s^2+\omega^2)(s^2-\omega_0^2)}=\frac{a+bs}{s^2+\omega^2}+\frac c{s-\omega}+\frac d{s+\omega}$$ and use the techniques you are used to.  You can clear fractions and equate powers of $s$, you can take limits as $s \to \pm \omega$, and so on.  Clearly $a,b,c,d$ are proportional to $F_0$ so you can start by ignoring it and multiply by it at the end if you want.


text:
Q: Mobile CSS Bar in landscape doesn't work I have CSS bars, instead of links, on my mobile web page. It works fine in portraits but defaults to to links in landscape view. I use a little bit of jQuery to do this but I can't figure out why it doesn't work in landscape. I simplified the code to force it to work but that didn't help. Could someone help me with this. The jQuery code is below.
if (window.innerWidth && window.innerWidth <= 600)
{
    $(document).ready(function(){
        $('#header ul').addClass('show');
    });
}
else
{
   $(document).ready(function () {
    $('#header ul').addClass('show');
}

A: u cannot use document.ready function inside an if-else construct.
$(document).ready(function() is called as soon as the dom is ready or all your page elements are created. you should indeed do this
$(document).ready(function(){
    if (window.innerWidth && window.innerWidth <= 600) {
    $('#header ul').addClass('show');
    }
});


text:
Q: Contradiction while solving circuit problem! Translation: Find the supplied power from the 4V Source using meshes method

I proposed five equations related with the circuit but I only find contradiction cause I find Rv value fixed. I suspect there should be voltage drops in current sources but I am not sure I think I am doing something conceptually wrong.
Here my calcuations

I skipped some steps but I hope you can follow me.
I am currently getting I2=I3 = 0 which makes the first two equations to fix Rv. By my understanding it is a contradiction.
Note: .5Nk is a name for the resistor value (proportional to N), I have just called it Rv.

A: Let's set up the mesh equations as you have the schematic drawn up:
$$\begin{align*}
0\:\text{V}-200\cdot I_3-600\cdot I_3-400\cdot\left(I_3-I_2\right)-V_{5\:\text{mA}}&= 0\:\text{V}\\\\
0\:\text{V}-R_V\cdot\left(I_2-I_1\right)-400\cdot\left(I_2-I_3\right)-V_{V_2\over 400}&=0\:\text{V}\\\\
0\:\text{V}+4\:\text{V}-500\cdot I_1+V_{5\:\text{mA}}-R_V\cdot\left(I_1-I_2\right)&=0\:\text{V}\\\\
I_1-I_3&=5\:\text{mA}\\\\
I_2=\frac{V_2=200\cdot I_3}{400}&=\frac{I_3}{2}
\end{align*}$$
This provides 5 equations and five unknowns: \$I_1\$, \$I_2\$, \$I_3\$, \$V_{5\:\text{mA}}\$, \$V_{V_2\over 400}\$.
Note that this includes the fact that there are, in fact, voltage drops across your current sources. Those are just two more variables, as shown.
Solving this yields 5 functions which depend upon \$R_V\$.

I can't tell you if \$I_2=I_3=0\:\text{A}\$ without knowing more about \$R_V\$. And I don't understand \$.5\:N\:k\$. (Does it mean \$500\cdot N\$?) So I'm stuck at this point, if you are looking for numerical results that aren't functions of \$R_V\$ (or N.)

(You can get \$I_2=I_3=0\:\text{A}\$ if and only if \$R_V=300\:\Omega\$. For obvious reasons.)

A: If you want to avoid the voltage drops across the current sources, you can write an equation for the loop that doesn't have any current sources (around the outside and down the middle). Use this as your third equation rather than the one you're using now.


text:
Q: How to get rid of the Suitebar I'm pretty new to everything SharePoint, but I'm tasked at the moment to 'brand' a company's intranet (I've got a fair knowledge of HTML and CSS).
One of the things I want to do (actually,what the client wants) is to get rid of the suite bar at the top of the page, but I want to keep the right part of it (login, site settings etc.). That right part must become a part of the master page.
What snippets or other code do I have to use to get this all done.

A: In 2013 ribbon has two section: s4-ribbonrow and suiteBar
#s4-ribbonrow, #suiteBar { display : none; }

The above CSS can hide both sections. And you should place this in the master page to make it work.
If you do the above then even the System Account or Administrator will not be able to see this. That situation can be avoided by doing adding below
<!—MS:<SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2″ runat="server" PermissionsString="AddAndCustomizePages">—>
    <script type="text/javascript">
        document.getElementById("s4-ribbonrow").style.display = "block";
        document.getElementById("suiteBar").style.display = "block";
    </script>
<!—MS:</SharePoint:SPSecurityTrimmedControl>—>

If you want to hide individual Ribbon items then follow this blog. It explains how to find the element class/id using browser tools and then explain how you can hide it using CSS.


text:
Q: 'RestKit/RKSerialization.h' file not found via Cocapods I've been trying for hours but couldn't find any solution that helped me to solve the issue.
my Podfile looks like:
source 'https://github.com/CocoaPods/Specs.git'

inhibit_all_warnings!

xcodeproj 'MyProject.xcodeproj'

# Uncomment this line to define a global platform for your project
# platform :ios, '6.0'

target 'MyProject' do

pod 'ZBarSDK', '~> 1.3.1'
pod 'RestKit'

end

I have tried different options but none of them are working.
Header Search Paths and Library Search Paths & Framework Search Paths have: $(inherited) as value.
#import <RestKit/RestKit.h> // works fine
#import <RestKit/RKSerialization.h> // I get 'RestKit/RKSerialization.h' file not found
#import <RestKit/RKJSONParserJSONKit.h> // 'RestKit/RKJSONParserJSONKit.h' file not found

UPDATE:
cocapods version - 0.38.0
XCode version - Version 7.0 (7A220)

A: I've managed to solve it by using the following Podfile and recreated the project from scratch. I think the problem was that the XCode was created with older version and might interfere something.
source 'https://github.com/CocoaPods/Specs.git'

inhibit_all_warnings!

xcodeproj 'MyProject.xcodeproj'

# Uncomment this line to define a global platform for your project
# platform :ios, '6.0'

target 'MyProject' do

pod 'ZBarSDK', '~> 1.3.1'
pod 'RestKit', '0.10.3' //This is the lastest version that has RKJSONParserJSONKit file, next version is not backward compatibility with previous version, you need to update the code
pod 'FileMD5Hash', :podspec => 'FileMD5Hash.podspec.json'
end

and FileMD5Hash.podspec.json content. You will need to create that file on root folder of the Podfile, thanks &  +1 to @ryanmaxwell
{
  "name": "FileMD5Hash",
  "version": "0.0.1",
  "license": "Apache",
  "summary": "Library for computing MD5 hashes of files with small memory usage.",
  "homepage": "http://www.joel.lopes-da-silva.com/2010/09/07/compute-md5-or-sha-hash-of-large-file-efficiently-on-ios-and-mac-os-x/",
  "authors": {
    "Joel Lopes Da Silva": "joel@lopes-da-silva.com"
  },
  "source": {
    "git": "https://github.com/JoeKun/FileMD5Hash.git",
    "commit": "6864c180c010ab4b0514ba5c025091e12ab01199"
  },
  "prefix_header_file": "Common/FileMD5Hash_Prefix.pch",
  "source_files": "Common/*.{h,c}",
  "requires_arc": false
}


text:
Q: What's the proper way to use different pipenv environments for a Django project on different computer systems? Hopefully this isn't too stupid of a question, concerning the use of pipenv for the same Django project on different computer systems.  The scenario is that I'm using pipenv with a test Django project on one laptop, everything works fine, using VS Code and it's using the proper pipenv environment for the Python environment within VS Code.
The project however is within Dropbox so when I'm using a different laptop, which I do sometimes, one is my work laptop the other is my personal one at home, I can work on the same project wherever I left off.  So you can probably deduce the issue I'm having.
I'm using pipenv environment A on my work laptop for the Django project.  But when I open the project in VS Code on my personal laptop at home I have to keep specifying the proper pipenv environment to use, which obviously is different than the one on my work laptop.
Maybe I shouldn't be working this way and should just work on one laptop for the project, but I imagine others have done the same with similar setups before.
Is there a "proper" way to do this, using different pipenv environments on different machines for the same Django project?  Should I copy over the pipenv environment to each machine as well?  Or am I missing something really simple here?

A: First, use version control.  (git is the defacto standard these days and there are plenty of services to choose from)
For using pipenv, you want to keep your Pipfile and Pipfile.lock in your repository (these are the only files you should be copying related to your environment from system to system).
The local environment is then built on each machine where it is needed by using pipenv sync or pipenv sync --dev (to install dev specific requirements).
So the related virtualenv will be created on each system in which you are developing your project.


text:
Q: File system structure policy using OPA I have a requirement to enforce a particular file system structure on each of my team's repositories.
For example, each repository should have a helm directory with a particular folder structure.
I thought about using OPA, so first, I would like to figure out whether OPA is the right tool for that use case.
And secondly, can someone please provide an example of such a policy?
BTW, I have chosen the Golang SDK and not the REST API.


text:
Q: Is "Joe, I've been finishing with the task" correct? Is this a correct phrase?

Joe, I've been finishing with the task.

A: Possibly. But you might mean any of:

Joe, I've finished the task.

or

Joe, I've finished with the task.

or

Joe, I've been working on the task.

or

Joe, I've been finishing the task.

or

Joe, I'm still finishing the task.

Which all have slightly different meanings.

Joe, I've been finishing with the task

implies (to me at least) you have been doing what is needed to discontinue your work on the task, leaving it in a state where someone else may have to take over the work in order to complete the task, but where you have not yet done enough for your contribution to cease. This is a moderately complex thought and might not be exactly what you intend.

Of course, this is the sort of analysis which enables lawyers to send their children to expensive schools and drive Ferraris. However if I encountered your sentence in a novel I would probably not give it a second glance as these nuances would be unimportant or clear from context.

A: The tense construction, I've been finishing, indicates that the act of finishing has continued for some time. It sounds a bit awkward because the verb finish doesn't seem to have a sense of extended continuity. In other words, saying that the act of finishing is going on for quite a some time sounds unusual.
One can say, I've been working or I've been reading and that would look correct because the verbs work and read can be 'perefectively progressive' like many other verbs and unlike the verb finish.


text:
Q: Pattern-Matching mixed with guards I wanted to define the function:
accumulate_list' :: Num a => [a] -> ( a -> a -> a ) -> a
accumulate_list' l f
    | [] f = 0
    | (x:xs) f = f x (accumulate_list xs f)

but it doesn't compile, complaining that x, xs, x, xs, are Not in scope.
Trying to achieve the same result, I have defined this function
accumulate_list :: Num a => [a] -> ( a -> a -> a ) -> a
accumulate_list [] f = 0
accumulate_list (x:xs) f = f x $ accumulate_list xs f

it compiles well, and does like sum does on a list if the functgion passed in parameter is (+). Yes, I finally found that indeed what I wanted to achieve was already existing in Prelude as the sum function.
However, I don't understand why the first version with mixed guards and pattern matching doesn't compile. What is the problem ?

A: Using what @Sibi's answer provided, I've completed it so as to provide entire working code example:
accumulate_list' :: (Eq a ,Num a) => [a] -> ( a -> a -> a ) -> a
accumulate_list' l f
    | l == [] = 0
    | otherwise = f x $ accumulate_list xs f
                    where (x:xs) = l

A: It is because guards are basically a boolean expression. They have to evaluate to either True or False. Something like this should typecheck:
accumulate_list' :: (Eq a, Num a) => [a] -> ( a -> a -> a ) -> a
accumulate_list' l f
    | l == [] = 0
    | otherwise = undefined -- fill out undefined

It's also worth mentioning that since pattern guards were added to Haskell 2010, you're allowed to mix patterns and guards like so:
accumulate_list' :: (Eq a, Num a) => [a] -> ( a -> a -> a ) -> a
accumulate_list' l f
    | []     <- l = 0          --pattern for the empty list case
    | 10 < 5      = 10         --arbitrary regular guard just because
    | (x:xs) <- l = undefined  --pattern for the non-empty case


text:
Q: How to show progressbar in App store during installation? I try to install Xcode through App store. As I found, it can take a long time (hours) while it is fully installed. Is it possible to display progressbar, how much time (estimately) is remaining to finish installation? Or at least a progress bar, that shows, how much percent of size was downloaded / installed?

A: There should be a progress bar underneath the Launchpad dock icon.
If you removed Launchpad from your dock, open it through Spotlight, then search for the icon of the app you are installing (which in your case would be Xcode). There should be a progress bar and further status information on it.

A: Go to the « Purchased » tab of the Mac App Store. There will be a progress bar.


text:
Q: Obtain all the players born in a particular month in Sqlite I have a players table which contains the following attributes
_id INTEGER PRIMARY KEY, name text not null,birth_date date not null

I want a query which can give me a list of all the players born in a particular month say May of 1986.
How could this be achieved? I tried using the date and time functions provided in SQLite but they were of no use.
Any pointers would be appreciated.
Thanks

A: SELECT p.name, p.birth_date
    FROM Player p
        WHERE p.birth_date > '1986-04-30'
            AND p.birth_date < '1986-06-01';

(untested)

A: I think this should work. I haven't tried it:
SELECT _id, name, birth_date
FROM players
WHERE strftime('%m',birth_date) = '05' AND  strftime('%Y',birth_date) = '1986'

A: SELECT p.name
     , p.birth_date
FROM Player p
WHERE p.birth_date >= '1986-05-01'
  AND p.birth_date < date('1986-05-01','+1 month')
;


text:
Q: My data generator is not getting new data. Just gets same data each interation I have created a data generator in python/Keras to pull in filenames and labels in batchesize=5.  It is getting the same file names and labels every iteration.  I would like it to get new (succeeding) file names and labels each iteration.
I have looked at a number of examples and read the docs but cannot figure this out.
def datagenerator(imgfns, imglabels, batchsize, mode="train"):
    while True:
        images = []
        labels = []
        cnt=0

        while len(images) < batchsize:
            images.append(imgfns[cnt])
            labels.append(imglabels[cnt])
            cnt=cnt+1

        #for ii in range(batchsize):
        #    #img = np.load(imgfns[ii])
        #    #images.append(img)
        #    images.append(imgfns[ii])
        #    labels.append(imglabels[ii])

        #for image, label in zip(imgfns, imglabels):
        #    #img = np.load(image)
        #    #images.append(img)
        #    images.append(image)
        #    labels.append(label)

        print(images)
        print(labels)
        print('********** cnt = ', cnt)
        yield images, labels

train_gen = datagenerator(train_uxo_scrap, train_uxo_scrap_labels, batchsize=BS)

valid_gen = datagenerator(test_uxo_scrap, test_uxo_scrap_labels, batchsize=BS)

# train the network
H = model.fit_generator(
    train_gen,
    steps_per_epoch=NUM_TRAIN_IMAGES // BS,
    validation_data=valid_gen,
    validation_steps=NUM_TEST_IMAGES // BS,
    epochs=NUM_EPOCHS)

Here is an example of the outputs I am getting.  You can see that each time it goes through the generator it fetches the same data.  The first line after "Epoch 1/10", has 5 files names.  The next line has 5 labels (corresponding to batchsize=5).  For example, you can see in each output for the first file name is "... 508.npy" etc.  And the labels are the same for each iteration.
Epoch 1/10
['C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#508.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#1218.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#71.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#551.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#843.npy']
[1, 0, 0, 0, 1]
********** cnt =  5
['C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#508.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#1218.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#71.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#551.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#843.npy']
[1, 0, 0, 0, 1]
********** cnt =  5
['C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#508.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#1218.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#71.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\scrap_48-81\\JBCC_Norm_Formatted_48-81_#551.npy', 'C:\\Users\\jfhauris\\Documents\\xtemp\\ML GEO\\MLGeoCode\\FormattedDataStore\\uxo_48-81\\JBCC_Norm_Formatted_48-81_#843.npy']
[1, 0, 0, 0, 1]
********** cnt =  5

A: The issue is that you are setting cnt=0 every iteration.  You grab 5 filenames, yield those, and then the exact thing is repeated so you're always grabbing the first 5.  You want to change
def datagenerator(imgfns, imglabels, batchsize, mode="train"):
  while True:
    images = []
    labels = []
    cnt=0

to
def datagenerator(imgfns, imglabels, batchsize, mode="train"):
  cnt=0
  while True:
    images = []
    labels = []

You'll also want to make sure cnt stays within the limits of your lists. So something like
while len(images) < batchsize and cnt < len(imgfns):
  # blah


text:
Q: How exactly doctype works in browser? And how exactly xml namespaces work? Consider simple:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Which basically tells the browser to manipulate the tags according to some rules.. So are these rules really read from http://www.w3.org/TR/html4/strict.dtd ? What if this site goes down?
Also, in a simple JSF page using Primefaces for example, you will start with:
xmlns:p="http://primefaces.org/ui"

so that you can use p: tags and Primefaces components..
What exactly is "http://primefaces.org/ui" in here? Does it reference the primefaces.jar ? If so, how? Does it really connect to: "http://primefaces.org/ui" ?
Thank you.

A: No.
Those are URIs – Uniform Resource Identifiers.
They serve as a unique identifier for a doctype or namespace, but they are not used with HTTP.


text:
Q: A solution of second order differential equation has finite zeros or infinite zeros Show that the solution of $y'' + p(x)y' +q(x)y = 0$ on every interal $[a,b]$ has either finite number of zeros or is identically zero.
I'm completely lost here. I've tried using wronskian and Liouville's theroem but they gave me nothing. I have no idea where does the distinction between finite and infinite zeros come from. What conditions are there for solutions to have different zero sets.
I've tried computing the derivative of $y(t_0)$ while assuming that $y(t_0) = 0$. I got $y'(t_0) = lim_{t\to t_0} \frac{y(t)}{t-t_0}$ and from the uniqueness and existence theroem I can show that $y(t) \equiv 0$ if $y'(t_0) = 0$. There are no assumptions on $p(x)$ and $q(x)$.


text:
Q: Pagination for custom shop loop woocommerce I'm using custom shop loop on woocommerce archive-product page. And trouble is that i have one more extra empty page. This pagination work fine for blog, but not here.
<?php
                $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
                $product = new WC_Product(get_the_ID());
                $params = array('posts_per_page' => 12, 'post_type' => 'product', 'paged' => $paged, 'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'free' ),
            'operator' => 'NOT IN'
        )
    ));
                $wc_query = new WP_Query($params);
                ?>
                <?php if ($wc_query->have_posts()) : ?>
                <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>

                        <?php if ( has_post_thumbnail()) {the_post_thumbnail('thumb-blog' ,array("class"=>"portfolio__image post_thumbnail"));} ?>

<?php the_title(); ?>

<?php $product = new WC_Product(get_the_ID()); echo $product->get_price_html(); ?>

                            <img class="portfolio__content-image" src="<?php echo get_template_directory_uri(); ?>/img/link-loop.png" alt="" data-jslghtbx="<?php
                                $thumb_id = get_post_thumbnail_id();
                                $thumb_url = wp_get_attachment_image_src($thumb_id,'thumb-big', true);
                                echo $thumb_url[0];
                            ?>">
                            <a href="?add-to-cart=<?php echo $product->id; ?>" class="portfolio__link">

Click to buy

                <?php endwhile; ?>

How i can fix this? http://wrap-design.com/portfolio/
And this is me code for pagination in function.php
function wp_corenavi() {
  global $wp_query;
  $pages = '';
  $max = $wp_query->max_num_pages;
  if (!$current = get_query_var('paged')) $current = 1;
  $a['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
  $a['total'] = $max;
  $a['current'] = $current;

  $total = 0; //1 - выводить текст "Страница N из N", 0 - не выводить
  $a['mid_size'] = 3; //сколько ссылок показывать слева и справа от текущей
  $a['end_size'] = 1; //сколько ссылок показывать в начале и в конце
  $a['prev_text'] = ''; //текст ссылки "Предыдущая страница"
  $a['next_text'] = ''; //текст ссылки "Следующая страница"

  if ($max > 1) echo '
';
  if ($total == 1 && $max > 1) $pages = 'Страница ' . $current . ' из ' . $max . ''."\r\n";
  echo $pages . paginate_links($a);
  if ($max > 1) echo '
';
}

A: It's a strange, but when in wordpress setting - reading "blog page show at most" number equal with post_per_page in my loop everything is working!)


text:
Q: How to show that $\sqrt{\ln 2}\times\sum_{k=1}^{\infty}\frac{\sqrt{k+1}}{2^k}<\frac{3}{2}$? I know that $\sum_{k=1}^{\infty}\frac{\sqrt{k+1}}{2^k}$ is a convergent sequence. Indeed, I can show that $\sum_{k=1}^{\infty}\frac{\sqrt{k+1}}{2^k}\leq \sum_{k=1}^{\infty}\frac{k+1}{2^k}=3$. However, when I multiply $\sum_{k=1}^{\infty}\frac{\sqrt{k+1}}{2^k}$ by $\sqrt{\ln 2}$, I can use Mathematica to show that $\sqrt{\ln 2}\sum_{k=1}^{\infty}\frac{\sqrt{k+1}}{2^k}<\frac{3}{2}$. However, I would like to seek for a mathematical proof. Unfortunately, I cannot prove the assertion rigorously. Could anyone help me?

A: By the Cauchy–Schwarz inequality
$$
\sum\limits_{k = 1}^\infty  {\frac{{\sqrt {k + 1} }}{{2^k }}}  = \sum\limits_{k = 1}^\infty  {\frac{1}{{2^{k/2} }}\frac{{\sqrt {k + 1} }}{{2^{k/2} }}}  \le \sqrt {\sum\limits_{k = 1}^\infty  {\frac{1}{{2^k }}} } \sqrt {\sum\limits_{k = 1}^\infty  {\frac{{k + 1}}{{2^k }}} }  = \sqrt 3 .
$$
Thus,
$$
\sqrt {\ln 2} \sum\limits_{k = 1}^\infty  {\frac{{\sqrt {k + 1} }}{{2^k }}}  \le \sqrt {3\ln 2}<\sqrt{3\cdot 0.75} = \frac{3}{2}.
$$

A: $$S=\sum_{k=1}^{\infty }\frac{\sqrt{k+1}}{2^k}=\sum_{k=1}^{\infty }\sqrt{k}\frac{\sqrt{1+\frac{1}{k}}}{2^k}$$ So
$$\sqrt{k+1}=\sum_{p=0}^\infty \binom{\frac{1}{2}}{p} \,k^{\frac{1}{2}-p}$$ Swith the summations to face
$$S=\sum_{p=0}^\infty \binom{\frac{1}{2}}{p} \text{Li}_{p-\frac{1}{2}}\left(\frac{1}{2}\right)$$
which converges very fast. Computing a few partail sums
$$T_n=\sum_{p=0}^n \binom{\frac{1}{2}}{p} \text{Li}_{p-\frac{1}{2}}\left(\frac{1}{2}\right)$$
$$\left(
\begin{array}{cc}
n & T_n \\
 1 & 1.75032 \\
 2 & 1.67221 \\
 3 & 1.70690 \\
 4 & 1.68638 \\
 5 & 1.70038 \\
 6 & 1.69000 \\
 7 & 1.69811 \\
 8 & 1.69154 \\
 9 & 1.69701 \\
 10 & 1.69237
\end{array}
\right)$$
Even with $T_1$ you have the inequality.
Edit
If you enjoy special functions
$$S=\frac{1}{2} \Phi \left(\frac{1}{2},-\frac{1}{2},2\right)$$ where appears the Lerch transcendent function. Its numerical value is $1.69451$.


text:
Q: Authoritatively signed certificates or own certificate for web service for Android clients with phonegap I develop web services for enterprises and I'm use to generate my own certificates that I can install on my clients as our SW will be allways intalled in closed organizations.
Now my web service will be serving a Android App which is indeed a HTML5 & Javascript application compiled with phonegap...
Here, I don't know how to install my certificate, I found some examples in internet, but they are more or less workarounds.
Is there a way to install a certificate on Android or on the browser used by phonegap, or should I consider adquiring a certificate from a official provider?
Any help or opinion from someone which made a similar installation will be great, it is my first Android project!
Thanks!

A: On Android 4.0 and later you can install any certificate in the system trust store (needs user confirmation). On earlier versions you cannot change system trust stores. To make sure your app works in all versions you need to include the certificate in the app by creating a custom TrustManager initialized with your own certificate(s). For whether one can be used with Phonegap or not, check their documentation.


text:
Q: Can't read UTF-8 filenames when launched as an Upstart service My Java program reads the contents of a directory recursively. This is a sample tree (note the non-ASCII characters):
./sviluppo
./sviluppo/ciaò
./sviluppo/ciaò/subdir
./sviluppo/pippo
./sviluppo/pippo/prova2.txt <-file
./sviluppo/così

The program is started as an Upstart service, with a configuration file named like /init/myservice.conf
description "Private Service"
author "AD"
start on runlevel [2345]
stop on runlevel [! 2345]
exec java -jar /home/mainFind.jar >> /tmp/log.txt

When I launch the service:
root@mdr:/tmp#  service myservice start
myservice start/running, process 15344

it doesn't log filenames with non-ASCII characters in the name:
root@mdr:/tmp#  cat /tmp/log.txt
Found dir: /mnt/sviluppo/pippo

Instead, when I run the command (as root, to mimic what happens when it's started as a service) it works fine, with and without exec:
root@mdr:/tmp# java -jar /home/mainFind.jar  >> /tmp/log.txt
root@mdr:/tmp# exec java -jar /home/mainFind.jar  >> /tmp/log.txt

root@mdr:/tmp#  cat /tmp/log.txt
Found dir: /mnt/sviluppo/ciaò
Found dir: /mnt/sviluppo/ciaò/subdir
Found dir: /mnt/sviluppo/pippo
Found dir: /mnt/sviluppo/così

Why the same program run by the same user doesn't work in an Upstart service, but correctly processes all of the filenames when run from the command line? Here is the Java code
public static void aggiungiFileDir(File f){
  File[] lista= f.listFiles();
  for(int i=0;i<lista.length;i++){
    if(lista[i].isDirectory()){
      System.out.println("Found dir: "+lista[i]);
    }
  }
}

Where the formal parameter f is the root dir. The function will be called recursively on each subdir.
EDIT 2: Post ls
root@mdr:/tmp# ls -al /mnt/sviluppo
totale 20
drwx------ 5 root root 4096 nov 15 15:10 .
drwxr-xr-x 7 root root 4096 nov  9 10:43 ..
drwxr-xr-x 2 root root 4096 nov 15 15:10 ciaò
drwxr-xr-x 2 root root 4096 nov 15 11:23 così
drwxr-xr-x 2 root root 4096 nov 15 17:57 pippo

A: Java uses a native call to list the contents of a directory. The underlying C runtime  relies on the locale concept to build Java Strings from the byte blob stored by the filesystem as the filename.
When you execute a Java program from a shell (either as a privileged user or an unprivileged one) it carries an environment made of variables. The variable LANG is read to transcode the stream of bytes to a Java String, and by default on Ubuntu it's associated to the UTF-8 encoding.
Note that a process need not to be run from any shell, but looking at the code it seems that Upstart is smart enough to understand when the command in the configuration file is intended to be executed from a shell. So, assuming that the JVM is invoked through a shell, the problem is that the variable LANG is not set, so the C runtime assumes a default charset, which happens to not be UTF-8. The solution is in the Upstart stanza:
description "List UTF-8 encoded filenames"
author "Raffaele Sgarro"
env LANG=en_US.UTF-8
script
  cd /workspace
  java -jar list.jar test > log.txt
end script

I used en_US.UTF-8 as the locale, but any UTF-8 backed one will do just as well. The sources of the test list.jar
public static void main(String[] args) {
    for (File file : new File(args[0]).listFiles()) {
        System.out.println(file.getName());
    }
}

The directory /workspace/test contains filenames like ààà, èèè and so on. Now you can move to the database part ;)

A: Adding this to /etc/init.d/script fixed this issue for me (I copied it from /etc/init.d/tomcat7):
# Make sure script is started with system locale
if [ -r /etc/default/locale ]; then
    . /etc/default/locale
    export LANG
fi

Contents of /etc/default/locale on my machine:
LANGUAGE=en_US:en
LANG=en_US.UTF-8


text:
Q: Angular 4 - DateFormatter - how to I have application in Angular 2 that use custom formatting date to Polish:
return DateFormatter.format( new Date( date + ' 12:00:00' ), 'pl-PL', 'd MMMM y' );

It is possible by importing class
import { DateFormatter } from '@angular/common/src/facade/intl';

Next, I converting/upgrading my application to Angular 4.3 and this class (DateFormatter) is no longer there.
I someone knows where it is located, or what other methods I should use to achieve such formatting?

A: The DateFormatter class can currently be found here in source code.
However, Angular disallows importing from deep path such as this one. If @angular/common does not expose the function you're looking for, it means it's private and you're not supposed to be using it (which is why your application broke after upgrading).
Consider using the DatePipe or a utility library such as date-fns.

A: In our application we use date pipe. E.g.
{{bfPreventer.nextControlDate | date: 'shortDate'}}

By default it takes the current culture of your browser. But you can change it at start up. I'm not sure if it's perfect, but it works for us well.
@NgModule({
bootstrap: [AppComponent],
declarations: [
    ...pageComponents
],
imports: [
    BrowserModule,
    ...
    TranslateModule.forRoot(),

],
providers: [

    { provide: LOCALE_ID, useValue: window.navigator.language.indexOf("en") >= 0 ? "en-US" : "nb-NO" },

]})

Also, please take into the consideration that the pipe relies on i18n API of the browser, so old browsers might have issues with that.


text:
Q: What does g++ allocate unused memory on the stack? When analyzing the binary code generated by g++ 5.2.0, I found that the compiler frequently allocates memory that seems not used by any program elements. Below is an example.
The source code is
void
cxx_pretty_printer::declarator (tree t)
{
  this->direct_declarator (t); // A virtual function call
}

and the generated binary
0x8427ce8   _ZN18cxx_pretty_printer10declaratorEP9tree_node:
0x8427ce8   push    %ebp
0x8427ce9   mov     %esp, %ebp
0x8427ceb   sub     $0x8, %esp
0x8427cee   mov     0x8(%ebp), %eax
0x8427cf1   mov     0x0(%eax), %eax
0x8427cf3   add     $0x4c, %eax
0x8427cf6   mov     0x0(%eax), %eax
0x8427cf8   sub     $0x8, %esp
0x8427cfb   pushl   0xc(%ebp)
0x8427cfe   pushl   0x8(%ebp)
0x8427d01   call    *0x0(%eax,0)
0x8427d03   add     $0x10, %esp
0x8427d06   nop
0x8427d07   leave
0x8427d08   ret

I don't quite understand why the code at 0x8427ceb and 0x8427cf8 should exist. The compiler decreases the stack register, which seems to me that it is allocating some space on the stack. However, this space is never used by anything.
Is there any particular reason that makes g++ do this? The options I used are
-O2 -fno-exceptions -fno-rtti -fasynchronous-unwind-tables

A: As EOF mentioned in the comment, this is due to stack alignment and is subject to change by setting the option -mpreferred-stack-boundary. The credit goes to this answer https://stackoverflow.com/a/1061942/696110
The option mentioned affects C compilation as well.


text:
Q: Get is_read when I'm one of the many message recipients In my app, users
CREATE TABLE users (
    id bigserial PRIMARY KEY,
    username varchar(50) NOT NULL
);

can send messages
CREATE TABLE messages (
    id bigserial PRIMARY KEY,
    from_id bigint NOT NULL REFERENCES users ON DELETE RESTRICT,
    body text NOT NULL CHECK (body <> ''),
    created_at timestamp(0) NOT NULL DEFAULT LOCALTIMESTAMP(0),
    is_read boolean NOT NULL DEFAULT TRUE
);

to many recipients
CREATE TABLE message_recipients (
    message_id bigint NOT NULL REFERENCES messages ON DELETE CASCADE,
    user_id bigint NOT NULL REFERENCES users ON DELETE RESTRICT,
    is_read boolean NOT NULL DEFAULT FALSE,
    PRIMARY KEY (message_id, user_id)
);

How do I select messages sent between multiple users such that the is_read column specifies whether one of those users has read the messages? I also want to include a column called to_ids that contains a comma-separated list of the message-recipient user IDs.
E.g., how do I get the messages sent between users 1, 2, and 3 such that the is_read column specifies whether user 1 has read the messages? The to_ids column contains two comma-separated IDs from the set {1, 2, 3}.
The result set should include the columns: id, from_id, to_ids, body, created_at, is_read.
Sample Data
SELECT * FROM users;
#  id |  username  |
# ----+------------+
#   1 | user1      |
#   2 | user2      |
#   3 | user3      |

SELECT * FROM messages;
#  id | from_id |       body          |     created_at      | is_read
# ----+---------+---------------------+---------------------+---------
#   1 |       1 | This is message 1.  | 2016-12-16 11:41:50 | t
#   2 |       2 | This is message 2.  | 2016-12-16 11:41:50 | t
#   3 |       3 | This is message 3.  | 2016-12-16 11:41:50 | t
#   4 |       1 | This is message 4.  | 2016-12-16 11:41:50 | t
#   5 |       2 | This is message 5.  | 2016-12-16 11:41:50 | t
#   6 |       3 | This is message 6.  | 2016-12-16 11:41:50 | t
#   7 |       1 | This is message 7.  | 2016-12-16 11:41:50 | t

SELECT * FROM message_recipients;
#  message_id | user_id | is_read
# ------------+---------+---------
#           1 |       2 | f
#           1 |       3 | f
#           2 |       1 | f
#           2 |       3 | f
#           3 |       1 | f
#           3 |       2 | f
#           4 |       2 | f
#           4 |       3 | f
#           5 |       1 | f
#           5 |       3 | f
#           6 |       1 | f
#           6 |       2 | f
#           7 |       2 | f
#           7 |       3 | f

Expected Output
#  id | from_id | to_ids |       body          |     created_at      | is_read
# ----+---------+--------+---------------------+---------------------+---------
#   1 |       1 |    2,3 | This is message 1.  | 2016-12-16 11:41:50 | t
#   2 |       2 |    1,3 | This is message 2.  | 2016-12-16 11:41:50 | f
#   3 |       3 |    1,2 | This is message 3.  | 2016-12-16 11:41:50 | f
#   4 |       1 |    2,3 | This is message 4.  | 2016-12-16 11:41:50 | t
#   5 |       2 |    1,3 | This is message 5.  | 2016-12-16 11:41:50 | f
#   6 |       3 |    1,2 | This is message 6.  | 2016-12-16 11:41:50 | f
#   7 |       1 |    2,3 | This is message 7.  | 2016-12-16 11:41:50 | t


text:
Q: WCF client works as console application but running as Windows service, fails with EndpointNotFoundException I wrote a C# console application to consume a local WCF service using NetNamedPipeBinding. The WCF service I consume is running as a local Windows application. My WCF client works fine as a console application. However, when I implement essentially the same WCF client not as a console application but as a Windows service, my WCF client cannot find the local WCF endpoint and throws System.ServiceModel.EndpointNotFoundException exceptions.
Why would a WCF client run fine as a console application and then throw EndpointNotFoundException when the client is running as a Windows service?
This is how I create the channel factory in the client code:
// Define some local variables needed to create the channel factory
string strendpoint = string.Format("net.pipe://localhost/{0}", BluehillAPIService.ServiceName);
EndpointAddress endpoint = new EndpointAddress(strendpoint);
NetNamedPipeBinding binding = new NetNamedPipeBinding();
InstanceContext instanceContact = new InstanceContext(this);

// Create the channel factory
ChannelFactory = new DuplexChannelFactory<IBluehillAPIService>(instanceContact, binding, endpoint);

Then I create the channel like this:
_bluehillAPIService = ChannelFactory.CreateChannel();

No errors so far, but when I try to actually use the channel as follows, I get an exception:
if (!_bluehillAPIService.APIHeartbeat()) ...

The call to _bluehillAPIService.APIHeartbeat() in my WCF client generates a System.ServiceModel.EndpointNotFoundException when this code is running as a Windows service logged in as Local System but works fine when essentially identical code is running as a console application.

A: Because the LocalSystem account presents anonymous credentials when accessing network resources, network applications running in that context may not operate as expected.
Specify an appropriate account on your service's "Log On" tab -- an account where you can log in and run the application without error:


text:
Q: Python IMAP search using a subject encoded with utf-8 This question is related to question Python IMAP search using a subject encoded with iso-8859-1, but the reply given there is not working for me.
I am doing the following IMAP search in python:
typ, data = self.M.search("utf-8", "(SUBJECT %s)" % u"réception".encode("utf-8"))

And I get the following exception:
...
    typ, data = self.M.search("utf-8", "(SUBJECT %s)" % u"réception".encode("utf-8"))
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 625, in search
    typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 1070, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/local/python/2.7.2/lib/python2.7/imaplib.py", line 905, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
error: SEARCH command error: BAD ['Could not parse command']

Why is that? How can I solve this problem?

A: import imaplib
import getpass
email = "XXXXXXX@gmail.com"

sock = imaplib.IMAP4_SSL("imap.gmail.com", 993)
sock.login(email, getpass.getpass())

# select the correct mailbox...
sock.select()
# turn on debugging if you like
sock.debug = 4

then:
# use the undocumented IMAP4.literal attribute
sock.literal = "réception"
sock.uid('SEARCH', 'CHARSET', 'UTF-8', 'SUBJECT')

A: u"réception" will need to be wrapped with quotes: u'"réception"', as IMAPLIB will not quote the string for you in the list.
Update: I could not get gmail's IMAP implementation to accept even a quoted string, and had to use IMAP literal syntax.  I'm not sure if this is limitation of my encoding using socat, or a limitation with gmail.
a UID SEARCH CHARSET utf-8 SUBJECT "réception"
a BAD Could not parse command

a UID SEARCH CHARSET utf-8 SUBJECT {10}
+ go ahead
réception
* SEARCH
a OK SEARCH completed (Success)

Unfortunately, imaplib does not provide any way to force using of an IMAP literal.

A: External lib https://github.com/ikvk/imap_tools supports search by encoded data
from imap_tools import MailBox, A

# get list of emails that subject contains "réception" from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
    for msg in mailbox.fetch(A(subject='réception'), charset='utf8'):
        print(msg.subject)

A: this one works for me
# use the undocumented IMAP4.literal attribute
sock.literal = u"réception".encode('utf-8')
sock.uid('SEARCH', 'CHARSET', 'UTF-8', 'SUBJECT')

Thanks, Lee!


text:
Q: Order by depending on 2 column values I have a query which returns the output as below,
SELECT DISTINCT  a.rev_date ,fruitname,
 fruit_id , primary_fruit_id
FROM fruits a, fruit_lookup s,fruit_reference r
WHERE a.id = s.id(+)
 and primary_fruit_id = r.fruit_id(+)
AND (fruit_id = 24 or fruit_id = 0)
ORDER BY fruit_id desc, a.rev_date desc

How to handle this such that I still get the desired output where when both the id and primary id are same show them first? any idea is appreciated. I tried doing union etc but not getting the desired o/p. The order by fruit_id desc is not right as this is not ordering in the correct manner.thanks
 NAME       FRUIT_ID    PRIMARY_FRUIT_ID
--------------------------------------
apple       24          24
orange      24          12
pear        24           7
apple       24          24
kiwi        24           6
apple       24          24
apple       24          24
melon       24           2
grape        0          90
banana       0          45
carrot       0          30

Desired output
NAME    FRUIT_ID    PRIMARY_FRUIT_ID
--------------------------------------
apple       24          24
apple       24          24
apple       24          24
apple       24          24
kiwi        24           6
orange      24          12
melon       24           2
pear        24           7
grape        0          90
banana       0          45
carrot       0          30

A: You want to generate a value just to sort on based on the condition you want.
ORDER BY fruit_id desc,
         a.rev_date desc,
         case when fruit_id = primary_fruit_id then 0 else 1 end

You don't show the date field in your sample outputs, so I don't know how that date segments the output. I'm guessing that the date is more relevant than the "same key value" but you can place it wherever gives you the effect you want.
ORDER BY fruit_id desc,
         case when fruit_id = primary_fruit_id then 0 else 1 end,
         a.rev_date desc

ORDER BY case when fruit_id = primary_fruit_id then 0 else 1 end,
         fruit_id desc,
         a.rev_date desc

A: Try this:
ORDER BY fruit_id desc, abs(fruit_id-PRIMARY_FRUIT_ID) asc


text:
Q: ThreeJS on iPhone, long touch ( holding ) selects whole screen and makes it blue Also before the whole screen gets selected and turns transparent blue, small bubble pops up ( not sure if its for moving cursor or it's a magnifier.
Anyways, is there some way to prevent these events on iPhone when using threejs?
Already using these in my css:
*
{
    -webkit-touch-callout: none;
    -webkit-user-callout: none;
    -webkit-user-select: none;
    user-select: none;
    -webkit-user-drag: none;
    -webkit-user-modify: none;
    -webkit-highlight: none;
}

This text selection is showing up I think:
https://support.apple.com/guide/iphone/select-and-edit-text-iph1a9cae52c/ios
https://9to5mac.com/2021/06/07/ios-15-brings-back-the-magnifying-glass-for-accurate-text-selection/


text:
Q: C++ Confused by epoll and socket fd on Linux systems and async threads I am trying to understand how to use the epoll library (Linux) in combination with socket file descriptors. There is limited information about epoll available online as far as I can tell. So far the most useful resource I have found is this:
https://www.suchprogramming.com/epoll-in-3-easy-steps/
Which gives a complete working example of epoll however it is used with the stdin file descriptor. (Elsewhere I read that epoll can not be used with stdin, stdout and stderr. I assume that information was wrong.)
I have tried to build on this with a MWE.
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <string.h>
#include <unistd.h>
#include <future>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>

int thread_function(int accept_sock_fd)
{
    char *read_buffer = new char[1024];

    unsigned int read_length = 0;
    std::string read_string = "";
    for(;;)
    {
        unsigned int t_read_length = read(accept_sock_fd, read_buffer, 1024 - 1);
        //std::cout << "t_read_length=" << t_read_length << std::endl;
        //std::cout << read_buffer << std::endl;
        read_string += std::string(read_buffer);
        read_length += t_read_length;

        // dodgy ?
        // tries to detect end of data using new lines
        // but what if client does not send new line char?
        if(read_buffer[t_read_length - 1] == '\n')
        {
            break;
        }
    }
    std::cout << read_string << std::endl;
    //std::cout << read_length << std::endl;
    //std::cout << read_buffer << std::endl;

    std::string status_line = "HTTP/1.0 200 OK\r\n\r\n";
    std::string html_lines = "Hello World\r\n\r\n";
    std::string write_string = status_line + html_lines;
    //std::cout << write_string << std::endl;
    unsigned int write_length = write(accept_sock_fd, write_string.data(), write_string.length());
    //std::cout << "write_length=" << write_length << std::endl;
    close(accept_sock_fd);

    delete [] read_buffer;

    return 0;
}

int main()
{

    // read configuration file
    //Config config;
    //config.ReadFromFile("config.txt");
    //std::cout << config << std::endl;

    unsigned int num_threads = 4; //config.GetNumThreads();

    ///////////////////////////////////////////////////////////////////////////
    // init epoll
    //
    //

    int epoll_fd = epoll_create(num_threads);
    if(epoll_fd < 0)
    {
        std::cout << "epoll error" << std::endl;
    }

    struct epoll_event event;
    struct epoll_event *events = new struct epoll_event[num_threads * sizeof(struct epoll_event)];

    ///////////////////////////////////////////////////////////////////////////
    // create socket fd
    //
    //

    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == 0)
    {
        std::cout << "Error creating sock_fd" << std::endl;
    }
//    int setsockopt(sockfd,

    struct sockaddr_in server_address;
    memset(&server_address, 0, sizeof(struct sockaddr_in));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = INADDR_ANY;
    server_address.sin_port = htons(55555 /*config.GetPort()*/);

    bind(sock_fd, (struct sockaddr *)&server_address, sizeof(server_address));
    if(bind < 0)
    {
        std::cout << "Error: bind" << std::endl;
    }

    if(listen(sock_fd, 10) < 0)
    {
        std::cout << "Error: listen" << std::endl;
    }

    ///////////////////////////////////////////////////////////////////////////
    // continue epoll setup
    //
    //

    event.events = EPOLLIN; // | EPOLLPRI | EPOLLERR | EPOLLHUP;
    event.data.fd = 0; //client_sock;
    if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &event)) // not sure about this
    {
        std::cout << "Failed to add epoll" << std::endl;
        return 1;
    }

    for(;;)
    {
        int n_fd = epoll_wait(epoll_fd, events, num_threads, 0);
        if(n_fd < 0)
        {
            std::cout << "die" << std::endl;
            break;
        }

        for(int i = 0; i < n_fd; ++ i)
        {
            int fd = events[i].data.fd;

            // accpt connection
            int accept_sock_fd = 0;
            struct sockaddr client_address;
            int addrlen = sizeof(client_address);
            accept_sock_fd = accept(fd, NULL, NULL); // not sure what goes here
            accept_sock_fd = accept(sock_fd, NULL, NULL); // not sure what goes here
            if(accept_sock_fd < 0)
            {
                std::cout << "Error: accept" << std::endl;
            }

            // do something to handle data on accept_sock_fd
            std::future<int> thread_future = std::async(thread_function, accept_sock_fd);
            int ret = thread_future.get();
            std::cout << ret << std::endl;

            // close connection
            close(accept_sock_fd);

        }
    }

    delete [] events;

    close(sock_fd);

    if(close(epoll_fd))
    {
        std::cout << "error: failed to close epoll fd" << std::endl;
    }

    return 0;
}

I have searched pretty extensively for further information on how to combine epoll with sockets, but there isn't much information about this. I suppose it is quite a niche area.
Ideally if anyone knows of any good resources (even a book) where I can find more information about this and thus solve the problem myself that would be great, otherwise some advice on how to proceed would be appreciated also.
I am mostly confused as to how I watch for events on the socket fd and also how I then accept events and handle the new fd returned by accept.
See these lines in the above code:
// correct fd
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, /*the_server_socket_fd*/, &event);
...
// not sure about this one, particularly the waiting time of 0
for(;;)
    epoll_wait(epoll_fd, events, /*num_threads*/, 0);

    for(i ...)
        fd = events[i].data.fd; // what fd is this? what does it mean?
        accept(/*something here, but what*/ fd OR the_server_socket_fd ?, NULL, NULL);
        // launch thread with retuned value from accept, probably

A: Using epoll is not so much different with using poll. The tricky thing is that keep track which client owns file descriptor returned by epoll (if there are a lot of clients).

How to handle socket file asynchronously with epoll (in this case as TCP socket server).

*

*Open an epoll file descriptor with epoll_create(2).

*Create a TCP socket with socket(2), bind(2) and listen(2).

*Add the main TCP socket file descriptor to epoll with epoll_ctl + EPOLL_CTL_ADD.

*Call epoll_wait inside a loop, the program will sleep on epoll_wait, the kernel will wake the program up when there is event coming from monitored file descriptors or when timeout is reached.

*If epoll_wait returns a value greater than zero, then you need to decide, what file descriptor returned by epoll.

5.1. If it is main TCP file descriptor, then you need to accept(2). And then add the client file descriptor returned by accept(2) to epoll with epoll_ctl + EPOLL_CTL_ADD. Other
5.2. If it is client file descriptor, then you need to call recv(2) and do any action you want with that client.
At step 5.2, if you see EPOLLHUP in the events[i].events, then the client has closed its connection and you need to call epoll_ctl + EPOLL_CTL_DEL and close the client file descriptor (it may be safe not to call epoll_ctl + EPOLL_CTL_DEL and just close the client file descriptor, but I prefer to delete it from epoll first).

*Goto step 4.

Detailed mechanism about how to determine which client owns file descriptor returned by epoll can be seen from server.c code below.

Flowchart
Flowchart can make it more clear.

Working example you can try at home
server.c
/*
 * https://stackoverflow.com/questions/66916835/c-confused-by-epoll-and-socket-fd-on-linux-systems-and-async-threads
 */
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>

#define PRERF "(errno=%d) %s\n"
#define PREAR(NUM) NUM, strerror(NUM)
#define EPOLL_MAP_TO_NOP (0u)
#define EPOLL_MAP_SHIFT  (1u) /* Shift to cover reserved value MAP_TO_NOP */

struct client_slot {
    bool                is_used;
    int                 client_fd;
    char                src_ip[sizeof("xxx.xxx.xxx.xxx")];
    uint16_t            src_port;
    uint16_t            my_index;
};

struct tcp_state {
    bool                stop;
    int                 tcp_fd;
    int                 epoll_fd;
    uint16_t            client_c;
    struct client_slot  clients[10];

    /*
     * Map the file descriptor to client_slot array index
     * Note: We assume there is no file descriptor greater than 10000.
     *
     * You must adjust this in production.
     */
    uint32_t            client_map[10000];
};

static int my_epoll_add(int epoll_fd, int fd, uint32_t events)
{
    int err;
    struct epoll_event event;

    /* Shut the valgrind up! */
    memset(&event, 0, sizeof(struct epoll_event));

    event.events  = events;
    event.data.fd = fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) {
        err = errno;
        printf("epoll_ctl(EPOLL_CTL_ADD): " PRERF, PREAR(err));
        return -1;
    }
    return 0;
}

static int my_epoll_delete(int epoll_fd, int fd)
{
    int err;

    if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL) < 0) {
        err = errno;
        printf("epoll_ctl(EPOLL_CTL_DEL): " PRERF, PREAR(err));
        return -1;
    }
    return 0;
}

static const char *convert_addr_ntop(struct sockaddr_in *addr, char *src_ip_buf)
{
    int err;
    const char *ret;
    in_addr_t saddr = addr->sin_addr.s_addr;

    ret = inet_ntop(AF_INET, &saddr, src_ip_buf, sizeof("xxx.xxx.xxx.xxx"));
    if (ret == NULL) {
        err = errno;
        err = err ? err : EINVAL;
        printf("inet_ntop(): " PRERF, PREAR(err));
        return NULL;
    }

    return ret;
}

static int accept_new_client(int tcp_fd, struct tcp_state *state)
{
    int err;
    int client_fd;
    struct sockaddr_in addr;
    socklen_t addr_len = sizeof(addr);
    uint16_t src_port;
    const char *src_ip;
    char src_ip_buf[sizeof("xxx.xxx.xxx.xxx")];
    const size_t client_slot_num = sizeof(state->clients) / sizeof(*state->clients);

    memset(&addr, 0, sizeof(addr));
    client_fd = accept(tcp_fd, (struct sockaddr *)&addr, &addr_len);
    if (client_fd < 0) {
        err = errno;
        if (err == EAGAIN)
            return 0;

        /* Error */
        printf("accept(): " PRERF, PREAR(err));
        return -1;
    }

    src_port = ntohs(addr.sin_port);
    src_ip   = convert_addr_ntop(&addr, src_ip_buf);
    if (!src_ip) {
        printf("Cannot parse source address\n");
        goto out_close;
    }

    /*
     * Find unused client slot.
     *
     * In real world application, you don't want to iterate
     * the whole array, instead you can use stack data structure
     * to retrieve unused index in O(1).
     *
     */
    for (size_t i = 0; i < client_slot_num; i++) {
        struct client_slot *client = &state->clients[i];

        if (!client->is_used) {
            /*
             * We found unused slot.
             */

            client->client_fd = client_fd;
            memcpy(client->src_ip, src_ip_buf, sizeof(src_ip_buf));
            client->src_port = src_port;
            client->is_used = true;
            client->my_index = i;

            /*
             * We map the client_fd to client array index that we accept
             * here.
             */
            state->client_map[client_fd] = client->my_index + EPOLL_MAP_SHIFT;

            /*
             * Let's tell to `epoll` to monitor this client file descriptor.
             */
            my_epoll_add(state->epoll_fd, client_fd, EPOLLIN | EPOLLPRI);

            printf("Client %s:%u has been accepted!\n", src_ip, src_port);
            return 0;
        }
    }
    printf("Sorry, can't accept more client at the moment, slot is full\n");

out_close:
    close(client_fd);
    return 0;
}

static void handle_client_event(int client_fd, uint32_t revents,
                                struct tcp_state *state)
{
    int err;
    ssize_t recv_ret;
    char buffer[1024];
    const uint32_t err_mask = EPOLLERR | EPOLLHUP;
    /*
     * Read the mapped value to get client index.
     */
    uint32_t index = state->client_map[client_fd] - EPOLL_MAP_SHIFT;
    struct client_slot *client = &state->clients[index];

    if (revents & err_mask)
        goto close_conn;

    recv_ret = recv(client_fd, buffer, sizeof(buffer), 0);
    if (recv_ret == 0)
        goto close_conn;

    if (recv_ret < 0) {
        err = errno;
        if (err == EAGAIN)
            return;

        /* Error */
        printf("recv(): " PRERF, PREAR(err));
        goto close_conn;
    }

    /*
     * Safe printing
     */
    buffer[recv_ret] = '\0';
    if (buffer[recv_ret - 1] == '\n') {
        buffer[recv_ret - 1] = '\0';
    }

    printf("Client %s:%u sends: \"%s\"\n", client->src_ip, client->src_port,
           buffer);
    return;

close_conn:
    printf("Client %s:%u has closed its connection\n", client->src_ip,
           client->src_port);
    my_epoll_delete(state->epoll_fd, client_fd);
    close(client_fd);
    client->is_used = false;
    return;
}

static int event_loop(struct tcp_state *state)
{
    int err;
    int ret = 0;
    int timeout = 3000; /* in milliseconds */
    int maxevents = 32;
    int epoll_ret;
    int epoll_fd = state->epoll_fd;
    struct epoll_event events[32];

    printf("Entering event loop...\n");

    while (!state->stop) {

        /*
         * I sleep on `epoll_wait` and the kernel will wake me up
         * when event comes to my monitored file descriptors, or
         * when the timeout reached.
         */
        epoll_ret = epoll_wait(epoll_fd, events, maxevents, timeout);

        if (epoll_ret == 0) {
            /*
             *`epoll_wait` reached its timeout
             */
            printf("I don't see any event within %d milliseconds\n", timeout);
            continue;
        }

        if (epoll_ret == -1) {
            err = errno;
            if (err == EINTR) {
                printf("Something interrupted me!\n");
                continue;
            }

            /* Error */
            ret = -1;
            printf("epoll_wait(): " PRERF, PREAR(err));
            break;
        }

        for (int i = 0; i < epoll_ret; i++) {
            int fd = events[i].data.fd;

            if (fd == state->tcp_fd) {
                /*
                 * A new client is connecting to us...
                 */
                if (accept_new_client(fd, state) < 0) {
                    ret = -1;
                    goto out;
                }
                continue;
            }

            /*
             * We have event(s) from client, let's call `recv()` to read it.
             */
            handle_client_event(fd, events[i].events, state);
        }
    }

out:
    return ret;
}

static int init_epoll(struct tcp_state *state)
{
    int err;
    int epoll_fd;

    printf("Initializing epoll_fd...\n");

    /* The epoll_create argument is ignored on modern Linux */
    epoll_fd = epoll_create(255);
    if (epoll_fd < 0) {
        err = errno;
        printf("epoll_create(): " PRERF, PREAR(err));
        return -1;
    }

    state->epoll_fd = epoll_fd;
    return 0;
}

static int init_socket(struct tcp_state *state)
{
    int ret;
    int err;
    int tcp_fd = -1;
    struct sockaddr_in addr;
    socklen_t addr_len = sizeof(addr);
    const char *bind_addr = "0.0.0.0";
    uint16_t bind_port = 1234;

    printf("Creating TCP socket...\n");
    tcp_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
    if (tcp_fd < 0) {
        err = errno;
        printf("socket(): " PRERF, PREAR(err));
        return -1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(bind_port);
    addr.sin_addr.s_addr = inet_addr(bind_addr);

    ret = bind(tcp_fd, (struct sockaddr *)&addr, addr_len);
    if (ret < 0) {
        ret = -1;
        err = errno;
        printf("bind(): " PRERF, PREAR(err));
        goto out;
    }

    ret = listen(tcp_fd, 10);
    if (ret < 0) {
        ret = -1;
        err = errno;
        printf("listen(): " PRERF, PREAR(err));
        goto out;
    }

    /*
     * Add `tcp_fd` to epoll monitoring.
     *
     * If epoll returned tcp_fd in `events` then a client is
     * trying to connect to us.
     */
    ret = my_epoll_add(state->epoll_fd, tcp_fd, EPOLLIN | EPOLLPRI);
    if (ret < 0) {
        ret = -1;
        goto out;
    }

    printf("Listening on %s:%u...\n", bind_addr, bind_port);
    state->tcp_fd = tcp_fd;
    return 0;
out:
    close(tcp_fd);
    return ret;
}

static void init_state(struct tcp_state *state)
{
    const size_t client_slot_num = sizeof(state->clients) / sizeof(*state->clients);
    const uint16_t client_map_num = sizeof(state->client_map) / sizeof(*state->client_map);

    for (size_t i = 0; i < client_slot_num; i++) {
        state->clients[i].is_used = false;
        state->clients[i].client_fd = -1;
    }

    for (uint16_t i = 0; i < client_map_num; i++) {
        state->client_map[i] = EPOLL_MAP_TO_NOP;
    }
}

int main(void)
{
    int ret;
    struct tcp_state state;

    init_state(&state);

    ret = init_epoll(&state);
    if (ret != 0)
        goto out;

    ret = init_socket(&state);
    if (ret != 0)
        goto out;

    state.stop = false;

    ret = event_loop(&state);

out:
    /*
     * You should write a cleaner here.
     *
     * Close all client file descriptors and release
     * some resources you may have.
     *
     * You may also want to set interrupt handler
     * before the event_loop.
     *
     * For example, if you get SIGINT or SIGTERM
     * set `state->stop` to true, so that it exits
     * gracefully.
     */
    return ret;
}

test.php (PHP script to simulate client)
I am too lazy to write a client TCP socket in C. So I use PHP.
<?php

function main(): int
{
    $sock = socket_create(AF_INET, SOCK_STREAM, 0);
    $conn = socket_connect($sock, "127.0.0.1", 1234);
    if (!$conn)
        return 1;
    socket_write($sock, "AAAAAAAA\n", 9);
    sleep(1);
    socket_write($sock, "BBBBBBBB\n", 9);
    sleep(1);
    socket_write($sock, "CCCCCCCC\n", 9);
    sleep(1);
    socket_close($sock);
    return 0;
}

exit(main());

Compile and run the server
ammarfaizi2@integral:~/ex$ gcc -Wall -Wextra -ggdb3 server.c -o server
ammarfaizi2@integral:~/ex$ ./server
Initializing epoll_fd...
Creating TCP socket...
Listening on 0.0.0.0:1234...
Entering event loop...

Simulate multiple clients with test.php
ammarfaizi2@integral:~$ for i in {1..10}; do php test.php & done;
[1] 14214
[2] 14215
[3] 14216
[4] 14217
[5] 14218
[6] 14219
[7] 14220
[8] 14221
[9] 14222
[10] 14223
ammarfaizi2@integral:~$

Server output when clients connect
ammarfaizi2@integral:~/ex$ ./server
Initializing epoll_fd...
Creating TCP socket...
Listening on 0.0.0.0:1234...
Entering event loop...
Client 127.0.0.1:60866 has been accepted!
Client 127.0.0.1:60866 sends: "AAAAAAAA"
Client 127.0.0.1:60868 has been accepted!
Client 127.0.0.1:60868 sends: "AAAAAAAA"
Client 127.0.0.1:60870 has been accepted!
Client 127.0.0.1:60872 has been accepted!
Client 127.0.0.1:60870 sends: "AAAAAAAA"
Client 127.0.0.1:60872 sends: "AAAAAAAA"
Client 127.0.0.1:60874 has been accepted!
Client 127.0.0.1:60874 sends: "AAAAAAAA"
Client 127.0.0.1:60876 has been accepted!
Client 127.0.0.1:60878 has been accepted!
Client 127.0.0.1:60878 sends: "AAAAAAAA"
Client 127.0.0.1:60876 sends: "AAAAAAAA"
Client 127.0.0.1:60880 has been accepted!
Client 127.0.0.1:60880 sends: "AAAAAAAA"
Client 127.0.0.1:60882 has been accepted!
Client 127.0.0.1:60882 sends: "AAAAAAAA"
Client 127.0.0.1:60884 has been accepted!
Client 127.0.0.1:60884 sends: "AAAAAAAA"
Client 127.0.0.1:60866 sends: "BBBBBBBB"
Client 127.0.0.1:60868 sends: "BBBBBBBB"
Client 127.0.0.1:60870 sends: "BBBBBBBB"
Client 127.0.0.1:60872 sends: "BBBBBBBB"
Client 127.0.0.1:60874 sends: "BBBBBBBB"
Client 127.0.0.1:60878 sends: "BBBBBBBB"
Client 127.0.0.1:60876 sends: "BBBBBBBB"
Client 127.0.0.1:60880 sends: "BBBBBBBB"
Client 127.0.0.1:60882 sends: "BBBBBBBB"
Client 127.0.0.1:60884 sends: "BBBBBBBB"
Client 127.0.0.1:60866 sends: "CCCCCCCC"
Client 127.0.0.1:60868 sends: "CCCCCCCC"
Client 127.0.0.1:60870 sends: "CCCCCCCC"
Client 127.0.0.1:60872 sends: "CCCCCCCC"
Client 127.0.0.1:60874 sends: "CCCCCCCC"
Client 127.0.0.1:60878 sends: "CCCCCCCC"
Client 127.0.0.1:60876 sends: "CCCCCCCC"
Client 127.0.0.1:60880 sends: "CCCCCCCC"
Client 127.0.0.1:60882 sends: "CCCCCCCC"
Client 127.0.0.1:60884 sends: "CCCCCCCC"
Client 127.0.0.1:60866 has closed its connection
Client 127.0.0.1:60868 has closed its connection
Client 127.0.0.1:60870 has closed its connection
Client 127.0.0.1:60872 has closed its connection
Client 127.0.0.1:60874 has closed its connection
Client 127.0.0.1:60878 has closed its connection
Client 127.0.0.1:60876 has closed its connection
Client 127.0.0.1:60880 has closed its connection
Client 127.0.0.1:60882 has closed its connection
Client 127.0.0.1:60884 has closed its connection

A: Assuming you have already open server socket you can use code below. It is based on man epoll accessible here.
// assume you have opened listen_sock properly
// int listen_sock;
//
int epollfd = epoll_create1(0);
if (epollfd == -1) {
  exit(1);
}

struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = listen_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) {
  exit(2);
}

for (;;) {
  #define MAX_EVENTS 64
  struct epoll_event events[MAX_EVENTS];
  int events_count = epoll_wait(epollfd, events, MAX_EVENTS, -1);
  if (n == -1) {
    exit(3);
  }

  for (int n = 0; n < events_count; ++ n) {
    if (events[n].data.fd == listen_sock) {
      struct sockaddr_un addr;
      socklen_t addrlen;
      int socket = accept(listen_sock, (struct sockaddr *) &addr, &addrlen);
    }
  }
}


text:
Q: How to convert Dart to JavaScript? The Dart app runs fine in Dartium, but I would like to convert it to JS.
C:\dart-sdk\bin\dart2js --out=test.js main.dart generates JS from:
import 'dart:html';

void main() {
  querySelector('#myid').text = 'Wake up, sleepy head!';
}

Then I add it to the :
<!DOCTYPE html>

  <title></title>

hello

But when I run it in Firefox, it doesn't work. It shows only "Hello" on the page. What am I doing wrong?

A: dart2js is usually not the straight-forward way to generated JS from Dart.
Normally you just run pub build in your project directory.
Ensure you have your pubspec.yaml configured properly csp: true (for Chrome apps Using Polymer in a Dart Chrome App, Chrome App CSP violation after Dart/Polymer transform/compile to JavaScript)