Update flag for multiple/single, but max date for one ID only

Question: I have record as given below

RowID
RefId
FId
CId
TDateTime
NoOfRec
LastRecFlag
MainId

1
7532
159
777
2023-02-21 00:00:00.000
NULL
NULL
0

2
7532
159
777
2023-02-21 12:58:49.000
NULL
NULL
55279

3
7532
159
777
2023-02-22 00:00:00.000
NULL
NULL
0

4
7532
159
777
2023-02-22 08:33:43.000
NULL
NULL
55288

5
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55269

6
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55270

7
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55280

8
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55284

Can any one please help to set LastRecFlag as true only when TDateTime is max in whole day but only for one record having max datetime whose Tdatetime is max. There can be multiple records for a day. And the task can be set for future as well. It will set future time as 9:00:00 for all future related records. After This time passes, If I try to make entry. It takes current time. If current time is max then future related record which is having 9:00:00 time then it will work fine. Because max datetime is the record for the day where time is max then future datetime. Here, I can't set it based on max MainId for the day. Because future related entry is done on current date. And when the actual day comes with that future related date. User can also insert data with current datetime. If it is before future datetime then it is latest record. So MainId will be greater. However it is not the last record. Here, Max Tdatetime should be based on RefId. Can anyone please please suggest something for this issue. I'm tired of
thinking about the solution for this.
Expected result:

RowID
RefId
FId
CId
TDateTime
NoOfRec
LastRecFlag
MainId

1
7532
159
777
2023-02-21 00:00:00.000
NULL
NULL
0

2
7532
159
777
2023-02-21 12:58:49.000
2
1
55279

3
7532
159
777
2023-02-22 00:00:00.000
NULL
NULL
0

4
7532
159
777
2023-02-22 08:33:43.000
6
NULL
55288

5
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55269

6
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55270

7
7532
159
777
2023-02-22 09:00:00.000
NULL
NULL
55280

8
7532
159
777
2023-02-22 09:00:00.000
NULL
1
55284

Actual result:

RowID
RefId
FId
CId
TDateTime
NoOfRec
LastRecFlag
MainId

1
7532
9
777
2023-02-21 00:00:00.000
NULL
0
0

2
7532
9
777
2023-02-21 12:58:49.000
2
1
55279

3
7532
9
777
2023-02-22 00:00:00.000
NULL
0
0

4
7532
9
777
2023-02-22 08:33:43.000
6
0
55288

5
7532
9
777
2023-02-22 09:00:00.000
NULL
0
55269

6
7532
9
777
2023-02-22 09:00:00.000
NULL
0
55270

7
7532
9
777
2023-02-22 09:00:00.000
NULL
0
55280

8
7532
9
777
2023-02-22 09:00:00.000
NULL
0
55284

UPDATE f
SET f.NoOfRec = t.NoOfRec,
    f.LastRecFlag = CASE
                        WHEN f.TDateTime = t.MaxTDateTime
                            THEN 1
                            ELSE 0
                    END
FROM #Final AS f
JOIN
    (SELECT COUNT(1) AS NoOfRec, RefId,
            CAST(TDateTime AS Date) AS TDateTime,
            MAX(TDateTime) AS MaxTDateTime,
            MAX(ISNULL(MainId, 0)) AS MainId
     FROM #FinalResult
     GROUP BY RedId, CAST(TDateTime AS Date))t ON f.RefId = t.RefId
                                               AND ISNULL(f.MainId, 0) = t.MainId
                                               AND CAST(f.TDateTime AS Date) = t.TDateTime

Comment: Is the "future" logic thing actually relevant in the question or just an aside? If it's not relevant i suggest to remove it because it's confusing
Answer: Don't quite understand your logic on the future time etc. Anyway you can make use of the window function to get the information you need and tweak the logic to suites your requirement. The query below does gives your expected result for the provided sample data. Verify the logic with your data.
update t
set   NoOfRec = case when t.LastRec = 1
                     then RecCount
                     end,
      LastRecFlag = case when  t.TDateTime = t.MaxDateTime
                         and   convert(time, MaxDateTime) <> '09:00'
                         then 1
                         else 0
                         end
from
(
  select *,
         RecCount    = count(*) over (partition by RefId, convert(date, TDateTime)),
         MaxDateTime = max(TDateTime) over (partition by RefId, convert(date, TDateTime)),
         LastRec     = row_number() over (partition by RefId, convert(date, TDateTime)
                                              order by case when convert(time, TDateTime) = '09:00'
                                                            then convert(date, TDateTime)
                                                            else TDateTime
                                                            end desc,
                                                       MainId desc)
  from   yourtable
) t

Answer: I don't fully understand you future logic, but to get the expected result from your sample data you could use an inner join like this
update f
set    f.NoOfRec = case when f.TDateTime = tt.maxdate then tt.reccount else null end,
       f.LastRecFlag = case when f.RowID = tt.maxrowid then 1 else null end
from   final f
  inner join (
    select convert(date, f2.TDateTime) as TDate,
           count(f2.RowID) as reccount,
           max( case when datepart(hour, f2.TDateTime) <> 9
                      and datepart(minute, f2.TDateTime) <> 0 then f2.TDateTime
                     else null end) as maxdate,
           max(RowID) as maxrowid
    from   final f2
    group by convert(date, f2.TDateTime)
  ) tt on f.TDateTime = tt.maxdate or f.RowID = tt.maxrowid

See this at work in this DBFiddle
Answer: This looks like a simple "Get top 1 from query" select:
-- Data
SELECT  *
INTO #data
FROM    (
    VALUES  (1, 7532, 159, 777, N'2023-02-21 00:00:00.000', NULL, NULL, 0)
    ,   (2, 7532, 159, 777, N'2023-02-21 12:58:49.000', NULL, NULL, 55279)
    ,   (3, 7532, 159, 777, N'2023-02-22 00:00:00.000', NULL, NULL, 0)
    ,   (4, 7532, 159, 777, N'2023-02-22 08:33:43.000', NULL, NULL, 55288)
    ,   (5, 7532, 159, 777, N'2023-02-22 09:00:00.000', NULL, NULL, 55269)
    ,   (6, 7532, 159, 777, N'2023-02-22 09:00:00.000', NULL, NULL, 55270)
    ,   (7, 7532, 159, 777, N'2023-02-22 09:00:00.000', NULL, NULL, 55280)
    ,   (8, 7532, 159, 777, N'2023-02-22 09:00:00.000', NULL, NULL, 55284)
) t (RowID,RefId,FId,CId,TDateTime,NoOfRec,LastRecFlag,MainId)

-- SELECT
SELECT *
,   noofrec = CASE WHEN sortRecCount = 1 THEN NoOfRecNew END
,   LastRecFlag = CASE WHEN sort = 1 THEN 1 END
FROM    (
    SELECT  *
    ,   ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY TDateTime DESC, MainID DESC /*tiebreaker??*/) AS sort
    ,   ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY MainID DESC ) AS sortRecCount
    ,   COUNT(*) OVER(PARTITION BY RefId, CAST(TDateTime AS DATE)) AS NoOfRecNew
    FROM    #data
    ) t

-- Update
UPDATE  t
SET noofrec = CASE WHEN sortRecCount = 1 THEN NoOfRecNew END
,   LastRecFlag = CASE WHEN sort = 1 THEN 1 END
FROM    (
    SELECT  *
    ,   ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY TDateTime DESC, MainID DESC /*tiebreaker??*/) AS sort
    ,   ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY MainID DESC ) AS sortRecCount
    ,   COUNT(*) OVER(PARTITION BY RefId, CAST(TDateTime AS DATE)) AS NoOfRecNew
    FROM    #data
    ) t

ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY TDateTime DESC, MainID DESC /*tiebreaker??*/) gives us the last time per day sorted by MainID as tiebreaker to assign the LastRecFlag.
ROW_NUMBER() OVER(PARTITION BY RefId, CAST(TDateTime AS DATE) ORDER BY MainID DESC ) AS sortRecCount is similar, but here you want to assign the record count to the highest MainID.
The final CASE WHEN ensure that we only set the values where both of the above conditions are = 1, ie, the desired row.
Output:


Percentages not adding up

Question: I have a series of percentages:
132/220 (60%) and 88/220 (40%).
Now when I break them down into subcategories and then recalculate the percentages them come out 5% different.
81/140 (58%) and 59/140 (42%) (percentages ROUNDED).
21/40 (52.5%) and 19/40 (47.5%).
14/20 (70%) and  6/20 (30%).
16/20 (80%) and 4/20 (20%).
then we I do the averages I get:
65.125% and 34.875%
I have no idea what is happening???
Answer: If the samples/subcategories have different sizes, the average of the averages is not the same as the average of all numbers.
You have to make a weighted average: multiply each percentage by the size of the group, add them together and divide by the total size.
Answer: You seem to be suggesting that $\frac{132}{220} = \frac{81}{140} + \frac{21}{40} + \frac{14}{20} + \frac{16}{20}$. This is not true. The simplest example, $\frac{4}{6}$ is not equal to $\frac{3}{5}+\frac{1}{1}=1.6$.
Answer: There might be a typo. Although others have already answered this question adequately.
The type being 19/20 I believe you meant to type 19/40.
Answer: This is "normal." Suppose you have $2$ big exams, each out of $100$, and you get $40\%$ in each. Average: $40\%$.
You also have $2$ little assignments, each out of $25$, and you get a perfect score in each. Average: $100\%$.
The average of the two averages is $70\%$.
However, the total mak out of $250$ was $130$. Average: $52\%$.
Your example is less extreme, but the same phenomenon is involved.
For a correct computation, you should take a weighted average of the averages.
So correct would be $(40\%)\frac{200}{250}+(100\%)\frac{50}{250}$.

Percentages not adding up


Juntar tabela fotos à consulta

Question: Tenho a seguinte consulta que pega os favoritos do utilizador ID=X
$sql="SELECT * FROM user WHERE id IN (SELECT user_2_id FROM favoritos WHERE
user_1_id =$id_user_logado)";

Agora, como eu posso pegar a foto de utilizador dos utilizador que saem dessa consulta? O id da foto é guardado na tabela do utilizador no campo photo_p_id e a informação relativa à foto está na tabela photos como a localização da mesma.
Algo deste gênero:
$sql="SELECT * FROM user WHERE id IN
(SELECT user_2_id FROM favoritos WHERE
user_1_id =$id_user_logado)

LEFT JOIN photos AS p

ON user.photo_p_id=p.id

";

Answer: Resolvi desta forma:
$sql = "SELECT  u.id, u.username, u.genero, u.idade, u.local, u.descricao,    u.status,u.last_login, u.photo_p_id, p.location, f.user_2_id, f.user_1_id

FROM user AS u

LEFT JOIN photos AS p

ON u.photo_p_id=p.id

LEFT JOIN favoritos AS f

ON f.user_2_id=u.id

WHERE f.user_1_id =$id_user_logado

LIMIT 5;
";

Juntar tabela fotos à consulta


Can Mean Square Error cause underfitting?

Question: Mean Square Error (MSE) is used in Regression problems to compute the error in prediction. Large errors have a large influence on the MSE, and small errors have almost negligible influence on the error. So if an observation is giving a large error, there's a possibility that the observation is an outlier. And MSE will work really hard to minimize that error. So, does minimize MSE cause Underfitting?
Comment: I think it's rather overfitting to the noise in the training dataset that it should not have
Answer: By itself, no. The choice of loss function depends on your data and the nature of the problem you are trying to solve. As you noticed, mean square error is sensitive to large errors, while something like mean absolute error is less sensitive. Such sensitiveness is sometimes a desirable property, while in other cases you need a robust loss function that is insensitive. You use squared error when you need it to be sensitive.
No matter what loss you choose, overfitting is about the whole model, not only the loss. For example, if you use a simple regression model that minimizes the squared error, it has no chance to overfit, because it is not expressive enough. On another hand, if you use instead something like $k$NN no matter of the loss, it could overfit. Basically, if the model can drag the training error to zero (e.g. model with enough parameters to memoize the data), it eventually will, no matter what the loss is.
Comment: Thank you. I got the same issue with my model as I used `MSE`. I tried adding dropout layers and batch normalization, but it does not work. Any recommendations please? I am using by the way LSTM autoencoder.


How to pass C# dictionary into typescript Map

Question: How can I pass correctly C# dictionary into typescript Map.
[HttpGet("reportsUsage")]
    public IActionResult GetReportsUsage()
    {
        //var reportsUsage = _statService.GetReportsUsage();

        IDictionary<int, int> test = new Dictionary<int, int>();

        test.Add(1, 20);
        test.Add(2, 30);
        test.Add(3, 40);
        test.Add(4, 50);
        test.Add(5, 70);
        test.Add(6, 60);
        test.Add(7, 90);
        test.Add(8, 30);

        return Ok(test);
        //return Ok(reportsUsage );
    }

In angular:
getReportsUsage() {
return this.http.get<Map<number, number>>(`${environment.apiUrl}/stats/reportsUsage`, {
  headers: new HttpHeaders({
    'Content-Type': 'text/plain',
    'Accept': 'application/json'
  }),
  withCredentials: true
});
}

reportsUsage = new Map<number, number>();

this.statsService.getReportsUsage().subscribe(data => {
    this.reportsUsage = data;

    //1
    console.log(this.reportsUsage);
    //2
    console.log(this.reportsUsage.values());
    //3
    console.log(typeof(this.reportsUsage));
};

Results:
1

{1: 20, 2: 30, 3: 40, 4: 50, 5: 70, 6: 60, 7: 90, 8: 30}

2

ERROR TypeError: this.reportsUsage.values is not a function

3

object

So the data type change from Dictionary into object, I have tried to convert it with the below but still not working:
console.log(new Map(this.reportsUsage));

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
Answer: I don't know that C# is very relevant here, other than the fact that what comes over the wire is a JSON object like this:
const data: Record<number, number> =
  { 1: 20, 2: 30, 3: 40, 4: 50, 5: 70, 6: 60, 7: 90, 8: 30 };

This is not already a JavaScript Map, but a plain JSON object.  So the right type to use is probably Record<number, number> where I'm using the Record utility type to say "an object with numeric keys and numeric values".
So when you call your http.get you should specify Record<number, number> instead of Map<number, number>:
this.http.get<Record<number, number>>(...)

If you want to convert that into a Map, you need to call the Map constructor with an appropriately iterable argument (such as an array) of key-value tuples.  And since JSON objects always have string keys and not actual numbers, you need to convert to numbers yourself if you want the resulting map to be Map<number, number> instead of Map<string, number>:
const map = new Map(Object.entries(data).map(([k, v]) => [+k, v]));
// const map: Map<number, number>

This is using Object.entries() to convert the JavaScript object into an array of such entry tuples, and we are mapping these entries so that the keys are numbers.
Let's make sure it works:
console.log(map.get(3)?.toFixed(2)) // "40.00"

Looks good.
Playground link to code
Answer: 1- if you want to create a map out of reportsUsage:
const map = new Map(Object.entries(this.reportsUsage));
console.log(map.get("1")); // prints 20

2- if you want an array with the values only:
const arrayOfValues = Object.values(this.reportsUsage)


Newsletter com refresh ajax

Question: Estou tentando fazer o envio desse formulário por ajax e não estou conseguindo, tem algo de errado? Estou batendo a cabeça nisso amais de 4 horas sem sucesso.
Obs: estou desenvolvendo via wordpress e estou utilizando um plugin chamado Newsletter para armazenar os emails capitados pelo formulario. Já consegui fazer funcionar uma vez, mas em outra estancia e em outro site, mas acabei perdendo o código que funciona e estou tentando novamente fazer funcionar.
        var fmr = $('#formsnewslatetr');
        var dados = $('#formsnewslatetr').serialize();
        fmr.submit(function (e){
             e.preventDefault();

             $.ajax(
           {
               type: fmr.attr('method'),
               url: fmr.attr('action'),
               data: dados,
               success: function ( response )
               {
                   $('.success-box').fadeIn();
                   var retorno = 'true';
                   fmr.fadeOut();

                },
               error: function ( txt )
               {
                   alert( "ERRO" );
               }
           }
       );
});

<form id="formsnewslatetr" method="post" action="/?na=s" onsubmit="return newsletter_check(this)" class="form-inline w-100">

          <input class="i-email" type="email" name="ne" id="email" placeholder="Email" required="">
          <input class="b-email" type="submit" value="Assinar">

</form>

Answer: O formulário está sendo submetido via botão submit passando pela função newsletter_check(this) que espera um return. Neste caso, se torna desnecessário o fmr.submit (até porque se ele estivesse na memória -- não está na memória porque parece estar dentro de uma função que ainda não foi executada --, o formulário seria enviado 2x: uma pelo botão submit e outra pelo frm.submit).
Neste caso é necessário ainda colocar um return false; no final da função para evitar que a página seja redirecionada.
Em vista disso, seu código deveria ter esta estrutura:
function newsletter_check(formulario){ // o parâmetro "formulário" apenas como exemplo
   var fmr = $('#formsnewslatetr');
   var dados = $('#formsnewslatetr').serialize();
   $.ajax({
      type: fmr.attr('method'),
      url: fmr.attr('action'),
      data: dados,
      success: function(response){
         $('.success-box').fadeIn();
         var retorno = 'true';
         fmr.fadeOut();
      },
      error: function(txt){
         alert( "ERRO" );
      }
   });
   return false;
}

Se quiser fazer algum tipo de validação do e-mail, basta colocar essa validação no início da função e se não for validado, adicionar return false; para que a função não entre no Ajax.

Newsletter com refresh ajax


$L = \{a^m b^n c^k \mid \text{ if $(n=k)$ then $(m=n)$}\}$ CFL or CSL?

Question: Whether the given Language is CFL or CSL?
$L = \{a^m b^n c^k \mid \text{ if $(n=k)$ then $(m=n)$}\}$
I am getting as CSL. Professor teaching this course has provided explanation on basis of Propositional logic, stating if...then is equivalent to $((n≠k) \text{ or }m=n))$, on this ground, he claims to be CFL.
What I have understood is that we will take 2 cases
Case 1: Check $n=k$, if yes then it will verify $m=n$, that will make Language $L$ as $a^n b^n c^n$ which will be CSL.
Case 2: If n≠k, then there is no restrictions on any parameters, it can be CFL. It can be accepted by empty stack or by final state.
Take Union of both cases, so the resulting language will be CSL (as CSL and CFL is closed under Union)
If you can provided state transition diagram for this language, that would be helpful.
Correct me if I am wrong or misinterpreted some property of CFL?
Answer: Following the explanation of your professor, one has
\begin{align}
L &= \{a^m b^n c^k \mid \text{if $(n=k)$ then $(m=n)$}\} \\
&= \{a^m b^n c^k \mid \text{$(n \not= k)$ or $(m=n)$}\} \\
&= \{a^m b^n c^k \mid m \geqslant 0 \text{ and } n \not= k\} \cup \{a^m b^n c^k \mid m=n \text{ and } k \geqslant 0\} \\
&= a^*  \{b^n c^k \mid n \not= k\} \cup \{a^m b^n \mid m=n \}c^*
\end{align}
Now, the languages $\{b^n c^k \mid n \not= k\}$ and $\{a^m b^n \mid m=n \}$ are context-free. Furthermore, the product of a regular language and a context-free language is context-free and the union of two context-free languages is context-free. It follows that $L$ is context free.


How to save bool value using shared preferences

Question: So I created a categories section in my app where you can select multiple categories by clicking on the container. The container you select changes colour. What I want to do is save the choices selected using shared preferences and display it again whenever user wants to see his selected categories.
return GestureDetector(
  onTap: () {
    setState(() {
      if (isSelected == false) {
        isSelected = !isSelected;
        color = widget.color;
        print('Coming here');
      } else {
        isSelected = false;
        color = Colors.white;
      }
      prefs.setBool(_key, isSelected);
    });
  },
  child: AnimatedContainer(
    padding: EdgeInsets.all(widget.padding),
    decoration: BoxDecoration(
      color: color,
      shape: BoxShape.circle,
    ),
    duration: Duration(milliseconds: 500),
    child: Container(
      child: Text(
        widget.labelText,
        style: TextStyle(
            color: kLightBlue,
            fontFamily: 'clanproBold',
            fontSize: SizeConfig.blockSizeHorizontal * 3),
      ),
    ),
  ),
);

This is the code to create multiple containers.
How can I save the options?
Comment: Welcome to Stack Overflow, thank you for your question! Is there any chance that you might be able to update your code sample to show your entire widget, so that we can better help you?
Answer: First of all, you have to add the dependency of shared preferences at your pubspec.yaml file as follows:
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

After that you have to import to your class the package:
import 'package:shared_preferences/shared_preferences.dart';

Then at the state, you want to save the options add the following code:
_saveOptions() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setBool('option', true);
}

You can read the data you saved at SharedPreferences using the following code:
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool boolValue = prefs.getBool('option');

Important: You can only save int, String, double or bool variables using SharedPreferences.
So if you want to save the options the user gives, you can use only the types above.
You can make it work by passing the values of the options as String or int to SharedPrefrences and convert them back again.
Example:
Color color = new Color(0x#BD452C);
int colorValue = color.value;
String colorString = color.toString();
Color newColor = new Color(colorValue);

Answer: Just check this example I have created an example that will tell you how to save the shared preferences value and then retrieve it
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Users'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isSelected = false;
  String stringValue = "No value";

  @override
  void initState() {
    super.initState();
    getAllSavedData();
    // You can use the initState where you can get all the saved categories and the assign it based on it.

  }

  getAllSavedData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    bool value = prefs.getBool("youKey");

    // For first time you get null data so no value
    // is assigned so it will not assign anything
    if (value != null) stringValue = value.toString();

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            GestureDetector(
              onTap: () async {
                if (isSelected == false) {
                  isSelected = !isSelected;
                  //color = Colors.pink;
                  print('Coming here');
                } else {
                  isSelected = false;
                  // color = Colors.white;
                }

                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.setBool("youKey", isSelected);

                // This is where you save the data and then when the user second time opens  he will get the stoared data
                setState(() {});
              },
              child: AnimatedContainer(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.red,
                  shape: BoxShape.circle,
                ),
                duration: Duration(milliseconds: 500),
                child: Container(
                  child: Text(
                    'S',
                    style: TextStyle(
                        color: Colors.blue,
                        fontFamily: 'clanproBold',
                        fontSize: 20),
                  ),
                ),
              ),
            ),
            // This is when you open the screen for second time you get the value as true
            Text('This is the value you saved $stringValue'),
          ],
        ),
      ),
    );
  }
}

Let me know if it works.
Comment: I tried. It isn't working. setBool is only saving value as true, even if nothing is selected.
Comment: Use value instead of directly using true

_saveOptions(bool value) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setBool('option', value);
}


Open Airplay popover in my custom button

Question: I'm wondering is it possible to create a custom airplay button and add it to a toolbar? i.e. I would like to create button that open the same popover that original AirPlay button, to share all the screen.
I saw that it is possible to do with MPMoviePlayerController or WebView, but in that way I send on air a video or audio, but non all the screen...
Thans
Answer: In iOS 5 there were some hoops to jump through. In iOS 6, it's much easier. Add a MPVolumeView and use setRouteButtonImage:forState: to change the icon:
airplayView = [[MPVolumeView alloc] initWithFrame:airplayContainer.bounds];
airplayView.showsVolumeSlider = NO;
[airplayView setRouteButtonImage:[UIImage imageNamed:@"airplay"] forState:UIControlStateNormal];
[airplayView setRouteButtonImage:[UIImage imageNamed:@"airplay-highlighted"] forState:UIControlStateHighlighted];
[airplayView setRouteButtonImage:[UIImage imageNamed:@"airplay-selected"] forState:UIControlStateSelected];
[airplayContainer addSubview:airplayView]; // or add it to your toolbar or wherever

airplayContainer is just a plain UIView I added in Interface Builder to get the layout I wanted.


CSS padding distance?

Question: Free Code Camp defines padding as the distance between the elements of a container and its borders.
In this example (https://www.freecodecamp.org/learn/responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element

.injected-text {
  margin-bottom: -25px;
  text-align: center;
}

.box {
  border-style: solid;
  border-color: black;
  border-width: 5px;
  text-align: center;
}

.yellow-box {
  background-color: yellow;
  padding: 10px;
}

.red-box {
  background-color: crimson;
  color: #fff;
  padding-top: 40px;
  padding-right: 20px;
  padding-bottom: 20px;
  padding-left: 40px;
}

.blue-box {
  background-color: blue;
  color: #fff;
}

margin

padding

padding

The padding of the element (the word in white "padding") seems to be correct on all of values (top, down, left) except for the right direction; the (padding-right) is supposedly 20px which is equal to the (padding-bottom) but there is a huge difference between the 2 distances.
What am I missing?
Comment: Add `display:inline-block;` - by default `h5` is a block element, which makes it full width.
Comment: The text is centred, so the example is rather misleading. If you inspect the element in the dev console (and hover the element), you should be able to see padding more effectively.
Comment: Start using your developer tools. See this image: https://i.stack.imgur.com/3lbic.jpg you can hover the box at bottom-right corner in developer tools and then you can see the different areas. (What you didn't see is the width of the box is changed depending on screen width. The padding remains to 20px!)
Comment: Welcome to Stack Overflow! The padding for bottom and right are exactly the same. There isn't a huge difference at all. What are you seeing?
Comment: Because padding-right and padding-left should have the same value "40px". But once  padding-left is 40, it's pushing the text to the other side.
Comment: @Mari the padding shouldn't be the same. This is an exercise on Free Code camp. The values are correct. What the OP is seeing is the text centered within the container.
Comment: @DBS it seems like it + I have finished the curriculum and it never mentioned this "display: inline; " property, thank you everyone anyway, it seems I will have to find another source that covers the positioning more extensively, any suggestions would be appreciated.
Answer: I believe that the h5 cascades to a display: block which causes the element to span the available distance (minus padding of course). Try adding :
display: unset

to the .red-box class and see if it looks like more like you were expecting.
Answer: The padding is correct, but you can't see the padding left and right because the text-align is centred.
Add the following and you will see the correct padding to the left in the green box, and the correct padding to the right in the orange box.
...
 .green-box {
    background-color: lime;
    padding-left: 20px;
    text-align: left;
  }
  .orange-box {
     background-color: orange;
     padding-right: 20px;
     text-align: right;
  }
 </style>

margin

padding

padding

padding

padding

Answer: I have a complete Github repo with all answers to FreeCodeCamp!
https://github.com/Laaouatni/FreeCodeCamp-Responsive-Web-Design

use this if you need some help, the code there is 100% working because I do it also :)

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>document</title>

margin

padding

padding

CSS padding distance?


Which DNS settings are used when setting up your server

Question: I have a server and want to run my own name server service. Now I have set it up already and it works not, but I do not know where the exact settings are stored.
On my server I use Plesk. When I edit DNS settings there I think it is stored in named.conf. Named is installed on the server, and BIND.
Now I also have a panel from my registrar. This is separate from my server.
Both places I can add the normal MX,A,CNAME, etc records.
Now where is the best way to place this settings. Currently I have the same records on both places, on the server and at the registrar panel.
I am correct to just add all the records at the registrar panel, and remove everything from within PLESK, and just don't run DNS on my server, because it is already done in the registrar panel.
Or should I add the records in both places.
Comment: Any chance of OS details? Windows? Linux? BSD?
Comment: I am on CentOS 5.4
Answer: named.conf is the BIND configuration file, you will have .hosts and .rev files for your
forward and reverse look up settings respectively in your
If your registrar is also your DNS service provider, then you do not need DNS entries in both places.
Comment: Ok thank you I will check and remove the entries from my server. I hope it does not break.
Answer: To move DNS you will need to access your registrar's cpanel and give your domain new authoritative namesevers (the DNS on your LAN). You should have a backup DNS someplace too.
On your network you will need to configure your zonefile (you can google for help on writing a proper zonefile) and then make sure to open up the proper ports on your firewall to allow DNS traffic from those on the outside who want to query (TCP/UDP 53).
Are you sure you want to do this? If you just want to run a caching DNS server, you can leave your domain DNS with whatever your are using now (assuming your registrar) and just run one locally for LAN requests.
Comment: No I do not need to move anything. Everything is set up correctly. But now I have everything configured in bot my registrars panel and in the zone-file. But I was thinking of removing the zone-file entries.


Solve $dy/dx = (x+y+1)/(3x+3y-1)$

Question: How do I solve the following ODE:
$$\frac{dy}{dx} = \frac{x+y+1}{3x+3y-1}$$?
It's not separable, linear or exact. The substitution $z=x+y$ was proposed but when I use that the y term is present both independently and in $\ln(y)$ and I cannot solve for it. Could you please give me some guidelines?
Comment: I don't think you can really solve it, other than with lambert w function. Just leave it in implicit form.
Answer: with $z=x+y$ we get $$z'=1+y'$$ and our equation is
$$z'-1=\frac{z+1}{3z-1}$$ can you finish?
Comment: I used this method when first solving the ODE, but got as far as
(3/4)y-ln(x+y)=(1/4)x+constant
and I'm not sure how to solve for y since it's both independent and in ln form
Answer: For solving a differential equation of this form, consider the lines $x+y+1=0$ and $3x+3y-1=0$ corresponding to the numerator and denominator in:
$$\frac{\mbox{d}y}{\mbox{d}x} = \frac{x+y+1}{3x+3y-1}= \frac{x+y+1}{3\left( x+y\right)-1}$$
In your case, these lines are parallel and you substitute $u=x+y \implies u'=1+y'$ to get a separable differential equation in $u(x)$:
$$\frac{\mbox{d}u}{\mbox{d}x}-1 = \frac{u+1}{3u-1}$$

For completeness: if the lines were non-parallel and their point of intersection has coordinates $(x_0,y_0)$, then the substitution:
$$\left\{ \begin{array}{l}
x = t + x_0 \\
y = u +y_0
\end{array}\right.$$
will turn the differential equation into a homogeneous one.

Solve $dy/dx = (x+y+1)/(3x+3y-1)$


To search from the api and print the data separately in a table

Question:

const [userID, setUserId] = useState("");
let userid = ""
axios
.get('url').then((process) => {
       const proces = process.data;

       proces.map((item) =\> {

           if (item.fulname === fulname) {

               userID += (\`${item.id}\\n\\n\`)

               setUserId(userid)})

           \

               {userID}

           \

How to print, whatever I did, it doesn't work, please guide me
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: I'm considering your userid is in data only one time.
There are a lot of syntax errors in this code. JavaScript is case sensitive so write code carefully or you can use Syntax autocomplete extensions to avoid these mistakes.
var userid = ""
axios.get('url').then((process) => {
    const proces = process.data;
    proces.map((item) => {
       if (item.fulname === fulname) {
           userid += (`${item.id}\\n\\n`);
           setUserId(userid);
       })
    })
})

return(
{userID}
)


CKeditor does not show icons properly

Question:
The exact problem is that the editor doesn't show all the Toolbar icons. also, these that it does show, are black and white icons. something works wrong there...
Tried to change fields - didn't help. tried to go through all the options and re-save them, didn't help either. ideas?
Thanks.
Answer: I am assuming you recently updated ckeditor. The new version uses a black and white skin. There is also a know issue with updates and is noted in the issue queue. You need to go a resave all of your ckeditor profiles and flush drupal's cache, as well as your browser's cache.
Comment: Hey Nigel. didn't understand: "esave all of your ckeditor profiles". what do you mean?, and what will flusing the caches do? flush all Druapl caches didn't seem to help.
Comment: See https://drupal.org/node/1882396
Answer: Not sure, this might be the problem/solution.  What has happened is you have installed the CK editor library as part of the drupal 7 WYSIWYG module/project. This only allows you to see this black and white editor.
http://johnathanthwaites.info/sites/default/files/toolbar.png
if you want the full editor including colour text, spell check and insert flash object etc etc. then you actually need to install CK editor as a module not as a library for wysiwyg. Then you get this one;
(Url above but image is toolbar2.png)
Ive done a full explanation here;
http://johnathanthwaites.info/Ckeditor
Comment: Please copy the important pieces from the linked article and include in your answer. Just in case the site is unavailable for any reason.

CKeditor does not show icons properly


Is it possible to add html/js to pages cached by varnish?

Question: I have a lot of websites and want to get analytics from Google about all pages served by the cache.
Is it possible to add javascript or html to the bottom of each page served by the cache?
For example swap  with
Answer: You can use mod_ext_filter from apache:
ExtFilterDefine fixtext mode=output intype=text/html cmd="/bin/sed s//<analytics code>/"

<Location />
    # core directive to cause the fixtext filter to
    # be run on output
   SetOutputFilter fixtext
</Location>

For varnish you have ESI. See: Edge Side Includes for more details.
Comment: I tried this apache filter, it resulted in garbage being displayed on the page.  The Edge Side Includes requires changes to the html which we are trying to avoid because there are thousands of sites.
Answer: The short answer is that you can't. Varnish only allows you to edit outbound Headers, not the content of the outbound response. It does allow you to add C code to the vcl file, so you might be able to hack something together, but it's not designed for it.
Otherwise, I would recommend Mircea's options; either using ESI, or modifying apache or whichever webserver you're using to inject the code.
Just in case, as your question didn't make it clear, you don't need to get Varnish to add the Analytics monitoring code in order for the sites to be monitored, only that that code is on the page. The analytics code all works client-side, making calls directly from the visitor's browser.
Make sure to configure varnish to disregard the analytics cookies - your backend webserver doesn't need them, and leaving them will kill your hit rate :)
Answer: I've written a VMOD to modify response body in varnish before sending it to client. Use it at your own risk https://github.com/aivarsk/libvmod-rewrite


How i add uniformly distributed noisy attributes to data set?

Question: I want to add some artificial outliers to my data set by follow same method below.
so, how i can add contaminated data statistically to real data set like Pima Indians Diabetes?
info:
Pima Indians Diabetes:  768 instances    8  attributes
enter link description here
Note:                                                                           I want steps not programming code.

We have added uniformly distributed attributes as noisy attributes to data
  sets [15]. To compare outlier detection and false alarm rate in our experiments we have planted 3% to 5% artificial outliers into real data sets according to the data sets domain knowledge (statistical characteristics like mean, standard
  deviation, class distribution, type of attributes).
  Blockquote

enter link description here
Comment: Hello.  Is this a statistics question (which would fit on this site) or a question about how to complete this task using certain software (which wouldn't fit)?
Comment: statistics question, i want steps to do statistically.ex: calculate mean or std
Comment: You may have a different impression, but really there is no universally accepted definition of "outlier."  Even the article you cite on outlier detection doesn't give much of a definition (based on a quick look); it talks about the need for outliers to meet certain criteria, and rather than specifying these it merely refers to another article ("13").  So it's not as if one could straightforwardly advise you create artificial values that are, e.g., >3.44 standard deviations from each variable's mean.  You'll need to come up with your own criteria.  Cheers ~
Comment: https://stats.stackexchange.com/questions/7155/rigorous-definition-of-an-outlier
Comment: Thanks ,  how can  i create attributes that is 3.3 standard deviations from each variable's mean?   Take random sample from data set then add mean of data set+3.44 standard deviations of data set .
Answer: One way would be to train a model that learns the distribution of each feature separately; it could be a KDE for each feature.
Then you could use this model to generate outliers for the data. I'd suggest producing the outliers by generating values at 4 std from the mean for a few of the features and generate realistic values for the rest. This will prevent the outliers to be too easily detectable.
Comment: Thanks.why this will prevent the outliers to be too easily detectable? .
If i calculate each feature mean and std separately ,then take random features and add mean and 4 std?
Comment: I think that the point should not be an outlier on all features. It's realistic if it is an outlier on one or two features alone. Yes that's what I'd do.
Comment: can do same rule for non normal distributed data?
Comment: I think that the point should not be an outlier on all features? can explain more please .you mean if i have point with 4 features ,for example add outlier for 2 of them better than all 4 features?


Problems moving to production site

Question: I have developed a D7 website locally (WAMP), now I want to move it to a production server.
The production server has a SVN repository, so when I want to move my local files to the server I do a commit of all the changed files.
To sync the databases I get a dump of the local DB and I import it in the DB on the server.
First of all, is this a proper way to move my site to production or is there a better workflow?
The problems I encounter are these:

When I enable caching and aggregation on my local site and then sync the two databases, when I go to the production site it's like all my stylesheets are gone. There's no css styles applied whatsoever.
When I disable caching and aggregation and sync the databases, the styles are back but it's like it's the design of a month ago. The design of the local site doesn't resemble the design of the production site. When I look at the page source, I see the CSS files getting called as: pages.css?mmtwln. What does this ?mmtwln mean?
I can't login to the admin pages on the production site. When I enter my username and password nothing happens but the page getting refreshed. No error message, no red border around the textboxes. The rewrite module is enabled on the production site. I also set the $base_url and $cookie_domain in the settings.php (I have a multisite configuration, should $base_url and $cookie_domain go in sites/default/settings.php or sites/mysite/settings.php?).

If anyone can help me with any of these questions, or point me in the right direction I'll be forever grateful.
Answer:
Exclude /sites/*/files/css and /sites/*/files/js from repository. It's just a cache so it should never be committed or migrated.
Before each migration purge /sites/*/files/css and /sites/*/files/js. That way you will get rid of months old cache. After each migration, make sure these directories are writeable. mmtwln seems to be a string added by Drupal or some module to prevent proxy caching, or it may be a string added by a proxy itself. it shouldn't affect static files at all (except cache prevention, but even that isn't sure)
Your site fails at saving cookies. Check your cookie domain settings in sites/mysite/settings.php and make sure you have right data in example.org/admin/config/system/site-information

If above is insufficient:

manually (via ssh/sftp/ftp) compare offending CSS files. Does the version downloaded from server look the same as version you was sure you uploaded? If not, consult your sysadmin as your server is malfunctioning somehow.
if the version you download from server via ssh is the same you uploaded, but differs from the one you downloaded via http, check carefully your .htaccess - probably there are some redirection rules that make your server to serve file from different location. Common offender is boost module, if you used to have it installed and now only it's rewrites are left, you can easily get the exact behaviour you described.
Comment: Thanks for your response, they're some great pointers. I tried the first two though, but to no avail. I still get the "old" design.
Comment: Expanded my answer, added 2 more points.
Comment: Apparently the files that are in my repository don't match with the files on the webserver. Don't know why yet, but that's the reason I get the old design. Thanks for your help!

Problems moving to production site


jQuery sum values (text) of all lis to the parent ones

Question: I have tried to find an answer a few hours long but all i found did not solve my problem
I have a bunch of nested unordered lists where in the last level there are values in a span

            0

                    0

                            1

                            2

            0

                    0

                            5

                            6

I want to sum this values to the above elements span
My code looks following.
$($("li a span").get().reverse()).each(function()
             {
                 var itemValue = parseInt($(this).text());
                 var parentSpan = $(this).parent().parent().parent().parent().find("a span:first");
                 var parentVal= parseInt(parentSpan.text());
                 parentVal=parentVal + itemValue;
                 parentSpan.text(parentVal.toString());
             });

this results in the following
28  <-- here is the problem ...
    3
        1
        2
11
    11
        5
        6

The first li sums also all the other li in the same level
what i expected was that only the sublevels should sum up to the parent level like in the second part
expected result:
3   <-- this should only count childs not same level elements
    3
        1
        2
11
    11
        5
        6

Any help is highly appreciated
Thanks in advance
Don
Answer: You can try putting below code, Hope this will help you.
var $topUl = $($('ul')[0]);
$.each($topUl.children('li'), function(index, val){
$ulEle = $(val).children('ul');
var sum1 = 0;
$.each($ulEle.children('li'), function(index, val){
    var sum2 = 0;
    $.each($(val).find('ul span'), function(index2, val){
        sum2+=parseInt($(val).text());
    });
    $(val).children('a').find('span').text(sum2);
    sum1+=sum2;
});
$(val).children('a').find('span').text(sum1);
});

Comment: Vikram, you saved my day! thanks a lot - I tried to vote up your anwer but i am sorry - it seems i am not aloowed to do so ..


Get User Rights Assignment values in Local Computer Setting using VBScript and WMI

Question: I'd like to get all the values of User Rights Assignment in Local Computer Setting using VBScript and WMI. Is there a way I can do this with VBScript and WMI?
Thanks.
Comment: It's buried somewhere within the root\rsop\computer WMI namespace, I just know it, but I've been working on this for a couple hours and I have yet to arrive at a silver bullet solution. :(
Answer: Here is an example of how I did in C# .NET based on Jay Adams link and the RSOP_UserPrivilegeRight class documentation, I guess this is easily portable to VBS:
<code>using System.Management;

ManagementScope scope = new ManagementScope(@"\\localhost\root\rsop\computer");
ObjectQuery query = new ObjectQuery("SELECT * FROM RSOP_UserPrivilegeRight");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

scope.Connect();

ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
    Console.WriteLine("=> User right: {0}, precedence: {1}", m["UserRight"], m["precedence"]);

    Action<string> action = new Action<string>(Console.WriteLine);
    Array.ForEach((string[])m["AccountList"], action);
 }
</code>
Answer: Hopefully this is what you're looking for: http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/computermanagement/policy/#EnumPolUserPrivs.htm
Comment: [Are answers that just contain links elsewhere really "good answers"?](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers)
Comment: I think so when the link takes you to information that directly solves the user's question. The code needed no modification and I felt it redundant to copy/paste when we could all take advantage of a "hyperlink".
Comment: You may consider following my comment's link. It will provide you some of the StackExchange community's discussion on this topic.


Expectation of maximum of i.i.d Weibull random variables?

Question: I'm trying to find an asymptotic approximation for the expectation of the maximum of $n$ Weibull random variables $X_i \sim Weibull(\lambda,\beta)$ when $\beta < 1/2$ and $n$ is large. From simulations, I'm getting that
$$E[max(X_1,...,X_n) ]  \approx  A n^{c}$$ for some constant $A$ and constant $c < 1$, but I'm not sure how to prove something like this.
Are there any well-known approximations for the expectation of the maximum of Weibull random variables?
Answer: An exact formula is given by "A note on order statistics from Weibull distribution" by Balakrishnan and Joshi. Define
$$J(p,0) =  \frac{\Gamma\left(\frac{1}{\beta}\right)}{\lambda\beta p^{1/\beta}}$$
with
$$J(p,m) = J(p,m-1) - J(p+1,m-1) $$
Define $\alpha_n$ as the expected value of the $n$th smallest sample. Then the expected value of the smallest sample is
$$\alpha_1 = J(1,0)$$
and for larger samples is
$$ \alpha_r = \alpha_{r-1} + \binom{N-1}{r-1}J(N-r+1,r-1)$$
Comment: Thanks! I also found the following slightly more explicit formula for the expectation of the maximum on a book by Chin-Diew Lai called "Generalized Weibull Distributions"

$$ E[max(X_1,...,X_n)] = n \Gamma(1+1/\beta) \sum_{i=0}^{n-1} \binom{n-1}{i} (-1)^i (\frac{1}{i+1})^{1 + 1/\beta}$$


Em uma matriz Z de elementos (i,j) como atribuir o valor 1 quando i=j? (software R)

Question: Através da seguinte condição:
ifelse(??, 1, Z/(1+1))

O que colocar no lugar de "??" para que o R entenda que quando i=j na matriz Z, quero que se atribua o valor 1?
Comment: Por i=j você quer dizer o índice i = o índice j? Se for, a resposta do Daniel com `diag` é a mais adequada.
Answer: Não vejo uma forma de resolução simples a partir da sua pergunta. Mas proponho duas formas de resolução:
Atribuir o valor desejado à diagonal, de forma direta.
a <- matrix(rep(0,100), nrow = 10)
diag(a) <- 1

Analisar a posição para atribuir o valor.
a <- matrix(rep(0,100), nrow = 10)
for(i in 1:dim(a)[1]){
  for(j in 1:dim(a)[2]){
    if(i == j){
      a[i,j] <- 1
    }
  }
}


Simple Workstation Imaging Solution?

Question: I need a fairly cheap imaging solution for Windows XP corporate desktops. Ideally, I'd be able to  set up a desktop exactly as we want it, create an image, deploy this image to a server, then boot a new desktop to a CD/USB Drive/Network and quickly set up the workstation. Ideally, each computer would also have a unique workstation name. Any ideas? Right now I'm using a custom built Linux DD solution, but it's slow, not network-based, can't image multiple computers at the same time as there's only one copy on a USB drive, and can't uniquely name the computers.
Thanks,
Will
Answer: Use Clonezilla, but then also use DHCP server and Active Directory to handle workstation names using their MAC Addresses. If set up correctly, it will automatically set up the hostname when each server boots up. It might take a bit to index the MAC Addresses and map hostnames to them, but it will help you out in the long run, as when you need to reimage the server, it will automatically get the same hostname again.
Answer: Windows Server 2003 R2 and above have Windows Deployment Services included.  If you already have a Windows server, this may be an inexpensive solution for you.
Answer: CloneZilla can do network deployment, but I'm, not aware that it can change workdstation names.
Answer: The Windows AIK (Google for details) works beautifully for XP deployments, will work from a network, from USB, or from bootable DVD, and will also produce an image that works with Windows Deployment Services, all for a modest outlay of £/$/€/¥ 0.00.  It used to be restricted to certain customers, but in the past few years it has moved to being available to everyone.
The only issue is that the learning curve can be a little steep, but if you're already using a Linux-based solution you should be more than able to tackle this.  Look for the Microsoft Malware Removal Starter Kit for what I believe is probably the best getting started guide.
Answer: Microsoft's free MDT 2010 (Microsoft Deployment Toolkit) lets you do all of this, and even completely automate it if you want.
Answer: I'm not sure imaging is the right way to go; you'll be moving around a lot of redundant data. Have you looked into terminal services? Set everything to boot straight into the terminal, and you can add new machines to your location just by plugging them in and pointing them at the server.
Answer: I have used "Ping" a few times for imaging windows workstations, it's free and is pretty simple to use.
Ping
Answer: Free and Open Ghost has worked very well for me. I would recommend it.
Comment: freeghost.sf.net [link](http://freeghost.sf.net)
Answer: I'm using Partimage and Sysprep and a Linux Live-CD.
Answer: New Reply to a very old post: www.redobackup.org - dead simple bare metal imaging / backup and restore.
Answer: Heaps of imaging options out there,
- G4U
- G4L
- Clonezilla
- Partimage
The cleanest free option though would probably be, http://unattended.sourceforge.net/
As you can see it also has the ability to deal with workstation naming, hotfix, application installation, and even joining to an existing domain/workgroup.
http://unattended.sourceforge.net/step-by-step.php

Simple Workstation Imaging Solution?


Add file permissions with express and node

Question: I have an express API to upload files into a server filesystem with root owner. Is there a way to add the owner and permissions to the file when I upload it, for example: owner: me, access: 644.
My route look like this
router.post('/',

imageUpload.single('file'),

function (req, res) {
    res.set('location', encodeURI(urlJoin(UPLOAD_URL, req.file.filename)))
    res.status(req.file.isCreation ? 201 : 204).send()
}
)

I use multer to store the files
const imageUpload = multer({
storage,
})

Answer: The only way you can change ownership of a file is if you run your script as root (or if you write a SUID root helper program to do that). This is of course if you are talking about the OS access rights. Your backend could serve the file or not based on a cookie, seesion id, a token in some header or anything else in the request. But you won't be able to change the ownership of the file in the file system without root privileges. Consider if that is something that you really need.
If your script runs as root as you wrote in the comments then you can use fs.chown to change the owner and fs.chmod to change permissions.
See:

https://nodejs.org/api/fs.html#fs_fs_chown_path_uid_gid_callback
https://nodejs.org/api/fs.html#fs_fs_fchmod_fd_mode_callback
Comment: indeed the application will be executed by root owner, but I need to associate the files to a different owner once uploaded to filesystem
Comment: @kyserslick If so then you can use fs.chmod and fs.chown - see my updated answer.
Comment: Yes I found that, tkx.


how to write views for our own custom module?

Question: I am new to drupal. I have created one form submission module like this
 <?php
function form_test_permission()
{
return array(
'submit_form_test' =>array(
'title' =>('submit_form_test'),
'description' =>('submit the form_test form'),
),
);
}
function form_test_menu() {
$items=array();
$items['application']=array(
'title' =>'Application Form',
'type' =>MENU_NORMAL_ITEM,
'access arguments' => array('submit_form_test'),
'page callback' =>'drupal_get_form',
'page arguments' => array('form_test_form'),
);
return $items;
}

function form_test_form($form,&$form_state){
$form['firstname'] =array(
'#title' =>t('Firstname'),
'#type' => 'textfield',
);
$form['lastname'] =array(
'#title' =>t('Lastname'),
'#type' => 'textfield',
);
$form['addr']=array(
'#title' =>t('Address'),
'#type' => 'textfield',
);
$form['age']=array(
'#title' =>t('Age'),
'#type' => 'textfield',
);
$form['submit']=array(
'#value' => 'submit',
'#type'=> 'submit',
);
return $form;
}
function form_test_form_submit($form,&$form_state) {
$ft_id=db_insert('form_test')
->fields(array(
'firstname' => $form_state['values']['firstname'],
'lastname' =>$form_state['values']['lastname'],
'addr'=>$form_state['values']['addr'],
'age'=>$form_state['values']['age']
))
->execute();
drupal_set_message(t('Saved.'));
}

if I go like localhost/drupal-example/application.. this module works.. But I want to display this module in front page.I referred a lot. But it doesn't works. Can anyone guide me how to write a view function in this module?
Comment: "display this module in front page" - what do you mean by that? You want to create block to put on frontpage? Or to set module's page as front page? Or what exactly?
Comment: But I wrote this as page..I want to this as page in views..not as block in views
Answer: In order to be able to use a custom module's table with Views, you need to use hook_views_data().
Even better, I would recommend that you invest some time to learn about entities. Entities are much better for most and thay can be almost immediately used in views.
To define a custom view into your module, put it in file module.views_default.inc (replacing with your module name), in a function module_views_default_views().
Comment: can u give example format codes for my module
Comment: I would be glad to, but I do not know your tables and specifics. One more page that could help you with that is https://drupal.org/comment/5687844#comment-5687844
Comment: Afterwards, to add a view in module_views_default_views(), simply create it in Views UI and use the export feature to get the code.


Sorry, you are not allowed to access this page. - wordpress

Question: i am getting this error message "Sorry, you are not allowed to access this page".
when i go to my page http://localhost/wordpressstuff/wp-admin/options-general.php?page=editstuff?id=4 that is when i get the error but when i remove ?id=4 it removes the error i am trying to do a edit mysql table row but for some reason i am getting this in wordpresS
HERE IS MY CODE:
/** Step 2 (from text above). */
add_action( 'admin_menu', 'my_edit_news_menu' );

/** Step 1. */
function my_edit_news_menu() {
    add_options_page( 'My Plugin Options', '', 'manage_options', 'editstuff', 'edit_news' );
}

/** Step 3. */
function edit_news() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'Well You do not have sufficient permissions to access this page. Embarassing is\'nt it' ) );
    }
...

hERE IS THE LINK THAT I CLICK TO GET TO THAT PAGE

<?php echo $row['title']; ?>

Delete

<a href="http://kollossus.com/wp-admin/options-general.php?page=editstuff?id=<?php echo $row['id']; ?>">Edit

Which is in a different page like the first one up there the first bit of code only exception is the stuff is different the url etc.
Thank You
Comment: I'm not sure is it help, but change 'options-general.php?page=editstuff?id=...' to 'options-general.php?page=editstuff&id=...'
Comment: add that as an answer (i will accept) it works thankyou @TomaszWinter
Answer: Change options-general.php?page=editstuff?id=... to options-general.php?page=editstuff&id=...
Comment: You should consider explaining the problem, i.e. the separator for GET variables is &, not ? It took me a couple minutes to see what the problem was.
Answer: [Solved]: Sorry, you are not allowed to access this page

Anytime I go to /wp-admin/ I get "Sorry, you are not allowed to access
this page" The sites frontend works fine.
I am no novice to solving WP problems but this one has me perplexed.
So far I've: Reset .htaccess Disabled all plugins from folder & db
Disabled custom themes from folder & db and have done tons of
debugging
I've been doing tests with the db and I can get it working normally if
I replace the wp_options table with a fresh builds backup.
I am now searching through the options table to find the issue. It
might take me a while because my options table is 4000+ rows.
Any ideas are welcome and greatly appreciated!

Solutions:
Ok after countless hours of examining wp_options tables in phpmyadmin I finally discovered the problem. Somehow the wp_user_role row got deleted. It can also happen if it is edited/changed by a plugin such as WooCommerce.
So to fix it I copied the following from a fresh install and inserted it into the wp_options table with phpmyadmin:
Remember to replace 'wp_' with your db prefix.
option_name

wp_user_role

option_value

a:5:{s:13:"administrator";a:2:{s:4:"name";s:13:"Administrator";s:12:"capabilities";a:61:{s:13:"switch_themes";b:1;s:11:"edit_themes";b:1;s:16:"activate_plugins";b:1;s:12:"edit_plugins";b:1;s:10:"edit_users";b:1;s:10:"edit_files";b:1;s:14:"manage_options";b:1;s:17:"moderate_comments";b:1;s:17:"manage_categories";b:1;s:12:"manage_links";b:1;s:12:"upload_files";b:1;s:6:"import";b:1;s:15:"unfiltered_html";b:1;s:10:"edit_posts";b:1;s:17:"edit_others_posts";b:1;s:20:"edit_published_posts";b:1;s:13:"publish_posts";b:1;s:10:"edit_pages";b:1;s:4:"read";b:1;s:8:"level_10";b:1;s:7:"level_9";b:1;s:7:"level_8";b:1;s:7:"level_7";b:1;s:7:"level_6";b:1;s:7:"level_5";b:1;s:7:"level_4";b:1;s:7:"level_3";b:1;s:7:"level_2";b:1;s:7:"level_1";b:1;s:7:"level_0";b:1;s:17:"edit_others_pages";b:1;s:20:"edit_published_pages";b:1;s:13:"publish_pages";b:1;s:12:"delete_pages";b:1;s:19:"delete_others_pages";b:1;s:22:"delete_published_pages";b:1;s:12:"delete_posts";b:1;s:19:"delete_others_posts";b:1;s:22:"delete_published_posts";b:1;s:20:"delete_private_posts";b:1;s:18:"edit_private_posts";b:1;s:18:"read_private_posts";b:1;s:20:"delete_private_pages";b:1;s:18:"edit_private_pages";b:1;s:18:"read_private_pages";b:1;s:12:"delete_users";b:1;s:12:"create_users";b:1;s:17:"unfiltered_upload";b:1;s:14:"edit_dashboard";b:1;s:14:"update_plugins";b:1;s:14:"delete_plugins";b:1;s:15:"install_plugins";b:1;s:13:"update_themes";b:1;s:14:"install_themes";b:1;s:11:"update_core";b:1;s:10:"list_users";b:1;s:12:"remove_users";b:1;s:13:"promote_users";b:1;s:18:"edit_theme_options";b:1;s:13:"delete_themes";b:1;s:6:"export";b:1;}}s:6:"editor";a:2:{s:4:"name";s:6:"Editor";s:12:"capabilities";a:34:{s:17:"moderate_comments";b:1;s:17:"manage_categories";b:1;s:12:"manage_links";b:1;s:12:"upload_files";b:1;s:15:"unfiltered_html";b:1;s:10:"edit_posts";b:1;s:17:"edit_others_posts";b:1;s:20:"edit_published_posts";b:1;s:13:"publish_posts";b:1;s:10:"edit_pages";b:1;s:4:"read";b:1;s:7:"level_7";b:1;s:7:"level_6";b:1;s:7:"level_5";b:1;s:7:"level_4";b:1;s:7:"level_3";b:1;s:7:"level_2";b:1;s:7:"level_1";b:1;s:7:"level_0";b:1;s:17:"edit_others_pages";b:1;s:20:"edit_published_pages";b:1;s:13:"publish_pages";b:1;s:12:"delete_pages";b:1;s:19:"delete_others_pages";b:1;s:22:"delete_published_pages";b:1;s:12:"delete_posts";b:1;s:19:"delete_others_posts";b:1;s:22:"delete_published_posts";b:1;s:20:"delete_private_posts";b:1;s:18:"edit_private_posts";b:1;s:18:"read_private_posts";b:1;s:20:"delete_private_pages";b:1;s:18:"edit_private_pages";b:1;s:18:"read_private_pages";b:1;}}s:6:"author";a:2:{s:4:"name";s:6:"Author";s:12:"capabilities";a:10:{s:12:"upload_files";b:1;s:10:"edit_posts";b:1;s:20:"edit_published_posts";b:1;s:13:"publish_posts";b:1;s:4:"read";b:1;s:7:"level_2";b:1;s:7:"level_1";b:1;s:7:"level_0";b:1;s:12:"delete_posts";b:1;s:22:"delete_published_posts";b:1;}}s:11:"contributor";a:2:{s:4:"name";s:11:"Contributor";s:12:"capabilities";a:5:{s:10:"edit_posts";b:1;s:4:"read";b:1;s:7:"level_1";b:1;s:7:"level_0";b:1;s:12:"delete_posts";b:1;}}s:10:"subscriber";a:2:{s:4:"name";s:10:"Subscriber";s:12:"capabilities";a:2:{s:4:"read";b:1;s:7:"level_0";b:1;}}}


Exposing boost::optional via Boost.Python as internal reference or None

Question: I am exposing my C++ classes via Boost.Python. My intention is to expose member variables that are of a user-defined class type with an internal reference. This worked fine until I decided to introduce a member variable of type boost::optional<T>.
There are several great posts that show how to expose boost::optional<T> as return by value. Specifically, I have implemented this converter. The other relevant pieces of my code look like this:
struct Bar {}

struct Foo {
  boost::optional<Bar> bar;
}

BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;

  python_optional<Bar>();  //registering the converter

  class_<Foo>("Foo")
    .add_property ( "bar", make_getter(&Foo::bar, return_value_policy<return_by_value>()), make_setter(&Foo::bar) )
  ;
}

I tried to replace return_value_policy<return_by_value>() with either return_value_policy<reference_existing_object>() or return_internal_reference<>(). Both produced a Python TypeError:
>> import mymodule
>> foo = mymodule.Foo()
>> bar = foo.bar
TypeError: No Python class registered for C++ class boost::optional<Bar>

My understanding is that I now I am getting a reference to the boost::optional<T> object. The converter I registered is, however, not called because it expects a boost::optional<T> object and not a reference to such an object. I thought about changing the converter but I am new to this and I really do not know how. Any suggestions?
Answer: I found a workaround by adding a getter to struct Foo that either returns a pointer to the object held by boost::optional or a nullptr in case of boost::none. As &*bar returns const Bar* I had to use const_cast.
struct Bar {}

struct Foo {
  Bar* getBar() { return (bar ? const_cast<Bar*>(&*bar) : nullptr); };
  boost::optional<Bar> bar;
}

BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;

  python_optional<Bar>();  //registering the converter

  class_<Foo>("Foo")
    .add_property ( "bar", make_function(static_cast< Bar*(Foo::*)() >(&Foo::getBar), return_internal_reference<>() ), make_setter(&Foo::bar) )
  ;
}

In case bar belongs to a base class of Foo Python will produce an ArgumentError like this:
>> import mymodule
>> foo = mymodule.Foo()
>> foo.bar = mymodule.Bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument tpyes in
  None.None(Foo, Bar)
did not match C++ signature:
  None(FooBase {lvalue}, boost::optional<Bar>)

To solve the problem define a getter and a setter for bar in class Foo.
struct Bar {}

struct FooBase {
  boost::optional<Bar> bar;
}

struct Foo : public FooBase {
  Bar* getBar() { return (bar ? const_cast<Bar*>(&*bar) : nullptr); };
  void setBar(const Bar* bar) { bar ?  this->bar = *bar : this->bar = boost::none; }
}

void (Foo::*foo_bar_set)(const Bar*) = &Foo::setBar;

BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;

  python_optional<Bar>();  //registering the converter

  class_<Foo>("Foo")
    .add_property ( "bar", make_function(static_cast< Bar*(Foo::*)() >(&Foo::getBar), return_internal_reference<>() ), foo_bar_set )
  ;
}


Is this the right way to implement chaining in javascript?

Question: After reading up online I wrote this simple code that does addition and multiplication via chaining. But reading the code, it looks like to me, that the method "Result" makes the code less readable and kind of seems redundant. Can someone help me get rid of the Result function?
var Calculator = function () {
    var result = 0;
    this.Add = function (x) {

        result = result + x;

        return this;
    };

     this.Multiply = function (x) {

        result = result * x;

        return this;
    };

    this.Result = function () {
        return result;
    }

};

var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total.Result());

What I am trying to achieve is
var total = new Calculator().Add(2).Add(3).Multiply(5);

alert(total);

Comment: Well, `total` isn't really a total, is it?  It's a `Calculator` object.
Comment: Your question is very similar to this one: [How to achieve arbitrary chain on function call in javascript?](http://stackoverflow.com/questions/26656718/how-to-achieve-arbitrary-chain-on-function-call-in-javascript) Look for the answers by mintsauce and friedi.
Comment: Why don't you just chain `.Result()` at the end? (Unrelated note: there's an informal JS standard that non-constructor method names start with a lower-case letter.)
Answer: You could do some interesting stuff with prototyping:
var Calculator = function(){ /*...*/ }

// Works with alert
Calculator.prototype.toString = function(){
   return this.Result();
}

// Works with operators
Calculator.prototype.valueOf = function(){
   return this.Result();
}

var total = new Calculator().Add(2).Add(3).Multiply(5);
alert(total); // 25
total + 1; // 26

Note that the function alert(...) converts the arguments to strings before being displayed using .toString(). This also applies to any other operation that has strings, such as concatenation (ex. total + ""). Operations with numbers use .valueOf() instead.
Answer: I think returning .Result() is perfectly fine, since you cannot have the chainable methods return one type and then in the end auto-magically turn into something else.
Even the other suggested answers are using methods to turn your Calculator into a result, they are just implicitly invoked by the runtime (e.g. toString in the alert function).
If you want real chaining of numbers you should extend the Number prototype and not use a calculator (but i know, Monkey-patching is evil).


Excluir simultaneamente imagem do BD e da pasta de destino do servidor

Question: Estou tentando excluir simultaneamente uma determinada imagem que esta no campo "logo" de uma tabela que tem vários outros campos, e da pasta onde esta armazenada que se chama "upload", porém somente consigo excluir toda linha da tabela referente ao campo "logo", e mesmo assim não exclui da pasta "upload".
O objetivo é para que quando o usuário decida alterar a imagem, não fique as imagens antigas sobrecarregando o servidor, já que elas não estão sendo mais usadas.
Segue abaixo o código que já tenho:
   <?php
   include 'conexao.php';
   $pasta = 'upload/';
   if (isset($_POST['deletar'])){
   $check = @$_POST['apagar'];
   foreach($check as $logo){
   $delcheck = mysql_query("DELETE FROM topo WHERE logo = '$logo'") or die (mysql_error());
   unlink($pasta.$delcheck['logo']);
   if ($delcheck >= '1'){
   echo '';
   }else{
   echo '';
   }}}
   ?>

   <form action="" method="POST" enctype="multipart/form-data">

   <?php
   include 'conexao.php';
   $seleciona = "SELECT * FROM topo";
   $queryum = mysql_query($seleciona);
   while ($list = mysql_fetch_array($queryum)){
   $logo = $list['logo'];
   ?>
   <input type="checkbox" name="apagar[]" value="<?php echo $logo; ?>" readonly><?php echo $logo; ?>

   <?php
   }
   ?>
   <input type="submit" name="deletar" value="Excluir">

   </form>

Comment: Prezado Amigo: Seu script esta na mesma raiz, pois quando dá um unlink na pasta/arquivo upload/NOME DO ARQUIVO DE IMAGEM. Tente colocar `error_reporting(E_ALL);` no inicio do script para ver se algum erro aparece para voce. Na verdade esta função nem sempre funciona, depende da instalação do PHP. Pois é possivel sumprimir toda e qualquer saida de erros. Nao da nenhum erro ? Seu PHP esta com o modo de erro habilitado?
Comment: Boa noite, gostaria de saber se a minha resposta lhe ajudou? Se não, informe poderia teve alguma duvida no uso dela.
Comment: Boa noite, gostaria de saber se alguma das respostas lhe ajudou, se não por favor comente o que acha que falta.
Answer: Existe uma série de problemas no teu script:

Você deve levar em consideração é o uso de caminhos relativos, se a pasta ./upload/ não estiver no mesmo diretório que a pasta do teu script, então ele nunca irá conseguir encontrar o arquivo. Recomendo que sempre use caminhos absolutos, para isto crie um arquivo "global" (incluído no começo em todos scripts) para sempre apontar pra pasta correta usando uma variável, por exemplo:

global.php
<?php
define('ABSOLUTE_PATH', strtr(dirname(__FILE__), '\\', '/') . '/');

ABSOLUTE_PATH irá exibir algo como c:/wamp/projeto/ ou  /etc/www/projeto/ ou /home/user/htdocs/. Se a pasta upload no seu servidor estiver localizada em /home/user/htdocs/upload/, então bastará usar o unlink assim (apenas um exemplo):
 unlink(ABSOLUTE_PATH . 'upload/arquivo.jpg');

O unlink pode retornar true se conseguiu excluir ou false caso contrario. Você deve usar isto ao seu favor combinado com if, o que você não fez.
Você está foreach, da a entender que são vários logos que você necessita deletar, mas o teu script usa window.location.href, o redirecionamento deveria somente ocorrer após o loop.
Você criou duas variáveis $_POST['deletar'] e $_POST['apagar'], você deveria ter usado apenas o isset, leia esta resposta que fiz em outra pergunta: https://pt.stackoverflow.com/a/63550/3635
Você usou if ($delcheck >= '1'){, mas note que mysql_query não retorna numeros ou strings e sim valores "booleanos".
Funções que começam com o nome mysql_ estão em desuso e logo serão descontinuadas, ou seja assim que o seu servidor (ou servidor dos teus clientes) atualizarem pra versões mais recentes do PHP os teus script irão parar de funcionar e irão emitir várias sequencias de erros semelhantes a este:

Fatal error: Call to undefined function mysql_connect() in arquivo.php on line 1

Leia sobre isto em nesta outras respostas:

https://pt.stackoverflow.com/a/4675/3635
https://pt.stackoverflow.com/a/66489/3635

Você está deletando os logotipos pelo endereço da imagem, quando o preferível seria usar o id da tabela do banco.
Recomendação: Prefira usar Prepared Statements


Problemas ao gerar uma PartialView com BeginCollectionItem

Question: Com a intenção de criar um ação para Adc/Deletar dados dinamicamente a uma tabela com relação 1 para Muitas, o .net retorna a exceção "Referência de objeto não definida para uma instância de um objeto." quando chamo a PartialView tento visualizar a view, segue os Models, viewModels, Controller, View e PartialView...
Models
public class Candidato
{
    [Key]
    public int id { get; set; }
    public string nome { get; set; }
    public string cpf { get; set; }
    public string sexo { get; set; }
}

public class CandidatoEP
{
    [Key]
    public int id { get; set; }
    public int id_candidato { get; set; }
    public string empresa { get; set; }
    public string cargo { get; set; }
    public DateTime inicio { get; set; }
    public DateTime fim { get; set; }
    public string obsEp { get; set; }

    [ForeignKey("id_candidato")]
    public virtual Candidato candidato { get; set; }
}

ViewModel
public class NovoCandidato
{
    [Required(ErrorMessage = "Obrigatório informar o Nome")]
    [Display(Name = "Nome")]
    public string nome { get; set; }

    [Required(ErrorMessage = "Obrigatório informar o CPF")]
    [Display(Name = "CPF")]
    public string cpf { get; set; }

    [Required(ErrorMessage = "Obrigatório informar o Sexo")]
    [Display(Name = "Sexo")]
    public string sexo { get; set; }

    public virtual ICollection<CandidatoEP> CandidatoEPs { get; set; }
}

Controller
public ActionResult Novo()
{
    var novoCandidato = new CandidatoNovo();
    return View(novoCandidato);
}

View (parte onde insiro a PartialView)

    Experiência (opcional)

        @foreach (var Experiencia in Model.CandidatoEPs)
        {
            Html.RenderPartial("_AddCandidatoExp", Experiencia);
        }

        + Adicionar Experiência

PartialView
@model Site.ViewModels.CandidatoNovo

@using (Html.BeginCollectionItem("CandidatoEPs"))
{

            @Html.EditorFor(m => m.empresa, new { htmlAttributes = new { @class = "form-control", @placeholder = "Empresa onde trabalhou" } })

            @Html.EditorFor(m => m.id_departamento, new { htmlAttributes = new { @class = "form-control", @placeholder = "Departamento" } })

            @Html.EditorFor(m => m.cargo, new { htmlAttributes = new { @class = "form-control", @placeholder = "Função exercida" } })

            @Html.EditorFor(m => m.inicio, new { htmlAttributes = new { @class = "form-control", @placeholder = "Início (MM/AAAA)" } })

            @Html.EditorFor(m => m.fim, new { htmlAttributes = new { @class = "form-control", @placeholder = "Fim (MM/AAAA)" } })

            @Html.TextAreaFor(m => m.obsEp, new { @class = "dc-textarea form-control", @placeholder = "Descreva as atividades exercidas na função...", @rows = "3" })
            @Html.ValidationMessageFor(model => model.obsEp, "", new { @class = "text-danger" })

}

Ai, eu uso uma função no js para adicionar multiplos box de experiencia.
Javascript
$('.dc-box-clonar').hide();
$('.control-add-box').on('click', function (e) {
    e.preventDefault();
    var newElem = $(this).parent().find('.dc-box-clonar:first').clone();
    newElem.find('input').val('');
    newElem.prependTo($(this).parent()).show();
    var height = $(this).prev('.dc-box-clonar').outerHeight(true);

    $("html, body").stop().animate({ scrollTop: $(this).offset().top - 520 }, 600);
});

Answer: Resolvendo rapidamente o problema, seria algo assim:

    Experiência (opcional)

        @if (Model != null && Model.CandidatoEPs != null)
        {
            foreach (var Experiencia in Model.CandidatoEPs)
            {
                Html.RenderPartial("_AddCandidatoExp", Experiencia);
            }
        }

        + Adicionar Experiência

Pra você adicionar a experiência, use algo assim:

E no Controller (usando Guid):
    public ActionResult NovaLinha()
    {
        return PartialView("_LinhaExperiencia", new Experiencia { ExperienciaId = Guid.NewGuid() });
    }

Usando int:
    public ActionResult NovaLinha()
    {
        return PartialView("_LinhaExperiencia", new Experiencia());
    }

Com int a chave não é definida em Controller porque a definição da chave fica a cargo do banco de dados, no momento em que você salva o registro.
O Controller recebe o seguinte:
[HttpPost]
public ActionResult Novo(CandidatoNovo candidatoNovo)
{
    if (ModelState.IsValid)
    {
        /* Aqui candidatoNovo.CandidatoEPs está preenchido */
    }
}

Comment: E Cigano, porque ao colocar @if na view o problema foi resolvido?
Comment: Porque as referências podem vir nulas. Eu não sei como você está preenchendo, então confiro as variáveis antes de tentar imprimir qualquer coisa.
Comment: Aqui a Id da Experiencia está declado como int, ai quando se coloca Guid retorna um erro... Qual a melhor saida pra isso?
Comment: Atualizei a resposta.
Comment: E como ficaria o action Post no controller? ele receberia o modelo ou uma lista?
Comment: Ele recebe o Model inteiro.
Comment: Mas aqui, não sei porque não esta gravando o que esta sendo armazenado no ICollection, os dados que estão indo pro banco são somente aqueles que estão declarados fora do ICollecion... Teria como atualizar a resposta com um breve exemplo?
Comment: @MatheusSilva Veja agora.
Comment: Hmmm, então acredito que tenha algum erro no meu ViewModel, porque quando coloco assim e dou o comando para adicionar ao modelo original (db.Candidato.Add(candidatoNovo)), aponta um erro, algo como "The best overloaded method match for..."
Comment: Acho que é o caso de mais uma pergunta.